answer stringlengths 15 1.25M |
|---|
#include <asm/io.h>
/*
** It is supposed these functions to be used for a low level
** debugging (via Cayman LEDs), hence to be available as soon
** as possible.
** Unfortunately Cayman LEDs relies on Cayman EPLD to be mapped
** (this happen when IRQ are initialized... quite late).
** These triky dependencies should be removed. Temporary, it
** may be enough to NOP until EPLD is mapped.
*/
extern unsigned long epld_virt;
#define LED_ADDR (epld_virt + 0x008)
#define HDSP2534_ADDR (epld_virt + 0x100)
void mach_led(int position, int value)
{
if (!epld_virt)
return;
if (value)
ctrl_outl(0, LED_ADDR);
else
ctrl_outl(1, LED_ADDR);
}
void mach_alphanum(int position, unsigned char value)
{
if (!epld_virt)
return;
ctrl_outb(value, HDSP2534_ADDR + 0xe0 + (position << 2));
}
void <API key>(int setting)
{
ctrl_outb(setting & 7, HDSP2534_ADDR + 0xc0);
} |
// <API key>: GPL-2.0
#ifndef __LINUX_KBUILD_H
# error "Please do not build this file directly, build asm-offsets.c instead"
#endif
#include <linux/efi.h>
#include <asm/ucontext.h>
/* workaround for a warning with -Wmissing-prototypes */
void foo(void);
void foo(void)
{
OFFSET(CPUINFO_x86, cpuinfo_x86, x86);
OFFSET(CPUINFO_x86_vendor, cpuinfo_x86, x86_vendor);
OFFSET(CPUINFO_x86_model, cpuinfo_x86, x86_model);
OFFSET(<API key>, cpuinfo_x86, x86_stepping);
OFFSET(CPUINFO_cpuid_level, cpuinfo_x86, cpuid_level);
OFFSET(<API key>, cpuinfo_x86, x86_capability);
OFFSET(<API key>, cpuinfo_x86, x86_vendor_id);
BLANK();
OFFSET(PT_EBX, pt_regs, bx);
OFFSET(PT_ECX, pt_regs, cx);
OFFSET(PT_EDX, pt_regs, dx);
OFFSET(PT_ESI, pt_regs, si);
OFFSET(PT_EDI, pt_regs, di);
OFFSET(PT_EBP, pt_regs, bp);
OFFSET(PT_EAX, pt_regs, ax);
OFFSET(PT_DS, pt_regs, ds);
OFFSET(PT_ES, pt_regs, es);
OFFSET(PT_FS, pt_regs, fs);
OFFSET(PT_GS, pt_regs, gs);
OFFSET(PT_ORIG_EAX, pt_regs, orig_ax);
OFFSET(PT_EIP, pt_regs, ip);
OFFSET(PT_CS, pt_regs, cs);
OFFSET(PT_EFLAGS, pt_regs, flags);
OFFSET(PT_OLDESP, pt_regs, sp);
OFFSET(PT_OLDSS, pt_regs, ss);
BLANK();
OFFSET(<API key>, saved_context, gdt_desc);
BLANK();
/*
* Offset from the entry stack to task stack stored in TSS. Kernel entry
* happens on the per-cpu entry-stack, and the asm code switches to the
* task-stack pointer stored in x86_tss.sp1, which is a copy of
* task->thread.sp0 where entry code can find it.
*/
DEFINE(<API key>,
offsetof(struct cpu_entry_area, tss.x86_tss.sp1) -
offsetofend(struct cpu_entry_area, entry_stack_page.stack));
BLANK();
DEFINE(EFI_svam, offsetof(<API key>, <API key>));
} |
FROM debian:wheezy
MAINTAINER Tim Hockin "thockin@google.com"
RUN apt-get -q update && \
apt-get install -y dnsutils && \
apt-get clean |
<!DOCTYPE html>
<html lang="en-gb" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Form-file - UIkit tests</title>
<script src="../_test.js"></script>
</head>
<body>
<div class="uk-container uk-container-center">
<h1>Form file</h1>
<div class="uk-margin">
<div class="uk-form-file">
<button class="uk-button">Select</button>
<input id="form-file" type="file">
</div>
<button class="uk-button">Another button</button>
</div>
<div class="uk-margin">
Here is a text
<div class="uk-form-file uk-text-primary">upload<input id="form-file" type="file"></div>.
</div>
</div>
</body>
</html> |
.syntaxhighlighter a,
.syntaxhighlighter div,
.syntaxhighlighter code,
.syntaxhighlighter table,
.syntaxhighlighter table td,
.syntaxhighlighter table tr,
.syntaxhighlighter table tbody,
.syntaxhighlighter table thead,
.syntaxhighlighter table caption,
.syntaxhighlighter textarea {
-moz-border-radius: 0 0 0 0 !important;
-<API key>: 0 0 0 0 !important;
background: none !important;
border: 0 !important;
bottom: auto !important;
float: none !important;
height: auto !important;
left: auto !important;
line-height: 1.1em !important;
margin: 0 !important;
outline: 0 !important;
overflow: visible !important;
padding: 0 !important;
position: static !important;
right: auto !important;
text-align: left !important;
top: auto !important;
vertical-align: baseline !important;
width: auto !important;
box-sizing: content-box !important;
font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
font-weight: normal !important;
font-style: normal !important;
font-size: 1em !important;
min-height: inherit !important;
min-height: auto !important;
}
.syntaxhighlighter {
width: 100% !important;
margin: 1em 0 1em 0 !important;
position: relative !important;
overflow: auto !important;
font-size: 1em !important;
}
.syntaxhighlighter.source {
overflow: hidden !important;
}
.syntaxhighlighter .bold {
font-weight: bold !important;
}
.syntaxhighlighter .italic {
font-style: italic !important;
}
.syntaxhighlighter .line {
white-space: pre !important;
}
.syntaxhighlighter table {
width: 100% !important;
}
.syntaxhighlighter table caption {
text-align: left !important;
padding: .5em 0 0.5em 1em !important;
}
.syntaxhighlighter table td.code {
width: 100% !important;
}
.syntaxhighlighter table td.code .container {
position: relative !important;
}
.syntaxhighlighter table td.code .container textarea {
box-sizing: border-box !important;
position: absolute !important;
left: 0 !important;
top: 0 !important;
width: 100% !important;
height: 100% !important;
border: none !important;
background: white !important;
padding-left: 1em !important;
overflow: hidden !important;
white-space: pre !important;
}
.syntaxhighlighter table td.gutter .line {
text-align: right !important;
padding: 0 0.5em 0 1em !important;
}
.syntaxhighlighter table td.code .line {
padding: 0 1em !important;
}
.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
padding-left: 0em !important;
}
.syntaxhighlighter.show {
display: block !important;
}
.syntaxhighlighter.collapsed table {
display: none !important;
}
.syntaxhighlighter.collapsed .toolbar {
padding: 0.1em 0.8em 0em 0.8em !important;
font-size: 1em !important;
position: static !important;
width: auto !important;
height: auto !important;
}
.syntaxhighlighter.collapsed .toolbar span {
display: inline !important;
margin-right: 1em !important;
}
.syntaxhighlighter.collapsed .toolbar span a {
padding: 0 !important;
display: none !important;
}
.syntaxhighlighter.collapsed .toolbar span a.expandSource {
display: inline !important;
}
.syntaxhighlighter .toolbar {
position: absolute !important;
right: 1px !important;
top: 1px !important;
width: 11px !important;
height: 11px !important;
font-size: 10px !important;
z-index: 10 !important;
}
.syntaxhighlighter .toolbar span.title {
display: inline !important;
}
.syntaxhighlighter .toolbar a {
display: block !important;
text-align: center !important;
text-decoration: none !important;
padding-top: 1px !important;
}
.syntaxhighlighter .toolbar a.expandSource {
display: none !important;
}
.syntaxhighlighter.ie {
font-size: .9em !important;
padding: 1px 0 1px 0 !important;
}
.syntaxhighlighter.ie .toolbar {
line-height: 8px !important;
}
.syntaxhighlighter.ie .toolbar a {
padding-top: 0px !important;
}
.syntaxhighlighter.printing .line.alt1 .content,
.syntaxhighlighter.printing .line.alt2 .content,
.syntaxhighlighter.printing .line.highlighted .number,
.syntaxhighlighter.printing .line.highlighted.alt1 .content,
.syntaxhighlighter.printing .line.highlighted.alt2 .content {
background: none !important;
}
.syntaxhighlighter.printing .line .number {
color: #bbbbbb !important;
}
.syntaxhighlighter.printing .line .content {
color: black !important;
}
.syntaxhighlighter.printing .toolbar {
display: none !important;
}
.syntaxhighlighter.printing a {
text-decoration: none !important;
}
.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
color: black !important;
}
.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
color: #008200 !important;
}
.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
color: blue !important;
}
.syntaxhighlighter.printing .keyword {
color: #006699 !important;
font-weight: bold !important;
}
.syntaxhighlighter.printing .preprocessor {
color: gray !important;
}
.syntaxhighlighter.printing .variable {
color: #aa7700 !important;
}
.syntaxhighlighter.printing .value {
color: #009900 !important;
}
.syntaxhighlighter.printing .functions {
color: #ff1493 !important;
}
.syntaxhighlighter.printing .constants {
color: #0066cc !important;
}
.syntaxhighlighter.printing .script {
font-weight: bold !important;
}
.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
color: gray !important;
}
.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
color: #ff1493 !important;
}
.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
color: red !important;
}
.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
color: black !important;
}
.syntaxhighlighter {
background-color: white !important;
}
.syntaxhighlighter .line.alt1 {
background-color: white !important;
}
.syntaxhighlighter .line.alt2 {
background-color: white !important;
}
.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
background-color: #e0e0e0 !important;
}
.syntaxhighlighter .line.highlighted.number {
color: black !important;
}
.syntaxhighlighter table caption {
color: black !important;
}
.syntaxhighlighter .gutter {
color: #afafaf !important;
}
.syntaxhighlighter .gutter .line {
border-right: 3px solid #6ce26c !important;
}
.syntaxhighlighter .gutter .line.highlighted {
background-color: #6ce26c !important;
color: white !important;
}
.syntaxhighlighter.printing .line .content {
border: none !important;
}
.syntaxhighlighter.collapsed {
overflow: visible !important;
}
.syntaxhighlighter.collapsed .toolbar {
color: blue !important;
background: white !important;
border: 1px solid #6ce26c !important;
}
.syntaxhighlighter.collapsed .toolbar a {
color: blue !important;
}
.syntaxhighlighter.collapsed .toolbar a:hover {
color: red !important;
}
.syntaxhighlighter .toolbar {
color: white !important;
background: #6ce26c !important;
border: none !important;
}
.syntaxhighlighter .toolbar a {
color: white !important;
}
.syntaxhighlighter .toolbar a:hover {
color: black !important;
}
.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
color: black !important;
}
.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
color: #008200 !important;
}
.syntaxhighlighter .string, .syntaxhighlighter .string a {
color: blue !important;
}
.syntaxhighlighter .keyword {
color: #006699 !important;
}
.syntaxhighlighter .preprocessor {
color: gray !important;
}
.syntaxhighlighter .variable {
color: #aa7700 !important;
}
.syntaxhighlighter .value {
color: #009900 !important;
}
.syntaxhighlighter .functions {
color: #ff1493 !important;
}
.syntaxhighlighter .constants {
color: #0066cc !important;
}
.syntaxhighlighter .script {
font-weight: bold !important;
color: #006699 !important;
background-color: none !important;
}
.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
color: gray !important;
}
.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
color: #ff1493 !important;
}
.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
color: red !important;
}
.syntaxhighlighter .keyword {
font-weight: bold !important;
} |
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/dw_mmc.h>
#include <linux/of.h>
#include <linux/clk.h>
#include "dw_mmc.h"
#include "dw_mmc-pltfm.h"
int <API key>(struct platform_device *pdev,
const struct dw_mci_drv_data *drv_data)
{
struct dw_mci *host;
struct resource *regs;
host = devm_kzalloc(&pdev->dev, sizeof(struct dw_mci), GFP_KERNEL);
if (!host)
return -ENOMEM;
host->irq = platform_get_irq(pdev, 0);
if (host->irq < 0)
return host->irq;
host->drv_data = drv_data;
host->dev = &pdev->dev;
host->irq_flags = 0;
host->pdata = pdev->dev.platform_data;
regs = <API key>(pdev, IORESOURCE_MEM, 0);
host->regs = <API key>(&pdev->dev, regs);
if (IS_ERR(host->regs))
return PTR_ERR(host->regs);
/* Get registers' physical base address */
host->phy_regs = regs->start;
<API key>(pdev, host);
return dw_mci_probe(host);
}
EXPORT_SYMBOL_GPL(<API key>);
#ifdef CONFIG_PM_SLEEP
/*
* TODO: we should probably disable the clock to the card in the suspend path.
*/
static int <API key>(struct device *dev)
{
struct dw_mci *host = dev_get_drvdata(dev);
return dw_mci_suspend(host);
}
static int dw_mci_pltfm_resume(struct device *dev)
{
struct dw_mci *host = dev_get_drvdata(dev);
return dw_mci_resume(host);
}
#endif /* CONFIG_PM_SLEEP */
SIMPLE_DEV_PM_OPS(dw_mci_pltfm_pmops, <API key>, dw_mci_pltfm_resume);
EXPORT_SYMBOL_GPL(dw_mci_pltfm_pmops);
static const struct of_device_id dw_mci_pltfm_match[] = {
{ .compatible = "snps,dw-mshc", },
{ .compatible = "altr,socfpga-dw-mshc", },
{ .compatible = "img,pistachio-dw-mshc", },
{},
};
MODULE_DEVICE_TABLE(of, dw_mci_pltfm_match);
static int dw_mci_pltfm_probe(struct platform_device *pdev)
{
const struct dw_mci_drv_data *drv_data = NULL;
const struct of_device_id *match;
if (pdev->dev.of_node) {
match = of_match_node(dw_mci_pltfm_match, pdev->dev.of_node);
drv_data = match->data;
}
return <API key>(pdev, drv_data);
}
int dw_mci_pltfm_remove(struct platform_device *pdev)
{
struct dw_mci *host = <API key>(pdev);
dw_mci_remove(host);
return 0;
}
EXPORT_SYMBOL_GPL(dw_mci_pltfm_remove);
static struct platform_driver dw_mci_pltfm_driver = {
.probe = dw_mci_pltfm_probe,
.remove = dw_mci_pltfm_remove,
.driver = {
.name = "dw_mmc",
.of_match_table = dw_mci_pltfm_match,
.pm = &dw_mci_pltfm_pmops,
},
};
<API key>(dw_mci_pltfm_driver);
MODULE_DESCRIPTION("DW Multimedia Card Interface driver");
MODULE_AUTHOR("NXP Semiconductor VietNam");
MODULE_AUTHOR("Imagination Technologies Ltd");
MODULE_LICENSE("GPL v2"); |
-- Test for trac #2956
module TH_sections where
two :: Int
two = $( [| (1 +) 1 |] )
three :: Int
three = $( [| (+ 2) 1 |] ) |
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/ethtool.h>
#include <linux/usb.h>
#include <linux/timer.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/kmod.h>
#include <linux/rfkill.h>
#include <linux/ip.h>
#include <linux/uaccess.h>
#include <linux/usb/cdc.h>
#include <net/arp.h>
#include <asm/byteorder.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#define MOD_AUTHOR "Option Wireless"
#define MOD_DESCRIPTION "USB High Speed Option driver"
#define MOD_LICENSE "GPL"
#define HSO_MAX_NET_DEVICES 10
#define HSO__MAX_MTU 2048
#define DEFAULT_MTU 1500
#define DEFAULT_MRU 1500
#define CTRL_URB_RX_SIZE 1024
#define CTRL_URB_TX_SIZE 64
#define BULK_URB_RX_SIZE 4096
#define BULK_URB_TX_SIZE 8192
#define <API key> HSO__MAX_MTU
#define <API key> HSO__MAX_MTU
#define <API key> 4
#define <API key> 0x20
/* These definitions are used with the struct hso_net flags element */
/* - use *_bit operations on it. (bit indices not values.) */
#define HSO_NET_RUNNING 0
#define HSO_NET_TX_TIMEOUT (HZ*10)
#define HSO_SERIAL_MAGIC 0x48534f31
/* Number of ttys to handle */
#define <API key> 256
#define MAX_RX_URBS 2
/* Debugging functions */
#define D__(lvl_, fmt, arg...) \
do { \
printk(lvl_ "[%d:%s]: " fmt "\n", \
__LINE__, __func__, ## arg); \
} while (0)
#define D_(lvl, args...) \
do { \
if (lvl & debug) \
D__(KERN_INFO, args); \
} while (0)
#define D1(args...) D_(0x01, ##args)
#define D2(args...) D_(0x02, ##args)
#define D3(args...) D_(0x04, ##args)
#define D4(args...) D_(0x08, ##args)
#define D5(args...) D_(0x10, ##args)
/* Enumerators */
enum pkt_parse_state {
WAIT_IP,
WAIT_DATA,
WAIT_SYNC
};
/* Structs */
struct hso_shared_int {
struct <API key> *intr_endp;
void *shared_intr_buf;
struct urb *shared_intr_urb;
struct usb_device *usb;
int use_count;
int ref_count;
struct mutex shared_int_lock;
};
struct hso_net {
struct hso_device *parent;
struct net_device *net;
struct rfkill *rfkill;
struct <API key> *in_endp;
struct <API key> *out_endp;
struct urb *<API key>[<API key>];
struct urb *mux_bulk_tx_urb;
void *<API key>[<API key>];
void *mux_bulk_tx_buf;
struct sk_buff *skb_rx_buf;
struct sk_buff *skb_tx_buf;
enum pkt_parse_state rx_parse_state;
spinlock_t net_lock;
unsigned short rx_buf_size;
unsigned short rx_buf_missing;
struct iphdr rx_ip_hdr;
unsigned long flags;
};
enum rx_ctrl_state{
RX_IDLE,
RX_SENT,
RX_PENDING
};
#define BM_REQUEST_TYPE (0xa1)
#define B_NOTIFICATION (0x20)
#define W_VALUE (0x0)
#define W_LENGTH (0x2)
#define B_OVERRUN (0x1<<6)
#define B_PARITY (0x1<<5)
#define B_FRAMING (0x1<<4)
#define B_RING_SIGNAL (0x1<<3)
#define B_BREAK (0x1<<2)
#define B_TX_CARRIER (0x1<<1)
#define B_RX_CARRIER (0x1<<0)
struct <API key> {
u8 bmRequestType;
u8 bNotification;
u16 wValue;
u16 wIndex;
u16 wLength;
u16 UART_state_bitmap;
} __packed;
struct hso_tiocmget {
struct mutex mutex;
wait_queue_head_t waitq;
int intr_completed;
struct <API key> *endp;
struct urb *urb;
struct <API key> <API key>;
u16 <API key>;
struct uart_icount icount;
};
struct hso_serial {
struct hso_device *parent;
int magic;
u8 minor;
struct hso_shared_int *shared_int;
/* rx/tx urb could be either a bulk urb or a control urb depending
on which serial port it is used on. */
struct urb *rx_urb[MAX_RX_URBS];
u8 num_rx_urbs;
u8 *rx_data[MAX_RX_URBS];
u16 rx_data_length; /* should contain allocated length */
struct urb *tx_urb;
u8 *tx_data;
u8 *tx_buffer;
u16 tx_data_length; /* should contain allocated length */
u16 tx_data_count;
u16 tx_buffer_count;
struct usb_ctrlrequest ctrl_req_tx;
struct usb_ctrlrequest ctrl_req_rx;
struct <API key> *in_endp;
struct <API key> *out_endp;
enum rx_ctrl_state rx_state;
u8 rts_state;
u8 dtr_state;
unsigned tx_urb_used:1;
struct tty_port port;
/* from usb_serial_port */
spinlock_t serial_lock;
int (*write_data) (struct hso_serial *serial);
struct hso_tiocmget *tiocmget;
/* Hacks required to get flow control
* working on the serial receive buffers
* so as not to drop characters on the floor.
*/
int curr_rx_urb_idx;
u8 rx_urb_filled[MAX_RX_URBS];
struct tasklet_struct unthrottle_tasklet;
};
struct hso_device {
union {
struct hso_serial *dev_serial;
struct hso_net *dev_net;
} port_data;
u32 port_spec;
u8 is_active;
u8 usb_gone;
struct work_struct async_get_intf;
struct work_struct async_put_intf;
struct work_struct reset_device;
struct usb_device *usb;
struct usb_interface *interface;
struct device *dev;
struct kref ref;
struct mutex mutex;
};
/* Type of interface */
#define HSO_INTF_MASK 0xFF00
#define HSO_INTF_MUX 0x0100
#define HSO_INTF_BULK 0x0200
/* Type of port */
#define HSO_PORT_MASK 0xFF
#define HSO_PORT_NO_PORT 0x0
#define HSO_PORT_CONTROL 0x1
#define HSO_PORT_APP 0x2
#define HSO_PORT_GPS 0x3
#define HSO_PORT_PCSC 0x4
#define HSO_PORT_APP2 0x5
#define <API key> 0x6
#define HSO_PORT_MSD 0x7
#define HSO_PORT_VOICE 0x8
#define HSO_PORT_DIAG2 0x9
#define HSO_PORT_DIAG 0x10
#define HSO_PORT_MODEM 0x11
#define HSO_PORT_NETWORK 0x12
/* Additional device info */
#define HSO_INFO_MASK 0xFF000000
#define HSO_INFO_CRC_BUG 0x01000000
/* Prototypes */
/* Serial driver functions */
static int hso_serial_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear);
static void ctrl_callback(struct urb *urb);
static int put_rxbuf_data(struct urb *urb, struct hso_serial *serial);
static void hso_kick_transmit(struct hso_serial *serial);
/* Helper functions */
static int <API key>(struct hso_shared_int *mux_int,
struct usb_device *usb, gfp_t gfp);
static void handle_usb_error(int status, const char *function,
struct hso_device *hso_dev);
static struct <API key> *hso_get_ep(struct usb_interface *intf,
int type, int dir);
static int hso_get_mux_ports(struct usb_interface *intf, unsigned char *ports);
static void hso_free_interface(struct usb_interface *intf);
static int <API key>(struct hso_device *hso_dev, gfp_t flags);
static int <API key>(struct hso_device *hso_dev);
static int <API key>(struct hso_device *hso_dev);
static void hso_free_shared_int(struct hso_shared_int *shared_int);
static int hso_stop_net_device(struct hso_device *hso_dev);
static void hso_serial_ref_free(struct kref *ref);
static void <API key>(struct urb *urb);
static int hso_mux_serial_read(struct hso_serial *serial);
static void async_get_intf(struct work_struct *data);
static void async_put_intf(struct work_struct *data);
static int hso_put_activity(struct hso_device *hso_dev);
static int hso_get_activity(struct hso_device *hso_dev);
static void <API key>(struct urb *urb);
static void reset_device(struct work_struct *data);
/* Helping functions */
/* #define DEBUG */
static inline struct hso_net *dev2net(struct hso_device *hso_dev)
{
return hso_dev->port_data.dev_net;
}
static inline struct hso_serial *dev2ser(struct hso_device *hso_dev)
{
return hso_dev->port_data.dev_serial;
}
/* Debugging functions */
#ifdef DEBUG
static void dbg_dump(int line_count, const char *func_name, unsigned char *buf,
unsigned int len)
{
static char name[255];
sprintf(name, "hso[%d:%s]", line_count, func_name);
<API key>(name, DUMP_PREFIX_NONE, buf, len);
}
#define DUMP(buf_, len_) \
dbg_dump(__LINE__, __func__, (unsigned char *)buf_, len_)
#define DUMP1(buf_, len_) \
do { \
if (0x01 & debug) \
DUMP(buf_, len_); \
} while (0)
#else
#define DUMP(buf_, len_)
#define DUMP1(buf_, len_)
#endif
/* module parameters */
static int debug;
static int tty_major;
static int disable_net;
/* driver info */
static const char driver_name[] = "hso";
static const char tty_filename[] = "ttyHS";
static const char *version = __FILE__ ": " MOD_AUTHOR;
/* the usb driver itself (registered in hso_init) */
static struct usb_driver hso_driver;
/* serial structures */
static struct tty_driver *tty_drv;
static struct hso_device *serial_table[<API key>];
static struct hso_device *network_table[HSO_MAX_NET_DEVICES];
static spinlock_t serial_table_lock;
static const s32 default_port_spec[] = {
HSO_INTF_MUX | HSO_PORT_NETWORK,
HSO_INTF_BULK | HSO_PORT_DIAG,
HSO_INTF_BULK | HSO_PORT_MODEM,
0
};
static const s32 icon321_port_spec[] = {
HSO_INTF_MUX | HSO_PORT_NETWORK,
HSO_INTF_BULK | HSO_PORT_DIAG2,
HSO_INTF_BULK | HSO_PORT_MODEM,
HSO_INTF_BULK | HSO_PORT_DIAG,
0
};
#define default_port_device(vendor, product) \
USB_DEVICE(vendor, product), \
.driver_info = (kernel_ulong_t)default_port_spec
#define icon321_port_device(vendor, product) \
USB_DEVICE(vendor, product), \
.driver_info = (kernel_ulong_t)icon321_port_spec
/* list of devices we support */
static const struct usb_device_id hso_ids[] = {
{default_port_device(0x0af0, 0x6711)},
{default_port_device(0x0af0, 0x6731)},
{default_port_device(0x0af0, 0x6751)},
{default_port_device(0x0af0, 0x6771)},
{default_port_device(0x0af0, 0x6791)},
{default_port_device(0x0af0, 0x6811)},
{default_port_device(0x0af0, 0x6911)},
{default_port_device(0x0af0, 0x6951)},
{default_port_device(0x0af0, 0x6971)},
{default_port_device(0x0af0, 0x7011)},
{default_port_device(0x0af0, 0x7031)},
{default_port_device(0x0af0, 0x7051)},
{default_port_device(0x0af0, 0x7071)},
{default_port_device(0x0af0, 0x7111)},
{default_port_device(0x0af0, 0x7211)},
{default_port_device(0x0af0, 0x7251)},
{default_port_device(0x0af0, 0x7271)},
{default_port_device(0x0af0, 0x7311)},
{default_port_device(0x0af0, 0xc031)}, /* Icon-Edge */
{icon321_port_device(0x0af0, 0xd013)}, /* Module HSxPA */
{icon321_port_device(0x0af0, 0xd031)}, /* Icon-321 */
{icon321_port_device(0x0af0, 0xd033)}, /* Icon-322 */
{USB_DEVICE(0x0af0, 0x7301)}, /* GE40x */
{USB_DEVICE(0x0af0, 0x7361)}, /* GE40x */
{USB_DEVICE(0x0af0, 0x7381)}, /* GE40x */
{USB_DEVICE(0x0af0, 0x7401)}, /* GI 0401 */
{USB_DEVICE(0x0af0, 0x7501)}, /* GTM 382 */
{USB_DEVICE(0x0af0, 0x7601)}, /* GE40x */
{USB_DEVICE(0x0af0, 0x7701)},
{USB_DEVICE(0x0af0, 0x7706)},
{USB_DEVICE(0x0af0, 0x7801)},
{USB_DEVICE(0x0af0, 0x7901)},
{USB_DEVICE(0x0af0, 0x7A01)},
{USB_DEVICE(0x0af0, 0x7A05)},
{USB_DEVICE(0x0af0, 0x8200)},
{USB_DEVICE(0x0af0, 0x8201)},
{USB_DEVICE(0x0af0, 0x8300)},
{USB_DEVICE(0x0af0, 0x8302)},
{USB_DEVICE(0x0af0, 0x8304)},
{USB_DEVICE(0x0af0, 0x8400)},
{USB_DEVICE(0x0af0, 0x8600)},
{USB_DEVICE(0x0af0, 0x8800)},
{USB_DEVICE(0x0af0, 0x8900)},
{USB_DEVICE(0x0af0, 0x9000)},
{USB_DEVICE(0x0af0, 0x9200)}, /* Option GTM671WFS */
{USB_DEVICE(0x0af0, 0xd035)},
{USB_DEVICE(0x0af0, 0xd055)},
{USB_DEVICE(0x0af0, 0xd155)},
{USB_DEVICE(0x0af0, 0xd255)},
{USB_DEVICE(0x0af0, 0xd057)},
{USB_DEVICE(0x0af0, 0xd157)},
{USB_DEVICE(0x0af0, 0xd257)},
{USB_DEVICE(0x0af0, 0xd357)},
{USB_DEVICE(0x0af0, 0xd058)},
{USB_DEVICE(0x0af0, 0xc100)},
{}
};
MODULE_DEVICE_TABLE(usb, hso_ids);
/* Sysfs attribute */
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hso_device *hso_dev = dev_get_drvdata(dev);
char *port_name;
if (!hso_dev)
return 0;
switch (hso_dev->port_spec & HSO_PORT_MASK) {
case HSO_PORT_CONTROL:
port_name = "Control";
break;
case HSO_PORT_APP:
port_name = "Application";
break;
case HSO_PORT_APP2:
port_name = "Application2";
break;
case HSO_PORT_GPS:
port_name = "GPS";
break;
case <API key>:
port_name = "GPS Control";
break;
case HSO_PORT_PCSC:
port_name = "PCSC";
break;
case HSO_PORT_DIAG:
port_name = "Diagnostic";
break;
case HSO_PORT_DIAG2:
port_name = "Diagnostic2";
break;
case HSO_PORT_MODEM:
port_name = "Modem";
break;
case HSO_PORT_NETWORK:
port_name = "Network";
break;
default:
port_name = "Unknown";
break;
}
return sprintf(buf, "%s\n", port_name);
}
static DEVICE_ATTR(hsotype, S_IRUGO, <API key>, NULL);
static int hso_urb_to_index(struct hso_serial *serial, struct urb *urb)
{
int idx;
for (idx = 0; idx < serial->num_rx_urbs; idx++)
if (serial->rx_urb[idx] == urb)
return idx;
dev_err(serial->parent->dev, "hso_urb_to_index failed\n");
return -1;
}
/* converts mux value to a port spec value */
static u32 hso_mux_to_port(int mux)
{
u32 result;
switch (mux) {
case 0x1:
result = HSO_PORT_CONTROL;
break;
case 0x2:
result = HSO_PORT_APP;
break;
case 0x4:
result = HSO_PORT_PCSC;
break;
case 0x8:
result = HSO_PORT_GPS;
break;
case 0x10:
result = HSO_PORT_APP2;
break;
default:
result = HSO_PORT_NO_PORT;
}
return result;
}
/* converts port spec value to a mux value */
static u32 hso_port_to_mux(int port)
{
u32 result;
switch (port & HSO_PORT_MASK) {
case HSO_PORT_CONTROL:
result = 0x0;
break;
case HSO_PORT_APP:
result = 0x1;
break;
case HSO_PORT_PCSC:
result = 0x2;
break;
case HSO_PORT_GPS:
result = 0x3;
break;
case HSO_PORT_APP2:
result = 0x4;
break;
default:
result = 0x0;
}
return result;
}
static struct hso_serial *<API key>(
struct hso_shared_int *shared_int,
int mux)
{
int i, port;
port = hso_mux_to_port(mux);
for (i = 0; i < <API key>; i++) {
if (serial_table[i] &&
(dev2ser(serial_table[i])->shared_int == shared_int) &&
((serial_table[i]->port_spec & HSO_PORT_MASK) == port)) {
return dev2ser(serial_table[i]);
}
}
return NULL;
}
static struct hso_serial *get_serial_by_index(unsigned index)
{
struct hso_serial *serial = NULL;
unsigned long flags;
spin_lock_irqsave(&serial_table_lock, flags);
if (serial_table[index])
serial = dev2ser(serial_table[index]);
<API key>(&serial_table_lock, flags);
return serial;
}
static int <API key>(void)
{
int index;
unsigned long flags;
spin_lock_irqsave(&serial_table_lock, flags);
for (index = 0; index < <API key>; index++) {
if (serial_table[index] == NULL) {
<API key>(&serial_table_lock, flags);
return index;
}
}
<API key>(&serial_table_lock, flags);
printk(KERN_ERR "%s: no free serial devices in table\n", __func__);
return -1;
}
static void set_serial_by_index(unsigned index, struct hso_serial *serial)
{
unsigned long flags;
spin_lock_irqsave(&serial_table_lock, flags);
if (serial)
serial_table[index] = serial->parent;
else
serial_table[index] = NULL;
<API key>(&serial_table_lock, flags);
}
static void handle_usb_error(int status, const char *function,
struct hso_device *hso_dev)
{
char *explanation;
switch (status) {
case -ENODEV:
explanation = "no device";
break;
case -ENOENT:
explanation = "endpoint not enabled";
break;
case -EPIPE:
explanation = "endpoint stalled";
break;
case -ENOSPC:
explanation = "not enough bandwidth";
break;
case -ESHUTDOWN:
explanation = "device disabled";
break;
case -EHOSTUNREACH:
explanation = "device suspended";
break;
case -EINVAL:
case -EAGAIN:
case -EFBIG:
case -EMSGSIZE:
explanation = "internal error";
break;
case -EILSEQ:
case -EPROTO:
case -ETIME:
case -ETIMEDOUT:
explanation = "protocol error";
if (hso_dev)
schedule_work(&hso_dev->reset_device);
break;
default:
explanation = "unknown status";
break;
}
/* log a meaningful explanation of an USB status */
D1("%s: received USB status - %s (%d)", function, explanation, status);
}
/* Network interface functions */
/* called when net interface is brought up by ifconfig */
static int hso_net_open(struct net_device *net)
{
struct hso_net *odev = netdev_priv(net);
unsigned long flags = 0;
if (!odev) {
dev_err(&net->dev, "No net device !\n");
return -ENODEV;
}
odev->skb_tx_buf = NULL;
/* setup environment */
spin_lock_irqsave(&odev->net_lock, flags);
odev->rx_parse_state = WAIT_IP;
odev->rx_buf_size = 0;
odev->rx_buf_missing = sizeof(struct iphdr);
<API key>(&odev->net_lock, flags);
/* We are up and running. */
set_bit(HSO_NET_RUNNING, &odev->flags);
<API key>(odev->parent);
/* Tell the kernel we are ready to start receiving from it */
netif_start_queue(net);
return 0;
}
/* called when interface is brought down by ifconfig */
static int hso_net_close(struct net_device *net)
{
struct hso_net *odev = netdev_priv(net);
/* we don't need the queue anymore */
netif_stop_queue(net);
/* no longer running */
clear_bit(HSO_NET_RUNNING, &odev->flags);
hso_stop_net_device(odev->parent);
/* done */
return 0;
}
/* USB tells is xmit done, we should start the netqueue again */
static void write_bulk_callback(struct urb *urb)
{
struct hso_net *odev = urb->context;
int status = urb->status;
/* Sanity check */
if (!odev || !test_bit(HSO_NET_RUNNING, &odev->flags)) {
dev_err(&urb->dev->dev, "%s: device not running\n", __func__);
return;
}
/* Do we still have a valid kernel network device? */
if (!<API key>(odev->net)) {
dev_err(&urb->dev->dev, "%s: net device not present\n",
__func__);
return;
}
/* log status, but don't act on it, we don't need to resubmit anything
* anyhow */
if (status)
handle_usb_error(status, __func__, odev->parent);
hso_put_activity(odev->parent);
/* Tell the network interface we are ready for another frame */
netif_wake_queue(odev->net);
}
/* called by kernel when we need to transmit a packet */
static netdev_tx_t hso_net_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct hso_net *odev = netdev_priv(net);
int result;
/* Tell the kernel, "No more frames 'til we are done with this one." */
netif_stop_queue(net);
if (hso_get_activity(odev->parent) == -EAGAIN) {
odev->skb_tx_buf = skb;
return NETDEV_TX_OK;
}
/* log if asked */
DUMP1(skb->data, skb->len);
/* Copy it from kernel memory to OUR memory */
memcpy(odev->mux_bulk_tx_buf, skb->data, skb->len);
D1("len: %d/%d", skb->len, <API key>);
/* Fill in the URB for shipping it out. */
usb_fill_bulk_urb(odev->mux_bulk_tx_urb,
odev->parent->usb,
usb_sndbulkpipe(odev->parent->usb,
odev->out_endp->
bEndpointAddress & 0x7F),
odev->mux_bulk_tx_buf, skb->len, write_bulk_callback,
odev);
/* Deal with the Zero Length packet problem, I hope */
odev->mux_bulk_tx_urb->transfer_flags |= URB_ZERO_PACKET;
/* Send the URB on its merry way. */
result = usb_submit_urb(odev->mux_bulk_tx_urb, GFP_ATOMIC);
if (result) {
dev_warn(&odev->parent->interface->dev,
"failed mux_bulk_tx_urb %d\n", result);
net->stats.tx_errors++;
netif_start_queue(net);
} else {
net->stats.tx_packets++;
net->stats.tx_bytes += skb->len;
}
dev_kfree_skb(skb);
/* we're done */
return NETDEV_TX_OK;
}
static const struct ethtool_ops ops = {
.get_link = ethtool_op_get_link
};
/* called when a packet did not ack after watchdogtimeout */
static void hso_net_tx_timeout(struct net_device *net)
{
struct hso_net *odev = netdev_priv(net);
if (!odev)
return;
/* Tell syslog we are hosed. */
dev_warn(&net->dev, "Tx timed out.\n");
/* Tear the waiting frame off the list */
if (odev->mux_bulk_tx_urb &&
(odev->mux_bulk_tx_urb->status == -EINPROGRESS))
usb_unlink_urb(odev->mux_bulk_tx_urb);
/* Update statistics */
net->stats.tx_errors++;
}
/* make a real packet from the received USB buffer */
static void packetizeRx(struct hso_net *odev, unsigned char *ip_pkt,
unsigned int count, unsigned char is_eop)
{
unsigned short temp_bytes;
unsigned short buffer_offset = 0;
unsigned short frame_len;
unsigned char *tmp_rx_buf;
/* log if needed */
D1("Rx %d bytes", count);
DUMP(ip_pkt, min(128, (int)count));
while (count) {
switch (odev->rx_parse_state) {
case WAIT_IP:
/* waiting for IP header. */
/* wanted bytes - size of ip header */
temp_bytes =
(count <
odev->rx_buf_missing) ? count : odev->
rx_buf_missing;
memcpy(((unsigned char *)(&odev->rx_ip_hdr)) +
odev->rx_buf_size, ip_pkt + buffer_offset,
temp_bytes);
odev->rx_buf_size += temp_bytes;
buffer_offset += temp_bytes;
odev->rx_buf_missing -= temp_bytes;
count -= temp_bytes;
if (!odev->rx_buf_missing) {
/* header is complete allocate an sk_buffer and
* continue to WAIT_DATA */
frame_len = ntohs(odev->rx_ip_hdr.tot_len);
if ((frame_len > DEFAULT_MRU) ||
(frame_len < sizeof(struct iphdr))) {
dev_err(&odev->net->dev,
"Invalid frame (%d) length\n",
frame_len);
odev->rx_parse_state = WAIT_SYNC;
continue;
}
/* Allocate an sk_buff */
odev->skb_rx_buf = netdev_alloc_skb(odev->net,
frame_len);
if (!odev->skb_rx_buf) {
/* We got no receive buffer. */
D1("could not allocate memory");
odev->rx_parse_state = WAIT_SYNC;
return;
}
/* Copy what we got so far. make room for iphdr
* after tail. */
tmp_rx_buf =
skb_put(odev->skb_rx_buf,
sizeof(struct iphdr));
memcpy(tmp_rx_buf, (char *)&(odev->rx_ip_hdr),
sizeof(struct iphdr));
/* ETH_HLEN */
odev->rx_buf_size = sizeof(struct iphdr);
/* Filip actually use .tot_len */
odev->rx_buf_missing =
frame_len - sizeof(struct iphdr);
odev->rx_parse_state = WAIT_DATA;
}
break;
case WAIT_DATA:
temp_bytes = (count < odev->rx_buf_missing)
? count : odev->rx_buf_missing;
/* Copy the rest of the bytes that are left in the
* buffer into the waiting sk_buf. */
/* Make room for temp_bytes after tail. */
tmp_rx_buf = skb_put(odev->skb_rx_buf, temp_bytes);
memcpy(tmp_rx_buf, ip_pkt + buffer_offset, temp_bytes);
odev->rx_buf_missing -= temp_bytes;
count -= temp_bytes;
buffer_offset += temp_bytes;
odev->rx_buf_size += temp_bytes;
if (!odev->rx_buf_missing) {
/* Packet is complete. Inject into stack. */
/* We have IP packet here */
odev->skb_rx_buf->protocol = cpu_to_be16(ETH_P_IP);
<API key>(odev->skb_rx_buf);
/* Ship it off to the kernel */
netif_rx(odev->skb_rx_buf);
/* No longer our buffer. */
odev->skb_rx_buf = NULL;
/* update out statistics */
odev->net->stats.rx_packets++;
odev->net->stats.rx_bytes += odev->rx_buf_size;
odev->rx_buf_size = 0;
odev->rx_buf_missing = sizeof(struct iphdr);
odev->rx_parse_state = WAIT_IP;
}
break;
case WAIT_SYNC:
D1(" W_S");
count = 0;
break;
default:
D1(" ");
count
break;
}
}
/* Recovery mechanism for WAIT_SYNC state. */
if (is_eop) {
if (odev->rx_parse_state == WAIT_SYNC) {
odev->rx_parse_state = WAIT_IP;
odev->rx_buf_size = 0;
odev->rx_buf_missing = sizeof(struct iphdr);
}
}
}
static void fix_crc_bug(struct urb *urb, __le16 max_packet_size)
{
static const u8 crc_check[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
u32 rest = urb->actual_length % le16_to_cpu(max_packet_size);
if (((rest == 5) || (rest == 6)) &&
!memcmp(((u8 *)urb->transfer_buffer) + urb->actual_length - 4,
crc_check, 4)) {
urb->actual_length -= 4;
}
}
/* Moving data from usb to kernel (in interrupt state) */
static void read_bulk_callback(struct urb *urb)
{
struct hso_net *odev = urb->context;
struct net_device *net;
int result;
int status = urb->status;
/* is al ok? (Filip: Who's Al ?) */
if (status) {
handle_usb_error(status, __func__, odev->parent);
return;
}
/* Sanity check */
if (!odev || !test_bit(HSO_NET_RUNNING, &odev->flags)) {
D1("BULK IN callback but driver is not active!");
return;
}
usb_mark_last_busy(urb->dev);
net = odev->net;
if (!<API key>(net)) {
/* Somebody killed our network interface... */
return;
}
if (odev->parent->port_spec & HSO_INFO_CRC_BUG)
fix_crc_bug(urb, odev->in_endp->wMaxPacketSize);
/* do we even have a packet? */
if (urb->actual_length) {
/* Handle the IP stream, add header and push it onto network
* stack if the packet is complete. */
spin_lock(&odev->net_lock);
packetizeRx(odev, urb->transfer_buffer, urb->actual_length,
(urb-><API key> >
urb->actual_length) ? 1 : 0);
spin_unlock(&odev->net_lock);
}
/* We are done with this URB, resubmit it. Prep the USB to wait for
* another frame. Reuse same as received. */
usb_fill_bulk_urb(urb,
odev->parent->usb,
usb_rcvbulkpipe(odev->parent->usb,
odev->in_endp->
bEndpointAddress & 0x7F),
urb->transfer_buffer, <API key>,
read_bulk_callback, odev);
/* Give this to the USB subsystem so it can tell us when more data
* arrives. */
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_warn(&odev->parent->interface->dev,
"%s failed submit mux_bulk_rx_urb %d\n", __func__,
result);
}
/* Serial driver functions */
static void hso_init_termios(struct ktermios *termios)
{
/*
* The default requirements for this device are:
*/
termios->c_iflag &=
~(IGNBRK /* disable ignore break */
| BRKINT /* disable break causes interrupt */
| PARMRK /* disable mark parity errors */
| ISTRIP /* disable clear high bit of input characters */
| INLCR /* disable translate NL to CR */
| IGNCR /* disable ignore CR */
| ICRNL /* disable translate CR to NL */
| IXON); /* disable enable XON/XOFF flow control */
/* disable postprocess output characters */
termios->c_oflag &= ~OPOST;
termios->c_lflag &=
~(ECHO /* disable echo input characters */
| ECHONL /* disable echo new line */
| ICANON /* disable erase, kill, werase, and rprnt
special characters */
| ISIG /* disable interrupt, quit, and suspend special
characters */
| IEXTEN); /* disable non-POSIX special characters */
termios->c_cflag &=
~(CSIZE /* no size */
| PARENB /* disable parity bit */
| CBAUD /* clear current baud rate */
| CBAUDEX); /* clear current buad rate */
termios->c_cflag |= CS8; /* character size 8 bits */
/* baud rate 115200 */
<API key>(termios, 115200, 115200);
}
static void <API key>(struct tty_struct *tty,
struct ktermios *old)
{
struct hso_serial *serial = tty->driver_data;
if (!serial) {
printk(KERN_ERR "%s: no tty structures", __func__);
return;
}
D4("port %d", serial->minor);
/*
* Fix up unsupported bits
*/
tty->termios.c_iflag &= ~IXON; /* disable enable XON/XOFF flow control */
tty->termios.c_cflag &=
~(CSIZE /* no size */
| PARENB /* disable parity bit */
| CBAUD /* clear current baud rate */
| CBAUDEX); /* clear current buad rate */
tty->termios.c_cflag |= CS8; /* character size 8 bits */
/* baud rate 115200 */
<API key>(tty, 115200, 115200);
}
static void <API key>(struct hso_serial *serial, struct urb *urb)
{
int result;
/* We are done with this URB, resubmit it. Prep the USB to wait for
* another frame */
usb_fill_bulk_urb(urb, serial->parent->usb,
usb_rcvbulkpipe(serial->parent->usb,
serial->in_endp->
bEndpointAddress & 0x7F),
urb->transfer_buffer, serial->rx_data_length,
<API key>, serial);
/* Give this to the USB subsystem so it can tell us when more data
* arrives. */
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result) {
dev_err(&urb->dev->dev, "%s failed submit serial rx_urb %d\n",
__func__, result);
}
}
static void <API key>(struct hso_serial *serial)
{
int count;
struct urb *curr_urb;
while (serial->rx_urb_filled[serial->curr_rx_urb_idx]) {
curr_urb = serial->rx_urb[serial->curr_rx_urb_idx];
count = put_rxbuf_data(curr_urb, serial);
if (count == -1)
return;
if (count == 0) {
serial->curr_rx_urb_idx++;
if (serial->curr_rx_urb_idx >= serial->num_rx_urbs)
serial->curr_rx_urb_idx = 0;
<API key>(serial, curr_urb);
}
}
}
static void <API key>(struct hso_serial *serial)
{
int count = 0;
struct urb *urb;
urb = serial->rx_urb[0];
if (serial->port.count > 0) {
count = put_rxbuf_data(urb, serial);
if (count == -1)
return;
}
/* Re issue a read as long as we receive data. */
if (count == 0 && ((urb->actual_length != 0) ||
(serial->rx_state == RX_PENDING))) {
serial->rx_state = RX_SENT;
hso_mux_serial_read(serial);
} else
serial->rx_state = RX_IDLE;
}
/* read callback for Diag and CS port */
static void <API key>(struct urb *urb)
{
struct hso_serial *serial = urb->context;
int status = urb->status;
D4("\n
/* sanity check */
if (!serial) {
D1("serial == NULL");
return;
}
if (status) {
handle_usb_error(status, __func__, serial->parent);
return;
}
D1("Actual length = %d\n", urb->actual_length);
DUMP1(urb->transfer_buffer, urb->actual_length);
/* Anyone listening? */
if (serial->port.count == 0)
return;
if (serial->parent->port_spec & HSO_INFO_CRC_BUG)
fix_crc_bug(urb, serial->in_endp->wMaxPacketSize);
/* Valid data, handle RX data */
spin_lock(&serial->serial_lock);
serial->rx_urb_filled[hso_urb_to_index(serial, urb)] = 1;
<API key>(serial);
spin_unlock(&serial->serial_lock);
}
/*
* This needs to be a tasklet otherwise we will
* end up recursively calling this function.
*/
static void <API key>(struct hso_serial *serial)
{
unsigned long flags;
spin_lock_irqsave(&serial->serial_lock, flags);
if ((serial->parent->port_spec & HSO_INTF_MUX))
<API key>(serial);
else
<API key>(serial);
<API key>(&serial->serial_lock, flags);
}
static void hso_unthrottle(struct tty_struct *tty)
{
struct hso_serial *serial = tty->driver_data;
tasklet_hi_schedule(&serial->unthrottle_tasklet);
}
/* open the requested serial port */
static int hso_serial_open(struct tty_struct *tty, struct file *filp)
{
struct hso_serial *serial = get_serial_by_index(tty->index);
int result;
/* sanity check */
if (serial == NULL || serial->magic != HSO_SERIAL_MAGIC) {
WARN_ON(1);
tty->driver_data = NULL;
D1("Failed to open port");
return -ENODEV;
}
mutex_lock(&serial->parent->mutex);
result = <API key>(serial->parent->interface);
if (result < 0)
goto err_out;
D1("Opening %d", serial->minor);
kref_get(&serial->parent->ref);
/* setup */
tty->driver_data = serial;
tty_port_tty_set(&serial->port, tty);
/* check for port already opened, if not set the termios */
serial->port.count++;
if (serial->port.count == 1) {
serial->rx_state = RX_IDLE;
/* Force default termio settings */
<API key>(tty, NULL);
tasklet_init(&serial->unthrottle_tasklet,
(void (*)(unsigned long))<API key>,
(unsigned long)serial);
result = <API key>(serial->parent, GFP_KERNEL);
if (result) {
<API key>(serial->parent);
serial->port.count
kref_put(&serial->parent->ref, hso_serial_ref_free);
}
} else {
D1("Port was already open");
}
<API key>(serial->parent->interface);
/* done */
if (result)
hso_serial_tiocmset(tty, TIOCM_RTS | TIOCM_DTR, 0);
err_out:
mutex_unlock(&serial->parent->mutex);
return result;
}
/* close the requested serial port */
static void hso_serial_close(struct tty_struct *tty, struct file *filp)
{
struct hso_serial *serial = tty->driver_data;
u8 usb_gone;
D1("Closing serial port");
/* Open failed, no close cleanup required */
if (serial == NULL)
return;
mutex_lock(&serial->parent->mutex);
usb_gone = serial->parent->usb_gone;
if (!usb_gone)
<API key>(serial->parent->interface);
/* reset the rts and dtr */
/* do the actual close */
serial->port.count
if (serial->port.count <= 0) {
serial->port.count = 0;
tty_port_tty_set(&serial->port, NULL);
if (!usb_gone)
<API key>(serial->parent);
tasklet_kill(&serial->unthrottle_tasklet);
}
if (!usb_gone)
<API key>(serial->parent->interface);
mutex_unlock(&serial->parent->mutex);
kref_put(&serial->parent->ref, hso_serial_ref_free);
}
/* close the requested serial port */
static int hso_serial_write(struct tty_struct *tty, const unsigned char *buf,
int count)
{
struct hso_serial *serial = tty->driver_data;
int space, tx_bytes;
unsigned long flags;
/* sanity check */
if (serial == NULL) {
printk(KERN_ERR "%s: serial is NULL\n", __func__);
return -ENODEV;
}
spin_lock_irqsave(&serial->serial_lock, flags);
space = serial->tx_data_length - serial->tx_buffer_count;
tx_bytes = (count < space) ? count : space;
if (!tx_bytes)
goto out;
memcpy(serial->tx_buffer + serial->tx_buffer_count, buf, tx_bytes);
serial->tx_buffer_count += tx_bytes;
out:
<API key>(&serial->serial_lock, flags);
hso_kick_transmit(serial);
/* done */
return tx_bytes;
}
/* how much room is there for writing */
static int <API key>(struct tty_struct *tty)
{
struct hso_serial *serial = tty->driver_data;
int room;
unsigned long flags;
spin_lock_irqsave(&serial->serial_lock, flags);
room = serial->tx_data_length - serial->tx_buffer_count;
<API key>(&serial->serial_lock, flags);
/* return free room */
return room;
}
/* setup the term */
static void <API key>(struct tty_struct *tty, struct ktermios *old)
{
struct hso_serial *serial = tty->driver_data;
unsigned long flags;
if (old)
D5("Termios called with: cflags new[%d] - old[%d]",
tty->termios.c_cflag, old->c_cflag);
/* the actual setup */
spin_lock_irqsave(&serial->serial_lock, flags);
if (serial->port.count)
<API key>(tty, old);
else
tty->termios = *old;
<API key>(&serial->serial_lock, flags);
/* done */
}
/* how many characters in the buffer */
static int <API key>(struct tty_struct *tty)
{
struct hso_serial *serial = tty->driver_data;
int chars;
unsigned long flags;
/* sanity check */
if (serial == NULL)
return 0;
spin_lock_irqsave(&serial->serial_lock, flags);
chars = serial->tx_buffer_count;
<API key>(&serial->serial_lock, flags);
return chars;
}
static int tiocmget_submit_urb(struct hso_serial *serial,
struct hso_tiocmget *tiocmget,
struct usb_device *usb)
{
int result;
if (serial->parent->usb_gone)
return -ENODEV;
usb_fill_int_urb(tiocmget->urb, usb,
usb_rcvintpipe(usb,
tiocmget->endp->
bEndpointAddress & 0x7F),
&tiocmget-><API key>,
sizeof(struct <API key>),
<API key>, serial,
tiocmget->endp->bInterval);
result = usb_submit_urb(tiocmget->urb, GFP_ATOMIC);
if (result) {
dev_warn(&usb->dev, "%s usb_submit_urb failed %d\n", __func__,
result);
}
return result;
}
static void <API key>(struct urb *urb)
{
struct hso_serial *serial = urb->context;
struct hso_tiocmget *tiocmget;
int status = urb->status;
u16 UART_state_bitmap, <API key>;
struct uart_icount *icount;
struct <API key> *<API key>;
struct usb_device *usb;
int if_num;
/* Sanity checks */
if (!serial)
return;
if (status) {
handle_usb_error(status, __func__, serial->parent);
return;
}
/* tiocmget is only supported on HSO_PORT_MODEM */
tiocmget = serial->tiocmget;
if (!tiocmget)
return;
BUG_ON((serial->parent->port_spec & HSO_PORT_MASK) != HSO_PORT_MODEM);
usb = serial->parent->usb;
if_num = serial->parent->interface->altsetting->desc.bInterfaceNumber;
/* wIndex should be the USB interface number of the port to which the
* notification applies, which should always be the Modem port.
*/
<API key> = &tiocmget-><API key>;
if (<API key>->bmRequestType != BM_REQUEST_TYPE ||
<API key>->bNotification != B_NOTIFICATION ||
le16_to_cpu(<API key>->wValue) != W_VALUE ||
le16_to_cpu(<API key>->wIndex) != if_num ||
le16_to_cpu(<API key>->wLength) != W_LENGTH) {
dev_warn(&usb->dev,
"hso received invalid serial state notification\n");
DUMP(<API key>,
sizeof(struct <API key>));
} else {
UART_state_bitmap = le16_to_cpu(<API key>->
UART_state_bitmap);
<API key> = tiocmget-><API key>;
icount = &tiocmget->icount;
spin_lock(&serial->serial_lock);
if ((UART_state_bitmap & B_OVERRUN) !=
(<API key> & B_OVERRUN))
icount->parity++;
if ((UART_state_bitmap & B_PARITY) !=
(<API key> & B_PARITY))
icount->parity++;
if ((UART_state_bitmap & B_FRAMING) !=
(<API key> & B_FRAMING))
icount->frame++;
if ((UART_state_bitmap & B_RING_SIGNAL) &&
!(<API key> & B_RING_SIGNAL))
icount->rng++;
if ((UART_state_bitmap & B_BREAK) !=
(<API key> & B_BREAK))
icount->brk++;
if ((UART_state_bitmap & B_TX_CARRIER) !=
(<API key> & B_TX_CARRIER))
icount->dsr++;
if ((UART_state_bitmap & B_RX_CARRIER) !=
(<API key> & B_RX_CARRIER))
icount->dcd++;
tiocmget-><API key> = UART_state_bitmap;
spin_unlock(&serial->serial_lock);
tiocmget->intr_completed = 1;
<API key>(&tiocmget->waitq);
}
memset(<API key>, 0,
sizeof(struct <API key>));
tiocmget_submit_urb(serial,
tiocmget,
serial->parent->usb);
}
/*
* next few functions largely stolen from drivers/serial/serial_core.c
*/
/* Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
* - mask passed in arg for lines of interest
* (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
* Caller should use TIOCGICOUNT to see which one it was
*/
static int
<API key>(struct hso_serial *serial, unsigned long arg)
{
DECLARE_WAITQUEUE(wait, current);
struct uart_icount cprev, cnow;
struct hso_tiocmget *tiocmget;
int ret;
tiocmget = serial->tiocmget;
if (!tiocmget)
return -ENOENT;
/*
* note the counters on entry
*/
spin_lock_irq(&serial->serial_lock);
memcpy(&cprev, &tiocmget->icount, sizeof(struct uart_icount));
spin_unlock_irq(&serial->serial_lock);
add_wait_queue(&tiocmget->waitq, &wait);
for (;;) {
spin_lock_irq(&serial->serial_lock);
memcpy(&cnow, &tiocmget->icount, sizeof(struct uart_icount));
spin_unlock_irq(&serial->serial_lock);
set_current_state(TASK_INTERRUPTIBLE);
if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd))) {
ret = 0;
break;
}
schedule();
/* see if a signal did it */
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
cprev = cnow;
}
current->state = TASK_RUNNING;
remove_wait_queue(&tiocmget->waitq, &wait);
return ret;
}
/*
* Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
* Return: write counters to the user passed counter struct
* NB: both 1->0 and 0->1 transitions are counted except for
* RI where only 0->1 is counted.
*/
static int hso_get_count(struct tty_struct *tty,
struct <API key> *icount)
{
struct uart_icount cnow;
struct hso_serial *serial = tty->driver_data;
struct hso_tiocmget *tiocmget = serial->tiocmget;
memset(icount, 0, sizeof(struct <API key>));
if (!tiocmget)
return -ENOENT;
spin_lock_irq(&serial->serial_lock);
memcpy(&cnow, &tiocmget->icount, sizeof(struct uart_icount));
spin_unlock_irq(&serial->serial_lock);
icount->cts = cnow.cts;
icount->dsr = cnow.dsr;
icount->rng = cnow.rng;
icount->dcd = cnow.dcd;
icount->rx = cnow.rx;
icount->tx = cnow.tx;
icount->frame = cnow.frame;
icount->overrun = cnow.overrun;
icount->parity = cnow.parity;
icount->brk = cnow.brk;
icount->buf_overrun = cnow.buf_overrun;
return 0;
}
static int hso_serial_tiocmget(struct tty_struct *tty)
{
int retval;
struct hso_serial *serial = tty->driver_data;
struct hso_tiocmget *tiocmget;
u16 UART_state_bitmap;
/* sanity check */
if (!serial) {
D1("no tty structures");
return -EINVAL;
}
spin_lock_irq(&serial->serial_lock);
retval = ((serial->rts_state) ? TIOCM_RTS : 0) |
((serial->dtr_state) ? TIOCM_DTR : 0);
tiocmget = serial->tiocmget;
if (tiocmget) {
UART_state_bitmap = le16_to_cpu(
tiocmget-><API key>);
if (UART_state_bitmap & B_RING_SIGNAL)
retval |= TIOCM_RNG;
if (UART_state_bitmap & B_RX_CARRIER)
retval |= TIOCM_CD;
if (UART_state_bitmap & B_TX_CARRIER)
retval |= TIOCM_DSR;
}
spin_unlock_irq(&serial->serial_lock);
return retval;
}
static int hso_serial_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
int val = 0;
unsigned long flags;
int if_num;
struct hso_serial *serial = tty->driver_data;
/* sanity check */
if (!serial) {
D1("no tty structures");
return -EINVAL;
}
if ((serial->parent->port_spec & HSO_PORT_MASK) != HSO_PORT_MODEM)
return -EINVAL;
if_num = serial->parent->interface->altsetting->desc.bInterfaceNumber;
spin_lock_irqsave(&serial->serial_lock, flags);
if (set & TIOCM_RTS)
serial->rts_state = 1;
if (set & TIOCM_DTR)
serial->dtr_state = 1;
if (clear & TIOCM_RTS)
serial->rts_state = 0;
if (clear & TIOCM_DTR)
serial->dtr_state = 0;
if (serial->dtr_state)
val |= 0x01;
if (serial->rts_state)
val |= 0x02;
<API key>(&serial->serial_lock, flags);
return usb_control_msg(serial->parent->usb,
usb_rcvctrlpipe(serial->parent->usb, 0), 0x22,
0x21, val, if_num, NULL, 0,
<API key>);
}
static int hso_serial_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct hso_serial *serial = tty->driver_data;
int ret = 0;
D4("IOCTL cmd: %d, arg: %ld", cmd, arg);
if (!serial)
return -ENODEV;
switch (cmd) {
case TIOCMIWAIT:
ret = <API key>(serial, arg);
break;
default:
ret = -ENOIOCTLCMD;
break;
}
return ret;
}
/* starts a transmit */
static void hso_kick_transmit(struct hso_serial *serial)
{
u8 *temp;
unsigned long flags;
int res;
spin_lock_irqsave(&serial->serial_lock, flags);
if (!serial->tx_buffer_count)
goto out;
if (serial->tx_urb_used)
goto out;
/* Wakeup USB interface if necessary */
if (hso_get_activity(serial->parent) == -EAGAIN)
goto out;
/* Switch pointers around to avoid memcpy */
temp = serial->tx_buffer;
serial->tx_buffer = serial->tx_data;
serial->tx_data = temp;
serial->tx_data_count = serial->tx_buffer_count;
serial->tx_buffer_count = 0;
/* If temp is set, it means we switched buffers */
if (temp && serial->write_data) {
res = serial->write_data(serial);
if (res >= 0)
serial->tx_urb_used = 1;
}
out:
<API key>(&serial->serial_lock, flags);
}
/* make a request (for reading and writing data to muxed serial port) */
static int mux_device_request(struct hso_serial *serial, u8 type, u16 port,
struct urb *ctrl_urb,
struct usb_ctrlrequest *ctrl_req,
u8 *ctrl_urb_data, u32 size)
{
int result;
int pipe;
/* Sanity check */
if (!serial || !ctrl_urb || !ctrl_req) {
printk(KERN_ERR "%s: Wrong arguments\n", __func__);
return -EINVAL;
}
/* initialize */
ctrl_req->wValue = 0;
ctrl_req->wIndex = cpu_to_le16(hso_port_to_mux(port));
ctrl_req->wLength = cpu_to_le16(size);
if (type == <API key>) {
/* Reading command */
ctrl_req->bRequestType = USB_DIR_IN |
<API key> |
USB_RECIP_INTERFACE;
ctrl_req->bRequest = <API key>;
pipe = usb_rcvctrlpipe(serial->parent->usb, 0);
} else {
/* Writing command */
ctrl_req->bRequestType = USB_DIR_OUT |
<API key> |
USB_RECIP_INTERFACE;
ctrl_req->bRequest = <API key>;
pipe = usb_sndctrlpipe(serial->parent->usb, 0);
}
/* syslog */
D2("%s command (%02x) len: %d, port: %d",
type == <API key> ? "Read" : "Write",
ctrl_req->bRequestType, ctrl_req->wLength, port);
/* Load ctrl urb */
ctrl_urb->transfer_flags = 0;
<API key>(ctrl_urb,
serial->parent->usb,
pipe,
(u8 *) ctrl_req,
ctrl_urb_data, size, ctrl_callback, serial);
/* Send it on merry way */
result = usb_submit_urb(ctrl_urb, GFP_ATOMIC);
if (result) {
dev_err(&ctrl_urb->dev->dev,
"%s failed submit ctrl_urb %d type %d\n", __func__,
result, type);
return result;
}
/* done */
return size;
}
/* called by intr_callback when read occurs */
static int hso_mux_serial_read(struct hso_serial *serial)
{
if (!serial)
return -EINVAL;
/* clean data */
memset(serial->rx_data[0], 0, CTRL_URB_RX_SIZE);
/* make the request */
if (serial->num_rx_urbs != 1) {
dev_err(&serial->parent->interface->dev,
"ERROR: mux'd reads with multiple buffers "
"not possible\n");
return 0;
}
return mux_device_request(serial,
<API key>,
serial->parent->port_spec & HSO_PORT_MASK,
serial->rx_urb[0],
&serial->ctrl_req_rx,
serial->rx_data[0], serial->rx_data_length);
}
/* used for muxed serial port callback (muxed serial read) */
static void intr_callback(struct urb *urb)
{
struct hso_shared_int *shared_int = urb->context;
struct hso_serial *serial;
unsigned char *port_req;
int status = urb->status;
int i;
usb_mark_last_busy(urb->dev);
/* sanity check */
if (!shared_int)
return;
/* status check */
if (status) {
handle_usb_error(status, __func__, NULL);
return;
}
D4("\n
/* what request? */
port_req = urb->transfer_buffer;
D4(" port_req = 0x%.2X\n", *port_req);
/* loop over all muxed ports to find the one sending this */
for (i = 0; i < 8; i++) {
/* max 8 channels on MUX */
if (*port_req & (1 << i)) {
serial = <API key>(shared_int,
(1 << i));
if (serial != NULL) {
D1("Pending read interrupt on port %d\n", i);
spin_lock(&serial->serial_lock);
if (serial->rx_state == RX_IDLE &&
serial->port.count > 0) {
/* Setup and send a ctrl req read on
* port i */
if (!serial->rx_urb_filled[0]) {
serial->rx_state = RX_SENT;
hso_mux_serial_read(serial);
} else
serial->rx_state = RX_PENDING;
} else {
D1("Already a read pending on "
"port %d or port not open\n", i);
}
spin_unlock(&serial->serial_lock);
}
}
}
/* Resubmit interrupt urb */
<API key>(shared_int, urb->dev, GFP_ATOMIC);
}
/* called for writing to muxed serial port */
static int <API key>(struct hso_serial *serial)
{
if (NULL == serial)
return -EINVAL;
return mux_device_request(serial,
<API key>,
serial->parent->port_spec & HSO_PORT_MASK,
serial->tx_urb,
&serial->ctrl_req_tx,
serial->tx_data, serial->tx_data_count);
}
/* write callback for Diag and CS port */
static void <API key>(struct urb *urb)
{
struct hso_serial *serial = urb->context;
int status = urb->status;
/* sanity check */
if (!serial) {
D1("serial == NULL");
return;
}
spin_lock(&serial->serial_lock);
serial->tx_urb_used = 0;
spin_unlock(&serial->serial_lock);
if (status) {
handle_usb_error(status, __func__, serial->parent);
return;
}
hso_put_activity(serial->parent);
tty_port_tty_wakeup(&serial->port);
hso_kick_transmit(serial);
D1(" ");
}
/* called for writing diag or CS serial port */
static int <API key>(struct hso_serial *serial)
{
int count = serial->tx_data_count;
int result;
usb_fill_bulk_urb(serial->tx_urb,
serial->parent->usb,
usb_sndbulkpipe(serial->parent->usb,
serial->out_endp->
bEndpointAddress & 0x7F),
serial->tx_data, serial->tx_data_count,
<API key>, serial);
result = usb_submit_urb(serial->tx_urb, GFP_ATOMIC);
if (result) {
dev_warn(&serial->parent->usb->dev,
"Failed to submit urb - res %d\n", result);
return result;
}
return count;
}
/* callback after read or write on muxed serial port */
static void ctrl_callback(struct urb *urb)
{
struct hso_serial *serial = urb->context;
struct usb_ctrlrequest *req;
int status = urb->status;
/* sanity check */
if (!serial)
return;
spin_lock(&serial->serial_lock);
serial->tx_urb_used = 0;
spin_unlock(&serial->serial_lock);
if (status) {
handle_usb_error(status, __func__, serial->parent);
return;
}
/* what request? */
req = (struct usb_ctrlrequest *)(urb->setup_packet);
D4("\n
D4("Actual length of urb = %d\n", urb->actual_length);
DUMP1(urb->transfer_buffer, urb->actual_length);
if (req->bRequestType ==
(USB_DIR_IN | <API key> | USB_RECIP_INTERFACE)) {
/* response to a read command */
serial->rx_urb_filled[0] = 1;
spin_lock(&serial->serial_lock);
<API key>(serial);
spin_unlock(&serial->serial_lock);
} else {
hso_put_activity(serial->parent);
tty_port_tty_wakeup(&serial->port);
/* response to a write command */
hso_kick_transmit(serial);
}
}
/* handle RX data for serial port */
static int put_rxbuf_data(struct urb *urb, struct hso_serial *serial)
{
struct tty_struct *tty;
int count;
/* Sanity check */
if (urb == NULL || serial == NULL) {
D1("serial = NULL");
return -2;
}
tty = tty_port_tty_get(&serial->port);
if (tty && test_bit(TTY_THROTTLED, &tty->flags)) {
tty_kref_put(tty);
return -1;
}
/* Push data to tty */
D1("data to push to tty");
count = <API key>(&serial->port, urb->actual_length);
if (count >= urb->actual_length) {
<API key>(&serial->port, urb->transfer_buffer,
urb->actual_length);
<API key>(&serial->port);
} else {
dev_warn(&serial->parent->usb->dev,
"dropping data, %d bytes lost\n", urb->actual_length);
}
tty_kref_put(tty);
serial->rx_urb_filled[hso_urb_to_index(serial, urb)] = 0;
return 0;
}
/* Base driver functions */
static void hso_log_port(struct hso_device *hso_dev)
{
char *port_type;
char port_dev[20];
switch (hso_dev->port_spec & HSO_PORT_MASK) {
case HSO_PORT_CONTROL:
port_type = "Control";
break;
case HSO_PORT_APP:
port_type = "Application";
break;
case HSO_PORT_GPS:
port_type = "GPS";
break;
case <API key>:
port_type = "GPS control";
break;
case HSO_PORT_APP2:
port_type = "Application2";
break;
case HSO_PORT_PCSC:
port_type = "PCSC";
break;
case HSO_PORT_DIAG:
port_type = "Diagnostic";
break;
case HSO_PORT_DIAG2:
port_type = "Diagnostic2";
break;
case HSO_PORT_MODEM:
port_type = "Modem";
break;
case HSO_PORT_NETWORK:
port_type = "Network";
break;
default:
port_type = "Unknown";
break;
}
if ((hso_dev->port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {
sprintf(port_dev, "%s", dev2net(hso_dev)->net->name);
} else
sprintf(port_dev, "/dev/%s%d", tty_filename,
dev2ser(hso_dev)->minor);
dev_dbg(&hso_dev->interface->dev, "HSO: Found %s port %s\n",
port_type, port_dev);
}
static int <API key>(struct hso_device *hso_dev)
{
int i, result = 0;
struct hso_net *hso_net = dev2net(hso_dev);
if (!hso_net)
return -ENODEV;
/* send URBs for all read buffers */
for (i = 0; i < <API key>; i++) {
/* Prep a receive URB */
usb_fill_bulk_urb(hso_net-><API key>[i],
hso_dev->usb,
usb_rcvbulkpipe(hso_dev->usb,
hso_net->in_endp->
bEndpointAddress & 0x7F),
hso_net-><API key>[i],
<API key>, read_bulk_callback,
hso_net);
/* Put it out there so the device can send us stuff */
result = usb_submit_urb(hso_net-><API key>[i],
GFP_NOIO);
if (result)
dev_warn(&hso_dev->usb->dev,
"%s failed mux_bulk_rx_urb[%d] %d\n", __func__,
i, result);
}
return result;
}
static int hso_stop_net_device(struct hso_device *hso_dev)
{
int i;
struct hso_net *hso_net = dev2net(hso_dev);
if (!hso_net)
return -ENODEV;
for (i = 0; i < <API key>; i++) {
if (hso_net-><API key>[i])
usb_kill_urb(hso_net-><API key>[i]);
}
if (hso_net->mux_bulk_tx_urb)
usb_kill_urb(hso_net->mux_bulk_tx_urb);
return 0;
}
static int <API key>(struct hso_device *hso_dev, gfp_t flags)
{
int i, result = 0;
struct hso_serial *serial = dev2ser(hso_dev);
if (!serial)
return -ENODEV;
/* If it is not the MUX port fill in and submit a bulk urb (already
* allocated in hso_serial_start) */
if (!(serial->parent->port_spec & HSO_INTF_MUX)) {
for (i = 0; i < serial->num_rx_urbs; i++) {
usb_fill_bulk_urb(serial->rx_urb[i],
serial->parent->usb,
usb_rcvbulkpipe(serial->parent->usb,
serial->in_endp->
bEndpointAddress &
0x7F),
serial->rx_data[i],
serial->rx_data_length,
<API key>,
serial);
result = usb_submit_urb(serial->rx_urb[i], flags);
if (result) {
dev_warn(&serial->parent->usb->dev,
"Failed to submit urb - res %d\n",
result);
break;
}
}
} else {
mutex_lock(&serial->shared_int->shared_int_lock);
if (!serial->shared_int->use_count) {
result =
<API key>(serial->shared_int,
hso_dev->usb, flags);
}
serial->shared_int->use_count++;
mutex_unlock(&serial->shared_int->shared_int_lock);
}
if (serial->tiocmget)
tiocmget_submit_urb(serial,
serial->tiocmget,
serial->parent->usb);
return result;
}
static int <API key>(struct hso_device *hso_dev)
{
int i;
struct hso_serial *serial = dev2ser(hso_dev);
struct hso_tiocmget *tiocmget;
if (!serial)
return -ENODEV;
for (i = 0; i < serial->num_rx_urbs; i++) {
if (serial->rx_urb[i]) {
usb_kill_urb(serial->rx_urb[i]);
serial->rx_urb_filled[i] = 0;
}
}
serial->curr_rx_urb_idx = 0;
if (serial->tx_urb)
usb_kill_urb(serial->tx_urb);
if (serial->shared_int) {
mutex_lock(&serial->shared_int->shared_int_lock);
if (serial->shared_int->use_count &&
(--serial->shared_int->use_count == 0)) {
struct urb *urb;
urb = serial->shared_int->shared_intr_urb;
if (urb)
usb_kill_urb(urb);
}
mutex_unlock(&serial->shared_int->shared_int_lock);
}
tiocmget = serial->tiocmget;
if (tiocmget) {
<API key>(&tiocmget->waitq);
usb_kill_urb(tiocmget->urb);
}
return 0;
}
static void <API key>(struct hso_serial *serial)
{
int i;
if (serial->parent->dev)
device_remove_file(serial->parent->dev, &dev_attr_hsotype);
<API key>(tty_drv, serial->minor);
for (i = 0; i < serial->num_rx_urbs; i++) {
/* unlink and free RX URB */
usb_free_urb(serial->rx_urb[i]);
/* free the RX buffer */
kfree(serial->rx_data[i]);
}
/* unlink and free TX URB */
usb_free_urb(serial->tx_urb);
kfree(serial->tx_data);
tty_port_destroy(&serial->port);
}
static int <API key>(struct hso_serial *serial, int num_urbs,
int rx_size, int tx_size)
{
struct device *dev;
int minor;
int i;
tty_port_init(&serial->port);
minor = <API key>();
if (minor < 0)
goto exit;
/* register our minor number */
serial->parent->dev = <API key>(&serial->port, tty_drv,
minor, &serial->parent->interface->dev);
dev = serial->parent->dev;
dev_set_drvdata(dev, serial->parent);
i = device_create_file(dev, &dev_attr_hsotype);
/* fill in specific data for later use */
serial->minor = minor;
serial->magic = HSO_SERIAL_MAGIC;
spin_lock_init(&serial->serial_lock);
serial->num_rx_urbs = num_urbs;
/* RX, allocate urb and initialize */
/* prepare our RX buffer */
serial->rx_data_length = rx_size;
for (i = 0; i < serial->num_rx_urbs; i++) {
serial->rx_urb[i] = usb_alloc_urb(0, GFP_KERNEL);
if (!serial->rx_urb[i]) {
dev_err(dev, "Could not allocate urb?\n");
goto exit;
}
serial->rx_urb[i]->transfer_buffer = NULL;
serial->rx_urb[i]-><API key> = 0;
serial->rx_data[i] = kzalloc(serial->rx_data_length,
GFP_KERNEL);
if (!serial->rx_data[i])
goto exit;
}
/* TX, allocate urb and initialize */
serial->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!serial->tx_urb) {
dev_err(dev, "Could not allocate urb?\n");
goto exit;
}
serial->tx_urb->transfer_buffer = NULL;
serial->tx_urb-><API key> = 0;
/* prepare our TX buffer */
serial->tx_data_count = 0;
serial->tx_buffer_count = 0;
serial->tx_data_length = tx_size;
serial->tx_data = kzalloc(serial->tx_data_length, GFP_KERNEL);
if (!serial->tx_data)
goto exit;
serial->tx_buffer = kzalloc(serial->tx_data_length, GFP_KERNEL);
if (!serial->tx_buffer)
goto exit;
return 0;
exit:
<API key>(serial);
return -1;
}
/* Creates a general hso device */
static struct hso_device *hso_create_device(struct usb_interface *intf,
int port_spec)
{
struct hso_device *hso_dev;
hso_dev = kzalloc(sizeof(*hso_dev), GFP_ATOMIC);
if (!hso_dev)
return NULL;
hso_dev->port_spec = port_spec;
hso_dev->usb = interface_to_usbdev(intf);
hso_dev->interface = intf;
kref_init(&hso_dev->ref);
mutex_init(&hso_dev->mutex);
INIT_WORK(&hso_dev->async_get_intf, async_get_intf);
INIT_WORK(&hso_dev->async_put_intf, async_put_intf);
INIT_WORK(&hso_dev->reset_device, reset_device);
return hso_dev;
}
/* Removes a network device in the network device table */
static int remove_net_device(struct hso_device *hso_dev)
{
int i;
for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
if (network_table[i] == hso_dev) {
network_table[i] = NULL;
break;
}
}
if (i == HSO_MAX_NET_DEVICES)
return -1;
return 0;
}
/* Frees our network device */
static void hso_free_net_device(struct hso_device *hso_dev)
{
int i;
struct hso_net *hso_net = dev2net(hso_dev);
if (!hso_net)
return;
remove_net_device(hso_net->parent);
if (hso_net->net)
unregister_netdev(hso_net->net);
/* start freeing */
for (i = 0; i < <API key>; i++) {
usb_free_urb(hso_net-><API key>[i]);
kfree(hso_net-><API key>[i]);
hso_net-><API key>[i] = NULL;
}
usb_free_urb(hso_net->mux_bulk_tx_urb);
kfree(hso_net->mux_bulk_tx_buf);
hso_net->mux_bulk_tx_buf = NULL;
if (hso_net->net)
free_netdev(hso_net->net);
kfree(hso_dev);
}
static const struct net_device_ops hso_netdev_ops = {
.ndo_open = hso_net_open,
.ndo_stop = hso_net_close,
.ndo_start_xmit = hso_net_start_xmit,
.ndo_tx_timeout = hso_net_tx_timeout,
};
/* initialize the network interface */
static void hso_net_init(struct net_device *net)
{
struct hso_net *hso_net = netdev_priv(net);
D1("sizeof hso_net is %d", (int)sizeof(*hso_net));
/* fill in the other fields */
net->netdev_ops = &hso_netdev_ops;
net->watchdog_timeo = HSO_NET_TX_TIMEOUT;
net->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
net->type = ARPHRD_NONE;
net->mtu = DEFAULT_MTU - 14;
net->tx_queue_len = 10;
net->ethtool_ops = &ops;
/* and initialize the semaphore */
spin_lock_init(&hso_net->net_lock);
}
/* Adds a network device in the network device table */
static int add_net_device(struct hso_device *hso_dev)
{
int i;
for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
if (network_table[i] == NULL) {
network_table[i] = hso_dev;
break;
}
}
if (i == HSO_MAX_NET_DEVICES)
return -1;
return 0;
}
static int <API key>(void *data, bool blocked)
{
struct hso_device *hso_dev = data;
int enabled = !blocked;
int rv;
mutex_lock(&hso_dev->mutex);
if (hso_dev->usb_gone)
rv = 0;
else
rv = usb_control_msg(hso_dev->usb, usb_rcvctrlpipe(hso_dev->usb, 0),
enabled ? 0x82 : 0x81, 0x40, 0, 0, NULL, 0,
<API key>);
mutex_unlock(&hso_dev->mutex);
return rv;
}
static const struct rfkill_ops hso_rfkill_ops = {
.set_block = <API key>,
};
/* Creates and sets up everything for rfkill */
static void hso_create_rfkill(struct hso_device *hso_dev,
struct usb_interface *interface)
{
struct hso_net *hso_net = dev2net(hso_dev);
struct device *dev = &hso_net->net->dev;
char *rfkn;
rfkn = kzalloc(20, GFP_KERNEL);
if (!rfkn)
dev_err(dev, "%s - Out of memory\n", __func__);
snprintf(rfkn, 20, "hso-%d",
interface->altsetting->desc.bInterfaceNumber);
hso_net->rfkill = rfkill_alloc(rfkn,
&interface_to_usbdev(interface)->dev,
RFKILL_TYPE_WWAN,
&hso_rfkill_ops, hso_dev);
if (!hso_net->rfkill) {
dev_err(dev, "%s - Out of memory\n", __func__);
kfree(rfkn);
return;
}
if (rfkill_register(hso_net->rfkill) < 0) {
rfkill_destroy(hso_net->rfkill);
kfree(rfkn);
hso_net->rfkill = NULL;
dev_err(dev, "%s - Failed to register rfkill\n", __func__);
return;
}
}
static struct device_type hso_type = {
.name = "wwan",
};
/* Creates our network device */
static struct hso_device *<API key>(struct usb_interface *interface,
int port_spec)
{
int result, i;
struct net_device *net;
struct hso_net *hso_net;
struct hso_device *hso_dev;
hso_dev = hso_create_device(interface, port_spec);
if (!hso_dev)
return NULL;
/* allocate our network device, then we can put in our private data */
/* call hso_net_init to do the basic initialization */
net = alloc_netdev(sizeof(struct hso_net), "hso%d", NET_NAME_UNKNOWN,
hso_net_init);
if (!net) {
dev_err(&interface->dev, "Unable to create ethernet device\n");
goto exit;
}
hso_net = netdev_priv(net);
hso_dev->port_data.dev_net = hso_net;
hso_net->net = net;
hso_net->parent = hso_dev;
hso_net->in_endp = hso_get_ep(interface, <API key>,
USB_DIR_IN);
if (!hso_net->in_endp) {
dev_err(&interface->dev, "Can't find BULK IN endpoint\n");
goto exit;
}
hso_net->out_endp = hso_get_ep(interface, <API key>,
USB_DIR_OUT);
if (!hso_net->out_endp) {
dev_err(&interface->dev, "Can't find BULK OUT endpoint\n");
goto exit;
}
SET_NETDEV_DEV(net, &interface->dev);
SET_NETDEV_DEVTYPE(net, &hso_type);
/* registering our net device */
result = register_netdev(net);
if (result) {
dev_err(&interface->dev, "Failed to register device\n");
goto exit;
}
/* start allocating */
for (i = 0; i < <API key>; i++) {
hso_net-><API key>[i] = usb_alloc_urb(0, GFP_KERNEL);
if (!hso_net-><API key>[i]) {
dev_err(&interface->dev, "Could not allocate rx urb\n");
goto exit;
}
hso_net-><API key>[i] = kzalloc(<API key>,
GFP_KERNEL);
if (!hso_net-><API key>[i])
goto exit;
}
hso_net->mux_bulk_tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!hso_net->mux_bulk_tx_urb) {
dev_err(&interface->dev, "Could not allocate tx urb\n");
goto exit;
}
hso_net->mux_bulk_tx_buf = kzalloc(<API key>, GFP_KERNEL);
if (!hso_net->mux_bulk_tx_buf)
goto exit;
add_net_device(hso_dev);
hso_log_port(hso_dev);
hso_create_rfkill(hso_dev, interface);
return hso_dev;
exit:
hso_free_net_device(hso_dev);
return NULL;
}
static void hso_free_tiomget(struct hso_serial *serial)
{
struct hso_tiocmget *tiocmget;
if (!serial)
return;
tiocmget = serial->tiocmget;
if (tiocmget) {
usb_free_urb(tiocmget->urb);
tiocmget->urb = NULL;
serial->tiocmget = NULL;
kfree(tiocmget);
}
}
/* Frees an AT channel ( goes for both mux and non-mux ) */
static void <API key>(struct hso_device *hso_dev)
{
struct hso_serial *serial = dev2ser(hso_dev);
if (!serial)
return;
set_serial_by_index(serial->minor, NULL);
<API key>(serial);
if (serial->shared_int) {
mutex_lock(&serial->shared_int->shared_int_lock);
if (--serial->shared_int->ref_count == 0)
hso_free_shared_int(serial->shared_int);
else
mutex_unlock(&serial->shared_int->shared_int_lock);
}
hso_free_tiomget(serial);
kfree(serial);
kfree(hso_dev);
}
/* Creates a bulk AT channel */
static struct hso_device *<API key>(
struct usb_interface *interface, int port)
{
struct hso_device *hso_dev;
struct hso_serial *serial;
int num_urbs;
struct hso_tiocmget *tiocmget;
hso_dev = hso_create_device(interface, port);
if (!hso_dev)
return NULL;
serial = kzalloc(sizeof(*serial), GFP_KERNEL);
if (!serial)
goto exit;
serial->parent = hso_dev;
hso_dev->port_data.dev_serial = serial;
if ((port & HSO_PORT_MASK) == HSO_PORT_MODEM) {
num_urbs = 2;
serial->tiocmget = kzalloc(sizeof(struct hso_tiocmget),
GFP_KERNEL);
/* it isn't going to break our heart if serial->tiocmget
* allocation fails don't bother checking this.
*/
if (serial->tiocmget) {
tiocmget = serial->tiocmget;
tiocmget->urb = usb_alloc_urb(0, GFP_KERNEL);
if (tiocmget->urb) {
mutex_init(&tiocmget->mutex);
init_waitqueue_head(&tiocmget->waitq);
tiocmget->endp = hso_get_ep(
interface,
<API key>,
USB_DIR_IN);
} else
hso_free_tiomget(serial);
}
}
else
num_urbs = 1;
if (<API key>(serial, num_urbs, BULK_URB_RX_SIZE,
BULK_URB_TX_SIZE))
goto exit;
serial->in_endp = hso_get_ep(interface, <API key>,
USB_DIR_IN);
if (!serial->in_endp) {
dev_err(&interface->dev, "Failed to find BULK IN ep\n");
goto exit2;
}
if (!
(serial->out_endp =
hso_get_ep(interface, <API key>, USB_DIR_OUT))) {
dev_err(&interface->dev, "Failed to find BULK IN ep\n");
goto exit2;
}
serial->write_data = <API key>;
/* and record this serial */
set_serial_by_index(serial->minor, serial);
/* setup the proc dirs and files if needed */
hso_log_port(hso_dev);
/* done, return it */
return hso_dev;
exit2:
<API key>(serial);
exit:
hso_free_tiomget(serial);
kfree(serial);
kfree(hso_dev);
return NULL;
}
/* Creates a multiplexed AT channel */
static
struct hso_device *<API key>(struct usb_interface *interface,
int port,
struct hso_shared_int *mux)
{
struct hso_device *hso_dev;
struct hso_serial *serial;
int port_spec;
port_spec = HSO_INTF_MUX;
port_spec &= ~HSO_PORT_MASK;
port_spec |= hso_mux_to_port(port);
if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NO_PORT)
return NULL;
hso_dev = hso_create_device(interface, port_spec);
if (!hso_dev)
return NULL;
serial = kzalloc(sizeof(*serial), GFP_KERNEL);
if (!serial)
goto exit;
hso_dev->port_data.dev_serial = serial;
serial->parent = hso_dev;
if (<API key>
(serial, 1, CTRL_URB_RX_SIZE, CTRL_URB_TX_SIZE))
goto exit;
serial->tx_data_length
serial->write_data = <API key>;
serial->shared_int = mux;
mutex_lock(&serial->shared_int->shared_int_lock);
serial->shared_int->ref_count++;
mutex_unlock(&serial->shared_int->shared_int_lock);
/* and record this serial */
set_serial_by_index(serial->minor, serial);
/* setup the proc dirs and files if needed */
hso_log_port(hso_dev);
/* done, return it */
return hso_dev;
exit:
if (serial) {
<API key>(tty_drv, serial->minor);
kfree(serial);
}
kfree(hso_dev);
return NULL;
}
static void hso_free_shared_int(struct hso_shared_int *mux)
{
usb_free_urb(mux->shared_intr_urb);
kfree(mux->shared_intr_buf);
mutex_unlock(&mux->shared_int_lock);
kfree(mux);
}
static
struct hso_shared_int *<API key>(struct usb_interface *interface)
{
struct hso_shared_int *mux = kzalloc(sizeof(*mux), GFP_KERNEL);
if (!mux)
return NULL;
mux->intr_endp = hso_get_ep(interface, <API key>,
USB_DIR_IN);
if (!mux->intr_endp) {
dev_err(&interface->dev, "Can't find INT IN endpoint\n");
goto exit;
}
mux->shared_intr_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!mux->shared_intr_urb) {
dev_err(&interface->dev, "Could not allocate intr urb?\n");
goto exit;
}
mux->shared_intr_buf =
kzalloc(le16_to_cpu(mux->intr_endp->wMaxPacketSize),
GFP_KERNEL);
if (!mux->shared_intr_buf)
goto exit;
mutex_init(&mux->shared_int_lock);
return mux;
exit:
kfree(mux->shared_intr_buf);
usb_free_urb(mux->shared_intr_urb);
kfree(mux);
return NULL;
}
/* Gets the port spec for a certain interface */
static int hso_get_config_data(struct usb_interface *interface)
{
struct usb_device *usbdev = interface_to_usbdev(interface);
u8 *config_data = kmalloc(17, GFP_KERNEL);
u32 if_num = interface->altsetting->desc.bInterfaceNumber;
s32 result;
if (!config_data)
return -ENOMEM;
if (usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
0x86, 0xC0, 0, 0, config_data, 17,
<API key>) != 0x11) {
kfree(config_data);
return -EIO;
}
switch (config_data[if_num]) {
case 0x0:
result = 0;
break;
case 0x1:
result = HSO_PORT_DIAG;
break;
case 0x2:
result = HSO_PORT_GPS;
break;
case 0x3:
result = <API key>;
break;
case 0x4:
result = HSO_PORT_APP;
break;
case 0x5:
result = HSO_PORT_APP2;
break;
case 0x6:
result = HSO_PORT_CONTROL;
break;
case 0x7:
result = HSO_PORT_NETWORK;
break;
case 0x8:
result = HSO_PORT_MODEM;
break;
case 0x9:
result = HSO_PORT_MSD;
break;
case 0xa:
result = HSO_PORT_PCSC;
break;
case 0xb:
result = HSO_PORT_VOICE;
break;
default:
result = 0;
}
if (result)
result |= HSO_INTF_BULK;
if (config_data[16] & 0x1)
result |= HSO_INFO_CRC_BUG;
kfree(config_data);
return result;
}
/* called once for each interface upon device insertion */
static int hso_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
int mux, i, if_num, port_spec;
unsigned char port_mask;
struct hso_device *hso_dev = NULL;
struct hso_shared_int *shared_int;
struct hso_device *tmp_dev = NULL;
if (interface->cur_altsetting->desc.bInterfaceClass != 0xFF) {
dev_err(&interface->dev, "Not our interface\n");
return -ENODEV;
}
if_num = interface->altsetting->desc.bInterfaceNumber;
/* Get the interface/port specification from either driver_info or from
* the device itself */
if (id->driver_info)
port_spec = ((u32 *)(id->driver_info))[if_num];
else
port_spec = hso_get_config_data(interface);
/* Check if we need to switch to alt interfaces prior to port
* configuration */
if (interface->num_altsetting > 1)
usb_set_interface(interface_to_usbdev(interface), if_num, 1);
interface->needs_remote_wakeup = 1;
/* Allocate new hso device(s) */
switch (port_spec & HSO_INTF_MASK) {
case HSO_INTF_MUX:
if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {
/* Create the network device */
if (!disable_net) {
hso_dev = <API key>(interface,
port_spec);
if (!hso_dev)
goto exit;
tmp_dev = hso_dev;
}
}
if (hso_get_mux_ports(interface, &port_mask))
/* TODO: de-allocate everything */
goto exit;
shared_int = <API key>(interface);
if (!shared_int)
goto exit;
for (i = 1, mux = 0; i < 0x100; i = i << 1, mux++) {
if (port_mask & i) {
hso_dev = <API key>(
interface, i, shared_int);
if (!hso_dev)
goto exit;
}
}
if (tmp_dev)
hso_dev = tmp_dev;
break;
case HSO_INTF_BULK:
/* It's a regular bulk interface */
if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {
if (!disable_net)
hso_dev =
<API key>(interface, port_spec);
} else {
hso_dev =
<API key>(interface, port_spec);
}
if (!hso_dev)
goto exit;
break;
default:
goto exit;
}
/* save our data pointer in this device */
usb_set_intfdata(interface, hso_dev);
/* done */
return 0;
exit:
hso_free_interface(interface);
return -ENODEV;
}
/* device removed, cleaning up */
static void hso_disconnect(struct usb_interface *interface)
{
hso_free_interface(interface);
/* remove reference of our private data */
usb_set_intfdata(interface, NULL);
}
static void async_get_intf(struct work_struct *data)
{
struct hso_device *hso_dev =
container_of(data, struct hso_device, async_get_intf);
<API key>(hso_dev->interface);
}
static void async_put_intf(struct work_struct *data)
{
struct hso_device *hso_dev =
container_of(data, struct hso_device, async_put_intf);
<API key>(hso_dev->interface);
}
static int hso_get_activity(struct hso_device *hso_dev)
{
if (hso_dev->usb->state == USB_STATE_SUSPENDED) {
if (!hso_dev->is_active) {
hso_dev->is_active = 1;
schedule_work(&hso_dev->async_get_intf);
}
}
if (hso_dev->usb->state != <API key>)
return -EAGAIN;
usb_mark_last_busy(hso_dev->usb);
return 0;
}
static int hso_put_activity(struct hso_device *hso_dev)
{
if (hso_dev->usb->state != USB_STATE_SUSPENDED) {
if (hso_dev->is_active) {
hso_dev->is_active = 0;
schedule_work(&hso_dev->async_put_intf);
return -EAGAIN;
}
}
hso_dev->is_active = 0;
return 0;
}
/* called by kernel when we need to suspend device */
static int hso_suspend(struct usb_interface *iface, pm_message_t message)
{
int i, result;
/* Stop all serial ports */
for (i = 0; i < <API key>; i++) {
if (serial_table[i] && (serial_table[i]->interface == iface)) {
result = <API key>(serial_table[i]);
if (result)
goto out;
}
}
/* Stop all network ports */
for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
if (network_table[i] &&
(network_table[i]->interface == iface)) {
result = hso_stop_net_device(network_table[i]);
if (result)
goto out;
}
}
out:
return 0;
}
/* called by kernel when we need to resume device */
static int hso_resume(struct usb_interface *iface)
{
int i, result = 0;
struct hso_net *hso_net;
/* Start all serial ports */
for (i = 0; i < <API key>; i++) {
if (serial_table[i] && (serial_table[i]->interface == iface)) {
if (dev2ser(serial_table[i])->port.count) {
result =
<API key>(serial_table[i], GFP_NOIO);
hso_kick_transmit(dev2ser(serial_table[i]));
if (result)
goto out;
}
}
}
/* Start all network ports */
for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
if (network_table[i] &&
(network_table[i]->interface == iface)) {
hso_net = dev2net(network_table[i]);
if (hso_net->flags & IFF_UP) {
/* First transmit any lingering data,
then restart the device. */
if (hso_net->skb_tx_buf) {
dev_dbg(&iface->dev,
"Transmitting"
" lingering data\n");
hso_net_start_xmit(hso_net->skb_tx_buf,
hso_net->net);
hso_net->skb_tx_buf = NULL;
}
result = <API key>(network_table[i]);
if (result)
goto out;
}
}
}
out:
return result;
}
static void reset_device(struct work_struct *data)
{
struct hso_device *hso_dev =
container_of(data, struct hso_device, reset_device);
struct usb_device *usb = hso_dev->usb;
int result;
if (hso_dev->usb_gone) {
D1("No reset during disconnect\n");
} else {
result = <API key>(usb, hso_dev->interface);
if (result < 0)
D1("unable to lock device for reset: %d\n", result);
else {
usb_reset_device(usb);
usb_unlock_device(usb);
}
}
}
static void hso_serial_ref_free(struct kref *ref)
{
struct hso_device *hso_dev = container_of(ref, struct hso_device, ref);
<API key>(hso_dev);
}
static void hso_free_interface(struct usb_interface *interface)
{
struct hso_serial *hso_dev;
int i;
for (i = 0; i < <API key>; i++) {
if (serial_table[i] &&
(serial_table[i]->interface == interface)) {
hso_dev = dev2ser(serial_table[i]);
tty_port_tty_hangup(&hso_dev->port, false);
mutex_lock(&hso_dev->parent->mutex);
hso_dev->parent->usb_gone = 1;
mutex_unlock(&hso_dev->parent->mutex);
kref_put(&serial_table[i]->ref, hso_serial_ref_free);
}
}
for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
if (network_table[i] &&
(network_table[i]->interface == interface)) {
struct rfkill *rfk = dev2net(network_table[i])->rfkill;
/* hso_stop_net_device doesn't stop the net queue since
* traffic needs to start it again when suspended */
netif_stop_queue(dev2net(network_table[i])->net);
hso_stop_net_device(network_table[i]);
cancel_work_sync(&network_table[i]->async_put_intf);
cancel_work_sync(&network_table[i]->async_get_intf);
if (rfk) {
rfkill_unregister(rfk);
rfkill_destroy(rfk);
}
hso_free_net_device(network_table[i]);
}
}
}
/* Helper functions */
/* Get the endpoint ! */
static struct <API key> *hso_get_ep(struct usb_interface *intf,
int type, int dir)
{
int i;
struct usb_host_interface *iface = intf->cur_altsetting;
struct <API key> *endp;
for (i = 0; i < iface->desc.bNumEndpoints; i++) {
endp = &iface->endpoint[i].desc;
if (((endp->bEndpointAddress & <API key>) == dir) &&
(usb_endpoint_type(endp) == type))
return endp;
}
return NULL;
}
/* Get the byte that describes which ports are enabled */
static int hso_get_mux_ports(struct usb_interface *intf, unsigned char *ports)
{
int i;
struct usb_host_interface *iface = intf->cur_altsetting;
if (iface->extralen == 3) {
*ports = iface->extra[2];
return 0;
}
for (i = 0; i < iface->desc.bNumEndpoints; i++) {
if (iface->endpoint[i].extralen == 3) {
*ports = iface->endpoint[i].extra[2];
return 0;
}
}
return -1;
}
/* interrupt urb needs to be submitted, used for serial read of muxed port */
static int <API key>(struct hso_shared_int *shared_int,
struct usb_device *usb, gfp_t gfp)
{
int result;
usb_fill_int_urb(shared_int->shared_intr_urb, usb,
usb_rcvintpipe(usb,
shared_int->intr_endp->bEndpointAddress & 0x7F),
shared_int->shared_intr_buf,
1,
intr_callback, shared_int,
shared_int->intr_endp->bInterval);
result = usb_submit_urb(shared_int->shared_intr_urb, gfp);
if (result)
dev_warn(&usb->dev, "%s failed mux_intr_urb %d\n", __func__,
result);
return result;
}
/* operations setup of the serial interface */
static const struct tty_operations hso_serial_ops = {
.open = hso_serial_open,
.close = hso_serial_close,
.write = hso_serial_write,
.write_room = <API key>,
.ioctl = hso_serial_ioctl,
.set_termios = <API key>,
.chars_in_buffer = <API key>,
.tiocmget = hso_serial_tiocmget,
.tiocmset = hso_serial_tiocmset,
.get_icount = hso_get_count,
.unthrottle = hso_unthrottle
};
static struct usb_driver hso_driver = {
.name = driver_name,
.probe = hso_probe,
.disconnect = hso_disconnect,
.id_table = hso_ids,
.suspend = hso_suspend,
.resume = hso_resume,
.reset_resume = hso_resume,
.<API key> = 1,
.<API key> = 1,
};
static int __init hso_init(void)
{
int i;
int result;
/* put it in the log */
printk(KERN_INFO "hso: %s\n", version);
/* Initialise the serial table semaphore and table */
spin_lock_init(&serial_table_lock);
for (i = 0; i < <API key>; i++)
serial_table[i] = NULL;
/* allocate our driver using the proper amount of supported minors */
tty_drv = alloc_tty_driver(<API key>);
if (!tty_drv)
return -ENOMEM;
/* fill in all needed values */
tty_drv->driver_name = driver_name;
tty_drv->name = tty_filename;
/* if major number is provided as parameter, use that one */
if (tty_major)
tty_drv->major = tty_major;
tty_drv->minor_start = 0;
tty_drv->type = <API key>;
tty_drv->subtype = SERIAL_TYPE_NORMAL;
tty_drv->flags = TTY_DRIVER_REAL_RAW | <API key>;
tty_drv->init_termios = tty_std_termios;
hso_init_termios(&tty_drv->init_termios);
tty_set_operations(tty_drv, &hso_serial_ops);
/* register the tty driver */
result = tty_register_driver(tty_drv);
if (result) {
printk(KERN_ERR "%s - tty_register_driver failed(%d)\n",
__func__, result);
goto err_free_tty;
}
/* register this module as an usb driver */
result = usb_register(&hso_driver);
if (result) {
printk(KERN_ERR "Could not register hso driver? error: %d\n",
result);
goto err_unreg_tty;
}
/* done */
return 0;
err_unreg_tty:
<API key>(tty_drv);
err_free_tty:
put_tty_driver(tty_drv);
return result;
}
static void __exit hso_exit(void)
{
printk(KERN_INFO "hso: unloaded\n");
<API key>(tty_drv);
put_tty_driver(tty_drv);
/* deregister the usb driver */
usb_deregister(&hso_driver);
}
/* Module definitions */
module_init(hso_init);
module_exit(hso_exit);
MODULE_AUTHOR(MOD_AUTHOR);
MODULE_DESCRIPTION(MOD_DESCRIPTION);
MODULE_LICENSE(MOD_LICENSE);
/* change the debug level (eg: insmod hso.ko debug=0x04) */
MODULE_PARM_DESC(debug, "Level of debug [0x01 | 0x02 | 0x04 | 0x08 | 0x10]");
module_param(debug, int, S_IRUGO | S_IWUSR);
/* set the major tty number (eg: insmod hso.ko tty_major=245) */
MODULE_PARM_DESC(tty_major, "Set the major tty number");
module_param(tty_major, int, S_IRUGO | S_IWUSR);
/* disable network interface (eg: insmod hso.ko disable_net=1) */
MODULE_PARM_DESC(disable_net, "Disable the network interface");
module_param(disable_net, int, S_IRUGO | S_IWUSR); |
#ifndef <API key>
#define <API key>
#include <boost/fusion/support/detail/index_sequence.hpp>
namespace boost { namespace phoenix { namespace detail {
using ::boost::fusion::detail::index_sequence;
using ::boost::fusion::detail::make_index_sequence;
}}}
#endif |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
EXAMPLES = '''
- name: allow inbound port 80/tcp from 1.2.3.4 added to security group 'default'
local_action:
module: <API key>
security_group: default
port: 80
cidr: 1.2.3.4/32
- name: allow tcp/udp outbound added to security group 'default'
local_action:
module: <API key>
security_group: default
type: egress
start_port: 1
end_port: 65535
protocol: '{{ item }}'
with_items:
- tcp
- udp
- name: allow inbound icmp from 0.0.0.0/0 added to security group 'default'
local_action:
module: <API key>
security_group: default
protocol: icmp
icmp_code: -1
icmp_type: -1
- name: remove rule inbound port 80/tcp from 0.0.0.0/0 from security group 'default'
local_action:
module: <API key>
security_group: default
port: 80
state: absent
- name: allow inbound port 80/tcp from security group web added to security group 'default'
local_action:
module: <API key>
security_group: default
port: 80
user_security_group: web
'''
RETURN = '''
id:
description: UUID of the of the rule.
returned: success
type: string
sample: <API key>
security_group:
description: security group of the rule.
returned: success
type: string
sample: default
type:
description: type of the rule.
returned: success
type: string
sample: ingress
cidr:
description: CIDR of the rule.
returned: success and cidr is defined
type: string
sample: 0.0.0.0/0
user_security_group:
description: user security group of the rule.
returned: success and user_security_group is defined
type: string
sample: default
protocol:
description: protocol of the rule.
returned: success
type: string
sample: tcp
start_port:
description: start port of the rule.
returned: success
type: int
sample: 80
end_port:
description: end port of the rule.
returned: success
type: int
sample: 80
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import AnsibleCloudStack, cs_argument_spec, <API key>
class <API key>(AnsibleCloudStack):
def __init__(self, module):
super(<API key>, self).__init__(module)
self.returns = {
'icmptype': 'icmp_type',
'icmpcode': 'icmp_code',
'endport': 'end_port',
'startport': 'start_port',
'protocol': 'protocol',
'cidr': 'cidr',
'securitygroupname': 'user_security_group',
}
def _tcp_udp_match(self, rule, protocol, start_port, end_port):
return (protocol in ['tcp', 'udp'] and
protocol == rule['protocol'] and
start_port == int(rule['startport']) and
end_port == int(rule['endport']))
def _icmp_match(self, rule, protocol, icmp_code, icmp_type):
return (protocol == 'icmp' and
protocol == rule['protocol'] and
icmp_code == int(rule['icmpcode']) and
icmp_type == int(rule['icmptype']))
def _ah_esp_gre_match(self, rule, protocol):
return (protocol in ['ah', 'esp', 'gre'] and
protocol == rule['protocol'])
def <API key>(self, rule, security_group_name):
return (security_group_name and
'securitygroupname' in rule and
security_group_name == rule['securitygroupname'])
def _type_cidr_match(self, rule, cidr):
return ('cidr' in rule and
cidr == rule['cidr'])
def _get_rule(self, rules):
<API key> = self.module.params.get('user_security_group')
cidr = self.module.params.get('cidr')
protocol = self.module.params.get('protocol')
start_port = self.module.params.get('start_port')
end_port = self.get_or_fallback('end_port', 'start_port')
icmp_code = self.module.params.get('icmp_code')
icmp_type = self.module.params.get('icmp_type')
if protocol in ['tcp', 'udp'] and (start_port is None or end_port is None):
self.module.fail_json(msg="no start_port or end_port set for protocol '%s'" % protocol)
if protocol == 'icmp' and (icmp_type is None or icmp_code is None):
self.module.fail_json(msg="no icmp_type or icmp_code set for protocol '%s'" % protocol)
for rule in rules:
if <API key>:
type_match = self.<API key>(rule, <API key>)
else:
type_match = self._type_cidr_match(rule, cidr)
protocol_match = (self._tcp_udp_match(rule, protocol, start_port, end_port) or
self._icmp_match(rule, protocol, icmp_code, icmp_type) or
self._ah_esp_gre_match(rule, protocol))
if type_match and protocol_match:
return rule
return None
def get_security_group(self, security_group_name=None):
if not security_group_name:
security_group_name = self.module.params.get('security_group')
args = {
'securitygroupname': security_group_name,
'projectid': self.get_project('id'),
}
sgs = self.query_api('listSecurityGroups', **args)
if not sgs or 'securitygroup' not in sgs:
self.module.fail_json(msg="security group '%s' not found" % security_group_name)
return sgs['securitygroup'][0]
def add_rule(self):
security_group = self.get_security_group()
args = {}
<API key> = self.module.params.get('user_security_group')
# the user_security_group and cidr are mutually_exclusive, but cidr is defaulted to 0.0.0.0/0.
# that is why we ignore if we have a user_security_group.
if <API key>:
args['<API key>'] = []
user_security_group = self.get_security_group(<API key>)
args['<API key>'].append({
'group': user_security_group['name'],
'account': user_security_group['account'],
})
else:
args['cidrlist'] = self.module.params.get('cidr')
args['protocol'] = self.module.params.get('protocol')
args['startport'] = self.module.params.get('start_port')
args['endport'] = self.get_or_fallback('end_port', 'start_port')
args['icmptype'] = self.module.params.get('icmp_type')
args['icmpcode'] = self.module.params.get('icmp_code')
args['projectid'] = self.get_project('id')
args['securitygroupid'] = security_group['id']
rule = None
res = None
sg_type = self.module.params.get('type')
if sg_type == 'ingress':
if 'ingressrule' in security_group:
rule = self._get_rule(security_group['ingressrule'])
if not rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.query_api('<API key>, **args)
elif sg_type == 'egress':
if 'egressrule' in security_group:
rule = self._get_rule(security_group['egressrule'])
if not rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.query_api('<API key>, **args)
poll_async = self.module.params.get('poll_async')
if res and poll_async:
security_group = self.poll_job(res, 'securitygroup')
key = sg_type + "rule" # ingressrule / egressrule
if key in security_group:
rule = security_group[key][0]
return rule
def remove_rule(self):
security_group = self.get_security_group()
rule = None
res = None
sg_type = self.module.params.get('type')
if sg_type == 'ingress':
rule = self._get_rule(security_group['ingressrule'])
if rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.query_api('<API key>', id=rule['ruleid'])
elif sg_type == 'egress':
rule = self._get_rule(security_group['egressrule'])
if rule:
self.result['changed'] = True
if not self.module.check_mode:
res = self.query_api('<API key>', id=rule['ruleid'])
poll_async = self.module.params.get('poll_async')
if res and poll_async:
res = self.poll_job(res, 'securitygroup')
return rule
def get_result(self, security_group_rule):
super(<API key>, self).get_result(security_group_rule)
self.result['type'] = self.module.params.get('type')
self.result['security_group'] = self.module.params.get('security_group')
return self.result
def main():
argument_spec = cs_argument_spec()
argument_spec.update(dict(
security_group=dict(required=True),
type=dict(choices=['ingress', 'egress'], default='ingress'),
cidr=dict(default='0.0.0.0/0'),
user_security_group=dict(),
protocol=dict(choices=['tcp', 'udp', 'icmp', 'ah', 'esp', 'gre'], default='tcp'),
icmp_type=dict(type='int'),
icmp_code=dict(type='int'),
start_port=dict(type='int', aliases=['port']),
end_port=dict(type='int'),
state=dict(choices=['present', 'absent'], default='present'),
project=dict(),
poll_async=dict(type='bool', default=True),
))
required_together = <API key>()
required_together.extend([
['icmp_type', 'icmp_code'],
])
module = AnsibleModule(
argument_spec=argument_spec,
required_together=required_together,
mutually_exclusive=(
['icmp_type', 'start_port'],
['icmp_type', 'end_port'],
['icmp_code', 'start_port'],
['icmp_code', 'end_port'],
),
supports_check_mode=True
)
acs_sg_rule = <API key>(module)
state = module.params.get('state')
if state in ['absent']:
sg_rule = acs_sg_rule.remove_rule()
else:
sg_rule = acs_sg_rule.add_rule()
result = acs_sg_rule.get_result(sg_rule)
module.exit_json(**result)
if __name__ == '__main__':
main() |
var win = Ti.UI.currentWindow;
// initialize to all modes
win.orientationModes = [
Titanium.UI.PORTRAIT,
Titanium.UI.LANDSCAPE_LEFT,
Titanium.UI.LANDSCAPE_RIGHT
];
Titanium.Media.openPhotoGallery({
allowEditing:true,
success: function(event)
{
var emailDialog = Titanium.UI.createEmailDialog();
if (!emailDialog.isSupported()) {
Ti.UI.createAlertDialog({
title:'Error',
message:'Email not available'
}).show();
return;
}
emailDialog.setSubject('Hello from Titanium!');
emailDialog.setToRecipients(['foo@yahoo.com']);
emailDialog.setCcRecipients(['bar@yahoo.com']);
emailDialog.setBccRecipients(['blah@yahoo.com']);
if (Ti.Platform.name == 'iPhone OS') {
emailDialog.setMessageBody('<b>Appcelerator Titanium Rocks!</b>å');
emailDialog.setHtml(true);
emailDialog.setBarColor('#336699');
} else {
emailDialog.setMessageBody('Appcelerator Titanium Rocks!');
}
// attach a blob
emailDialog.addAttachment(event.media);
// attach a file
var f = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'cricket.wav');
emailDialog.addAttachment(f);
emailDialog.addEventListener('complete',function(e)
{
if (e.result == emailDialog.SENT)
{
if (Ti.Platform.osname != 'android') {
// android doesn't give us useful result codes.
// it anyway shows a toast.
alert("message was sent");
}
}
else
{
alert("message was not sent. result = " + e.result);
}
});
emailDialog.open();
},
error: function(error)
{
},
cancel: function()
{
}
}); |
// Protocol Buffers - Google's data interchange format
// modification, are permitted provided that the following conditions are
// met:
// 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
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/stubs/int128.h>
#include <iomanip>
#include <ostream> // NOLINT(readability/streams)
#include <sstream>
namespace google {
namespace protobuf {
const uint128_pod kuint128max = {
static_cast<uint64>(GOOGLE_LONGLONG(0xFFFFFFFFFFFFFFFF)),
static_cast<uint64>(GOOGLE_LONGLONG(0xFFFFFFFFFFFFFFFF))
};
// Returns the 0-based position of the last set bit (i.e., most significant bit)
// in the given uint64. The argument may not be 0.
// For example:
// Given: 5 (decimal) == 101 (binary)
// Returns: 2
#define STEP(T, n, pos, sh) \
do { \
if ((n) >= (static_cast<T>(1) << (sh))) { \
(n) = (n) >> (sh); \
(pos) |= (sh); \
} \
} while (0)
static inline int Fls64(uint64 n) {
GOOGLE_DCHECK_NE(0, n);
int pos = 0;
STEP(uint64, n, pos, 0x20);
uint32 n32 = n;
STEP(uint32, n32, pos, 0x10);
STEP(uint32, n32, pos, 0x08);
STEP(uint32, n32, pos, 0x04);
return pos + ((GOOGLE_ULONGLONG(0x3333333322221100) >> (n32 << 2)) & 0x3);
}
#undef STEP
// Like Fls64() above, but returns the 0-based position of the last set bit
// (i.e., most significant bit) in the given uint128. The argument may not be 0.
static inline int Fls128(uint128 n) {
if (uint64 hi = Uint128High64(n)) {
return Fls64(hi) + 64;
}
return Fls64(Uint128Low64(n));
}
// Long division/modulo for uint128 implemented using the shift-subtract
// division algorithm adapted from:
void uint128::DivModImpl(uint128 dividend, uint128 divisor,
uint128* quotient_ret, uint128* remainder_ret) {
if (divisor == 0) {
GOOGLE_LOG(FATAL) << "Division or mod by zero: dividend.hi=" << dividend.hi_
<< ", lo=" << dividend.lo_;
}
if (divisor > dividend) {
*quotient_ret = 0;
*remainder_ret = dividend;
return;
}
if (divisor == dividend) {
*quotient_ret = 1;
*remainder_ret = 0;
return;
}
uint128 denominator = divisor;
uint128 position = 1;
uint128 quotient = 0;
// Left aligns the MSB of the denominator and the dividend.
int shift = Fls128(dividend) - Fls128(denominator);
denominator <<= shift;
position <<= shift;
// Uses shift-subtract algorithm to divide dividend by denominator. The
// remainder will be left in dividend.
while (position > 0) {
if (dividend >= denominator) {
dividend -= denominator;
quotient |= position;
}
position >>= 1;
denominator >>= 1;
}
*quotient_ret = quotient;
*remainder_ret = dividend;
}
uint128& uint128::operator/=(const uint128& divisor) {
uint128 quotient = 0;
uint128 remainder = 0;
DivModImpl(*this, divisor, "ient, &remainder);
*this = quotient;
return *this;
}
uint128& uint128::operator%=(const uint128& divisor) {
uint128 quotient = 0;
uint128 remainder = 0;
DivModImpl(*this, divisor, "ient, &remainder);
*this = remainder;
return *this;
}
std::ostream& operator<<(std::ostream& o, const uint128& b) {
std::ios_base::fmtflags flags = o.flags();
// Select a divisor which is the largest power of the base < 2^64.
uint128 div;
std::streamsize div_base_log;
switch (flags & std::ios::basefield) {
case std::ios::hex:
div = static_cast<uint64>(GOOGLE_ULONGLONG(0x1000000000000000)); // 16^15
div_base_log = 15;
break;
case std::ios::oct:
div = static_cast<uint64>(GOOGLE_ULONGLONG(<API key>)); // 8^21
div_base_log = 21;
break;
default: // std::ios::dec
div = static_cast<uint64>(GOOGLE_ULONGLONG(<API key>)); // 10^19
div_base_log = 19;
break;
}
// Now piece together the uint128 representation from three chunks of
// the original value, each less than "div" and therefore representable
// as a uint64.
std::ostringstream os;
std::ios_base::fmtflags copy_mask =
std::ios::basefield | std::ios::showbase | std::ios::uppercase;
os.setf(flags & copy_mask, copy_mask);
uint128 high = b;
uint128 low;
uint128::DivModImpl(high, div, &high, &low);
uint128 mid;
uint128::DivModImpl(high, div, &high, &mid);
if (high.lo_ != 0) {
os << high.lo_;
os << std::noshowbase << std::setfill('0') << std::setw(div_base_log);
os << mid.lo_;
os << std::setw(div_base_log);
} else if (mid.lo_ != 0) {
os << mid.lo_;
os << std::noshowbase << std::setfill('0') << std::setw(div_base_log);
}
os << low.lo_;
std::string rep = os.str();
// Add the requisite padding.
std::streamsize width = o.width(0);
if (width > rep.size()) {
if ((flags & std::ios::adjustfield) == std::ios::left) {
rep.append(width - rep.size(), o.fill());
} else {
rep.insert(static_cast<std::string::size_type>(0),
width - rep.size(), o.fill());
}
}
// Stream the final representation in a single "<<" call.
return o << rep;
}
} // namespace protobuf
} // namespace google |
#include "webkit/browser/quota/<API key>.h"
namespace quota {
<API key>::Observer::~Observer() {}
<API key>::<API key>() {}
<API key>::~<API key>() {}
void <API key>::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void <API key>::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void <API key>::NotifyGranted(const GURL& origin, int change_flags) {
scoped_refptr<<API key>> protect(this);
FOR_EACH_OBSERVER(Observer, observers_, OnGranted(origin, change_flags));
}
void <API key>::NotifyRevoked(const GURL& origin, int change_flags) {
scoped_refptr<<API key>> protect(this);
FOR_EACH_OBSERVER(Observer, observers_, OnRevoked(origin, change_flags));
}
void <API key>::NotifyCleared() {
scoped_refptr<<API key>> protect(this);
FOR_EACH_OBSERVER(Observer, observers_, OnCleared());
}
} // namespace quota |
/* <API key>: GPL-2.0 */
#ifndef NFSCACHE_H
#define NFSCACHE_H
#include <linux/sunrpc/svc.h>
/*
* Representation of a reply cache entry.
*
* Note that we use a sockaddr_in6 to hold the address instead of the more
* typical sockaddr_storage. This is for space reasons, since sockaddr_storage
* is much larger than a sockaddr_in6.
*/
struct svc_cacherep {
struct {
/* Keep often-read xid, csum in the same cache line: */
__be32 k_xid;
__wsum k_csum;
u32 k_proc;
u32 k_prot;
u32 k_vers;
unsigned int k_len;
struct sockaddr_in6 k_addr;
} c_key;
struct rb_node c_node;
struct list_head c_lru;
unsigned char c_state, /* unused, inprog, done */
c_type, /* status, buffer */
c_secure : 1; /* req came from port < 1024 */
unsigned long c_timestamp;
union {
struct kvec u_vec;
__be32 u_status;
} c_u;
};
#define c_replvec c_u.u_vec
#define c_replstat c_u.u_status
/* cache entry states */
enum {
RC_UNUSED,
RC_INPROG,
RC_DONE
};
/* return values */
enum {
RC_DROPIT,
RC_REPLY,
RC_DOIT
};
/*
* Cache types.
* We may want to add more types one day, e.g. for diropres and
* attrstat replies. Using cache entries with fixed length instead
* of buffer pointers may be more efficient.
*/
enum {
RC_NOCACHE,
RC_REPLSTAT,
RC_REPLBUFF,
};
/* Cache entries expire after this time period */
#define RC_EXPIRE (120 * HZ)
/* Checksum this amount of the request */
#define RC_CSUMLEN (256U)
int <API key>(void);
void <API key>(void);
int nfsd_cache_lookup(struct svc_rqst *);
void nfsd_cache_update(struct svc_rqst *, int, __be32 *);
int <API key>(struct inode *, struct file *);
#endif /* NFSCACHE_H */ |
<p>Esta pàgina l'ajudarà en la primera instalació i configuració de <a href="http:
<a href="http:
<p>DokuWiki utilisa archius corrents per a l'almagasenament de les pàgines del wiki i atra informació associada ad estes pàgines (p. e. imàgens, índexs de busca, versions antigues, etc.). Per a que DokuWiki funcione correctament
<strong>deu</strong> tindre accés d'escritura als directoris que contenen estos archius. Est instalador no pot ajustar els permissos del directori. Normalment haurà de fer-ho directament en una consola de del sistema o, si utilisa un hostage, per FTP o en el panel de control (p. e. cPanel).</p>
<p>Est instalador configurarà <abbr title="access control list">ACL</abbr> en el seu DokuWiki, que al mateix temps permet l'accés de l'administrador i l'accés al menú d'administració de DokuWiki per a instalar plúgins, gestionar usuaris, gestionar els accessos a les pàgines del wiki i la modificació dels ajusts de configuració. No és necessari per a que DokuWiki funcione, pero farà més fàcil la seua administració.</p>
<p>Els usuaris experimentats o en necessitats especials de configuració deuen utilisar estos vínculs per a informació referent a
<a href="http:
i <a href="http: |
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/leds-gpio.h>
/* our context */
struct s3c24xx_gpio_led {
struct led_classdev cdev;
struct <API key> *pdata;
};
static inline struct s3c24xx_gpio_led *pdev_to_gpio(struct platform_device *dev)
{
return <API key>(dev);
}
static inline struct s3c24xx_gpio_led *to_gpio(struct led_classdev *led_cdev)
{
return container_of(led_cdev, struct s3c24xx_gpio_led, cdev);
}
static void s3c24xx_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct s3c24xx_gpio_led *led = to_gpio(led_cdev);
struct <API key> *pd = led->pdata;
/* there will be a short delay between setting the output and
* going from output to input when using tristate. */
s3c2410_gpio_setpin(pd->gpio, (value ? 1 : 0) ^
(pd->flags & S3C24XX_LEDF_ACTLOW));
if (pd->flags & <API key>)
s3c2410_gpio_cfgpin(pd->gpio,
value ? S3C2410_GPIO_OUTPUT : S3C2410_GPIO_INPUT);
}
static int s3c24xx_led_remove(struct platform_device *dev)
{
struct s3c24xx_gpio_led *led = pdev_to_gpio(dev);
<API key>(&led->cdev);
kfree(led);
return 0;
}
static int s3c24xx_led_probe(struct platform_device *dev)
{
struct <API key> *pdata = dev->dev.platform_data;
struct s3c24xx_gpio_led *led;
int ret;
led = kzalloc(sizeof(struct s3c24xx_gpio_led), GFP_KERNEL);
if (led == NULL) {
dev_err(&dev->dev, "No memory for device\n");
return -ENOMEM;
}
<API key>(dev, led);
led->cdev.brightness_set = s3c24xx_led_set;
led->cdev.default_trigger = pdata->def_trigger;
led->cdev.name = pdata->name;
led->cdev.flags |= <API key>;
led->pdata = pdata;
/* no point in having a pull-up if we are always driving */
if (pdata->flags & <API key>) {
s3c2410_gpio_setpin(pdata->gpio, 0);
s3c2410_gpio_cfgpin(pdata->gpio, S3C2410_GPIO_INPUT);
} else {
s3c2410_gpio_pullup(pdata->gpio, 0);
s3c2410_gpio_setpin(pdata->gpio, 0);
s3c2410_gpio_cfgpin(pdata->gpio, S3C2410_GPIO_OUTPUT);
}
/* register our new led device */
ret = <API key>(&dev->dev, &led->cdev);
if (ret < 0) {
dev_err(&dev->dev, "<API key> failed\n");
kfree(led);
return ret;
}
return 0;
}
static struct platform_driver s3c24xx_led_driver = {
.probe = s3c24xx_led_probe,
.remove = s3c24xx_led_remove,
.driver = {
.name = "s3c24xx_led",
.owner = THIS_MODULE,
},
};
static int __init s3c24xx_led_init(void)
{
return <API key>(&s3c24xx_led_driver);
}
static void __exit s3c24xx_led_exit(void)
{
<API key>(&s3c24xx_led_driver);
}
module_init(s3c24xx_led_init);
module_exit(s3c24xx_led_exit);
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("S3C24XX LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:s3c24xx_led"); |
// generic/detail/endpoint.hpp
#ifndef <API key>
#define <API key>
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <cstddef>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace generic {
namespace detail {
// Helper class for implementing a generic socket endpoint.
class endpoint
{
public:
// Default constructor.
BOOST_ASIO_DECL endpoint();
// Construct an endpoint from the specified raw bytes.
BOOST_ASIO_DECL endpoint(const void* sock_addr,
std::size_t sock_addr_size, int sock_protocol);
// Copy constructor.
endpoint(const endpoint& other)
: data_(other.data_),
size_(other.size_),
protocol_(other.protocol_)
{
}
// Assign from another endpoint.
endpoint& operator=(const endpoint& other)
{
data_ = other.data_;
size_ = other.size_;
protocol_ = other.protocol_;
return *this;
}
// Get the address family associated with the endpoint.
int family() const
{
return data_.base.sa_family;
}
// Get the socket protocol associated with the endpoint.
int protocol() const
{
return protocol_;
}
// Get the underlying endpoint in the native type.
boost::asio::detail::socket_addr_type* data()
{
return &data_.base;
}
// Get the underlying endpoint in the native type.
const boost::asio::detail::socket_addr_type* data() const
{
return &data_.base;
}
// Get the underlying size of the endpoint in the native type.
std::size_t size() const
{
return size_;
}
// Set the underlying size of the endpoint in the native type.
BOOST_ASIO_DECL void resize(std::size_t size);
// Get the capacity of the endpoint in the native type.
std::size_t capacity() const
{
return sizeof(boost::asio::detail::<API key>);
}
// Compare two endpoints for equality.
BOOST_ASIO_DECL friend bool operator==(
const endpoint& e1, const endpoint& e2);
// Compare endpoints for ordering.
BOOST_ASIO_DECL friend bool operator<(
const endpoint& e1, const endpoint& e2);
private:
// The underlying socket address.
union data_union
{
boost::asio::detail::socket_addr_type base;
boost::asio::detail::<API key> generic;
} data_;
// The length of the socket address stored in the endpoint.
std::size_t size_;
// The socket protocol associated with the endpoint.
int protocol_;
// Initialise with a specified memory.
BOOST_ASIO_DECL void init(const void* sock_addr,
std::size_t sock_addr_size, int sock_protocol);
};
} // namespace detail
} // namespace generic
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#if defined(<API key>)
# include <boost/asio/generic/detail/impl/endpoint.ipp>
#endif // defined(<API key>)
#endif // <API key> |
// Type definitions for through
<reference path="../node/node.d.ts" />
declare module "through" {
import Stream = require("stream");
function through(write?: (data) => void,
end?: () => void,
opts?: {
autoDestroy: boolean;
}): through.ThroughStream;
module through {
export interface ThroughStream extends Stream.ReadWriteStream {
autoDestroy: boolean;
}
}
export = through;
} |
<?php
namespace Psy\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Clear the Psy Shell.
*
* Just what it says on the tin.
*/
class ClearCommand extends Command
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('clear')
->setDefinition(array())
->setDescription('Clear the Psy Shell screen.')
->setHelp(
HELP
Clear the Psy Shell screen.
Pro Tip: If your PHP has readline support, you should be able to use ctrl+l too!
HELP
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->write(sprintf('%c[2J%c[0;0f', 27, 27));
}
} |
#ifndef __TCA642X_H_
#define __TCA642X_H_
#ifdef CONFIG_CMD_TCA642X
enum {
TCA642X_CMD_INFO,
TCA642X_CMD_DEVICE,
TCA642X_CMD_OUTPUT,
TCA642X_CMD_INPUT,
TCA642X_CMD_INVERT,
};
#endif
#define TCA642X_OUT_LOW 0
#define TCA642X_OUT_HIGH 1
#define TCA642X_POL_NORMAL 0
#define TCA642X_POL_INVERT 1
#define TCA642X_DIR_OUT 0
#define TCA642X_DIR_IN 1
/* Default to an address that hopefully won't corrupt other i2c devices */
#ifndef <API key>
#define <API key> (~0)
#endif
/* Default to an address that hopefully won't corrupt other i2c devices */
#ifndef <API key>
#define <API key> (0)
#endif
struct tca642x_bank_info {
uint8_t input_reg;
uint8_t output_reg;
uint8_t polarity_reg;
uint8_t configuration_reg;
};
int tca642x_set_val(uchar chip, uint8_t gpio_bank,
uint8_t reg_bit, uint8_t data);
int tca642x_set_pol(uchar chip, uint8_t gpio_bank,
uint8_t reg_bit, uint8_t data);
int tca642x_set_dir(uchar chip, uint8_t gpio_bank,
uint8_t reg_bit, uint8_t data);
int tca642x_get_val(uchar chip, uint8_t gpio_bank);
int <API key>(uchar chip, struct tca642x_bank_info init_data[]);
#endif /* __TCA642X_H_ */ |
cask 'jxplorer' do
version '3.3.1.2'
sha256 '<SHA256-like>'
# sourceforge.net/jxplorer was verified as official when first introduced to the cask
url "https://downloads.sourceforge.net/jxplorer/jxplorer/version%20#{version}/jxplorer-#{version}-osx.zip"
appcast 'https://sourceforge.net/projects/jxplorer/rss?path=/jxplorer',
checkpoint: '<SHA256-like>'
name 'JXplorer'
homepage 'http://jxplorer.org/'
app "jxplorer-#{version}.app"
postflight do
set_permissions "#{appdir}/jxplorer-#{version}.app/Contents/MacOS/jxplorer", 'a+x'
end
end |
#ifndef <API key>
#define <API key>
#include <linux/bitops.h>
/* Coresight management registers (0xF00-0xFCC)
* 0xFA0 - 0xFA4: Management registers in PFTv1.0
* Trace registers in PFTv1.1
*/
#define CS_ITCTRL (0xF00)
#define CS_CLAIMSET (0xFA0)
#define CS_CLAIMCLR (0xFA4)
#define CS_LAR (0xFB0)
#define CS_LSR (0xFB4)
#define CS_AUTHSTATUS (0xFB8)
#define CS_DEVID (0xFC8)
#define CS_DEVTYPE (0xFCC)
/* Peripheral id registers (0xFD0-0xFEC) */
#define CS_PIDR4 (0xFD0)
#define CS_PIDR5 (0xFD4)
#define CS_PIDR6 (0xFD8)
#define CS_PIDR7 (0xFDC)
#define CS_PIDR0 (0xFE0)
#define CS_PIDR1 (0xFE4)
#define CS_PIDR2 (0xFE8)
#define CS_PIDR3 (0xFEC)
/* Component id registers (0xFF0-0xFFC) */
#define CS_CIDR0 (0xFF0)
#define CS_CIDR1 (0xFF4)
#define CS_CIDR2 (0xFF8)
#define CS_CIDR3 (0xFFC)
/* DBGv7 with baseline CP14 registers implemented */
#define ARM_DEBUG_ARCH_V7B (0x3)
/* DBGv7 with all CP14 registers implemented */
#define ARM_DEBUG_ARCH_V7 (0x4)
#define ARM_DEBUG_ARCH_V7_1 (0x5)
#define ETM_ARCH_V3_3 (0x23)
#define PFT_ARCH_V1_1 (0x31)
#define TIMEOUT_US (100)
#define OSLOCK_MAGIC (0xC5ACCE55)
#define CS_UNLOCK_MAGIC (0xC5ACCE55)
#define BM(lsb, msb) ((BIT(msb) - BIT(lsb)) + BIT(msb))
#define BMVAL(val, lsb, msb) ((val & BM(lsb, msb)) >> lsb)
#define BVAL(val, n) ((val & BIT(n)) >> n)
int etb_init(void);
void etb_exit(void);
int tpiu_init(void);
void tpiu_exit(void);
int funnel_init(void);
void funnel_exit(void);
int etm_init(void);
void etm_exit(void);
void etb_enable(void);
void etb_disable(void);
void etb_dump(void);
void tpiu_disable(void);
void funnel_enable(uint8_t id, uint32_t port_mask);
void funnel_disable(uint8_t id, uint32_t port_mask);
struct kobject *qdss_get_modulekobj(void);
int qdss_clk_enable(void);
void qdss_clk_disable(void);
#ifdef CONFIG_MSM_JTAG
extern void msm_jtag_save_state(void);
extern void <API key>(void);
#else
static inline void msm_jtag_save_state(void) {}
static inline void <API key>(void) {}
#endif
#endif |
#! /usr/bin/env python
# encoding: utf-8
import os
all_modifs={}
def fixdir(dir):
global all_modifs
for k in all_modifs:
for v in all_modifs[k]:
modif(os.path.join(dir,'waflib'),k,v)
def modif(dir,name,fun):
if name=='*':
lst=[]
for y in'. Tools extras'.split():
for x in os.listdir(os.path.join(dir,y)):
if x.endswith('.py'):
lst.append(y+os.sep+x)
for x in lst:
modif(dir,x,fun)
return
filename=os.path.join(dir,name)
f=open(filename,'r')
try:
txt=f.read()
finally:
f.close()
txt=fun(txt)
f=open(filename,'w')
try:
f.write(txt)
finally:
f.close()
def subst(*k):
def do_subst(fun):
global all_modifs
for x in k:
try:
all_modifs[x].append(fun)
except KeyError:
all_modifs[x]=[fun]
return fun
return do_subst
@subst('*')
def r1(code):
code=code.replace(',e:',',e:')
code=code.replace("",'')
code=code.replace('','')
return code
@subst('Runner.py')
def r4(code):
code=code.replace('next(self.biter)','self.biter.next()')
return code |
/**
* @module echarts/model/Model
*/
define(function (require) {
var zrUtil = require('zrender/core/util');
var clazzUtil = require('../util/clazz');
/**
* @alias module:echarts/model/Model
* @constructor
* @param {Object} option
* @param {module:echarts/model/Model} parentModel
* @param {module:echarts/model/Global} ecModel
* @param {Object} extraOpt
*/
function Model(option, parentModel, ecModel, extraOpt) {
/**
* @type {module:echarts/model/Model}
* @readOnly
*/
this.parentModel = parentModel;
/**
* @type {module:echarts/model/Global}
* @readOnly
*/
this.ecModel = ecModel;
/**
* @type {Object}
* @protected
*/
this.option = option;
// Simple optimization
if (this.init) {
if (arguments.length <= 4) {
this.init(option, parentModel, ecModel, extraOpt);
}
else {
this.init.apply(this, arguments);
}
}
}
Model.prototype = {
constructor: Model,
/**
* Model
* @param {Object} option
*/
init: null,
/**
* Option merge
*/
mergeOption: function (option) {
zrUtil.merge(this.option, option, true);
},
/**
* @param {string} path
* @param {boolean} [ignoreParent=false]
* @return {*}
*/
get: function (path, ignoreParent) {
if (!path) {
return this.option;
}
if (typeof path === 'string') {
path = path.split('.');
}
var obj = this.option;
var parentModel = this.parentModel;
for (var i = 0; i < path.length; i++) {
// obj could be number/string/... (like 0)
obj = (obj && typeof obj === 'object') ? obj[path[i]] : null;
if (obj == null) {
break;
}
}
if (obj == null && parentModel && !ignoreParent) {
obj = parentModel.get(path);
}
return obj;
},
/**
* @param {string} key
* @param {boolean} [ignoreParent=false]
* @return {*}
*/
getShallow: function (key, ignoreParent) {
var option = this.option;
var val = option && option[key];
var parentModel = this.parentModel;
if (val == null && parentModel && !ignoreParent) {
val = parentModel.getShallow(key);
}
return val;
},
/**
* @param {string} path
* @param {module:echarts/model/Model} [parentModel]
* @return {module:echarts/model/Model}
*/
getModel: function (path, parentModel) {
var obj = this.get(path, true);
var thisParentModel = this.parentModel;
var model = new Model(
obj, parentModel || (thisParentModel && thisParentModel.getModel(path)),
this.ecModel
);
return model;
},
/**
* If model has option
*/
isEmpty: function () {
return this.option == null;
},
restoreData: function () {},
// Pending
clone: function () {
var Ctor = this.constructor;
return new Ctor(zrUtil.clone(this.option));
},
setReadOnly: function (properties) {
clazzUtil.setReadOnly(this, properties);
}
};
// Enable Model.extend.
clazzUtil.enableClassExtend(Model);
var mixin = zrUtil.mixin;
mixin(Model, require('./mixin/lineStyle'));
mixin(Model, require('./mixin/areaStyle'));
mixin(Model, require('./mixin/textStyle'));
mixin(Model, require('./mixin/itemStyle'));
return Model;
}); |
<?php
/**
* @see <API key>
*/
require_once 'Zend/Gdata/App/Extension/Element.php';
class <API key> extends <API key>
{
/**
* Namespace for Google Base elements
*
* var @string
*/
protected $_rootNamespace = 'g';
/**
* Create a new instance.
*
* @param string $name (optional) The name of the Base attribute
* @param string $text (optional) The text value of the Base attribute
* @param string $text (optional) The type of the Base attribute
*/
public function __construct($name = null, $text = null, $type = null)
{
$this-><API key>(Zend_Gdata_Gbase::$namespaces);
if ($type !== null) {
$attr = array('name' => 'type', 'value' => $type);
$typeAttr = array('type' => $attr);
$this-><API key>($typeAttr);
}
parent::__construct($name,
$this->_rootNamespace,
$this->lookupNamespace($this->_rootNamespace),
$text);
}
/**
* Get the name of the attribute
*
* @return attribute name The requested object.
*/
public function getName() {
return $this->_rootElement;
}
/**
* Get the type of the attribute
*
* @return attribute type The requested object.
*/
public function getType() {
$typeAttr = $this-><API key>();
return $typeAttr['type']['value'];
}
/**
* Set the 'name' of the Base attribute object:
* <g:[$name] type='[$type]'>[$value]</g:[$name]>
*
* @param <API key> $attribute The attribute object
* @param string $name The name of the Base attribute
* @return <API key> Provides a fluent interface
*/
public function setName($name) {
$this->_rootElement = $name;
return $this;
}
/**
* Set the 'type' of the Base attribute object:
* <g:[$name] type='[$type]'>[$value]</g:[$name]>
*
* @param <API key> $attribute The attribute object
* @param string $type The type of the Base attribute
* @return <API key> Provides a fluent interface
*/
public function setType($type) {
$attr = array('name' => 'type', 'value' => $type);
$typeAttr = array('type' => $attr);
$this-><API key>($typeAttr);
return $this;
}
} |
#!/usr/bin/python
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
- name: add sending authorization policy to domain identity
<API key>:
identity: example.com
policy_name: ExamplePolicy
policy: "{{ lookup('template', 'policy.json.j2') }}"
state: present
- name: add sending authorization policy to email identity
<API key>:
identity: example@example.com
policy_name: ExamplePolicy
policy: "{{ lookup('template', 'policy.json.j2') }}"
state: present
- name: add sending authorization policy to identity using ARN
<API key>:
identity: "arn:aws:ses:us-east-1:12345678:identity/example.com"
policy_name: ExamplePolicy
policy: "{{ lookup('template', 'policy.json.j2') }}"
state: present
- name: remove sending authorization policy
<API key>:
identity: example.com
policy_name: ExamplePolicy
state: absent
'''
RETURN = '''
policies:
description: A list of all policies present on the identity after the operation.
returned: success
type: list
sample: [ExamplePolicy]
'''
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import compare_policies, AWSRetry
import json
try:
from botocore.exceptions import BotoCoreError, ClientError
except ImportError:
pass # caught by imported HAS_BOTO3
def get_identity_policy(connection, module, identity, policy_name):
try:
response = connection.<API key>(Identity=identity, PolicyNames=[policy_name], aws_retry=True)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg='Failed to retrieve identity policy {policy}'.format(policy=policy_name))
policies = response['Policies']
if policy_name in policies:
return policies[policy_name]
return None
def <API key>(connection, module):
identity = module.params.get('identity')
policy_name = module.params.get('policy_name')
required_policy = module.params.get('policy')
<API key> = json.loads(required_policy)
changed = False
policy = get_identity_policy(connection, module, identity, policy_name)
policy_dict = json.loads(policy) if policy else None
if compare_policies(policy_dict, <API key>):
changed = True
try:
if not module.check_mode:
connection.put_identity_policy(Identity=identity, PolicyName=policy_name, Policy=required_policy, aws_retry=True)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg='Failed to put identity policy {policy}'.format(policy=policy_name))
# Load the list of applied policies to include in the response.
# In principle we should be able to just return the response, but given
# eventual consistency behaviours in AWS it's plausible that we could
# end up with a list that doesn't contain the policy we just added.
# So out of paranoia check for this case and if we're missing the policy
# just make sure it's present.
# As a nice side benefit this also means the return is correct in check mode
try:
policies_present = connection.<API key>(Identity=identity, aws_retry=True)['PolicyNames']
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg='Failed to list identity policies')
if policy_name is not None and policy_name not in policies_present:
policies_present = list(policies_present)
policies_present.append(policy_name)
module.exit_json(
changed=changed,
policies=policies_present,
)
def <API key>(connection, module):
identity = module.params.get('identity')
policy_name = module.params.get('policy_name')
changed = False
try:
policies_present = connection.<API key>(Identity=identity, aws_retry=True)['PolicyNames']
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg='Failed to list identity policies')
if policy_name in policies_present:
try:
if not module.check_mode:
connection.<API key>(Identity=identity, PolicyName=policy_name, aws_retry=True)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e, msg='Failed to delete identity policy {policy}'.format(policy=policy_name))
changed = True
policies_present = list(policies_present)
policies_present.remove(policy_name)
module.exit_json(
changed=changed,
policies=policies_present,
)
def main():
module = AnsibleAWSModule(
argument_spec={
'identity': dict(required=True, type='str'),
'state': dict(default='present', choices=['present', 'absent']),
'policy_name': dict(required=True, type='str'),
'policy': dict(type='json', default=None),
},
required_if=[['state', 'present', ['policy']]],
supports_check_mode=True,
)
# SES APIs seem to have a much lower throttling threshold than most of the rest of the AWS APIs.
# Docs say 1 call per second. This shouldn't actually be a big problem for normal usage, but
# the ansible build runs multiple instances of the test in parallel that's caused throttling
# failures so apply a jittered backoff to call SES calls.
connection = module.client('ses', retry_decorator=AWSRetry.jittered_backoff())
state = module.params.get("state")
if state == 'present':
<API key>(connection, module)
else:
<API key>(connection, module)
if __name__ == '__main__':
main() |
package com.subgraph.orchid.circuits.hs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import com.subgraph.orchid.DirectoryCircuit;
import com.subgraph.orchid.InternalCircuit;
import com.subgraph.orchid.OpenFailedException;
import com.subgraph.orchid.Router;
import com.subgraph.orchid.Stream;
import com.subgraph.orchid.<API key>;
import com.subgraph.orchid.TorException;
import com.subgraph.orchid.circuits.CircuitManagerImpl;
import com.subgraph.orchid.directory.<API key>;
import com.subgraph.orchid.directory.downloader.<API key>;
import com.subgraph.orchid.directory.downloader.HttpConnection;
import com.subgraph.orchid.directory.parsing.<API key>;
public class <API key> {
private final static Logger logger = Logger.getLogger(<API key>.class.getName());
private final HiddenService hiddenService;
private final CircuitManagerImpl circuitManager;
private final List<<API key>> directories;
public <API key>(HiddenService hiddenService, CircuitManagerImpl circuitManager, List<<API key>> directories) {
this.hiddenService = hiddenService;
this.circuitManager = circuitManager;
this.directories = directories;
}
public HSDescriptor downloadDescriptor() {
for(<API key> d: directories) {
HSDescriptor descriptor = <API key>(d);
if(descriptor != null) {
return descriptor;
}
}
// All directories failed
return null;
}
private HSDescriptor <API key>(<API key> dd) {
logger.fine("Downloading descriptor from "+ dd.getDirectory());
Stream stream = null;
try {
stream = <API key>(dd.getDirectory());
HttpConnection http = new HttpConnection(stream);
http.sendGetRequest("/tor/rendezvous2/"+ dd.getDescriptorId().toBase32());
http.readResponse();
if(http.getStatusCode() == 200) {
return readDocument(dd, http.getMessageBody());
} else {
logger.fine("HS descriptor download for "+ hiddenService.<API key>() + " failed with status "+ http.getStatusCode());
}
} catch (<API key> e) {
Thread.currentThread().interrupt();
return null;
} catch (TimeoutException e) {
logger.fine("Timeout downloading HS descriptor from "+ dd.getDirectory());
e.printStackTrace();
return null;
} catch (IOException e) {
logger.info("IOException downloading HS descriptor from "+ dd.getDirectory() +" : "+ e);
return null;
} catch (OpenFailedException e) {
logger.info("Failed to open stream to HS directory "+ dd.getDirectory() +" : "+ e.getMessage());
return null;
} catch (<API key> e) {
logger.info("Directory request to HS directory "+ dd.getDirectory() + " failed "+ e.getMessage());
return null;
} finally {
if(stream != null) {
stream.close();
stream.getCircuit().markForClose();
}
}
return null;
}
private Stream <API key>(Router directory) throws TimeoutException, <API key>, OpenFailedException {
final InternalCircuit circuit = circuitManager.<API key>();
try {
final DirectoryCircuit dc = circuit.<API key>(directory);
return dc.openDirectoryStream(10000, true);
} catch (<API key> e) {
circuit.markForClose();
throw new OpenFailedException("Failed to open directory stream");
} catch (TorException e) {
circuit.markForClose();
throw new OpenFailedException("Failed to extend circuit to HS directory: "+ e.getMessage());
}
}
private HSDescriptor readDocument(<API key> dd, ByteBuffer body) {
<API key> fieldParser = new <API key>(body);
HSDescriptorParser parser = new HSDescriptorParser(hiddenService, fieldParser, hiddenService.get<API key>());
<API key> result = new <API key>(dd);
parser.parse(result);
return result.getDescriptor();
}
private static class <API key> implements <API key><HSDescriptor> {
<API key> dd;
HSDescriptor descriptor;
public <API key>(<API key> dd) {
this.dd = dd;
}
HSDescriptor getDescriptor() {
return descriptor;
}
public void documentParsed(HSDescriptor document) {
this.descriptor = document;
}
public void documentInvalid(HSDescriptor document, String message) {
logger.info("Invalid HS descriptor document received from "+ dd.getDirectory() + " for descriptor "+ dd.getDescriptorId());
}
public void parsingError(String message) {
logger.info("Failed to parse HS descriptor document received from "+ dd.getDirectory() + " for descriptor "+ dd.getDescriptorId() + " : " + message);
}
}
} |
class <API key> < ActiveRecord::Migration
def up
sql = <<-SQL
UPDATE #{ActiveRecord::Base.connection.quote_table_name('agents')}
SET #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::EmailDigestAgent'
WHERE #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::DigestEmailAgent'
SQL
execute sql
end
def down
sql = <<-SQL
UPDATE #{ActiveRecord::Base.connection.quote_table_name('agents')}
SET #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::DigestEmailAgent'
WHERE #{ActiveRecord::Base.connection.quote_column_name('type')} = 'Agents::EmailDigestAgent'
SQL
execute sql
end
end |
<?php
require_once pb_backupbuddy::plugin_path() . '/destinations/dropbox/lib/dropbuddy/pear_includes/HTTP/OAuth/Store/Data.php';
require_once pb_backupbuddy::plugin_path() . '/destinations/dropbox/lib/dropbuddy/pear_includes/HTTP/OAuth/Store/Consumer/Interface.php';
require_once pb_backupbuddy::plugin_path() . '/destinations/dropbox/lib/dropbuddy/pear_includes/Cache/Lite.php';
class HTTP_O<API key>
implements HTTP_O<API key>
{
const TYPE_REQUEST = 'requestTokens';
const TYPE_ACCESS = 'accessTokens';
const <API key> = 300;
/**
* Instance of Cache_Lite
*
* @var Cache_Lite|null
*/
protected $cache = null;
/**
* CacheLite options
*
* @var array
* @see $defaultOptions
*/
protected $options = array();
/**
* Default options for Cache_Lite
*
* @var array
*/
protected $defaultOptions = array(
'cacheDir' => '/tmp',
'lifeTime' => 300,
'<API key>' => 2
);
/**
* Instantiate Cache_Lite. Allows for options to be passed to Cache_Lite.
*
* @param array $options Options for Cache_Lite constructor
*
* @return void
*/
public function __construct(array $options = array())
{
$this->options = array_merge($this->defaultOptions, $options);
$this->cache = new Cache_Lite($this->options);
}
/**
* Sets a request token
*
* @param string $token The request token
* @param string $tokenSecret The request token secret
* @param string $providerName The name of the provider (i.e. 'twitter')
* @param string $sessionID A string representing this user's session
*
* @return true on success, false or PEAR_Error on failure
*/
public function setRequestToken($token, $tokenSecret, $providerName, $sessionID)
{
$this->setOptions(self::TYPE_REQUEST, self::<API key>);
$data = array(
'token' => $token,
'tokenSecret' => $tokenSecret,
'providerName' => $providerName,
'sessionID' => $sessionID
);
return $this->cache->save(
serialize($data),
$this->getRequestTokenKey($providerName, $sessionID)
);
}
/**
* Gets a request token as an array of the token, tokenSecret, providerName,
* and sessionID (array key names)
*
* @param string $providerName The provider name (i.e. 'twitter')
* @param string $sessionID A string representing this user's session
*
* @return array on success, false on failure
*/
public function getRequestToken($providerName, $sessionID)
{
$this->setOptions(self::TYPE_REQUEST, self::<API key>);
$result = $this->cache->get(
$this->getRequestTokenKey($providerName, $sessionID)
);
return unserialize($result);
}
/**
* Gets a cache key for request tokens. It's an md5 hash of the provider name
* and sessionID
*
* @param string $providerName The provider name (i.e. 'twitter')
* @param string $sessionID A string representing this user's session
*
* @return string
*/
protected function getRequestTokenKey($providerName, $sessionID)
{
return md5($providerName . ':' . $sessionID);
}
/**
* Gets access token data in the form of an <API key> object
*
* @param string $consumerUserID The end user's ID at the consumer
* @param string $providerName The provider name (i.e. 'twitter')
*
* @return <API key>
*/
public function getAccessToken($consumerUserID, $providerName)
{
$this->setOptions(self::TYPE_ACCESS);
$result = $this->cache->get(
$this->getAccessTokenKey($consumerUserID, $providerName)
);
return unserialize($result);
}
/**
* Sets access token data from an <API key> object
*
* @param <API key> $data The access token data
*
* @return bool true on success, false or PEAR_Error on failure
*/
public function setAccessToken(<API key> $data)
{
$this->setOptions(self::TYPE_ACCESS);
$key = $this->getAccessTokenKey($data->consumerUserID, $data->providerName);
return $this->cache->save(serialize($data), $key);
}
/**
* Removes an access token
*
* @param <API key> $data The access token data
*
* @return bool true on success, false or PEAR_Error on failure
*/
public function removeAccessToken(<API key> $data)
{
$this->setOptions(self::TYPE_ACCESS);
$key = $this->getAccessTokenKey($data->consumerUserID, $data->providerName);
return $this->cache->remove($key);
}
/**
* Gets an access token key for storage, based on the consumer user ID and the
* provider name
*
* @param string $consumerUserID The end user's ID at the consumer
* @param string $providerName The provider name (i.e. 'twitter')
*
* @return void
*/
protected function getAccessTokenKey($consumerUserID, $providerName)
{
return md5($consumerUserID . ':' . $providerName);
}
/**
* Sets options for Cache_Lite based on the needs of the current method.
* Options set include the subdirectory to be used, and the expiration.
*
* @param string $key The sub-directory of the cacheDir
* @param string $expire The cache lifetime (expire) to be used
*
* @return void
*/
protected function setOptions($key, $expire = null)
{
$cacheDir = $this->options['cacheDir'] . '/oauth/';
$cacheDir .= rtrim($key, '/') . '/';
$this-><API key>($cacheDir);
$this->cache->setOption('cacheDir', $cacheDir);
$this->cache->setOption('lifeTime', $expire);
}
/**
* Make sure the given sub directory exists. If not, create it.
*
* @param string $dir The full path to the sub director we plan to write to
*
* @return void
*/
protected function <API key>($dir)
{
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
}
}
?> |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Parallel;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
[ParallelFixture]
public class <API key> : <API key>
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExpression()
{
VerifyKeyword(AddInsideMethod(
@"var q = $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf()
{
VerifyAbsence(
@"#if $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf_Or()
{
VerifyAbsence(
@"#if a || $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf_And()
{
VerifyAbsence(
@"#if a && $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf_Not()
{
VerifyAbsence(
@"#if ! $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf_Paren()
{
VerifyAbsence(
@"#if ( $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf_Equals()
{
VerifyAbsence(
@"#if a == $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPIf_NotEquals()
{
VerifyAbsence(
@"#if a != $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPElIf()
{
VerifyAbsence(
@"#if true
#elif $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPelIf_Or()
{
VerifyAbsence(
@"#if true
#elif a || $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPElIf_And()
{
VerifyAbsence(
@"#if true
#elif a && $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPElIf_Not()
{
VerifyAbsence(
@"#if true
#elif ! $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPElIf_Paren()
{
VerifyAbsence(
@"#if true
#elif ( $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPPElIf_Equals()
{
VerifyAbsence(
@"#if true
#elif a == $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyAbsence(
@"#if true
#elif a != $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyAbsence(
@"class C {
public static bool operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyAbsence(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyAbsence(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterCastInField()
{
VerifyKeyword(
@"class C {
public static readonly ImmutableList<T> Empty = new ImmutableList<T>((Segment)$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InTernary()
{
VerifyKeyword(AddInsideMethod(
@"SyntaxKind kind = <API key> == $$ ? SyntaxKind.GotoStatement :
<API key>.Kind == SyntaxKind.CaseKeyword ? SyntaxKind.GotoCaseStatement : SyntaxKind.<API key>;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForMiddle()
{
VerifyKeyword(AddInsideMethod(
@"for (int i = 0; $$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInTypeOf()
{
VerifyAbsence(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInDefault()
{
VerifyAbsence(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInSizeOf()
{
VerifyAbsence(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(541670)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InReferenceSwitch()
{
VerifyKeyword(AddInsideMethod(
@"switch (""foo"")
{
case $$
}"));
}
#if false
[WorkItem(8486)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInValueSwitch()
{
VerifyAbsence(AddInsideMethod(
@"switch (0)
{
case $$
}"));
}
#endif
[WorkItem(543766)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyKeyword(
@"class C { void Foo(string[] args = $$");
}
[WorkItem(544219)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCrefContext()
{
VerifyAbsence(@"
class Program
{
<see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955)]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void <API key>()
{
VerifyAbsence(@"
<see cref=""System.$$"" />
class C { }
");
}
}
} |
# <API key>
Compile ES2015 default and rest parameters to ES5
## Installation
sh
$ npm install <API key>
## Usage
Via `.babelrc` (Recommended)
**.babelrc**
json
{
"plugins": ["<API key>"]
}
Via CLI
sh
$ babel --plugins <API key> script.js
Via Node API
javascript
require("babel-core").transform("code", {
plugins: ["<API key>"]
}); |
#include <linux/kernel.h>
#include <asm/mach/arch.h>
#include "board-dt.h"
static const char *msm8940_dt_match[] __initconst = {
"qcom,msm8940",
NULL
};
static void __init msm8940_init(void)
{
board_dt_populate(NULL);
}
DT_MACHINE_START(MSM8940_DT,
"Qualcomm Technologies, Inc. MSM 8940 (Flattened Device Tree)")
.init_machine = msm8940_init,
.dt_compat = msm8940_dt_match,
MACHINE_END |
/* PR debug/49676 */
/* { dg-do run { target lp64 } } */
/* { dg-options "-g -fno-ipa-icf" } */
volatile int v;
__attribute__((noinline, noclone))
unsigned long long
foo (unsigned long long x)
{
unsigned long long a = x * (0x17ULL << 31); /* { dg-final { gdb-test 29 "a" "(0x17ULL << 31)" } } */
unsigned long long b = x * (0x7ULL << 33); /* { dg-final { gdb-test 29 "b" "(0x7ULL << 33)" } } */
unsigned long long c = x * (0x1ULL << 35); /* { dg-final { gdb-test 29 "c" "(0x1ULL << 35)" } } */
unsigned long long d = x * (0x17ULL << 15); /* { dg-final { gdb-test 29 "d" "(0x17ULL << 15)" } } */
unsigned long long e = x * (0x17ULL << 50); /* { dg-final { gdb-test 29 "e" "(0x17ULL << 50)" } } */
unsigned long long f = x * (0x37ULL << 31); /* { dg-final { gdb-test 29 "f" "(0x37ULL << 31)" } } */
unsigned long long g = x * (0x37ULL << 50); /* { dg-final { gdb-test 29 "g" "(0x37ULL << 50)" } } */
unsigned long long h = x * (0x1efULL << 33); /* { dg-final { gdb-test 29 "h" "(0x1efULL << 33)" } } */
unsigned long long i = x * (0x1efULL << 50); /* { dg-final { gdb-test 29 "i" "(0x1efULL << 50)" } } */
unsigned long long j = x * -(0x17ULL << 31); /* { dg-final { gdb-test 29 "j" "-(0x17ULL << 31)" } } */
unsigned long long k = x * -(0x7ULL << 33); /* { dg-final { gdb-test 29 "k" "-(0x7ULL << 33)" } } */
unsigned long long l = x * -(0x1ULL << 35); /* { dg-final { gdb-test 29 "l" "-(0x1ULL << 35)" } } */
unsigned long long m = x * -(0x17ULL << 15); /* { dg-final { gdb-test 29 "m" "-(0x17ULL << 15)" } } */
unsigned long long n = x * -(0x17ULL << 50); /* { dg-final { gdb-test 29 "n" "-(0x17ULL << 50)" } } */
unsigned long long o = x * -(0x37ULL << 31); /* { dg-final { gdb-test 29 "o" "-(0x37ULL << 31)" } } */
unsigned long long p = x * -(0x37ULL << 50); /* { dg-final { gdb-test 29 "p" "-(0x37ULL << 50)" } } */
unsigned long long q = x * -(0x1efULL << 33); /* { dg-final { gdb-test 29 "q" "-(0x1efULL << 33)" } } */
unsigned long long r = x * -(0x1efULL << 50); /* { dg-final { gdb-test 29 "r" "-(0x1efULL << 50)" } } */
v++;
return x;
}
__attribute__((noinline, noclone))
unsigned long long
bar (unsigned long long x)
{
unsigned long long a = (x & 255) + (0x17ULL << 31); /* { dg-final { gdb-test 55 "a" "(0x17ULL << 31)" } } */
unsigned long long b = (x & 255) + (0x7ULL << 33); /* { dg-final { gdb-test 55 "b" "(0x7ULL << 33)" } } */
unsigned long long c = (x & 255) + (0x1ULL << 35); /* { dg-final { gdb-test 55 "c" "(0x1ULL << 35)" } } */
unsigned long long d = (x & 255) + (0x17ULL << 15); /* { dg-final { gdb-test 55 "d" "(0x17ULL << 15)" } } */
unsigned long long e = (x & 255) + (0x17ULL << 50); /* { dg-final { gdb-test 55 "e" "(0x17ULL << 50)" } } */
unsigned long long f = (x & 255) + (0x37ULL << 31); /* { dg-final { gdb-test 55 "f" "(0x37ULL << 31)" } } */
unsigned long long g = (x & 255) + (0x37ULL << 50); /* { dg-final { gdb-test 55 "g" "(0x37ULL << 50)" } } */
unsigned long long h = (x & 255) + (0x1efULL << 33); /* { dg-final { gdb-test 55 "h" "(0x1efULL << 33)" } } */
unsigned long long i = (x & 255) + (0x1efULL << 50); /* { dg-final { gdb-test 55 "i" "(0x1efULL << 50)" } } */
unsigned long long j = (x & 255) + -(0x17ULL << 31); /* { dg-final { gdb-test 55 "j" "-(0x17ULL << 31)" } } */
unsigned long long k = (x & 255) + -(0x7ULL << 33); /* { dg-final { gdb-test 55 "k" "-(0x7ULL << 33)" } } */
unsigned long long l = (x & 255) + -(0x1ULL << 35); /* { dg-final { gdb-test 55 "l" "-(0x1ULL << 35)" } } */
unsigned long long m = (x & 255) + -(0x17ULL << 15); /* { dg-final { gdb-test 55 "m" "-(0x17ULL << 15)" } } */
unsigned long long n = (x & 255) + -(0x17ULL << 50); /* { dg-final { gdb-test 55 "n" "-(0x17ULL << 50)" } } */
unsigned long long o = (x & 255) + -(0x37ULL << 31); /* { dg-final { gdb-test 55 "o" "-(0x37ULL << 31)" } } */
unsigned long long p = (x & 255) + -(0x37ULL << 50); /* { dg-final { gdb-test 55 "p" "-(0x37ULL << 50)" } } */
unsigned long long q = (x & 255) + -(0x1efULL << 33); /* { dg-final { gdb-test 55 "q" "-(0x1efULL << 33)" } } */
unsigned long long r = (x & 255) + -(0x1efULL << 50); /* { dg-final { gdb-test 55 "r" "-(0x1efULL << 50)" } } */
v++;
return x;
}
int
main ()
{
return foo (1) + bar (256) - 257;
} |
Filters are used to reduce the data set that Views provides. That is to say, without any filters applied, Views will return all of your content. You don't want that, so at least some filters must be used.
Some very commonly used filters:
<ul>
<li> The 'Node: Published' filter is used to restrict a node View to only nodes that are are have the 'published' box checked. This can be very important to prevent users from viewing content they should not have access to.</li>
<li> The 'Node: Promoted to front page' filter can be used to show only nodes that have the 'promote to front page' turned on. </li>
<li> The 'Node: Type' filter is useful for showing only certain types of nodes. Let's say you wanted users to see only nodes that were 'book' nodes, or a combination of 'book' nodes and 'staff-blog' nodes. This filter allows you to select exactly that.</li>
<li> The 'User: Current' filter will show only nodes that the logged in user has authored.</li>
<li> The 'Node: Post date' filter can be used to show only nodes posted before, after, or between a range of dates.</li>
</ul>
The above list is only a tiny fraction of the filters available in Views, referenced here to give an idea of the kinds of tasks filters can accomplish. When you do not find a filter type, you may need to choose a <a href="topic:views/relationship">Relationship</a> before the expected filter will show, or to install a new module that contains the requested filter.
When you click the Rearrange Icon you can first rearrange your filters, easily delete filters and select an operator: "AND" or "Or". By default the "AND" operator is selcted. At the lower right of the window is the new button "Add new group". When you click on it, you can drag and drop an individual filter to the new group "Group 1". For this new group and the default group you can select the "Group operator": "And" or "Or". To remove a group, remove all filters and click the "Remove group 1" button.
When you want that the user to select their own filter, you can expose the filter. A selection box will show for the user and they will be able to select one item. After that the view will reload and only the selected item will be displayed. You can also choose to expose the selection to a block, see <a href="topic:views/exposed-form">here</a>.
For exposed filters, you can create a grouped filter. When filters are in a group, each item of the group represents a set of operators and values. The following table illustrates how this feature works. The values of the first column of the table are displayed as options of a single select box:
<table>
<thead>
<tr><th>What the user see</th><th>What views does</th></tr>
</thead>
<tbody>
<tr><td>Is lower than 10</td><td><strong>Operator:</strong> Is Lower than. <strong>Value:</strong> 10</td></tr>
<tr><td>Is between 10 and 20</td><td><strong>Operator:</strong> Is between. <strong>Value:</strong> 10 and 20</td></tr>
<tr><td>Is greater than 20</td><td><strong>Operator:</strong> Is Greater. <strong>Value:</strong> 20</td></tr>
</tbody>
</table>
<strong>Please note:</strong> When using grouped filters with the option: 'Enable to allow users to select multiple items' checked, you probably may want to to place the filter in a separated group and define the operator of the group as 'OR'. This may be neccesary because in order to use multiple times the same filter, all options have to be applied using the OR operator, if not, probably you will get nothing listed since usually items in a group are mutually exclusive.
Taxonomy filters have been significantly altered in Views 7.x-3.x. D7 significantly re-organized taxonomy, there was a lot of duplicate taxonomy related fields and filters. Some of them were removed to try and reduce confusion between them. Implicit relationships to taxonomy have been removed, in favor of explicit relationships. If the filters you can find don't do what you need, try adding either the related taxonomy terms relationship, or a relationship on the specific taxonomy field. That will give you the term specific filters.
You can override the complete filter section - see <a href="topic:views/overrides">here</a> for more information. |
#ifndef _LJ_TARGET_ARM_H
#define _LJ_TARGET_ARM_H
#define GPRDEF(_) \
_(R0) _(R1) _(R2) _(R3) _(R4) _(R5) _(R6) _(R7) \
_(R8) _(R9) _(R10) _(R11) _(R12) _(SP) _(LR) _(PC)
#if LJ_SOFTFP
#define FPRDEF(_)
#else
#define FPRDEF(_) \
_(D0) _(D1) _(D2) _(D3) _(D4) _(D5) _(D6) _(D7) \
_(D8) _(D9) _(D10) _(D11) _(D12) _(D13) _(D14) _(D15)
#endif
#define VRIDDEF(_)
#define RIDENUM(name) RID_##name,
enum {
GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */
FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */
RID_MAX,
RID_TMP = RID_LR,
/* Calling conventions. */
RID_RET = RID_R0,
RID_RETLO = RID_R0,
RID_RETHI = RID_R1,
#if LJ_SOFTFP
RID_FPRET = RID_R0,
#else
RID_FPRET = RID_D0,
#endif
/* These definitions must match with the *.dasc file(s): */
RID_BASE = RID_R9, /* Interpreter BASE. */
RID_LPC = RID_R6, /* Interpreter PC. */
RID_DISPATCH = RID_R7, /* Interpreter DISPATCH table. */
RID_LREG = RID_R8, /* Interpreter L. */
/* Register ranges [min, max) and number of registers. */
RID_MIN_GPR = RID_R0,
RID_MAX_GPR = RID_PC+1,
RID_MIN_FPR = RID_MAX_GPR,
#if LJ_SOFTFP
RID_MAX_FPR = RID_MIN_FPR,
#else
RID_MAX_FPR = RID_D15+1,
#endif
RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR,
RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR
};
#define RID_NUM_KREF RID_NUM_GPR
#define RID_MIN_KREF RID_R0
/* Make use of all registers, except sp, lr and pc. */
#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_R12+1))
#define RSET_GPREVEN \
(RID2RSET(RID_R0)|RID2RSET(RID_R2)|RID2RSET(RID_R4)|RID2RSET(RID_R6)| \
RID2RSET(RID_R8)|RID2RSET(RID_R10))
#define RSET_GPRODD \
(RID2RSET(RID_R1)|RID2RSET(RID_R3)|RID2RSET(RID_R5)|RID2RSET(RID_R7)| \
RID2RSET(RID_R9)|RID2RSET(RID_R11))
#if LJ_SOFTFP
#define RSET_FPR 0
#else
#define RSET_FPR (RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR))
#endif
#define RSET_ALL (RSET_GPR|RSET_FPR)
#define RSET_INIT RSET_ALL
/* ABI-specific register sets. lr is an implicit scratch register. */
#define RSET_SCRATCH_GPR_ (RSET_RANGE(RID_R0, RID_R3+1)|RID2RSET(RID_R12))
#ifdef __APPLE__
#define RSET_SCRATCH_GPR (RSET_SCRATCH_GPR_|RID2RSET(RID_R9))
#else
#define RSET_SCRATCH_GPR RSET_SCRATCH_GPR_
#endif
#if LJ_SOFTFP
#define RSET_SCRATCH_FPR 0
#else
#define RSET_SCRATCH_FPR (RSET_RANGE(RID_D0, RID_D7+1))
#endif
#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR)
#define REGARG_FIRSTGPR RID_R0
#define REGARG_LASTGPR RID_R3
#define REGARG_NUMGPR 4
#if LJ_ABI_SOFTFP
#define REGARG_FIRSTFPR 0
#define REGARG_LASTFPR 0
#define REGARG_NUMFPR 0
#else
#define REGARG_FIRSTFPR RID_D0
#define REGARG_LASTFPR RID_D7
#define REGARG_NUMFPR 8
#endif
/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs.
**
** SPS_FIXED: Available fixed spill slots in interpreter frame.
** This definition must match with the *.dasc file(s).
**
** SPS_FIRST: First spill slot for general use. Reserve min. two 32 bit slots.
*/
#define SPS_FIXED 2
#define SPS_FIRST 2
#define SPOFS_TMP 0
#define sps_scale(slot) (4 * (int32_t)(slot))
#define sps_align(slot) (((slot) - SPS_FIXED + 1) & ~1)
/* This definition must match with the *.dasc file(s). */
typedef struct {
#if !LJ_SOFTFP
lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */
#endif
int32_t gpr[RID_NUM_GPR]; /* General-purpose registers. */
int32_t spill[256]; /* Spill slots. */
} ExitState;
/* PC after instruction that caused an exit. Used to find the trace number. */
#define EXITSTATE_PCREG RID_PC
/* Highest exit + 1 indicates stack check. */
#define EXITSTATE_CHECKEXIT 1
#define EXITSTUB_SPACING 4
#define EXITSTUBS_PER_GROUP 32
/* Instruction fields. */
#define ARMF_CC(ai, cc) (((ai) ^ ARMI_CCAL) | ((cc) << 28))
#define ARMF_N(r) ((r) << 16)
#define ARMF_D(r) ((r) << 12)
#define ARMF_S(r) ((r) << 8)
#define ARMF_M(r) (r)
#define ARMF_SH(sh, n) (((sh) << 5) | ((n) << 7))
#define ARMF_RSH(sh, r) (0x10 | ((sh) << 5) | ARMF_S(r))
typedef enum ARMIns {
ARMI_CCAL = 0xe0000000,
ARMI_S = 0x000100000,
ARMI_K12 = 0x02000000,
ARMI_KNEG = 0x00200000,
ARMI_LS_W = 0x00200000,
ARMI_LS_U = 0x00800000,
ARMI_LS_P = 0x01000000,
ARMI_LS_R = 0x02000000,
ARMI_LSX_I = 0x00400000,
ARMI_AND = 0xe0000000,
ARMI_EOR = 0xe0200000,
ARMI_SUB = 0xe0400000,
ARMI_RSB = 0xe0600000,
ARMI_ADD = 0xe0800000,
ARMI_ADC = 0xe0a00000,
ARMI_SBC = 0xe0c00000,
ARMI_RSC = 0xe0e00000,
ARMI_TST = 0xe1100000,
ARMI_TEQ = 0xe1300000,
ARMI_CMP = 0xe1500000,
ARMI_CMN = 0xe1700000,
ARMI_ORR = 0xe1800000,
ARMI_MOV = 0xe1a00000,
ARMI_BIC = 0xe1c00000,
ARMI_MVN = 0xe1e00000,
ARMI_NOP = 0xe1a00000,
ARMI_MUL = 0xe0000090,
ARMI_SMULL = 0xe0c00090,
ARMI_LDR = 0xe4100000,
ARMI_LDRB = 0xe4500000,
ARMI_LDRH = 0xe01000b0,
ARMI_LDRSB = 0xe01000d0,
ARMI_LDRSH = 0xe01000f0,
ARMI_LDRD = 0xe00000d0,
ARMI_STR = 0xe4000000,
ARMI_STRB = 0xe4400000,
ARMI_STRH = 0xe00000b0,
ARMI_STRD = 0xe00000f0,
ARMI_PUSH = 0xe92d0000,
ARMI_B = 0xea000000,
ARMI_BL = 0xeb000000,
ARMI_BLX = 0xfa000000,
ARMI_BLXr = 0xe12fff30,
/* ARMv6 */
ARMI_REV = 0xe6bf0f30,
ARMI_SXTB = 0xe6af0070,
ARMI_SXTH = 0xe6bf0070,
ARMI_UXTB = 0xe6ef0070,
ARMI_UXTH = 0xe6ff0070,
/* ARMv6T2 */
ARMI_MOVW = 0xe3000000,
ARMI_MOVT = 0xe3400000,
/* VFP */
ARMI_VMOV_D = 0xeeb00b40,
ARMI_VMOV_S = 0xeeb00a40,
ARMI_VMOVI_D = 0xeeb00b00,
ARMI_VMOV_R_S = 0xee100a10,
ARMI_VMOV_S_R = 0xee000a10,
ARMI_VMOV_RR_D = 0xec500b10,
ARMI_VMOV_D_RR = 0xec400b10,
ARMI_VADD_D = 0xee300b00,
ARMI_VSUB_D = 0xee300b40,
ARMI_VMUL_D = 0xee200b00,
ARMI_VMLA_D = 0xee000b00,
ARMI_VMLS_D = 0xee000b40,
ARMI_VNMLS_D = 0xee100b00,
ARMI_VDIV_D = 0xee800b00,
ARMI_VABS_D = 0xeeb00bc0,
ARMI_VNEG_D = 0xeeb10b40,
ARMI_VSQRT_D = 0xeeb10bc0,
ARMI_VCMP_D = 0xeeb40b40,
ARMI_VCMPZ_D = 0xeeb50b40,
ARMI_VMRS = 0xeef1fa10,
ARMI_VCVT_S32_F32 = 0xeebd0ac0,
ARMI_VCVT_S32_F64 = 0xeebd0bc0,
ARMI_VCVT_U32_F32 = 0xeebc0ac0,
ARMI_VCVT_U32_F64 = 0xeebc0bc0,
ARMI_VCVTR_S32_F32 = 0xeebd0a40,
ARMI_VCVTR_S32_F64 = 0xeebd0b40,
ARMI_VCVTR_U32_F32 = 0xeebc0a40,
ARMI_VCVTR_U32_F64 = 0xeebc0b40,
ARMI_VCVT_F32_S32 = 0xeeb80ac0,
ARMI_VCVT_F64_S32 = 0xeeb80bc0,
ARMI_VCVT_F32_U32 = 0xeeb80a40,
ARMI_VCVT_F64_U32 = 0xeeb80b40,
ARMI_VCVT_F32_F64 = 0xeeb70bc0,
ARMI_VCVT_F64_F32 = 0xeeb70ac0,
ARMI_VLDR_S = 0xed100a00,
ARMI_VLDR_D = 0xed100b00,
ARMI_VSTR_S = 0xed000a00,
ARMI_VSTR_D = 0xed000b00,
} ARMIns;
typedef enum ARMShift {
ARMSH_LSL, ARMSH_LSR, ARMSH_ASR, ARMSH_ROR
} ARMShift;
/* ARM condition codes. */
typedef enum ARMCC {
CC_EQ, CC_NE, CC_CS, CC_CC, CC_MI, CC_PL, CC_VS, CC_VC,
CC_HI, CC_LS, CC_GE, CC_LT, CC_GT, CC_LE, CC_AL,
CC_HS = CC_CS, CC_LO = CC_CC
} ARMCC;
#endif |
<?php
/**
* @file
* Bootstrap 8-4 template for Display Suite.
*/
?>
<<?php print $layout_wrapper; print $layout_attributes; ?> class="<?php print $classes; ?>">
<?php if (isset($title_suffix['contextual_links'])): ?>
<?php print render($title_suffix['contextual_links']); ?>
<?php endif; ?>
<div class="row">
<<?php print $left_wrapper; ?> class="col-sm-8 <?php print $left_classes; ?>">
<?php print $left; ?>
</<?php print $left_wrapper; ?>>
<<?php print $right_wrapper; ?> class="col-sm-4 <?php print $right_classes; ?>">
<?php print $right; ?>
</<?php print $right_wrapper; ?>>
</div>
</<?php print $layout_wrapper ?>>
<!-- Needed to activate display suite support on forms -->
<?php if (!empty($<API key>)): ?>
<?php print $<API key> ?>
<?php endif; ?> |
class A {
{
String[] result = new String[1];
result[0] = "";
String c = result[0];
System.out.println(c);
System.out.println(c);
}
} |
#ifndef XmlParse_INCLUDED
#define XmlParse_INCLUDED 1
#ifdef __VMS
/* 0 1 2 3 0 1 2 3
<API key> <API key> */
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
#endif
#include <stdlib.h>
#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
#define <API key> 1
#endif
/* Expat tries very hard to make the API boundary very specifically
defined. There are two macros defined to control this boundary;
each of these can be defined before including this header to
achieve some different behavior, but doing so it not recommended or
tested frequently.
XMLCALL - The calling convention to use for all calls across the
"library boundary." This will default to cdecl, and
try really hard to tell the compiler that's what we
want.
XMLIMPORT - Whatever magic is needed to note that a function is
to be imported from a dynamically loaded library
(.dll, .so, or .sl, depending on your platform).
The XMLCALL macro was added in Expat 1.95.7. The only one which is
expected to be directly useful in client code is XMLCALL.
Note that on at least some Unix versions, the Expat library must be
compiled with the cdecl calling convention as the default since
system headers may assume the cdecl convention.
*/
#ifndef XMLCALL
#if defined(<API key>)
#define XMLCALL __cdecl
#elif defined(__GNUC__) && defined(__i386)
#define XMLCALL __attribute__((cdecl))
#else
/* For any platform which uses this definition and supports more than
one calling convention, we need to extend this definition to
declare the convention used on that platform, if it's possible to
do so.
If this is the case for your platform, please file a bug report
with information on how to identify your platform via the C
pre-processor and how to specify the same calling convention as the
platform's malloc() implementation.
*/
#define XMLCALL
#endif
#endif /* not defined XMLCALL */
#if !defined(XML_STATIC) && !defined(XMLIMPORT)
#ifndef XML_BUILDING_EXPAT
/* using Expat from an application */
#ifdef <API key>
#define XMLIMPORT __declspec(dllimport)
#endif
#endif
#endif /* not defined XML_STATIC */
/* If we didn't define it above, define it away: */
#ifndef XMLIMPORT
#define XMLIMPORT
#endif
#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
#ifdef __cplusplus
extern "C" {
#endif
#ifdef XML_UNICODE_WCHAR_T
#define XML_UNICODE
#endif
struct XML_ParserStruct;
typedef struct XML_ParserStruct *XML_Parser;
#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
#ifdef XML_UNICODE_WCHAR_T
typedef wchar_t XML_Char;
typedef wchar_t XML_LChar;
#else
typedef unsigned short XML_Char;
typedef char XML_LChar;
#endif /* XML_UNICODE_WCHAR_T */
#else /* Information is UTF-8 encoded. */
typedef char XML_Char;
typedef char XML_LChar;
#endif /* XML_UNICODE */
/* Should this be defined using stdbool.h when C99 is available? */
typedef unsigned char XML_Bool;
#define XML_TRUE ((XML_Bool) 1)
#define XML_FALSE ((XML_Bool) 0)
/* The XML_Status enum gives the possible return values for several
API functions. The preprocessor #defines are included so this
stanza can be added to code that still needs to support older
versions of Expat 1.95.x:
#ifndef XML_STATUS_OK
#define XML_STATUS_OK 1
#define XML_STATUS_ERROR 0
#endif
Otherwise, the #define hackery is quite ugly and would have been
dropped.
*/
enum XML_Status {
XML_STATUS_ERROR = 0,
#define XML_STATUS_ERROR XML_STATUS_ERROR
XML_STATUS_OK = 1
#define XML_STATUS_OK XML_STATUS_OK
};
enum XML_Error {
XML_ERROR_NONE,
XML_ERROR_NO_MEMORY,
XML_ERROR_SYNTAX,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
};
enum XML_Content_Type {
XML_CTYPE_EMPTY = 1,
XML_CTYPE_ANY,
XML_CTYPE_MIXED,
XML_CTYPE_NAME,
XML_CTYPE_CHOICE,
XML_CTYPE_SEQ
};
enum XML_Content_Quant {
XML_CQUANT_NONE,
XML_CQUANT_OPT,
XML_CQUANT_REP,
XML_CQUANT_PLUS
};
/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be
XML_CQUANT_NONE, and the other fields will be zero or NULL.
If type == XML_CTYPE_MIXED, then quant will be NONE or REP and
numchildren will contain number of elements that may be mixed in
and children point to an array of XML_Content cells that will be
all of XML_CTYPE_NAME type with no quantification.
If type == XML_CTYPE_NAME, then the name points to the name, and
the numchildren field will be zero and children will be NULL. The
quant fields indicates any quantifiers placed on the name.
CHOICE and SEQ will have name NULL, the number of children in
numchildren and children will point, recursively, to an array
of XML_Content cells.
The EMPTY, ANY, and MIXED types will only occur at top level.
*/
typedef struct XML_cp XML_Content;
struct XML_cp {
enum XML_Content_Type type;
enum XML_Content_Quant quant;
XML_Char * name;
unsigned int numchildren;
XML_Content * children;
};
/* This is called for an element declaration. See above for
description of the model argument. It's the caller's responsibility
to free model when finished with it.
*/
typedef void (XMLCALL *<API key>) (void *userData,
const XML_Char *name,
XML_Content *model);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> eldecl);
/* The Attlist declaration handler is called for *each* attribute. So
a single Attlist declaration with multiple attributes declared will
generate multiple calls to this handler. The "default" parameter
may be NULL in the case of the "#IMPLIED" or "#REQUIRED"
keyword. The "isrequired" parameter will be true and the default
value will be NULL in the case of "#REQUIRED". If "isrequired" is
true and default is non-NULL, then this is a "#FIXED" default.
*/
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *elname,
const XML_Char *attname,
const XML_Char *att_type,
const XML_Char *dflt,
int isrequired);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> attdecl);
/* The XML declaration handler is called for *both* XML declarations
and text declarations. The way to distinguish is that the version
parameter will be NULL for text declarations. The encoding
parameter may be NULL for XML declarations. The standalone
parameter will be -1, 0, or 1 indicating respectively that there
was no standalone parameter in the declaration, that it was given
as no, or that it was given as yes.
*/
typedef void (XMLCALL *XML_XmlDeclHandler) (void *userData,
const XML_Char *version,
const XML_Char *encoding,
int standalone);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
XML_XmlDeclHandler xmldecl);
typedef struct {
void *(XMLCALL *malloc_fcn)(size_t size);
void *(XMLCALL *realloc_fcn)(void *ptr, size_t size);
void (XMLCALL *free_fcn)(void *ptr);
} <API key>;
/* Constructs a new parser; encoding is the encoding specified by the
external protocol or NULL if there is none specified.
*/
XMLPARSEAPI(XML_Parser)
XML_ParserCreate(const XML_Char *encoding);
/* Constructs a new parser and namespace processor. Element type
names and attribute names that belong to a namespace will be
expanded; unprefixed attribute names are never expanded; unprefixed
element type names are expanded only if there is a default
namespace. The expanded name is the concatenation of the namespace
URI, the namespace separator character, and the local part of the
name. If the namespace separator is '\0' then the namespace URI
and the local part will be concatenated without any separator.
When a namespace is not declared, the name and prefix will be
passed through without expansion.
*/
XMLPARSEAPI(XML_Parser)
XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);
/* Constructs a new parser using the memory management suite referred to
by memsuite. If memsuite is NULL, then use the standard library memory
suite. If namespaceSeparator is non-NULL it creates a parser with
namespace processing as described above. The character pointed at
will serve as the namespace separator.
All further memory operations used for the created parser will come from
the given suite.
*/
XMLPARSEAPI(XML_Parser)
XML_ParserCreate_MM(const XML_Char *encoding,
const <API key> *memsuite,
const XML_Char *namespaceSeparator);
/* Prepare a parser object to be re-used. This is particularly
valuable when memory allocation overhead is disproportionatly high,
such as when a large number of small documnents need to be parsed.
All handlers are cleared from the parser, except for the
<API key>. The parser's external state is re-initialized
except for the values of ns and ns_triplets.
Added in Expat 1.95.3.
*/
XMLPARSEAPI(XML_Bool)
XML_ParserReset(XML_Parser parser, const XML_Char *encoding);
/* atts is array of name/value pairs, terminated by 0;
names and values are 0 terminated.
*/
typedef void (XMLCALL *<API key>) (void *userData,
const XML_Char *name,
const XML_Char **atts);
typedef void (XMLCALL *<API key>) (void *userData,
const XML_Char *name);
/* s is not 0 terminated. */
typedef void (XMLCALL *<API key>) (void *userData,
const XML_Char *s,
int len);
/* target and data are 0 terminated */
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *target,
const XML_Char *data);
/* data is 0 terminated */
typedef void (XMLCALL *XML_CommentHandler) (void *userData,
const XML_Char *data);
typedef void (XMLCALL *<API key>) (void *userData);
typedef void (XMLCALL *<API key>) (void *userData);
/* This is called for any characters in the XML document for which
there is no applicable handler. This includes both characters that
are part of markup which is of a kind that is not reported
(comments, markup declarations), or characters that are part of a
construct which could be reported but for which no handler has been
supplied. The characters are passed exactly as they were in the XML
document except that they will be encoded in UTF-8 or UTF-16.
Line boundaries are not normalized. Note that a byte order mark
character is not passed to the default handler. There are no
guarantees about how characters are divided between calls to the
default handler: for example, a comment might be split between
multiple calls.
*/
typedef void (XMLCALL *XML_DefaultHandler) (void *userData,
const XML_Char *s,
int len);
/* This is called for the start of the DOCTYPE declaration, before
any DTD or internal subset is parsed.
*/
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *doctypeName,
const XML_Char *sysid,
const XML_Char *pubid,
int has_internal_subset);
/* This is called for the start of the DOCTYPE declaration when the
closing > is encountered, but after processing any external
subset.
*/
typedef void (XMLCALL *<API key>)(void *userData);
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *entityName,
int is_parameter_entity,
const XML_Char *value,
int value_length,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
/* OBSOLETE -- OBSOLETE -- OBSOLETE
This handler has been superceded by the EntityDeclHandler above.
It is provided here for backward compatibility.
This is called for a declaration of an unparsed (NDATA) entity.
The base argument is whatever was set by XML_SetBase. The
entityName, systemId and notationName arguments will never be
NULL. The other arguments may be.
*/
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName);
/* This is called for a declaration of notation. The base argument is
whatever was set by XML_SetBase. The notationName will never be
NULL. The other arguments can be.
*/
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
/* When namespace processing is enabled, these are called once for
each namespace declaration. The call to the start and end element
handlers occur between the calls to the start and end namespace
declaration handlers. For an xmlns attribute, prefix will be
NULL. For an xmlns="" attribute, uri will be NULL.
*/
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *prefix,
const XML_Char *uri);
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *prefix);
/* This is called if the document is not standalone, that is, it has an
external subset or a reference to a parameter entity, but does not
have standalone="yes". If this handler returns XML_STATUS_ERROR,
then processing will not continue, and the parser will return a
<API key> error.
If parameter entity parsing is enabled, then in addition to the
conditions above this handler will only be called if the referenced
entity was actually read.
*/
typedef int (XMLCALL *<API key>) (void *userData);
/* This is called for a reference to an external parsed general
entity. The referenced entity is not automatically parsed. The
application can parse it immediately or later using
<API key>.
The parser argument is the parser parsing the entity containing the
reference; it can be passed as the parser argument to
<API key>. The systemId argument is the
system identifier as specified in the entity declaration; it will
not be NULL.
The base argument is the system identifier that should be used as
the base for resolving systemId if systemId was relative; this is
set by XML_SetBase; it may be NULL.
The publicId argument is the public identifier as specified in the
entity declaration, or NULL if none was specified; the whitespace
in the public identifier will have been normalized as required by
the XML spec.
The context argument specifies the parsing context in the format
expected by the context argument to <API key>;
context is valid only until the handler returns, so if the
referenced entity is to be parsed later, it must be copied.
context is NULL only when the entity is a parameter entity.
The handler should return XML_STATUS_ERROR if processing should not
continue because of a fatal error in the handling of the external
entity. In this case the calling parser will return an
<API key> error.
Note that unlike other handlers the first argument is the parser,
not userData.
*/
typedef int (XMLCALL *<API key>) (
XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId);
/* This is called in two situations:
1) An entity reference is encountered for which no declaration
has been read *and* this is not an error.
2) An internal entity reference is read, but not expanded, because
<API key> has been called.
Note: skipped parameter entities in declarations and skipped general
entities in attribute values cannot be reported, because
the event would be out of sync with the reporting of the
declarations or attribute values
*/
typedef void (XMLCALL *<API key>) (
void *userData,
const XML_Char *entityName,
int is_parameter_entity);
/* This structure is filled in by the <API key> to
provide information to the parser about encodings that are unknown
to the parser.
The map[b] member gives information about byte sequences whose
first byte is b.
If map[b] is c where c is >= 0, then b by itself encodes the
Unicode scalar value c.
If map[b] is -1, then the byte sequence is malformed.
If map[b] is -n, where n >= 2, then b is the first byte of an
n-byte sequence that encodes a single Unicode scalar value.
The data member will be passed as the first argument to the convert
function.
The convert function is used to convert multibyte sequences; s will
point to a n-byte sequence where map[(unsigned char)*s] == -n. The
convert function must return the Unicode scalar value represented
by this byte sequence or -1 if the byte sequence is malformed.
The convert function may be NULL if the encoding is a single-byte
encoding, that is if map[b] >= -1 for all bytes b.
When the parser is finished with the encoding, then if release is
not NULL, it will call release passing it the data member; once
release has been called, the convert function will not be called
again.
Expat places certain restrictions on the encodings that are supported
using this mechanism.
1. Every ASCII character that can appear in a well-formed XML document,
other than the characters
$@\^`{}~
must be represented by a single byte, and that byte must be the
same byte that represents that character in ASCII.
2. No character may require more than 4 bytes to encode.
3. All characters encoded must have Unicode scalar values <=
0xFFFF, (i.e., characters that would be encoded by surrogates in
UTF-16 are not allowed). Note that this restriction doesn't
apply to the built-in support for UTF-8 and UTF-16.
4. No Unicode character may be encoded by more than one distinct
sequence of bytes.
*/
typedef struct {
int map[256];
void *data;
int (XMLCALL *convert)(void *data, const char *s);
void (XMLCALL *release)(void *data);
} XML_Encoding;
/* This is called for an encoding that is unknown to the parser.
The encodingHandlerData argument is that which was passed as the
second argument to <API key>.
The name argument gives the name of the encoding as specified in
the encoding declaration.
If the callback can provide information about the encoding, it must
fill in the XML_Encoding structure, and return XML_STATUS_OK.
Otherwise it must return XML_STATUS_ERROR.
If info does not describe a suitable encoding, then the parser will
return an <API key> error.
*/
typedef int (XMLCALL *<API key>) (
void *encodingHandlerData,
const XML_Char *name,
XML_Encoding *info);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start,
<API key> end);
XMLPARSEAPI(void)
<API key>(XML_Parser, <API key>);
XMLPARSEAPI(void)
<API key>(XML_Parser, <API key>);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
XML_CommentHandler handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start,
<API key> end);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> end);
/* This sets the default handler and also inhibits expansion of
internal entities. These entity references will be passed to the
default handler, or to the skipped entity handler, if one is set.
*/
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
XML_DefaultHandler handler);
/* This sets the default handler but does not inhibit expansion of
internal entities. The entity reference will not be passed to the
default handler.
*/
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
XML_DefaultHandler handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start,
<API key> end);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> end);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start,
<API key> end);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> start);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> end);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
/* If a non-NULL value for arg is specified here, then it will be
passed as the first argument to the external entity ref handler
instead of the parser object.
*/
XMLPARSEAPI(void)
<API key>(XML_Parser, void *arg);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler);
XMLPARSEAPI(void)
<API key>(XML_Parser parser,
<API key> handler,
void *encodingHandlerData);
/* This can be called within a handler for a start element, end
element, processing instruction or character data. It causes the
corresponding markup to be passed to the default handler.
*/
XMLPARSEAPI(void)
XML_DefaultCurrent(XML_Parser parser);
/* If do_nst is non-zero, and namespace processing is in effect, and
a name has a prefix (i.e. an explicit namespace qualifier) then
that name is returned as a triplet in a single string separated by
the separator character specified when the parser was created: URI
+ sep + local_name + sep + prefix.
If do_nst is zero, then namespace information is returned in the
default manner (URI + sep + local_name) whether or not the name
has a prefix.
Note: Calling <API key> after XML_Parse or
XML_ParseBuffer has no effect.
*/
XMLPARSEAPI(void)
<API key>(XML_Parser parser, int do_nst);
/* This value is passed as the userData argument to callbacks. */
XMLPARSEAPI(void)
XML_SetUserData(XML_Parser parser, void *userData);
/* Returns the last value set by XML_SetUserData or NULL. */
#define XML_GetUserData(parser) (*(void **)(parser))
/* This is equivalent to supplying an encoding argument to
XML_ParserCreate. On success XML_SetEncoding returns non-zero,
zero otherwise.
Note: Calling XML_SetEncoding after XML_Parse or XML_ParseBuffer
has no effect and returns XML_STATUS_ERROR.
*/
XMLPARSEAPI(enum XML_Status)
XML_SetEncoding(XML_Parser parser, const XML_Char *encoding);
/* If this function is called, then the parser will be passed as the
first argument to callbacks instead of userData. The userData will
still be accessible using XML_GetUserData.
*/
XMLPARSEAPI(void)
<API key>(XML_Parser parser);
/* If useDTD == XML_TRUE is passed to this function, then the parser
will assume that there is an external subset, even if none is
specified in the document. In such a case the parser will call the
<API key> with a value of NULL for the systemId
argument (the publicId and context arguments will be NULL as well).
Note: If this function is called, then this must be done before
the first call to XML_Parse or XML_ParseBuffer, since it will
have no effect after that. Returns
<API key>.
Note: If the document does not have a DOCTYPE declaration at all,
then <API key> and <API key> will not
be called, despite an external subset being parsed.
Note: If XML_DTD is not defined when Expat is compiled, returns
<API key>.
*/
XMLPARSEAPI(enum XML_Error)
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);
/* Sets the base to be used for resolving relative URIs in system
identifiers in declarations. Resolving relative identifiers is
left to the application: this value will be passed through as the
base argument to the <API key>,
<API key> and <API key>. The base
argument will be copied. Returns XML_STATUS_ERROR if out of memory,
XML_STATUS_OK otherwise.
*/
XMLPARSEAPI(enum XML_Status)
XML_SetBase(XML_Parser parser, const XML_Char *base);
XMLPARSEAPI(const XML_Char *)
XML_GetBase(XML_Parser parser);
/* Returns the number of the attribute/value pairs passed in last call
to the <API key> that were specified in the start-tag
rather than defaulted. Each attribute/value pair counts as 2; thus
this correspondds to an index into the atts array passed to the
<API key>.
*/
XMLPARSEAPI(int)
<API key>(XML_Parser parser);
/* Returns the index of the ID attribute passed in the last call to
<API key>, or -1 if there is no ID attribute. Each
attribute/value pair counts as 2; thus this correspondds to an
index into the atts array passed to the <API key>.
*/
XMLPARSEAPI(int)
<API key>(XML_Parser parser);
/* Parses some input. Returns XML_STATUS_ERROR if a fatal error is
detected. The last call to XML_Parse must have isFinal true; len
may be zero for this call (or any other).
Though the return values for these functions has always been
described as a Boolean value, the implementation, at least for the
1.95.x series, has always returned exactly one of the XML_Status
values.
*/
XMLPARSEAPI(enum XML_Status)
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal);
XMLPARSEAPI(void *)
XML_GetBuffer(XML_Parser parser, int len);
XMLPARSEAPI(enum XML_Status)
XML_ParseBuffer(XML_Parser parser, int len, int isFinal);
/* Creates an XML_Parser object that can parse an external general
entity; context is a '\0'-terminated string specifying the parse
context; encoding is a '\0'-terminated string giving the name of
the externally specified encoding, or NULL if there is no
externally specified encoding. The context string consists of a
sequence of tokens separated by formfeeds (\f); a token consisting
of a name specifies that the general entity of the name is open; a
token of the form prefix=uri specifies the namespace for a
particular prefix; a token of the form =uri specifies the default
namespace. This can be called at any point after the first call to
an <API key> so longer as the parser has not yet
been freed. The new parser is completely independent and may
safely be used in a separate thread. The handlers and userData are
initialized from the parser argument. Returns NULL if out of memory.
Otherwise returns a new XML_Parser object.
*/
XMLPARSEAPI(XML_Parser)
<API key>(XML_Parser parser,
const XML_Char *context,
const XML_Char *encoding);
enum <API key> {
<API key>,
<API key>,
<API key>
};
XMLPARSEAPI(int)
<API key>(XML_Parser parser,
enum <API key> parsing);
/* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then
XML_GetErrorCode returns information about the error.
*/
XMLPARSEAPI(enum XML_Error)
XML_GetErrorCode(XML_Parser parser);
/* These functions return information about the current parse
location. They may be called from any callback called to report
some parse event; in this case the location is the location of the
first of the sequence of characters that generated the event. When
called from callbacks generated by declarations in the document
prologue, the location identified isn't as neatly defined, but will
be within the relevant markup. When called outside of the callback
functions, the position indicated will be just past the last parse
event (regardless of whether there was an associated callback).
They may also be called after returning from a call to XML_Parse
or XML_ParseBuffer. If the return value is XML_STATUS_ERROR then
the location is the location of the character at which the error
was detected; otherwise the location is the location of the last
parse event, as described above.
*/
XMLPARSEAPI(int) <API key>(XML_Parser parser);
XMLPARSEAPI(int) <API key>(XML_Parser parser);
XMLPARSEAPI(long) <API key>(XML_Parser parser);
/* Return the number of bytes in the current event.
Returns 0 if the event is in an internal entity.
*/
XMLPARSEAPI(int)
<API key>(XML_Parser parser);
/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets
the integer pointed to by offset to the offset within this buffer
of the current parse position, and sets the integer pointed to by size
to the size of this buffer (the number of input bytes). Otherwise
returns a NULL pointer. Also returns a NULL pointer if a parse isn't
active.
NOTE: The character pointer returned should not be used outside
the handler that makes the call.
*/
XMLPARSEAPI(const char *)
XML_GetInputContext(XML_Parser parser,
int *offset,
int *size);
/* For backwards compatibility with previous versions. */
#define <API key> <API key>
#define <API key> <API key>
#define <API key> <API key>
/* Frees the content model passed to the element declaration handler */
XMLPARSEAPI(void)
<API key>(XML_Parser parser, XML_Content *model);
/* Exposing the memory handling functions used in Expat */
XMLPARSEAPI(void *)
XML_MemMalloc(XML_Parser parser, size_t size);
XMLPARSEAPI(void *)
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size);
XMLPARSEAPI(void)
XML_MemFree(XML_Parser parser, void *ptr);
/* Frees memory used by the parser. */
XMLPARSEAPI(void)
XML_ParserFree(XML_Parser parser);
/* Returns a string describing the error. */
XMLPARSEAPI(const XML_LChar *)
XML_ErrorString(enum XML_Error code);
/* Return a string containing the version number of this expat */
XMLPARSEAPI(const XML_LChar *)
XML_ExpatVersion(void);
typedef struct {
int major;
int minor;
int micro;
} XML_Expat_Version;
/* Return an XML_Expat_Version structure containing numeric version
number information for this version of expat.
*/
XMLPARSEAPI(XML_Expat_Version)
<API key>(void);
/* Added in Expat 1.95.5. */
enum XML_FeatureEnum {
XML_FEATURE_END = 0,
XML_FEATURE_UNICODE,
<API key>,
XML_FEATURE_DTD,
<API key>,
<API key>,
<API key>,
<API key>
/* Additional features must be added to the end of this enum. */
};
typedef struct {
enum XML_FeatureEnum feature;
const XML_LChar *name;
long int value;
} XML_Feature;
XMLPARSEAPI(const XML_Feature *)
XML_GetFeatureList(void);
/* Expat follows the GNU/Linux convention of odd number minor version for
beta/development releases and even number minor version for stable
releases. Micro is bumped with each release, and set to 0 with each
change to major or minor version.
*/
#define XML_MAJOR_VERSION 1
#define XML_MINOR_VERSION 95
#define XML_MICRO_VERSION 7
#ifdef __cplusplus
}
#endif
#endif /* not XmlParse_INCLUDED */ |
(function($){$.fn.jflickrfeed=function(settings,callback){settings=$.extend(true,{flickrbase:'http://api.flickr.com/services/feeds/',feedapi:'photos_public.gne',limit:20,qstrings:{lang:'en-us',format:'json',jsoncallback:'?'},cleanDescription:true,useTemplate:true,itemTemplate:'',itemCallback:function(){}},settings);var url=settings.flickrbase+settings.feedapi+'?';var first=true;for(var key in settings.qstrings){if(!first)
url+='&';url+=key+'='+settings.qstrings[key];first=false;}
return $(this).each(function(){var $container=$(this);var container=this;$.getJSON(url,function(data){$.each(data.items,function(i,item){if(i<settings.limit){if(settings.cleanDescription){var regex=/<p>(.*?)<\/p>/g;var input=item.description;if(regex.test(input)){item.description=input.match(regex)[2]
if(item.description!=undefined)
item.description=item.description.replace('<p>','').replace('</p>','');}}
item['image_s']=item.media.m.replace('_m','_s');item['image_t']=item.media.m.replace('_m','_t');item['image_m']=item.media.m.replace('_m','_m');item['image']=item.media.m.replace('_m','');item['image_b']=item.media.m.replace('_m','_b');delete item.media;if(settings.useTemplate){var template=settings.itemTemplate;for(var key in item){var rgx=new RegExp('{{'+key+'}}','g');template=template.replace(rgx,item[key]);}
$container.append(template)}
settings.itemCallback.call(container,item);}});if($.isFunction(callback)){callback.call(container,data);}});});}})(jQuery); |
#ifndef <API key>
#define <API key>
extern struct sys_timer msm_timer;
uint32_t <API key>(void);
int <API key>(void (*timeout)(void));
#ifndef <API key>
void __iomem *<API key>(void);
int64_t <API key>(void);
void msm_timer_exit_idle(int low_power);
int64_t <API key>(int64_t *period);
#else
static inline int64_t <API key>(void) { return 0; }
static inline void msm_timer_exit_idle(int low_power) { return; }
static inline int64_t <API key>(int64_t *period) { return 0; }
static inline void __iomem *<API key>(void) { return NULL; }
#endif
#endif |
(function (requirejs, require, define) {
define(
'video/<API key>.js',
['video/00_iterator.js'],
function (Iterator) {
"use strict";
/**
* Video speed control module.
* @exports video/<API key>.js
* @constructor
* @param {object} state The object containing the state of the video player.
* @return {jquery Promise}
*/
var SpeedControl = function (state) {
if (!(this instanceof SpeedControl)) {
return new SpeedControl(state);
}
_.bindAll(this, 'onSetSpeed', 'onRenderSpeed', 'clickLinkHandler',
'keyDownLinkHandler', 'mouseEnterHandler', 'mouseLeaveHandler',
'clickMenuHandler', 'keyDownMenuHandler', 'destroy'
);
this.state = state;
this.state.videoSpeedControl = this;
this.initialize();
return $.Deferred().resolve().promise();
};
SpeedControl.prototype = {
template: [
'<div class="speeds menu-container">',
'<a class="speed-button" href="#" title="',
gettext('Speeds'), '" role="button" aria-disabled="false">',
'<span class="label">', gettext('Speed'), '</span>',
'<span class="value"></span>',
'</a>',
'<ol class="video-speeds menu" role="menu"></ol>',
'</div>'
].join(''),
destroy: function () {
this.el.off({
'mouseenter': this.mouseEnterHandler,
'mouseleave': this.mouseLeaveHandler,
'click': this.clickMenuHandler,
'keydown': this.keyDownMenuHandler
});
this.state.el.off({
'speed:set': this.onSetSpeed,
'speed:render': this.onRenderSpeed
});
this.closeMenu(true);
this.speedsContainer.remove();
this.el.remove();
delete this.state.videoSpeedControl;
},
/** Initializes the module. */
initialize: function () {
var state = this.state;
if (!this.<API key>(state)) {
console.log(
'[Video info]: playbackRate is not supported.'
);
return false;
}
this.el = $(this.template);
this.speedsContainer = this.el.find('.video-speeds');
this.speedButton = this.el.find('.speed-button');
this.render(state.speeds, state.speed);
this.setSpeed(state.speed, true, true);
this.bindHandlers();
return true;
},
/**
* Creates any necessary DOM elements, attach them, and set their,
* initial configuration.
* @param {array} speeds List of speeds available for the player.
*/
render: function (speeds) {
var speedsContainer = this.speedsContainer,
reversedSpeeds = speeds.concat().reverse(),
speedsList = $.map(reversedSpeeds, function (speed) {
return [
'<li data-speed="', speed, '" role="presentation">',
'<a class="speed-link" href="#" role="menuitem" tabindex="-1">',
speed, 'x',
'</a>',
'</li>'
].join('');
});
speedsContainer.html(speedsList.join(''));
this.speedLinks = new Iterator(speedsContainer.find('.speed-link'));
this.state.el.find('.secondary-controls').prepend(this.el);
},
/**
* Bind any necessary function callbacks to DOM events (click,
* mousemove, etc.).
*/
bindHandlers: function () {
// Attach various events handlers to the speed menu button.
this.el.on({
'mouseenter': this.mouseEnterHandler,
'mouseleave': this.mouseLeaveHandler,
'click': this.clickMenuHandler,
'keydown': this.keyDownMenuHandler
});
// Attach click and keydown event handlers to the individual speed
// entries.
this.speedsContainer.on({
click: this.clickLinkHandler,
keydown: this.keyDownLinkHandler
}, 'a.speed-link');
this.state.el.on({
'speed:set': this.onSetSpeed,
'speed:render': this.onRenderSpeed
});
this.state.el.on('destroy', this.destroy);
},
onSetSpeed: function (event, speed) {
this.setSpeed(speed, true);
},
onRenderSpeed: function (event, speeds, currentSpeed) {
this.render(speeds, currentSpeed);
},
/**
* Check if playbackRate supports by browser. If browser supports, 1.0
* should be returned by playbackRate property. In this case, function
* return True. Otherwise, False will be returned.
* iOS doesn't support speed change.
* @param {object} state The object containing the state of the video
* player.
* @return {boolean}
* true: Browser support playbackRate functionality.
* false: Browser doesn't support playbackRate functionality.
*/
<API key>: function (state) {
var isHtml5 = state.videoType === 'html5',
isTouch = state.isTouch,
video = document.createElement('video');
return !isTouch || (isHtml5 && !Boolean(video.playbackRate));
},
/**
* Opens speed menu.
* @param {boolean} [bindEvent] Click event will be attached on window.
*/
openMenu: function (bindEvent) {
// When speed entries have focus, the menu stays open on
// mouseleave. A clickHandler is added to the window
// element to have clicks close the menu when they happen
// outside of it.
if (bindEvent) {
$(window).on('click.speedMenu', this.clickMenuHandler);
}
this.el.addClass('is-opened');
this.speedButton.attr('tabindex', -1);
},
/**
* Closes speed menu.
* @param {boolean} [unBindEvent] Click event will be detached from window.
*/
closeMenu: function (unBindEvent) {
// Remove the previously added clickHandler from window element.
if (unBindEvent) {
$(window).off('click.speedMenu');
}
this.el.removeClass('is-opened');
this.speedButton.attr('tabindex', 0);
},
/**
* Sets new current speed for the speed control and triggers `speedchange`
* event if needed.
* @param {string|number} speed Speed to be set.
* @param {boolean} [silent] Sets the new speed without triggering
* `speedchange` event.
* @param {boolean} [forceUpdate] Updates the speed even if it's
* not differs from current speed.
*/
setSpeed: function (speed, silent, forceUpdate) {
if (speed !== this.currentSpeed || forceUpdate) {
this.speedsContainer
.find('li')
.removeClass('is-active')
.siblings("li[data-speed='" + speed + "']")
.addClass('is-active');
this.speedButton.find('.value').html(speed + 'x');
this.currentSpeed = speed;
if (!silent) {
this.el.trigger('speedchange', [speed, this.state.speed]);
}
}
},
/**
* Click event handler for the menu.
* @param {jquery Event} event
*/
clickMenuHandler: function (event) {
this.closeMenu();
return false;
},
/**
* Click event handler for speed links.
* @param {jquery Event} event
*/
clickLinkHandler: function (event) {
var speed = $(event.currentTarget).parent().data('speed');
this.closeMenu();
this.state.videoCommands.execute('speed', speed);
return false;
},
/**
* Mouseenter event handler for the menu.
* @param {jquery Event} event
*/
mouseEnterHandler: function (event) {
this.openMenu();
return false;
},
/**
* Mouseleave event handler for the menu.
* @param {jquery Event} event
*/
mouseLeaveHandler: function (event) {
// Only close the menu is no speed entry has focus.
if (!this.speedLinks.list.is(':focus')) {
this.closeMenu();
}
return false;
},
/**
* Keydown event handler for the menu.
* @param {jquery Event} event
*/
keyDownMenuHandler: function (event) {
var KEY = $.ui.keyCode,
keyCode = event.keyCode;
switch(keyCode) {
// Open menu and focus on last element of list above it.
case KEY.ENTER:
case KEY.SPACE:
case KEY.UP:
this.openMenu(true);
this.speedLinks.last().focus();
break;
// Close menu.
case KEY.ESCAPE:
this.closeMenu(true);
break;
}
// We do not stop propagation and default behavior on a TAB
// keypress.
return event.keyCode === KEY.TAB;
},
/**
* Keydown event handler for speed links.
* @param {jquery Event} event
*/
keyDownLinkHandler: function (event) {
// ALT key is used to change (alternate) the function of
// other pressed keys. In this, do nothing.
if (event.altKey) {
return true;
}
var KEY = $.ui.keyCode,
self = this,
parent = $(event.currentTarget).parent(),
index = parent.index(),
speed = parent.data('speed');
switch (event.keyCode) {
// Close menu.
case KEY.TAB:
// Closes menu after 25ms delay to change `tabindex` after
// finishing default behavior.
setTimeout(function () {
self.closeMenu(true);
}, 25);
return true;
// Close menu and give focus to speed control.
case KEY.ESCAPE:
this.closeMenu(true);
this.speedButton.focus();
return false;
// Scroll up menu, wrapping at the top. Keep menu open.
case KEY.UP:
// Shift + Arrows keyboard shortcut might be used by
// screen readers. In this, do nothing.
if (event.shiftKey) {
return true;
}
this.speedLinks.prev(index).focus();
return false;
// Scroll down menu, wrapping at the bottom. Keep menu
// open.
case KEY.DOWN:
// Shift + Arrows keyboard shortcut might be used by
// screen readers. In this, do nothing.
if (event.shiftKey) {
return true;
}
this.speedLinks.next(index).focus();
return false;
// Close menu, give focus to speed control and change
// speed.
case KEY.ENTER:
case KEY.SPACE:
this.closeMenu(true);
this.speedButton.focus();
this.setSpeed(this.state.speedToString(speed));
return false;
}
return true;
}
};
return SpeedControl;
});
}(RequireJS.requirejs, RequireJS.require, RequireJS.define)); |
module.exports = require('./lib/entry').default; |
// <API key>: GPL-2.0
#include <sound/soc-acpi.h>
#include <sound/<API key>.h>
#include "../skylake/skl.h"
static struct skl_machine_pdata skl_dmic_data;
static struct snd_soc_acpi_codecs kbl_codecs = {
.num_codecs = 1,
.codecs = {"10508825"}
};
static struct snd_soc_acpi_codecs kbl_poppy_codecs = {
.num_codecs = 1,
.codecs = {"10EC5663"}
};
static struct snd_soc_acpi_codecs <API key> = {
.num_codecs = 2,
.codecs = {"10EC5663", "10EC5514"}
};
static struct snd_soc_acpi_codecs <API key> = {
.num_codecs = 1,
.codecs = {"MX98357A"}
};
static struct snd_soc_acpi_codecs <API key> = {
.num_codecs = 1,
.codecs = {"MX98927"}
};
static struct snd_soc_acpi_codecs <API key> = {
.num_codecs = 1,
.codecs = {"MX98373"}
};
struct snd_soc_acpi_mach <API key>[] = {
{
.id = "INT343A",
.drv_name = "kbl_alc286s_i2s",
.fw_filename = "intel/dsp_fw_kbl.bin",
},
{
.id = "INT343B",
.drv_name = "kbl_n88l25_s4567",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &kbl_codecs,
.pdata = &skl_dmic_data,
},
{
.id = "MX98357A",
.drv_name = "kbl_n88l25_m98357a",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &kbl_codecs,
.pdata = &skl_dmic_data,
},
{
.id = "MX98927",
.drv_name = "kbl_r5514_5663_max",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &<API key>,
.pdata = &skl_dmic_data,
},
{
.id = "MX98927",
.drv_name = "kbl_rt5663_m98927",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &kbl_poppy_codecs,
.pdata = &skl_dmic_data,
},
{
.id = "10EC5663",
.drv_name = "kbl_rt5663",
.fw_filename = "intel/dsp_fw_kbl.bin",
},
{
.id = "DLGS7219",
.drv_name = "<API key>",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &<API key>,
.pdata = &skl_dmic_data,
},
{
.id = "DLGS7219",
.drv_name = "kbl_da7219_max98927",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &<API key>,
.pdata = &skl_dmic_data
},
{
.id = "10EC5660",
.drv_name = "kbl_rt5660",
.fw_filename = "intel/dsp_fw_kbl.bin",
},
{
.id = "10EC3277",
.drv_name = "kbl_rt5660",
.fw_filename = "intel/dsp_fw_kbl.bin",
},
{
.id = "DLGS7219",
.drv_name = "kbl_da7219_max98373",
.fw_filename = "intel/dsp_fw_kbl.bin",
.machine_quirk = <API key>,
.quirk_data = &<API key>,
.pdata = &skl_dmic_data
},
{
.id = "MX98373",
.drv_name = "kbl_max98373",
.fw_filename = "intel/dsp_fw_kbl.bin",
.pdata = &skl_dmic_data
},
{},
};
EXPORT_SYMBOL_GPL(<API key>);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Intel Common ACPI Match module"); |
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/audit.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/netlink.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include "audit.h"
/*
* Locking model:
*
* audit_filter_mutex:
* Synchronizes writes and blocking reads of audit's filterlist
* data. Rcu is used to traverse the filterlist and access
* contents of structs audit_entry, audit_watch and opaque
* LSM rules during filtering. If modified, these structures
* must be copied and replace their counterparts in the filterlist.
* An audit_parent struct is not accessed during filtering, so may
* be written directly provided audit_filter_mutex is held.
*/
/* Audit filter lists, defined in <linux/audit.h> */
struct list_head audit_filter_list[AUDIT_NR_FILTERS] = {
LIST_HEAD_INIT(audit_filter_list[0]),
LIST_HEAD_INIT(audit_filter_list[1]),
LIST_HEAD_INIT(audit_filter_list[2]),
LIST_HEAD_INIT(audit_filter_list[3]),
LIST_HEAD_INIT(audit_filter_list[4]),
LIST_HEAD_INIT(audit_filter_list[5]),
#if AUDIT_NR_FILTERS != 6
#error Fix audit_filter_list initialiser
#endif
};
static struct list_head audit_rules_list[AUDIT_NR_FILTERS] = {
LIST_HEAD_INIT(audit_rules_list[0]),
LIST_HEAD_INIT(audit_rules_list[1]),
LIST_HEAD_INIT(audit_rules_list[2]),
LIST_HEAD_INIT(audit_rules_list[3]),
LIST_HEAD_INIT(audit_rules_list[4]),
LIST_HEAD_INIT(audit_rules_list[5]),
};
DEFINE_MUTEX(audit_filter_mutex);
static void <API key>(struct audit_field *f)
{
switch (f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
kfree(f->lsm_str);
<API key>(f->lsm_rule);
}
}
static inline void audit_free_rule(struct audit_entry *e)
{
int i;
struct audit_krule *erule = &e->rule;
/* some rules don't have associated watches */
if (erule->watch)
audit_put_watch(erule->watch);
if (erule->fields)
for (i = 0; i < erule->field_count; i++)
<API key>(&erule->fields[i]);
kfree(erule->fields);
kfree(erule->filterkey);
kfree(e);
}
void audit_free_rule_rcu(struct rcu_head *head)
{
struct audit_entry *e = container_of(head, struct audit_entry, rcu);
audit_free_rule(e);
}
/* Initialize an audit filterlist entry. */
static inline struct audit_entry *audit_init_entry(u32 field_count)
{
struct audit_entry *entry;
struct audit_field *fields;
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (unlikely(!entry))
return NULL;
fields = kcalloc(field_count, sizeof(*fields), GFP_KERNEL);
if (unlikely(!fields)) {
kfree(entry);
return NULL;
}
entry->rule.fields = fields;
return entry;
}
/* Unpack a filter field's string representation from user-space
* buffer. */
char *audit_unpack_string(void **bufp, size_t *remain, size_t len)
{
char *str;
if (!*bufp || (len == 0) || (len > *remain))
return ERR_PTR(-EINVAL);
/* Of the currently implemented string fields, PATH_MAX
* defines the longest valid length.
*/
if (len > PATH_MAX)
return ERR_PTR(-ENAMETOOLONG);
str = kmalloc(len + 1, GFP_KERNEL);
if (unlikely(!str))
return ERR_PTR(-ENOMEM);
memcpy(str, *bufp, len);
str[len] = 0;
*bufp += len;
*remain -= len;
return str;
}
/* Translate an inode field to kernel representation. */
static inline int audit_to_inode(struct audit_krule *krule,
struct audit_field *f)
{
if (krule->listnr != AUDIT_FILTER_EXIT ||
krule->inode_f || krule->watch || krule->tree ||
(f->op != Audit_equal && f->op != Audit_not_equal))
return -EINVAL;
krule->inode_f = f;
return 0;
}
static __u32 *classes[<API key>];
int __init <API key>(int class, unsigned *list)
{
__u32 *p = kcalloc(AUDIT_BITMASK_SIZE, sizeof(__u32), GFP_KERNEL);
if (!p)
return -ENOMEM;
while (*list != ~0U) {
unsigned n = *list++;
if (n >= AUDIT_BITMASK_SIZE * 32 - <API key>) {
kfree(p);
return -EINVAL;
}
p[AUDIT_WORD(n)] |= AUDIT_BIT(n);
}
if (class >= <API key> || classes[class]) {
kfree(p);
return -EINVAL;
}
classes[class] = p;
return 0;
}
int audit_match_class(int class, unsigned syscall)
{
if (unlikely(syscall >= AUDIT_BITMASK_SIZE * 32))
return 0;
if (unlikely(class >= <API key> || !classes[class]))
return 0;
return classes[class][AUDIT_WORD(syscall)] & AUDIT_BIT(syscall);
}
#ifdef CONFIG_AUDITSYSCALL
static inline int <API key>(int class, u32 *mask)
{
int i;
if (classes[class]) {
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
if (mask[i] & classes[class][i])
return 0;
}
return 1;
}
static int audit_match_signal(struct audit_entry *entry)
{
struct audit_field *arch = entry->rule.arch_f;
if (!arch) {
/* When arch is unspecified, we must check both masks on biarch
* as syscall number alone is ambiguous. */
return (<API key>(AUDIT_CLASS_SIGNAL,
entry->rule.mask) &&
<API key>(<API key>,
entry->rule.mask));
}
switch(audit_classify_arch(arch->val)) {
case 0: /* native */
return (<API key>(AUDIT_CLASS_SIGNAL,
entry->rule.mask));
case 1: /* 32bit on biarch */
return (<API key>(<API key>,
entry->rule.mask));
default:
return 1;
}
}
#endif
/* Common user-space to kernel rule translation. */
static inline struct audit_entry *<API key>(struct audit_rule_data *rule)
{
unsigned listnr;
struct audit_entry *entry;
int i, err;
err = -EINVAL;
listnr = rule->flags & ~<API key>;
switch(listnr) {
default:
goto exit_err;
#ifdef CONFIG_AUDITSYSCALL
case AUDIT_FILTER_ENTRY:
if (rule->action == AUDIT_ALWAYS)
goto exit_err;
case AUDIT_FILTER_EXIT:
case AUDIT_FILTER_TASK:
#endif
case AUDIT_FILTER_USER:
case AUDIT_FILTER_TYPE:
;
}
if (unlikely(rule->action == AUDIT_POSSIBLE)) {
pr_err("AUDIT_POSSIBLE is deprecated\n");
goto exit_err;
}
if (rule->action != AUDIT_NEVER && rule->action != AUDIT_ALWAYS)
goto exit_err;
if (rule->field_count > AUDIT_MAX_FIELDS)
goto exit_err;
err = -ENOMEM;
entry = audit_init_entry(rule->field_count);
if (!entry)
goto exit_err;
entry->rule.flags = rule->flags & <API key>;
entry->rule.listnr = listnr;
entry->rule.action = rule->action;
entry->rule.field_count = rule->field_count;
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
entry->rule.mask[i] = rule->mask[i];
for (i = 0; i < <API key>; i++) {
int bit = AUDIT_BITMASK_SIZE * 32 - i - 1;
__u32 *p = &entry->rule.mask[AUDIT_WORD(bit)];
__u32 *class;
if (!(*p & AUDIT_BIT(bit)))
continue;
*p &= ~AUDIT_BIT(bit);
class = classes[i];
if (class) {
int j;
for (j = 0; j < AUDIT_BITMASK_SIZE; j++)
entry->rule.mask[j] |= class[j];
}
}
return entry;
exit_err:
return ERR_PTR(err);
}
static u32 audit_ops[] =
{
[Audit_equal] = AUDIT_EQUAL,
[Audit_not_equal] = AUDIT_NOT_EQUAL,
[Audit_bitmask] = AUDIT_BIT_MASK,
[Audit_bittest] = AUDIT_BIT_TEST,
[Audit_lt] = AUDIT_LESS_THAN,
[Audit_gt] = AUDIT_GREATER_THAN,
[Audit_le] = <API key>,
[Audit_ge] = <API key>,
};
static u32 audit_to_op(u32 op)
{
u32 n;
for (n = Audit_equal; n < Audit_bad && audit_ops[n] != op; n++)
;
return n;
}
/* check if an audit field is valid */
static int audit_field_valid(struct audit_entry *entry, struct audit_field *f)
{
switch(f->type) {
case AUDIT_MSGTYPE:
if (entry->rule.listnr != AUDIT_FILTER_TYPE &&
entry->rule.listnr != AUDIT_FILTER_USER)
return -EINVAL;
break;
};
switch(f->type) {
default:
return -EINVAL;
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_LOGINUID:
case AUDIT_OBJ_UID:
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_OBJ_GID:
case AUDIT_PID:
case AUDIT_PERS:
case AUDIT_MSGTYPE:
case AUDIT_PPID:
case AUDIT_DEVMAJOR:
case AUDIT_DEVMINOR:
case AUDIT_EXIT:
case AUDIT_SUCCESS:
case AUDIT_INODE:
/* bit ops are only useful on syscall args */
if (f->op == Audit_bitmask || f->op == Audit_bittest)
return -EINVAL;
break;
case AUDIT_ARG0:
case AUDIT_ARG1:
case AUDIT_ARG2:
case AUDIT_ARG3:
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
case AUDIT_WATCH:
case AUDIT_DIR:
case AUDIT_FILTERKEY:
break;
case AUDIT_LOGINUID_SET:
if ((f->val != 0) && (f->val != 1))
return -EINVAL;
/* FALL THROUGH */
case AUDIT_ARCH:
if (f->op != Audit_not_equal && f->op != Audit_equal)
return -EINVAL;
break;
case AUDIT_PERM:
if (f->val & ~15)
return -EINVAL;
break;
case AUDIT_FILETYPE:
if (f->val & ~S_IFMT)
return -EINVAL;
break;
case AUDIT_FIELD_COMPARE:
if (f->val > <API key>)
return -EINVAL;
break;
case AUDIT_EXE:
if (f->op != Audit_equal)
return -EINVAL;
if (entry->rule.listnr != AUDIT_FILTER_EXIT)
return -EINVAL;
break;
};
return 0;
}
/* Translate struct audit_rule_data to kernel's rule representation. */
static struct audit_entry *audit_data_to_entry(struct audit_rule_data *data,
size_t datasz)
{
int err = 0;
struct audit_entry *entry;
void *bufp;
size_t remain = datasz - sizeof(struct audit_rule_data);
int i;
char *str;
struct audit_fsnotify_mark *audit_mark;
entry = <API key>(data);
if (IS_ERR(entry))
goto exit_nofree;
bufp = data->buf;
for (i = 0; i < data->field_count; i++) {
struct audit_field *f = &entry->rule.fields[i];
err = -EINVAL;
f->op = audit_to_op(data->fieldflags[i]);
if (f->op == Audit_bad)
goto exit_free;
f->type = data->fields[i];
f->val = data->values[i];
/* Support legacy tests for a valid loginuid */
if ((f->type == AUDIT_LOGINUID) && (f->val == AUDIT_UID_UNSET)) {
f->type = AUDIT_LOGINUID_SET;
f->val = 0;
entry->rule.pflags |= <API key>;
}
err = audit_field_valid(entry, f);
if (err)
goto exit_free;
err = -EINVAL;
switch (f->type) {
case AUDIT_LOGINUID:
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_OBJ_UID:
f->uid = make_kuid(current_user_ns(), f->val);
if (!uid_valid(f->uid))
goto exit_free;
break;
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_OBJ_GID:
f->gid = make_kgid(current_user_ns(), f->val);
if (!gid_valid(f->gid))
goto exit_free;
break;
case AUDIT_ARCH:
entry->rule.arch_f = f;
break;
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = <API key>(f->type, f->op, str,
(void **)&f->lsm_rule);
/* Keep currently invalid fields around in case they
* become valid after a policy reload. */
if (err == -EINVAL) {
pr_warn("audit rule for LSM \'%s\' is invalid\n",
str);
err = 0;
}
if (err) {
kfree(str);
goto exit_free;
} else
f->lsm_str = str;
break;
case AUDIT_WATCH:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = audit_to_watch(&entry->rule, str, f->val, f->op);
if (err) {
kfree(str);
goto exit_free;
}
break;
case AUDIT_DIR:
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
err = audit_make_tree(&entry->rule, str, f->op);
kfree(str);
if (err)
goto exit_free;
break;
case AUDIT_INODE:
err = audit_to_inode(&entry->rule, f);
if (err)
goto exit_free;
break;
case AUDIT_FILTERKEY:
if (entry->rule.filterkey || f->val > AUDIT_MAX_KEY_LEN)
goto exit_free;
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str))
goto exit_free;
entry->rule.buflen += f->val;
entry->rule.filterkey = str;
break;
case AUDIT_EXE:
if (entry->rule.exe || f->val > PATH_MAX)
goto exit_free;
str = audit_unpack_string(&bufp, &remain, f->val);
if (IS_ERR(str)) {
err = PTR_ERR(str);
goto exit_free;
}
entry->rule.buflen += f->val;
audit_mark = audit_alloc_mark(&entry->rule, str, f->val);
if (IS_ERR(audit_mark)) {
kfree(str);
err = PTR_ERR(audit_mark);
goto exit_free;
}
entry->rule.exe = audit_mark;
break;
}
}
if (entry->rule.inode_f && entry->rule.inode_f->op == Audit_not_equal)
entry->rule.inode_f = NULL;
exit_nofree:
return entry;
exit_free:
if (entry->rule.tree)
audit_put_tree(entry->rule.tree); /* that's the temporary one */
if (entry->rule.exe)
audit_remove_mark(entry->rule.exe); /* that's the template one */
audit_free_rule(entry);
return ERR_PTR(err);
}
/* Pack a filter field's string representation into data block. */
static inline size_t audit_pack_string(void **bufp, const char *str)
{
size_t len = strlen(str);
memcpy(*bufp, str, len);
*bufp += len;
return len;
}
/* Translate kernel rule representation to struct audit_rule_data. */
static struct audit_rule_data *audit_krule_to_data(struct audit_krule *krule)
{
struct audit_rule_data *data;
void *bufp;
int i;
data = kmalloc(sizeof(*data) + krule->buflen, GFP_KERNEL);
if (unlikely(!data))
return NULL;
memset(data, 0, sizeof(*data));
data->flags = krule->flags | krule->listnr;
data->action = krule->action;
data->field_count = krule->field_count;
bufp = data->buf;
for (i = 0; i < data->field_count; i++) {
struct audit_field *f = &krule->fields[i];
data->fields[i] = f->type;
data->fieldflags[i] = audit_ops[f->op];
switch(f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
data->buflen += data->values[i] =
audit_pack_string(&bufp, f->lsm_str);
break;
case AUDIT_WATCH:
data->buflen += data->values[i] =
audit_pack_string(&bufp,
audit_watch_path(krule->watch));
break;
case AUDIT_DIR:
data->buflen += data->values[i] =
audit_pack_string(&bufp,
audit_tree_path(krule->tree));
break;
case AUDIT_FILTERKEY:
data->buflen += data->values[i] =
audit_pack_string(&bufp, krule->filterkey);
break;
case AUDIT_EXE:
data->buflen += data->values[i] =
audit_pack_string(&bufp, audit_mark_path(krule->exe));
break;
case AUDIT_LOGINUID_SET:
if (krule->pflags & <API key> && !f->val) {
data->fields[i] = AUDIT_LOGINUID;
data->values[i] = AUDIT_UID_UNSET;
break;
}
/* fallthrough if set */
default:
data->values[i] = f->val;
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++) data->mask[i] = krule->mask[i];
return data;
}
/* Compare two rules in kernel format. Considered success if rules
* don't match. */
static int audit_compare_rule(struct audit_krule *a, struct audit_krule *b)
{
int i;
if (a->flags != b->flags ||
a->pflags != b->pflags ||
a->listnr != b->listnr ||
a->action != b->action ||
a->field_count != b->field_count)
return 1;
for (i = 0; i < a->field_count; i++) {
if (a->fields[i].type != b->fields[i].type ||
a->fields[i].op != b->fields[i].op)
return 1;
switch(a->fields[i].type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
if (strcmp(a->fields[i].lsm_str, b->fields[i].lsm_str))
return 1;
break;
case AUDIT_WATCH:
if (strcmp(audit_watch_path(a->watch),
audit_watch_path(b->watch)))
return 1;
break;
case AUDIT_DIR:
if (strcmp(audit_tree_path(a->tree),
audit_tree_path(b->tree)))
return 1;
break;
case AUDIT_FILTERKEY:
/* both filterkeys exist based on above type compare */
if (strcmp(a->filterkey, b->filterkey))
return 1;
break;
case AUDIT_EXE:
/* both paths exist based on above type compare */
if (strcmp(audit_mark_path(a->exe),
audit_mark_path(b->exe)))
return 1;
break;
case AUDIT_UID:
case AUDIT_EUID:
case AUDIT_SUID:
case AUDIT_FSUID:
case AUDIT_LOGINUID:
case AUDIT_OBJ_UID:
if (!uid_eq(a->fields[i].uid, b->fields[i].uid))
return 1;
break;
case AUDIT_GID:
case AUDIT_EGID:
case AUDIT_SGID:
case AUDIT_FSGID:
case AUDIT_OBJ_GID:
if (!gid_eq(a->fields[i].gid, b->fields[i].gid))
return 1;
break;
default:
if (a->fields[i].val != b->fields[i].val)
return 1;
}
}
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
if (a->mask[i] != b->mask[i])
return 1;
return 0;
}
/* Duplicate LSM field information. The lsm_rule is opaque, so must be
* re-initialized. */
static inline int <API key>(struct audit_field *df,
struct audit_field *sf)
{
int ret = 0;
char *lsm_str;
/* our own copy of lsm_str */
lsm_str = kstrdup(sf->lsm_str, GFP_KERNEL);
if (unlikely(!lsm_str))
return -ENOMEM;
df->lsm_str = lsm_str;
/* our own (refreshed) copy of lsm_rule */
ret = <API key>(df->type, df->op, df->lsm_str,
(void **)&df->lsm_rule);
/* Keep currently invalid fields around in case they
* become valid after a policy reload. */
if (ret == -EINVAL) {
pr_warn("audit rule for LSM \'%s\' is invalid\n",
df->lsm_str);
ret = 0;
}
return ret;
}
/* Duplicate an audit rule. This will be a deep copy with the exception
* of the watch - that pointer is carried over. The LSM specific fields
* will be updated in the copy. The point is to be able to replace the old
* rule with the new rule in the filterlist, then free the old rule.
* The rlist element is undefined; list manipulations are handled apart from
* the initial copy. */
struct audit_entry *audit_dupe_rule(struct audit_krule *old)
{
u32 fcount = old->field_count;
struct audit_entry *entry;
struct audit_krule *new;
char *fk;
int i, err = 0;
entry = audit_init_entry(fcount);
if (unlikely(!entry))
return ERR_PTR(-ENOMEM);
new = &entry->rule;
new->flags = old->flags;
new->pflags = old->pflags;
new->listnr = old->listnr;
new->action = old->action;
for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
new->mask[i] = old->mask[i];
new->prio = old->prio;
new->buflen = old->buflen;
new->inode_f = old->inode_f;
new->field_count = old->field_count;
/*
* note that we are OK with not refcounting here; audit_match_tree()
* never dereferences tree and we can't get false positives there
* since we'd have to have rule gone from the list *and* removed
* before the chunks found by lookup had been allocated, i.e. before
* the beginning of list scan.
*/
new->tree = old->tree;
memcpy(new->fields, old->fields, sizeof(struct audit_field) * fcount);
/* deep copy this information, updating the lsm_rule fields, because
* the originals will all be freed when the old rule is freed. */
for (i = 0; i < fcount; i++) {
switch (new->fields[i].type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
err = <API key>(&new->fields[i],
&old->fields[i]);
break;
case AUDIT_FILTERKEY:
fk = kstrdup(old->filterkey, GFP_KERNEL);
if (unlikely(!fk))
err = -ENOMEM;
else
new->filterkey = fk;
break;
case AUDIT_EXE:
err = audit_dupe_exe(new, old);
break;
}
if (err) {
if (new->exe)
audit_remove_mark(new->exe);
audit_free_rule(entry);
return ERR_PTR(err);
}
}
if (old->watch) {
audit_get_watch(old->watch);
new->watch = old->watch;
}
return entry;
}
/* Find an existing audit rule.
* Caller must hold audit_filter_mutex to prevent stale rule data. */
static struct audit_entry *audit_find_rule(struct audit_entry *entry,
struct list_head **p)
{
struct audit_entry *e, *found = NULL;
struct list_head *list;
int h;
if (entry->rule.inode_f) {
h = audit_hash_ino(entry->rule.inode_f->val);
*p = list = &audit_inode_hash[h];
} else if (entry->rule.watch) {
/* we don't know the inode number, so must walk entire hash */
for (h = 0; h < AUDIT_INODE_BUCKETS; h++) {
list = &audit_inode_hash[h];
list_for_each_entry(e, list, list)
if (!audit_compare_rule(&entry->rule, &e->rule)) {
found = e;
goto out;
}
}
goto out;
} else {
*p = list = &audit_filter_list[entry->rule.listnr];
}
list_for_each_entry(e, list, list)
if (!audit_compare_rule(&entry->rule, &e->rule)) {
found = e;
goto out;
}
out:
return found;
}
static u64 prio_low = ~0ULL/2;
static u64 prio_high = ~0ULL/2 - 1;
/* Add rule to given filterlist if not a duplicate. */
static inline int audit_add_rule(struct audit_entry *entry)
{
struct audit_entry *e;
struct audit_watch *watch = entry->rule.watch;
struct audit_tree *tree = entry->rule.tree;
struct list_head *list;
int err = 0;
#ifdef CONFIG_AUDITSYSCALL
int dont_count = 0;
/* If either of these, don't count towards total */
if (entry->rule.listnr == AUDIT_FILTER_USER ||
entry->rule.listnr == AUDIT_FILTER_TYPE)
dont_count = 1;
#endif
mutex_lock(&audit_filter_mutex);
e = audit_find_rule(entry, &list);
if (e) {
mutex_unlock(&audit_filter_mutex);
err = -EEXIST;
/* normally audit_add_tree_rule() will free it on failure */
if (tree)
audit_put_tree(tree);
return err;
}
if (watch) {
/* audit_filter_mutex is dropped and re-taken during this call */
err = audit_add_watch(&entry->rule, &list);
if (err) {
mutex_unlock(&audit_filter_mutex);
/*
* normally audit_add_tree_rule() will free it
* on failure
*/
if (tree)
audit_put_tree(tree);
return err;
}
}
if (tree) {
err = audit_add_tree_rule(&entry->rule);
if (err) {
mutex_unlock(&audit_filter_mutex);
return err;
}
}
entry->rule.prio = ~0ULL;
if (entry->rule.listnr == AUDIT_FILTER_EXIT) {
if (entry->rule.flags & <API key>)
entry->rule.prio = ++prio_high;
else
entry->rule.prio = --prio_low;
}
if (entry->rule.flags & <API key>) {
list_add(&entry->rule.list,
&audit_rules_list[entry->rule.listnr]);
list_add_rcu(&entry->list, list);
entry->rule.flags &= ~<API key>;
} else {
list_add_tail(&entry->rule.list,
&audit_rules_list[entry->rule.listnr]);
list_add_tail_rcu(&entry->list, list);
}
#ifdef CONFIG_AUDITSYSCALL
if (!dont_count)
audit_n_rules++;
if (!audit_match_signal(entry))
audit_signals++;
#endif
mutex_unlock(&audit_filter_mutex);
return err;
}
/* Remove an existing rule from filterlist. */
int audit_del_rule(struct audit_entry *entry)
{
struct audit_entry *e;
struct audit_tree *tree = entry->rule.tree;
struct list_head *list;
int ret = 0;
#ifdef CONFIG_AUDITSYSCALL
int dont_count = 0;
/* If either of these, don't count towards total */
if (entry->rule.listnr == AUDIT_FILTER_USER ||
entry->rule.listnr == AUDIT_FILTER_TYPE)
dont_count = 1;
#endif
mutex_lock(&audit_filter_mutex);
e = audit_find_rule(entry, &list);
if (!e) {
ret = -ENOENT;
goto out;
}
if (e->rule.watch)
<API key>(&e->rule);
if (e->rule.tree)
<API key>(&e->rule);
if (e->rule.exe)
<API key>(&e->rule);
#ifdef CONFIG_AUDITSYSCALL
if (!dont_count)
audit_n_rules
if (!audit_match_signal(entry))
audit_signals
#endif
list_del_rcu(&e->list);
list_del(&e->rule.list);
call_rcu(&e->rcu, audit_free_rule_rcu);
out:
mutex_unlock(&audit_filter_mutex);
if (tree)
audit_put_tree(tree); /* that's the temporary one */
return ret;
}
/* List rules using struct audit_rule_data. */
static void audit_list_rules(__u32 portid, int seq, struct sk_buff_head *q)
{
struct sk_buff *skb;
struct audit_krule *r;
int i;
/* This is a blocking read, so use audit_filter_mutex instead of rcu
* iterator to sync with list writers. */
for (i=0; i<AUDIT_NR_FILTERS; i++) {
list_for_each_entry(r, &audit_rules_list[i], list) {
struct audit_rule_data *data;
data = audit_krule_to_data(r);
if (unlikely(!data))
break;
skb = audit_make_reply(portid, seq, AUDIT_LIST_RULES,
0, 1, data,
sizeof(*data) + data->buflen);
if (skb)
skb_queue_tail(q, skb);
kfree(data);
}
}
skb = audit_make_reply(portid, seq, AUDIT_LIST_RULES, 1, 1, NULL, 0);
if (skb)
skb_queue_tail(q, skb);
}
/* Log rule additions and removals */
static void <API key>(char *action, struct audit_krule *rule, int res)
{
struct audit_buffer *ab;
uid_t loginuid = from_kuid(&init_user_ns, audit_get_loginuid(current));
unsigned int sessionid = audit_get_sessionid(current);
if (!audit_enabled)
return;
ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
if (!ab)
return;
audit_log_format(ab, "auid=%u ses=%u" ,loginuid, sessionid);
<API key>(ab);
audit_log_format(ab, " op=");
audit_log_string(ab, action);
audit_log_key(ab, rule->filterkey);
audit_log_format(ab, " list=%d res=%d", rule->listnr, res);
audit_log_end(ab);
}
/**
* audit_rule_change - apply all rules to the specified message type
* @type: audit message type
* @portid: target port id for netlink audit messages
* @seq: netlink audit message sequence (serial) number
* @data: payload data
* @datasz: size of payload data
*/
int audit_rule_change(int type, __u32 portid, int seq, void *data,
size_t datasz)
{
int err = 0;
struct audit_entry *entry;
entry = audit_data_to_entry(data, datasz);
if (IS_ERR(entry))
return PTR_ERR(entry);
switch (type) {
case AUDIT_ADD_RULE:
err = audit_add_rule(entry);
<API key>("add_rule", &entry->rule, !err);
break;
case AUDIT_DEL_RULE:
err = audit_del_rule(entry);
<API key>("remove_rule", &entry->rule, !err);
break;
default:
err = -EINVAL;
WARN_ON(1);
}
if (err || type == AUDIT_DEL_RULE) {
if (entry->rule.exe)
audit_remove_mark(entry->rule.exe);
audit_free_rule(entry);
}
return err;
}
/**
* <API key> - list the audit rules
* @request_skb: skb of request we are replying to (used to target the reply)
* @seq: netlink audit message sequence (serial) number
*/
int <API key>(struct sk_buff *request_skb, int seq)
{
u32 portid = NETLINK_CB(request_skb).portid;
struct net *net = sock_net(NETLINK_CB(request_skb).sk);
struct task_struct *tsk;
struct audit_netlink_list *dest;
int err = 0;
/* We can't just spew out the rules here because we might fill
* the available socket buffer space and deadlock waiting for
* auditctl to read from it... which isn't ever going to
* happen if we're actually running in the context of auditctl
* trying to _send_ the stuff */
dest = kmalloc(sizeof(struct audit_netlink_list), GFP_KERNEL);
if (!dest)
return -ENOMEM;
dest->net = get_net(net);
dest->portid = portid;
skb_queue_head_init(&dest->q);
mutex_lock(&audit_filter_mutex);
audit_list_rules(portid, seq, &dest->q);
mutex_unlock(&audit_filter_mutex);
tsk = kthread_run(audit_send_list, dest, "audit_send_list");
if (IS_ERR(tsk)) {
skb_queue_purge(&dest->q);
kfree(dest);
err = PTR_ERR(tsk);
}
return err;
}
int audit_comparator(u32 left, u32 op, u32 right)
{
switch (op) {
case Audit_equal:
return (left == right);
case Audit_not_equal:
return (left != right);
case Audit_lt:
return (left < right);
case Audit_le:
return (left <= right);
case Audit_gt:
return (left > right);
case Audit_ge:
return (left >= right);
case Audit_bitmask:
return (left & right);
case Audit_bittest:
return ((left & right) == right);
default:
BUG();
return 0;
}
}
int <API key>(kuid_t left, u32 op, kuid_t right)
{
switch (op) {
case Audit_equal:
return uid_eq(left, right);
case Audit_not_equal:
return !uid_eq(left, right);
case Audit_lt:
return uid_lt(left, right);
case Audit_le:
return uid_lte(left, right);
case Audit_gt:
return uid_gt(left, right);
case Audit_ge:
return uid_gte(left, right);
case Audit_bitmask:
case Audit_bittest:
default:
BUG();
return 0;
}
}
int <API key>(kgid_t left, u32 op, kgid_t right)
{
switch (op) {
case Audit_equal:
return gid_eq(left, right);
case Audit_not_equal:
return !gid_eq(left, right);
case Audit_lt:
return gid_lt(left, right);
case Audit_le:
return gid_lte(left, right);
case Audit_gt:
return gid_gt(left, right);
case Audit_ge:
return gid_gte(left, right);
case Audit_bitmask:
case Audit_bittest:
default:
BUG();
return 0;
}
}
/**
* parent_len - find the length of the parent portion of a pathname
* @path: pathname of which to determine length
*/
int parent_len(const char *path)
{
int plen;
const char *p;
plen = strlen(path);
if (plen == 0)
return plen;
/* disregard trailing slashes */
p = path + plen - 1;
while ((*p == '/') && (p > path))
p
/* walk backward until we find the next slash or hit beginning */
while ((*p != '/') && (p > path))
p
/* did we find a slash? Then increment to include it in path */
if (*p == '/')
p++;
return p - path;
}
/**
* <API key> - compare given dentry name with last component in
* given path. Return of 0 indicates a match.
* @dname: dentry name that we're comparing
* @path: full pathname that we're comparing
* @parentlen: length of the parent if known. Passing in AUDIT_NAME_FULL
* here indicates that we must compute this value.
*/
int <API key>(const char *dname, const char *path, int parentlen)
{
int dlen, pathlen;
const char *p;
dlen = strlen(dname);
pathlen = strlen(path);
if (pathlen < dlen)
return 1;
parentlen = parentlen == AUDIT_NAME_FULL ? parent_len(path) : parentlen;
if (pathlen - parentlen != dlen)
return 1;
p = path + parentlen;
return strncmp(p, dname, dlen);
}
static int <API key>(struct audit_krule *rule, int type,
enum audit_state *state)
{
int i;
for (i = 0; i < rule->field_count; i++) {
struct audit_field *f = &rule->fields[i];
pid_t pid;
int result = 0;
u32 sid;
switch (f->type) {
case AUDIT_PID:
pid = task_pid_nr(current);
result = audit_comparator(pid, f->op, f->val);
break;
case AUDIT_UID:
result = <API key>(current_uid(), f->op, f->uid);
break;
case AUDIT_GID:
result = <API key>(current_gid(), f->op, f->gid);
break;
case AUDIT_LOGINUID:
result = <API key>(audit_get_loginuid(current),
f->op, f->uid);
break;
case AUDIT_LOGINUID_SET:
result = audit_comparator(audit_loginuid_set(current),
f->op, f->val);
break;
case AUDIT_MSGTYPE:
result = audit_comparator(type, f->op, f->val);
break;
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
if (f->lsm_rule) {
<API key>(current, &sid);
result = <API key>(sid,
f->type,
f->op,
f->lsm_rule,
NULL);
}
break;
}
if (!result)
return 0;
}
switch (rule->action) {
case AUDIT_NEVER: *state = AUDIT_DISABLED; break;
case AUDIT_ALWAYS: *state = <API key>; break;
}
return 1;
}
int audit_filter_user(int type)
{
enum audit_state state = AUDIT_DISABLED;
struct audit_entry *e;
int rc, ret;
ret = 1; /* Audit by default */
rcu_read_lock();
<API key>(e, &audit_filter_list[AUDIT_FILTER_USER], list) {
rc = <API key>(&e->rule, type, &state);
if (rc) {
if (rc > 0 && state == AUDIT_DISABLED)
ret = 0;
break;
}
}
rcu_read_unlock();
return ret;
}
int audit_filter_type(int type)
{
struct audit_entry *e;
int result = 0;
rcu_read_lock();
if (list_empty(&audit_filter_list[AUDIT_FILTER_TYPE]))
goto unlock_and_return;
<API key>(e, &audit_filter_list[AUDIT_FILTER_TYPE],
list) {
int i;
for (i = 0; i < e->rule.field_count; i++) {
struct audit_field *f = &e->rule.fields[i];
if (f->type == AUDIT_MSGTYPE) {
result = audit_comparator(type, f->op, f->val);
if (!result)
break;
}
}
if (result)
goto unlock_and_return;
}
unlock_and_return:
rcu_read_unlock();
return result;
}
static int update_lsm_rule(struct audit_krule *r)
{
struct audit_entry *entry = container_of(r, struct audit_entry, rule);
struct audit_entry *nentry;
int err = 0;
if (!<API key>(r))
return 0;
nentry = audit_dupe_rule(r);
if (entry->rule.exe)
audit_remove_mark(entry->rule.exe);
if (IS_ERR(nentry)) {
/* save the first error encountered for the
* return value */
err = PTR_ERR(nentry);
audit_panic("error updating LSM filters");
if (r->watch)
list_del(&r->rlist);
list_del_rcu(&entry->list);
list_del(&r->list);
} else {
if (r->watch || r->tree)
list_replace_init(&r->rlist, &nentry->rule.rlist);
list_replace_rcu(&entry->list, &nentry->list);
list_replace(&r->list, &nentry->rule.list);
}
call_rcu(&entry->rcu, audit_free_rule_rcu);
return err;
}
/* This function will re-initialize the lsm_rule field of all applicable rules.
* It will traverse the filter lists serarching for rules that contain LSM
* specific filter fields. When such a rule is found, it is copied, the
* LSM field is re-initialized, and the old rule is replaced with the
* updated rule. */
int <API key>(void)
{
struct audit_krule *r, *n;
int i, err = 0;
/* audit_filter_mutex synchronizes the writers */
mutex_lock(&audit_filter_mutex);
for (i = 0; i < AUDIT_NR_FILTERS; i++) {
<API key>(r, n, &audit_rules_list[i], list) {
int res = update_lsm_rule(r);
if (!err)
err = res;
}
}
mutex_unlock(&audit_filter_mutex);
return err;
} |
from social.backends.oauth import BaseOAuth1
class XingOAuth(BaseOAuth1):
"""Xing OAuth authentication backend"""
name = 'xing'
AUTHORIZATION_URL = 'https://api.xing.com/v1/authorize'
REQUEST_TOKEN_URL = 'https:
SCOPE_SEPARATOR = '+'
EXTRA_DATA = [
('id', 'id'),
('user_id', 'user_id')
]
def get_user_details(self, response):
"""Return user details from Xing account"""
email = response.get('email', '')
fullname, first_name, last_name = self.get_user_names(
first_name=response['first_name'],
last_name=response['last_name']
)
return {'username': first_name + last_name,
'fullname': fullname,
'first_name': first_name,
'last_name': last_name,
'email': email}
def user_data(self, access_token, *args, **kwargs):
"""Return user data provided"""
profile = self.get_json(
'https://api.xing.com/v1/users/me.json',
auth=self.oauth_auth(access_token)
)['users'][0]
return {
'user_id': profile['id'],
'id': profile['id'],
'first_name': profile['first_name'],
'last_name': profile['last_name'],
'email': profile['active_email']
} |
#include <linux/export.h>
#include <linux/wireless.h>
#include <linux/nl80211.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <linux/slab.h>
#include <net/iw_handler.h>
#include <net/cfg80211.h>
#include <net/cfg80211-wext.h>
#include "wext-compat.h"
#include "core.h"
int <API key>(struct net_device *dev,
struct iw_request_info *info,
char *name, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *sband;
bool is_ht = false, is_a = false, is_b = false, is_g = false;
if (!wdev)
return -EOPNOTSUPP;
sband = wdev->wiphy->bands[IEEE80211_BAND_5GHZ];
if (sband) {
is_a = true;
is_ht |= sband->ht_cap.ht_supported;
}
sband = wdev->wiphy->bands[IEEE80211_BAND_2GHZ];
if (sband) {
int i;
for (i = 0; i < sband->n_bitrates; i++) {
if (sband->bitrates[i].bitrate == 10)
is_b = true;
if (sband->bitrates[i].bitrate == 60)
is_g = true;
}
is_ht |= sband->ht_cap.ht_supported;
}
strcpy(name, "IEEE 802.11");
if (is_a)
strcat(name, "a");
if (is_b)
strcat(name, "b");
if (is_g)
strcat(name, "g");
if (is_ht)
strcat(name, "n");
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
int <API key>(struct net_device *dev, struct iw_request_info *info,
u32 *mode, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev;
struct vif_params vifparams;
enum nl80211_iftype type;
int ret;
rdev = wiphy_to_dev(wdev->wiphy);
switch (*mode) {
case IW_MODE_INFRA:
type = <API key>;
break;
case IW_MODE_ADHOC:
type = <API key>;
break;
case IW_MODE_REPEAT:
type = NL80211_IFTYPE_WDS;
break;
case IW_MODE_MONITOR:
type = <API key>;
break;
default:
return -EINVAL;
}
if (type == wdev->iftype)
return 0;
memset(&vifparams, 0, sizeof(vifparams));
cfg80211_lock_rdev(rdev);
ret = <API key>(rdev, dev, type, NULL, &vifparams);
<API key>(rdev);
return ret;
}
EXPORT_SYMBOL_GPL(<API key>);
int <API key>(struct net_device *dev, struct iw_request_info *info,
u32 *mode, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (!wdev)
return -EOPNOTSUPP;
switch (wdev->iftype) {
case NL80211_IFTYPE_AP:
*mode = IW_MODE_MASTER;
break;
case <API key>:
*mode = IW_MODE_INFRA;
break;
case <API key>:
*mode = IW_MODE_ADHOC;
break;
case <API key>:
*mode = IW_MODE_MONITOR;
break;
case NL80211_IFTYPE_WDS:
*mode = IW_MODE_REPEAT;
break;
case <API key>:
*mode = IW_MODE_SECOND;
break;
default:
*mode = IW_MODE_AUTO;
break;
}
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct iw_range *range = (struct iw_range *) extra;
enum ieee80211_band band;
int i, c = 0;
if (!wdev)
return -EOPNOTSUPP;
data->length = sizeof(struct iw_range);
memset(range, 0, sizeof(struct iw_range));
range->we_version_compiled = WIRELESS_EXT;
range->we_version_source = 21;
range->retry_capa = IW_RETRY_LIMIT;
range->retry_flags = IW_RETRY_LIMIT;
range->min_retry = 0;
range->max_retry = 255;
range->min_rts = 0;
range->max_rts = 2347;
range->min_frag = 256;
range->max_frag = 2346;
range->max_encoding_tokens = 4;
range->max_qual.updated = <API key>;
switch (wdev->wiphy->signal_type) {
case <API key>:
break;
case <API key>:
range->max_qual.level = -110;
range->max_qual.qual = 70;
range->avg_qual.qual = 35;
range->max_qual.updated |= IW_QUAL_DBM;
range->max_qual.updated |= <API key>;
range->max_qual.updated |= <API key>;
break;
case <API key>:
range->max_qual.level = 100;
range->max_qual.qual = 100;
range->avg_qual.qual = 50;
range->max_qual.updated |= <API key>;
range->max_qual.updated |= <API key>;
break;
}
range->avg_qual.level = range->max_qual.level / 2;
range->avg_qual.noise = range->max_qual.noise / 2;
range->avg_qual.updated = range->max_qual.updated;
for (i = 0; i < wdev->wiphy->n_cipher_suites; i++) {
switch (wdev->wiphy->cipher_suites[i]) {
case <API key>:
range->enc_capa |= (<API key> |
IW_ENC_CAPA_WPA);
break;
case <API key>:
range->enc_capa |= (<API key> |
IW_ENC_CAPA_WPA2);
break;
case <API key>:
range->encoding_size[range->num_encoding_sizes++] =
WLAN_KEY_LEN_WEP40;
break;
case <API key>:
range->encoding_size[range->num_encoding_sizes++] =
WLAN_KEY_LEN_WEP104;
break;
}
}
for (band = 0; band < IEEE80211_NUM_BANDS; band ++) {
struct <API key> *sband;
sband = wdev->wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_channels && c < IW_MAX_FREQUENCIES; i++) {
struct ieee80211_channel *chan = &sband->channels[i];
if (!(chan->flags & <API key>)) {
range->freq[c].i =
<API key>(
chan->center_freq);
range->freq[c].m = chan->center_freq;
range->freq[c].e = 6;
c++;
}
}
}
range->num_channels = c;
range->num_frequency = c;
<API key>(range->event_capa);
IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWAP);
IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWSCAN);
if (wdev->wiphy->max_scan_ssids > 0)
range->scan_capa |= IW_SCAN_CAPA_ESSID;
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
int cfg80211_wext_freq(struct wiphy *wiphy, struct iw_freq *freq)
{
if (freq->e == 0) {
enum ieee80211_band band = IEEE80211_BAND_2GHZ;
if (freq->m < 0)
return 0;
if (freq->m > 14)
band = IEEE80211_BAND_5GHZ;
return <API key>(freq->m, band);
} else {
int i, div = 1000000;
for (i = 0; i < freq->e; i++)
div /= 10;
if (div <= 0)
return -EINVAL;
return freq->m / div;
}
}
int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rts, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
u32 orts = wdev->wiphy->rts_threshold;
int err;
if (rts->disabled || !rts->fixed)
wdev->wiphy->rts_threshold = (u32) -1;
else if (rts->value < 0)
return -EINVAL;
else
wdev->wiphy->rts_threshold = rts->value;
err = rdev->ops->set_wiphy_params(wdev->wiphy,
<API key>);
if (err)
wdev->wiphy->rts_threshold = orts;
return err;
}
EXPORT_SYMBOL_GPL(<API key>);
int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rts, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
rts->value = wdev->wiphy->rts_threshold;
rts->disabled = rts->value == (u32) -1;
rts->fixed = 1;
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *frag, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
u32 ofrag = wdev->wiphy->frag_threshold;
int err;
if (frag->disabled || !frag->fixed)
wdev->wiphy->frag_threshold = (u32) -1;
else if (frag->value < 256)
return -EINVAL;
else {
wdev->wiphy->frag_threshold = frag->value & ~0x1;
}
err = rdev->ops->set_wiphy_params(wdev->wiphy,
<API key>);
if (err)
wdev->wiphy->frag_threshold = ofrag;
return err;
}
EXPORT_SYMBOL_GPL(<API key>);
int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *frag, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
frag->value = wdev->wiphy->frag_threshold;
frag->disabled = frag->value == (u32) -1;
frag->fixed = 1;
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *retry, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
u32 changed = 0;
u8 olong = wdev->wiphy->retry_long;
u8 oshort = wdev->wiphy->retry_short;
int err;
if (retry->disabled ||
(retry->flags & IW_RETRY_TYPE) != IW_RETRY_LIMIT)
return -EINVAL;
if (retry->flags & IW_RETRY_LONG) {
wdev->wiphy->retry_long = retry->value;
changed |= <API key>;
} else if (retry->flags & IW_RETRY_SHORT) {
wdev->wiphy->retry_short = retry->value;
changed |= <API key>;
} else {
wdev->wiphy->retry_short = retry->value;
wdev->wiphy->retry_long = retry->value;
changed |= <API key>;
changed |= <API key>;
}
if (!changed)
return 0;
err = rdev->ops->set_wiphy_params(wdev->wiphy, changed);
if (err) {
wdev->wiphy->retry_short = oshort;
wdev->wiphy->retry_long = olong;
}
return err;
}
int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *retry, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
retry->disabled = 0;
if (retry->flags == 0 || (retry->flags & IW_RETRY_SHORT)) {
retry->flags |= IW_RETRY_LIMIT;
retry->value = wdev->wiphy->retry_short;
if (wdev->wiphy->retry_long != wdev->wiphy->retry_short)
retry->flags |= IW_RETRY_LONG;
return 0;
}
if (retry->flags & IW_RETRY_LONG) {
retry->flags = IW_RETRY_LIMIT | IW_RETRY_LONG;
retry->value = wdev->wiphy->retry_long;
}
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
static int <API key>(struct <API key> *rdev,
struct net_device *dev, bool pairwise,
const u8 *addr, bool remove, bool tx_key,
int idx, struct key_params *params)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err, i;
bool rejoin = false;
if (pairwise && !addr)
return -EINVAL;
if (!wdev->wext.keys) {
wdev->wext.keys = kzalloc(sizeof(*wdev->wext.keys),
GFP_KERNEL);
if (!wdev->wext.keys)
return -ENOMEM;
for (i = 0; i < 6; i++)
wdev->wext.keys->params[i].key =
wdev->wext.keys->data[i];
}
if (wdev->iftype != <API key> &&
wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (params->cipher == <API key>) {
if (!wdev->current_bss)
return -ENOLINK;
if (!rdev->ops-><API key>)
return -EOPNOTSUPP;
if (idx < 4 || idx > 5)
return -EINVAL;
} else if (idx < 0 || idx > 3)
return -EINVAL;
if (remove) {
err = 0;
if (wdev->current_bss) {
if (idx == wdev->wext.default_key &&
wdev->iftype == <API key>) {
<API key>(rdev, wdev->netdev, true);
rejoin = true;
}
if (!pairwise && addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
err = -ENOENT;
else
err = rdev->ops->del_key(&rdev->wiphy, dev, idx,
pairwise, addr);
}
wdev->wext.connect.privacy = false;
if (err == -ENOENT)
err = 0;
if (!err) {
if (!addr) {
wdev->wext.keys->params[idx].key_len = 0;
wdev->wext.keys->params[idx].cipher = 0;
}
if (idx == wdev->wext.default_key)
wdev->wext.default_key = -1;
else if (idx == wdev->wext.default_mgmt_key)
wdev->wext.default_mgmt_key = -1;
}
if (!err && rejoin)
err = <API key>(rdev, wdev);
return err;
}
if (addr)
tx_key = false;
if (<API key>(rdev, params, idx, pairwise, addr))
return -EINVAL;
err = 0;
if (wdev->current_bss)
err = rdev->ops->add_key(&rdev->wiphy, dev, idx,
pairwise, addr, params);
if (err)
return err;
if (!addr) {
wdev->wext.keys->params[idx] = *params;
memcpy(wdev->wext.keys->data[idx],
params->key, params->key_len);
wdev->wext.keys->params[idx].key =
wdev->wext.keys->data[idx];
}
if ((params->cipher == <API key> ||
params->cipher == <API key>) &&
(tx_key || (!addr && wdev->wext.default_key == -1))) {
if (wdev->current_bss) {
if (wdev->iftype == <API key> &&
wdev->wext.default_key == -1) {
<API key>(rdev, wdev->netdev, true);
rejoin = true;
}
err = rdev->ops->set_default_key(&rdev->wiphy, dev,
idx, true, true);
}
if (!err) {
wdev->wext.default_key = idx;
if (rejoin)
err = <API key>(rdev, wdev);
}
return err;
}
if (params->cipher == <API key> &&
(tx_key || (!addr && wdev->wext.default_mgmt_key == -1))) {
if (wdev->current_bss)
err = rdev->ops-><API key>(&rdev->wiphy,
dev, idx);
if (!err)
wdev->wext.default_mgmt_key = idx;
return err;
}
return 0;
}
static int <API key>(struct <API key> *rdev,
struct net_device *dev, bool pairwise,
const u8 *addr, bool remove, bool tx_key,
int idx, struct key_params *params)
{
int err;
mutex_lock(&rdev->devlist_mtx);
wdev_lock(dev->ieee80211_ptr);
err = <API key>(rdev, dev, pairwise, addr,
remove, tx_key, idx, params);
wdev_unlock(dev->ieee80211_ptr);
mutex_unlock(&rdev->devlist_mtx);
return err;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *keybuf)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
int idx, err;
bool remove = false;
struct key_params params;
if (wdev->iftype != <API key> &&
wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->del_key ||
!rdev->ops->add_key ||
!rdev->ops->set_default_key)
return -EOPNOTSUPP;
idx = erq->flags & IW_ENCODE_INDEX;
if (idx == 0) {
idx = wdev->wext.default_key;
if (idx < 0)
idx = 0;
} else if (idx < 1 || idx > 4)
return -EINVAL;
else
idx
if (erq->flags & IW_ENCODE_DISABLED)
remove = true;
else if (erq->length == 0) {
err = 0;
wdev_lock(wdev);
if (wdev->current_bss)
err = rdev->ops->set_default_key(&rdev->wiphy, dev,
idx, true, true);
if (!err)
wdev->wext.default_key = idx;
wdev_unlock(wdev);
return err;
}
memset(¶ms, 0, sizeof(params));
params.key = keybuf;
params.key_len = erq->length;
if (erq->length == 5)
params.cipher = <API key>;
else if (erq->length == 13)
params.cipher = <API key>;
else if (!remove)
return -EINVAL;
return <API key>(rdev, dev, false, NULL, remove,
wdev->wext.default_key == -1,
idx, ¶ms);
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct iw_encode_ext *ext = (struct iw_encode_ext *) extra;
const u8 *addr;
int idx;
bool remove = false;
struct key_params params;
u32 cipher;
if (wdev->iftype != <API key> &&
wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->del_key ||
!rdev->ops->add_key ||
!rdev->ops->set_default_key)
return -EOPNOTSUPP;
switch (ext->alg) {
case IW_ENCODE_ALG_NONE:
remove = true;
cipher = 0;
break;
case IW_ENCODE_ALG_WEP:
if (ext->key_len == 5)
cipher = <API key>;
else if (ext->key_len == 13)
cipher = <API key>;
else
return -EINVAL;
break;
case IW_ENCODE_ALG_TKIP:
cipher = <API key>;
break;
case IW_ENCODE_ALG_CCMP:
cipher = <API key>;
break;
case <API key>:
cipher = <API key>;
break;
default:
return -EOPNOTSUPP;
}
if (erq->flags & IW_ENCODE_DISABLED)
remove = true;
idx = erq->flags & IW_ENCODE_INDEX;
if (cipher == <API key>) {
if (idx < 4 || idx > 5) {
idx = wdev->wext.default_mgmt_key;
if (idx < 0)
return -EINVAL;
} else
idx
} else {
if (idx < 1 || idx > 4) {
idx = wdev->wext.default_key;
if (idx < 0)
return -EINVAL;
} else
idx
}
addr = ext->addr.sa_data;
if (<API key>(addr))
addr = NULL;
memset(¶ms, 0, sizeof(params));
params.key = ext->key;
params.key_len = ext->key_len;
params.cipher = cipher;
if (ext->ext_flags & <API key>) {
params.seq = ext->rx_seq;
params.seq_len = 6;
}
return <API key>(
rdev, dev,
!(ext->ext_flags & <API key>),
addr, remove,
ext->ext_flags & <API key>,
idx, ¶ms);
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *keybuf)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int idx;
if (wdev->iftype != <API key> &&
wdev->iftype != <API key>)
return -EOPNOTSUPP;
idx = erq->flags & IW_ENCODE_INDEX;
if (idx == 0) {
idx = wdev->wext.default_key;
if (idx < 0)
idx = 0;
} else if (idx < 1 || idx > 4)
return -EINVAL;
else
idx
erq->flags = idx + 1;
if (!wdev->wext.keys || !wdev->wext.keys->params[idx].cipher) {
erq->flags |= IW_ENCODE_DISABLED;
erq->length = 0;
return 0;
}
erq->length = min_t(size_t, erq->length,
wdev->wext.keys->params[idx].key_len);
memcpy(keybuf, wdev->wext.keys->params[idx].key, erq->length);
erq->flags |= IW_ENCODE_ENABLED;
return 0;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_freq *wextfreq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
int freq, err;
switch (wdev->iftype) {
case <API key>:
return <API key>(dev, info, wextfreq, extra);
case <API key>:
return <API key>(dev, info, wextfreq, extra);
case <API key>:
case NL80211_IFTYPE_WDS:
case <API key>:
freq = cfg80211_wext_freq(wdev->wiphy, wextfreq);
if (freq < 0)
return freq;
if (freq == 0)
return -EINVAL;
mutex_lock(&rdev->devlist_mtx);
wdev_lock(wdev);
err = cfg80211_set_freq(rdev, wdev, freq, NL80211_CHAN_NO_HT);
wdev_unlock(wdev);
mutex_unlock(&rdev->devlist_mtx);
return err;
default:
return -EOPNOTSUPP;
}
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_freq *freq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct ieee80211_channel *chan;
switch (wdev->iftype) {
case <API key>:
return <API key>(dev, info, freq, extra);
case <API key>:
return <API key>(dev, info, freq, extra);
case <API key>:
if (!rdev->ops->get_channel)
return -EINVAL;
chan = rdev->ops->get_channel(wdev->wiphy);
if (!chan)
return -EINVAL;
freq->m = chan->center_freq;
freq->e = 6;
return 0;
default:
if (!wdev->channel)
return -EINVAL;
freq->m = wdev->channel->center_freq;
freq->e = 6;
return 0;
}
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
enum <API key> type;
int dbm = 0;
if ((data->txpower.flags & IW_TXPOW_TYPE) != IW_TXPOW_DBM)
return -EINVAL;
if (data->txpower.flags & IW_TXPOW_RANGE)
return -EINVAL;
if (!rdev->ops->set_tx_power)
return -EOPNOTSUPP;
if (!data->txpower.disabled) {
rfkill_set_sw_state(rdev->rfkill, false);
if (data->txpower.fixed) {
if (data->txpower.value < 0)
return -EINVAL;
dbm = data->txpower.value;
type = <API key>;
} else {
if (data->txpower.value < 0) {
type = <API key>;
} else {
dbm = data->txpower.value;
type = <API key>;
}
}
} else {
rfkill_set_sw_state(rdev->rfkill, true);
schedule_work(&rdev->rfkill_sync);
return 0;
}
return rdev->ops->set_tx_power(wdev->wiphy, type, DBM_TO_MBM(dbm));
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
int err, val;
if ((data->txpower.flags & IW_TXPOW_TYPE) != IW_TXPOW_DBM)
return -EINVAL;
if (data->txpower.flags & IW_TXPOW_RANGE)
return -EINVAL;
if (!rdev->ops->get_tx_power)
return -EOPNOTSUPP;
err = rdev->ops->get_tx_power(wdev->wiphy, &val);
if (err)
return err;
data->txpower.fixed = 1;
data->txpower.disabled = rfkill_blocked(rdev->rfkill);
data->txpower.value = val;
data->txpower.flags = IW_TXPOW_DBM;
return 0;
}
static int <API key>(struct wireless_dev *wdev,
s32 auth_alg)
{
int nr_alg = 0;
if (!auth_alg)
return -EINVAL;
if (auth_alg & ~(IW_<API key> |
<API key> |
IW_AUTH_ALG_LEAP))
return -EINVAL;
if (auth_alg & IW_<API key>) {
nr_alg++;
wdev->wext.connect.auth_type = NL80211_<API key>;
}
if (auth_alg & <API key>) {
nr_alg++;
wdev->wext.connect.auth_type = <API key>;
}
if (auth_alg & IW_AUTH_ALG_LEAP) {
nr_alg++;
wdev->wext.connect.auth_type = NL80211_<API key>;
}
if (nr_alg > 1)
wdev->wext.connect.auth_type = <API key>;
return 0;
}
static int <API key>(struct wireless_dev *wdev, u32 wpa_versions)
{
if (wpa_versions & ~(IW_<API key> |
IW_<API key>|
IW_<API key>))
return -EINVAL;
if ((wpa_versions & IW_<API key>) &&
(wpa_versions & (IW_<API key>|
IW_<API key>)))
return -EINVAL;
if (wpa_versions & IW_<API key>)
wdev->wext.connect.crypto.wpa_versions &=
~(<API key>|<API key>);
if (wpa_versions & IW_<API key>)
wdev->wext.connect.crypto.wpa_versions |=
<API key>;
if (wpa_versions & IW_<API key>)
wdev->wext.connect.crypto.wpa_versions |=
<API key>;
return 0;
}
static int <API key>(struct wireless_dev *wdev, u32 cipher)
{
if (cipher & <API key>)
wdev->wext.connect.crypto.cipher_group =
<API key>;
else if (cipher & <API key>)
wdev->wext.connect.crypto.cipher_group =
<API key>;
else if (cipher & IW_AUTH_CIPHER_TKIP)
wdev->wext.connect.crypto.cipher_group =
<API key>;
else if (cipher & IW_AUTH_CIPHER_CCMP)
wdev->wext.connect.crypto.cipher_group =
<API key>;
else if (cipher & IW_<API key>)
wdev->wext.connect.crypto.cipher_group =
<API key>;
else if (cipher & IW_AUTH_CIPHER_NONE)
wdev->wext.connect.crypto.cipher_group = 0;
else
return -EINVAL;
return 0;
}
static int <API key>(struct wireless_dev *wdev, u32 cipher)
{
int nr_ciphers = 0;
u32 *ciphers_pairwise = wdev->wext.connect.crypto.ciphers_pairwise;
if (cipher & <API key>) {
ciphers_pairwise[nr_ciphers] = <API key>;
nr_ciphers++;
}
if (cipher & <API key>) {
ciphers_pairwise[nr_ciphers] = <API key>;
nr_ciphers++;
}
if (cipher & IW_AUTH_CIPHER_TKIP) {
ciphers_pairwise[nr_ciphers] = <API key>;
nr_ciphers++;
}
if (cipher & IW_AUTH_CIPHER_CCMP) {
ciphers_pairwise[nr_ciphers] = <API key>;
nr_ciphers++;
}
if (cipher & IW_<API key>) {
ciphers_pairwise[nr_ciphers] = <API key>;
nr_ciphers++;
}
BUILD_BUG_ON(<API key> < 5);
wdev->wext.connect.crypto.n_ciphers_pairwise = nr_ciphers;
return 0;
}
static int <API key>(struct wireless_dev *wdev, u32 key_mgt)
{
int nr_akm_suites = 0;
if (key_mgt & ~(IW_<API key> |
<API key>))
return -EINVAL;
if (key_mgt & IW_<API key>) {
wdev->wext.connect.crypto.akm_suites[nr_akm_suites] =
<API key>;
nr_akm_suites++;
}
if (key_mgt & <API key>) {
wdev->wext.connect.crypto.akm_suites[nr_akm_suites] =
WLAN_AKM_SUITE_PSK;
nr_akm_suites++;
}
wdev->wext.connect.crypto.n_akm_suites = nr_akm_suites;
return 0;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (wdev->iftype != <API key>)
return -EOPNOTSUPP;
switch (data->flags & IW_AUTH_INDEX) {
case IW_<API key>:
wdev->wext.connect.privacy = data->value;
return 0;
case IW_AUTH_WPA_VERSION:
return <API key>(wdev, data->value);
case <API key>:
return <API key>(wdev, data->value);
case IW_AUTH_KEY_MGMT:
return <API key>(wdev, data->value);
case IW_<API key>:
return <API key>(wdev, data->value);
case <API key>:
return <API key>(wdev, data->value);
case IW_AUTH_WPA_ENABLED:
case IW_<API key>:
case IW_<API key>:
case IW_AUTH_MFP:
return 0;
default:
return -EOPNOTSUPP;
}
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *data, char *extra)
{
return -EOPNOTSUPP;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *wrq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
bool ps = wdev->ps;
int timeout = wdev->ps_timeout;
int err;
if (wdev->iftype != <API key>)
return -EINVAL;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
if (wrq->disabled) {
ps = false;
} else {
switch (wrq->flags & IW_POWER_MODE) {
case IW_POWER_ON:
case IW_POWER_MODE:
case IW_POWER_ALL_R:
ps = true;
break;
default:
return -EINVAL;
}
if (wrq->flags & ~(IW_POWER_MODE | IW_POWER_TIMEOUT))
return -EINVAL;
if (wrq->flags & IW_POWER_TIMEOUT)
timeout = wrq->value / 1000;
}
err = rdev->ops->set_power_mgmt(wdev->wiphy, dev, ps, timeout);
if (err)
return err;
wdev->ps = ps;
wdev->ps_timeout = timeout;
return 0;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *wrq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
wrq->disabled = !wdev->ps;
return 0;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
int err;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_WDS))
return -EINVAL;
if (addr->sa_family != ARPHRD_ETHER)
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
if (!rdev->ops->set_wds_peer)
return -EOPNOTSUPP;
err = rdev->ops->set_wds_peer(wdev->wiphy, dev, (u8 *) &addr->sa_data);
if (err)
return err;
memcpy(&wdev->wext.bssid, (u8 *) &addr->sa_data, ETH_ALEN);
return 0;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_WDS))
return -EINVAL;
addr->sa_family = ARPHRD_ETHER;
memcpy(&addr->sa_data, wdev->wext.bssid, ETH_ALEN);
return 0;
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rate, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct <API key> mask;
u32 fixed, maxrate;
struct <API key> *sband;
int band, ridx;
bool match = false;
if (!rdev->ops->set_bitrate_mask)
return -EOPNOTSUPP;
memset(&mask, 0, sizeof(mask));
fixed = 0;
maxrate = (u32)-1;
if (rate->value < 0) {
} else if (rate->fixed) {
fixed = rate->value / 100000;
} else {
maxrate = rate->value / 100000;
}
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
sband = wdev->wiphy->bands[band];
if (sband == NULL)
continue;
for (ridx = 0; ridx < sband->n_bitrates; ridx++) {
struct ieee80211_rate *srate = &sband->bitrates[ridx];
if (fixed == srate->bitrate) {
mask.control[band].legacy = 1 << ridx;
match = true;
break;
}
if (srate->bitrate <= maxrate) {
mask.control[band].legacy |= 1 << ridx;
match = true;
}
}
}
if (!match)
return -EINVAL;
return rdev->ops->set_bitrate_mask(wdev->wiphy, dev, NULL, &mask);
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rate, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
static struct station_info sinfo;
u8 addr[ETH_ALEN];
int err;
if (wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->get_station)
return -EOPNOTSUPP;
err = 0;
wdev_lock(wdev);
if (wdev->current_bss)
memcpy(addr, wdev->current_bss->pub.bssid, ETH_ALEN);
else
err = -EOPNOTSUPP;
wdev_unlock(wdev);
if (err)
return err;
err = rdev->ops->get_station(&rdev->wiphy, dev, addr, &sinfo);
if (err)
return err;
if (!(sinfo.filled & <API key>))
return -EOPNOTSUPP;
rate->value = 100000 * <API key>(&sinfo.txrate);
return 0;
}
static struct iw_statistics *<API key>(struct net_device *dev)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
static struct iw_statistics wstats;
static struct station_info sinfo;
u8 bssid[ETH_ALEN];
if (dev->ieee80211_ptr->iftype != <API key>)
return NULL;
if (!rdev->ops->get_station)
return NULL;
wdev_lock(wdev);
if (!wdev->current_bss) {
wdev_unlock(wdev);
return NULL;
}
memcpy(bssid, wdev->current_bss->pub.bssid, ETH_ALEN);
wdev_unlock(wdev);
if (rdev->ops->get_station(&rdev->wiphy, dev, bssid, &sinfo))
return NULL;
memset(&wstats, 0, sizeof(wstats));
switch (rdev->wiphy.signal_type) {
case <API key>:
if (sinfo.filled & STATION_INFO_SIGNAL) {
int sig = sinfo.signal;
wstats.qual.updated |= <API key>;
wstats.qual.updated |= <API key>;
wstats.qual.updated |= IW_QUAL_DBM;
wstats.qual.level = sig;
if (sig < -110)
sig = -110;
else if (sig > -40)
sig = -40;
wstats.qual.qual = sig + 110;
break;
}
case <API key>:
if (sinfo.filled & STATION_INFO_SIGNAL) {
wstats.qual.updated |= <API key>;
wstats.qual.updated |= <API key>;
wstats.qual.level = sinfo.signal;
wstats.qual.qual = sinfo.signal;
break;
}
default:
wstats.qual.updated |= <API key>;
wstats.qual.updated |= <API key>;
}
wstats.qual.updated |= <API key>;
if (sinfo.filled & <API key>)
wstats.discard.misc = sinfo.rx_dropped_misc;
if (sinfo.filled & <API key>)
wstats.discard.retries = sinfo.tx_failed;
return &wstats;
}
static int cfg80211_wext_siwap(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *ap_addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
switch (wdev->iftype) {
case <API key>:
return <API key>(dev, info, ap_addr, extra);
case <API key>:
return <API key>(dev, info, ap_addr, extra);
case NL80211_IFTYPE_WDS:
return <API key>(dev, info, ap_addr, extra);
default:
return -EOPNOTSUPP;
}
}
static int cfg80211_wext_giwap(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *ap_addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
switch (wdev->iftype) {
case <API key>:
return <API key>(dev, info, ap_addr, extra);
case <API key>:
return <API key>(dev, info, ap_addr, extra);
case NL80211_IFTYPE_WDS:
return <API key>(dev, info, ap_addr, extra);
default:
return -EOPNOTSUPP;
}
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *ssid)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
switch (wdev->iftype) {
case <API key>:
return <API key>(dev, info, data, ssid);
case <API key>:
return <API key>(dev, info, data, ssid);
default:
return -EOPNOTSUPP;
}
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *ssid)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
data->flags = 0;
data->length = 0;
switch (wdev->iftype) {
case <API key>:
return <API key>(dev, info, data, ssid);
case <API key>:
return <API key>(dev, info, data, ssid);
default:
return -EOPNOTSUPP;
}
}
static int <API key>(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct cfg80211_pmksa cfg_pmksa;
struct iw_pmksa *pmksa = (struct iw_pmksa *)extra;
memset(&cfg_pmksa, 0, sizeof(struct cfg80211_pmksa));
if (wdev->iftype != <API key>)
return -EINVAL;
cfg_pmksa.bssid = pmksa->bssid.sa_data;
cfg_pmksa.pmkid = pmksa->pmkid;
switch (pmksa->cmd) {
case IW_PMKSA_ADD:
if (!rdev->ops->set_pmksa)
return -EOPNOTSUPP;
return rdev->ops->set_pmksa(&rdev->wiphy, dev, &cfg_pmksa);
case IW_PMKSA_REMOVE:
if (!rdev->ops->del_pmksa)
return -EOPNOTSUPP;
return rdev->ops->del_pmksa(&rdev->wiphy, dev, &cfg_pmksa);
case IW_PMKSA_FLUSH:
if (!rdev->ops->flush_pmksa)
return -EOPNOTSUPP;
return rdev->ops->flush_pmksa(&rdev->wiphy, dev);
default:
return -EOPNOTSUPP;
}
}
static const iw_handler cfg80211_handlers[] = {
[IW_IOCTL_IDX(SIOCGIWNAME)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWFREQ)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWFREQ)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWMODE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWMODE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWRANGE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWAP)] = (iw_handler) cfg80211_wext_siwap,
[IW_IOCTL_IDX(SIOCGIWAP)] = (iw_handler) cfg80211_wext_giwap,
[IW_IOCTL_IDX(SIOCSIWMLME)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWSCAN)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWSCAN)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWESSID)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWESSID)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWRATE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWRATE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWRTS)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWRTS)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWFRAG)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWFRAG)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWTXPOW)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWTXPOW)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWRETRY)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWRETRY)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWENCODE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWENCODE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWPOWER)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWPOWER)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWGENIE)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWAUTH)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCGIWAUTH)] = (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWENCODEEXT)]= (iw_handler) <API key>,
[IW_IOCTL_IDX(SIOCSIWPMKSA)] = (iw_handler) <API key>,
};
const struct iw_handler_def <API key> = {
.num_standard = ARRAY_SIZE(cfg80211_handlers),
.standard = cfg80211_handlers,
.get_wireless_stats = <API key>,
}; |
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class <API key> extends React.Component<IconBaseProps> { } |
(function($, undefined){
// TODO: -
// ARIA stuff: menuitem, menuitemcheckbox und menuitemradio
// create <menu> structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative
// determine html5 compatibility
$.support.htmlMenuitem = ('HTMLMenuItemElement' in window);
$.support.htmlCommand = ('HTMLCommandElement' in window);
$.support.eventSelectstart = ("onselectstart" in document.documentElement);
/* // should the need arise, test for css user-select
$.support.cssUserSelect = (function(){
var t = false,
e = document.createElement('div');
$.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) {
var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect',
prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select';
e.style.cssText = prop + ': text;';
if (e.style[propCC] == 'text') {
t = true;
return false;
}
return true;
});
return t;
})();
*/
var // currently active contextMenu trigger
$currentTrigger = null,
// is contextMenu initialized with at least one menu?
initialized = false,
// window handle
$win = $(window),
// number of registered menus
counter = 0,
// mapping selector to namespace
namespaces = {},
// mapping namespace to options
menus = {},
// custom command type handlers
types = {},
// default values
defaults = {
// selector of contextMenu trigger
selector: null,
// where to append the menu to
appendTo: null,
// method to trigger context menu ["right", "left", "hover"]
trigger: "right",
// hide menu when mouse leaves trigger / menu elements
autoHide: false,
// ms to wait before showing a hover-triggered context menu
delay: 200,
// determine position to show menu at
determinePosition: function($menu) {
// position to the lower middle of the trigger element
if ($.ui && $.ui.position) {
// .position() is provided as a jQuery UI utility
// (...and it won't work on hidden elements)
$menu.css('display', 'block').position({
my: "center top",
at: "center bottom",
of: this,
offset: "0 5",
collision: "fit"
}).css('display', 'none');
} else {
// determine contextMenu position
var offset = this.offset();
offset.top += this.outerHeight();
offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2;
$menu.css(offset);
}
},
// position menu
position: function(opt, x, y) {
var $this = this,
offset;
// determine contextMenu position
if (!x && !y) {
opt.determinePosition.call(this, opt.$menu);
return;
} else if (x === "maintain" && y === "maintain") {
// x and y must not be changed (after re-show on command click)
offset = opt.$menu.position();
} else {
// x and y are given (by mouse event)
var triggerIsFixed = opt.$trigger.parents().andSelf()
.filter(function() {
return $(this).css('position') == "fixed";
}).length;
if (triggerIsFixed) {
y -= $win.scrollTop();
x -= $win.scrollLeft();
}
offset = {top: y, left: x};
}
// correct offset if viewport demands it
var bottom = $win.scrollTop() + $win.height(),
right = $win.scrollLeft() + $win.width(),
height = opt.$menu.height(),
width = opt.$menu.width();
if (offset.top + height > bottom) {
offset.top -= height;
}
if (offset.left + width > right) {
offset.left -= width;
}
opt.$menu.css(offset);
},
// position the sub-menu
positionSubmenu: function($menu) {
if ($.ui && $.ui.position) {
// .position() is provided as a jQuery UI utility
// (...and it won't work on hidden elements)
$menu.css('display', 'block').position({
my: "left top",
at: "right top",
of: this,
collision: "fit"
}).css('display', '');
} else {
// determine contextMenu position
var offset = {
top: 0,
left: this.outerWidth()
};
$menu.css(offset);
}
},
// offset to add to zIndex
zIndex: 1,
// show hide animation settings
animation: {
duration: 50,
show: 'slideDown',
hide: 'slideUp'
},
// events
events: {
show: $.noop,
hide: $.noop
},
// default callback
callback: null,
// list of contextMenu items
items: {}
},
// mouse position for hover activation
hoveract = {
timer: null,
pageX: null,
pageY: null
},
// determine zIndex
zindex = function($t) {
var zin = 0,
$tt = $t;
while (true) {
zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0);
$tt = $tt.parent();
if (!$tt || !$tt.length || "html body".indexOf($tt.prop('nodeName').toLowerCase()) > -1 ) {
break;
}
}
return zin;
},
// event handlers
handle = {
// abort anything
abortevent: function(e){
e.preventDefault();
e.<API key>();
},
// contextmenu show dispatcher
contextmenu: function(e) {
var $this = $(this);
// disable actual context-menu
e.preventDefault();
e.<API key>();
// abort native-triggered events unless we're triggering on right click
if (e.data.trigger != 'right' && e.originalEvent) {
return;
}
if (!$this.hasClass('<API key>')) {
// theoretically need to fire a show event at <menu>
// http://www.whatwg.org/specs/web-apps/current-work/multipage/<API key>.html#context-menus
// var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this });
// e.data.$menu.trigger(evt);
$currentTrigger = $this;
if (e.data.build) {
var built = e.data.build($currentTrigger, e);
// abort if build() returned false
if (built === false) {
return;
}
// dynamically build menu on invocation
e.data = $.extend(true, {}, defaults, e.data, built || {});
// abort if there are no items to display
if (!e.data.items || $.isEmptyObject(e.data.items)) {
// Note: jQuery captures and ignores errors from event handlers
if (window.console) {
(console.error || console.log)("No items specified to show in contextMenu");
}
throw new Error('No Items sepcified');
}
// backreference for custom command type creation
e.data.$trigger = $currentTrigger;
op.create(e.data);
}
// show menu
op.show.call($this, e.data, e.pageX, e.pageY);
}
},
// contextMenu left-click trigger
click: function(e) {
e.preventDefault();
e.<API key>();
$(this).trigger(jQuery.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY }));
},
// contextMenu right-click trigger
mousedown: function(e) {
// register mouse down
var $this = $(this);
// hide any previous menus
if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) {
$currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide');
}
// activate on right click
if (e.button == 2) {
$currentTrigger = $this.data('contextMenuActive', true);
}
},
// contextMenu right-click trigger
mouseup: function(e) {
// show menu
var $this = $(this);
if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('<API key>')) {
e.preventDefault();
e.<API key>();
$currentTrigger = $this;
$this.trigger(jQuery.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY }));
}
$this.removeData('contextMenuActive');
},
// contextMenu hover trigger
mouseenter: function(e) {
var $this = $(this),
$related = $(e.relatedTarget),
$document = $(document);
// abort if we're coming from a menu
if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) {
return;
}
// abort if a menu is shown
if ($currentTrigger && $currentTrigger.length) {
return;
}
hoveract.pageX = e.pageX;
hoveract.pageY = e.pageY;
hoveract.data = e.data;
$document.on('mousemove.contextMenuShow', handle.mousemove);
hoveract.timer = setTimeout(function() {
hoveract.timer = null;
$document.off('mousemove.contextMenuShow');
$currentTrigger = $this;
$this.trigger(jQuery.Event("contextmenu", { data: hoveract.data, pageX: hoveract.pageX, pageY: hoveract.pageY }));
}, e.data.delay );
},
// contextMenu hover trigger
mousemove: function(e) {
hoveract.pageX = e.pageX;
hoveract.pageY = e.pageY;
},
// contextMenu hover trigger
mouseleave: function(e) {
// abort if we're leaving for a menu
var $related = $(e.relatedTarget);
if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) {
return;
}
try {
clearTimeout(hoveract.timer);
} catch(e) {}
hoveract.timer = null;
},
// click on layer to hide contextMenu
layerClick: function(e) {
var $this = $(this),
root = $this.data('contextMenuRoot'),
mouseup = false,
button = e.button,
x = e.pageX,
y = e.pageY,
target,
offset,
selectors;
e.preventDefault();
e.<API key>();
// This hack looks about as ugly as it is
// Firefox 12 (at least) fires the contextmenu event directly "after" mousedown
// for some reason `root.$layer.hide(); document.elementFromPoint()` causes this
// contextmenu event to be triggered on the uncovered element instead of on the
// layer (where every other sane browser, including Firefox nightly at the time)
// triggers the event. This workaround might be obsolete by September 2012.
$this.on('mouseup', function() {
mouseup = true;
});
setTimeout(function() {
var $window, hideshow;
// test if we need to reposition the menu
if ((root.trigger == 'left' && button == 0) || (root.trigger == 'right' && button == 2)) {
if (document.elementFromPoint) {
root.$layer.hide();
target = document.elementFromPoint(x, y);
root.$layer.show();
selectors = [];
for (var s in namespaces) {
selectors.push(s);
}
target = $(target).closest(selectors.join(', '));
if (target.length) {
if (target.is(root.$trigger[0])) {
root.position.call(root.$trigger, root, x, y);
return;
}
}
} else {
offset = root.$trigger.offset();
$window = $(window);
// while this looks kinda awful, it's the best way to avoid
// unnecessarily calculating any positions
offset.top += $window.scrollTop();
if (offset.top <= e.pageY) {
offset.left += $window.scrollLeft();
if (offset.left <= e.pageX) {
offset.bottom = offset.top + root.$trigger.outerHeight();
if (offset.bottom >= e.pageY) {
offset.right = offset.left + root.$trigger.outerWidth();
if (offset.right >= e.pageX) {
// reposition
root.position.call(root.$trigger, root, x, y);
return;
}
}
}
}
}
}
hideshow = function(e) {
if (e) {
e.preventDefault();
e.<API key>();
}
root.$menu.trigger('contextmenu:hide');
if (target && target.length) {
setTimeout(function() {
target.contextMenu({x: x, y: y});
}, 50);
}
};
if (mouseup) {
// mouseup has already happened
hideshow();
} else {
// remove only after mouseup has completed
$this.on('mouseup', hideshow);
}
}, 50);
},
// key handled :hover
keyStop: function(e, opt) {
if (!opt.isInput) {
e.preventDefault();
}
e.stopPropagation();
},
key: function(e) {
var opt = $currentTrigger.data('contextMenu') || {},
$children = opt.$menu.children(),
$round;
switch (e.keyCode) {
case 9:
case 38:
handle.keyStop(e, opt);
// if keyCode is [38 (up)] or [9 (tab) with shift]
if (opt.isInput) {
if (e.keyCode == 9 && e.shiftKey) {
e.preventDefault();
opt.$selected && opt.$selected.find('input, textarea, select').blur();
opt.$menu.trigger('prevcommand');
return;
} else if (e.keyCode == 38 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') {
// checkboxes don't capture this key
e.preventDefault();
return;
}
} else if (e.keyCode != 9 || e.shiftKey) {
opt.$menu.trigger('prevcommand');
return;
}
case 9: // tab
case 40: // down
handle.keyStop(e, opt);
if (opt.isInput) {
if (e.keyCode == 9) {
e.preventDefault();
opt.$selected && opt.$selected.find('input, textarea, select').blur();
opt.$menu.trigger('nextcommand');
return;
} else if (e.keyCode == 40 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') {
// checkboxes don't capture this key
e.preventDefault();
return;
}
} else {
opt.$menu.trigger('nextcommand');
return;
}
break;
case 37: // left
handle.keyStop(e, opt);
if (opt.isInput || !opt.$selected || !opt.$selected.length) {
break;
}
if (!opt.$selected.parent().hasClass('context-menu-root')) {
var $parent = opt.$selected.parent().parent();
opt.$selected.trigger('contextmenu:blur');
opt.$selected = $parent;
return;
}
break;
case 39: // right
handle.keyStop(e, opt);
if (opt.isInput || !opt.$selected || !opt.$selected.length) {
break;
}
var itemdata = opt.$selected.data('contextMenu') || {};
if (itemdata.$menu && opt.$selected.hasClass('<API key>')) {
opt.$selected = null;
itemdata.$selected = null;
itemdata.$menu.trigger('nextcommand');
return;
}
break;
case 35: // end
case 36: // home
if (opt.$selected && opt.$selected.find('input, textarea, select').length) {
return;
} else {
(opt.$selected && opt.$selected.parent() || opt.$menu)
.children(':not(.disabled, .not-selectable)')[e.keyCode == 36 ? 'first' : 'last']()
.trigger('contextmenu:focus');
e.preventDefault();
return;
}
break;
case 13: // enter
handle.keyStop(e, opt);
if (opt.isInput) {
if (opt.$selected && !opt.$selected.is('textarea, select')) {
e.preventDefault();
return;
}
break;
}
opt.$selected && opt.$selected.trigger('mouseup');
return;
case 32: // space
case 33: // page up
case 34: // page down
// prevent browser from scrolling down while menu is visible
handle.keyStop(e, opt);
return;
case 27: // esc
handle.keyStop(e, opt);
opt.$menu.trigger('contextmenu:hide');
return;
default: // 0-9, a-z
var k = (String.fromCharCode(e.keyCode)).toUpperCase();
if (opt.accesskeys[k]) {
// according to the specs accesskeys must be invoked immediately
opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu
? 'contextmenu:focus'
: 'mouseup'
);
return;
}
break;
}
// pass event to selected item,
// stop propagation to avoid endless recursion
e.stopPropagation();
opt.$selected && opt.$selected.trigger(e);
},
// select previous possible command in menu
prevItem: function(e) {
e.stopPropagation();
var opt = $(this).data('contextMenu') || {};
// obtain currently selected menu
if (opt.$selected) {
var $s = opt.$selected;
opt = opt.$selected.parent().data('contextMenu') || {};
opt.$selected = $s;
}
var $children = opt.$menu.children(),
$prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(),
$round = $prev;
// skip disabled
while ($prev.hasClass('disabled') || $prev.hasClass('not-selectable')) {
if ($prev.prev().length) {
$prev = $prev.prev();
} else {
$prev = $children.last();
}
if ($prev.is($round)) {
// break endless loop
return;
}
}
// leave current
if (opt.$selected) {
handle.itemMouseleave.call(opt.$selected.get(0), e);
}
// activate next
handle.itemMouseenter.call($prev.get(0), e);
// focus input
var $input = $prev.find('input, textarea, select');
if ($input.length) {
$input.focus();
}
},
// select next possible command in menu
nextItem: function(e) {
e.stopPropagation();
var opt = $(this).data('contextMenu') || {};
// obtain currently selected menu
if (opt.$selected) {
var $s = opt.$selected;
opt = opt.$selected.parent().data('contextMenu') || {};
opt.$selected = $s;
}
var $children = opt.$menu.children(),
$next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(),
$round = $next;
// skip disabled
while ($next.hasClass('disabled') || $next.hasClass('not-selectable')) {
if ($next.next().length) {
$next = $next.next();
} else {
$next = $children.first();
}
if ($next.is($round)) {
// break endless loop
return;
}
}
// leave current
if (opt.$selected) {
handle.itemMouseleave.call(opt.$selected.get(0), e);
}
// activate next
handle.itemMouseenter.call($next.get(0), e);
// focus input
var $input = $next.find('input, textarea, select');
if ($input.length) {
$input.focus();
}
},
// flag that we're inside an input so the key handler can act accordingly
focusInput: function(e) {
var $this = $(this).closest('.context-menu-item'),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
root.$selected = opt.$selected = $this;
root.isInput = opt.isInput = true;
},
// flag that we're inside an input so the key handler can act accordingly
blurInput: function(e) {
var $this = $(this).closest('.context-menu-item'),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
root.isInput = opt.isInput = false;
},
// :hover on menu
menuMouseenter: function(e) {
var root = $(this).data().contextMenuRoot;
root.hovering = true;
},
// :hover on menu
menuMouseleave: function(e) {
var root = $(this).data().contextMenuRoot;
if (root.$layer && root.$layer.is(e.relatedTarget)) {
root.hovering = false;
}
},
// :hover done manually so key handling is possible
itemMouseenter: function(e) {
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
root.hovering = true;
// abort if we're re-entering
if (e && root.$layer && root.$layer.is(e.relatedTarget)) {
e.preventDefault();
e.<API key>();
}
// make sure only one item is selected
(opt.$menu ? opt : root).$menu
.children('.hover').trigger('contextmenu:blur');
if ($this.hasClass('disabled') || $this.hasClass('not-selectable')) {
opt.$selected = null;
return;
}
$this.trigger('contextmenu:focus');
},
// :hover done manually so key handling is possible
itemMouseleave: function(e) {
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) {
root.$selected && root.$selected.trigger('contextmenu:blur');
e.preventDefault();
e.<API key>();
root.$selected = opt.$selected = opt.$node;
return;
}
$this.trigger('contextmenu:blur');
},
// contextMenu item click
itemClick: function(e) {
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot,
key = data.contextMenuKey,
callback;
// abort if the key is unknown or disabled or is a menu
if (!opt.items[key] || $this.hasClass('disabled') || $this.hasClass('<API key>')) {
return;
}
e.preventDefault();
e.<API key>();
if ($.isFunction(root.callbacks[key])) {
// item-specific callback
callback = root.callbacks[key];
} else if ($.isFunction(root.callback)) {
// default callback
callback = root.callback;
} else {
// no callback, no action
return;
}
// hide menu if callback doesn't stop that
if (callback.call(root.$trigger, key, root) !== false) {
root.$menu.trigger('contextmenu:hide');
} else if (root.$menu.parent().length) {
op.update.call(root.$trigger, root);
}
},
// ignore click events on input elements
inputClick: function(e) {
e.<API key>();
},
// hide <menu>
hideMenu: function(e, data) {
var root = $(this).data('contextMenuRoot');
op.hide.call(root.$trigger, root, data && data.force);
},
// focus <command>
focusItem: function(e) {
e.stopPropagation();
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
$this.addClass('hover')
.siblings('.hover').trigger('contextmenu:blur');
// remember selected
opt.$selected = root.$selected = $this;
// position sub-menu - do after show so dumb $.ui.position can keep up
if (opt.$node) {
root.positionSubmenu.call(opt.$node, opt.$menu);
}
},
// blur <command>
blurItem: function(e) {
e.stopPropagation();
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
$this.removeClass('hover');
opt.$selected = null;
}
},
// operations
op = {
show: function(opt, x, y) {
var $this = $(this),
offset,
css = {};
// hide any open menus
$('#context-menu-layer').trigger('mousedown');
// backreference for callbacks
opt.$trigger = $this;
// show event
if (opt.events.show.call($this, opt) === false) {
$currentTrigger = null;
return;
}
// create or update context menu
op.update.call($this, opt);
// position menu
opt.position.call($this, opt, x, y);
// make sure we're in front
if (opt.zIndex) {
css.zIndex = zindex($this) + opt.zIndex;
}
// add layer
op.layer.call(opt.$menu, opt, css.zIndex);
// adjust sub-menu zIndexes
opt.$menu.find('ul').css('zIndex', css.zIndex + 1);
// position and show context menu
opt.$menu.css( css )[opt.animation.show](opt.animation.duration);
// make options available
$this.data('contextMenu', opt);
// register key handler
$(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key);
// register autoHide handler
if (opt.autoHide) {
// trigger element coordinates
var pos = $this.position();
pos.right = pos.left + $this.outerWidth();
pos.bottom = pos.top + this.outerHeight();
// mouse position handler
$(document).on('mousemove.contextMenuAutoHide', function(e) {
if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) {
// if mouse in menu...
opt.$menu.trigger('contextmenu:hide');
}
});
}
},
hide: function(opt, force) {
var $this = $(this);
if (!opt) {
opt = $this.data('contextMenu') || {};
}
// hide event
if (!force && opt.events && opt.events.hide.call($this, opt) === false) {
return;
}
if (opt.$layer) {
// keep layer for a bit so the contextmenu event can be aborted properly by opera
setTimeout((function($layer){ return function(){
$layer.remove();
};
})(opt.$layer), 10);
try {
delete opt.$layer;
} catch(e) {
opt.$layer = null;
}
}
// remove handle
$currentTrigger = null;
// remove selected
opt.$menu.find('.hover').trigger('contextmenu:blur');
opt.$selected = null;
// unregister key and mouse handlers
$(document).off('.contextMenuAutoHide').off('keydown.contextMenu');
// hide menu
opt.$menu && opt.$menu[opt.animation.hide](opt.animation.duration);
// tear down dynamically built menu
if (opt.build) {
opt.$menu.remove();
$.each(opt, function(key, value) {
switch (key) {
case 'ns':
case 'selector':
case 'build':
case 'trigger':
return true;
default:
opt[key] = undefined;
try {
delete opt[key];
} catch (e) {}
return true;
}
});
}
},
create: function(opt, root) {
if (root === undefined) {
root = opt;
}
// create contextMenu
opt.$menu = $('<ul class="context-menu-list ' + (opt.className || "") + '"></ul>').data({
'contextMenu': opt,
'contextMenuRoot': root
});
$.each(['callbacks', 'commands', 'inputs'], function(i,k){
opt[k] = {};
if (!root[k]) {
root[k] = {};
}
});
root.accesskeys || (root.accesskeys = {});
// create contextMenu items
$.each(opt.items, function(key, item){
var $t = $('<li class="context-menu-item ' + (item.className || "") +'"></li>'),
$label = null,
$input = null;
item.$node = $t.data({
'contextMenu': opt,
'contextMenuRoot': root,
'contextMenuKey': key
});
// register accesskey
// NOTE: the accesskey attribute should be applicable to any element, but Safari5 and Chrome13 still can't do that
if (item.accesskey) {
var aks = splitAccesskey(item.accesskey);
for (var i=0, ak; ak = aks[i]; i++) {
if (!root.accesskeys[ak]) {
root.accesskeys[ak] = item;
item._name = item.name.replace(new RegExp('(' + ak + ')', 'i'), '<span class="<API key>">$1</span>');
break;
}
}
}
if (typeof item == "string") {
$t.addClass('<API key> not-selectable');
} else if (item.type && types[item.type]) {
// run custom type handler
types[item.type].call($t, item, opt, root);
// register commands
$.each([opt, root], function(i,k){
k.commands[key] = item;
if ($.isFunction(item.callback)) {
k.callbacks[key] = item.callback;
}
});
} else {
// add label for input
if (item.type == 'html') {
$t.addClass('context-menu-html not-selectable');
} else if (item.type) {
$label = $('<label></label>').appendTo($t);
$('<span></span>').html(item._name || item.name).appendTo($label);
$t.addClass('context-menu-input');
opt.hasTypes = true;
$.each([opt, root], function(i,k){
k.commands[key] = item;
k.inputs[key] = item;
});
} else if (item.items) {
item.type = 'sub';
}
switch (item.type) {
case 'text':
$input = $('<input type="text" value="1" name="context-menu-input-'+ key +'" value="">')
.val(item.value || "").appendTo($label);
break;
case 'textarea':
$input = $('<textarea name="context-menu-input-'+ key +'"></textarea>')
.val(item.value || "").appendTo($label);
if (item.height) {
$input.height(item.height);
}
break;
case 'checkbox':
$input = $('<input type="checkbox" value="1" name="context-menu-input-'+ key +'" value="">')
.val(item.value || "").prop("checked", !!item.selected).prependTo($label);
break;
case 'radio':
$input = $('<input type="radio" value="1" name="context-menu-input-'+ item.radio +'" value="">')
.val(item.value || "").prop("checked", !!item.selected).prependTo($label);
break;
case 'select':
$input = $('<select name="context-menu-input-'+ key +'">').appendTo($label);
if (item.options) {
$.each(item.options, function(value, text) {
$('<option></option>').val(value).text(text).appendTo($input);
});
$input.val(item.selected);
}
break;
case 'sub':
$('<span></span>').html(item._name || item.name).appendTo($t);
item.appendTo = item.$node;
op.create(item, root);
$t.data('contextMenu', item).addClass('<API key>');
item.callback = null;
break;
case 'html':
$(item.html).appendTo($t);
break;
default:
$.each([opt, root], function(i,k){
k.commands[key] = item;
if ($.isFunction(item.callback)) {
k.callbacks[key] = item.callback;
}
});
$('<span></span>').html(item._name || item.name || "").appendTo($t);
break;
}
// disable key listener in <input>
if (item.type && item.type != 'sub' && item.type != 'html') {
$input
.on('focus', handle.focusInput)
.on('blur', handle.blurInput);
if (item.events) {
$input.on(item.events);
}
}
// add icons
if (item.icon) {
$t.addClass("icon icon-" + item.icon);
}
}
// cache contained elements
item.$input = $input;
item.$label = $label;
// attach item to menu
$t.appendTo(opt.$menu);
// Disable text selection
if (!opt.hasTypes && $.support.eventSelectstart) {
// browsers support user-select: none,
// IE has a special event for text-selection
// browsers supporting neither will not be preventing text-selection
$t.on('selectstart.disableTextSelect', handle.abortevent);
}
});
// attach contextMenu to <body> (to bypass any possible overflow:hidden issues on parents of the trigger element)
if (!opt.$node) {
opt.$menu.css('display', 'none').addClass('context-menu-root');
}
opt.$menu.appendTo(opt.appendTo || document.body);
},
update: function(opt, root) {
var $this = this;
if (root === undefined) {
root = opt;
// determine widths of submenus, as CSS won't grow them automatically
// position:absolute > position:absolute; min-width:100; max-width:200; results in width: 100;
// kinda sucks hard...
opt.$menu.find('ul').andSelf().css({position: 'static', display: 'block'}).each(function(){
var $this = $(this);
$this.width($this.css('position', 'absolute').width())
.css('position', 'static');
}).css({position: '', display: ''});
}
// re-check disabled for each item
opt.$menu.children().each(function(){
var $item = $(this),
key = $item.data('contextMenuKey'),
item = opt.items[key],
disabled = ($.isFunction(item.disabled) && item.disabled.call($this, key, root)) || item.disabled === true;
// dis- / enable item
$item[disabled ? 'addClass' : 'removeClass']('disabled');
if (item.type) {
// dis- / enable input elements
$item.find('input, select, textarea').prop('disabled', disabled);
// update input states
switch (item.type) {
case 'text':
case 'textarea':
item.$input.val(item.value || "");
break;
case 'checkbox':
case 'radio':
item.$input.val(item.value || "").prop('checked', !!item.selected);
break;
case 'select':
item.$input.val(item.selected || "");
break;
}
}
if (item.$menu) {
// update sub-menu
op.update.call($this, item, root);
}
});
},
layer: function(opt, zIndex) {
// add transparent layer for click area
// filter and background for Internet Explorer, Issue
var $layer = opt.$layer = $('<div id="context-menu-layer" style="position:fixed; z-index:' + zIndex + '; top:0; left:0; opacity: 0; filter: alpha(opacity=0); background-color: #000;"></div>')
.css({height: $win.height(), width: $win.width(), display: 'block'})
.data('contextMenuRoot', opt)
.insertBefore(this)
.on('contextmenu', handle.abortevent)
.on('mousedown', handle.layerClick);
// IE6 doesn't know position:fixed;
if (!$.support.fixedPosition) {
$layer.css({
'position' : 'absolute',
'height' : $(document).height()
});
}
return $layer;
}
};
// split accesskey according to http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#assigned-access-key
function splitAccesskey(val) {
var t = val.split(/\s+/),
keys = [];
for (var i=0, k; k = t[i]; i++) {
k = k[0].toUpperCase(); // first character only
// theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it.
// a map to look up already used access keys would be nice
keys.push(k);
}
return keys;
}
// handle contextMenu triggers
$.fn.contextMenu = function(operation) {
if (operation === undefined) {
this.first().trigger('contextmenu');
} else if (operation.x && operation.y) {
this.first().trigger(jQuery.Event("contextmenu", {pageX: operation.x, pageY: operation.y}));
} else if (operation === "hide") {
var $menu = this.data('contextMenu').$menu;
$menu && $menu.trigger('contextmenu:hide');
} else if (operation) {
this.removeClass('<API key>');
} else if (!operation) {
this.addClass('<API key>');
}
return this;
};
// manage contextMenu instances
$.contextMenu = function(operation, options) {
if (typeof operation != 'string') {
options = operation;
operation = 'create';
}
if (typeof options == 'string') {
options = {selector: options};
} else if (options === undefined) {
options = {};
}
// merge with default options
var o = $.extend(true, {}, defaults, options || {}),
$document = $(document);
switch (operation) {
case 'create':
// no selector no joy
if (!o.selector) {
throw new Error('No selector specified');
}
// make sure internal classes are not bound to
if (o.selector.match(/.context-menu-(list|item|input)($|\s)/)) {
throw new Error('Cannot bind to selector "' + o.selector + '" as it contains a reserved className');
}
if (!o.build && (!o.items || $.isEmptyObject(o.items))) {
throw new Error('No Items sepcified');
}
counter ++;
o.ns = '.contextMenu' + counter;
namespaces[o.selector] = o.ns;
menus[o.ns] = o;
// default to right click
if (!o.trigger) {
o.trigger = 'right';
}
if (!initialized) {
// make sure item click is registered first
$document
.on({
'contextmenu:hide.contextMenu': handle.hideMenu,
'prevcommand.contextMenu': handle.prevItem,
'nextcommand.contextMenu': handle.nextItem,
'contextmenu.contextMenu': handle.abortevent,
'mouseenter.contextMenu': handle.menuMouseenter,
'mouseleave.contextMenu': handle.menuMouseleave
}, '.context-menu-list')
.on('mouseup.contextMenu', '.context-menu-input', handle.inputClick)
.on({
'mouseup.contextMenu': handle.itemClick,
'contextmenu:focus.contextMenu': handle.focusItem,
'contextmenu:blur.contextMenu': handle.blurItem,
'contextmenu.contextMenu': handle.abortevent,
'mouseenter.contextMenu': handle.itemMouseenter,
'mouseleave.contextMenu': handle.itemMouseleave
}, '.context-menu-item');
initialized = true;
}
// engage native contextmenu event
$document
.on('contextmenu' + o.ns, o.selector, o, handle.contextmenu);
switch (o.trigger) {
case 'hover':
$document
.on('mouseenter' + o.ns, o.selector, o, handle.mouseenter)
.on('mouseleave' + o.ns, o.selector, o, handle.mouseleave);
break;
case 'left':
$document.on('click' + o.ns, o.selector, o, handle.click);
break;
}
// create menu
if (!o.build) {
op.create(o);
}
break;
case 'destroy':
if (!o.selector) {
$document.off('.contextMenu .contextMenuAutoHide');
$.each(namespaces, function(key, value) {
$document.off(value);
});
namespaces = {};
menus = {};
counter = 0;
initialized = false;
$('#context-menu-layer, .context-menu-list').remove();
} else if (namespaces[o.selector]) {
var $visibleMenu = $('.context-menu-list').filter(':visible');
if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(o.selector)) {
$visibleMenu.trigger('contextmenu:hide', {force: true});
}
try {
if (menus[namespaces[o.selector]].$menu) {
menus[namespaces[o.selector]].$menu.remove();
}
delete menus[namespaces[o.selector]];
} catch(e) {
menus[namespaces[o.selector]] = null;
}
$document.off(namespaces[o.selector]);
}
break;
case 'html5':
// if <command> or <menuitem> are not handled by the browser,
// or options was a bool true,
// initialize $.contextMenu for them
if ((!$.support.htmlCommand && !$.support.htmlMenuitem) || (typeof options == "boolean" && options)) {
$('menu[type="context"]').each(function() {
if (this.id) {
$.contextMenu({
selector: '[contextmenu=' + this.id +']',
items: $.contextMenu.fromMenu(this)
});
}
}).css('display', 'none');
}
break;
default:
throw new Error('Unknown operation "' + operation + '"');
}
return this;
};
// import values into <input> commands
$.contextMenu.setInputValues = function(opt, data) {
if (data === undefined) {
data = {};
}
$.each(opt.inputs, function(key, item) {
switch (item.type) {
case 'text':
case 'textarea':
item.value = data[key] || "";
break;
case 'checkbox':
item.selected = data[key] ? true : false;
break;
case 'radio':
item.selected = (data[item.radio] || "") == item.value ? true : false;
break;
case 'select':
item.selected = data[key] || "";
break;
}
});
};
// export values from <input> commands
$.contextMenu.getInputValues = function(opt, data) {
if (data === undefined) {
data = {};
}
$.each(opt.inputs, function(key, item) {
switch (item.type) {
case 'text':
case 'textarea':
case 'select':
data[key] = item.$input.val();
break;
case 'checkbox':
data[key] = item.$input.prop('checked');
break;
case 'radio':
if (item.$input.prop('checked')) {
data[item.radio] = item.value;
}
break;
}
});
return data;
};
// find <label for="xyz">
function inputLabel(node) {
return (node.id && $('label[for="'+ node.id +'"]').val()) || node.name;
}
// convert <menu> to items object
function menuChildren(items, $children, counter) {
if (!counter) {
counter = 0;
}
$children.each(function() {
var $node = $(this),
node = this,
nodeName = this.nodeName.toLowerCase(),
label,
item;
// extract <label><input>
if (nodeName == 'label' && $node.find('input, textarea, select').length) {
label = $node.text();
$node = $node.children().first();
node = $node.get(0);
nodeName = node.nodeName.toLowerCase();
}
/*
* <menu> accepts flow-content as children. that means <embed>, <canvas> and such are valid menu items.
* Not being the sadistic kind, $.contextMenu only accepts:
* <command>, <menuitem>, <hr>, <span>, <p> <input [text, radio, checkbox]>, <textarea>, <select> and of course <menu>.
* Everything else will be imported as an html node, which is not interfaced with contextMenu.
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#concept-command
switch (nodeName) {
// http://www.whatwg.org/specs/web-apps/current-work/multipage/<API key>.html#the-menu-element
case 'menu':
item = {name: $node.attr('label'), items: {}};
counter = menuChildren(item.items, $node.children(), counter);
break;
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#<API key>
case 'a':
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#<API key>
case 'button':
item = {
name: $node.text(),
disabled: !!$node.attr('disabled'),
callback: (function(){ return function(){ $node.click(); }; })()
};
break;
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#<API key>
case 'menuitem':
case 'command':
switch ($node.attr('type')) {
case undefined:
case 'command':
case 'menuitem':
item = {
name: $node.attr('label'),
disabled: !!$node.attr('disabled'),
callback: (function(){ return function(){ $node.click(); }; })()
};
break;
case 'checkbox':
item = {
type: 'checkbox',
disabled: !!$node.attr('disabled'),
name: $node.attr('label'),
selected: !!$node.attr('checked')
};
break;
case 'radio':
item = {
type: 'radio',
disabled: !!$node.attr('disabled'),
name: $node.attr('label'),
radio: $node.attr('radiogroup'),
value: $node.attr('id'),
selected: !!$node.attr('checked')
};
break;
default:
item = undefined;
}
break;
case 'hr':
item = '
break;
case 'input':
switch ($node.attr('type')) {
case 'text':
item = {
type: 'text',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
value: $node.val()
};
break;
case 'checkbox':
item = {
type: 'checkbox',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
selected: !!$node.attr('checked')
};
break;
case 'radio':
item = {
type: 'radio',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
radio: !!$node.attr('name'),
value: $node.val(),
selected: !!$node.attr('checked')
};
break;
default:
item = undefined;
break;
}
break;
case 'select':
item = {
type: 'select',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
selected: $node.val(),
options: {}
};
$node.children().each(function(){
item.options[this.value] = $(this).text();
});
break;
case 'textarea':
item = {
type: 'textarea',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
value: $node.val()
};
break;
case 'label':
break;
default:
item = {type: 'html', html: $node.clone(true)};
break;
}
if (item) {
counter++;
items['key' + counter] = item;
}
});
return counter;
}
// convert html5 menu
$.contextMenu.fromMenu = function(element) {
var $this = $(element),
items = {};
menuChildren(items, $this.children());
return items;
};
// make defaults accessible
$.contextMenu.defaults = defaults;
$.contextMenu.types = types;
})(jQuery); |
#ifndef __TAS2770__
#define __TAS2770__
/* Book Control Register (available in page0 of each book) */
#define <API key> 0
#define TAS2770_BOOKCTL_REG 127
#define TAS2770_REG(page, reg) ((page * 128) + reg)
/* Page */
#define TAS2770_PAGE TAS2770_REG(0X0, 0x00)
#define <API key> 255
/* Software Reset */
#define TAS2770_SW_RST TAS2770_REG(0X0, 0x01)
#define TAS2770_RST BIT(0)
/* Power Control */
#define TAS2770_PWR_CTRL TAS2770_REG(0X0, 0x02)
#define <API key> 0x3
#define <API key> 0x0
#define <API key> BIT(0)
#define <API key> 0x2
/* Playback Configuration Reg0 */
#define <API key> TAS2770_REG(0X0, 0x03)
/* Playback Configuration Reg1 */
#define <API key> TAS2770_REG(0X0, 0x04)
/* Playback Configuration Reg2 */
#define <API key> TAS2770_REG(0X0, 0x05)
#define <API key> 0xc9
/* Misc Configuration Reg0 */
#define <API key> TAS2770_REG(0X0, 0x07)
/* TDM Configuration Reg0 */
#define <API key> TAS2770_REG(0X0, 0x0A)
#define <API key> BIT(5)
#define <API key> 0x0
#define <API key> BIT(5)
#define <API key> 0xe
#define <API key> 0x6
#define <API key> 0x8
#define <API key> 0xa
/* TDM Configuration Reg1 */
#define <API key> TAS2770_REG(0X0, 0x0B)
#define <API key> 0x3e
#define <API key> 1
#define <API key> BIT(0)
#define <API key> 0x0
#define <API key> BIT(0)
/* TDM Configuration Reg2 */
#define <API key> TAS2770_REG(0X0, 0x0C)
#define <API key> 0xc
#define <API key> 0x0
#define <API key> 0x8
#define <API key> 0xc
#define <API key> 0x3
#define <API key> 0x0
#define <API key> BIT(0)
#define <API key> 0x2
/* TDM Configuration Reg3 */
#define <API key> TAS2770_REG(0X0, 0x0D)
#define <API key> 0xf0
#define <API key> 0x4
#define <API key> 0xf
#define <API key> 0
/* TDM Configuration Reg5 */
#define <API key> TAS2770_REG(0X0, 0x0F)
#define <API key> BIT(6)
#define <API key> BIT(6)
#define <API key> 0x3f
/* TDM Configuration Reg6 */
#define <API key> TAS2770_REG(0X0, 0x10)
#define <API key> BIT(6)
#define <API key> BIT(6)
#define <API key> 0x3f
/* Brown Out Prevention Reg0 */
#define TAS2770_BO_PRV_REG0 TAS2770_REG(0X0, 0x1B)
/* Interrupt MASK Reg0 */
#define <API key> TAS2770_REG(0X0, 0x20)
#define <API key> 0xfc
#define <API key> 0xff
/* Interrupt MASK Reg1 */
#define <API key> TAS2770_REG(0X0, 0x21)
#define <API key> 0xb1
#define <API key> 0xff
/* Live-Interrupt Reg0 */
#define <API key> TAS2770_REG(0X0, 0x22)
/* Live-Interrupt Reg1 */
#define <API key> TAS2770_REG(0X0, 0x23)
/* Latched-Interrupt Reg0 */
#define <API key> TAS2770_REG(0X0, 0x24)
#define <API key> BIT(1)
#define <API key> BIT(0)
/* Latched-Interrupt Reg1 */
#define <API key> TAS2770_REG(0X0, 0x25)
#define <API key> BIT(3)
#define <API key> BIT(2)
#define <API key> BIT(1)
/* VBAT MSB */
#define TAS2770_VBAT_MSB TAS2770_REG(0X0, 0x27)
/* VBAT LSB */
#define TAS2770_VBAT_LSB TAS2770_REG(0X0, 0x28)
/* TEMP MSB */
#define TAS2770_TEMP_MSB TAS2770_REG(0X0, 0x29)
/* TEMP LSB */
#define TAS2770_TEMP_LSB TAS2770_REG(0X0, 0x2A)
/* Interrupt Configuration */
#define TAS2770_INT_CFG TAS2770_REG(0X0, 0x30)
/* Misc IRQ */
#define TAS2770_MISC_IRQ TAS2770_REG(0X0, 0x32)
/* Clock Configuration */
#define TAS2770_CLK_CGF TAS2770_REG(0X0, 0x3C)
/* TDM Clock detection monitor */
#define <API key> TAS2770_REG(0X0, 0x77)
/* Revision and PG ID */
#define <API key> TAS2770_REG(0X0, 0x7D)
#define <API key> 0
#define TAS2770_POWER_MUTE 1
#define <API key> 2
#define ERROR_OVER_CURRENT 0x0000001
#define ERROR_DIE_OVERTEMP 0x0000002
#define ERROR_OVER_VOLTAGE 0x0000004
#define ERROR_UNDER_VOLTAGE 0x0000008
#define ERROR_BROWNOUT 0x0000010
#define ERROR_CLASSD_PWR 0x0000020
struct tas2770_priv {
struct device *dev;
struct regmap *regmap;
struct snd_soc_component *component;
int power_state;
int asi_format;
struct gpio_desc *reset_gpio;
int sampling_rate;
int channel_size;
int slot_width;
int v_sense_slot;
int i_sense_slot;
};
#endif /* __TAS2770__ */ |
class C:
x = 1
def foo(self): pass |
# stream-counter
Keep track of how many bytes have been written to a stream.
## Usage
js
var StreamCounter = require('stream-counter');
var counter = new StreamCounter();
counter.on('progress', function() {
console.log("progress", counter.bytes);
});
fs.createReadStream('foo.txt').pipe(counter); |
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/onenand.h>
#include <linux/interrupt.h>
#include <linux/platform_data/pca953x.h>
#include <linux/gpio.h>
#include <linux/gpio-pxa.h>
#include <linux/mfd/88pm860x.h>
#include <linux/platform_data/mv_usb.h>
#include <linux/spi/spi.h>
#include <linux/delay.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/flash.h>
#include "addr-map.h"
#include "mfp-pxa910.h"
#include "pxa910.h"
#include "irqs.h"
#include "regs-usb.h"
#include "common.h"
#define TTCDKB_GPIO_EXT0(x) (MMP_NR_BUILTIN_GPIO + ((x < 0) ? 0 : \
((x < 16) ? x : 15)))
#define TTCDKB_GPIO_EXT1(x) (MMP_NR_BUILTIN_GPIO + 16 + ((x < 0) ? 0 : \
((x < 16) ? x : 15)))
/*
* 16 board interrupts -- MAX7312 GPIO expander
* 16 board interrupts -- PCA9575 GPIO expander
* 24 board interrupts -- 88PM860x PMIC
*/
#define TTCDKB_NR_IRQS (MMP_NR_IRQS + 16 + 16 + 24)
static unsigned long ttc_dkb_pin_config[] __initdata = {
/* UART2 */
GPIO47_UART2_RXD,
GPIO48_UART2_TXD,
/* DFI */
DF_IO0_ND_IO0,
DF_IO1_ND_IO1,
DF_IO2_ND_IO2,
DF_IO3_ND_IO3,
DF_IO4_ND_IO4,
DF_IO5_ND_IO5,
DF_IO6_ND_IO6,
DF_IO7_ND_IO7,
DF_IO8_ND_IO8,
DF_IO9_ND_IO9,
DF_IO10_ND_IO10,
DF_IO11_ND_IO11,
DF_IO12_ND_IO12,
DF_IO13_ND_IO13,
DF_IO14_ND_IO14,
DF_IO15_ND_IO15,
<API key>,
<API key>,
<API key>,
DF_WEn_DF_WEn,
DF_REn_DF_REn,
DF_RDY0_DF_RDY0,
};
static struct <API key> pxa910_gpio_pdata = {
.irq_base = MMP_GPIO_TO_IRQ(0),
};
static struct mtd_partition <API key>[] = {
{
.name = "bootloader",
.offset = 0,
.size = SZ_1M,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "reserved",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "reserved",
.offset = MTDPART_OFS_APPEND,
.size = SZ_8M,
.mask_flags = MTD_WRITEABLE,
}, {
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = (SZ_2M + SZ_1M),
.mask_flags = 0,
}, {
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = SZ_32M + SZ_16M,
.mask_flags = 0,
}
};
static struct <API key> <API key> = {
.parts = <API key>,
.nr_parts = ARRAY_SIZE(<API key>),
};
static struct resource <API key>[] = {
[0] = {
.start = SMC_CS0_PHYS_BASE,
.end = SMC_CS0_PHYS_BASE + SZ_1M,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device <API key> = {
.name = "onenand-flash",
.id = -1,
.resource = <API key>,
.num_resources = ARRAY_SIZE(<API key>),
.dev = {
.platform_data = &<API key>,
},
};
static struct platform_device *ttc_dkb_devices[] = {
&pxa910_device_gpio,
&pxa910_device_rtc,
&<API key>,
};
static struct <API key> max7312_data[] = {
{
.gpio_base = TTCDKB_GPIO_EXT0(0),
.irq_base = MMP_NR_IRQS,
},
};
static struct <API key> ttc_dkb_pm8607_info = {
.irq_base = IRQ_BOARD_START,
};
static struct i2c_board_info ttc_dkb_i2c_info[] = {
{
.type = "88PM860x",
.addr = 0x34,
.platform_data = &ttc_dkb_pm8607_info,
.irq = IRQ_PXA910_PMIC_INT,
},
{
.type = "max7312",
.addr = 0x23,
.irq = MMP_GPIO_TO_IRQ(80),
.platform_data = &max7312_data,
},
};
#if IS_ENABLED(CONFIG_USB_SUPPORT)
#if IS_ENABLED(CONFIG_USB_MV_UDC) || IS_ENABLED(<API key>)
static struct <API key> ttc_usb_pdata = {
.vbus = NULL,
.mode = MV_USB_MODE_OTG,
.otg_force_a_bus_req = 1,
.phy_init = pxa_usb_phy_init,
.phy_deinit = pxa_usb_phy_deinit,
.set_vbus = NULL,
};
#endif
#endif
#if IS_ENABLED(<API key>)
static struct <API key> dkb_nand_info = {};
#endif
#if IS_ENABLED(CONFIG_MMP_DISP)
/* path config */
#define CFG_IOPADMODE(iopad) (iopad) /* 0x0 ~ 0xd */
#define SCLK_SOURCE_SELECT(x) (x << 30) /* 0x0 ~ 0x3 */
/* link config */
#define CFG_DUMBMODE(mode) (mode << 28) /* 0x0 ~ 0x6*/
static struct <API key> dkb_disp_config[] = {
[0] = {
.name = "mmp-parallel",
.overlay_num = 2,
.output_type = PATH_OUT_PARALLEL,
.path_config = CFG_IOPADMODE(0x1)
| SCLK_SOURCE_SELECT(0x1),
.link_config = CFG_DUMBMODE(0x2),
},
};
static struct mmp_mach_plat_info dkb_disp_info = {
.name = "mmp-disp",
.clk_name = "disp0",
.path_num = 1,
.paths = dkb_disp_config,
};
static struct <API key> dkb_fb_info = {
.name = "mmp-fb",
.path_name = "mmp-parallel",
.overlay_id = 0,
.dmafetch_id = 1,
.default_pixfmt = PIXFMT_RGB565,
};
static void dkb_tpo_panel_power(int on)
{
int err;
u32 spi_reset = mfp_to_gpio(MFP_PIN_GPIO106);
if (on) {
err = gpio_request(spi_reset, "TPO_LCD_SPI_RESET");
if (err) {
pr_err("failed to request GPIO for TPO LCD RESET\n");
return;
}
<API key>(spi_reset, 0);
udelay(100);
gpio_set_value(spi_reset, 1);
gpio_free(spi_reset);
} else {
err = gpio_request(spi_reset, "TPO_LCD_SPI_RESET");
if (err) {
pr_err("failed to request LCD RESET gpio\n");
return;
}
gpio_set_value(spi_reset, 0);
gpio_free(spi_reset);
}
}
static struct mmp_mach_panel_info dkb_tpo_panel_info = {
.name = "tpo-hvga",
.plat_path_name = "mmp-parallel",
.plat_set_onoff = dkb_tpo_panel_power,
};
static struct spi_board_info spi_board_info[] __initdata = {
{
.modalias = "tpo-hvga",
.platform_data = &dkb_tpo_panel_info,
.bus_num = 5,
}
};
static void __init add_disp(void)
{
pxa_register_device(&pxa910_device_disp,
&dkb_disp_info, sizeof(dkb_disp_info));
<API key>(spi_board_info, ARRAY_SIZE(spi_board_info));
pxa_register_device(&pxa910_device_fb,
&dkb_fb_info, sizeof(dkb_fb_info));
pxa_register_device(&pxa910_device_panel,
&dkb_tpo_panel_info, sizeof(dkb_tpo_panel_info));
}
#endif
static void __init ttc_dkb_init(void)
{
mfp_config(ARRAY_AND_SIZE(ttc_dkb_pin_config));
/* on-chip devices */
pxa910_add_uart(1);
#if IS_ENABLED(<API key>)
pxa910_add_nand(&dkb_nand_info);
#endif
/* off-chip devices */
pxa910_add_twsi(0, NULL, ARRAY_AND_SIZE(ttc_dkb_i2c_info));
<API key>(&pxa910_device_gpio, &pxa910_gpio_pdata,
sizeof(struct <API key>));
<API key>(ARRAY_AND_SIZE(ttc_dkb_devices));
#if IS_ENABLED(CONFIG_USB_MV_UDC)
pxa168_device_u2o.dev.platform_data = &ttc_usb_pdata;
<API key>(&pxa168_device_u2o);
#endif
#if IS_ENABLED(<API key>)
<API key>.dev.platform_data = &ttc_usb_pdata;
<API key>(&<API key>);
#endif
#if IS_ENABLED(CONFIG_USB_MV_OTG)
<API key>.dev.platform_data = &ttc_usb_pdata;
<API key>(&<API key>);
#endif
#if IS_ENABLED(CONFIG_MMP_DISP)
add_disp();
#endif
}
MACHINE_START(TTC_DKB, "PXA910-based TTC_DKB Development Platform")
.map_io = mmp_map_io,
.nr_irqs = TTCDKB_NR_IRQS,
.init_irq = pxa910_init_irq,
.init_time = pxa910_timer_init,
.init_machine = ttc_dkb_init,
.restart = mmp_restart,
MACHINE_END |
#ifndef <API key>
#define <API key>
#define VM_TYPES_PARNEW(declare_type) \
declare_type(ParNewGeneration, DefNewGeneration)
#define <API key>(declare_constant) \
declare_constant(Generation::ParNew)
#endif // <API key> |
/*
* Ported from Ebony flash support
* Travis B. Sawyer
* Sandburst Corporation
*/
#include <common.h>
#include <asm/ppc4xx.h>
#include <asm/processor.h>
#undef DEBUG
#ifdef DEBUG
#define DEBUGF(x...) printf(x)
#else
#define DEBUGF(x...)
#endif /* DEBUG */
flash_info_t flash_info[<API key>]; /* info for FLASH chips */
static unsigned long flash_addr_table[8][<API key>] = {
{0xfff80000} /* Boot Flash */
};
static ulong flash_get_size (vu_long *addr, flash_info_t *info);
static int write_word (flash_info_t *info, ulong dest, ulong data);
#define ADDR0 0x5555
#define ADDR1 0x2aaa
#define FLASH_WORD_SIZE unsigned char
unsigned long flash_init (void)
{
unsigned long total_b = 0;
unsigned long size_b[<API key>];
unsigned short index = 0;
int i;
DEBUGF("\n");
DEBUGF("FLASH: Index: %d\n", index);
/* Init: no FLASHes known */
for (i=0; i<<API key>; ++i) {
flash_info[i].flash_id = FLASH_UNKNOWN;
flash_info[i].sector_count = -1;
flash_info[i].size = 0;
/* check whether the address is 0 */
if (flash_addr_table[index][i] == 0) {
continue;
}
/* call flash_get_size() to initialize sector address */
size_b[i] = flash_get_size(
(vu_long *)flash_addr_table[index][i], &flash_info[i]);
flash_info[i].size = size_b[i];
if (flash_info[i].flash_id == FLASH_UNKNOWN) {
printf ("## Unknown FLASH on Bank %d - Size = 0x%08lx = %ld MB\n",
i, size_b[i], size_b[i]<<20);
flash_info[i].sector_count = -1;
flash_info[i].size = 0;
}
total_b += flash_info[i].size;
}
return total_b;
}
void flash_print_info (flash_info_t *info)
{
int i;
int k;
int size;
int erased;
volatile unsigned long *flash;
if (info->flash_id == FLASH_UNKNOWN) {
printf ("missing or unknown FLASH type\n");
return;
}
switch (info->flash_id & FLASH_VENDMASK) {
case FLASH_MAN_AMD: printf ("AMD "); break;
default: printf ("Unknown Vendor "); break;
}
switch (info->flash_id & FLASH_TYPEMASK) {
case FLASH_AM040: printf ("AM29F040 (512 Kbit, uniform sector size)\n");
break;
default: printf ("Unknown Chip Type\n");
break;
}
printf (" Size: %ld KB in %d Sectors\n",
info->size >> 10, info->sector_count);
printf (" Sector Start Addresses:");
for (i=0; i<info->sector_count; ++i) {
/*
* Check if whole sector is erased
*/
if (i != (info->sector_count-1))
size = info->start[i+1] - info->start[i];
else
size = info->start[0] + info->size - info->start[i];
erased = 1;
flash = (volatile unsigned long *)info->start[i];
size = size >> 2; /* divide by 4 for longword access */
for (k=0; k<size; k++)
{
if (*flash++ != 0xffffffff)
{
erased = 0;
break;
}
}
if ((i % 5) == 0)
printf ("\n ");
printf (" %08lX%s%s",
info->start[i],
erased ? " E" : " ",
info->protect[i] ? "RO " : " "
);
}
printf ("\n");
return;
}
/*
* The following code cannot be run from FLASH!
*/
static ulong flash_get_size (vu_long *addr, flash_info_t *info)
{
short i;
FLASH_WORD_SIZE value;
ulong base = (ulong)addr;
volatile FLASH_WORD_SIZE *addr2 = (FLASH_WORD_SIZE *)addr;
DEBUGF("FLASH ADDR: %08x\n", (unsigned)addr );
/* Write auto select command: read Manufacturer ID */
udelay(10000);
addr2[ADDR0] = (FLASH_WORD_SIZE)0x00AA00AA;
udelay(1000);
addr2[ADDR1] = (FLASH_WORD_SIZE)0x00550055;
udelay(1000);
addr2[ADDR0] = (FLASH_WORD_SIZE)0x00900090;
udelay(1000);
value = addr2[0];
DEBUGF("FLASH MANUFACT: %x\n", value);
switch (value) {
case (FLASH_WORD_SIZE)AMD_MANUFACT:
info->flash_id = FLASH_MAN_AMD;
break;
default:
info->flash_id = FLASH_UNKNOWN;
info->sector_count = 0;
info->size = 0;
return (0); /* no or unknown flash */
}
value = addr2[1]; /* device ID */
DEBUGF("\nFLASH DEVICEID: %x\n", value);
switch (value) {
case (FLASH_WORD_SIZE)AMD_ID_LV040B:
info->flash_id += FLASH_AM040;
info->sector_count = 8;
info->size = 0x00080000; /* => 512 kb */
break;
default:
info->flash_id = FLASH_UNKNOWN;
return (0); /* => no or unknown flash */
}
/* set up sector start address table */
if (info->flash_id == FLASH_AM040) {
for (i = 0; i < info->sector_count; i++)
info->start[i] = base + (i * 0x00010000);
} else {
if (info->flash_id & FLASH_BTYPE) {
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00004000;
info->start[2] = base + 0x00006000;
info->start[3] = base + 0x00008000;
for (i = 4; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00010000) - 0x00030000;
}
} else {
/* set sector offsets for top boot block type */
i = info->sector_count - 1;
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00006000;
info->start[i--] = base + info->size - 0x00008000;
for (; i >= 0; i
info->start[i] = base + i * 0x00010000;
}
}
}
/* check for protected sectors */
for (i = 0; i < info->sector_count; i++) {
/* read sector protection at sector address, (A7 .. A0) = 0x02 */
/* D0 = 1 if protected */
addr2 = (volatile FLASH_WORD_SIZE *)(info->start[i]);
if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_SST)
info->protect[i] = 0;
else
info->protect[i] = addr2[2] & 1;
}
/* reset to return to reading data */
addr2[0] = (FLASH_WORD_SIZE) 0x00F000F0; /* reset bank */
/*
* Prevent writes to uninitialized FLASH.
*/
if (info->flash_id != FLASH_UNKNOWN) {
addr2 = (FLASH_WORD_SIZE *)info->start[0];
*addr2 = (FLASH_WORD_SIZE)0x00F000F0; /* reset bank */
}
return (info->size);
}
int wait_for_DQ7(flash_info_t *info, int sect)
{
ulong start, now, last;
volatile FLASH_WORD_SIZE *addr = (FLASH_WORD_SIZE *)(info->start[sect]);
start = get_timer (0);
last = start;
while ((addr[0] & (FLASH_WORD_SIZE)0x00800080) != (FLASH_WORD_SIZE)0x00800080) {
if ((now = get_timer(start)) > <API key>) {
printf ("Timeout\n");
return -1;
}
/* show that we're waiting */
if ((now - last) > 1000) { /* every second */
putc ('.');
last = now;
}
}
return 0;
}
int flash_erase (flash_info_t *info, int s_first, int s_last)
{
volatile FLASH_WORD_SIZE *addr = (FLASH_WORD_SIZE *)(info->start[0]);
volatile FLASH_WORD_SIZE *addr2;
int flag, prot, sect, l_sect;
int i;
if ((s_first < 0) || (s_first > s_last)) {
if (info->flash_id == FLASH_UNKNOWN) {
printf ("- missing\n");
} else {
printf ("- no sectors to erase\n");
}
return 1;
}
if (info->flash_id == FLASH_UNKNOWN) {
printf ("Can't erase unknown flash type - aborted\n");
return 1;
}
prot = 0;
for (sect=s_first; sect<=s_last; ++sect) {
if (info->protect[sect]) {
prot++;
}
}
if (prot) {
printf ("- Warning: %d protected sectors will not be erased!\n",
prot);
} else {
printf ("\n");
}
l_sect = -1;
/* Disable interrupts which might cause a timeout here */
flag = disable_interrupts();
/* Start erase on unprotected sectors */
for (sect = s_first; sect<=s_last; sect++) {
if (info->protect[sect] == 0) { /* not protected */
addr2 = (FLASH_WORD_SIZE *)(info->start[sect]);
DEBUGF("Erasing sector %p\n", addr2);
if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_SST) {
addr[ADDR0] = (FLASH_WORD_SIZE)0x00AA00AA;
addr[ADDR1] = (FLASH_WORD_SIZE)0x00550055;
addr[ADDR0] = (FLASH_WORD_SIZE)0x00800080;
addr[ADDR0] = (FLASH_WORD_SIZE)0x00AA00AA;
addr[ADDR1] = (FLASH_WORD_SIZE)0x00550055;
addr2[0] = (FLASH_WORD_SIZE)0x00500050; /* block erase */
for (i=0; i<50; i++)
udelay(1000); /* wait 1 ms */
} else {
addr[ADDR0] = (FLASH_WORD_SIZE)0x00AA00AA;
addr[ADDR1] = (FLASH_WORD_SIZE)0x00550055;
addr[ADDR0] = (FLASH_WORD_SIZE)0x00800080;
addr[ADDR0] = (FLASH_WORD_SIZE)0x00AA00AA;
addr[ADDR1] = (FLASH_WORD_SIZE)0x00550055;
addr2[0] = (FLASH_WORD_SIZE)0x00300030; /* sector erase */
}
l_sect = sect;
/*
* Wait for each sector to complete, it's more
* reliable. According to AMD Spec, you must
* issue all erase commands within a specified
* timeout. This has been seen to fail, especially
* if printf()s are included (for debug)!!
*/
wait_for_DQ7(info, sect);
}
}
/* re-enable interrupts if necessary */
if (flag)
enable_interrupts();
/* wait at least 80us - let's wait 1 ms */
udelay (1000);
/* reset to read mode */
addr = (FLASH_WORD_SIZE *)info->start[0];
addr[0] = (FLASH_WORD_SIZE)0x00F000F0; /* reset bank */
printf (" done\n");
return 0;
}
int write_buff (flash_info_t *info, uchar *src, ulong addr, ulong cnt)
{
ulong cp, wp, data;
int i, l, rc;
wp = (addr & ~3); /* get lower word aligned address */
/*
* handle unaligned start bytes
*/
if ((l = addr - wp) != 0) {
data = 0;
for (i=0, cp=wp; i<l; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
for (; i<4 && cnt>0; ++i) {
data = (data << 8) | *src++;
--cnt;
++cp;
}
for (; cnt==0 && i<4; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
if ((rc = write_word(info, wp, data)) != 0) {
return (rc);
}
wp += 4;
}
/*
* handle word aligned part
*/
while (cnt >= 4) {
data = 0;
for (i=0; i<4; ++i) {
data = (data << 8) | *src++;
}
if ((rc = write_word(info, wp, data)) != 0) {
return (rc);
}
wp += 4;
cnt -= 4;
}
if (cnt == 0) {
return (0);
}
/*
* handle unaligned tail bytes
*/
data = 0;
for (i=0, cp=wp; i<4 && cnt>0; ++i, ++cp) {
data = (data << 8) | *src++;
--cnt;
}
for (; i<4; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
return (write_word(info, wp, data));
}
static int write_word (flash_info_t * info, ulong dest, ulong data)
{
volatile FLASH_WORD_SIZE *addr2 = (FLASH_WORD_SIZE *) (info->start[0]);
volatile FLASH_WORD_SIZE *dest2 = (FLASH_WORD_SIZE *) dest;
volatile FLASH_WORD_SIZE *data2 = (FLASH_WORD_SIZE *) & data;
ulong start;
int i;
/* Check if Flash is (sufficiently) erased */
if ((*((volatile FLASH_WORD_SIZE *) dest) &
(FLASH_WORD_SIZE) data) != (FLASH_WORD_SIZE) data) {
return (2);
}
for (i = 0; i < 4 / sizeof (FLASH_WORD_SIZE); i++) {
int flag;
/* Disable interrupts which might cause a timeout here */
flag = disable_interrupts ();
addr2[ADDR0] = (FLASH_WORD_SIZE) 0x00AA00AA;
addr2[ADDR1] = (FLASH_WORD_SIZE) 0x00550055;
addr2[ADDR0] = (FLASH_WORD_SIZE) 0x00A000A0;
dest2[i] = data2[i];
/* re-enable interrupts if necessary */
if (flag)
enable_interrupts ();
/* data polling for D7 */
start = get_timer (0);
while ((dest2[i] & (FLASH_WORD_SIZE) 0x00800080) !=
(data2[i] & (FLASH_WORD_SIZE) 0x00800080)) {
if (get_timer (start) > <API key>) {
return (1);
}
}
}
return (0);
} |
/*jslint browser:true evil:true */
(function (global) {
'use strict';
var lookup;
function id(i) {
return document.getElementById(i);
}
function escaped(str) {
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
function setText(id, str) {
var el = document.getElementById(id);
if (typeof el.innerText === 'string') {
el.innerText = str;
} else {
el.textContent = str;
}
}
function isLineTerminator(ch) {
return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
}
// Remove all previous tracing.
function untrace(code) {
var i, trace, traces = [];
// Executes visitor on the object and its children (recursively).
function traverse(object, visitor, master) {
var key, child, parent, path;
parent = (typeof master === 'undefined') ? [] : master;
if (visitor.call(null, object, parent) === false) {
return;
}
for (key in object) {
if (object.hasOwnProperty(key)) {
child = object[key];
path = [ object ];
path.push(parent);
if (typeof child === 'object' && child !== null) {
traverse(child, visitor, path);
}
}
}
}
// In order to remove all previous tracing, we need to find the syntax
// nodes associated with the tracing.
traverse(global.esprima.parse(code, { range: true }), function (node, parent) {
var n = node;
if (n.type !== 'CallExpression') {
return;
}
n = n.callee;
if (!n || n.type !== 'MemberExpression') {
return;
}
if (n.property.type !== 'Identifier' || n.property.name !== 'enterFunction') {
return;
}
n = n.object;
if (!n || n.type !== 'MemberExpression') {
return;
}
if (n.object.type !== 'Identifier' || n.object.name !== 'window') {
return;
}
if (n.property.type !== 'Identifier' || n.property.name !== 'TRACE') {
return;
}
traces.push({ start: parent[0].range[0], end: parent[0].range[1] });
});
// Remove the farther trace first, this is to avoid changing the range
// info for each trace node.
for (i = traces.length - 1; i >= 0; i -= 1) {
trace = traces[i];
if (code[trace.end] === '\n') {
trace.end = trace.end + 1;
}
code = code.slice(0, trace.start) + code.slice(trace.end, code.length);
}
return code;
}
global.traceInstrument = function () {
var tracer, code, i, functionList, signature, pos;
if (typeof window.editor === 'undefined') {
code = document.getElementById('code').value;
} else {
code = window.editor.getValue();
}
code = untrace(code);
tracer = window.esmorph.Tracer.FunctionEntrance(function (fn) {
signature = 'window.TRACE.enterFunction({ ';
signature += 'name: "' + fn.name + '", ';
signature += 'lineNumber: ' + fn.loc.start.line + ', ';
signature += 'range: [' + fn.range[0] + ',' + fn.range[1] + ']';
signature += ' });';
return signature;
});
code = window.esmorph.modify(code, tracer);
if (typeof window.editor === 'undefined') {
document.getElementById('code').value = code;
} else {
window.editor.setValue(code);
}
// Enclose in IIFE.
code = '(function() {\n' + code + '\n}())';
return code;
};
function showResult() {
var i, str, histogram, entry;
histogram = window.TRACE.getHistogram();
str = '<table><thead><tr><td>Function</td><td>Hits</td></tr></thead>';
for (i = 0; i < histogram.length; i += 1) {
entry = histogram[i];
str += '<tr>';
str += '<td>' + entry.name + '</td>';
str += '<td>' + entry.count + '</td>';
str += '</tr>';
}
str += '</table>';
id('result').innerHTML = str;
}
function <API key>() {
global.TRACE = {
hits: {},
enterFunction: function (info) {
var key = info.name + ' at line ' + info.lineNumber;
if (this.hits.hasOwnProperty(key)) {
this.hits[key] = this.hits[key] + 1;
} else {
this.hits[key] = 1;
}
},
getHistogram: function () {
var entry,
sorted = [];
for (entry in this.hits) {
if (this.hits.hasOwnProperty(entry)) {
sorted.push({ name: entry, count: this.hits[entry]});
}
}
sorted.sort(function (a, b) {
return b.count - a.count;
});
return sorted;
}
};
}
global.traceRun = function () {
var code;
try {
code = global.traceInstrument();
<API key>();
eval(code);
showResult();
} catch (e) {
id('result').innerText = e.toString();
}
};
}(window));
/* vim: set sw=4 ts=4 et tw=80 : */ |
#ifndef <API key>
#define <API key>
/* Return current instruction pointer. */
#define current_text_addr() \
({void *pc; __asm__ __volatile__ ("lapcq .,%0" : "=rm" (pc)); pc;})
/*
* Since CRIS doesn't do hardware task-switching this hasn't really anything to
* do with the proccessor itself, it's just here for legacy reasons. This is
* used when task-switching using _resume defined in entry.S. The offsets here
* are hardcoded into _resume, so if this struct is changed, entry.S needs to be
* changed as well.
*/
struct thread_struct {
unsigned long ksp; /* Kernel stack pointer. */
unsigned long usp; /* User stack pointer. */
unsigned long ccs; /* Saved flags register. */
};
/*
* User-space process size. This is hardcoded into a few places, so don't
* changed it unless everything's clear!
*/
#ifndef <API key>
#define TASK_SIZE (0xB0000000UL)
#else
#define TASK_SIZE (0xA0000000UL)
#endif
/* CCS I=1, enable interrupts. */
#define INIT_THREAD { 0, 0, (1 << I_CCS_BITNR) }
#define KSTK_EIP(tsk) \
({ \
unsigned long eip = 0; \
unsigned long regs = (unsigned long)task_pt_regs(tsk); \
if (regs > PAGE_SIZE && virt_addr_valid(regs)) \
eip = ((struct pt_regs *)regs)->erp; \
eip; \
})
/*
* Give the thread a program location, set user-mode and switch user
* stackpointer.
*/
#define start_thread(regs, ip, usp) \
do { \
regs->erp = ip; \
regs->ccs |= 1 << (U_CCS_BITNR + CCS_SHIFT); \
wrusp(usp); \
} while(0)
/* Nothing special to do for v32 when handling a kernel bus fault fixup. */
#define arch_fixup(regs) {};
#endif /* <API key> */ |
// <API key>: Apache-2.0
package yaml
import (
"reflect"
"strings"
y1_1 "gopkg.in/yaml.v2"
"k8s.io/kube-openapi/pkg/validation/spec"
y1_2 "sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/go-yaml/yaml"
)
// typeToTag maps OpenAPI schema types to yaml 1.2 tags
var typeToTag = map[string]string{
"string": NodeTagString,
"integer": NodeTagInt,
"boolean": NodeTagBool,
"number": NodeTagFloat,
}
// <API key> makes sure that values which parse as non-string values in yaml 1.1
// are correctly formatted given the Schema type.
func <API key>(node *Node, schema spec.Schema) {
if len(schema.Type) != 1 {
return
}
t := schema.Type[0]
if !IsYaml1_1NonString(node) {
return
}
switch {
case t == "string" && schema.Format != "int-or-string":
if (node.Style&DoubleQuotedStyle == 0) && (node.Style&SingleQuotedStyle == 0) {
// must quote values so they are parsed as strings
node.Style = DoubleQuotedStyle
}
case t == "boolean" || t == "integer" || t == "number":
if (node.Style&DoubleQuotedStyle != 0) || (node.Style&SingleQuotedStyle != 0) {
// must NOT quote the values so they aren't parsed as strings
node.Style = 0
}
default:
return
}
// if the node tag is null, make sure we don't add any non-null tags
if node.Tag == NodeTagNull {
// must NOT quote null values
node.Style = 0
return
}
if tag, found := typeToTag[t]; found {
// make sure the right tag is set
node.Tag = tag
}
}
// IsYaml1_1NonString returns true if the value parses as a non-string value in yaml 1.1
// when unquoted.
// Note: yaml 1.2 uses different keywords than yaml 1.1. Example: yaml 1.2 interprets
// `field: on` and `field: "on"` as equivalent (both strings). However Yaml 1.1 interprets
// `field: on` as on being a bool and `field: "on"` as on being a string.
// If an input is read with `field: "on"`, and the style is changed from DoubleQuote to 0,
// it will change the type of the field from a string to a bool. For this reason, fields
// which are keywords in yaml 1.1 should never have their style changed, as it would break
// backwards compatibility with yaml 1.1 -- which is what is used by the Kubernetes apiserver.
func IsYaml1_1NonString(node *Node) bool {
if node.Kind != y1_2.ScalarNode {
// not a keyword
return false
}
return IsValueNonString(node.Value)
}
func IsValueNonString(value string) bool {
if value == "" {
return false
}
if strings.Contains(value, "\n") {
// multi-line strings will fail to unmarshal
return false
}
// check if the value will unmarshal into a non-string value using a yaml 1.1 parser
var i1 interface{}
if err := y1_1.Unmarshal([]byte(value), &i1); err != nil {
return false
}
if reflect.TypeOf(i1) != stringType {
return true
}
return false
}
var stringType = reflect.TypeOf("string") |
require "helper"
class UnitTestApi < Loofah::TestCase
HTML = "<div>a</div>\n<div>b</div>"
XML_FRAGMENT = "<div>a</div>\n<div>b</div>"
XML = "<root>#{XML_FRAGMENT}</root>"
describe "HTML" do
it "creates documents" do
doc = Loofah.document(HTML)
<API key> doc
end
it "creates fragments" do
doc = Loofah.fragment(HTML)
<API key> doc
end
it "parses documents" do
doc = Loofah::HTML::Document.parse(HTML)
<API key> doc
end
it "parses document fragment" do
doc = Loofah::HTML::DocumentFragment.parse(HTML)
<API key> doc
end
it "scrubs documents" do
doc = Loofah.document(HTML).scrub!(:strip)
<API key> doc
end
it "scrubs fragments" do
doc = Loofah.fragment(HTML).scrub!(:strip)
<API key> doc
end
it "scrubs document nodes" do
doc = Loofah.document(HTML)
assert(node = doc.at_css("div"))
node.scrub!(:strip)
end
it "scrubs fragment nodes" do
doc = Loofah.fragment(HTML)
assert(node = doc.at_css("div"))
node.scrub!(:strip)
end
it "scrubs document nodesets" do
doc = Loofah.document(HTML)
assert(node_set = doc.css("div"))
assert_instance_of Nokogiri::XML::NodeSet, node_set
node_set.scrub!(:strip)
end
it "exposes serialize_root on HTML::DocumentFragment" do
doc = Loofah.fragment(HTML)
assert_equal HTML, doc.serialize_root.to_html
end
it "exposes serialize_root on HTML::Document" do
doc = Loofah.document(HTML)
assert_equal HTML, doc.serialize_root.children.to_html
end
end
describe "XML" do
it "creates documents" do
doc = Loofah.xml_document(XML)
<API key> doc
end
it "creates fragments" do
doc = Loofah.xml_fragment(XML_FRAGMENT)
<API key> doc
end
it "parses documents" do
doc = Loofah::XML::Document.parse(XML)
<API key> doc
end
it "parses document fragments" do
doc = Loofah::XML::DocumentFragment.parse(XML_FRAGMENT)
<API key> doc
end
it "scrubs documents" do
scrubber = Loofah::Scrubber.new { |node| }
doc = Loofah.xml_document(XML).scrub!(scrubber)
<API key> doc
end
it "scrubs fragments" do
scrubber = Loofah::Scrubber.new { |node| }
doc = Loofah.xml_fragment(XML_FRAGMENT).scrub!(scrubber)
<API key> doc
end
it "scrubs document nodes" do
doc = Loofah.xml_document(XML)
assert(node = doc.at_css("div"))
node.scrub!(:strip)
end
it "scrubs fragment nodes" do
doc = Loofah.xml_fragment(XML)
assert(node = doc.at_css("div"))
node.scrub!(:strip)
end
end
private
def <API key>(doc)
assert_kind_of Nokogiri::HTML::Document, doc
assert_kind_of Loofah::HTML::Document, doc
assert_equal HTML, doc.xpath("/html/body").inner_html
end
def <API key>(doc)
assert_kind_of Nokogiri::HTML::DocumentFragment, doc
assert_kind_of Loofah::HTML::DocumentFragment, doc
assert_equal HTML, doc.inner_html
end
def <API key>(doc)
assert_kind_of Nokogiri::XML::Document, doc
assert_kind_of Loofah::XML::Document, doc
assert_equal XML, doc.root.to_xml
end
def <API key>(doc)
assert_kind_of Nokogiri::XML::DocumentFragment, doc
assert_kind_of Loofah::XML::DocumentFragment, doc
assert_equal XML_FRAGMENT, doc.children.to_xml
end
end |
#ifndef AIR_430BOOST_FCC_H
#define AIR_430BOOST_FCC_H
#include "utility/A110x2500Radio.h"
#endif /* AIR_430BOOST_FCC_H */ |
using System.Collections.Generic;
using Orchard.Scripting.Compiler;
namespace Orchard.Scripting.Ast {
public class MethodCallAstNode : AstNode, IAstNodeWithToken {
private readonly Token _token;
private readonly IList<AstNode> _arguments;
public MethodCallAstNode(Token token, IList<AstNode> arguments) {
_token = token;
_arguments = arguments;
}
public Token Target { get { return _token; } }
public IList<AstNode> Arguments { get { return _arguments; } }
public Token Token { get { return _token; } }
public override IEnumerable<AstNode> Children {
get { return _arguments; }
}
public override object Accept(AstVisitor visitor) {
return visitor.VisitMethodCall(this);
}
}
} |
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class <API key> : <API key>
{
public <API key>()
: base(SyntaxKind.StringKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, Cancellation<API key>)
{
var syntaxTree = context.SyntaxTree;
return
context.<API key> ||
context.<API key> ||
context.IsStatementContext ||
context.<API key> ||
context.<API key> ||
(context.<API key> && !context.TargetToken.Parent.HasAncestor<<API key>>()) ||
context.IsIsOrAsTypeContext ||
context.<API key> ||
context.<API key> ||
context.<API key> ||
context.<API key> ||
context.<API key> ||
context.IsCrefContext ||
syntaxTree.<API key>(position, context.LeftToken, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
context.<API key> ||
syntaxTree.<API key>(position, SyntaxKindSet.<API key>, cancellationToken) ||
context.<API key>(
validModifiers: SyntaxKindSet.AllMemberModifiers,
<API key>: SyntaxKindSet.<API key>,
canBePartial: false,
cancellation<API key>);
}
}
} |
var through = require('through2');
var gutil = require('gulp-util');
var Minimize = require('minimize');
module.exports = function(opt){
function minimize (file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(new gutil.PluginError('gulp-minify-html', 'doesn\'t support Streams'));
}
var minimize = new Minimize(opt || {} );
minimize.parse(file.contents.toString(), function (err, data) {
if (err) {
return callback(new gutil.PluginError('gulp-minify-html', err));
}
file.contents = new Buffer(data);
callback(null, file);
});
}
return through.obj(minimize);
} |
#import <Foundation/Foundation.h>
/*!
These fields can be used for the wire format parameter names required by
the |GAITracker| get, set and send methods as well as the set methods in the
|<API key>| class.
*/
extern NSString *const kGAIUseSecure;
extern NSString *const kGAIHitType;
extern NSString *const kGAITrackingId;
extern NSString *const kGAIClientId;
extern NSString *const kGAIDataSource;
extern NSString *const kGAIAnonymizeIp;
extern NSString *const kGAISessionControl;
extern NSString *const <API key>;
extern NSString *const kGAIViewportSize;
extern NSString *const kGAIEncoding;
extern NSString *const kGAIScreenColors;
extern NSString *const kGAILanguage;
extern NSString *const kGAIJavaEnabled;
extern NSString *const kGAIFlashVersion;
extern NSString *const kGAINonInteraction;
extern NSString *const kGAIReferrer;
extern NSString *const kGAILocation;
extern NSString *const kGAIHostname;
extern NSString *const kGAIPage;
extern NSString *const kGAIDescription; // synonym for kGAIScreenName
extern NSString *const kGAIScreenName; // synonym for kGAIDescription
extern NSString *const kGAITitle;
extern NSString *const kGAIAdMobHitId;
extern NSString *const kGAIAppName;
extern NSString *const kGAIAppVersion;
extern NSString *const kGAIAppId;
extern NSString *const kGAIAppInstallerId;
extern NSString *const kGAIUserId;
extern NSString *const kGAIEventCategory;
extern NSString *const kGAIEventAction;
extern NSString *const kGAIEventLabel;
extern NSString *const kGAIEventValue;
extern NSString *const kGAISocialNetwork;
extern NSString *const kGAISocialAction;
extern NSString *const kGAISocialTarget;
extern NSString *const kGAITransactionId;
extern NSString *const <API key>;
extern NSString *const <API key>;
extern NSString *const <API key>;
extern NSString *const kGAITransactionTax;
extern NSString *const kGAICurrencyCode;
extern NSString *const kGAIItemPrice;
extern NSString *const kGAIItemQuantity;
extern NSString *const kGAIItemSku;
extern NSString *const kGAIItemName;
extern NSString *const kGAIItemCategory;
extern NSString *const kGAICampaignSource;
extern NSString *const kGAICampaignMedium;
extern NSString *const kGAICampaignName;
extern NSString *const kGAICampaignKeyword;
extern NSString *const kGAICampaignContent;
extern NSString *const kGAICampaignId;
extern NSString *const kGAITimingCategory;
extern NSString *const kGAITimingVar;
extern NSString *const kGAITimingValue;
extern NSString *const kGAITimingLabel;
extern NSString *const kGAIExDescription;
extern NSString *const kGAIExFatal;
extern NSString *const kGAISampleRate;
extern NSString *const kGAIIdfa;
extern NSString *const <API key>;
// hit types
extern NSString *const kGAIAppView; // deprecated, use kGAIScreenView instead
extern NSString *const kGAIScreenView;
extern NSString *const kGAIEvent;
extern NSString *const kGAISocial;
extern NSString *const kGAITransaction;
extern NSString *const kGAIItem;
extern NSString *const kGAIException;
extern NSString *const kGAITiming;
/*!
This class provides several fields and methods useful as wire format parameter
names. The methods are used for wire format parameter names that are indexed.
*/
@interface GAIFields : NSObject
/*!
Generates the correct parameter name for a content group with an index.
@param index the index of the content group.
@return an NSString representing the content group parameter for the index.
*/
+ (NSString *)<API key>:(NSUInteger)index;
/*!
Generates the correct parameter name for a custon dimension with an index.
@param index the index of the custom dimension.
@return an NSString representing the custom dimension parameter for the index.
*/
+ (NSString *)<API key>:(NSUInteger)index;
/*!
Generates the correct parameter name for a custom metric with an index.
@param index the index of the custom metric.
@return an NSString representing the custom metric parameter for the index.
*/
+ (NSString *)<API key>:(NSUInteger)index;
@end |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by mixed-content/generic/tools/generate.py using mixed-content/generic/template/test.release.html.template. -->
<html>
<head>
<title>Mixed-Content: <API key> content</title>
<meta charset='utf-8'>
<meta name="description" content="Test behavior of <API key> content">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="http://www.w3.org/TR/mixed-content/#<API key>">
<meta name="assert" content="opt_in_method: meta-csp
origin: cross-origin-http
source_scheme: https
context_nesting: top-level
redirection: no-redirect
subresource: link-prefetch-tag
expectation: blocked">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/mixed-content/generic/common.js"></script>
<script src="/mixed-content/generic/<API key>.js?pipe=sub"></script>
</head>
<body>
<script>
<API key>(
{
"opt_in_method": "meta-csp",
"origin": "cross-origin-http",
"source_scheme": "https",
"context_nesting": "top-level",
"redirection": "no-redirect",
"subresource": "link-prefetch-tag",
"expectation": "blocked"
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html> |
function template(locals) {
var pug_html = "", pug_mixins = {}, pug_interp;
pug_html = pug_html + "<pre><code>code sample\n</code></pre>\n<h1>Heading</h1>\n";
return pug_html;
} |
// @target: es5
var x = `\u{48}\u{65}\u{6c}\u{6c}\u{6f}\u{20}\u{77}\u{6f}\u{72}\u{6c}\u{64}`; |
// <API key>: BSD-3-Clause OR GPL-2.0
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "acdispat.h"
#include "acinterp.h"
#include "acevents.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nsinit")
/* Local prototypes */
static acpi_status
<API key>(acpi_handle obj_handle,
u32 level, void *context, void **return_value);
static acpi_status
<API key>(acpi_handle obj_handle,
u32 nesting_level, void *context, void **return_value);
static acpi_status
<API key>(acpi_handle obj_handle,
u32 nesting_level, void *context, void **return_value);
acpi_status <API key>(void)
{
acpi_status status;
struct acpi_init_walk_info info;
ACPI_FUNCTION_TRACE(<API key>);
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"[Init] Completing Initialization of ACPI Objects\n"));
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"**** Starting initialization of namespace objects ****\n"));
<API key>((ACPI_DB_INIT,
"Final data object initialization: "));
/* Clear the info block */
memset(&info, 0, sizeof(struct acpi_init_walk_info));
/* Walk entire namespace from the supplied root */
/*
* TBD: will become ACPI_TYPE_PACKAGE as this type object
* is now the only one that supports deferred initialization
* (forward references).
*/
status = acpi_walk_namespace(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, <API key>,
NULL, &info, NULL);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status, "During WalkNamespace"));
}
<API key>((ACPI_DB_INIT,
"Namespace contains %u (0x%X) objects\n",
info.object_count, info.object_count));
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"%u Control Methods found\n%u Op Regions found\n",
info.method_count, info.op_region_count));
return_ACPI_STATUS(AE_OK);
}
acpi_status <API key>(u32 flags)
{
acpi_status status = AE_OK;
struct <API key> info;
acpi_handle handle;
ACPI_FUNCTION_TRACE(<API key>);
if (!(flags & ACPI_NO_DEVICE_INIT)) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"[Init] Initializing ACPI Devices\n"));
/* Init counters */
info.device_count = 0;
info.num_STA = 0;
info.num_INI = 0;
<API key>((ACPI_DB_INIT,
"Initializing Device/Processor/Thermal objects "
"and executing _INI/_STA methods:\n"));
/* Tree analysis: find all subtrees that contain _INI methods */
status = <API key>(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, FALSE,
<API key>, NULL,
&info, NULL);
if (ACPI_FAILURE(status)) {
goto error_exit;
}
/* Allocate the evaluation information block */
info.evaluate_info =
<API key>(sizeof(struct acpi_evaluate_info));
if (!info.evaluate_info) {
status = AE_NO_MEMORY;
goto error_exit;
}
/*
* Execute the "global" _INI method that may appear at the root.
* This support is provided for Windows compatibility (Vista+) and
* is not part of the ACPI specification.
*/
info.evaluate_info->prefix_node = acpi_gbl_root_node;
info.evaluate_info->relative_pathname = METHOD_NAME__INI;
info.evaluate_info->parameters = NULL;
info.evaluate_info->flags = <API key>;
status = acpi_ns_evaluate(info.evaluate_info);
if (ACPI_SUCCESS(status)) {
info.num_INI++;
}
/*
* Execute \_SB._INI.
* There appears to be a strict order requirement for \_SB._INI,
* which should be evaluated before any _REG evaluations.
*/
status = acpi_get_handle(NULL, "\\_SB", &handle);
if (ACPI_SUCCESS(status)) {
memset(info.evaluate_info, 0,
sizeof(struct acpi_evaluate_info));
info.evaluate_info->prefix_node = handle;
info.evaluate_info->relative_pathname =
METHOD_NAME__INI;
info.evaluate_info->parameters = NULL;
info.evaluate_info->flags = <API key>;
status = acpi_ns_evaluate(info.evaluate_info);
if (ACPI_SUCCESS(status)) {
info.num_INI++;
}
}
}
/*
* Run all _REG methods
*
* Note: Any objects accessed by the _REG methods will be automatically
* initialized, even if they contain executable AML (see the call to
* <API key> below).
*
* Note: According to the ACPI specification, we actually needn't execute
* _REG for system_memory/system_io operation regions, but for PCI_Config
* operation regions, it is required to evaluate _REG for those on a PCI
* root bus that doesn't contain _BBN object. So this code is kept here
* in order not to break things.
*/
if (!(flags & <API key>)) {
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"[Init] Executing _REG OpRegion methods\n"));
status = <API key>();
if (ACPI_FAILURE(status)) {
goto error_exit;
}
}
if (!(flags & ACPI_NO_DEVICE_INIT)) {
/* Walk namespace to execute all _INIs on present devices */
status = <API key>(ACPI_TYPE_ANY, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, FALSE,
<API key>, NULL,
&info, NULL);
/*
* Any _OSI requests should be completed by now. If the BIOS has
* requested any Windows OSI strings, we will always truncate
* I/O addresses to 16 bits -- for Windows compatibility.
*/
if (acpi_gbl_osi_data >= ACPI_OSI_WIN_2000) {
<API key> = TRUE;
}
ACPI_FREE(info.evaluate_info);
if (ACPI_FAILURE(status)) {
goto error_exit;
}
<API key>((ACPI_DB_INIT,
" Executed %u _INI methods requiring %u _STA executions "
"(examined %u objects)\n",
info.num_INI, info.num_STA,
info.device_count));
}
return_ACPI_STATUS(status);
error_exit:
ACPI_EXCEPTION((AE_INFO, status, "During device initialization"));
return_ACPI_STATUS(status);
}
acpi_status
<API key>(acpi_handle obj_handle,
u32 level, void *context, void **return_value)
{
acpi_status status;
union acpi_operand_object *obj_desc;
struct acpi_namespace_node *node =
(struct acpi_namespace_node *)obj_handle;
obj_desc = <API key>(node);
if (!obj_desc) {
return (AE_OK);
}
/* Exit if package is already initialized */
if (obj_desc->package.flags & AOPOBJ_DATA_VALID) {
return (AE_OK);
}
status = <API key>(obj_desc);
if (ACPI_FAILURE(status)) {
return (AE_OK);
}
status =
<API key>(obj_desc, NULL,
<API key>, NULL);
if (ACPI_FAILURE(status)) {
return (AE_OK);
}
obj_desc->package.flags |= AOPOBJ_DATA_VALID;
return (AE_OK);
}
static acpi_status
<API key>(acpi_handle obj_handle,
u32 level, void *context, void **return_value)
{
acpi_object_type type;
acpi_status status = AE_OK;
struct acpi_init_walk_info *info =
(struct acpi_init_walk_info *)context;
struct acpi_namespace_node *node =
(struct acpi_namespace_node *)obj_handle;
union acpi_operand_object *obj_desc;
ACPI_FUNCTION_NAME(ns_init_one_object);
info->object_count++;
/* And even then, we are only interested in a few object types */
type = acpi_ns_get_type(obj_handle);
obj_desc = <API key>(node);
if (!obj_desc) {
return (AE_OK);
}
/* Increment counters for object types we are looking for */
switch (type) {
case ACPI_TYPE_REGION:
info->op_region_count++;
break;
case <API key>:
info->field_count++;
break;
case <API key>:
info->field_count++;
break;
case ACPI_TYPE_BUFFER:
info->buffer_count++;
break;
case ACPI_TYPE_PACKAGE:
info->package_count++;
break;
default:
/* No init required, just exit now */
return (AE_OK);
}
/* If the object is already initialized, nothing else to do */
if (obj_desc->common.flags & AOPOBJ_DATA_VALID) {
return (AE_OK);
}
/* Must lock the interpreter before executing AML code */
<API key>();
/*
* Only initialization of Package objects can be deferred, in order
* to support forward references.
*/
switch (type) {
case <API key>:
/* TBD: bank_fields do not require deferred init, remove this code */
info->field_init++;
status = <API key>(obj_desc);
break;
case ACPI_TYPE_PACKAGE:
/* Complete the initialization/resolution of the package object */
info->package_init++;
status =
<API key>(obj_handle, level, NULL, NULL);
break;
default:
/* No other types should get here */
status = AE_TYPE;
ACPI_EXCEPTION((AE_INFO, status,
"Opcode is not deferred [%4.4s] (%s)",
<API key>(node),
<API key>(type)));
break;
}
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Could not execute arguments for [%4.4s] (%s)",
<API key>(node),
<API key>(type)));
}
/*
* We ignore errors from above, and always return OK, since we don't want
* to abort the walk on any single error.
*/
<API key>();
return (AE_OK);
}
static acpi_status
<API key>(acpi_handle obj_handle,
u32 nesting_level, void *context, void **return_value)
{
struct <API key> *info =
ACPI_CAST_PTR(struct <API key>, context);
struct acpi_namespace_node *node;
struct acpi_namespace_node *parent_node;
/* Keep count of device/processor/thermal objects */
node = ACPI_CAST_PTR(struct acpi_namespace_node, obj_handle);
if ((node->type == ACPI_TYPE_DEVICE) ||
(node->type == ACPI_TYPE_PROCESSOR) ||
(node->type == ACPI_TYPE_THERMAL)) {
info->device_count++;
return (AE_OK);
}
/* We are only looking for methods named _INI */
if (!<API key>(node->name.ascii, METHOD_NAME__INI)) {
return (AE_OK);
}
/*
* The only _INI methods that we care about are those that are
* present under Device, Processor, and Thermal objects.
*/
parent_node = node->parent;
switch (parent_node->type) {
case ACPI_TYPE_DEVICE:
case ACPI_TYPE_PROCESSOR:
case ACPI_TYPE_THERMAL:
/* Mark parent and bubble up the INI present flag to the root */
while (parent_node) {
parent_node->flags |= <API key>;
parent_node = parent_node->parent;
}
break;
default:
break;
}
return (AE_OK);
}
static acpi_status
<API key>(acpi_handle obj_handle,
u32 nesting_level, void *context, void **return_value)
{
struct <API key> *walk_info =
ACPI_CAST_PTR(struct <API key>, context);
struct acpi_evaluate_info *info = walk_info->evaluate_info;
u32 flags;
acpi_status status;
struct acpi_namespace_node *device_node;
ACPI_FUNCTION_TRACE(ns_init_one_device);
/* We are interested in Devices, Processors and thermal_zones only */
device_node = ACPI_CAST_PTR(struct acpi_namespace_node, obj_handle);
if ((device_node->type != ACPI_TYPE_DEVICE) &&
(device_node->type != ACPI_TYPE_PROCESSOR) &&
(device_node->type != ACPI_TYPE_THERMAL)) {
return_ACPI_STATUS(AE_OK);
}
/*
* Because of an earlier namespace analysis, all subtrees that contain an
* _INI method are tagged.
*
* If this device subtree does not contain any _INI methods, we
* can exit now and stop traversing this entire subtree.
*/
if (!(device_node->flags & <API key>)) {
return_ACPI_STATUS(AE_CTRL_DEPTH);
}
/*
* Run _STA to determine if this device is present and functioning. We
* must know this information for two important reasons (from ACPI spec):
*
* 1) We can only run _INI if the device is present.
* 2) We must abort the device tree walk on this subtree if the device is
* not present and is not functional (we will not examine the children)
*
* The _STA method is not required to be present under the device, we
* assume the device is present if _STA does not exist.
*/
ACPI_DEBUG_EXEC(<API key>
(ACPI_TYPE_METHOD, device_node, METHOD_NAME__STA));
status = acpi_ut_execute_STA(device_node, &flags);
if (ACPI_FAILURE(status)) {
/* Ignore error and move on to next device */
return_ACPI_STATUS(AE_OK);
}
/*
* Flags == -1 means that _STA was not found. In this case, we assume that
* the device is both present and functional.
*
* From the ACPI spec, description of _STA:
*
* "If a device object (including the processor object) does not have an
* _STA object, then OSPM assumes that all of the above bits are set (in
* other words, the device is present, ..., and functioning)"
*/
if (flags != ACPI_UINT32_MAX) {
walk_info->num_STA++;
}
/*
* Examine the PRESENT and FUNCTIONING status bits
*
* Note: ACPI spec does not seem to specify behavior for the present but
* not functioning case, so we assume functioning if present.
*/
if (!(flags & <API key>)) {
/* Device is not present, we must examine the Functioning bit */
if (flags & <API key>) {
/*
* Device is not present but is "functioning". In this case,
* we will not run _INI, but we continue to examine the children
* of this device.
*
* From the ACPI spec, description of _STA: (note - no mention
* of whether to run _INI or not on the device in question)
*
* "_STA may return bit 0 clear (not present) with bit 3 set
* (device is functional). This case is used to indicate a valid
* device for which no device driver should be loaded (for example,
* a bridge device.) Children of this device may be present and
* valid. OSPM should continue enumeration below a device whose
* _STA returns this bit combination"
*/
return_ACPI_STATUS(AE_OK);
} else {
/*
* Device is not present and is not functioning. We must abort the
* walk of this subtree immediately -- don't look at the children
* of such a device.
*
* From the ACPI spec, description of _INI:
*
* "If the _STA method indicates that the device is not present,
* OSPM will not run the _INI and will not examine the children
* of the device for _INI methods"
*/
return_ACPI_STATUS(AE_CTRL_DEPTH);
}
}
/*
* The device is present or is assumed present if no _STA exists.
* Run the _INI if it exists (not required to exist)
*
* Note: We know there is an _INI within this subtree, but it may not be
* under this particular device, it may be lower in the branch.
*/
if (!<API key>(device_node->name.ascii, "_SB_") ||
device_node->parent != acpi_gbl_root_node) {
ACPI_DEBUG_EXEC(<API key>
(ACPI_TYPE_METHOD, device_node,
METHOD_NAME__INI));
memset(info, 0, sizeof(struct acpi_evaluate_info));
info->prefix_node = device_node;
info->relative_pathname = METHOD_NAME__INI;
info->parameters = NULL;
info->flags = <API key>;
status = acpi_ns_evaluate(info);
if (ACPI_SUCCESS(status)) {
walk_info->num_INI++;
}
#ifdef ACPI_DEBUG_OUTPUT
else if (status != AE_NOT_FOUND) {
/* Ignore error and move on to next device */
char *scope_name =
<API key>(device_node, TRUE);
ACPI_EXCEPTION((AE_INFO, status,
"during %s._INI execution",
scope_name));
ACPI_FREE(scope_name);
}
#endif
}
/* Ignore errors from above */
status = AE_OK;
/*
* The _INI method has been run if present; call the Global Initialization
* Handler for this device.
*/
if (<API key>) {
status =
<API key>(device_node, <API key>);
}
return_ACPI_STATUS(status);
} |
#include "ProtocolIAP.h"
#include "PluginJniHelper.h"
#include <android/log.h>
#include "PluginUtils.h"
#include "PluginJavaData.h"
namespace cocos2d { namespace plugin {
extern "C" {
JNIEXPORT void JNICALL <API key>(JNIEnv* env, jobject thiz, jstring className, jint ret, jstring msg)
{
std::string strMsg = PluginJniHelper::jstring2string(msg);
std::string strClassName = PluginJniHelper::jstring2string(className);
PluginProtocol* pPlugin = PluginUtils::getPluginPtr(strClassName);
PluginUtils::outputLog("ProtocolIAP", "nativeOnPayResult(), Get plugin ptr : %p", pPlugin);
if (pPlugin != NULL)
{
PluginUtils::outputLog("ProtocolIAP", "nativeOnPayResult(), Get plugin name : %s", pPlugin->getPluginName());
ProtocolIAP* pIAP = dynamic_cast<ProtocolIAP*>(pPlugin);
if (pIAP != NULL)
{
pIAP->onPayResult((PayResultCode) ret, strMsg.c_str());
}
else
{
ProtocolIAP::ProtocolIAPCallback callback = pIAP->getCallback();
if(callback)
callback(ret, strMsg);
}
}
}
}
bool ProtocolIAP::_paying = false;
ProtocolIAP::ProtocolIAP()
: _listener(NULL)
{
}
ProtocolIAP::~ProtocolIAP()
{
}
void ProtocolIAP::configDeveloperInfo(TIAPDeveloperInfo devInfo)
{
if (devInfo.empty())
{
PluginUtils::outputLog("ProtocolIAP", "The developer info is empty!");
return;
}
else
{
PluginJavaData* pData = PluginUtils::getPluginJavaData(this);
PluginJniMethodInfo t;
if (PluginJniHelper::getMethodInfo(t
, pData->jclassName.c_str()
, "configDeveloperInfo"
, "(Ljava/util/Hashtable;)V"))
{
// generate the hashtable from map
jobject obj_Map = PluginUtils::createJavaMapObject(&devInfo);
// invoke java method
t.env->CallVoidMethod(pData->jobj, t.methodID, obj_Map);
t.env->DeleteLocalRef(obj_Map);
t.env->DeleteLocalRef(t.classID);
}
}
}
void ProtocolIAP::payForProduct(TProductInfo info)
{
if (_paying)
{
PluginUtils::outputLog("ProtocolIAP", "Now is paying");
return;
}
if (info.empty())
{
if (NULL != _listener)
{
onPayResult(kPayFail, "Product info error");
}
PluginUtils::outputLog("ProtocolIAP", "The product info is empty!");
return;
}
else
{
_paying = true;
_curInfo = info;
PluginJavaData* pData = PluginUtils::getPluginJavaData(this);
PluginJniMethodInfo t;
if (PluginJniHelper::getMethodInfo(t
, pData->jclassName.c_str()
, "payForProduct"
, "(Ljava/util/Hashtable;)V"))
{
// generate the hashtable from map
jobject obj_Map = PluginUtils::createJavaMapObject(&info);
// invoke java method
t.env->CallVoidMethod(pData->jobj, t.methodID, obj_Map);
t.env->DeleteLocalRef(obj_Map);
t.env->DeleteLocalRef(t.classID);
}
}
}
void ProtocolIAP::payForProduct(TProductInfo info, ProtocolIAPCallback cb)
{
_callback = cb;
payForProduct(info);
}
void ProtocolIAP::setResultListener(PayResultListener* pListener)
{
_listener = pListener;
}
void ProtocolIAP::onPayResult(PayResultCode ret, const char* msg)
{
_paying = false;
if (_listener)
{
_listener->onPayResult(ret, msg, _curInfo);
}
else
{
PluginUtils::outputLog("ProtocolIAP", "Result listener is null!");
}
_curInfo.clear();
PluginUtils::outputLog("ProtocolIAP", "Pay result is : %d(%s)", (int) ret, msg);
}
}} // namespace cocos2d { namespace plugin { |
// PR c++/56871
// { dg-do compile { target c++11 } }
template<typename T> constexpr int foo(T);
template<> int foo(int);
template<> int foo(int); // { dg-error "previous" }
template<> constexpr int foo(int); // { dg-error "redeclaration" }
template<typename T> int bar(T);
template<> constexpr int bar(int);
template<> constexpr int bar(int); // { dg-error "previous" }
template<> int bar(int); // { dg-error "redeclaration" } |
(function(window, angular, undefined) {'use strict';
/**
* @ngdoc module
* @name ngCookies
* @description
*
* # ngCookies
*
* The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies.
*
*
* <div <API key>="ngCookies"></div>
*
* See {@link ngCookies.$cookies `$cookies`} and
* {@link ngCookies.$cookieStore `$cookieStore`} for usage.
*/
angular.module('ngCookies', ['ng']).
/**
* @ngdoc service
* @name $cookies
*
* @description
* Provides read/write access to browser's cookies.
*
* Only a simple Object is exposed and by adding or removing properties to/from this object, new
* cookies are created/deleted at the end of current $eval.
* The object's properties can only be strings.
*
* Requires the {@link ngCookies `ngCookies`} module to be installed.
*
* @example
*
* ```js
* angular.module('cookiesExample', ['ngCookies'])
* .controller('ExampleController', ['$cookies', function($cookies) {
* // Retrieving a cookie
* var favoriteCookie = $cookies.myFavorite;
* // Setting a cookie
* $cookies.myFavorite = 'oatmeal';
* }]);
* ```
*/
factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
var cookies = {},
lastCookies = {},
lastBrowserCookies,
runEval = false,
copy = angular.copy,
isUndefined = angular.isUndefined;
//creates a poller fn that copies all cookies from the $browser to service & inits the service
$browser.addPollFn(function() {
var currentCookies = $browser.cookies();
if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
lastBrowserCookies = currentCookies;
copy(currentCookies, lastCookies);
copy(currentCookies, cookies);
if (runEval) $rootScope.$apply();
}
})();
runEval = true;
//at the end of each eval, push cookies
//TODO: this should happen before the "delayed" watches fire, because if some cookies are not
// strings or browser refuses to store some cookies, we update the model in the push fn.
$rootScope.$watch(push);
return cookies;
/**
* Pushes all the cookies from the service to the browser and verifies if all cookies were
* stored.
*/
function push() {
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!angular.isString(value)) {
value = '' + value;
cookies[name] = value;
}
if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
}]).
/**
* @ngdoc service
* @name $cookieStore
* @requires $cookies
*
* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.
*
* Requires the {@link ngCookies `ngCookies`} module to be installed.
*
* @example
*
* ```js
* angular.module('cookieStoreExample', ['ngCookies'])
* .controller('ExampleController', ['$cookieStore', function($cookieStore) {
* // Put cookie
* $cookieStore.put('myFavorite','oatmeal');
* // Get cookie
* var favoriteCookie = $cookieStore.get('myFavorite');
* // Removing a cookie
* $cookieStore.remove('myFavorite');
* }]);
* ```
*/
factory('$cookieStore', ['$cookies', function($cookies) {
return {
/**
* @ngdoc method
* @name $cookieStore#get
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
get: function(key) {
var value = $cookies[key];
return value ? angular.fromJson(value) : value;
},
/**
* @ngdoc method
* @name $cookieStore#put
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$cookies[key] = angular.toJson(value);
},
/**
* @ngdoc method
* @name $cookieStore#remove
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
delete $cookies[key];
}
};
}]);
})(window, window.angular); |
/*
* The GT64260 has 2 PCI buses each with 1 window from the CPU bus to
* PCI I/O space and 4 windows from the CPU bus to PCI MEM space.
*/
#ifndef <API key>
#define <API key>
/*
* Define bd_t to pass in the MAC addresses used by the GT64260's enet ctlrs.
*/
#define CPCI690_BI_MAGIC 0xFE8765DC
typedef struct board_info {
u32 bi_magic;
u8 bi_enetaddr[3][6];
} bd_t;
/* PCI bus Resource setup */
#define <API key> 0x80000000
#define <API key> 0x00000000
#define <API key> 0x80000000
#define <API key> 0x10000000
#define <API key> 0xa0000000
#define <API key> 0x00000000
#define <API key> 0x01000000
#define <API key> 0x90000000
#define <API key> 0x00000000
#define <API key> 0x90000000
#define <API key> 0x10000000
#define <API key> 0xa1000000
#define <API key> 0x01000000
#define <API key> 0x01000000
/* Board Registers */
#define CPCI690_BR_BASE 0xf0000000
#define <API key> 0x8
#define CPCI690_BR_SIZE max(<API key>, \
<API key>)
#define CPCI690_BR_LED_CNTL 0x00
#define CPCI690_BR_SW_RESET 0x01
#define <API key> 0x02
#define <API key> 0x03
#define CPCI690_BR_MEM_CTLR 0x04
#define <API key> 0x05
#define <API key> 0x06
#define CPCI690_TODC_BASE 0xf0100000
#define <API key> 0x8000 /* Size or NVRAM + RTC */
#define CPCI690_TODC_SIZE max(<API key>, \
<API key>)
#define CPCI690_MAC_OFFSET 0x7c10 /* MAC in RTC NVRAM */
#define CPCI690_IPMI_BASE 0xf0200000
#define <API key> 0x10 /* 16 bytes of IPMI */
#define CPCI690_IPMI_SIZE max(<API key>, \
<API key>)
#define CPCI690_MPSC_BAUD 9600
#define <API key> 8 /* TCLK */
#endif /* <API key> */ |
(function()
{
angular.module('legendDirectives', [])
.directive('simpleSvgLegend', function(){
return {
restrict: 'EA',
scope: {
id: '@',
width: '@',
height: '@',
margin: '@',
x: '@',
y: '@',
labels: '@',
styles: '@',
classes: '@',
shapes: '@', //rect, circle, ellipse
padding: '@',
columns: '@'
},
compile: function(){
return function link(scope, element, attrs){
"use strict";
var id,
width,
height,
margin,
widthTracker = 0,
heightTracker = 0,
columns = 1,
columnTracker = 0,
padding = 10,
paddingStr,
svgNamespace = 'http:
svg,
g,
labels,
styles,
classes,
shapes,
x = 0,
y = 0,
container;
margin = (scope.$eval(attrs.margin) || {left:5, top:5, bottom:5, right:5});
width = (attrs.width === "undefined" ? ((element[0].parentElement.offsetWidth) - (margin.left + margin.right)) : (+attrs.width - (margin.left + margin.right)));
height = (attrs.height === "undefined" ? ((element[0].parentElement.offsetHeight) - (margin.top + margin.bottom)) : (+attrs.height - (margin.top + margin.bottom)));
if(!attrs.id){
//if an id is not supplied, create a random id.
id = 'legend-' + Math.random();
} else {
id = attrs.id;
}
container = d3.select(this).classed('legend-' + id, true);
if(attrs.columns){
columns = (+attrs.columns);
}
if(attrs.padding){
padding = (+attrs.padding);
}
paddingStr = padding + '';
svg = document.createElementNS(svgNamespace, 'svg');
if(attrs.width){
svg.setAttribute('width', width + '');
}
if(attrs.height){
svg.setAttribute('height', height + '');
}
svg.setAttribute('id', id);
if(attrs.x){
x = (+attrs.x);
}
if(attrs.y){
y = (+attrs.y);
}
element.append(svg);
g = document.createElementNS(svgNamespace, 'g');
g.setAttribute('transform', 'translate(' + x + ',' + y + ')');
svg.appendChild(g);
if(attrs.labels){
labels = scope.$eval(attrs.labels);
}
if(attrs.styles){
styles = scope.$eval(attrs.styles);
}
if(attrs.classes){
classes = scope.$eval(attrs.classes);
}
if(attrs.shapes){
shapes = scope.$eval(attrs.shapes);
}
for(var i in labels){
var shpe = shapes[i], shape, text, textSize, g1;
if( ( columnTracker % columns ) === 0 ){
widthTracker = 0;
heightTracker = heightTracker + ( padding + ( padding * 1.5 ) );
}
g1 = document.createElementNS(svgNamespace,'g');
g1.setAttribute('transform', 'translate(' + widthTracker + ', ' + heightTracker + ')');
if(shpe === 'rect'){
shape = document.createElementNS(svgNamespace, 'rect');
//x, y, rx, ry
shape.setAttribute('y', ( 0 - ( padding / 2 ) ) + '');
shape.setAttribute('width', paddingStr);
shape.setAttribute('height', paddingStr);
} else if (shpe === 'ellipse'){
shape = document.createElementNS(svgNamespace, 'ellipse');
shape.setAttribute('rx', paddingStr);
shape.setAttribute('ry', ( padding + ( padding / 2 ) ) + '');
} else {
shape = document.createElementNS(svgNamespace, 'circle');
shape.setAttribute('r', ( padding / 2 ) + '');
}
if(styles && styles[i]){
shape.setAttribute('style', styles[i]);
}
if(classes && classes[i]){
shape.setAttribute('class', classes[i]);
}
g1.appendChild(shape);
widthTracker = widthTracker + shape.clientWidth + ( padding + ( padding / 2 ) );
text = document.createElementNS(svgNamespace, 'text');
text.setAttribute('transform', 'translate(10, 5)');
text.appendChild(document.createTextNode(labels[i]));
g1.appendChild(text);
g.appendChild(g1);
textSize = text.clientWidth;
widthTracker = widthTracker + textSize + ( padding + ( padding * 0.75 ) );
columnTracker++;
}
};
}
};
})
.directive('nvd3Legend', [function(){
'use strict';
var margin, width, height, id;
return {
restrict: 'EA',
scope: {
data: '=',
id: '@',
margin: '&',
width: '@',
height: '@',
key: '&',
color: '&',
align: '@',
rightalign: '@',
updatestate: '@',
radiobuttonmode: '@',
x: '&',
y: '&'
},
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
if(scope.chart){
return d3.select('#' + attrs.id + ' svg')
.attr('height', height)
.attr('width', width)
.datum(data)
.transition()
.duration(250)
.call(scope.chart);
}
margin = (scope.$eval(attrs.margin) || {top: 5, right: 0, bottom: 5, left: 0});
width = (attrs.width === undefined ? ((element[0].parentElement.offsetWidth) - (margin.left + margin.right)) : (+attrs.width - (margin.left + margin.right)));
height = (attrs.height === undefined ? ((element[0].parentElement.offsetHeight) - (margin.top + margin.bottom)) : (+attrs.height - (margin.top + margin.bottom)));
if(width === undefined || width < 0){
width = 400;
}
if(height === undefined || height < 0){
height = 20;
}
if(!attrs.id){
//if an id is not supplied, create a random id.
id = 'legend-' + Math.random();
} else {
id = attrs.id;
}
nv.addGraph({
generate: function(){
var chart = nv.models.legend()
.width(width)
.height(height)
.margin(margin)
.align(attrs.align === undefined ? true : (attrs.align === "true"))
.rightAlign(attrs.rightalign === undefined ? true : (attrs.rightalign === "true"))
.updateState(attrs.updatestate === undefined ? true : (attrs.updatestate === "true"))
.radioButtonMode(attrs.radiobuttonmode === undefined ? false : (attrs.radiobuttonmode === "true"))
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.key(attrs.key === undefined ? function(d) { return d.key; } : scope.key());
if(!d3.select('#' + attrs.id + ' svg')[0][0]){
d3.select('#' + attrs.id).append("svg");
}
d3.select('#' + attrs.id + ' svg')
.attr('height', height)
.attr('width', width)
.datum(data)
.transition()
.duration(250)
.call(chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
}
});
}
});
}
};
}]);
function <API key>(scope, attrs){
'use strict';
var margin = (scope.$eval(attrs.legendmargin) || {left: 0, top: 5, bottom: 5, right: 0});
if (typeof(margin) !== "object") {
// we were passed a vanilla int, convert to full margin object
margin = {left: margin, top: margin, bottom: margin, right: margin};
}
scope.legendmargin = margin;
}
function configureLegend(chart, scope, attrs){
'use strict';
if(chart.legend && attrs.showlegend && (attrs.showlegend === "true")){
<API key>(scope, attrs);
chart.legend.margin(scope.legendmargin);
chart.legend.width(attrs.legendwidth === undefined ? 400 : (+attrs.legendwidth));
chart.legend.height(attrs.legendheight === undefined ? 20 : (+attrs.legendheight));
chart.legend.key(attrs.legendkey === undefined ? function(d) { return d.key; } : scope.legendkey());
chart.legend.color(attrs.legendcolor === undefined ? nv.utils.defaultColor() : scope.legendcolor());
chart.legend.align(attrs.legendalign === undefined ? true : (attrs.legendalign === "true"));
chart.legend.rightAlign(attrs.legendrightalign === undefined ? true : (attrs.legendrightalign === "true"));
chart.legend.updateState(attrs.legendupdatestate === undefined ? true : (attrs.legendupdatestate === "true"));
chart.legend.radioButtonMode(attrs.<API key> === undefined ? false : (attrs.<API key> === "true"));
}
}
function processEvents(chart, scope){
if(chart.dispatch){
if(chart.dispatch.tooltipShow){
chart.dispatch.on('tooltipShow.directive', function(event) {
scope.$emit('tooltipShow.directive', event);
});
}
if(chart.dispatch.tooltipHide){
chart.dispatch.on('tooltipHide.directive', function(event) {
scope.$emit('tooltipHide.directive', event);
});
}
if(chart.dispatch.beforeUpdate){
chart.dispatch.on('beforeUpdate.directive', function(event) {
scope.$emit('beforeUpdate.directive', event);
});
}
if(chart.dispatch.stateChange){
chart.dispatch.on('stateChange.directive', function(event) {
scope.$emit('stateChange.directive', event);
});
}
if(chart.dispatch.changeState){
chart.dispatch.on('changeState.directive', function(event) {
scope.$emit('changeState.directive', event);
});
}
}
if(chart.lines){
chart.lines.dispatch.on('elementMouseover.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.lines.dispatch.on('elementMouseout.tooltip.directive', function(event) {
scope.$emit('elementMouseout.tooltip.directive', event);
});
chart.lines.dispatch.on('elementClick.directive', function(event) {
scope.$emit('elementClick.directive', event);
});
}
if(chart.stacked && chart.stacked.dispatch){
chart.stacked.dispatch.on('areaClick.toggle.directive', function(event) {
scope.$emit('areaClick.toggle.directive', event);
});
chart.stacked.dispatch.on('tooltipShow.directive', function(event){
scope.$emit('tooltipShow.directive', event);
});
chart.stacked.dispatch.on('tooltipHide.directive', function(event){
scope.$emit('tooltipHide.directive', event);
});
}
if(chart.interactiveLayer){
if(chart.interactiveLayer.elementMouseout){
chart.interactiveLayer.dispatch.on('elementMouseout.directive', function(event){
scope.$emit('elementMouseout.directive', event);
});
}
if(chart.interactiveLayer.elementMousemove){
chart.interactiveLayer.dispatch.on('elementMousemove.directive', function(event){
scope.$emit('elementMousemove.directive', event);
});
}
}
if(chart.discretebar){
chart.discretebar.dispatch.on('elementMouseover.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.discretebar.dispatch.on('elementMouseout.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
}
if(chart.multibar){
chart.multibar.dispatch.on('elementMouseover.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.multibar.dispatch.on('elementMouseout.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.multibar.dispatch.on('elementClick.directive', function(event) {
scope.$emit('elementClick.directive', event);
});
}
if(chart.pie){
chart.pie.dispatch.on('elementMouseover.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.pie.dispatch.on('elementMouseout.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
}
if(chart.scatter){
chart.scatter.dispatch.on('elementMouseover.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.scatter.dispatch.on('elementMouseout.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
}
if(chart.bullet){
chart.bullet.dispatch.on('elementMouseover.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
chart.bullet.dispatch.on('elementMouseout.tooltip.directive', function(event) {
scope.$emit('elementMouseover.tooltip.directive', event);
});
}
if(chart.legend){
//'legendClick', 'legendDblclick', 'legendMouseover'
//stateChange
chart.legend.dispatch.on('stateChange.legend.directive', function(event) {
scope.$emit('stateChange.legend.directive', event);
});
chart.legend.dispatch.on('legendClick.directive', function(d, i) {
scope.$emit('legendClick.directive', d, i);
});
chart.legend.dispatch.on('legendDblclick.directive', function(d, i) {
scope.$emit('legendDblclick.directive', d, i);
});
chart.legend.dispatch.on('legendMouseover.directive', function(d, i) {
scope.$emit('legendMouseover.directive', d, i);
});
}
if(chart.controls){
if(chart.controls.legendClick){
chart.controls.dispatch.on('legendClick.directive', function(d, i){
scope.$emit('legendClick.directive', d, i);
});
}
}
}
function configureXaxis(chart, scope, attrs){
"use strict";
if(attrs.xaxisorient){
chart.xAxis.orient(attrs.xaxisorient);
}
if(attrs.xaxisticks){
chart.xAxis.scale().ticks(attrs.xaxisticks);
}
if(attrs.xaxistickvalues){
if(Array.isArray(scope.$eval(attrs.xaxistickvalues))){
chart.xAxis.tickValues(scope.$eval(attrs.xaxistickvalues));
} else if(typeof scope.xaxistickvalues() === 'function'){
chart.xAxis.tickValues(scope.xaxistickvalues());
}
}
if(attrs.xaxisticksubdivide){
chart.xAxis.tickSubdivide(scope.xaxisticksubdivide());
}
if(attrs.xaxisticksize){
chart.xAxis.tickSize(scope.xaxisticksize());
}
if(attrs.xaxistickpadding){
chart.xAxis.tickPadding(scope.xaxistickpadding());
}
if(attrs.xaxistickformat){
chart.xAxis.tickFormat(scope.xaxistickformat());
}
if(attrs.xaxislabel){
chart.xAxis.axisLabel(attrs.xaxislabel);
}
if(attrs.xaxisscale){
chart.xAxis.scale(scope.xaxisscale());
}
if(attrs.xaxisdomain){
chart.xAxis.domain(scope.xaxisdomain());
}
if(attrs.xaxisrange){
chart.xAxis.range(scope.xaxisrange());
}
if(attrs.xaxisrangeband){
chart.xAxis.rangeBand(scope.xaxisrangeband());
}
if(attrs.xaxisrangebands){
chart.xAxis.rangeBands(scope.xaxisrangebands());
}
if(attrs.xaxisshowmaxmin){
chart.xAxis.showMaxMin((attrs.xaxisshowmaxmin === "true"));
}
if(attrs.xaxishighlightzero){
chart.xAxis.highlightZero((attrs.xaxishighlightzero === "true"));
}
if(attrs.xaxisrotatelabels){
chart.xAxis.rotateLabels((+attrs.xaxisrotatelabels));
}
// if(attrs.xaxisrotateylabel){
if(attrs.xaxisstaggerlabels){
chart.xAxis.staggerLabels((attrs.xaxisstaggerlabels === "true"));
}
}
function configureX2axis(chart, scope, attrs){
"use strict";
if(attrs.x2axisorient){
chart.x2Axis.orient(attrs.x2axisorient);
}
if(attrs.x2axisticks){
chart.x2Axis.scale().ticks(attrs.x2axisticks);
}
if(attrs.x2axistickvalues){
if(Array.isArray(scope.$eval(attrs.x2axistickvalues))){
chart.x2Axis.tickValues(scope.$eval(attrs.x2axistickvalues));
} else if(typeof scope.xaxistickvalues() === 'function'){
chart.x2Axis.tickValues(scope.x2axistickvalues());
}
}
if(attrs.x2axisticksubdivide){
chart.x2Axis.tickSubdivide(scope.x2axisticksubdivide());
}
if(attrs.x2axisticksize){
chart.x2Axis.tickSize(scope.x2axisticksize());
}
if(attrs.x2axistickpadding){
chart.x2Axis.tickPadding(scope.x2axistickpadding());
}
if(attrs.x2axistickformat){
chart.x2Axis.tickFormat(scope.x2axistickformat());
}
if(attrs.x2axislabel){
chart.x2Axis.axisLabel(attrs.x2axislabel);
}
if(attrs.x2axisscale){
chart.x2Axis.scale(scope.x2axisscale());
}
if(attrs.x2axisdomain){
chart.x2Axis.domain(scope.x2axisdomain());
}
if(attrs.x2axisrange){
chart.x2Axis.range(scope.x2axisrange());
}
if(attrs.x2axisrangeband){
chart.x2Axis.rangeBand(scope.x2axisrangeband());
}
if(attrs.x2axisrangebands){
chart.x2Axis.rangeBands(scope.x2axisrangebands());
}
if(attrs.x2axisshowmaxmin){
chart.x2Axis.showMaxMin((attrs.x2axisshowmaxmin === "true"));
}
if(attrs.x2axishighlightzero){
chart.x2Axis.highlightZero((attrs.x2axishighlightzero === "true"));
}
if(attrs.x2axisrotatelables){
chart.x2Axis.rotateLabels((+attrs.x2axisrotatelables));
}
// if(attrs.xaxisrotateylabel){
if(attrs.x2axisstaggerlabels){
chart.x2Axis.staggerLabels((attrs.x2axisstaggerlabels === "true"));
}
}
function configureYaxis(chart, scope, attrs){
"use strict";
if(attrs.yaxisorient){
chart.yAxis.orient(attrs.yaxisorient);
}
if(attrs.yaxisticks){
chart.yAxis.scale().ticks(attrs.yaxisticks);
}
if(attrs.yaxistickvalues){
if(Array.isArray(scope.$eval(attrs.yaxistickvalues))){
chart.yAxis.tickValues(scope.$eval(attrs.yaxistickvalues));
} else if(typeof scope.yaxistickvalues() === 'function'){
chart.yAxis.tickValues(scope.yaxistickvalues());
}
}
if(attrs.yaxisticksubdivide){
chart.yAxis.tickSubdivide(scope.yaxisticksubdivide());
}
if(attrs.yaxisticksize){
chart.yAxis.tickSize(scope.yaxisticksize());
}
if(attrs.yaxistickpadding){
chart.yAxis.tickPadding(scope.yaxistickpadding());
}
if(attrs.yaxistickformat){
chart.yAxis.tickFormat(scope.yaxistickformat());
}
if(attrs.yaxislabel){
chart.yAxis.axisLabel(attrs.yaxislabel);
}
if(attrs.yaxisscale){
chart.yAxis.scale(scope.yaxisscale());
}
if(attrs.yaxisdomain){
chart.yAxis.domain(scope.yaxisdomain());
}
if(attrs.yaxisrange){
chart.yAxis.range(scope.yaxisrange());
}
if(attrs.yaxisrangeband){
chart.yAxis.rangeBand(scope.yaxisrangeband());
}
if(attrs.yaxisrangebands){
chart.yAxis.rangeBands(scope.yaxisrangebands());
}
if(attrs.yaxisshowmaxmin){
chart.yAxis.showMaxMin((attrs.yaxisshowmaxmin === "true"));
}
if(attrs.yaxishighlightzero){
chart.yAxis.highlightZero((attrs.yaxishighlightzero === "true"));
}
if(attrs.yaxisrotatelabels){
chart.yAxis.rotateLabels(attrs.yaxisrotatelabels);
}
if(attrs.yaxisrotateylabel){
chart.yAxis.rotateYLabel((attrs.yaxisrotateylabel === "true"));
}
if(attrs.yaxisstaggerlabels){
chart.yAxis.staggerLabels((attrs.yaxisstaggerlabels === "true"));
}
}
function configureY1axis(chart, scope, attrs){
"use strict";
if(attrs.y1axisticks){
chart.y1Axis.scale().ticks(attrs.y1axisticks);
}
if(attrs.y1axistickvalues){
chart.y1Axis.tickValues(attrs.y1axistickvalues);
}
if(attrs.y1axisticksubdivide){
chart.y1Axis.tickSubdivide(scope.y1axisticksubdivide());
}
if(attrs.y1axisticksize){
chart.y1Axis.tickSize(scope.y1axisticksize());
}
if(attrs.y1axistickpadding){
chart.y1Axis.tickPadding(scope.y1axistickpadding());
}
if(attrs.y1axistickformat){
chart.y1Axis.tickFormat(scope.y1axistickformat());
}
if(attrs.y1axislabel){
chart.y1Axis.axisLabel(attrs.y1axislabel);
}
if(attrs.y1axisscale){
chart.y1Axis.yScale(scope.y1axisscale());
}
if(attrs.y1axisdomain){
chart.y1Axis.domain(scope.y1axisdomain());
}
if(attrs.y1axisrange){
chart.y1Axis.range(scope.y1axisrange());
}
if(attrs.y1axisrangeband){
chart.y1Axis.rangeBand(scope.y1axisrangeband());
}
if(attrs.y1axisrangebands){
chart.y1Axis.rangeBands(scope.y1axisrangebands());
}
if(attrs.y1axisshowmaxmin){
chart.y1Axis.showMaxMin((attrs.y1axisshowmaxmin === "true"));
}
if(attrs.y1axishighlightzero){
chart.y1Axis.highlightZero((attrs.y1axishighlightzero === "true"));
}
if(attrs.y1axisrotatelabels){
chart.y1Axis.rotateLabels(scope.y1axisrotatelabels);
}
if(attrs.y1axisrotateylabel){
chart.y1Axis.rotateYLabel((attrs.y1axisrotateylabel === "true"));
}
if(attrs.y1axisstaggerlabels){
chart.y1Axis.staggerlabels((attrs.y1axisstaggerlabels === "true"));
}
}
function configureY2axis(chart, scope, attrs){
"use strict";
if(attrs.y2axisticks){
chart.y2Axis.scale().ticks(attrs.y2axisticks);
}
if(attrs.y2axistickvalues){
chart.y2Axis.tickValues(scope.$eval(attrs.y2axistickvalues));
}
if(attrs.y2axisticksubdivide){
chart.y2Axis.tickSubdivide(scope.y2axisticksubdivide());
}
if(attrs.y2axisticksize){
chart.y2Axis.tickSize(scope.y2axisticksize());
}
if(attrs.y2axistickpadding){
chart.y2Axis.tickPadding(scope.y2axistickpadding());
}
if(attrs.y2axistickformat){
chart.y2Axis.tickFormat(scope.y2axistickformat());
}
if(attrs.y2axislabel){
chart.y2Axis.axisLabel(attrs.y2axislabel);
}
if(attrs.y2axisscale){
chart.y2Axis.yScale(scope.y2axisscale());
}
if(attrs.y2axisdomain){
chart.y2Axis.domain(scope.y2axisdomain());
}
if(attrs.y2axisrange){
chart.y2Axis.range(scope.y2axisrange());
}
if(attrs.y2axisrangeband){
chart.y2Axis.rangeBand(scope.y2axisrangeband());
}
if(attrs.y2axisrangebands){
chart.y2Axis.rangeBands(scope.y2axisrangebands());
}
if(attrs.y2axisshowmaxmin){
chart.y2Axis.showMaxMin((attrs.y2axisshowmaxmin === "true"));
}
if(attrs.y2axishighlightzero){
chart.y2Axis.highlightZero((attrs.y2axishighlightzero === "true"));
}
if(attrs.y2axisrotatelabels){
chart.y2Axis.rotateLabels(scope.y2axisrotatelabels);
}
if(attrs.y2axisrotateylabel){
chart.y2Axis.rotateYLabel((attrs.y2axisrotateylabel === "true"));
}
if(attrs.y2axisstaggerlabels){
chart.y2Axis.staggerlabels((attrs.y2axisstaggerlabels === "true"));
}
}
function initializeMargin(scope, attrs){
'use strict';
var margin = (scope.$eval(attrs.margin) || {left: 50, top: 50, bottom: 50, right: 50});
if (typeof(margin) !== "object") {
// we were passed a vanilla int, convert to full margin object
margin = {left: margin, top: margin, bottom: margin, right: margin};
}
scope.margin = margin;
}
function checkElementID(scope, attrs, element, chart, data) {
'use strict';
var <API key>; //randomly generated if id attribute doesn't exist
if(!attrs.id){
<API key> = "chartid" + Math.floor(Math.random()*1000000001);
angular.element(element).attr('data-chartid', <API key> );
//if an id is not supplied, create a random id.
if(d3.select('[data-chartid=' + <API key> + '] svg').empty()) {
d3.select('[data-chartid=' + <API key> + ']').append('svg')
.attr('height', scope.height)
.attr('width', scope.width)
.datum(data)
.transition().duration((attrs.transitionduration === undefined ? 250 : (+attrs.transitionduration)))
.call(chart);
} else {
d3.select('[data-chartid=' + <API key> + '] svg')
.attr('height', scope.height)
.attr('width', scope.width)
.datum(data)
.transition().duration((attrs.transitionduration === undefined ? 250 : (+attrs.transitionduration)))
.call(chart);
}
} else {
if(d3.select('#' + attrs.id + ' svg').empty()) {
d3.select('#' + attrs.id)
.append('svg');
}
d3.select('#' + attrs.id + ' svg')
.attr('height', scope.height)
.attr('width', scope.width)
.datum(data)
.transition().duration((attrs.transitionduration === undefined ? 250 : (+attrs.transitionduration)))
.call(chart);
}
}
angular.module('nvd3ChartDirectives', [])
.directive('nvd3LineChart', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
showxaxis: '@',
showyaxis: '@',
rightalignyaxis: '@',
defaultstate: '@',
nodata: '@',
margin: '&',
tooltipcontent: '&',
color: '&',
x: '&',
y: '&',
forcex: '@',
forcey: '@',
isArea: '@',
interactive: '@',
clipedge: '@',
clipvoronoi: '@',
interpolate: '@',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '@',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@', //$watch(watchExpression, listener, objectEquality)
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.lineChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceX(attrs.forcex === undefined ? [] : scope.$eval(attrs.forcex)) // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey)) // List of numbers to Force into the Y scale
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.showXAxis(attrs.showxaxis === undefined ? false : (attrs.showxaxis === "true"))
.showYAxis(attrs.showyaxis === undefined ? false : (attrs.showyaxis === "true"))
.rightAlignYAxis(attrs.rightalignyaxis === undefined ? false : (attrs.rightalignyaxis === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.clipEdge(attrs.clipedge === undefined ? false : (attrs.clipedge === "true"))
.clipVoronoi(attrs.clipvoronoi === undefined ? false : (attrs.clipvoronoi === "true"))
.interpolate(attrs.interpolate === undefined ? 'linear' : attrs.interpolate)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.isArea(attrs.isarea === undefined ? function(){return false;} : function(){ return (attrs.isarea === "true"); });
if (chart.<API key>) {
chart.<API key>(attrs.<API key> === undefined ? false : (attrs.<API key> === "true"));
}
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
showxaxis: '@',
showyaxis: '@',
rightalignyaxis: '@',
defaultstate: '@',
nodata: '@',
margin: '&',
tooltipcontent: '&',
color: '&',
x: '&',
y: '&',
forcex: '@',
forcey: '@',
isArea: '@',
interactive: '@',
clipedge: '@',
clipvoronoi: '@',
usevoronoi: '@',
average: '&',
rescaley: '@',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@', //$watch(watchExpression, listener, objectEquality)
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.cumulativeLineChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceX(attrs.forcex === undefined ? [] : scope.$eval(attrs.forcex)) // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey)) // List of numbers to Force into the Y scale
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.showXAxis(attrs.showxaxis === undefined ? false : (attrs.showxaxis === "true"))
.showYAxis(attrs.showyaxis === undefined ? false : (attrs.showyaxis === "true"))
.rightAlignYAxis(attrs.rightalignyaxis === undefined ? false : (attrs.rightalignyaxis === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.clipEdge(attrs.clipedge === undefined ? false : (attrs.clipedge === "true"))
.clipVoronoi(attrs.clipvoronoi === undefined ? false : (attrs.clipvoronoi === "true"))
.useVoronoi(attrs.usevoronoi === undefined ? false : (attrs.usevoronoi === "true"))
.average(attrs.average === undefined ? function(d) { return d.average; } : scope.average())
.color(attrs.color === undefined ? d3.scale.category10().range() : scope.color())
.isArea(attrs.isarea === undefined ? false : (attrs.isarea === "true"));
if (chart.<API key>) {
chart.<API key>(attrs.<API key> === undefined ? false : (attrs.<API key> === "true"));
}
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
showcontrols: '@',
nodata: '@',
margin: '&',
tooltipcontent: '&',
color: '&',
x: '&',
y: '&',
forcex: '@', //List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
forcey: '@', // List of numbers to Force into the Y scale
forcesize: '@', // List of numbers to Force into the Size scale
interactive: '@',
usevoronoi: '@',
clipedge: '@',
interpolate: '@',
style: '@', //stack, stream, stream-center, expand
order: '@', //default, inside-out
offset: '@', //zero, wiggle, silhouette, expand
size: '&', //accessor to get the point size
xScale: '&',
yScale: '&',
xDomain: '&',
yDomain: '&',
xRange: '&',
yRange: '&',
sizeDomain: '&',
callback: '&',
//xaxis
showxaxis: '&',
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
showyaxis: '&',
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.stackedAreaChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceX(attrs.forcex === undefined ? [] : scope.$eval(attrs.forcex)) // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey)) // List of numbers to Force into the Y scale
.size(attrs.size === undefined ? function(d) { return d.size || 1; } : scope.size())
.forceSize(attrs.forcesize === undefined ? [] : scope.$eval(attrs.forcesize)) // List of numbers to Force into the Size scale
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.showControls(attrs.showcontrols === undefined ? false : (attrs.showcontrols === "true"))
.showXAxis(attrs.showxaxis === undefined ? false : (attrs.showxaxis === "true"))
.showYAxis(attrs.showyaxis === undefined ? false : (attrs.showyaxis === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.clipEdge(attrs.clipedge === undefined ? false : (attrs.clipedge === "true"))
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color());
if (chart.<API key>) {
chart.<API key>(attrs.<API key> === undefined ? false : (attrs.<API key> === "true"));
}
if(attrs.usevoronoi){
chart.useVoronoi((attrs.usevoronoi === "true"));
}
if(attrs.style){
chart.style(attrs.style);
}
if(attrs.order){
chart.order(attrs.order);
}
if(attrs.offset){
chart.offset(attrs.offset);
}
if(attrs.interpolate){
chart.interpolate(attrs.interpolate);
}
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
if(attrs.xscale){
chart.xScale(scope.xscale());
}
if(attrs.yscale){
chart.yScale(scope.yscale());
}
if(attrs.xdomain){
chart.xDomain(scope.xdomain());
}
if(attrs.ydomain){
chart.yDomain(scope.ydomain());
}
if(attrs.sizedomain){
chart.sizeDomain(scope.sizedomain());
}
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('nvd3MultiBarChart', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
tooltipcontent: '&',
color: '&',
showcontrols: '@',
nodata: '@',
reducexticks: '@',
staggerlabels: '@',
rotatelabels: '@',
margin: '&',
x: '&',
y: '&',
//forcex is not exposed in the nvd3 multibar.js file. it is not here on purpose.
forcey: '@',
delay: '@',
stacked: '@',
callback: '&',
//xaxis
showxaxis: '&',
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
showyaxis: '&',
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.multiBarChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey)) // List of numbers to Force into the Y scale
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.showControls(attrs.showcontrols === undefined ? false : (attrs.showcontrols === "true"))
.showXAxis(attrs.showxaxis === undefined ? false : (attrs.showxaxis === "true"))
.showYAxis(attrs.showyaxis === undefined ? false : (attrs.showyaxis === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.reduceXTicks(attrs.reducexticks === undefined ? false: (attrs.reducexticks === "true"))
.staggerLabels(attrs.staggerlabels === undefined ? false : (attrs.staggerlabels === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.rotateLabels(attrs.rotatelabels === undefined ? 0 : attrs.rotatelabels)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.delay(attrs.delay === undefined ? 1200 : attrs.delay)
.stacked(attrs.stacked === undefined ? false : (attrs.stacked === "true"));
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
tooltips: '@',
showxaxis: '@',
showyaxis: '@',
tooltipcontent: '&',
staggerlabels: '@',
color: '&',
margin: '&',
nodata: '@',
x: '&',
y: '&',
//forcex is not exposed in the nvd3 multibar.js file. it is not here on purpose.
forcey: '@',
showvalues: '@',
valueformat: '&',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.discreteBarChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey)) // List of numbers to Force into the Y scale
.showValues(attrs.showvalues === undefined ? false : (attrs.showvalues === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.showXAxis(attrs.showxaxis === undefined ? false : (attrs.showxaxis === "true"))
.showYAxis(attrs.showyaxis === undefined ? false : (attrs.showyaxis === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.staggerLabels(attrs.staggerlabels === undefined ? false : (attrs.staggerlabels === "true"))
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color());
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
if(attrs.valueformat){
chart.valueFormat(scope.valueformat());
}
//events
//https://github.com/mbostock/d3/wiki/Internals#wiki-dispatch
//dispatch: 'tooltipShow', 'tooltipHide', 'beforeUpdate',
//discretebar.dispatch: 'elementMouseout.tooltip', 'elementMouseover.tooltip'
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
tooltips: '@',
tooltipcontent: '&',
color: '&',
margin: '&',
nodata: '@',
x: '&',
y: '&',
// forcex: '@',
forcey: '@',
isarea: '@',
interactive: '@',
clipedge: '@',
clipvoronoi: '@',
interpolate: '@',
highlightPoint: '@',
clearHighlights: '@',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.historicalBarChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey)) // List of numbers to Force into the Y scale
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color());
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
if (chart.<API key>) {
chart.<API key>(attrs.<API key> === undefined ? false : (attrs.<API key> === "true"));
}
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
if(attrs.valueformat){
chart.valueFormat(scope.valueformat());
}
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
tooltipcontent: '&',
color: '&',
showcontrols: '@',
margin: '&',
nodata: '@',
x: '&',
y: '&',
//forcex: '@', //forcex is rebound from <API key>, but is not on multibar
forcey: '@',
stacked: '@',
showvalues: '@',
valueformat: '&',
//'xDomain', 'yDomain',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.<API key>()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceY(attrs.forcey === undefined ? [0] : scope.$eval(attrs.forcey))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.showControls(attrs.showcontrols === undefined ? false : (attrs.showcontrols === "true"))
.showValues(attrs.showvalues === undefined ? false : (attrs.showvalues === "true"))
.stacked(attrs.stacked === undefined ? false : (attrs.stacked === "true"));
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
if(attrs.valueformat){
chart.valueFormat(scope.valueformat());
}
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('nvd3PieChart', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlabels: '@',
showlegend: '@',
donutLabelsOutside: '@',
pieLabelsOutside: '@',
labelType: '@',
nodata: '@',
margin: '&',
x: '&',
y: '&',
color: '&',
donut: '@',
donutRatio: '@',
labelThreshold: '@',
description: '&',
tooltips: '@',
tooltipcontent: '&',
valueFormat: '&',
callback: '&',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.pieChart()
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.showLabels(attrs.showlabels === undefined ? false : (attrs.showlabels === "true"))
.labelThreshold(attrs.labelThreshold === undefined ? 0.02 : attrs.labelthreshold)
.labelType(attrs.labeltype === undefined ? 'key' : attrs.labeltype)
.pieLabelsOutside(attrs.pielabelsoutside === undefined ? true : (attrs.pielabelsoutside === "true"))
.valueFormat(attrs.valueformat === undefined ? d3.format(',.2f') : attrs.valueformat)
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.description(attrs.description === undefined ? function(d) { return d.description; } : scope.description())
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.donutLabelsOutside(attrs.donutlabelsoutside === undefined ? false : (attrs.donutlabelsoutside === "true"))
.donut(attrs.donut === undefined ? false : (attrs.donut === "true"))
.donutRatio(attrs.donutratio === undefined ? 0.5 : (attrs.donutratio));
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('nvd3ScatterChart', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
showcontrols: '@',
showDistX: '@',
showDistY: '@',
rightAlignYAxis: '@',
fisheye: '@',
xPadding: '@',
yPadding: '@',
tooltipContent: '&',
tooltipXContent: '&',
tooltipYContent: '&',
color: '&',
margin: '&',
nodata: '@',
transitionDuration: '@',
shape: '&',
onlyCircles: '@',
interactive: '@',
x: '&',
y: '&',
size: '&',
forceX: '@',
forceY: '@',
forceSize: '@',
xrange: '&',
xdomain: '&',
xscale: '&',
yrange: '&',
ydomain: '&',
yscale: '&',
sizerange: '&',
sizedomain: '&',
zscale: '&',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.scatterChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d.x; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d.y; } : scope.y())
.size(attrs.size === undefined ? function(d){ return d.size; }: scope.size())
.forceX(attrs.forcex === undefined ? [] : scope.$eval(attrs.forcex))
.forceY(attrs.forcey === undefined ? [] : scope.$eval(attrs.forcey))
.forceSize(attrs.forcesize === undefined ? [] : scope.$eval(attrs.forcesize))
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.tooltipContent(attrs.tooltipContent === undefined ? null : scope.tooltipContent())
.tooltipXContent(attrs.tooltipxcontent === undefined ? function(key, x) { return '<strong>' + x + '</strong>'; } : scope.tooltipXContent())
.tooltipYContent(attrs.tooltipycontent === undefined ? function(key, x, y) { return '<strong>' + y + '</strong>'; } : scope.tooltipYContent())
.showControls(attrs.showcontrols === undefined ? false : (attrs.showcontrols === "true"))
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.showDistX(attrs.showdistx === undefined ? false : (attrs.showdistx === "true"))
.showDistY(attrs.showdisty === undefined ? false : (attrs.showdisty === "true"))
.xPadding(attrs.xpadding === undefined ? 0 : (+attrs.xpadding))
.yPadding(attrs.ypadding === undefined ? 0 : (+attrs.ypadding))
.fisheye(attrs.fisheye === undefined ? 0 : (+attrs.fisheye))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.transitionDuration(attrs.transitionduration === undefined ? 250 : (+attrs.transitionduration));
if(attrs.shape){
chart.scatter.onlyCircles(false);
chart.scatter.shape(attrs.shape === undefined ? function(d) { return d.shape || 'circle'; } : scope.shape());
}
//'pointActive', 'clipVoronoi', 'clipRadius', 'useVoronoi'
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
if(attrs.xscale){
chart.xDomain(scope.xdomain());
chart.xRange(scope.xrange());
chart.xScale(scope.xscale());
}
if(attrs.yscale){
chart.yDomain(scope.ydomain());
chart.yRange(scope.yrange());
chart.yScale(scope.yscale());
}
if(attrs.zscale){
chart.sizeDomain(scope.sizedomain());
chart.sizeRange(scope.sizerange());
chart.zScale(scope.zscale());
}
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
callback: '&'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.<API key>()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d.x; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d.y; } : scope.y())
.size(attrs.size === undefined ? function(d){ return d.size; }: scope.size())
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.tooltipContent(attrs.tooltipContent === undefined ? null : scope.tooltipContent())
.tooltipXContent(attrs.tooltipxcontent === undefined ? function(key, x) { return '<strong>' + x + '</strong>'; } : scope.tooltipXContent())
.tooltipYContent(attrs.tooltipycontent === undefined ? function(key, x, y) { return '<strong>' + y + '</strong>'; } : scope.tooltipYContent())
.showControls(attrs.showcontrols === undefined ? false : (attrs.showcontrols === "true"))
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.showDistX(attrs.showdistx === undefined ? false : (attrs.showdistx === "true"))
.showDistY(attrs.showdisty === undefined ? false : (attrs.showdisty === "true"))
.xPadding(attrs.xpadding === undefined ? 0 : (+attrs.xpadding))
.yPadding(attrs.ypadding === undefined ? 0 : (+attrs.ypadding))
.fisheye(attrs.fisheye === undefined ? 0 : (+attrs.fisheye))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.transitionDuration(attrs.transitionduration === undefined ? 250 : (+attrs.transitionduration));
if(attrs.shape){
chart.scatter.onlyCircles(false);
chart.scatter.shape(attrs.shape === undefined ? function(d) { return d.shape || 'circle'; } : scope.shape());
}
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
});
}
};
}])
.directive('<API key>', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
showlegend: '@',
tooltips: '@',
showxaxis: '@',
showyaxis: '@',
forceX: '@',
forceY: '@',
forceY2: '@',
rightalignyaxis: '@',
defaultstate: '@',
nodata: '@',
margin: '&',
tooltipcontent: '&',
color: '&',
x: '&',
y: '&',
clipvoronoi: '@',
interpolate: '@',
// 'xScale', 'yScale', 'xDomain', 'yDomain', defined
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
//yaxis
y2axisorient: '&',
y2axisticks: '&',
y2axistickvalues: '&',
y2axisticksubdivide: '&',
y2axisticksize: '&',
y2axistickpadding: '&',
y2axistickformat: '&',
y2axislabel: '&',
y2axisscale: '&',
y2axisdomain: '&',
y2axisrange: '&',
y2axisrangeband: '&',
y2axisrangebands: '&',
y2axisshowmaxmin: '@',
y2axishighlightzero: '@',
y2axisrotatelabels: '@',
y2axisrotateylabel: '@',
y2axisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.linePlusBarChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.interpolate(attrs.interpolate === undefined ? 'linear' : attrs.interpolate)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color());
if(attrs.forcex){
chart.lines.forceX(scope.$eval(attrs.forcex));
chart.bars.forceX(scope.$eval(attrs.forcex));
}
if(attrs.forcey){
chart.lines.forceY(scope.$eval(attrs.forcey));
chart.bars.forceY(scope.$eval(attrs.forcey));
}
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
configureXaxis(chart, scope, attrs);
configureY1axis(chart, scope, attrs);
configureY2axis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
height2: '@',
id: '@',
showlegend: '@',
tooltips: '@',
showxaxis: '@',
showyaxis: '@',
rightalignyaxis: '@',
defaultstate: '@',
nodata: '@',
margin: '&',
margin2: '&',
tooltipcontent: '&',
color: '&',
x: '&',
y: '&',
forceX: '@',
forceY: '@',
clipedge: '@',
clipvoronoi: '@',
interpolate: '@',
isArea: '@',
size: '&',
defined: '&',
interactive: '@',
callback: '&',
//xaxis
xaxisorient: '&',
xaxisticks: '&',
xaxistickvalues: '&xaxistickvalues',
xaxisticksubdivide: '&',
xaxisticksize: '&',
xaxistickpadding: '&',
xaxistickformat: '&',
xaxislabel: '@',
xaxisscale: '&',
xaxisdomain: '&',
xaxisrange: '&',
xaxisrangeband: '&',
xaxisrangebands: '&',
xaxisshowmaxmin: '@',
xaxishighlightzero: '@',
xaxisrotatelabels: '@',
xaxisrotateylabel: '@',
xaxisstaggerlabels: '@',
//x2axis
x2axisorient: '&',
x2axisticks: '&',
x2axistickvalues: '&xaxistickvalues',
x2axisticksubdivide: '&',
x2axisticksize: '&',
x2axistickpadding: '&',
x2axistickformat: '&',
x2axislabel: '@',
x2axisscale: '&',
x2axisdomain: '&',
x2axisrange: '&',
x2axisrangeband: '&',
x2axisrangebands: '&',
x2axisshowmaxmin: '@',
x2axishighlightzero: '@',
x2axisrotatelables: '@',
x2axisrotateylabel: '@',
x2axisstaggerlabels: '@',
//yaxis
yaxisorient: '&',
yaxisticks: '&',
yaxistickvalues: '&yaxistickvalues',
yaxisticksubdivide: '&',
yaxisticksize: '&',
yaxistickpadding: '&',
yaxistickformat: '&',
yaxislabel: '@',
yaxisscale: '&',
yaxisdomain: '&',
yaxisrange: '&',
yaxisrangeband: '&',
yaxisrangebands: '&',
yaxisshowmaxmin: '@',
yaxishighlightzero: '@',
yaxisrotatelabels: '@',
yaxisrotateylabel: '@',
yaxisstaggerlabels: '@',
//yaxis
y2axisorient: '&',
y2axisticks: '&',
y2axistickvalues: '&',
y2axisticksubdivide: '&',
y2axisticksize: '&',
y2axistickpadding: '&',
y2axistickformat: '&',
y2axislabel: '&',
y2axisscale: '&',
y2axisdomain: '&',
y2axisrange: '&',
y2axisrangeband: '&',
y2axisrangebands: '&',
y2axisshowmaxmin: '@',
y2axishighlightzero: '@',
y2axisrotatelabels: '@',
y2axisrotateylabel: '@',
y2axisstaggerlabels: '@',
legendmargin: '&',
legendwidth: '@',
legendheight: '@',
legendkey: '@',
legendcolor: '&',
legendalign: '@',
legendrightalign: '@',
legendupdatestate: '@',
<API key>: '@',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
//setup height 2
//height 2 is 100
//margin
//nvd3 default is {top: 30, right: 30, bottom: 30, left: 60}
//setup margin 2
//nvd3 default is {top: 0, right: 30, bottom: 20, left: 60}
if(attrs.margin2){
var margin2 = (scope.$eval(attrs.margin2));
if (typeof(margin2) !== "object") {
// we were passed a vanilla int, convert to full margin object
margin2 = {left: margin2, top: margin2, bottom: margin2, right: margin2};
}
scope.margin2 = margin2;
} else {
scope.margin2 = {top: 0, right: 30, bottom: 20, left: 60};
}
//'xDomain', 'yDomain', 'xRange', 'yRange', ''clipEdge', 'clipVoronoi'
var chart = nv.models.lineWithFocusChart()
.width(scope.width)
.height(scope.height)
.height2((attrs.height2 === undefined ? 100 : (+attrs.height2)))
.margin(scope.margin)
.margin2(scope.margin2)
.x(attrs.x === undefined ? function(d){ return d[0]; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d[1]; } : scope.y())
.forceX(attrs.forcex === undefined ? [] : scope.$eval(attrs.forcex))
.forceY(attrs.forcey === undefined ? [] : scope.$eval(attrs.forcey))
.showLegend(attrs.showlegend === undefined ? false : (attrs.showlegend === "true"))
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata)
.color(attrs.color === undefined ? nv.utils.defaultColor() : scope.color())
.isArea(attrs.isarea === undefined ? function(){return false;} : function(){ return (attrs.isarea === "true"); })
.size(attrs.size === undefined ? function(d){ return d.size; }: scope.size())
.interactive(attrs.interactive === undefined ? false : (attrs.interactive === "true"))
.interpolate(attrs.interpolate === undefined ? 'linear' : attrs.interpolate);
if(attrs.defined){
chart.defined(scope.defined());
}
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
configureXaxis(chart, scope, attrs);
configureX2axis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
configureY2axis(chart, scope, attrs);
configureLegend(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('nvd3BulletChart', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
margin: '&',
tooltips: '@',
tooltipcontent: '&',
orient: '@', // left, right, top, bottom
ranges: '&', //ranges (bad, satisfactory, good)
markers: '&', // markers (previous, goal)
measures: '&', // measures (actual, forecast)
tickformat: '&',
nodata: '@',
callback: '&',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.bulletChart()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.orient(attrs.orient === undefined ? 'left' : attrs.orient)
.tickFormat(attrs.tickformat === undefined ? null : scope.tickformat())
.tooltips(attrs.tooltips === undefined ? false : (attrs.tooltips === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata);
if(attrs.tooltipcontent){
chart.tooltipContent(scope.tooltipcontent());
}
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('nvd3SparklineChart', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
margin: '&',
x: '&',
y: '&',
color: '&',
xscale: '&',
yscale: '&',
showvalue: '@',
alignvalue: '@',
rightalignvalue: '@',
nodata: '@',
callback: '&',
xaxistickformat: '&',
yaxistickformat: '&',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
$scope.d3Call = function(data, chart){
checkElementID($scope, $attrs, $element, chart, data);
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
initializeMargin(scope, attrs);
var chart = nv.models.sparklinePlus()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d.x; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d.y; } : scope.y())
.color(attrs.color === undefined ? nv.utils.getColor(['#000']) : scope.color())
.showValue(attrs.showvalue === undefined ? true : (attrs.showvalue === "true"))
.alignValue(attrs.alignvalue === undefined ? true : (attrs.alignvalue === "true"))
.rightAlignValue(attrs.rightalignvalue === undefined ? false : (attrs.rightalignvalue === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata);
if(attrs.xScale){
chart.xScale(scope.xScale());
}
if(attrs.yScale){
chart.yScale(scope.yScale());
}
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}])
.directive('<API key>', [function(){
'use strict';
return {
restrict: 'EA',
scope: {
data: '=',
width: '@',
height: '@',
id: '@',
margin: '&',
x: '&',
y: '&',
color: '&',
xscale: '&',
yscale: '&',
showvalue: '@',
alignvalue: '@',
rightalignvalue: '@',
nodata: '@',
callback: '&',
xaxistickformat: '&',
yaxistickformat: '&',
//angularjs specific
objectequality: '@',
//d3.js specific
transitionduration: '@'
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs){
//expect scope to contain bandlineProperties
$scope.d3Call = function(data, chart){
var <API key>; //randomly generated if id attribute doesn't exist
var selectedChart;
var sLineSelection;
var bandlineData;
var bandLines;
if(!$attrs.id){
<API key> = "chartid" + Math.floor(Math.random()*1000000001);
angular.element($element).attr('data-chartid', <API key> );
selectedChart = d3.select('[data-iem-chartid=' + <API key> + '] svg')
.attr('height', $scope.height)
.attr('width', $scope.width)
.datum(data);
//chart.yScale()($scope.bandlineProperties.median)
//var sLineSelection = d3.select('svg#' + $attrs.id + ' g.nvd3.nv-wrap.nv-sparkline');
sLineSelection = d3.select('[data-iem-chartid=' + <API key> + '] svg' + ' g.nvd3.nv-wrap.nv-sparkline');
bandlineData = [
$scope.bandlineProperties.min,
$scope.bandlineProperties.<API key>,
$scope.bandlineProperties.median,
$scope.bandlineProperties.<API key>,
$scope.bandlineProperties.max
];
bandLines = sLineSelection.selectAll('.nv-bandline').data([bandlineData]);
bandLines.enter().append('g')
.attr('class', 'nv-bandline');
selectedChart.transition().duration(($attrs.transitionduration === undefined ? 250 : (+$attrs.transitionduration)))
.call(chart);
}
else{
if (!d3.select('#' + $attrs.id+' svg')){
d3.select('#' + $attrs.id)
.append('svg');
}
selectedChart = d3.select('#' + $attrs.id+' svg')
.attr('height', $scope.height)
.attr('width', $scope.width)
.datum(data);
//chart.yScale()($scope.bandlineProperties.median)
sLineSelection = d3.select('svg#' + $attrs.id + ' g.nvd3.nv-wrap.nv-sparkline');
bandlineData = [
$scope.bandlineProperties.min,
$scope.bandlineProperties.<API key>,
$scope.bandlineProperties.median,
$scope.bandlineProperties.<API key>,
$scope.bandlineProperties.max
];
bandLines = sLineSelection.selectAll('.nv-bandline').data([bandlineData]);
bandLines.enter().append('g')
.attr('class', 'nv-bandline');
selectedChart.transition().duration(($attrs.transitionduration === undefined ? 250 : (+$attrs.transitionduration)))
.call(chart);
}
};
}],
link: function(scope, element, attrs){
scope.$watch('data', function(data){
if(data){
//if the chart exists on the scope, do not call addGraph again, update data and call the chart.
if(scope.chart){
return scope.d3Call(data, scope.chart);
}
nv.addGraph({
generate: function(){
scope.bandlineProperties = {};
var sortedValues;
initializeMargin(scope, attrs);
var chart = nv.models.sparklinePlus()
.width(scope.width)
.height(scope.height)
.margin(scope.margin)
.x(attrs.x === undefined ? function(d){ return d.x; } : scope.x())
.y(attrs.y === undefined ? function(d){ return d.y; } : scope.y())
.color(attrs.color === undefined ? nv.utils.getColor(['#000']) : scope.color())
.showValue(attrs.showvalue === undefined ? true : (attrs.showvalue === "true"))
.alignValue(attrs.alignvalue === undefined ? true : (attrs.alignvalue === "true"))
.rightAlignValue(attrs.rightalignvalue === undefined ? false : (attrs.rightalignvalue === "true"))
.noData(attrs.nodata === undefined ? 'No Data Available.' : scope.nodata);
//calc bandline data
scope.bandlineProperties.min = d3.min(data, function(d){ return d[1]; });
scope.bandlineProperties.max = d3.max(data, function(d){ return d[1]; });
sortedValues = data.map(function(d){
return d[1];
}).sort(function(a, b){
if(a[0] < b[0]){
return -1;
} else if (a[0] === b[0]){
return 0;
} else {
return 1;
}
});
scope.bandlineProperties.<API key> = d3.quantile(sortedValues, 0.25);
scope.bandlineProperties.median = d3.median(sortedValues);
scope.bandlineProperties.<API key> = d3.quantile(sortedValues, 0.75);
if(attrs.xScale){
chart.xScale(scope.xScale());
}
if(attrs.yScale){
chart.yScale(scope.yScale());
}
configureXaxis(chart, scope, attrs);
configureYaxis(chart, scope, attrs);
processEvents(chart, scope);
scope.d3Call(data, chart);
nv.utils.windowResize(chart.update);
scope.chart = chart;
return chart;
},
callback: attrs.callback === undefined ? null : scope.callback()
});
}
}, (attrs.objectequality === undefined ? false : (attrs.objectequality === "true")));
}
};
}]);
//still need to implement
//sparkbars??
//nv.models.<API key>
//nv.models.multiChart
//nv.models.<API key>
//nv.models.<API key>
//dual y-axis chart
//crossfilter using $services?
}()); |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
#include "dsdv-packet-queue.h"
#include <algorithm>
#include <functional>
#include "ns3/ipv4-route.h"
#include "ns3/socket.h"
#include "ns3/log.h"
<API key> ("DsdvPacketQueue");
namespace ns3 {
namespace dsdv {
uint32_t
PacketQueue::GetSize ()
{
Purge ();
return m_queue.size ();
}
bool
PacketQueue::Enqueue (QueueEntry & entry)
{
NS_LOG_FUNCTION ("Enqueing packet destined for" << entry.GetIpv4Header ().GetDestination ());
Purge ();
uint32_t numPacketswithdst;
for (std::vector<QueueEntry>::const_iterator i = m_queue.begin (); i
!= m_queue.end (); ++i)
{
if ((i->GetPacket ()->GetUid () == entry.GetPacket ()->GetUid ())
&& (i->GetIpv4Header ().GetDestination ()
== entry.GetIpv4Header ().GetDestination ()))
{
return false;
}
}
numPacketswithdst = <API key> (entry.GetIpv4Header ().GetDestination ());
NS_LOG_DEBUG ("Number of packets with this destination: " << numPacketswithdst);
/** For Brock Paper comparision*/
if (numPacketswithdst >= m_maxLenPerDst || m_queue.size () >= m_maxLen)
{
NS_LOG_DEBUG ("Max packets reached for this destination. Not queuing any further packets");
return false;
}
else
{
// NS_LOG_DEBUG("Packet size while enqueing "<<entry.GetPacket()->GetSize());
entry.SetExpireTime (m_queueTimeout);
m_queue.push_back (entry);
return true;
}
}
void
PacketQueue::DropPacketWithDst (Ipv4Address dst)
{
NS_LOG_FUNCTION ("Dropping packet to " << dst);
Purge ();
for (std::vector<QueueEntry>::iterator i = m_queue.begin (); i
!= m_queue.end (); ++i)
{
if (IsEqual (*i, dst))
{
Drop (*i, "DropPacketWithDst ");
}
}
m_queue.erase (std::remove_if (m_queue.begin (), m_queue.end (),
std::bind2nd (std::ptr_fun (PacketQueue::IsEqual), dst)), m_queue.end ());
}
bool
PacketQueue::Dequeue (Ipv4Address dst, QueueEntry & entry)
{
NS_LOG_FUNCTION ("Dequeueing packet destined for" << dst);
Purge ();
for (std::vector<QueueEntry>::iterator i = m_queue.begin (); i != m_queue.end (); ++i)
{
if (i->GetIpv4Header ().GetDestination () == dst)
{
entry = *i;
m_queue.erase (i);
return true;
}
}
return false;
}
bool
PacketQueue::Find (Ipv4Address dst)
{
for (std::vector<QueueEntry>::const_iterator i = m_queue.begin (); i
!= m_queue.end (); ++i)
{
if (i->GetIpv4Header ().GetDestination () == dst)
{
NS_LOG_DEBUG ("Find");
return true;
}
}
return false;
}
uint32_t
PacketQueue::<API key> (Ipv4Address dst)
{
uint32_t count = 0;
for (std::vector<QueueEntry>::const_iterator i = m_queue.begin (); i
!= m_queue.end (); ++i)
{
if (i->GetIpv4Header ().GetDestination () == dst)
{
count++;
}
}
return count;
}
struct IsExpired
{
bool
operator() (QueueEntry const & e) const
{
// NS_LOG_DEBUG("Expire time for packet in req queue: "<<e.GetExpireTime ());
return (e.GetExpireTime () < Seconds (0));
}
};
void
PacketQueue::Purge ()
{
// NS_LOG_DEBUG("Purging Queue");
IsExpired pred;
for (std::vector<QueueEntry>::iterator i = m_queue.begin (); i
!= m_queue.end (); ++i)
{
if (pred (*i))
{
NS_LOG_DEBUG ("Dropping outdated Packets");
Drop (*i, "Drop outdated packet ");
}
}
m_queue.erase (std::remove_if (m_queue.begin (), m_queue.end (), pred),
m_queue.end ());
}
void
PacketQueue::Drop (QueueEntry en, std::string reason)
{
NS_LOG_LOGIC (reason << en.GetPacket ()->GetUid () << " " << en.GetIpv4Header ().GetDestination ());
// en.GetErrorCallback () (en.GetPacket (), en.GetIpv4Header (),
// Socket::ERROR_NOROUTETOHOST);
return;
}
}
} |
using System;
namespace Tamir.SharpSsh.jsch.jce
{
/* -*-mode:java; c-basic-offset:2; -*- */
public class Random : Tamir.SharpSsh.jsch.Random
{
private byte[] tmp=new byte[16];
//private SecureRandom random;
private System.Security.Cryptography.<API key> rand;
public Random()
{
// random=null;
// random = new SecureRandom();
// try{ random=SecureRandom.getInstance("SHA1PRNG"); }
// catch(java.security.<API key> e){
// // System.out.println(e);
// // The following code is for IBM's JCE
// try{ random=SecureRandom.getInstance("IBMSecureRandom"); }
// catch(java.security.<API key> ee){
// System.out.println(ee);
rand = new System.Security.Cryptography.<API key>();
}
static int times = 0;
public void fill(byte[] foo, int start, int len)
{
try
{
if(len>tmp.Length){ tmp=new byte[len]; }
//random.nextBytes(tmp);
rand.GetBytes(tmp);
Array.Copy(tmp, 0, foo, start, len);
}
catch(Exception e)
{
times++;
Console.WriteLine(times+") Array.Copy(tmp={0}, 0, foo={1}, {2}, {3}", tmp.Length, foo.Length, start, len);
//Console.WriteLine(e.StackTrace);
}
}
}
} |
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
function getTargetURI() {
return "http:
}
var docsLoaded = -1000000;
var builder = null;
// This function is called by the testing framework before
// running the test suite.
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
function setUpPage() {
setUpPageStatus = 'running';
try {
// creates test document builder, may throw exception
builder = <API key>();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "hc_staff");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
<API key>(builder, ex);
setUpPageStatus = 'complete';
}
}
// This method is called on the completion of
// each asychronous load started in setUpTests.
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
}
}
function <API key>() {
var success;
if(checkInitialization(builder, "<API key>") != null) return;
var doc;
var elementList;
var addressNode;
var clonedNode;
var attributes;
var attributeNode;
var attributeName;
var result = new Array();
htmlExpected = new Array();
htmlExpected[0] = "class";
htmlExpected[1] = "title";
expected = new Array();
expected[0] = "class";
expected[1] = "title";
expected[2] = "dir";
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "hc_staff");
elementList = doc.<API key>("acronym");
addressNode = elementList.item(1);
clonedNode = addressNode.cloneNode(false);
attributes = clonedNode.attributes;
for(var indexN10076 = 0;indexN10076 < attributes.length; indexN10076++) {
attributeNode = attributes.item(indexN10076);
attributeName = attributeNode.nodeName;
result[result.length] = attributeName;
}
if(
(builder.contentType == "text/html")
) {
<API key>("nodeNames_html",toLowerArray(htmlExpected),toLowerArray(result));
}
else {
<API key>("nodeNames",expected,result);
}
}
function runTest() {
<API key>();
} |
/**
* An interface for retrieving documents by URL that the compiler uses
* to load templates.
*/
export declare class XHR {
get(url: string): Promise<string>;
} |
<reference path="./easy-session.d.ts" />
<reference path="../express-session/express-session.d.ts" />
<reference path="../cookie-parser/cookie-parser.d.ts" />
import express = require('express');
import session = require('express-session');
import cookieParser = require('cookie-parser');
import easySession = require('easy-session'); // Require the module : line 1
var app = express();
app.use(cookieParser('secreet'));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use(easySession.main(session));
app.get('/login', function (req, res, next) {
req.session.login('user', {email: 'email'}, function (err) {
if(err) {
res.send(500);
return;
}
res.send(200);
});
});
app.post('/logout', function (req, res, next) {
req.session.logout(function (err) {
if(err) {
res.send(500);
return;
}
res.send(200);
});
});
app.get('/isloggedin', function (req, res, next) {
res.send(req.session.isLoggedIn('user'));
});
app.get('/isfresh', function (req, res, next) {
res.send(req.session.isFresh());
});
app.get('/hasrole', function (req, res, next) {
res.send(req.session.hasRole('user'));
});
app.post('/setrole', function (req, res, next) {
req.session.setRole(req.query.role);
res.send(200);
});
app.get('/getrole', function (req, res, next) {
res.send(req.session.getRole());
});
app.use(easySession.isLoggedIn());
app.use(easySession.isFresh());
app.use(easySession.checkRole('user')); |
#!/bin/bash
LOG_FILE="/var/log/<API key>.log"
# manually set EXECNAME because this file is called from another script and it $0 is "bash"
EXECNAME="install-postgresql.sh"
<API key>='Azure_1'
SLEEP_INTERVAL=5
# logs everything to the $LOG_FILE
log() {
echo "$(date) [${EXECNAME}]: $*" >> "${LOG_FILE}"
}
stop_db()
{
sudo service postgresql stop
}
fail_or_continue()
{
local RET=$1
local STR=$2
if [[ $RET -ne 0 ]]; then
stop_db
if [[ -z $STR ]]; then
STR="--> Error $RET"
fi
log "$STR, giving up"
log "
exit "$RET"
fi
}
create_database()
{
local DB_CMD="sudo -u postgres psql"
local DBNAME=$1
local PW=$2
local ROLE=$DBNAME
#if pass in the third parameter, us it as the ROLE name
if ! [ -z "$3" ];then
local ROLE=$3
echo "$3, $ROLE"
fi
echo "$ROLE"
echo "CREATE ROLE $ROLE LOGIN PASSWORD '$PW';"
$DB_CMD --command "CREATE ROLE $ROLE LOGIN PASSWORD '$PW';"
fail_or_continue $? "Unable to create database role $ROLE"
echo "CREATE DATABASE $DBNAME OWNER $ROLE;"
$DB_CMD --command "CREATE DATABASE $DBNAME OWNER $ROLE;"
fail_or_continue $? "Unable to create database $DBNAME"
}
# Returns 0 if the given DB exists in the DB list file.
db_exists()
{
grep -q -s -e "^$1$" "$DB_LIST_FILE"
}
<API key>()
{
perl -le 'print map { ("a".."z", "A".."Z", 0..9)[rand 62] } 1..10'
}
# Creates the SCM database, if it doesn't exist yet.
create_scm_db()
{
if db_exists scm; then
return 0
fi
local PW=$1
create_database scm "$PW"
orig_umask=$(umask)
umask 0077
echo "Creating SCM configuration file: $DB_PROP_FILE"
cat > "$DB_PROP_FILE" << EOF
# Auto-generated by `basename $0`
# $NOW
# These are database settings for CM Manager
com.cloudera.cmf.db.type=postgresql
com.cloudera.cmf.db.host=localhost:$DB_PORT
com.cloudera.cmf.db.name=scm
com.cloudera.cmf.db.user=scm
com.cloudera.cmf.db.password=$PW
EOF
umask "$orig_umask"
fail_or_continue $? "Error creating file $DB_PROP_FILE"
echo "Created db properties file $DB_PROP_FILE"
backup_file "$DB_LIST_FILE"
echo scm >> "$DB_LIST_FILE"
}
<API key>()
{
# $1 is the MgmtServiceHandler.RoleNames Enum value
# $2 is the database name.
# hive has different db name and role name
local role='HIVEMETASTORESERVER'
local db='metastore'
local hive='hive'
if db_exists $db; then
return 0
fi
echo "Creating DB $db for role $role"
local pw
pw=$(<API key>)
create_database "$db" "$pw" "$hive"
echo "host $db $hive 0.0.0.0/0 md5" >> "$DATA_DIR"/pg_hba.conf
if [[ $MGMT_DB_MODIFIED -eq 0 ]]; then
backup_file "$MGMT_DB_PROP_FILE"
fi
MGMT_DB_MODIFIED=1
# Write the prop file header.
if [[ ! -f $MGMT_DB_PROP_FILE ]]; then
orig_umask=$(umask)
umask 0077
cat > "$MGMT_DB_PROP_FILE" << EOF
# Auto-generated by `basename $0`
# $NOW
# These are database credentials for databases
# Cloudera Manager Management Services,
# to be used during the installation wizard if
# the embedded database route is taken.
# The source of truth for these settings
# is the Cloudera Manager databases and
# changes made here will not be reflected
# there automatically.
EOF
umask "$orig_umask"
fail_or_continue $? "Error creating file $MGMT_DB_PROP_FILE"
fi
local PREFIX="com.cloudera.cmf.$role.db"
# Append the role db properties to the mgmt db props file.
cat >> "$MGMT_DB_PROP_FILE" <<EOF
$PREFIX.type=postgresql
$PREFIX.host=$DB_HOSTPORT
$PREFIX.name=$db
$PREFIX.user=$hive
$PREFIX.password=$pw
EOF
fail_or_continue $? "Error updating file $MGMT_DB_PROP_FILE"
# Update pg_hba.conf for the new database.
echo "host $db $hive 0.0.0.0/0 md5" >> "$DATA_DIR"/pg_hba.conf
echo "Created DB for role $role"
backup_file "$DB_LIST_FILE"
echo "$db" >> "$DB_LIST_FILE"
}
# Creates a database for a specific role, if it doesn't exist yet.
create_mgmt_role_db()
{
# $1 is the MgmtServiceHandler.RoleNames Enum value
# $2 is the database name.
local role=$1
local db=$2
if db_exists "$db"; then
return 0
fi
echo "Creating DB $db for role $role"
local pw
pw=$(<API key>)
create_database "$db" "$pw"
if [[ $MGMT_DB_MODIFIED -eq 0 ]]; then
backup_file "$MGMT_DB_PROP_FILE"
fi
MGMT_DB_MODIFIED=1
# Write the prop file header.
if [[ ! -f $MGMT_DB_PROP_FILE ]]; then
orig_umask=$(umask)
umask 0077
cat > "$MGMT_DB_PROP_FILE" << EOF
# Auto-generated by `basename $0`
# $NOW
# These are database credentials for databases
# Cloudera Manager Management Services,
# to be used during the installation wizard if
# the embedded database route is taken.
# The source of truth for these settings
# is the Cloudera Manager databases and
# changes made here will not be reflected
# there automatically.
EOF
umask "$orig_umask"
fail_or_continue $? "Error creating file $MGMT_DB_PROP_FILE"
fi
local PREFIX="com.cloudera.cmf.$role.db"
# Append the role db properties to the mgmt db props file.
cat >> "$MGMT_DB_PROP_FILE" <<EOF
$PREFIX.type=postgresql
$PREFIX.host=$DB_HOSTPORT
$PREFIX.name=$db
$PREFIX.user=$db
$PREFIX.password=$pw
EOF
fail_or_continue $? "Error updating file $MGMT_DB_PROP_FILE"
# Update pg_hba.conf for the new database.
echo "host $db $db 0.0.0.0/0 md5" >> "$DATA_DIR"/pg_hba.conf
echo "Created DB for role $role"
backup_file "$DB_LIST_FILE"
echo "$db" >> "$DB_LIST_FILE"
}
pg_hba_contains()
{
grep -q -s -e "^$1$" "$DATA_DIR"/pg_hba.conf
}
# changes postgres config to allow remote connections. Idempotent.
<API key>()
{
local FIRSTLINE="# block remote access for admin user"
local SECONDLINE="host all postgres 0.0.0.0/0 reject"
local THIRDLINE="# enable remote access for other users"
local FOURTHLINE="host sameuser all 0.0.0.0/0 md5"
if pg_hba_contains "$FIRSTLINE"; then
return 0
fi
# Update pg_hba.conf for the new database.
echo "$FIRSTLINE" >> "$DATA_DIR"/pg_hba.conf
echo "$SECONDLINE" >> "$DATA_DIR"/pg_hba.conf
echo "$THIRDLINE" >> "$DATA_DIR"/pg_hba.conf
echo "$FOURTHLINE" >> "$DATA_DIR"/pg_hba.conf
echo "Enabled remote connections"
}
# Get the amount of RAM on the system. Uses "free -b" to get the amount
# in bytes and parses the output to get total amount of memory available.
get_system_ram()
{
local free_output
free_output=$(free -b | grep Mem)
local regex="Mem:[[:space:]]+([[:digit:]]+)"
if [[ $free_output =~ $regex ]]; then
echo "${BASH_REMATCH[1]}"
else
fail_or_continue 1 "Unable to find amount of RAM on the system"
fi
}
# We need to set a good value for postgresql shared_buffer parameter. Default
# is 32 MB which is too low. Postgresql recommends setting this to 1/4 of RAM
# if there is more than 1GB of RAM on the system (which is true for most systems
# today). This parameter also depends on the Linux maximum shared memory parameter
# (cat /proc/sys/kernel/shmmax)
# Few linux systems default the shmmax to 32 MB, below that level we should let
# postgresql default as is. Above this value, we will use 50% of the shmmax as
# the shared_buffer default value. Also maximum recommended value is 8GB, so
# we will ceil on 8 GB.
# shared_buffer is specified in kernel buffer cache block size, typically
# 1024 bytes (8192 bits). So the shared_buffer value * 8192 gives the memory
# in bits that will be used (actually table 17-2 of postgresql doc says that
get_shared_buffers()
{
local ram
ram=$(get_system_ram)
local shmmax
shmmax=$(cat /proc/sys/kernel/shmmax)
local THIRTY_TWO_MB=$((32 * 1024 * 1024))
local EIGHT_GB=$((8 * 1024 * 1024 * 1024))
local SIXTEEN_GB=$((16 * 1024 * 1024 * 1024))
local shared_buffer;
# On some systems we get value of shmmax that is out of range for integer
# values that bash can process (see OPSAPS-11583). So we check for any
# value that is greater than 99 GB (length > 11) and then floor shmmax value
# to 16 GB (as 8GB is max shared buffer value, 50% of shmmax)
if [ ${#shmmax} -gt 11 ]; then
shmmax=$SIXTEEN_GB
fi
if [ "$shmmax" -eq "$THIRTY_TWO_MB" ]; then
let "shared_buffer=shmmax / 4"
let "shared_buffer=shared_buffer / (8192 + 208)"
echo "shared_buffers=$shared_buffer"
elif [ "$shmmax" -gt "$THIRTY_TWO_MB" ]; then
let "shared_buffer=shmmax / 2"
if [ "$shared_buffer" -gt "$EIGHT_GB" ]; then
shared_buffer=$EIGHT_GB
fi
let "quarter_of_ram=ram / 4"
if [ "$shared_buffer" -gt "$quarter_of_ram" ]; then
shared_buffer=$quarter_of_ram
fi
let "shared_buffer=shared_buffer / (8192 + 208)"
echo "shared_buffers=$shared_buffer"
fi
}
<API key>()
{
local psql_output
psql_output=$(psql --version)
local regex
regex="^psql \(PostgreSQL\) ([[:digit:]]+)\..*"
if [[ $psql_output =~ $regex ]]; then
echo "${BASH_REMATCH[1]}"
fi
}
<API key>()
{
local psql_version
psql_version=$(<API key>)
if [[ $psql_version -gt 8 ]]; then
# These lines will be fed to sed, add \\ to make them look like single line to sed
echo "# This is needed to make Hive work with Postgresql 9.1 and above\\"
echo "# See OPSAPS-11795\\"
echo "<API key>=off"
fi
}
backup_file()
{
local FILE=$1
if [[ -f $FILE ]] && [[ ! -f $FILE.$NOW ]]; then
cp "$FILE" "$FILE"."$NOW"
fi
}
<API key>()
{
local CONF_FILE="$1"
local IS_UPGRADE="$2"
# Re-configure the listen address and port, since the postgresql-server
# package may be using the default postgres port and listen address.
# Though typically the default configs don't specify a
# port, we try to remove it anyway.
# Listen on all IP addresses, as monitoring services may reside on
# different machines on the LAN.
sed -e '/^listen_addresses\s*=/d' -i "$CONF_FILE"
# Bump up max connections to server and shared buffer space that connections
# need. shared_buffers should be at least 2 * max_connections.
sed -e '/^max_connections\s*=/d' -i "$CONF_FILE"
sed -e '/^shared_buffers\s*=/d' -i "$CONF_FILE"
sed -e '/^<API key>\s*=/d' -i "$CONF_FILE"
# Prepend to the file
local TMPFILE
TMPFILE=$(mktemp /tmp/XXXXXXXX)
if [ "$IS_UPGRADE" -eq 0 ]; then
cat > "$TMPFILE" << EOF
EOF
fi
cat "$CONF_FILE" >> "$TMPFILE"
echo Adding configs
sed -i "2a
sed -i "3a port = $DB_PORT" "$TMPFILE"
sed -i "4a listen_addresses = '*'" "$TMPFILE"
sed -i "5a max_connections = 500" "$TMPFILE"
local LINE_NUM=6
local SHARED_BUFFERS
SHARED_BUFFERS="$(get_shared_buffers)"
if [ -n "${SHARED_BUFFERS}" ]; then
sed -i "${LINE_NUM}a ${SHARED_BUFFERS}" "$TMPFILE"
LINE_NUM=7
fi
local SCS
SCS="$(<API key>)"
if [ -n "${SCS}" ]; then
sed -i "${LINE_NUM}a ${SCS}" "$TMPFILE"
fi
cat "$TMPFILE" > "$CONF_FILE"
}
<API key>()
{
log "Wait for DB server to start"
i=0
until [ $i -ge 5 ]
do
i=$((i+1))
sudo -u postgres psql -l && break
sleep "${SLEEP_INTERVAL}"
done
if [ $i -ge 5 ]; then
log "DB failed to start within $((i * SLEEP_INTERVAL)) seconds, exit with status 1"
log "
exit 1
fi
}
log "
sudo service postgresql initdb
sudo service postgresql start
SCM_PWD=$(<API key>)
DATA_DIR=/var/lib/pgsql/data
DB_HOST=$(hostname -f)
DB_PORT=${DB_PORT:-5432}
DB_HOSTPORT="$DB_HOST:$DB_PORT"
DB_PROP_FILE=/etc/cloudera-scm-server/db.properties
MGMT_DB_PROP_FILE=/etc/cloudera-scm-server/db.mgmt.properties
DB_LIST_FILE=$DATA_DIR/scm.db.list
NOW=$(date +%Y%m%d-%H%M%S)
<API key> $DATA_DIR/postgresql.conf 0
# Add header to pg_hba.conf.
echo "# Accept connections from all hosts" >> $DATA_DIR/pg_hba.conf
#echo "export LANGUAGE=en_US.UTF-8" >> ~/.bashrc
#echo "export LANG=en_US.UTF-8" >> ~/.bashrc
#echo "export LC_ALL=en_US.UTF-8" >> ~/.bashrc
#source ~/.bashrc
#put this line to the top of the ident to allow all local access
sed -i '/host.*127.*ident/i \
host all all 127.0.0.1/32 md5 \ ' $DATA_DIR/pg_hba.conf
#append this line as well, need both to allow access
#echo "host all all 0.0.0.0/0 md5"
#echo "listen_addresses = '*'" >> $DATA_DIR/postgresql.conf
#configure the postgresql server to start at boot
sudo /sbin/chkconfig postgresql on
sudo service postgresql restart
<API key>
create_scm_db "$SCM_PWD"
create_mgmt_role_db ACTIVITYMONITOR amon
create_mgmt_role_db REPORTSMANAGER rman
create_mgmt_role_db NAVIGATOR nav
create_mgmt_role_db NAVIGATORMETASERVER navms
create_mgmt_role_db OOZIE oozie
<API key>
#host oozie oozie 0.0.0.0/0 md5
#create_mgmt_role_db HiveMetastoreServer navms
# with dynamic db creation, no need to call "create_mgmt_role_db" for new roles
# above calls kept for consistency
/usr/share/cmf/schema/<API key>.sh postgresql scm scm "$SCM_PWD" >> "${LOG_FILE}" 2>&1
<API key>
# restart to make sure all configuration take effects
sudo service postgresql restart
<API key>
log "
# always `exit 0` on success
exit 0 |
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/mfd/core.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/machine.h>
#include <linux/mfd/wm8994/core.h>
#include <linux/mfd/wm8994/pdata.h>
#include <linux/mfd/wm8994/registers.h>
#include "wm8994.h"
/**
* wm8994_reg_read: Read a single WM8994 register.
*
* @wm8994: Device to read from.
* @reg: Register to read.
*/
int wm8994_reg_read(struct wm8994 *wm8994, unsigned short reg)
{
unsigned int val;
int ret;
ret = regmap_read(wm8994->regmap, reg, &val);
if (ret < 0)
return ret;
else
return val;
}
EXPORT_SYMBOL_GPL(wm8994_reg_read);
/**
* wm8994_bulk_read: Read multiple WM8994 registers
*
* @wm8994: Device to read from
* @reg: First register
* @count: Number of registers
* @buf: Buffer to fill. The data will be returned big endian.
*/
int wm8994_bulk_read(struct wm8994 *wm8994, unsigned short reg,
int count, u16 *buf)
{
return regmap_bulk_read(wm8994->regmap, reg, buf, count);
}
/**
* wm8994_reg_write: Write a single WM8994 register.
*
* @wm8994: Device to write to.
* @reg: Register to write to.
* @val: Value to write.
*/
int wm8994_reg_write(struct wm8994 *wm8994, unsigned short reg,
unsigned short val)
{
return regmap_write(wm8994->regmap, reg, val);
}
EXPORT_SYMBOL_GPL(wm8994_reg_write);
/**
* wm8994_bulk_write: Write multiple WM8994 registers
*
* @wm8994: Device to write to
* @reg: First register
* @count: Number of registers
* @buf: Buffer to write from. Data must be big-endian formatted.
*/
int wm8994_bulk_write(struct wm8994 *wm8994, unsigned short reg,
int count, const u16 *buf)
{
return regmap_raw_write(wm8994->regmap, reg, buf, count * sizeof(u16));
}
EXPORT_SYMBOL_GPL(wm8994_bulk_write);
/**
* wm8994_set_bits: Set the value of a bitfield in a WM8994 register
*
* @wm8994: Device to write to.
* @reg: Register to write to.
* @mask: Mask of bits to set.
* @val: Value to set (unshifted)
*/
int wm8994_set_bits(struct wm8994 *wm8994, unsigned short reg,
unsigned short mask, unsigned short val)
{
return regmap_update_bits(wm8994->regmap, reg, mask, val);
}
EXPORT_SYMBOL_GPL(wm8994_set_bits);
static struct mfd_cell <API key>[] = {
{
.name = "wm8994-ldo",
.id = 1,
.<API key> = true,
},
{
.name = "wm8994-ldo",
.id = 2,
.<API key> = true,
},
};
static struct resource <API key>[] = {
{
.start = <API key>,
.end = <API key>,
.flags = IORESOURCE_IRQ,
},
};
static struct resource <API key>[] = {
{
.start = WM8994_IRQ_GPIO(1),
.end = WM8994_IRQ_GPIO(11),
.flags = IORESOURCE_IRQ,
},
};
static struct mfd_cell wm8994_devs[] = {
{
.name = "wm8994-codec",
.num_resources = ARRAY_SIZE(<API key>),
.resources = <API key>,
},
{
.name = "wm8994-gpio",
.num_resources = ARRAY_SIZE(<API key>),
.resources = <API key>,
.<API key> = true,
},
};
/*
* Supplies for the main bulk of CODEC; the LDO supplies are ignored
* and should be handled via the standard regulator API supply
* management.
*/
static const char *<API key>[] = {
"DBVDD1",
"DBVDD2",
"DBVDD3",
"DCVDD",
"AVDD1",
"AVDD2",
"CPVDD",
"SPKVDD1",
"SPKVDD2",
};
static const char *<API key>[] = {
"DBVDD",
"DCVDD",
"AVDD1",
"AVDD2",
"CPVDD",
"SPKVDD1",
"SPKVDD2",
};
static const char *<API key>[] = {
"DBVDD1",
"DBVDD2",
"DBVDD3",
"DCVDD",
"AVDD1",
"AVDD2",
"CPVDD",
"SPKVDD1",
"SPKVDD2",
};
#ifdef CONFIG_PM
static int wm8994_suspend(struct device *dev)
{
struct wm8994 *wm8994 = dev_get_drvdata(dev);
int ret;
/* Don't actually go through with the suspend if the CODEC is
* still active (eg, for audio passthrough from CP. */
ret = wm8994_reg_read(wm8994, <API key>);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & <API key>) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
ret = wm8994_reg_read(wm8994, <API key>);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & (WM8994_AIF2ADCL_ENA | WM8994_AIF2ADCR_ENA |
<API key> | <API key> |
<API key> | <API key>)) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
ret = wm8994_reg_read(wm8994, <API key>);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & (WM8994_AIF2DACL_ENA | WM8994_AIF2DACR_ENA |
<API key> | <API key> |
<API key> | <API key>)) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
switch (wm8994->type) {
case WM8958:
case WM1811:
ret = wm8994_reg_read(wm8994, WM8958_MIC_DETECT_1);
if (ret < 0) {
dev_err(dev, "Failed to read power status: %d\n", ret);
} else if (ret & WM8958_MICD_ENA) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
break;
default:
break;
}
switch (wm8994->type) {
case WM1811:
ret = wm8994_reg_read(wm8994, WM8994_ANTIPOP_2);
if (ret < 0) {
dev_err(dev, "Failed to read jackdet: %d\n", ret);
} else if (ret & <API key>) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
break;
default:
break;
}
switch (wm8994->type) {
case WM1811:
ret = wm8994_reg_read(wm8994, WM8994_ANTIPOP_2);
if (ret < 0) {
dev_err(dev, "Failed to read jackdet: %d\n", ret);
} else if (ret & <API key>) {
dev_dbg(dev, "CODEC still active, ignoring suspend\n");
return 0;
}
break;
default:
break;
}
/* Disable LDO pulldowns while the device is suspended if we
* don't know that something will be driving them. */
if (!wm8994-><API key>)
wm8994_set_bits(wm8994, <API key>,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD);
/* Explicitly put the device into reset in case regulators
* don't get disabled in order to ensure consistent restart.
*/
wm8994_reg_write(wm8994, <API key>,
wm8994_reg_read(wm8994, <API key>));
regcache_mark_dirty(wm8994->regmap);
/* Restore GPIO registers to prevent problems with mismatched
* pin configurations.
*/
ret = <API key>(wm8994->regmap, WM8994_GPIO_1,
WM8994_GPIO_11);
if (ret != 0)
dev_err(dev, "Failed to restore GPIO registers: %d\n", ret);
/* In case one of the GPIOs is used as a wake input. */
ret = <API key>(wm8994->regmap,
<API key>,
<API key>);
if (ret != 0)
dev_err(dev, "Failed to restore interrupt mask: %d\n", ret);
regcache_cache_only(wm8994->regmap, true);
wm8994->suspended = true;
ret = <API key>(wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(dev, "Failed to disable supplies: %d\n", ret);
return ret;
}
return 0;
}
static int wm8994_resume(struct device *dev)
{
struct wm8994 *wm8994 = dev_get_drvdata(dev);
int ret;
/* We may have lied to the PM core about suspending */
if (!wm8994->suspended)
return 0;
ret = <API key>(wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(dev, "Failed to enable supplies: %d\n", ret);
return ret;
}
regcache_cache_only(wm8994->regmap, false);
ret = regcache_sync(wm8994->regmap);
if (ret != 0) {
dev_err(dev, "Failed to restore register map: %d\n", ret);
goto err_enable;
}
/* Disable LDO pulldowns while the device is active */
wm8994_set_bits(wm8994, <API key>,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD,
0);
wm8994->suspended = false;
return 0;
err_enable:
<API key>(wm8994->num_supplies, wm8994->supplies);
return ret;
}
#endif
#ifdef CONFIG_REGULATOR
static int wm8994_ldo_in_use(struct wm8994_pdata *pdata, int ldo)
{
struct wm8994_ldo_pdata *ldo_pdata;
if (!pdata)
return 0;
ldo_pdata = &pdata->ldo[ldo];
if (!ldo_pdata->init_data)
return 0;
return ldo_pdata->init_data-><API key> != 0;
}
#else
static int wm8994_ldo_in_use(struct wm8994_pdata *pdata, int ldo)
{
return 0;
}
#endif
static const struct reg_default wm8994_revc_patch[] = {
{ 0x102, 0x3 },
{ 0x56, 0x3 },
{ 0x817, 0x0 },
{ 0x102, 0x0 },
};
static const struct reg_default wm8958_reva_patch[] = {
{ 0x102, 0x3 },
{ 0xcb, 0x81 },
{ 0x817, 0x0 },
{ 0x102, 0x0 },
};
static const struct reg_default wm1811_reva_patch[] = {
{ 0x102, 0x3 },
{ 0x56, 0xc07 },
{ 0x5d, 0x7e },
{ 0x5e, 0x0 },
{ 0x102, 0x0 },
};
/*
* Instantiate the generic non-control parts of the device.
*/
static int wm8994_device_init(struct wm8994 *wm8994, int irq)
{
struct wm8994_pdata *pdata;
struct regmap_config *regmap_config;
const struct reg_default *regmap_patch = NULL;
const char *devname;
int ret, i, patch_regs;
int pulls = 0;
if (dev_get_platdata(wm8994->dev)) {
pdata = dev_get_platdata(wm8994->dev);
wm8994->pdata = *pdata;
}
pdata = &wm8994->pdata;
dev_set_drvdata(wm8994->dev, wm8994);
/* Add the on-chip regulators first for bootstrapping */
ret = mfd_add_devices(wm8994->dev, -1,
<API key>,
ARRAY_SIZE(<API key>),
NULL, 0, NULL);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to add children: %d\n", ret);
goto err;
}
switch (wm8994->type) {
case WM1811:
wm8994->num_supplies = ARRAY_SIZE(<API key>);
break;
case WM8994:
wm8994->num_supplies = ARRAY_SIZE(<API key>);
break;
case WM8958:
wm8994->num_supplies = ARRAY_SIZE(<API key>);
break;
default:
BUG();
goto err;
}
wm8994->supplies = devm_kzalloc(wm8994->dev,
sizeof(struct regulator_bulk_data) *
wm8994->num_supplies, GFP_KERNEL);
if (!wm8994->supplies) {
ret = -ENOMEM;
goto err;
}
switch (wm8994->type) {
case WM1811:
for (i = 0; i < ARRAY_SIZE(<API key>); i++)
wm8994->supplies[i].supply = <API key>[i];
break;
case WM8994:
for (i = 0; i < ARRAY_SIZE(<API key>); i++)
wm8994->supplies[i].supply = <API key>[i];
break;
case WM8958:
for (i = 0; i < ARRAY_SIZE(<API key>); i++)
wm8994->supplies[i].supply = <API key>[i];
break;
default:
BUG();
goto err;
}
ret = regulator_bulk_get(wm8994->dev, wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to get supplies: %d\n", ret);
goto err;
}
ret = <API key>(wm8994->num_supplies,
wm8994->supplies);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to enable supplies: %d\n", ret);
goto err_get;
}
ret = wm8994_reg_read(wm8994, <API key>);
if (ret < 0) {
dev_err(wm8994->dev, "Failed to read ID register\n");
goto err_enable;
}
switch (ret) {
case 0x1811:
devname = "WM1811";
if (wm8994->type != WM1811)
dev_warn(wm8994->dev, "Device registered as type %d\n",
wm8994->type);
wm8994->type = WM1811;
break;
case 0x8994:
devname = "WM8994";
if (wm8994->type != WM8994)
dev_warn(wm8994->dev, "Device registered as type %d\n",
wm8994->type);
wm8994->type = WM8994;
break;
case 0x8958:
devname = "WM8958";
if (wm8994->type != WM8958)
dev_warn(wm8994->dev, "Device registered as type %d\n",
wm8994->type);
wm8994->type = WM8958;
break;
default:
dev_err(wm8994->dev, "Device is not a WM8994, ID is %x\n",
ret);
ret = -EINVAL;
goto err_enable;
}
ret = wm8994_reg_read(wm8994, <API key>);
if (ret < 0) {
dev_err(wm8994->dev, "Failed to read revision register: %d\n",
ret);
goto err_enable;
}
wm8994->revision = ret & <API key>;
wm8994->cust_id = (ret & WM8994_CUST_ID_MASK) >> <API key>;
switch (wm8994->type) {
case WM8994:
switch (wm8994->revision) {
case 0:
case 1:
dev_warn(wm8994->dev,
"revision %c not fully supported\n",
'A' + wm8994->revision);
break;
case 2:
case 3:
default:
regmap_patch = wm8994_revc_patch;
patch_regs = ARRAY_SIZE(wm8994_revc_patch);
break;
}
break;
case WM8958:
switch (wm8994->revision) {
case 0:
regmap_patch = wm8958_reva_patch;
patch_regs = ARRAY_SIZE(wm8958_reva_patch);
break;
default:
break;
}
break;
case WM1811:
/* Revision C did not change the relevant layer */
if (wm8994->revision > 1)
wm8994->revision++;
regmap_patch = wm1811_reva_patch;
patch_regs = ARRAY_SIZE(wm1811_reva_patch);
break;
default:
break;
}
dev_info(wm8994->dev, "%s revision %c CUST_ID %02x\n", devname,
'A' + wm8994->revision, wm8994->cust_id);
switch (wm8994->type) {
case WM1811:
regmap_config = &<API key>;
break;
case WM8994:
regmap_config = &<API key>;
break;
case WM8958:
regmap_config = &<API key>;
break;
default:
dev_err(wm8994->dev, "Unknown device type %d\n", wm8994->type);
return -EINVAL;
}
ret = regmap_reinit_cache(wm8994->regmap, regmap_config);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to reinit register cache: %d\n",
ret);
return ret;
}
if (regmap_patch) {
ret = <API key>(wm8994->regmap, regmap_patch,
patch_regs);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to register patch: %d\n",
ret);
goto err;
}
}
wm8994->irq_base = pdata->irq_base;
wm8994->gpio_base = pdata->gpio_base;
/* GPIO configuration is only applied if it's non-zero */
for (i = 0; i < ARRAY_SIZE(pdata->gpio_defaults); i++) {
if (pdata->gpio_defaults[i]) {
wm8994_set_bits(wm8994, WM8994_GPIO_1 + i,
0xffff, pdata->gpio_defaults[i]);
}
}
wm8994-><API key> = pdata-><API key>;
if (pdata->spkmode_pu)
pulls |= WM8994_SPKMODE_PU;
/* Disable unneeded pulls */
wm8994_set_bits(wm8994, <API key>,
WM8994_LDO1ENA_PD | WM8994_LDO2ENA_PD |
WM8994_SPKMODE_PU | WM8994_CSNADDR_PD,
pulls);
/* In some system designs where the regulators are not in use,
* we can achieve a small reduction in leakage currents by
* floating LDO outputs. This bit makes no difference if the
* LDOs are enabled, it only affects cases where the LDOs were
* in operation and are then disabled.
*/
for (i = 0; i < WM8994_NUM_LDO_REGS; i++) {
if (wm8994_ldo_in_use(pdata, i))
wm8994_set_bits(wm8994, WM8994_LDO_1 + i,
WM8994_LDO1_DISCH, WM8994_LDO1_DISCH);
else
wm8994_set_bits(wm8994, WM8994_LDO_1 + i,
WM8994_LDO1_DISCH, 0);
}
wm8994_irq_init(wm8994);
ret = mfd_add_devices(wm8994->dev, -1,
wm8994_devs, ARRAY_SIZE(wm8994_devs),
NULL, 0, NULL);
if (ret != 0) {
dev_err(wm8994->dev, "Failed to add children: %d\n", ret);
goto err_irq;
}
pm_runtime_enable(wm8994->dev);
pm_runtime_idle(wm8994->dev);
return 0;
err_irq:
wm8994_irq_exit(wm8994);
err_enable:
<API key>(wm8994->num_supplies,
wm8994->supplies);
err_get:
regulator_bulk_free(wm8994->num_supplies, wm8994->supplies);
err:
mfd_remove_devices(wm8994->dev);
return ret;
}
static void wm8994_device_exit(struct wm8994 *wm8994)
{
pm_runtime_disable(wm8994->dev);
mfd_remove_devices(wm8994->dev);
wm8994_irq_exit(wm8994);
<API key>(wm8994->num_supplies,
wm8994->supplies);
regulator_bulk_free(wm8994->num_supplies, wm8994->supplies);
}
static const struct of_device_id wm8994_of_match[] = {
{ .compatible = "wlf,wm1811", },
{ .compatible = "wlf,wm8994", },
{ .compatible = "wlf,wm8958", },
{ }
};
MODULE_DEVICE_TABLE(of, wm8994_of_match);
static int wm8994_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8994 *wm8994;
int ret;
wm8994 = devm_kzalloc(&i2c->dev, sizeof(struct wm8994), GFP_KERNEL);
if (wm8994 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8994);
wm8994->dev = &i2c->dev;
wm8994->irq = i2c->irq;
wm8994->type = id->driver_data;
wm8994->regmap = <API key>(i2c, &<API key>);
if (IS_ERR(wm8994->regmap)) {
ret = PTR_ERR(wm8994->regmap);
dev_err(wm8994->dev, "Failed to allocate register map: %d\n",
ret);
return ret;
}
return wm8994_device_init(wm8994, i2c->irq);
}
static int wm8994_i2c_remove(struct i2c_client *i2c)
{
struct wm8994 *wm8994 = i2c_get_clientdata(i2c);
wm8994_device_exit(wm8994);
return 0;
}
static const struct i2c_device_id wm8994_i2c_id[] = {
{ "wm1811", WM1811 },
{ "wm1811a", WM1811 },
{ "wm8994", WM8994 },
{ "wm8958", WM8958 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8994_i2c_id);
static <API key>(wm8994_pm_ops, wm8994_suspend, wm8994_resume,
NULL);
static struct i2c_driver wm8994_i2c_driver = {
.driver = {
.name = "wm8994",
.owner = THIS_MODULE,
.pm = &wm8994_pm_ops,
.of_match_table = wm8994_of_match,
},
.probe = wm8994_i2c_probe,
.remove = wm8994_i2c_remove,
.id_table = wm8994_i2c_id,
};
module_i2c_driver(wm8994_i2c_driver);
MODULE_DESCRIPTION("Core support for the WM8994 audio CODEC");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>"); |
#ifndef <API key>
#define <API key>
#include <boost/numeric/odeint/iterator/detail/ode_iterator_base.hpp>
#include <boost/numeric/odeint/util/unit_helper.hpp>
namespace boost {
namespace numeric {
namespace odeint {
template< class Iterator , class Stepper , class System , class State , typename Tag , class StepperTag >
class <API key>;
/*
* Specilization for steppers and error steppers
*/
/**
* \brief ODE Iterator performing exactly n steps with constant step size. The value type of this iterator is the state type of the stepper.
*
* Implements an ODE iterator solving the ODE with constant step size. Uses steppers fulfilling the Stepper concept.
* n_step_iterator is a model of single-pass iterator.
*
* The value type of this iterator is the state type of the stepper. Hence one can only access the state and not the current time.
*
* \tparam Stepper The stepper type which should be used during the iteration.
* \tparam System The type of the system function (ODE) which should be solved.
*/
template< class Iterator , class Stepper , class System , class State , typename Tag >
class <API key>< Iterator , Stepper , System , State , Tag , stepper_tag >
: public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >
{
private:
typedef Stepper stepper_type;
typedef System system_type;
typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type <API key>;
typedef State state_type;
typedef typename traits::time_type< stepper_type >::type time_type;
typedef typename traits::value_type< stepper_type >::type ode_value_type;
#ifndef DOXYGEN_SKIP
typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;
#endif
public:
/**
* \brief Constructs a n_step_iterator. This constructor should be used to construct the begin iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
* \param t The initial time.
* \param dt The initial time step.
* \param num_of_steps the number of steps to be executed.
*/
<API key>( stepper_type stepper , system_type sys , state_type &s ,
time_type t , time_type dt , size_t num_of_steps )
: base_type( stepper , sys , t , dt ) , m_t_start( t ) , m_state( &s ) ,
m_steps(num_of_steps) , m_step( 0 )
{ }
/**
* \brief Constructs a const_step_iterator. This constructor should be used to construct the end iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
*/
<API key>( stepper_type stepper , system_type sys , state_type &s )
: base_type( stepper , sys ) , m_state( &s ) { }
protected:
friend class boost::<API key>;
void increment()
{
if( this->m_step < this->m_steps )
{
<API key> &stepper = this->m_stepper;
stepper.do_step( this->m_system , *this->m_state , this->m_t , this->m_dt );
// use integer to compute current time to reduce roundoff errors
this->m_step++;
this->m_t = this->m_t_start + static_cast< typename unit_value_type<time_type>::type >(this->m_step)*this->m_dt;
} else {
this->m_at_end = true;
}
}
public:
const state_type& get_state() const
{
return *m_state;
}
private:
time_type m_t_start;
time_type m_t_end;
state_type* m_state;
size_t m_steps;
size_t m_step;
};
/*
* Specilization for dense output stepper
*/
/**
* \brief ODE Iterator with step-size control and dense output.
*
* Implements an ODE iterator solving the ODE with constant steps. Uses dense-output steppers.
* n_step_iterator is a model of single-pass iterator.
*
* The value type of this iterator is the state type of the stepper. Hence one can only access the state and not the current time.
*
* \tparam Stepper The stepper type which should be used during the iteration.
* \tparam System The type of the system function (ODE) which should be solved.
*/
template< class Iterator , class Stepper , class System , class State , typename Tag >
class <API key>< Iterator , Stepper , System , State , Tag , <API key> >
: public detail::ode_iterator_base< Iterator , Stepper , System , State , Tag >
{
private:
typedef Stepper stepper_type;
typedef System system_type;
typedef typename boost::numeric::odeint::unwrap_reference< stepper_type >::type <API key>;
typedef State state_type;
typedef typename traits::time_type< stepper_type >::type time_type;
typedef typename traits::value_type< stepper_type >::type ode_value_type;
#ifndef DOXYGEN_SKIP
typedef detail::ode_iterator_base< Iterator , Stepper , System , State , Tag > base_type;
#endif
public:
/**
* \brief Constructs a const_step_iterator. This constructor should be used to construct the begin iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
* \param t The initial time.
* \param dt The initial time step.
* \param num_of_steps the number of steps to be executed.
*/
<API key>( stepper_type stepper , system_type sys , state_type &s ,
time_type t , time_type dt , size_t num_of_steps )
: base_type( stepper , sys , t , dt ) , m_t_start( t ) , m_state( &s ) ,
m_steps( num_of_steps ) , m_step( 0 )
{
<API key> &st = this->m_stepper;
st.initialize( * ( this->m_state ) , this->m_t , this->m_dt );
}
/**
* \brief Constructs a const_step_iterator. This constructor should be used to construct the end iterator.
*
* \param stepper The stepper to use during the iteration.
* \param sys The system function (ODE) to solve.
* \param s The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
*/
<API key>( stepper_type stepper , system_type sys , state_type &s )
: base_type( stepper , sys ) , m_state( &s )
{
}
protected:
friend class boost::<API key>;
void increment( void )
{
if( this->m_step < this->m_steps )
{
<API key> &stepper = this->m_stepper;
// use integer to compute current time to reduce roundoff errors
this->m_step++;
this->m_t = this->m_t_start + static_cast< typename unit_value_type<time_type>::type >(this->m_step)*this->m_dt;
while( detail::less_with_sign( stepper.current_time() , this->m_t ,
stepper.current_time_step() ) )
{
stepper.do_step( this->m_system );
}
stepper.calc_state( this->m_t , *( this->m_state ) );
} else {
this->m_at_end = true;
}
}
public:
const state_type& get_state() const
{
return *m_state;
}
private:
time_type m_t_start;
time_type m_t_end;
state_type* m_state;
size_t m_steps;
size_t m_step;
};
} // namespace odeint
} // namespace numeric
} // namespace boost
#endif // <API key> |
// modification, are permitted provided that the following conditions are
// met:
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// 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.
/**
* @fileoverview Test concat on small and large arrays
*/
var poses;
poses = [140, 4000000000];
while (pos = poses.shift()) {
var a = new Array(pos);
var array_proto = [];
a.__proto__ = array_proto;
assertEquals(pos, a.length);
a.push('foo');
assertEquals(pos + 1, a.length);
var b = ['bar'];
var c = a.concat(b);
assertEquals(pos + 2, c.length);
assertEquals("undefined", typeof(c[pos - 1]));
assertEquals("foo", c[pos]);
assertEquals("bar", c[pos + 1]);
// Can we fool the system by putting a number in a string?
var onetwofour = "124";
a[onetwofour] = 'doo';
assertEquals(a[124], 'doo');
c = a.concat(b);
assertEquals(c[124], 'doo');
// If we put a number in the prototype, then the spec says it should be
// copied on concat.
array_proto["123"] = 'baz';
assertEquals(a[123], 'baz');
c = a.concat(b);
assertEquals(pos + 2, c.length);
assertEquals("baz", c[123]);
assertEquals("undefined", typeof(c[pos - 1]));
assertEquals("foo", c[pos]);
assertEquals("bar", c[pos + 1]);
// When we take the number off the prototype it disappears from a, but
// the concat put it in c itself.
array_proto["123"] = undefined;
assertEquals("undefined", typeof(a[123]));
assertEquals("baz", c[123]);
// If the element of prototype is shadowed, the element on the instance
// should be copied, but not the one on the prototype.
array_proto[123] = 'baz';
a[123] = 'xyz';
assertEquals('xyz', a[123]);
c = a.concat(b);
assertEquals('xyz', c[123]);
// Non-numeric properties on the prototype or the array shouldn't get
// copied.
array_proto.moe = 'joe';
a.ben = 'jerry';
assertEquals(a["moe"], 'joe');
assertEquals(a["ben"], 'jerry');
c = a.concat(b);
// ben was not copied
assertEquals("undefined", typeof(c.ben));
// When we take moe off the prototype it disappears from all arrays.
array_proto.moe = undefined;
assertEquals("undefined", typeof(c.moe));
// Negative indices don't get concated.
a[-1] = 'minus1';
assertEquals("minus1", a[-1]);
assertEquals("undefined", typeof(a[0xffffffff]));
c = a.concat(b);
assertEquals("undefined", typeof(c[-1]));
assertEquals("undefined", typeof(c[0xffffffff]));
assertEquals(c.length, a.length + 1);
}
poses = [140, 4000000000];
while (pos = poses.shift()) {
var a = new Array(pos);
assertEquals(pos, a.length);
a.push('foo');
assertEquals(pos + 1, a.length);
var b = ['bar'];
var c = a.concat(b);
assertEquals(pos + 2, c.length);
assertEquals("undefined", typeof(c[pos - 1]));
assertEquals("foo", c[pos]);
assertEquals("bar", c[pos + 1]);
// Can we fool the system by putting a number in a string?
var onetwofour = "124";
a[onetwofour] = 'doo';
assertEquals(a[124], 'doo');
c = a.concat(b);
assertEquals(c[124], 'doo');
// If we put a number in the prototype, then the spec says it should be
// copied on concat.
Array.prototype["123"] = 'baz';
assertEquals(a[123], 'baz');
c = a.concat(b);
assertEquals(pos + 2, c.length);
assertEquals("baz", c[123]);
assertEquals("undefined", typeof(c[pos - 1]));
assertEquals("foo", c[pos]);
assertEquals("bar", c[pos + 1]);
// When we take the number off the prototype it disappears from a, but
// the concat put it in c itself.
Array.prototype["123"] = undefined;
assertEquals("undefined", typeof(a[123]));
assertEquals("baz", c[123]);
// If the element of prototype is shadowed, the element on the instance
// should be copied, but not the one on the prototype.
Array.prototype[123] = 'baz';
a[123] = 'xyz';
assertEquals('xyz', a[123]);
c = a.concat(b);
assertEquals('xyz', c[123]);
// Non-numeric properties on the prototype or the array shouldn't get
// copied.
Array.prototype.moe = 'joe';
a.ben = 'jerry';
assertEquals(a["moe"], 'joe');
assertEquals(a["ben"], 'jerry');
c = a.concat(b);
// ben was not copied
assertEquals("undefined", typeof(c.ben));
// moe was not copied, but we can see it through the prototype
assertEquals("joe", c.moe);
// When we take moe off the prototype it disappears from all arrays.
Array.prototype.moe = undefined;
assertEquals("undefined", typeof(c.moe));
// Negative indices don't get concated.
a[-1] = 'minus1';
assertEquals("minus1", a[-1]);
assertEquals("undefined", typeof(a[0xffffffff]));
c = a.concat(b);
assertEquals("undefined", typeof(c[-1]));
assertEquals("undefined", typeof(c[0xffffffff]));
assertEquals(c.length, a.length + 1);
}
a = [];
c = a.concat('Hello');
assertEquals(1, c.length);
assertEquals("Hello", c[0]);
assertEquals("Hello", c.toString());
// Check that concat preserves holes.
var holey = [void 0,'a',,'c'].concat(['d',,'f',[0,,2],void 0])
assertEquals(9, holey.length); // hole in embedded array is ignored
for (var i = 0; i < holey.length; i++) {
if (i == 2 || i == 5) {
assertFalse(i in holey);
} else {
assertTrue(i in holey);
}
}
// Polluted prototype from prior tests.
delete Array.prototype[123];
// Check that concat reads getters in the correct order.
var arr1 = [,2];
var arr2 = [1,3];
var r1 = [].concat(arr1, arr2); // [,2,1,3]
assertEquals([,2,1,3], r1);
// Make first array change length of second array.
Object.defineProperty(arr1, 0, {get: function() {
arr2.push("X");
return undefined;
}, configurable: true})
var r2 = [].concat(arr1, arr2); // [undefined,2,1,3,"X"]
assertEquals([undefined,2,1,3,"X"], r2);
// Make first array change length of second array massively.
arr2.length = 2;
Object.defineProperty(arr1, 0, {get: function() {
arr2[500000] = "X";
return undefined;
}, configurable: true})
var r3 = [].concat(arr1, arr2); // [undefined,2,1,3,"X"]
var expected = [undefined,2,1,3];
expected[500000 + 2] = "X";
assertEquals(expected, r3);
var arr3 = [];
var trace = [];
var expectedTrace = []
function mkGetter(i) { return function() { trace.push(i); }; }
arr3.length = 10000;
for (var i = 0; i < 100; i++) {
Object.defineProperty(arr3, i * i, {get: mkGetter(i)});
expectedTrace[i] = i;
expectedTrace[100 + i] = i;
}
var r4 = [0].concat(arr3, arr3);
assertEquals(1 + arr3.length * 2, r4.length);
assertEquals(expectedTrace, trace); |
ALTER TABLE `<API key>` CHANGE `id` `ID` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE `<API key>` CHANGE `effIndex` `EffectIndex` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE `<API key>` CHANGE `target_map` `MapID` SMALLINT(3) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE `<API key>` CHANGE `target_position_x` `PositionX` FLOAT NOT NULL DEFAULT '0';
ALTER TABLE `<API key>` CHANGE `target_position_y` `PositionY` FLOAT NOT NULL DEFAULT '0';
ALTER TABLE `<API key>` CHANGE `target_position_z` `PositionZ` FLOAT NOT NULL DEFAULT '0';
ALTER TABLE `<API key>` DROP COLUMN `target_orientation`; |
YUI.add('series-bar-stacked', function (Y, NAME) {
/**
* Provides functionality for creating a stacked bar series.
*
* @module charts
* @submodule series-bar-stacked
*/
var Y_Lang = Y.Lang;
/**
* The StackedBarSeries renders bar chart in which series are stacked horizontally to show
* their contribution to the cumulative total.
*
* @class StackedBarSeries
* @extends BarSeries
* @uses StackingUtil
* @constructor
* @param {Object} config (optional) Configuration parameters.
* @submodule series-bar-stacked
*/
Y.StackedBarSeries = Y.Base.create("stackedBarSeries", Y.BarSeries, [Y.StackingUtil], {
/**
* @protected
*
* Draws the series.
*
* @method drawSeries
*/
drawSeries: function()
{
if(this.get("xcoords").length < 1)
{
return;
}
var isNumber = Y_Lang.isNumber,
style = Y.clone(this.get("styles").marker),
w = style.width,
h = style.height,
xcoords = this.get("xcoords"),
ycoords = this.get("ycoords"),
i = 0,
len = xcoords.length,
top = ycoords[0],
seriesCollection = this.get("<API key>"),
ratio,
order = this.get("order"),
graphOrder = this.get("graphOrder"),
left,
marker,
lastCollection,
negativeBaseValues,
positiveBaseValues,
fillColors,
borderColors,
useOrigin = order === 0,
totalHeight = len * h,
dimensions = {
width: [],
height: []
},
xvalues = [],
yvalues = [],
groupMarkers = this.get("groupMarkers");
if(Y_Lang.isArray(style.fill.color))
{
fillColors = style.fill.color.concat();
}
if(Y_Lang.isArray(style.border.color))
{
borderColors = style.border.color.concat();
}
this._createMarkerCache();
if(totalHeight > this.get("height"))
{
ratio = this.get("height")/totalHeight;
h *= ratio;
h = Math.max(h, 1);
}
if(!useOrigin)
{
lastCollection = seriesCollection[order - 1];
negativeBaseValues = lastCollection.get("negativeBaseValues");
positiveBaseValues = lastCollection.get("positiveBaseValues");
if(!negativeBaseValues || !positiveBaseValues)
{
useOrigin = true;
positiveBaseValues = [];
negativeBaseValues = [];
}
}
else
{
negativeBaseValues = [];
positiveBaseValues = [];
}
this.set("negativeBaseValues", negativeBaseValues);
this.set("positiveBaseValues", positiveBaseValues);
for(i = 0; i < len; ++i)
{
top = ycoords[i];
left = xcoords[i];
if(!isNumber(top) || !isNumber(left))
{
if(useOrigin)
{
positiveBaseValues[i] = this._leftOrigin;
negativeBaseValues[i] = this._leftOrigin;
}
this._markers.push(null);
continue;
}
if(useOrigin)
{
w = Math.abs(left - this._leftOrigin);
if(left > this._leftOrigin)
{
positiveBaseValues[i] = left;
negativeBaseValues[i] = this._leftOrigin;
left -= w;
}
else if(left < this._leftOrigin)
{
positiveBaseValues[i] = this._leftOrigin;
negativeBaseValues[i] = left;
}
else
{
positiveBaseValues[i] = left;
negativeBaseValues[i] = this._leftOrigin;
}
}
else
{
if(left < this._leftOrigin)
{
left = negativeBaseValues[i] - (this._leftOrigin - xcoords[i]);
w = negativeBaseValues[i] - left;
negativeBaseValues[i] = left;
}
else if(left >= this._leftOrigin)
{
left += (positiveBaseValues[i] - this._leftOrigin);
w = left - positiveBaseValues[i];
positiveBaseValues[i] = left;
left -= w;
}
}
if(!isNaN(w) && w > 0)
{
top -= h/2;
if(groupMarkers)
{
dimensions.width[i] = w;
dimensions.height[i] = h;
xvalues.push(left);
yvalues.push(top);
}
else
{
style.width = w;
style.height = h;
style.x = left;
style.y = top;
if(fillColors)
{
style.fill.color = fillColors[i % fillColors.length];
}
if(borderColors)
{
style.border.color = borderColors[i % borderColors.length];
}
marker = this.getMarker(style, graphOrder, i);
}
}
else if(!groupMarkers)
{
this._markers.push(null);
}
}
if(groupMarkers)
{
this._createGroupMarker({
fill: style.fill,
border: style.border,
dimensions: dimensions,
xvalues: xvalues,
yvalues: yvalues,
shape: style.shape
});
}
else
{
this._clearMarkerCache();
}
},
/**
* @protected
*
* Resizes and positions markers based on a mouse interaction.
*
* @method updateMarkerState
* @param {String} type state of the marker
* @param {Number} i index of the marker
*/
updateMarkerState: function(type, i)
{
if(this._markers[i])
{
var state = this._getState(type),
ycoords = this.get("ycoords"),
marker = this._markers[i],
styles = this.get("styles").marker,
h = styles.height,
markerStyles = state === "off" || !styles[state] ? Y.clone(styles) : Y.clone(styles[state]),
fillColor,
borderColor;
markerStyles.y = (ycoords[i] - h/2);
markerStyles.x = marker.get("x");
markerStyles.width = marker.get("width");
markerStyles.id = marker.get("id");
fillColor = markerStyles.fill.color;
borderColor = markerStyles.border.color;
if(Y_Lang.isArray(fillColor))
{
markerStyles.fill.color = fillColor[i % fillColor.length];
}
else
{
markerStyles.fill.color = this._getItemColor(markerStyles.fill.color, i);
}
if(Y_Lang.isArray(borderColor))
{
markerStyles.border.color = borderColor[i % borderColor.length];
}
else
{
markerStyles.border.color = this._getItemColor(markerStyles.border.color, i);
}
marker.set(markerStyles);
}
},
/**
* @protected
*
* Returns default values for the `styles` attribute.
*
* @method _getPlotDefaults
* @return Object
*/
_getPlotDefaults: function()
{
var defs = {
fill:{
type: "solid",
alpha: 1,
colors:null,
alphas: null,
ratios: null
},
border:{
weight: 0,
alpha: 1
},
width: 24,
height: 24,
shape: "rect",
padding:{
top: 0,
left: 0,
right: 0,
bottom: 0
}
};
defs.fill.color = this._getDefaultColor(this.get("graphOrder"), "fill");
defs.border.color = this._getDefaultColor(this.get("graphOrder"), "border");
return defs;
}
}, {
ATTRS: {
/**
* Read-only attribute indicating the type of series.
*
* @attribute type
* @type String
* @default stackedBar
*/
type: {
value: "stackedBar"
},
/**
* Direction of the series
*
* @attribute direction
* @type String
* @default vertical
*/
direction: {
value: "vertical"
},
/**
* @private
*
* @attribute negativeBaseValues
* @type Array
* @default null
*/
negativeBaseValues: {
value: null
},
/**
* @private
*
* @attribute positiveBaseValues
* @type Array
* @default null
*/
positiveBaseValues: {
value: null
}
/**
* Style properties used for drawing markers. This attribute is inherited from `BarSeries`. Below are the default values:
* <dl>
* <dt>fill</dt><dd>A hash containing the following values:
* <dl>
* <dt>color</dt><dd>Color of the fill. The default value is determined by the order of the series on the graph. The color
* will be retrieved from the below array:<br/>
* `["#66007f", "#a86f41", "#295454", "#996ab2", "#e8cdb7", "#90bdbd","#000000","#c3b8ca", "#968373", "#678585"]`
* </dd>
* <dt>alpha</dt><dd>Number from 0 to 1 indicating the opacity of the marker fill. The default value is 1.</dd>
* </dl>
* </dd>
* <dt>border</dt><dd>A hash containing the following values:
* <dl>
* <dt>color</dt><dd>Color of the border. The default value is determined by the order of the series on the graph. The color
* will be retrieved from the below array:<br/>
* `["#205096", "#b38206", "#000000", "#94001e", "#9d6fa0", "#e55b00", "#5e85c9", "#adab9e", "#6ac291", "#006457"]`
* <dt>alpha</dt><dd>Number from 0 to 1 indicating the opacity of the marker border. The default value is 1.</dd>
* <dt>weight</dt><dd>Number indicating the width of the border. The default value is 1.</dd>
* </dl>
* </dd>
* <dt>height</dt><dd>indicates the width of the marker. The default value is 24.</dd>
* <dt>over</dt><dd>hash containing styles for markers when highlighted by a `mouseover` event. The default
* values for each style is null. When an over style is not set, the non-over value will be used. For example,
* the default value for `marker.over.fill.color` is equivalent to `marker.fill.color`.</dd>
* </dl>
*
* @attribute styles
* @type Object
*/
}
});
}, '3.9.1', {"requires": ["series-stacked", "series-bar"]}); |
/*
Flymaple port by Mike McCauley
*/
#ifndef <API key>
#define <API key>
#include <AP_HAL_FLYMAPLE.h>
class AP_HAL_FLYMAPLE_NS::FLYMAPLEGPIO : public AP_HAL::GPIO {
public:
FLYMAPLEGPIO();
void init();
void pinMode(uint8_t pin, uint8_t output);
int8_t <API key>(uint8_t pin);
uint8_t read(uint8_t pin);
void write(uint8_t pin, uint8_t value);
void toggle(uint8_t pin);
/* Alternative interface: */
AP_HAL::DigitalSource* channel(uint16_t n);
/* Interrupt interface: */
bool attach_interrupt(uint8_t interrupt_num, AP_HAL::Proc p,
uint8_t mode);
/* return true if USB cable is connected */
bool usb_connected(void);
};
class AP_HAL_FLYMAPLE_NS::<API key> : public AP_HAL::DigitalSource {
public:
<API key>(uint8_t v);
void mode(uint8_t output);
uint8_t read();
void write(uint8_t value);
void toggle();
private:
uint8_t _v;
};
#endif // <API key> |
package sun.jvm.hotspot.utilities;
/** A class enabling simple construction of type-safe integer
enumerations */
public class IntegerEnum {
private int value;
/** Constructor is protected because it will only be used by the
subclass */
protected IntegerEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
} |
CKEDITOR.plugins.setLang( 'colordialog', 'en-ca', {
clear: 'Clear', // MISSING
highlight: 'Highlight', // MISSING
options: 'Color Options', // MISSING
selected: 'Selected Color', // MISSING
title: 'Select color' // MISSING
}); |
/**!
* AngularJS file upload/drop directive and service with progress and abort
* FileAPI Flash shim for old browsers not supporting FormData
* @author Danial <danial.farid@gmail.com>
* @version 7.0.9
*/
(function () {
/** @namespace FileAPI.noContentTimeout */
function patchXHR(fnName, newFn) {
window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]);
}
function redefineProp(xhr, prop, fn) {
try {
Object.defineProperty(xhr, prop, {get: fn});
} catch (e) {/*ignore*/
}
}
if (!window.FileAPI) {
window.FileAPI = {};
}
FileAPI.shouldLoad = (window.XMLHttpRequest && !window.FormData) || FileAPI.forceLoad;
if (FileAPI.shouldLoad) {
var <API key> = function (xhr) {
if (!xhr.__listeners) {
if (!xhr.upload) xhr.upload = {};
xhr.__listeners = [];
var <API key> = xhr.upload.addEventListener;
xhr.upload.addEventListener = function (t, fn) {
xhr.__listeners[t] = fn;
if (<API key>) <API key>.apply(this, arguments);
};
}
};
patchXHR('open', function (orig) {
return function (m, url, b) {
<API key>(this);
this.__url = url;
try {
orig.apply(this, [m, url, b]);
} catch (e) {
if (e.message.indexOf('Access is denied') > -1) {
this.__origError = e;
orig.apply(this, [m, '<API key>', b]);
}
}
};
});
patchXHR('getResponseHeader', function (orig) {
return function (h) {
return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h]));
};
});
patchXHR('<API key>', function (orig) {
return function () {
return this.__fileApiXHR && this.__fileApiXHR.<API key> ? this.__fileApiXHR.<API key>() : (orig == null ? null : orig.apply(this));
};
});
patchXHR('abort', function (orig) {
return function () {
return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this));
};
});
patchXHR('setRequestHeader', function (orig) {
return function (header, value) {
if (header === '__setXHR_') {
<API key>(this);
var val = value(this);
// fix for angular < 1.2.0
if (val instanceof Function) {
val(this);
}
} else {
this.__requestHeaders = this.__requestHeaders || {};
this.__requestHeaders[header] = value;
orig.apply(this, arguments);
}
};
});
patchXHR('send', function (orig) {
return function () {
var xhr = this;
if (arguments[0] && arguments[0].__isFileAPIShim) {
var formData = arguments[0];
var config = {
url: xhr.__url,
jsonp: false, //removes the callback form param
cache: true, //removes the ?fileapiXXX in the url
complete: function (err, fileApiXHR) {
if (err.indexOf('#2174') !== -1) {
// this error seems to be fine the file is being uploaded properly.
err = null;
}
xhr.__completed = true;
if (!err && xhr.__listeners.load)
xhr.__listeners.load({
type: 'load',
loaded: xhr.__loaded,
total: xhr.__total,
target: xhr,
lengthComputable: true
});
if (!err && xhr.__listeners.loadend)
xhr.__listeners.loadend({
type: 'loadend',
loaded: xhr.__loaded,
total: xhr.__total,
target: xhr,
lengthComputable: true
});
if (err === 'abort' && xhr.__listeners.abort)
xhr.__listeners.abort({
type: 'abort',
loaded: xhr.__loaded,
total: xhr.__total,
target: xhr,
lengthComputable: true
});
if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function () {
return (fileApiXHR.status === 0 && err && err !== 'abort') ? 500 : fileApiXHR.status;
});
if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function () {
return fileApiXHR.statusText;
});
redefineProp(xhr, 'readyState', function () {
return 4;
});
if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function () {
return fileApiXHR.response;
});
var resp = fileApiXHR.responseText || (err && fileApiXHR.status === 0 && err !== 'abort' ? err : undefined);
redefineProp(xhr, 'responseText', function () {
return resp;
});
redefineProp(xhr, 'response', function () {
return resp;
});
if (err) redefineProp(xhr, 'err', function () {
return err;
});
xhr.__fileApiXHR = fileApiXHR;
if (xhr.onreadystatechange) xhr.onreadystatechange();
if (xhr.onload) xhr.onload();
},
progress: function (e) {
e.target = xhr;
if (xhr.__listeners.progress) xhr.__listeners.progress(e);
xhr.__total = e.total;
xhr.__loaded = e.loaded;
if (e.total === e.loaded) {
// fix flash issue that doesn't call complete if there is no response text from the server
var _this = this;
setTimeout(function () {
if (!xhr.__completed) {
xhr.<API key> = function () {
};
_this.complete(null, {status: 204, statusText: 'No Content'});
}
}, FileAPI.noContentTimeout || 10000);
}
},
headers: xhr.__requestHeaders
};
config.data = {};
config.files = {};
for (var i = 0; i < formData.data.length; i++) {
var item = formData.data[i];
if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) {
config.files[item.key] = item.val;
} else {
config.data[item.key] = item.val;
}
}
setTimeout(function () {
if (!FileAPI.hasFlash) {
throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
}
xhr.__fileApiXHR = FileAPI.upload(config);
}, 1);
} else {
if (this.__origError) {
throw this.__origError;
}
orig.apply(xhr, arguments);
}
};
});
window.XMLHttpRequest.__isFileAPIShim = true;
window.FormData = FormData = function () {
return {
append: function (key, val, name) {
if (val.__isFileAPIBlobShim) {
val = val.data[0];
}
this.data.push({
key: key,
val: val,
name: name
});
},
data: [],
__isFileAPIShim: true
};
};
window.Blob = Blob = function (b) {
return {
data: b,
__isFileAPIBlobShim: true
};
};
}
})();
(function () {
/** @namespace FileAPI.forceLoad */
/** @namespace window.FileAPI.jsUrl */
/** @namespace window.FileAPI.jsPath */
function isInputTypeFile(elem) {
return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file';
}
function hasFlash() {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) return true;
} catch (e) {
if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) return true;
}
return false;
}
function getOffset(obj) {
var left = 0, top = 0;
if (window.jQuery) {
return jQuery(obj).offset();
}
if (obj.offsetParent) {
do {
left += (obj.offsetLeft - obj.scrollLeft);
top += (obj.offsetTop - obj.scrollTop);
obj = obj.offsetParent;
} while (obj);
}
return {
left: left,
top: top
};
}
if (FileAPI.shouldLoad) {
//load FileAPI
if (FileAPI.forceLoad) {
FileAPI.html5 = false;
}
if (!FileAPI.upload) {
var jsUrl, basePath, script = document.createElement('script'), allScripts = document.<API key>('script'), i, index, src;
if (window.FileAPI.jsUrl) {
jsUrl = window.FileAPI.jsUrl;
} else if (window.FileAPI.jsPath) {
basePath = window.FileAPI.jsPath;
} else {
for (i = 0; i < allScripts.length; i++) {
src = allScripts[i].src;
index = src.search(/\/ng\-file\-upload[\-a-zA-z0-9\.]*\.js/);
if (index > -1) {
basePath = src.substring(0, index + 1);
break;
}
}
}
if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;
script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js');
document.<API key>('head')[0].appendChild(script);
FileAPI.hasFlash = hasFlash();
}
FileAPI.ngfFixIE = function (elem, fileElem, changeFn) {
if (!hasFlash()) {
throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
}
var fixInputStyle = function () {
if (elem.attr('disabled')) {
if (fileElem) fileElem.removeClass('js-fileapi-wrapper');
} else {
if (!fileElem.attr('__ngf_flash_')) {
fileElem.unbind('change');
fileElem.unbind('click');
fileElem.bind('change', function (evt) {
fileApiChangeFn.apply(this, [evt]);
changeFn.apply(this, [evt]);
});
fileElem.attr('__ngf_flash_', 'true');
}
fileElem.addClass('js-fileapi-wrapper');
if (!isInputTypeFile(elem)) {
fileElem.css('position', 'absolute')
.css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px')
.css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px')
.css('filter', 'alpha(opacity=0)').css('display', elem.css('display'))
.css('overflow', 'hidden').css('z-index', '900000')
.css('visibility', 'visible');
}
}
};
elem.bind('mouseenter', fixInputStyle);
var fileApiChangeFn = function (evt) {
var files = FileAPI.getFiles(evt);
//just a double check for #233
for (var i = 0; i < files.length; i++) {
if (files[i].size === undefined) files[i].size = 0;
if (files[i].name === undefined) files[i].name = 'file';
if (files[i].type === undefined) files[i].type = 'undefined';
}
if (!evt.target) {
evt.target = {};
}
evt.target.files = files;
// if evt.target.files is not writable use helper field
if (evt.target.files !== files) {
evt.__files_ = files;
}
(evt.__files_ || evt.target.files).item = function (i) {
return (evt.__files_ || evt.target.files)[i] || null;
};
};
};
FileAPI.disableFileInput = function (elem, disable) {
if (disable) {
elem.removeClass('js-fileapi-wrapper');
} else {
elem.addClass('js-fileapi-wrapper');
}
};
}
})();
if (!window.FileReader) {
window.FileReader = function () {
var _this = this, loadStarted = false;
this.listeners = {};
this.addEventListener = function (type, fn) {
_this.listeners[type] = _this.listeners[type] || [];
_this.listeners[type].push(fn);
};
this.removeEventListener = function (type, fn) {
if (_this.listeners[type]) _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1);
};
this.dispatchEvent = function (evt) {
var list = _this.listeners[evt.type];
if (list) {
for (var i = 0; i < list.length; i++) {
list[i].call(_this, evt);
}
}
};
this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null;
var constructEvent = function (type, evt) {
var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
if (evt.result != null) e.target.result = evt.result;
return e;
};
var listener = function (evt) {
if (!loadStarted) {
loadStarted = true;
if (_this.onloadstart) _this.onloadstart(constructEvent('loadstart', evt));
}
var e;
if (evt.type === 'load') {
if (_this.onloadend) _this.onloadend(constructEvent('loadend', evt));
e = constructEvent('load', evt);
if (_this.onload) _this.onload(e);
_this.dispatchEvent(e);
} else if (evt.type === 'progress') {
e = constructEvent('progress', evt);
if (_this.onprogress) _this.onprogress(e);
_this.dispatchEvent(e);
} else {
e = constructEvent('error', evt);
if (_this.onerror) _this.onerror(e);
_this.dispatchEvent(e);
}
};
this.readAsArrayBuffer = function (file) {
FileAPI.readAsBinaryString(file, listener);
};
this.readAsBinaryString = function (file) {
FileAPI.readAsBinaryString(file, listener);
};
this.readAsDataURL = function (file) {
FileAPI.readAsDataURL(file, listener);
};
this.readAsText = function (file) {
FileAPI.readAsText(file, listener);
};
};
}
/**!
* AngularJS file upload/drop directive and service with progress and abort
* @author Danial <danial.farid@gmail.com>
* @version 7.0.9
*/
if (window.XMLHttpRequest && !(window.FileAPI && FileAPI.shouldLoad)) {
window.XMLHttpRequest.prototype.setRequestHeader = (function (orig) {
return function (header, value) {
if (header === '__setXHR_') {
var val = value(this);
// fix for angular < 1.2.0
if (val instanceof Function) {
val(this);
}
} else {
orig.apply(this, arguments);
}
};
})(window.XMLHttpRequest.prototype.setRequestHeader);
}
var ngFileUpload = angular.module('ngFileUpload', []);
ngFileUpload.version = '7.0.9';
ngFileUpload.service('UploadBase', ['$http', '$q', '$timeout', function ($http, $q, $timeout) {
function sendHttp(config) {
config.method = config.method || 'POST';
config.headers = config.headers || {};
var deferred = $q.defer();
var promise = deferred.promise;
config.headers.__setXHR_ = function () {
return function (xhr) {
if (!xhr) return;
config.__XHR = xhr;
if (config.xhrFn) config.xhrFn(xhr);
xhr.upload.addEventListener('progress', function (e) {
e.config = config;
if (deferred.notify) {
deferred.notify(e);
} else if (promise.progressFunc) {
$timeout(function () {
promise.progressFunc(e);
});
}
}, false);
//fix for firefox not firing upload progress end, also IE8-9
xhr.upload.addEventListener('load', function (e) {
if (e.lengthComputable) {
e.config = config;
if (deferred.notify) {
deferred.notify(e);
} else if (promise.progressFunc) {
$timeout(function () {
promise.progressFunc(e);
});
}
}
}, false);
};
};
$http(config).then(function (r) {
deferred.resolve(r);
}, function (e) {
deferred.reject(e);
}, function (n) {
deferred.notify(n);
});
promise.success = function (fn) {
promise.then(function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function (fn) {
promise.then(null, function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.progress = function (fn) {
promise.progressFunc = fn;
promise.then(null, null, function (update) {
fn(update);
});
return promise;
};
promise.abort = function () {
if (config.__XHR) {
$timeout(function () {
config.__XHR.abort();
});
}
return promise;
};
promise.xhr = function (fn) {
config.xhrFn = (function (origXhrFn) {
return function () {
if (origXhrFn) origXhrFn.apply(promise, arguments);
fn.apply(promise, arguments);
};
})(config.xhrFn);
return promise;
};
return promise;
}
this.upload = function (config) {
function addFieldToFormData(formData, val, key) {
if (val !== undefined) {
if (angular.isDate(val)) {
val = val.toISOString();
}
if (angular.isString(val)) {
formData.append(key, val);
} else if (config.sendFieldsAs === 'form') {
if (angular.isObject(val)) {
for (var k in val) {
if (val.hasOwnProperty(k)) {
addFieldToFormData(formData, val[k], key + '[' + k + ']');
}
}
} else {
formData.append(key, val);
}
} else {
val = angular.isString(val) ? val : JSON.stringify(val);
if (config.sendFieldsAs === 'json-blob') {
formData.append(key, new Blob([val], {type: 'application/json'}));
} else {
formData.append(key, val);
}
}
}
}
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
config.transformRequest = config.transformRequest ?
(angular.isArray(config.transformRequest) ?
config.transformRequest : [config.transformRequest]) : [];
config.transformRequest.push(function (data) {
var formData = new FormData();
var allFields = {};
var key;
for (key in config.fields) {
if (config.fields.hasOwnProperty(key)) {
allFields[key] = config.fields[key];
}
}
if (data) allFields.data = data;
for (key in allFields) {
if (allFields.hasOwnProperty(key)) {
var val = allFields[key];
if (config.formDataAppender) {
config.formDataAppender(formData, key, val);
} else {
addFieldToFormData(formData, val, key);
}
}
}
if (config.file != null) {
var fileFormName = config.fileFormDataName || 'file';
if (angular.isArray(config.file)) {
var <API key> = angular.isString(fileFormName);
for (var i = 0; i < config.file.length; i++) {
formData.append(<API key> ? fileFormName : fileFormName[i], config.file[i],
(config.fileName && config.fileName[i]) || config.file[i].name);
}
} else {
formData.append(fileFormName, config.file, config.fileName || config.file.name);
}
}
return formData;
});
return sendHttp(config);
};
this.http = function (config) {
config.transformRequest = config.transformRequest || function (data) {
if ((window.ArrayBuffer && data instanceof window.ArrayBuffer) || data instanceof Blob) {
return data;
}
return $http.defaults.transformRequest[0](arguments);
};
return sendHttp(config);
};
this.setDefaults = function(defaults) {
this.defaults = defaults || {};
};
this.defaults = {};
this.version = ngFileUpload.version;
}
]);
(function () {
ngFileUpload.service('Upload', ['$parse', '$timeout', '$compile', 'UploadValidate',
function ($parse, $timeout, $compile, UploadValidate) {
var upload = UploadValidate;
upload.getAttrWithDefaults = function (attr, name) {
return attr[name] != null ? attr[name] :
(upload.defaults[name] == null ?
upload.defaults[name] : upload.defaults[name].toString());
};
upload.attrGetter = function (name, attr, scope, params) {
if (scope) {
try {
if (params) {
return $parse(this.getAttrWithDefaults(attr, name))(scope, params);
} else {
return $parse(this.getAttrWithDefaults(attr, name))(scope);
}
} catch (e) {
// hangle string value without single qoute
if (name.search(/min|max|pattern/i)) {
return this.getAttrWithDefaults(attr, name);
} else {
throw e;
}
}
} else {
return this.getAttrWithDefaults(attr, name);
}
};
upload.updateModel = function (ngModel, attr, scope, fileChange, files, evt, noDelay) {
function update() {
var keep = upload.attrGetter('ngfKeep', attr, scope);
if (keep === true) {
var prevFiles = (ngModel.$modelValue || []).slice(0);
if (!files || !files.length) {
files = prevFiles;
} else if (upload.attrGetter('ngfKeepDistinct', attr, scope) === true) {
var len = prevFiles.length;
for (var i = 0; i < files.length; i++) {
for (var j = 0; j < len; j++) {
if (files[i].name === prevFiles[j].name) break;
}
if (j === len) {
prevFiles.push(files[i]);
}
}
files = prevFiles;
} else {
files = prevFiles.concat(files);
}
}
var file = files && files.length ? files[0] : null;
if (ngModel) {
var singleModel = !upload.attrGetter('ngfMultiple', attr, scope) && !upload.attrGetter('multiple', attr) && !keep;
$timeout(function () {
$parse(upload.attrGetter('ngModel', attr)).assign(scope, singleModel ? file : files);
});
}
var ngfModel = upload.attrGetter('ngfModel', attr);
if (ngfModel) {
$parse(ngfModel).assign(scope, files);
}
if (fileChange) {
$parse(fileChange)(scope, {
$files: files,
$file: file,
$event: evt
});
}
}
if (noDelay) {
update();
} else if (upload.validate(files, ngModel, attr, scope, upload.attrGetter('ngfValidateLater', attr), function () {
$timeout(function () {
update();
});
}));
};
return upload;
}]);
})();
(function () {
ngFileUpload.directive('ngfSelect', ['$parse', '$timeout', '$compile', 'Upload',
function ($parse, $timeout, $compile, Upload) {
return {
restrict: 'AEC',
require: '?ngModel',
link: function (scope, elem, attr, ngModel) {
linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, Upload);
}
};
}]);
function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, upload) {
/** @namespace attr.ngfSelect */
/** @namespace attr.ngfChange */
/** @namespace attr.ngModel */
/** @namespace attr.ngfModel */
/** @namespace attr.ngfMultiple */
/** @namespace attr.ngfCapture */
/** @namespace attr.ngfValidate */
/** @namespace attr.ngfKeep */
/** @namespace attr.ngfKeepDistinct */
var attrGetter = function (name, scope) {
return upload.attrGetter(name, attr, scope);
};
upload.registerValidators(ngModel, attr, scope);
function isInputTypeFile() {
return elem[0].tagName.toLowerCase() === 'input' && attr.type && attr.type.toLowerCase() === 'file';
}
function fileChangeAttr() {
return attrGetter('ngfChange') || attrGetter('ngfSelect');
}
function changeFn(evt) {
var fileList = evt.__files_ || (evt.target && evt.target.files), files = [];
for (var i = 0; i < fileList.length; i++) {
files.push(fileList[i]);
}
upload.updateModel(ngModel, attr, scope, fileChangeAttr(), files.length ? files : null, evt);
}
scope.$watch(attrGetter('ngfMultiple'), function() {
fileElem.attr('multiple', attrGetter('ngfMultiple', scope));
});
scope.$watch(attrGetter('ngfCapture'), function() {
fileElem.attr('capture', attrGetter('ngfCapture', scope));
});
attr.$observe('accept', function() {
fileElem.attr('accept', attrGetter('accept'));
});
function bindAttrToFileInput(fileElem) {
if (elem !== fileElem) {
for (var i = 0; i < elem[0].attributes.length; i++) {
var attribute = elem[0].attributes[i];
if (attribute.name !== 'type' && attribute.name !== 'class' &&
attribute.name !== 'id' && attribute.name !== 'style') {
if (attribute.value == null || attribute.value === '') {
if (attribute.name === 'required') attribute.value = 'required';
if (attribute.name === 'multiple') attribute.value = 'multiple';
}
fileElem.attr(attribute.name, attribute.value);
}
}
}
}
function createFileInput() {
if (isInputTypeFile()) {
return elem;
}
var fileElem = angular.element('<input type="file">');
bindAttrToFileInput(fileElem);
fileElem.css('visibility', 'hidden').css('position', 'absolute').css('overflow', 'hidden')
.css('width', '0px').css('height', '0px').css('border', 'none')
.css('margin', '0px').css('padding', '0px').attr('tabindex', '-1');
document.body.appendChild(fileElem[0]);
return fileElem;
}
var initialTouchStartY = 0;
function clickHandler(evt) {
if (elem.attr('disabled') || attrGetter('ngfSelectDisabled', scope)) return false;
var r = handleTouch(evt);
if (r != null) return r;
resetModel(evt);
// fix for android native browser < 4.4
if (shouldClickLater(navigator.userAgent)) {
setTimeout(function () {
fileElem[0].click();
}, 0);
} else {
fileElem[0].click();
}
return false;
}
function handleTouch(evt) {
var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches);
if (evt.type === 'touchstart') {
initialTouchStartY = touches ? touches[0].clientY : 0;
return true; // don't block event default
} else {
evt.stopPropagation();
evt.preventDefault();
// prevent scroll from triggering event
if (evt.type === 'touchend') {
var currentLocation = touches ? touches[0].clientY : 0;
if (Math.abs(currentLocation - initialTouchStartY) > 20) return false;
}
}
}
function shouldClickLater(ua) {
// android below 4.4
var m = ua.match(/Android[^\d]*(\d+)\.(\d+)/);
if (m && m.length > 2) {
var v = upload.defaults.<API key> || 4;
return parseInt(m[1]) < 4 || (parseInt(m[1]) === v && parseInt(m[2]) < v);
}
// safari on windows
return ua.indexOf('Chrome') === -1 && /.*Windows.*Safari.*/.test(ua);
}
var fileElem = elem;
function resetModel(evt) {
if (fileElem.val()) {
fileElem.val(null);
upload.updateModel(ngModel, attr, scope, fileChangeAttr(), null, evt, true);
}
}
if (!isInputTypeFile()) {
fileElem = createFileInput();
}
fileElem.bind('change', changeFn);
if (!isInputTypeFile()) {
elem.bind('click touchstart touchend', clickHandler);
} else {
elem.bind('click', resetModel);
}
function <API key>(evt) {
if (fileElem && !fileElem.attr('__ngf_ie10_Fix_')) {
if (!fileElem[0].parentNode) {
fileElem = null;
return;
}
evt.preventDefault();
evt.stopPropagation();
fileElem.unbind('click');
var clone = fileElem.clone();
fileElem.replaceWith(clone);
fileElem = clone;
fileElem.attr('__ngf_ie10_Fix_', 'true');
fileElem.bind('change', changeFn);
fileElem.bind('click', <API key>);
fileElem[0].click();
return false;
} else {
fileElem.removeAttr('__ngf_ie10_Fix_');
}
}
if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
fileElem.bind('click', <API key>);
}
scope.$on('$destroy', function () {
if (!isInputTypeFile()) fileElem.remove();
});
if (window.FileAPI && window.FileAPI.ngfFixIE) {
window.FileAPI.ngfFixIE(elem, fileElem, changeFn);
}
}
})();
(function () {
ngFileUpload.service('UploadDataUrl', ['UploadBase', '$timeout', '$q', function (UploadBase, $timeout, $q) {
var upload = UploadBase;
upload.dataUrl = function (file, disallowObjectUrl) {
if (file.dataUrl) {
var d = $q.defer();
$timeout(function () {
d.resolve(file.dataUrl);
});
return d.promise;
}
if (file.$ngfDataUrlPromise) return file.$ngfDataUrlPromise;
var deferred = $q.defer();
$timeout(function () {
if (window.FileReader && file &&
(!window.FileAPI || navigator.userAgent.indexOf('MSIE 8') === -1 || file.size < 20000) &&
(!window.FileAPI || navigator.userAgent.indexOf('MSIE 9') === -1 || file.size < 4000000)) {
//prefer URL.createObjectURL for handling refrences to files of all sizes
var URL = window.URL || window.webkitURL;
if (URL && URL.createObjectURL && !disallowObjectUrl) {
var url;
try {
url = URL.createObjectURL(file);
} catch (e) {
deferred.reject();
return;
}
file.dataUrl = url;
if (url) deferred.resolve(url);
} else {
var fileReader = new FileReader();
fileReader.onload = function (e) {
$timeout(function () {
file.dataUrl = e.target.result;
deferred.resolve(e.target.result);
});
};
fileReader.onerror = function () {
$timeout(function () {
file.dataUrl = '';
deferred.reject();
});
};
fileReader.readAsDataURL(file);
}
} else {
file.dataUrl = '';
deferred.reject();
}
});
file.$ngfDataUrlPromise = deferred.promise;
file.$ngfDataUrlPromise['finally'](function () {
delete file.$ngfDataUrlPromise;
});
return file.$ngfDataUrlPromise;
};
return upload;
}]);
function getTagType(el) {
if (el.tagName.toLowerCase() === 'img') return 'image';
if (el.tagName.toLowerCase() === 'audio') return 'audio';
if (el.tagName.toLowerCase() === 'video') return 'video';
return /\./;
}
var style = angular.element('<style>.ngf-hide{display:none !important}</style>');
document.<API key>('head')[0].appendChild(style[0]);
/** @namespace attr.ngfSrc */
/** @namespace attr.ngfNoObjectUrl */
ngFileUpload.directive('ngfSrc', ['$compile', '$timeout', 'Upload', function ($compile, $timeout, Upload) {
return {
restrict: 'AE',
link: function (scope, elem, attr) {
$timeout(function () {
scope.$watch(attr.ngfSrc, function (file) {
if (file && file.type.indexOf(getTagType(elem[0])) === 0) {
Upload.dataUrl(file, Upload.attrGetter('ngfNoObjectUrl', attr, scope))['finally'](function () {
$timeout(function () {
if (file.dataUrl) {
elem.removeClass('ngf-hide');
elem.attr('src', file.dataUrl);
} else {
elem.addClass('ngf-hide');
}
});
});
} else {
elem.addClass('ngf-hide');
}
});
});
}
};
}]);
/** @namespace attr.ngfBackground */
/** @namespace attr.ngfNoObjectUrl */
ngFileUpload.directive('ngfBackground', ['Upload', '$compile', '$timeout', function (Upload, $compile, $timeout) {
return {
restrict: 'AE',
link: function (scope, elem, attr) {
$timeout(function () {
scope.$watch(attr.ngfBackground, function (file) {
if (file && file.type.indexOf('image') === 0) {
Upload.dataUrl(file, Upload.attrGetter('ngfNoObjectUrl', attr, scope))['finally'](function () {
$timeout(function () {
if (file.dataUrl) {
elem.css('background-image', 'url(\'' + file.dataUrl + '\')');
} else {
elem.css('background-image', '');
}
});
});
} else {
elem.css('background-image', '');
}
});
});
}
};
}]);
ngFileUpload.config(['$compileProvider', function ($compileProvider) {
if ($compileProvider.<API key>) $compileProvider.<API key>(/^\s*(https?|ftp|local|file|data|blob):/);
if ($compileProvider.<API key>) $compileProvider.<API key>(/^\s*(https?|ftp|local|file|data|blob):/);
}]);
ngFileUpload.filter('ngfDataUrl', ['UploadDataUrl', '$sce', function (UploadDataUrl, $sce) {
return function (file, disallowObjectUrl) {
if (angular.isString(file)) {
return $sce.trustAsResourceUrl(file);
}
if (file && !file.dataUrl) {
if (file.dataUrl === undefined && angular.isObject(file)) {
file.dataUrl = null;
UploadDataUrl.dataUrl(file, disallowObjectUrl).then(function (url) {
file.dataUrl = url;
}, function () {
file.dataUrl = '';
});
}
return '';
}
return (file && file.dataUrl ? $sce.trustAsResourceUrl(file.dataUrl) : file) || '';
};
}]);
})();
(function () {
function globStringToRegex(str) {
if (str.length > 2 && str[0] === '/' && str[str.length - 1] === '/') {
return str.substring(1, str.length - 1);
}
var split = str.split(','), result = '';
if (split.length > 1) {
for (var i = 0; i < split.length; i++) {
result += '(' + globStringToRegex(split[i]) + ')';
if (i < split.length - 1) {
result += '|';
}
}
} else {
if (str.indexOf('.') === 0) {
str = '*' + str;
}
result = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + '-]', 'g'), '\\$&') + '$';
result = result.replace(/\\\*/g, '.*').replace(/\\\?/g, '.');
}
return result;
}
function translateScalars(str) {
if (angular.isString(str)) {
if (str.search(/kb/i) === str.length - 2) {
return parseFloat(str.substring(0, str.length - 2) * 1000);
} else if (str.search(/mb/i) === str.length - 2) {
return parseFloat(str.substring(0, str.length - 2) * 1000000);
} else if (str.search(/gb/i) === str.length - 2) {
return parseFloat(str.substring(0, str.length - 2) * 1000000000);
} else if (str.search(/b/i) === str.length - 1) {
return parseFloat(str.substring(0, str.length - 1));
} else if (str.search(/s/i) === str.length - 1) {
return parseFloat(str.substring(0, str.length - 1));
} else if (str.search(/m/i) === str.length - 1) {
return parseFloat(str.substring(0, str.length - 1) * 60);
} else if (str.search(/h/i) === str.length - 1) {
return parseFloat(str.substring(0, str.length - 1) * 3600);
}
}
return str;
}
ngFileUpload.service('UploadValidate', ['UploadDataUrl', '$q', '$timeout', function (UploadDataUrl, $q, $timeout) {
var upload = UploadDataUrl;
upload.registerValidators = function (ngModel, attr, scope, later) {
if (!ngModel) return;
ngModel.$ngfValidations = ngModel.$ngfValidations || {};
function setValidities(ngModel) {
for (var k in ngModel.$ngfValidations) {
if (ngModel.$ngfValidations.hasOwnProperty(k)) {
ngModel.$setValidity(k, ngModel.$ngfValidations[k]);
}
}
}
ngModel.$formatters.push(function (val) {
if (later) {
upload.validate(val, ngModel, attr, scope, false, function () {
setValidities(ngModel);
});
} else {
for (var k in ngModel.$ngfValidations) {
if (ngModel.$ngfValidations.hasOwnProperty(k)) {
ngModel.$setValidity(k, ngModel.$ngfValidations[k]);
}
}
setValidities(ngModel);
}
return val;
});
};
upload.validatePattern = function (file, val) {
if (!val) {
return true;
}
var regexp = new RegExp(globStringToRegex(val), 'gi');
return (file.type != null && regexp.test(file.type.toLowerCase())) ||
(file.name != null && regexp.test(file.name.toLowerCase()));
};
upload.validate = function (files, ngModel, attr, scope, later, callback) {
ngModel = ngModel || {};
ngModel.$ngfValidations = ngModel.$ngfValidations || {};
var attrGetter = function (name, params) {
return upload.attrGetter(name, attr, scope, params);
};
if (later) {
callback.call(ngModel);
return;
}
function validateSync(name, validatorVal, fn) {
if (files) {
var valid = null, dName = 'ngf' + name[0].toUpperCase() + name.substr(1);
angular.forEach(files.length === undefined ? [files] : files, function (file) {
var val = attrGetter(dName, {'$file': file});
if (val == null) {
val = validatorVal(attrGetter('ngfValidate') || {});
}
if (val != null) {
valid = true;
if (!fn(file, val)) {
file.$error = name;
file.$errorParam = val;
valid = false;
return false;
}
}
});
if (valid != null) {
ngModel.$ngfValidations[name] = valid;
return valid;
}
}
return true;
}
var valid = true;
valid = valid && validateSync('pattern', function (cons) {
return cons.pattern;
}, upload.validatePattern);
valid = valid && validateSync('minSize', function (cons) {
return cons.size && cons.size.min;
}, function (file, val) {
return file.size >= translateScalars(val);
});
valid = valid && validateSync('maxSize', function (cons) {
return cons.size && cons.size.max;
}, function (file, val) {
return file.size <= translateScalars(val);
});
valid = valid && validateSync('validateFn', function () {
return null;
}, function (file, r) {
return r === true || r === null || r === '';
});
if (!valid) {
callback.call(ngModel, ngModel.$ngfValidations);
return;
}
var pendings = 0;
function validateAsync(name, validatorVal, type, asyncFn, fn) {
if (files) {
var thisPendings = 0, hasError = false, dName = 'ngf' + name[0].toUpperCase() + name.substr(1);
files = files.length === undefined ? [files] : files;
angular.forEach(files, function (file) {
if (file.type.search(type) !== 0) {
return true;
}
var val = attrGetter(dName, {'$file': file}) || validatorVal(attrGetter('ngfValidate', {'$file': file}) || {});
if (val) {
pendings++;
thisPendings++;
asyncFn(file, val).then(function (d) {
if (!fn(d, val)) {
file.$error = name;
file.$errorParam = val;
hasError = true;
}
}, function () {
if (attrGetter('ngfValidateForce', {'$file': file})) {
file.$error = name;
file.$errorParam = val;
hasError = true;
}
})['finally'](function () {
pendings
thisPendings
if (!thisPendings) {
ngModel.$ngfValidations[name] = !hasError;
}
if (!pendings) {
callback.call(ngModel, ngModel.$ngfValidations);
}
});
}
});
}
}
validateAsync('maxHeight', function (cons) {
return cons.height && cons.height.max;
}, /image/, this.imageDimensions, function (d, val) {
return d.height <= val;
});
validateAsync('minHeight', function (cons) {
return cons.height && cons.height.min;
}, /image/, this.imageDimensions, function (d, val) {
return d.height >= val;
});
validateAsync('maxWidth', function (cons) {
return cons.height && cons.width.max;
}, /image/, this.imageDimensions, function (d, val) {
return d.width <= val;
});
validateAsync('minWidth', function (cons) {
return cons.height && cons.width.min;
}, /image/, this.imageDimensions, function (d, val) {
return d.width >= val;
});
validateAsync('maxDuration', function (cons) {
return cons.height && cons.duration.max;
}, /audio|video/, this.mediaDuration, function (d, val) {
return d <= translateScalars(val);
});
validateAsync('minDuration', function (cons) {
return cons.height && cons.duration.min;
}, /audio|video/, this.mediaDuration, function (d, val) {
return d >= translateScalars(val);
});
validateAsync('validateAsyncFn', function () {
return null;
}, /./, function (file, val) {
return val;
}, function (r) {
return r === true || r === null || r === '';
});
if (!pendings) {
callback.call(ngModel, ngModel.$ngfValidations);
}
};
upload.imageDimensions = function (file) {
if (file.width && file.height) {
var d = $q.defer();
$timeout(function () {
d.resolve({width: file.width, height: file.height});
});
return d.promise;
}
if (file.$ngfDimensionPromise) return file.$ngfDimensionPromise;
var deferred = $q.defer();
$timeout(function () {
if (file.type.indexOf('image') !== 0) {
deferred.reject('not image');
return;
}
upload.dataUrl(file).then(function (dataUrl) {
var img = angular.element('<img>').attr('src', dataUrl).css('visibility', 'hidden').css('position', 'fixed');
function success() {
var width = img[0].clientWidth;
var height = img[0].clientHeight;
img.remove();
file.width = width;
file.height = height;
deferred.resolve({width: width, height: height});
}
function error() {
img.remove();
deferred.reject('load error');
}
img.on('load', success);
img.on('error', error);
var count = 0;
function checkLoadError() {
$timeout(function () {
if (img[0].parentNode) {
if (img[0].clientWidth) {
success();
} else if (count > 10) {
error();
} else {
checkLoadError();
}
}
}, 1000);
}
checkLoadError();
angular.element(document.<API key>('body')[0]).append(img);
}, function () {
deferred.reject('load error');
});
});
file.$ngfDimensionPromise = deferred.promise;
file.$ngfDimensionPromise['finally'](function () {
delete file.$ngfDimensionPromise;
});
return file.$ngfDimensionPromise;
};
upload.mediaDuration = function (file) {
if (file.duration) {
var d = $q.defer();
$timeout(function () {
d.resolve(file.duration);
});
return d.promise;
}
if (file.$ngfDurationPromise) return file.$ngfDurationPromise;
var deferred = $q.defer();
$timeout(function () {
if (file.type.indexOf('audio') !== 0 && file.type.indexOf('video') !== 0) {
deferred.reject('not media');
return;
}
upload.dataUrl(file).then(function (dataUrl) {
var el = angular.element(file.type.indexOf('audio') === 0 ? '<audio>' : '<video>')
.attr('src', dataUrl).css('visibility', 'none').css('position', 'fixed');
function success() {
var duration = el[0].duration;
file.duration = duration;
el.remove();
deferred.resolve(duration);
}
function error() {
el.remove();
deferred.reject('load error');
}
el.on('loadedmetadata', success);
el.on('error', error);
var count = 0;
function checkLoadError() {
$timeout(function () {
if (el[0].parentNode) {
if (el[0].duration) {
success();
} else if (count > 10) {
error();
} else {
checkLoadError();
}
}
}, 1000);
}
checkLoadError();
angular.element(document.body).append(el);
}, function () {
deferred.reject('load error');
});
});
file.$ngfDurationPromise = deferred.promise;
file.$ngfDurationPromise['finally'](function () {
delete file.$ngfDurationPromise;
});
return file.$ngfDurationPromise;
};
return upload;
}
])
;
})
();
(function () {
ngFileUpload.directive('ngfDrop', ['$parse', '$timeout', '$location', 'Upload',
function ($parse, $timeout, $location, Upload) {
return {
restrict: 'AEC',
require: '?ngModel',
link: function (scope, elem, attr, ngModel) {
linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $location, Upload);
}
};
}]);
ngFileUpload.directive('ngfNoFileDrop', function () {
return function (scope, elem) {
if (dropAvailable()) elem.css('display', 'none');
};
});
ngFileUpload.directive('ngfDropAvailable', ['$parse', '$timeout', 'Upload', function ($parse, $timeout, Upload) {
return function (scope, elem, attr) {
if (dropAvailable()) {
var model = $parse(Upload.attrGetter('ngfDropAvailable', attr));
$timeout(function () {
model(scope);
if (model.assign) {
model.assign(scope, true);
}
});
}
};
}]);
function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $location, upload) {
var available = dropAvailable();
var attrGetter = function (name, scope, params) {
return upload.attrGetter(name, attr, scope, params);
};
if (attrGetter('dropAvailable')) {
$timeout(function () {
if (scope[attrGetter('dropAvailable')]) {
scope[attrGetter('dropAvailable')].value = available;
} else {
scope[attrGetter('dropAvailable')] = available;
}
});
}
if (!available) {
if (attrGetter('<API key>', scope) === true) {
elem.css('display', 'none');
}
return;
}
function isDisabled() {
return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
}
upload.registerValidators(ngModel, attr, scope);
var leaveTimeout = null;
var stopPropagation = $parse(attrGetter('ngfStopPropagation'));
var dragOverDelay = 1;
var actualDragOverClass;
elem[0].addEventListener('dragover', function (evt) {
if (isDisabled()) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
// handling dragover events from the Chrome download bar
if (navigator.userAgent.indexOf('Chrome') > -1) {
var b = evt.dataTransfer.effectAllowed;
evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy';
}
$timeout.cancel(leaveTimeout);
if (!actualDragOverClass) {
actualDragOverClass = 'C';
<API key>(scope, attr, evt, function (clazz) {
actualDragOverClass = clazz;
elem.addClass(actualDragOverClass);
});
}
}, false);
elem[0].addEventListener('dragenter', function (evt) {
if (isDisabled()) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
}, false);
elem[0].addEventListener('dragleave', function () {
if (isDisabled()) return;
leaveTimeout = $timeout(function () {
elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
}, dragOverDelay || 1);
}, false);
elem[0].addEventListener('drop', function (evt) {
if (isDisabled()) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
extractFiles(evt, function (files) {
upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
}, attrGetter('ngfAllowDir', scope) !== false,
attrGetter('multiple') || attrGetter('ngfMultiple', scope));
}, false);
elem[0].addEventListener('paste', function (evt) {
if (isDisabled()) return;
var files = [];
var clipboard = evt.clipboardData || evt.originalEvent.clipboardData;
if (clipboard && clipboard.items) {
for (var k = 0; k < clipboard.items.length; k++) {
if (clipboard.items[k].type.indexOf('image') !== -1) {
files.push(clipboard.items[k].getAsFile());
}
}
upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
}
}, false);
function <API key>(scope, attr, evt, callback) {
var clazz = attrGetter('ngfDragOverClass', scope, {$event: evt}),
dClass = attrGetter('ngfDragOverClass') || 'dragover';
if (angular.isString(clazz)) {
callback(clazz);
return;
}
if (clazz) {
if (clazz.delay) dragOverDelay = clazz.delay;
if (clazz.accept || clazz.reject) {
var items = evt.dataTransfer.items;
if (items != null) {
var pattern = attrGetter('ngfPattern', scope, {$event: evt});
for (var i = 0; i < items.length; i++) {
if (items[i].kind === 'file' || items[i].kind === '') {
if (!upload.validatePattern(items[i], pattern)) {
dClass = clazz.reject;
break;
} else {
dClass = clazz.accept;
}
}
}
}
}
}
callback(dClass);
}
function extractFiles(evt, callback, allowDir, multiple) {
var files = [], processing = 0;
function traverseFileTree(files, entry, path) {
if (entry != null) {
if (entry.isDirectory) {
var filePath = (path || '') + entry.name;
files.push({name: entry.name, type: 'directory', path: filePath});
var dirReader = entry.createReader();
var entries = [];
processing++;
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
for (var i = 0; i < entries.length; i++) {
traverseFileTree(files, entries[i], (path ? path : '') + entry.name + '/');
}
processing
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
processing
console.error(e);
}
}, function () {
processing
});
};
readEntries();
} else {
processing++;
entry.file(function (file) {
try {
processing
file.path = (path ? path : '') + file.name;
files.push(file);
} catch (e) {
processing
console.error(e);
}
}, function () {
processing
});
}
}
}
var items = evt.dataTransfer.items;
if (items && items.length > 0 && $location.protocol() !== 'file') {
for (var i = 0; i < items.length; i++) {
if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
var entry = items[i].webkitGetAsEntry();
if (entry.isDirectory && !allowDir) {
continue;
}
if (entry != null) {
traverseFileTree(files, entry);
}
} else {
var f = items[i].getAsFile();
if (f != null) files.push(f);
}
if (!multiple && files.length > 0) break;
}
} else {
var fileList = evt.dataTransfer.files;
if (fileList != null) {
for (var j = 0; j < fileList.length; j++) {
files.push(fileList.item(j));
if (!multiple && files.length > 0) {
break;
}
}
}
}
var delays = 0;
(function waitForProcess(delay) {
$timeout(function () {
if (!processing) {
if (!multiple && files.length > 1) {
i = 0;
while (files[i].type === 'directory') i++;
files = [files[i]];
}
callback(files);
} else {
if (delays++ * 10 < 20 * 1000) {
waitForProcess(10);
}
}
}, delay || 0);
})();
}
}
function dropAvailable() {
var div = document.createElement('div');
return ('draggable' in div) && ('ondrop' in div) && !/Edge\/12./i.test(navigator.userAgent);
}
})(); |
package hudson.util;
import java.io.IOException;
import java.io.Writer;
import java.util.LinkedList;
import java.util.List;
/**
* {@link Writer} that spools the output and writes to another {@link Writer} later.
*
* @author Kohsuke Kawaguchi
* @deprecated since 2008-05-28. moved to stapler
*/
@Deprecated
public final class CharSpool extends Writer {
private List<char[]> buf;
private char[] last = new char[1024];
private int pos;
public void write(char cbuf[], int off, int len) {
while(len>0) {
int sz = Math.min(last.length-pos,len);
System.arraycopy(cbuf,off,last,pos,sz);
len -= sz;
off += sz;
pos += sz;
renew();
}
}
private void renew() {
if(pos<last.length)
return;
if(buf==null)
buf = new LinkedList<char[]>();
buf.add(last);
last = new char[1024];
pos = 0;
}
public void write(int c) {
renew();
last[pos++] = (char)c;
}
public void flush() {
// noop
}
public void close() {
// noop
}
public void writeTo(Writer w) throws IOException {
if(buf!=null) {
for (char[] cb : buf) {
w.write(cb);
}
}
w.write(last,0,pos);
}
} |
interface I {
"H"?<T>();
} |
#include <net/protocol.h>
#include "ip6_offload.h"
static const struct net_offload rthdr_offload = {
.flags = <API key>,
};
static const struct net_offload dstopt_offload = {
.flags = <API key>,
};
int __init <API key>(void)
{
int ret;
ret = inet6_add_offload(&rthdr_offload, IPPROTO_ROUTING);
if (!ret)
goto out;
ret = inet6_add_offload(&dstopt_offload, IPPROTO_DSTOPTS);
if (!ret)
goto out_rt;
out:
return ret;
out_rt:
inet_del_offload(&rthdr_offload, IPPROTO_ROUTING);
goto out;
} |
// Backbone has a dependency on jQuery 1.7+ because it refers to the
// jQuery.fn.on and jQuery.fn.off methods. We polyfill them here, but prefer
// the native implementation if it exists.
(function ($) {
$.fn.off = $.fn.off || function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
};
$.fn.on = $.fn.on || function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
};
}(jQuery)); |
import * as webpack from 'webpack';
import DotenvPlugin = require('<API key>');
const config: webpack.Configuration = {
plugins: [
new DotenvPlugin(),
new DotenvPlugin({
sample: './.env.default',
path: './.env'
}),
new DotenvPlugin({
sample: './.env.default',
path: './.env',
silent: true,
encoding: 'utf-8',
allowEmptyValues: true
})
]
}; |
#include "defs.h"
#include "count.h"
#include "dct4_a.h"
extern Word16 anal_bias[DCT_LENGTH];
extern Word16 dct_core_a[DCT_LENGTH_DIV_32][DCT_LENGTH_DIV_32];
extern cos_msin_t a_cos_msin_2 [DCT_LENGTH_DIV_32];
extern cos_msin_t a_cos_msin_4 [DCT_LENGTH_DIV_16];
extern cos_msin_t a_cos_msin_8 [DCT_LENGTH_DIV_8];
extern cos_msin_t a_cos_msin_16[DCT_LENGTH_DIV_4];
extern cos_msin_t a_cos_msin_32[DCT_LENGTH_DIV_2];
extern cos_msin_t a_cos_msin_64[DCT_LENGTH];
extern cos_msin_t *a_cos_msin_table[];
void dct_type_iv_a (Word16 *input,Word16 *output,Word16 dct_length)
{
Word16 buffer_a[MAX_DCT_LENGTH], buffer_b[MAX_DCT_LENGTH], buffer_c[MAX_DCT_LENGTH];
Word16 *in_ptr, *in_ptr_low, *in_ptr_high, *next_in_base;
Word16 *out_ptr_low, *out_ptr_high, *next_out_base;
Word16 *out_buffer, *in_buffer, *buffer_swap;
Word16 in_val_low, in_val_high;
Word16 out_val_low, out_val_high;
Word16 in_low_even, in_low_odd;
Word16 in_high_even, in_high_odd;
Word16 out_low_even, out_low_odd;
Word16 out_high_even, out_high_odd;
Word16 *pair_ptr;
Word16 cos_even, cos_odd, msin_even, msin_odd;
Word16 neg_cos_odd;
Word16 neg_msin_even;
Word32 sum;
Word16 set_span, set_count, set_count_log, pairs_left, sets_left;
Word16 i,k;
Word16 index;
cos_msin_t **table_ptr_ptr, *cos_msin_ptr;
Word16 temp;
Word32 acca;
Word16 dct_length_log;
/* Do the sum/difference butterflies, the first part of */
/* converting one N-point transform into N/2 two-point */
/* transforms, where N = 1 << DCT_LENGTH_LOG. = 64/128 */
test();
if (dct_length==DCT_LENGTH)
{
dct_length_log = DCT_LENGTH_LOG;
/* Add bias offsets */
for (i=0;i<dct_length;i++)
{
input[i] = add(input[i],anal_bias[i]);
move16();
}
}
else
dct_length_log = MAX_DCT_LENGTH_LOG;
index = 0L;
move16();
in_buffer = input;
move16();
out_buffer = buffer_a;
move16();
temp = sub(dct_length_log,2);
for (set_count_log=0;set_count_log<=temp;set_count_log++)
{
/* Initialization for the loop over sets at the current size */
/* set_span = 1 << (DCT_LENGTH_LOG - set_count_log); */
set_span = shr_nocheck(dct_length,set_count_log);
set_count = shl_nocheck(1,set_count_log);
in_ptr = in_buffer;
move16();
next_out_base = out_buffer;
move16();
/* Loop over all the sets of this size */
for (sets_left=set_count;sets_left>0;sets_left
{
/* Set up output pointers for the current set */
out_ptr_low = next_out_base;
next_out_base = next_out_base + set_span;
out_ptr_high = next_out_base;
/* Loop over all the butterflies in the current set */
do
{
in_val_low = *in_ptr++;
in_val_high = *in_ptr++;
// blp: addition of two 16bits vars, there's no way
// they'll overflow a 32bit var
//acca = L_add(in_val_low,in_val_high);
acca = (in_val_low + in_val_high);
acca = L_shr_nocheck(acca,1);
out_val_low = extract_l(acca);
acca = L_sub(in_val_low,in_val_high);
acca = L_shr_nocheck(acca,1);
out_val_high = extract_l(acca);
*out_ptr_low++ = out_val_low;
*--out_ptr_high = out_val_high;
test();
} while (out_ptr_low < out_ptr_high);
} /* End of loop over sets of the current size */
/* Decide which buffers to use as input and output next time. */
/* Except for the first time (when the input buffer is the */
/* subroutine input) we just alternate the local buffers. */
in_buffer = out_buffer;
move16();
if (out_buffer == buffer_a)
out_buffer = buffer_b;
else
out_buffer = buffer_a;
index = add(index,1);
} /* End of loop over set sizes */
/* Do N/2 two-point transforms, */
/* where N = 1 << DCT_LENGTH_LOG */
pair_ptr = in_buffer;
move16();
buffer_swap = buffer_c;
move16();
temp = sub(dct_length_log,1);
temp = shl_nocheck(1,temp);
for (pairs_left=temp; pairs_left > 0; pairs_left
{
for ( k=0; k<CORE_SIZE; k++ )
{
#if PJ_HAS_INT64
/* blp: danger danger! not really compatible but faster */
pj_int64_t sum64=0;
move32();
for ( i=0; i<CORE_SIZE; i++ )
{
sum64 += L_mult(pair_ptr[i], dct_core_a[i][k]);
}
sum = L_saturate(sum64);
#else
sum=0L;
move32();
for ( i=0; i<CORE_SIZE; i++ )
{
sum = L_mac(sum, pair_ptr[i],dct_core_a[i][k]);
}
#endif
buffer_swap[k] = itu_round(sum);
}
/* address arithmetic */
pair_ptr += CORE_SIZE;
buffer_swap += CORE_SIZE;
}
for (i=0;i<dct_length;i++)
{
in_buffer[i] = buffer_c[i];
move16();
}
table_ptr_ptr = a_cos_msin_table;
/* Perform rotation butterflies */
temp = sub(dct_length_log,2);
for (set_count_log = temp; set_count_log >= 0; set_count_log
{
/* Initialization for the loop over sets at the current size */
/* set_span = 1 << (DCT_LENGTH_LOG - set_count_log); */
set_span = shr_nocheck(dct_length,set_count_log);
set_count = shl_nocheck(1,set_count_log);
next_in_base = in_buffer;
move16();
test();
if (set_count_log == 0)
{
next_out_base = output;
}
else
{
next_out_base = out_buffer;
}
/* Loop over all the sets of this size */
for (sets_left = set_count; sets_left > 0;sets_left
{
/* Set up the pointers for the current set */
in_ptr_low = next_in_base;
move16();
temp = shr_nocheck(set_span,1);
/* address arithmetic */
in_ptr_high = in_ptr_low + temp;
next_in_base += set_span;
out_ptr_low = next_out_base;
next_out_base += set_span;
out_ptr_high = next_out_base;
cos_msin_ptr = *table_ptr_ptr;
/* Loop over all the butterfly pairs in the current set */
do
{
/* address arithmetic */
in_low_even = *in_ptr_low++;
in_low_odd = *in_ptr_low++;
in_high_even = *in_ptr_high++;
in_high_odd = *in_ptr_high++;
cos_even = cos_msin_ptr[0].cosine;
move16();
msin_even = cos_msin_ptr[0].minus_sine;
move16();
cos_odd = cos_msin_ptr[1].cosine;
move16();
msin_odd = cos_msin_ptr[1].minus_sine;
move16();
cos_msin_ptr += 2;
sum = 0L;
sum=L_mac(sum,cos_even,in_low_even);
neg_msin_even = negate(msin_even);
sum=L_mac(sum,neg_msin_even,in_high_even);
out_low_even = itu_round(sum);
sum = 0L;
sum=L_mac(sum,msin_even,in_low_even);
sum=L_mac(sum,cos_even,in_high_even);
out_high_even= itu_round(sum);
sum = 0L;
sum=L_mac(sum,cos_odd,in_low_odd);
sum=L_mac(sum,msin_odd,in_high_odd);
out_low_odd= itu_round(sum);
sum = 0L;
sum=L_mac(sum,msin_odd,in_low_odd);
neg_cos_odd = negate(cos_odd);
sum=L_mac(sum,neg_cos_odd,in_high_odd);
out_high_odd= itu_round(sum);
*out_ptr_low++ = out_low_even;
*--out_ptr_high = out_high_even;
*out_ptr_low++ = out_low_odd;
*--out_ptr_high = out_high_odd;
test();
} while (out_ptr_low < out_ptr_high);
} /* End of loop over sets of the current size */
/* Swap input and output buffers for next time */
buffer_swap = in_buffer;
in_buffer = out_buffer;
out_buffer = buffer_swap;
table_ptr_ptr++;
}
} |
/*
* This file implements functions needed to recover from unclean un-mounts.
* When UBIFS is mounted, it checks a flag on the master node to determine if
* an un-mount was completed successfully. If not, the process of mounting
* incorporates additional checking and fixing of on-flash data structures.
* UBIFS always cleans away all remnants of an unclean un-mount, so that
* errors do not accumulate. However UBIFS defers recovery if it is mounted
* read-only, and the flash is not modified in that case.
*
* The general UBIFS approach to the recovery is that it recovers from
* corruptions which could be caused by power cuts, but it refuses to recover
* from corruption caused by other reasons. And UBIFS tries to distinguish
* between these 2 reasons of corruptions and silently recover in the former
* case and loudly complain in the latter case.
*
* UBIFS writes only to erased LEBs, so it writes only to the flash space
* containing only 0xFFs. UBIFS also always writes strictly from the beginning
* of the LEB to the end. And UBIFS assumes that the underlying flash media
* writes in @c->max_write_size bytes at a time.
*
* Hence, if UBIFS finds a corrupted node at offset X, it expects only the min.
* I/O unit corresponding to offset X to contain corrupted data, all the
* following min. I/O units have to contain empty space (all 0xFFs). If this is
* not true, the corruption cannot be the result of a power cut, and UBIFS
* refuses to mount.
*/
#include <linux/crc32.h>
#include <linux/slab.h>
#include "ubifs.h"
/**
* is_empty - determine whether a buffer is empty (contains all 0xff).
* @buf: buffer to clean
* @len: length of buffer
*
* This function returns %1 if the buffer is empty (contains all 0xff) otherwise
* %0 is returned.
*/
static int is_empty(void *buf, int len)
{
uint8_t *p = buf;
int i;
for (i = 0; i < len; i++)
if (*p++ != 0xff)
return 0;
return 1;
}
/**
* first_non_ff - find offset of the first non-0xff byte.
* @buf: buffer to search in
* @len: length of buffer
*
* This function returns offset of the first non-0xff byte in @buf or %-1 if
* the buffer contains only 0xff bytes.
*/
static int first_non_ff(void *buf, int len)
{
uint8_t *p = buf;
int i;
for (i = 0; i < len; i++)
if (*p++ != 0xff)
return i;
return -1;
}
/**
* get_master_node - get the last valid master node allowing for corruption.
* @c: UBIFS file-system description object
* @lnum: LEB number
* @pbuf: buffer containing the LEB read, is returned here
* @mst: master node, if found, is returned here
* @cor: corruption, if found, is returned here
*
* This function allocates a buffer, reads the LEB into it, and finds and
* returns the last valid master node allowing for one area of corruption.
* The corrupt area, if there is one, must be consistent with the assumption
* that it is the result of an unclean unmount while the master node was being
* written. Under those circumstances, it is valid to use the previously written
* master node.
*
* This function returns %0 on success and a negative error code on failure.
*/
static int get_master_node(const struct ubifs_info *c, int lnum, void **pbuf,
struct ubifs_mst_node **mst, void **cor)
{
const int sz = c->mst_node_alsz;
int err, offs, len;
void *sbuf, *buf;
sbuf = vmalloc(c->leb_size);
if (!sbuf)
return -ENOMEM;
err = ubifs_leb_read(c, lnum, sbuf, 0, c->leb_size, 0);
if (err && err != -EBADMSG)
goto out_free;
/* Find the first position that is definitely not a node */
offs = 0;
buf = sbuf;
len = c->leb_size;
while (offs + UBIFS_MST_NODE_SZ <= c->leb_size) {
struct ubifs_ch *ch = buf;
if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC)
break;
offs += sz;
buf += sz;
len -= sz;
}
/* See if there was a valid master node before that */
if (offs) {
int ret;
offs -= sz;
buf -= sz;
len += sz;
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
if (ret != SCANNED_A_NODE && offs) {
/* Could have been corruption so check one place back */
offs -= sz;
buf -= sz;
len += sz;
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
if (ret != SCANNED_A_NODE)
/*
* We accept only one area of corruption because
* we are assuming that it was caused while
* trying to write a master node.
*/
goto out_err;
}
if (ret == SCANNED_A_NODE) {
struct ubifs_ch *ch = buf;
if (ch->node_type != UBIFS_MST_NODE)
goto out_err;
dbg_rcvry("found a master node at %d:%d", lnum, offs);
*mst = buf;
offs += sz;
buf += sz;
len -= sz;
}
}
/* Check for corruption */
if (offs < c->leb_size) {
if (!is_empty(buf, min_t(int, len, sz))) {
*cor = buf;
dbg_rcvry("found corruption at %d:%d", lnum, offs);
}
offs += sz;
buf += sz;
len -= sz;
}
/* Check remaining empty space */
if (offs < c->leb_size)
if (!is_empty(buf, len))
goto out_err;
*pbuf = sbuf;
return 0;
out_err:
err = -EINVAL;
out_free:
vfree(sbuf);
*mst = NULL;
*cor = NULL;
return err;
}
/**
* <API key> - write recovered master node.
* @c: UBIFS file-system description object
* @mst: master node
*
* This function returns %0 on success and a negative error code on failure.
*/
static int <API key>(struct ubifs_info *c,
struct ubifs_mst_node *mst)
{
int err = 0, lnum = UBIFS_MST_LNUM, sz = c->mst_node_alsz;
__le32 save_flags;
dbg_rcvry("recovery");
save_flags = mst->flags;
mst->flags |= cpu_to_le32(UBIFS_MST_RCVRY);
ubifs_prepare_node(c, mst, UBIFS_MST_NODE_SZ, 1);
err = ubifs_leb_change(c, lnum, mst, sz);
if (err)
goto out;
err = ubifs_leb_change(c, lnum + 1, mst, sz);
if (err)
goto out;
out:
mst->flags = save_flags;
return err;
}
/**
* <API key> - recover the master node.
* @c: UBIFS file-system description object
*
* This function recovers the master node from corruption that may occur due to
* an unclean unmount.
*
* This function returns %0 on success and a negative error code on failure.
*/
int <API key>(struct ubifs_info *c)
{
void *buf1 = NULL, *buf2 = NULL, *cor1 = NULL, *cor2 = NULL;
struct ubifs_mst_node *mst1 = NULL, *mst2 = NULL, *mst;
const int sz = c->mst_node_alsz;
int err, offs1, offs2;
dbg_rcvry("recovery");
err = get_master_node(c, UBIFS_MST_LNUM, &buf1, &mst1, &cor1);
if (err)
goto out_free;
err = get_master_node(c, UBIFS_MST_LNUM + 1, &buf2, &mst2, &cor2);
if (err)
goto out_free;
if (mst1) {
offs1 = (void *)mst1 - buf1;
if ((le32_to_cpu(mst1->flags) & UBIFS_MST_RCVRY) &&
(offs1 == 0 && !cor1)) {
/*
* mst1 was written by recovery at offset 0 with no
* corruption.
*/
dbg_rcvry("recovery recovery");
mst = mst1;
} else if (mst2) {
offs2 = (void *)mst2 - buf2;
if (offs1 == offs2) {
/* Same offset, so must be the same */
if (memcmp((void *)mst1 + UBIFS_CH_SZ,
(void *)mst2 + UBIFS_CH_SZ,
UBIFS_MST_NODE_SZ - UBIFS_CH_SZ))
goto out_err;
mst = mst1;
} else if (offs2 + sz == offs1) {
/* 1st LEB was written, 2nd was not */
if (cor1)
goto out_err;
mst = mst1;
} else if (offs1 == 0 &&
c->leb_size - offs2 - sz < sz) {
/* 1st LEB was unmapped and written, 2nd not */
if (cor1)
goto out_err;
mst = mst1;
} else
goto out_err;
} else {
/*
* 2nd LEB was unmapped and about to be written, so
* there must be only one master node in the first LEB
* and no corruption.
*/
if (offs1 != 0 || cor1)
goto out_err;
mst = mst1;
}
} else {
if (!mst2)
goto out_err;
/*
* 1st LEB was unmapped and about to be written, so there must
* be no room left in 2nd LEB.
*/
offs2 = (void *)mst2 - buf2;
if (offs2 + sz + sz <= c->leb_size)
goto out_err;
mst = mst2;
}
ubifs_msg("recovered master node from LEB %d",
(mst == mst1 ? UBIFS_MST_LNUM : UBIFS_MST_LNUM + 1));
memcpy(c->mst_node, mst, UBIFS_MST_NODE_SZ);
if (c->ro_mount) {
/* Read-only mode. Keep a copy for switching to rw mode */
c->rcvrd_mst_node = kmalloc(sz, GFP_KERNEL);
if (!c->rcvrd_mst_node) {
err = -ENOMEM;
goto out_free;
}
memcpy(c->rcvrd_mst_node, c->mst_node, UBIFS_MST_NODE_SZ);
/*
* We had to recover the master node, which means there was an
* unclean reboot. However, it is possible that the master node
* is clean at this point, i.e., %UBIFS_MST_DIRTY is not set.
* E.g., consider the following chain of events:
*
* 1. UBIFS was cleanly unmounted, so the master node is clean
* 2. UBIFS is being mounted R/W and starts changing the master
* node in the first (%UBIFS_MST_LNUM). A power cut happens,
* so this LEB ends up with some amount of garbage at the
* end.
* 3. UBIFS is being mounted R/O. We reach this place and
* recover the master node from the second LEB
* (%UBIFS_MST_LNUM + 1). But we cannot update the media
* because we are being mounted R/O. We have to defer the
* operation.
* 4. However, this master node (@c->mst_node) is marked as
* clean (since the step 1). And if we just return, the
* mount code will be confused and won't recover the master
* node when it is re-mounter R/W later.
*
* Thus, to force the recovery by marking the master node as
* dirty.
*/
c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
} else {
/* Write the recovered master node */
c->max_sqnum = le64_to_cpu(mst->ch.sqnum) - 1;
err = <API key>(c, c->mst_node);
if (err)
goto out_free;
}
vfree(buf2);
vfree(buf1);
return 0;
out_err:
err = -EINVAL;
out_free:
ubifs_err("failed to recover master node");
if (mst1) {
ubifs_err("dumping first master node");
ubifs_dump_node(c, mst1);
}
if (mst2) {
ubifs_err("dumping second master node");
ubifs_dump_node(c, mst2);
}
vfree(buf2);
vfree(buf1);
return err;
}
/**
* <API key> - write the recovered master node.
* @c: UBIFS file-system description object
*
* This function writes the master node that was recovered during mounting in
* read-only mode and must now be written because we are remounting rw.
*
* This function returns %0 on success and a negative error code on failure.
*/
int <API key>(struct ubifs_info *c)
{
int err;
if (!c->rcvrd_mst_node)
return 0;
c->rcvrd_mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
err = <API key>(c, c->rcvrd_mst_node);
if (err)
return err;
kfree(c->rcvrd_mst_node);
c->rcvrd_mst_node = NULL;
return 0;
}
/**
* is_last_write - determine if an offset was in the last write to a LEB.
* @c: UBIFS file-system description object
* @buf: buffer to check
* @offs: offset to check
*
* This function returns %1 if @offs was in the last write to the LEB whose data
* is in @buf, otherwise %0 is returned. The determination is made by checking
* for subsequent empty space starting from the next @c->max_write_size
* boundary.
*/
static int is_last_write(const struct ubifs_info *c, void *buf, int offs)
{
int empty_offs, check_len;
uint8_t *p;
/*
* Round up to the next @c->max_write_size boundary i.e. @offs is in
* the last wbuf written. After that should be empty space.
*/
empty_offs = ALIGN(offs + 1, c->max_write_size);
check_len = c->leb_size - empty_offs;
p = buf + empty_offs - offs;
return is_empty(p, check_len);
}
/**
* clean_buf - clean the data from an LEB sitting in a buffer.
* @c: UBIFS file-system description object
* @buf: buffer to clean
* @lnum: LEB number to clean
* @offs: offset from which to clean
* @len: length of buffer
*
* This function pads up to the next min_io_size boundary (if there is one) and
* sets empty space to all 0xff. @buf, @offs and @len are updated to the next
* @c->min_io_size boundary.
*/
static void clean_buf(const struct ubifs_info *c, void **buf, int lnum,
int *offs, int *len)
{
int empty_offs, pad_len;
lnum = lnum;
dbg_rcvry("cleaning corruption at %d:%d", lnum, *offs);
ubifs_assert(!(*offs & 7));
empty_offs = ALIGN(*offs, c->min_io_size);
pad_len = empty_offs - *offs;
ubifs_pad(c, *buf, pad_len);
*offs += pad_len;
*buf += pad_len;
*len -= pad_len;
memset(*buf, 0xff, c->leb_size - empty_offs);
}
/**
* no_more_nodes - determine if there are no more nodes in a buffer.
* @c: UBIFS file-system description object
* @buf: buffer to check
* @len: length of buffer
* @lnum: LEB number of the LEB from which @buf was read
* @offs: offset from which @buf was read
*
* This function ensures that the corrupted node at @offs is the last thing
* written to a LEB. This function returns %1 if more data is not found and
* %0 if more data is found.
*/
static int no_more_nodes(const struct ubifs_info *c, void *buf, int len,
int lnum, int offs)
{
struct ubifs_ch *ch = buf;
int skip, dlen = le32_to_cpu(ch->len);
/* Check for empty space after the corrupt node's common header */
skip = ALIGN(offs + UBIFS_CH_SZ, c->max_write_size) - offs;
if (is_empty(buf + skip, len - skip))
return 1;
/*
* The area after the common header size is not empty, so the common
* header must be intact. Check it.
*/
if (ubifs_check_node(c, buf, lnum, offs, 1, 0) != -EUCLEAN) {
dbg_rcvry("unexpected bad common header at %d:%d", lnum, offs);
return 0;
}
/* Now we know the corrupt node's length we can skip over it */
skip = ALIGN(offs + dlen, c->max_write_size) - offs;
/* After which there should be empty space */
if (is_empty(buf + skip, len - skip))
return 1;
dbg_rcvry("unexpected data at %d:%d", lnum, offs + skip);
return 0;
}
/**
* fix_unclean_leb - fix an unclean LEB.
* @c: UBIFS file-system description object
* @sleb: scanned LEB information
* @start: offset where scan started
*/
static int fix_unclean_leb(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
int start)
{
int lnum = sleb->lnum, endpt = start;
/* Get the end offset of the last node we are keeping */
if (!list_empty(&sleb->nodes)) {
struct ubifs_scan_node *snod;
snod = list_entry(sleb->nodes.prev,
struct ubifs_scan_node, list);
endpt = snod->offs + snod->len;
}
if (c->ro_mount && !c->remounting_rw) {
/* Add to recovery list */
struct ubifs_unclean_leb *ucleb;
dbg_rcvry("need to fix LEB %d start %d endpt %d",
lnum, start, sleb->endpt);
ucleb = kzalloc(sizeof(struct ubifs_unclean_leb), GFP_NOFS);
if (!ucleb)
return -ENOMEM;
ucleb->lnum = lnum;
ucleb->endpt = endpt;
list_add_tail(&ucleb->list, &c->unclean_leb_list);
} else {
/* Write the fixed LEB back to flash */
int err;
dbg_rcvry("fixing LEB %d start %d endpt %d",
lnum, start, sleb->endpt);
if (endpt == 0) {
err = ubifs_leb_unmap(c, lnum);
if (err)
return err;
} else {
int len = ALIGN(endpt, c->min_io_size);
if (start) {
err = ubifs_leb_read(c, lnum, sleb->buf, 0,
start, 1);
if (err)
return err;
}
/* Pad to min_io_size */
if (len > endpt) {
int pad_len = len - ALIGN(endpt, 8);
if (pad_len > 0) {
void *buf = sleb->buf + len - pad_len;
ubifs_pad(c, buf, pad_len);
}
}
err = ubifs_leb_change(c, lnum, sleb->buf, len);
if (err)
return err;
}
}
return 0;
}
/**
* drop_last_group - drop the last group of nodes.
* @sleb: scanned LEB information
* @offs: offset of dropped nodes is returned here
*
* This is a helper function for 'ubifs_recover_leb()' which drops the last
* group of nodes of the scanned LEB.
*/
static void drop_last_group(struct ubifs_scan_leb *sleb, int *offs)
{
while (!list_empty(&sleb->nodes)) {
struct ubifs_scan_node *snod;
struct ubifs_ch *ch;
snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node,
list);
ch = snod->node;
if (ch->group_type != UBIFS_IN_NODE_GROUP)
break;
dbg_rcvry("dropping grouped node at %d:%d",
sleb->lnum, snod->offs);
*offs = snod->offs;
list_del(&snod->list);
kfree(snod);
sleb->nodes_cnt -= 1;
}
}
/**
* drop_last_node - drop the last node.
* @sleb: scanned LEB information
* @offs: offset of dropped nodes is returned here
* @grouped: non-zero if whole group of nodes have to be dropped
*
* This is a helper function for 'ubifs_recover_leb()' which drops the last
* node of the scanned LEB.
*/
static void drop_last_node(struct ubifs_scan_leb *sleb, int *offs)
{
struct ubifs_scan_node *snod;
if (!list_empty(&sleb->nodes)) {
snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node,
list);
dbg_rcvry("dropping last node at %d:%d",
sleb->lnum, snod->offs);
*offs = snod->offs;
list_del(&snod->list);
kfree(snod);
sleb->nodes_cnt -= 1;
}
}
/**
* ubifs_recover_leb - scan and recover a LEB.
* @c: UBIFS file-system description object
* @lnum: LEB number
* @offs: offset
* @sbuf: LEB-sized buffer to use
* @jhead: journal head number this LEB belongs to (%-1 if the LEB does not
* belong to any journal head)
*
* This function does a scan of a LEB, but caters for errors that might have
* been caused by the unclean unmount from which we are attempting to recover.
* Returns %0 in case of success, %-EUCLEAN if an unrecoverable corruption is
* found, and a negative error code in case of failure.
*/
struct ubifs_scan_leb *ubifs_recover_leb(struct ubifs_info *c, int lnum,
int offs, void *sbuf, int jhead)
{
int ret = 0, err, len = c->leb_size - offs, start = offs, min_io_unit;
int grouped = jhead == -1 ? 0 : c->jheads[jhead].grouped;
struct ubifs_scan_leb *sleb;
void *buf = sbuf + offs;
dbg_rcvry("%d:%d, jhead %d, grouped %d", lnum, offs, jhead, grouped);
sleb = ubifs_start_scan(c, lnum, offs, sbuf);
if (IS_ERR(sleb))
return sleb;
ubifs_assert(len >= 8);
while (len >= 8) {
dbg_scan("look at LEB %d:%d (%d bytes left)",
lnum, offs, len);
cond_resched();
/*
* Scan quietly until there is an error from which we cannot
* recover
*/
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
if (ret == SCANNED_A_NODE) {
/* A valid node, and not a padding node */
struct ubifs_ch *ch = buf;
int node_len;
err = ubifs_add_snod(c, sleb, buf, offs);
if (err)
goto error;
node_len = ALIGN(le32_to_cpu(ch->len), 8);
offs += node_len;
buf += node_len;
len -= node_len;
} else if (ret > 0) {
/* Padding bytes or a valid padding node */
offs += ret;
buf += ret;
len -= ret;
} else if (ret == SCANNED_EMPTY_SPACE ||
ret == SCANNED_GARBAGE ||
ret == <API key> ||
ret == <API key>) {
dbg_rcvry("found corruption (%d) at %d:%d",
ret, lnum, offs);
break;
} else {
ubifs_err("unexpected return value %d", ret);
err = -EINVAL;
goto error;
}
}
if (ret == SCANNED_GARBAGE || ret == <API key>) {
if (!is_last_write(c, buf, offs))
goto corrupted_rescan;
} else if (ret == <API key>) {
if (!no_more_nodes(c, buf, len, lnum, offs))
goto corrupted_rescan;
} else if (!is_empty(buf, len)) {
if (!is_last_write(c, buf, offs)) {
int corruption = first_non_ff(buf, len);
/*
* See header comment for this file for more
* explanations about the reasons we have this check.
*/
ubifs_err("corrupt empty space LEB %d:%d, corruption starts at %d",
lnum, offs, corruption);
/* Make sure we dump interesting non-0xFF data */
offs += corruption;
buf += corruption;
goto corrupted;
}
}
min_io_unit = round_down(offs, c->min_io_size);
if (grouped)
/*
* If nodes are grouped, always drop the incomplete group at
* the end.
*/
drop_last_group(sleb, &offs);
if (jhead == GCHD) {
/*
* If this LEB belongs to the GC head then while we are in the
* middle of the same min. I/O unit keep dropping nodes. So
* basically, what we want is to make sure that the last min.
* I/O unit where we saw the corruption is dropped completely
* with all the uncorrupted nodes which may possibly sit there.
*
* In other words, let's name the min. I/O unit where the
* corruption starts B, and the previous min. I/O unit A. The
* below code tries to deal with a situation when half of B
* contains valid nodes or the end of a valid node, and the
* second half of B contains corrupted data or garbage. This
* means that UBIFS had been writing to B just before the power
* cut happened. I do not know how realistic is this scenario
* that half of the min. I/O unit had been written successfully
* and the other half not, but this is possible in our 'failure
* mode emulation' infrastructure at least.
*
* So what is the problem, why we need to drop those nodes? Why
* can't we just clean-up the second half of B by putting a
* padding node there? We can, and this works fine with one
* exception which was reproduced with power cut emulation
* testing and happens extremely rarely.
*
* Imagine the file-system is full, we run GC which starts
* moving valid nodes from LEB X to LEB Y (obviously, LEB Y is
* the current GC head LEB). The @c->gc_lnum is -1, which means
* that GC will retain LEB X and will try to continue. Imagine
* that LEB X is currently the dirtiest LEB, and the amount of
* used space in LEB Y is exactly the same as amount of free
* space in LEB X.
*
* And a power cut happens when nodes are moved from LEB X to
* LEB Y. We are here trying to recover LEB Y which is the GC
* head LEB. We find the min. I/O unit B as described above.
* Then we clean-up LEB Y by padding min. I/O unit. And later
* '<API key>()' function fails, because it cannot
* find a dirty LEB which could be GC'd into LEB Y! Even LEB X
* does not match because the amount of valid nodes there does
* not fit the free space in LEB Y any more! And this is
* because of the padding node which we added to LEB Y. The
* user-visible effect of this which I once observed and
* analysed is that we cannot mount the file-system with
* -ENOSPC error.
*
* So obviously, to make sure that situation does not happen we
* should free min. I/O unit B in LEB Y completely and the last
* used min. I/O unit in LEB Y should be A. This is basically
* what the below code tries to do.
*/
while (offs > min_io_unit)
drop_last_node(sleb, &offs);
}
buf = sbuf + offs;
len = c->leb_size - offs;
clean_buf(c, &buf, lnum, &offs, &len);
ubifs_end_scan(c, sleb, lnum, offs);
err = fix_unclean_leb(c, sleb, start);
if (err)
goto error;
return sleb;
corrupted_rescan:
/* Re-scan the corrupted data with verbose messages */
ubifs_err("corruption %d", ret);
ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
corrupted:
<API key>(c, lnum, offs, buf);
err = -EUCLEAN;
error:
ubifs_err("LEB %d scanning failed", lnum);
ubifs_scan_destroy(sleb);
return ERR_PTR(err);
}
/**
* get_cs_sqnum - get commit start sequence number.
* @c: UBIFS file-system description object
* @lnum: LEB number of commit start node
* @offs: offset of commit start node
* @cs_sqnum: commit start sequence number is returned here
*
* This function returns %0 on success and a negative error code on failure.
*/
static int get_cs_sqnum(struct ubifs_info *c, int lnum, int offs,
unsigned long long *cs_sqnum)
{
struct ubifs_cs_node *cs_node = NULL;
int err, ret;
dbg_rcvry("at %d:%d", lnum, offs);
cs_node = kmalloc(UBIFS_CS_NODE_SZ, GFP_KERNEL);
if (!cs_node)
return -ENOMEM;
if (c->leb_size - offs < UBIFS_CS_NODE_SZ)
goto out_err;
err = ubifs_leb_read(c, lnum, (void *)cs_node, offs,
UBIFS_CS_NODE_SZ, 0);
if (err && err != -EBADMSG)
goto out_free;
ret = ubifs_scan_a_node(c, cs_node, UBIFS_CS_NODE_SZ, lnum, offs, 0);
if (ret != SCANNED_A_NODE) {
ubifs_err("Not a valid node");
goto out_err;
}
if (cs_node->ch.node_type != UBIFS_CS_NODE) {
ubifs_err("Node a CS node, type is %d", cs_node->ch.node_type);
goto out_err;
}
if (le64_to_cpu(cs_node->cmt_no) != c->cmt_no) {
ubifs_err("CS node cmt_no %llu != current cmt_no %llu",
(unsigned long long)le64_to_cpu(cs_node->cmt_no),
c->cmt_no);
goto out_err;
}
*cs_sqnum = le64_to_cpu(cs_node->ch.sqnum);
dbg_rcvry("commit start sqnum %llu", *cs_sqnum);
kfree(cs_node);
return 0;
out_err:
err = -EINVAL;
out_free:
ubifs_err("failed to get CS sqnum");
kfree(cs_node);
return err;
}
/**
* <API key> - scan and recover a log LEB.
* @c: UBIFS file-system description object
* @lnum: LEB number
* @offs: offset
* @sbuf: LEB-sized buffer to use
*
* This function does a scan of a LEB, but caters for errors that might have
* been caused by unclean reboots from which we are attempting to recover
* (assume that only the last log LEB can be corrupted by an unclean reboot).
*
* This function returns %0 on success and a negative error code on failure.
*/
struct ubifs_scan_leb *<API key>(struct ubifs_info *c, int lnum,
int offs, void *sbuf)
{
struct ubifs_scan_leb *sleb;
int next_lnum;
dbg_rcvry("LEB %d", lnum);
next_lnum = lnum + 1;
if (next_lnum >= UBIFS_LOG_LNUM + c->log_lebs)
next_lnum = UBIFS_LOG_LNUM;
if (next_lnum != c->ltail_lnum) {
/*
* We can only recover at the end of the log, so check that the
* next log LEB is empty or out of date.
*/
sleb = ubifs_scan(c, next_lnum, 0, sbuf, 0);
if (IS_ERR(sleb))
return sleb;
if (sleb->nodes_cnt) {
struct ubifs_scan_node *snod;
unsigned long long cs_sqnum = c->cs_sqnum;
snod = list_entry(sleb->nodes.next,
struct ubifs_scan_node, list);
if (cs_sqnum == 0) {
int err;
err = get_cs_sqnum(c, lnum, offs, &cs_sqnum);
if (err) {
ubifs_scan_destroy(sleb);
return ERR_PTR(err);
}
}
if (snod->sqnum > cs_sqnum) {
ubifs_err("unrecoverable log corruption in LEB %d",
lnum);
ubifs_scan_destroy(sleb);
return ERR_PTR(-EUCLEAN);
}
}
ubifs_scan_destroy(sleb);
}
return ubifs_recover_leb(c, lnum, offs, sbuf, -1);
}
/**
* recover_head - recover a head.
* @c: UBIFS file-system description object
* @lnum: LEB number of head to recover
* @offs: offset of head to recover
* @sbuf: LEB-sized buffer to use
*
* This function ensures that there is no data on the flash at a head location.
*
* This function returns %0 on success and a negative error code on failure.
*/
static int recover_head(struct ubifs_info *c, int lnum, int offs, void *sbuf)
{
int len = c->max_write_size, err;
if (offs + len > c->leb_size)
len = c->leb_size - offs;
if (!len)
return 0;
/* Read at the head location and check it is empty flash */
err = ubifs_leb_read(c, lnum, sbuf, offs, len, 1);
if (err || !is_empty(sbuf, len)) {
dbg_rcvry("cleaning head at %d:%d", lnum, offs);
if (offs == 0)
return ubifs_leb_unmap(c, lnum);
err = ubifs_leb_read(c, lnum, sbuf, 0, offs, 1);
if (err)
return err;
return ubifs_leb_change(c, lnum, sbuf, offs);
}
return 0;
}
/**
* <API key> - recover index and LPT heads.
* @c: UBIFS file-system description object
* @sbuf: LEB-sized buffer to use
*
* This function ensures that there is no data on the flash at the index and
* LPT head locations.
*
* This deals with the recovery of a half-completed journal commit. UBIFS is
* careful never to overwrite the last version of the index or the LPT. Because
* the index and LPT are wandering trees, data from a half-completed commit will
* not be referenced anywhere in UBIFS. The data will be either in LEBs that are
* assumed to be empty and will be unmapped anyway before use, or in the index
* and LPT heads.
*
* This function returns %0 on success and a negative error code on failure.
*/
int <API key>(struct ubifs_info *c, void *sbuf)
{
int err;
ubifs_assert(!c->ro_mount || c->remounting_rw);
dbg_rcvry("checking index head at %d:%d", c->ihead_lnum, c->ihead_offs);
err = recover_head(c, c->ihead_lnum, c->ihead_offs, sbuf);
if (err)
return err;
dbg_rcvry("checking LPT head at %d:%d", c->nhead_lnum, c->nhead_offs);
err = recover_head(c, c->nhead_lnum, c->nhead_offs, sbuf);
if (err)
return err;
return 0;
}
/**
* <API key> - read and write a LEB to remove corruption.
* @c: UBIFS file-system description object
* @ucleb: unclean LEB information
* @sbuf: LEB-sized buffer to use
*
* This function reads a LEB up to a point pre-determined by the mount recovery,
* checks the nodes, and writes the result back to the flash, thereby cleaning
* off any following corruption, or non-fatal ECC errors.
*
* This function returns %0 on success and a negative error code on failure.
*/
static int <API key>(struct ubifs_info *c,
struct ubifs_unclean_leb *ucleb, void *sbuf)
{
int err, lnum = ucleb->lnum, offs = 0, len = ucleb->endpt, quiet = 1;
void *buf = sbuf;
dbg_rcvry("LEB %d len %d", lnum, len);
if (len == 0) {
/* Nothing to read, just unmap it */
err = ubifs_leb_unmap(c, lnum);
if (err)
return err;
return 0;
}
err = ubifs_leb_read(c, lnum, buf, offs, len, 0);
if (err && err != -EBADMSG)
return err;
while (len >= 8) {
int ret;
cond_resched();
/* Scan quietly until there is an error */
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, quiet);
if (ret == SCANNED_A_NODE) {
/* A valid node, and not a padding node */
struct ubifs_ch *ch = buf;
int node_len;
node_len = ALIGN(le32_to_cpu(ch->len), 8);
offs += node_len;
buf += node_len;
len -= node_len;
continue;
}
if (ret > 0) {
/* Padding bytes or a valid padding node */
offs += ret;
buf += ret;
len -= ret;
continue;
}
if (ret == SCANNED_EMPTY_SPACE) {
ubifs_err("unexpected empty space at %d:%d",
lnum, offs);
return -EUCLEAN;
}
if (quiet) {
/* Redo the last scan but noisily */
quiet = 0;
continue;
}
<API key>(c, lnum, offs, buf);
return -EUCLEAN;
}
/* Pad to min_io_size */
len = ALIGN(ucleb->endpt, c->min_io_size);
if (len > ucleb->endpt) {
int pad_len = len - ALIGN(ucleb->endpt, 8);
if (pad_len > 0) {
buf = c->sbuf + len - pad_len;
ubifs_pad(c, buf, pad_len);
}
}
/* Write back the LEB atomically */
err = ubifs_leb_change(c, lnum, sbuf, len);
if (err)
return err;
dbg_rcvry("cleaned LEB %d", lnum);
return 0;
}
/**
* ubifs_clean_lebs - clean LEBs recovered during read-only mount.
* @c: UBIFS file-system description object
* @sbuf: LEB-sized buffer to use
*
* This function cleans a LEB identified during recovery that needs to be
* written but was not because UBIFS was mounted read-only. This happens when
* remounting to read-write mode.
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_clean_lebs(struct ubifs_info *c, void *sbuf)
{
dbg_rcvry("recovery");
while (!list_empty(&c->unclean_leb_list)) {
struct ubifs_unclean_leb *ucleb;
int err;
ucleb = list_entry(c->unclean_leb_list.next,
struct ubifs_unclean_leb, list);
err = <API key>(c, ucleb, sbuf);
if (err)
return err;
list_del(&ucleb->list);
kfree(ucleb);
}
return 0;
}
/**
* grab_empty_leb - grab an empty LEB to use as GC LEB and run commit.
* @c: UBIFS file-system description object
*
* This is a helper function for '<API key>()' which grabs an empty
* LEB to be used as GC LEB (@c->gc_lnum), and then runs the commit. Returns
* zero in case of success and a negative error code in case of failure.
*/
static int grab_empty_leb(struct ubifs_info *c)
{
int lnum, err;
/*
* Note, it is very important to first search for an empty LEB and then
* run the commit, not vice-versa. The reason is that there might be
* only one empty LEB at the moment, the one which has been the
* @c->gc_lnum just before the power cut happened. During the regular
* UBIFS operation (not now) @c->gc_lnum is marked as "taken", so no
* one but GC can grab it. But at this moment this single empty LEB is
* not marked as taken, so if we run commit - what happens? Right, the
* commit will grab it and write the index there. Remember that the
* index always expands as long as there is free space, and it only
* starts consolidating when we run out of space.
*
* IOW, if we run commit now, we might not be able to find a free LEB
* after this.
*/
lnum = <API key>(c);
if (lnum < 0) {
ubifs_err("could not find an empty LEB");
ubifs_dump_lprops(c);
ubifs_dump_budg(c, &c->bi);
return lnum;
}
/* Reset the index flag */
err = ubifs_change_one_lp(c, lnum, LPROPS_NC, LPROPS_NC, 0,
LPROPS_INDEX, 0);
if (err)
return err;
c->gc_lnum = lnum;
dbg_rcvry("found empty LEB %d, run commit", lnum);
return ubifs_run_commit(c);
}
/**
* <API key> - recover the GC LEB number and run the commit.
* @c: UBIFS file-system description object
*
* Out-of-place garbage collection requires always one empty LEB with which to
* start garbage collection. The LEB number is recorded in c->gc_lnum and is
* written to the master node on unmounting. In the case of an unclean unmount
* the value of gc_lnum recorded in the master node is out of date and cannot
* be used. Instead, recovery must allocate an empty LEB for this purpose.
* However, there may not be enough empty space, in which case it must be
* possible to GC the dirtiest LEB into the GC head LEB.
*
* This function also runs the commit which causes the TNC updates from
* size-recovery and orphans to be written to the flash. That is important to
* ensure correct replay order for subsequent mounts.
*
* This function returns %0 on success and a negative error code on failure.
*/
int <API key>(struct ubifs_info *c)
{
struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
struct ubifs_lprops lp;
int err;
dbg_rcvry("GC head LEB %d, offs %d", wbuf->lnum, wbuf->offs);
c->gc_lnum = -1;
if (wbuf->lnum == -1 || wbuf->offs == c->leb_size)
return grab_empty_leb(c);
err = <API key>(c, &lp, wbuf->offs, 2);
if (err) {
if (err != -ENOSPC)
return err;
dbg_rcvry("could not find a dirty LEB");
return grab_empty_leb(c);
}
ubifs_assert(!(lp.flags & LPROPS_INDEX));
ubifs_assert(lp.free + lp.dirty >= wbuf->offs);
/*
* We run the commit before garbage collection otherwise subsequent
* mounts will see the GC and orphan deletion in a different order.
*/
dbg_rcvry("committing");
err = ubifs_run_commit(c);
if (err)
return err;
dbg_rcvry("GC'ing LEB %d", lp.lnum);
mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
err = <API key>(c, &lp);
if (err >= 0) {
int err2 = <API key>(wbuf);
if (err2)
err = err2;
}
mutex_unlock(&wbuf->io_mutex);
if (err < 0) {
ubifs_err("GC failed, error %d", err);
if (err == -EAGAIN)
err = -EINVAL;
return err;
}
ubifs_assert(err == LEB_RETAINED);
if (err != LEB_RETAINED)
return -EINVAL;
err = ubifs_leb_unmap(c, c->gc_lnum);
if (err)
return err;
dbg_rcvry("allocated LEB %d for GC", lp.lnum);
return 0;
}
/**
* struct size_entry - inode size information for recovery.
* @rb: link in the RB-tree of sizes
* @inum: inode number
* @i_size: size on inode
* @d_size: maximum size based on data nodes
* @exists: indicates whether the inode exists
* @inode: inode if pinned in memory awaiting rw mode to fix it
*/
struct size_entry {
struct rb_node rb;
ino_t inum;
loff_t i_size;
loff_t d_size;
int exists;
struct inode *inode;
};
/**
* add_ino - add an entry to the size tree.
* @c: UBIFS file-system description object
* @inum: inode number
* @i_size: size on inode
* @d_size: maximum size based on data nodes
* @exists: indicates whether the inode exists
*/
static int add_ino(struct ubifs_info *c, ino_t inum, loff_t i_size,
loff_t d_size, int exists)
{
struct rb_node **p = &c->size_tree.rb_node, *parent = NULL;
struct size_entry *e;
while (*p) {
parent = *p;
e = rb_entry(parent, struct size_entry, rb);
if (inum < e->inum)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
e = kzalloc(sizeof(struct size_entry), GFP_KERNEL);
if (!e)
return -ENOMEM;
e->inum = inum;
e->i_size = i_size;
e->d_size = d_size;
e->exists = exists;
rb_link_node(&e->rb, parent, p);
rb_insert_color(&e->rb, &c->size_tree);
return 0;
}
/**
* find_ino - find an entry on the size tree.
* @c: UBIFS file-system description object
* @inum: inode number
*/
static struct size_entry *find_ino(struct ubifs_info *c, ino_t inum)
{
struct rb_node *p = c->size_tree.rb_node;
struct size_entry *e;
while (p) {
e = rb_entry(p, struct size_entry, rb);
if (inum < e->inum)
p = p->rb_left;
else if (inum > e->inum)
p = p->rb_right;
else
return e;
}
return NULL;
}
/**
* remove_ino - remove an entry from the size tree.
* @c: UBIFS file-system description object
* @inum: inode number
*/
static void remove_ino(struct ubifs_info *c, ino_t inum)
{
struct size_entry *e = find_ino(c, inum);
if (!e)
return;
rb_erase(&e->rb, &c->size_tree);
kfree(e);
}
/**
* <API key> - free resources related to the size tree.
* @c: UBIFS file-system description object
*/
void <API key>(struct ubifs_info *c)
{
struct size_entry *e, *n;
<API key>(e, n, &c->size_tree, rb) {
if (e->inode)
iput(e->inode);
kfree(e);
}
c->size_tree = RB_ROOT;
}
/**
* <API key> - accumulate inode sizes for recovery.
* @c: UBIFS file-system description object
* @key: node key
* @deletion: node is for a deletion
* @new_size: inode size
*
* This function has two purposes:
* 1) to ensure there are no data nodes that fall outside the inode size
* 2) to ensure there are no data nodes for inodes that do not exist
* To accomplish those purposes, a rb-tree is constructed containing an entry
* for each inode number in the journal that has not been deleted, and recording
* the size from the inode node, the maximum size of any data node (also altered
* by truncations) and a flag indicating a inode number for which no inode node
* was present in the journal.
*
* Note that there is still the possibility that there are data nodes that have
* been committed that are beyond the inode size, however the only way to find
* them would be to scan the entire index. Alternatively, some provision could
* be made to record the size of inodes at the start of commit, which would seem
* very cumbersome for a scenario that is quite unlikely and the only negative
* consequence of which is wasted space.
*
* This functions returns %0 on success and a negative error code on failure.
*/
int <API key>(struct ubifs_info *c, union ubifs_key *key,
int deletion, loff_t new_size)
{
ino_t inum = key_inum(c, key);
struct size_entry *e;
int err;
switch (key_type(c, key)) {
case UBIFS_INO_KEY:
if (deletion)
remove_ino(c, inum);
else {
e = find_ino(c, inum);
if (e) {
e->i_size = new_size;
e->exists = 1;
} else {
err = add_ino(c, inum, new_size, 0, 1);
if (err)
return err;
}
}
break;
case UBIFS_DATA_KEY:
e = find_ino(c, inum);
if (e) {
if (new_size > e->d_size)
e->d_size = new_size;
} else {
err = add_ino(c, inum, 0, new_size, 0);
if (err)
return err;
}
break;
case UBIFS_TRUN_KEY:
e = find_ino(c, inum);
if (e)
e->d_size = new_size;
break;
}
return 0;
}
/**
* fix_size_in_place - fix inode size in place on flash.
* @c: UBIFS file-system description object
* @e: inode size information for recovery
*/
static int fix_size_in_place(struct ubifs_info *c, struct size_entry *e)
{
struct ubifs_ino_node *ino = c->sbuf;
unsigned char *p;
union ubifs_key key;
int err, lnum, offs, len;
loff_t i_size;
uint32_t crc;
/* Locate the inode node LEB number and offset */
ino_key_init(c, &key, e->inum);
err = ubifs_tnc_locate(c, &key, ino, &lnum, &offs);
if (err)
goto out;
/*
* If the size recorded on the inode node is greater than the size that
* was calculated from nodes in the journal then don't change the inode.
*/
i_size = le64_to_cpu(ino->size);
if (i_size >= e->d_size)
return 0;
/* Read the LEB */
err = ubifs_leb_read(c, lnum, c->sbuf, 0, c->leb_size, 1);
if (err)
goto out;
/* Change the size field and recalculate the CRC */
ino = c->sbuf + offs;
ino->size = cpu_to_le64(e->d_size);
len = le32_to_cpu(ino->ch.len);
crc = crc32(UBIFS_CRC32_INIT, (void *)ino + 8, len - 8);
ino->ch.crc = cpu_to_le32(crc);
/* Work out where data in the LEB ends and free space begins */
p = c->sbuf;
len = c->leb_size - 1;
while (p[len] == 0xff)
len -= 1;
len = ALIGN(len + 1, c->min_io_size);
/* Atomically write the fixed LEB back again */
err = ubifs_leb_change(c, lnum, c->sbuf, len);
if (err)
goto out;
dbg_rcvry("inode %lu at %d:%d size %lld -> %lld",
(unsigned long)e->inum, lnum, offs, i_size, e->d_size);
return 0;
out:
ubifs_warn("inode %lu failed to fix size %lld -> %lld error %d",
(unsigned long)e->inum, e->i_size, e->d_size, err);
return err;
}
/**
* ubifs_recover_size - recover inode size.
* @c: UBIFS file-system description object
*
* This function attempts to fix inode size discrepancies identified by the
* '<API key>()' function.
*
* This functions returns %0 on success and a negative error code on failure.
*/
int ubifs_recover_size(struct ubifs_info *c)
{
struct rb_node *this = rb_first(&c->size_tree);
while (this) {
struct size_entry *e;
int err;
e = rb_entry(this, struct size_entry, rb);
if (!e->exists) {
union ubifs_key key;
ino_key_init(c, &key, e->inum);
err = ubifs_tnc_lookup(c, &key, c->sbuf);
if (err && err != -ENOENT)
return err;
if (err == -ENOENT) {
/* Remove data nodes that have no inode */
dbg_rcvry("removing ino %lu",
(unsigned long)e->inum);
err = <API key>(c, e->inum);
if (err)
return err;
} else {
struct ubifs_ino_node *ino = c->sbuf;
e->exists = 1;
e->i_size = le64_to_cpu(ino->size);
}
}
if (e->exists && e->i_size < e->d_size) {
if (c->ro_mount) {
/* Fix the inode size and pin it in memory */
struct inode *inode;
struct ubifs_inode *ui;
ubifs_assert(!e->inode);
inode = ubifs_iget(c->vfs_sb, e->inum);
if (IS_ERR(inode))
return PTR_ERR(inode);
ui = ubifs_inode(inode);
if (inode->i_size < e->d_size) {
dbg_rcvry("ino %lu size %lld -> %lld",
(unsigned long)e->inum,
inode->i_size, e->d_size);
inode->i_size = e->d_size;
ui->ui_size = e->d_size;
ui->synced_i_size = e->d_size;
e->inode = inode;
this = rb_next(this);
continue;
}
iput(inode);
} else {
/* Fix the size in place */
err = fix_size_in_place(c, e);
if (err)
return err;
if (e->inode)
iput(e->inode);
}
}
this = rb_next(this);
rb_erase(&e->rb, &c->size_tree);
kfree(e);
}
return 0;
} |
'use strict';angular.module('mgcrea.ngStrap.modal').run(['$templateCache',function(t){t.put('modal/modal.tpl.html','<div class="modal" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header" ng-show="title"><button type="button" class="close" aria-label="Close" ng-click="$hide()"><span aria-hidden="true">×</span></button><h4 class="modal-title" ng-bind="title"></h4></div><div class="modal-body" ng-bind="content"></div><div class="modal-footer"><button type="button" class="btn btn-default" ng-click="$hide()">Close</button></div></div></div></div>')}]); |
<?php
class profile_define_menu extends profile_define_base {
function <API key>($form) {
Param 1 for menu type contains the options
$form->addElement('textarea', 'param1', get_string('profilemenuoptions', 'admin'), array('rows' => 6, 'cols' => 40));
$form->setType('param1', PARAM_TEXT);
Default data
$form->addElement('text', 'defaultdata', get_string('profiledefaultdata', 'admin'), 'size="50"');
$form->setType('defaultdata', PARAM_TEXT);
}
function <API key>($data, $files) {
$err = array();
$data->param1 = str_replace("\r", '', $data->param1);
Check that we have at least 2 options
if (($options = explode("\n", $data->param1)) === false) {
$err['param1'] = get_string('<API key>', 'admin');
} elseif (count($options) < 2) {
$err['param1'] = get_string('<API key>', 'admin');
Check the default data exists in the options
} elseif (!empty($data->defaultdata) and !in_array($data->defaultdata, $options)) {
$err['defaultdata'] = get_string('<API key>', 'admin');
}
return $err;
}
function <API key>($data) {
$data->param1 = str_replace("\r", '', $data->param1);
return $data;
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>jQuery UI Tabs - Vertical Tabs functionality</title>
<link type="text/css" href="../../themes/base/jquery.ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="../../jquery-1.4.2.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.tabs.js"></script>
<link type="text/css" href="../demos.css" rel="stylesheet" />
<script type="text/javascript">
$(function() {
$("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
$("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');
});
</script>
<style type="text/css">
.ui-tabs-vertical { width: 55em; }
.ui-tabs-vertical .ui-tabs-nav { padding: .2em .1em .2em .2em; float: left; width: 12em; }
.ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
.ui-tabs-vertical .ui-tabs-nav li a { display:block; }
.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-selected { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
.ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 40em;}
</style>
</head>
<body>
<div class="demo">
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<h2>Content heading 1</h2>
<p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
</div>
<div id="tabs-2">
<h2>Content heading 2</h2>
<p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
</div>
<div id="tabs-3">
<h2>Content heading 3</h2>
<p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
<p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
</div>
</div>
</div><!-- End demo -->
<div class="demo-description">
<p>Click tabs to swap between content that is broken into logical sections.</p>
</div><!-- End demo-description -->
</body>
</html> |
"""Test functions for matrix module
"""
from __future__ import division, absolute_import, print_function
from numpy.testing import (
TestCase, run_module_suite, assert_equal, assert_array_equal,
<API key>, <API key>, assert_raises, rand,
)
from numpy import (
arange, rot90, add, fliplr, flipud, zeros, ones, eye, array, diag,
histogram2d, tri, mask_indices, triu_indices, triu_indices_from,
tril_indices, tril_indices_from, vander,
)
import numpy as np
from numpy.compat import asbytes_nested
def get_mat(n):
data = arange(n)
data = add.outer(data, data)
return data
class TestEye(TestCase):
def test_basic(self):
assert_equal(eye(4),
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]))
assert_equal(eye(4, dtype='f'),
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]], 'f'))
assert_equal(eye(3) == 1,
eye(3, dtype=bool))
def test_diag(self):
assert_equal(eye(4, k=1),
array([[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]))
assert_equal(eye(4, k=-1),
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]]))
def test_2d(self):
assert_equal(eye(4, 3),
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]]))
assert_equal(eye(3, 4),
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]]))
def test_diag2d(self):
assert_equal(eye(3, 4, k=2),
array([[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]))
assert_equal(eye(4, 3, k=-2),
array([[0, 0, 0],
[0, 0, 0],
[1, 0, 0],
[0, 1, 0]]))
def test_eye_bounds(self):
assert_equal(eye(2, 2, 1), [[0, 1], [0, 0]])
assert_equal(eye(2, 2, -1), [[0, 0], [1, 0]])
assert_equal(eye(2, 2, 2), [[0, 0], [0, 0]])
assert_equal(eye(2, 2, -2), [[0, 0], [0, 0]])
assert_equal(eye(3, 2, 2), [[0, 0], [0, 0], [0, 0]])
assert_equal(eye(3, 2, 1), [[0, 1], [0, 0], [0, 0]])
assert_equal(eye(3, 2, -1), [[0, 0], [1, 0], [0, 1]])
assert_equal(eye(3, 2, -2), [[0, 0], [0, 0], [1, 0]])
assert_equal(eye(3, 2, -3), [[0, 0], [0, 0], [0, 0]])
def test_strings(self):
assert_equal(eye(2, 2, dtype='S3'),
asbytes_nested([['1', ''], ['', '1']]))
def test_bool(self):
assert_equal(eye(2, 2, dtype=bool), [[True, False], [False, True]])
class TestDiag(TestCase):
def test_vector(self):
vals = (100 * arange(5)).astype('l')
b = zeros((5, 5))
for k in range(5):
b[k, k] = vals[k]
assert_equal(diag(vals), b)
b = zeros((7, 7))
c = b.copy()
for k in range(5):
b[k, k + 2] = vals[k]
c[k + 2, k] = vals[k]
assert_equal(diag(vals, k=2), b)
assert_equal(diag(vals, k=-2), c)
def test_matrix(self, vals=None):
if vals is None:
vals = (100 * get_mat(5) + 1).astype('l')
b = zeros((5,))
for k in range(5):
b[k] = vals[k, k]
assert_equal(diag(vals), b)
b = b * 0
for k in range(3):
b[k] = vals[k, k + 2]
assert_equal(diag(vals, 2), b[:3])
for k in range(3):
b[k] = vals[k + 2, k]
assert_equal(diag(vals, -2), b[:3])
def test_fortran_order(self):
vals = array((100 * get_mat(5) + 1), order='F', dtype='l')
self.test_matrix(vals)
def test_diag_bounds(self):
A = [[1, 2], [3, 4], [5, 6]]
assert_equal(diag(A, k=2), [])
assert_equal(diag(A, k=1), [2])
assert_equal(diag(A, k=0), [1, 4])
assert_equal(diag(A, k=-1), [3, 6])
assert_equal(diag(A, k=-2), [5])
assert_equal(diag(A, k=-3), [])
def test_failure(self):
self.assertRaises(ValueError, diag, [[[1]]])
class TestFliplr(TestCase):
def test_basic(self):
self.assertRaises(ValueError, fliplr, ones(4))
a = get_mat(4)
b = a[:, ::-1]
assert_equal(fliplr(a), b)
a = [[0, 1, 2],
[3, 4, 5]]
b = [[2, 1, 0],
[5, 4, 3]]
assert_equal(fliplr(a), b)
class TestFlipud(TestCase):
def test_basic(self):
a = get_mat(4)
b = a[::-1, :]
assert_equal(flipud(a), b)
a = [[0, 1, 2],
[3, 4, 5]]
b = [[3, 4, 5],
[0, 1, 2]]
assert_equal(flipud(a), b)
class TestRot90(TestCase):
def test_basic(self):
self.assertRaises(ValueError, rot90, ones(4))
a = [[0, 1, 2],
[3, 4, 5]]
b1 = [[2, 5],
[1, 4],
[0, 3]]
b2 = [[5, 4, 3],
[2, 1, 0]]
b3 = [[3, 0],
[4, 1],
[5, 2]]
b4 = [[0, 1, 2],
[3, 4, 5]]
for k in range(-3, 13, 4):
assert_equal(rot90(a, k=k), b1)
for k in range(-2, 13, 4):
assert_equal(rot90(a, k=k), b2)
for k in range(-1, 13, 4):
assert_equal(rot90(a, k=k), b3)
for k in range(0, 13, 4):
assert_equal(rot90(a, k=k), b4)
def test_axes(self):
a = ones((50, 40, 3))
assert_equal(rot90(a).shape, (40, 50, 3))
class TestHistogram2d(TestCase):
def test_simple(self):
x = array(
[0.41702200, 0.72032449, 1.1437481e-4, 0.302332573, 0.146755891])
y = array(
[0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673])
xedges = np.linspace(0, 1, 10)
yedges = np.linspace(0, 1, 10)
H = histogram2d(x, y, (xedges, yedges))[0]
answer = array(
[[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
assert_array_equal(H.T, answer)
H = histogram2d(x, y, xedges)[0]
assert_array_equal(H.T, answer)
H, xedges, yedges = histogram2d(list(range(10)), list(range(10)))
assert_array_equal(H, eye(10, 10))
assert_array_equal(xedges, np.linspace(0, 9, 11))
assert_array_equal(yedges, np.linspace(0, 9, 11))
def test_asym(self):
x = array([1, 1, 2, 3, 4, 4, 4, 5])
y = array([1, 3, 2, 0, 1, 2, 3, 4])
H, xed, yed = histogram2d(
x, y, (6, 5), range=[[0, 6], [0, 5]], normed=True)
answer = array(
[[0., 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[1, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 1]])
<API key>(H, answer/8., 3)
assert_array_equal(xed, np.linspace(0, 6, 7))
assert_array_equal(yed, np.linspace(0, 5, 6))
def test_norm(self):
x = array([1, 2, 3, 1, 2, 3, 1, 2, 3])
y = array([1, 1, 1, 2, 2, 2, 3, 3, 3])
H, xed, yed = histogram2d(
x, y, [[1, 2, 3, 5], [1, 2, 3, 5]], normed=True)
answer = array([[1, 1, .5],
[1, 1, .5],
[.5, .5, .25]])/9.
<API key>(H, answer, 3)
def test_all_outliers(self):
r = rand(100) + 1. + 1e6 # histogramdd rounds by decimal=6
H, xed, yed = histogram2d(r, r, (4, 5), range=([0, 1], [0, 1]))
assert_array_equal(H, 0)
def test_empty(self):
a, edge1, edge2 = histogram2d([], [], bins=([0, 1], [0, 1]))
<API key>(a, array([[0.]]))
a, edge1, edge2 = histogram2d([], [], bins=4)
<API key>(a, np.zeros((4, 4)))
def <API key>(self):
x = array(
[0, 0.09207008, 0.64575234, 0.12875982, 0.47390599,
0.59944483, 1])
y = array(
[0, 0.14344267, 0.48988575, 0.30558665, 0.44700682,
0.15886423, 1])
edges = (0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)
H, xe, ye = histogram2d(x, y, (edges, 4))
answer = array(
[[ 2., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 1.]])
assert_array_equal(H, answer)
assert_array_equal(ye, array([0., 0.25, 0.5, 0.75, 1]))
H, xe, ye = histogram2d(x, y, (4, edges))
answer = array(
[[ 1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
assert_array_equal(H, answer)
assert_array_equal(xe, array([0., 0.25, 0.5, 0.75, 1]))
class TestTri(TestCase):
def test_dtype(self):
out = array([[1, 0, 0],
[1, 1, 0],
[1, 1, 1]])
assert_array_equal(tri(3), out)
assert_array_equal(tri(3, dtype=bool), out.astype(bool))
def <API key>():
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
a = np.ones((2, 2), dtype=dtype)
b = np.tril(a)
c = np.triu(a)
yield assert_array_equal, b, [[1, 0], [1, 1]]
yield assert_array_equal, c, b.T
# should return the same dtype as the original array
yield assert_equal, b.dtype, a.dtype
yield assert_equal, c.dtype, a.dtype
def <API key>():
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
a = np.array([
[[1, 1], [1, 1]],
[[1, 1], [1, 0]],
[[1, 1], [0, 0]],
], dtype=dtype)
a_tril_desired = np.array([
[[1, 0], [1, 1]],
[[1, 0], [1, 0]],
[[1, 0], [0, 0]],
], dtype=dtype)
a_triu_desired = np.array([
[[1, 1], [0, 1]],
[[1, 1], [0, 0]],
[[1, 1], [0, 0]],
], dtype=dtype)
a_triu_observed = np.triu(a)
a_tril_observed = np.tril(a)
yield assert_array_equal, a_triu_observed, a_triu_desired
yield assert_array_equal, a_tril_observed, a_tril_desired
yield assert_equal, a_triu_observed.dtype, a.dtype
yield assert_equal, a_tril_observed.dtype, a.dtype
def <API key>():
# Issue 4859
arr = np.array([[1, 1, np.inf],
[1, 1, 1],
[np.inf, 1, 1]])
out_tril = np.array([[1, 0, 0],
[1, 1, 0],
[np.inf, 1, 1]])
out_triu = out_tril.T
assert_array_equal(np.triu(arr), out_triu)
assert_array_equal(np.tril(arr), out_tril)
def <API key>():
# Issue 4916
# tril and triu should return the same dtype as input
for c in np.typecodes['All']:
if c == 'V':
continue
arr = np.zeros((3, 3), dtype=c)
assert_equal(np.triu(arr).dtype, arr.dtype)
assert_equal(np.tril(arr).dtype, arr.dtype)
# check special cases
arr = np.array([['2001-01-01T12:00', '2002-02-03T13:56'],
['2004-01-01T12:00', '2003-01-03T13:45']],
dtype='datetime64')
assert_equal(np.triu(arr).dtype, arr.dtype)
assert_equal(np.tril(arr).dtype, arr.dtype)
arr = np.zeros((3,3), dtype='f4,f4')
assert_equal(np.triu(arr).dtype, arr.dtype)
assert_equal(np.tril(arr).dtype, arr.dtype)
def test_mask_indices():
# simple test without offset
iu = mask_indices(3, np.triu)
a = np.arange(9).reshape(3, 3)
yield (assert_array_equal, a[iu], array([0, 1, 2, 4, 5, 8]))
# Now with an offset
iu1 = mask_indices(3, np.triu, 1)
yield (assert_array_equal, a[iu1], array([1, 2, 5]))
def test_tril_indices():
# indices without and with offset
il1 = tril_indices(4)
il2 = tril_indices(4, k=2)
il3 = tril_indices(4, m=5)
il4 = tril_indices(4, k=2, m=5)
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
b = np.arange(1, 21).reshape(4, 5)
# indexing:
yield (assert_array_equal, a[il1],
array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
yield (assert_array_equal, b[il3],
array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
# And for assigning values:
a[il1] = -1
yield (assert_array_equal, a,
array([[-1, 2, 3, 4],
[-1, -1, 7, 8],
[-1, -1, -1, 12],
[-1, -1, -1, -1]]))
b[il3] = -1
yield (assert_array_equal, b,
array([[-1, 2, 3, 4, 5],
[-1, -1, 8, 9, 10],
[-1, -1, -1, 14, 15],
[-1, -1, -1, -1, 20]]))
# These cover almost the whole array (two diagonals right of the main one):
a[il2] = -10
yield (assert_array_equal, a,
array([[-10, -10, -10, 4],
[-10, -10, -10, -10],
[-10, -10, -10, -10],
[-10, -10, -10, -10]]))
b[il4] = -10
yield (assert_array_equal, b,
array([[-10, -10, -10, 4, 5],
[-10, -10, -10, -10, 10],
[-10, -10, -10, -10, -10],
[-10, -10, -10, -10, -10]]))
class TestTriuIndices(object):
def test_triu_indices(self):
iu1 = triu_indices(4)
iu2 = triu_indices(4, k=2)
iu3 = triu_indices(4, m=5)
iu4 = triu_indices(4, k=2, m=5)
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
b = np.arange(1, 21).reshape(4, 5)
# Both for indexing:
yield (assert_array_equal, a[iu1],
array([1, 2, 3, 4, 6, 7, 8, 11, 12, 16]))
yield (assert_array_equal, b[iu3],
array([1, 2, 3, 4, 5, 7, 8, 9, 10, 13, 14, 15, 19, 20]))
# And for assigning values:
a[iu1] = -1
yield (assert_array_equal, a,
array([[-1, -1, -1, -1],
[5, -1, -1, -1],
[9, 10, -1, -1],
[13, 14, 15, -1]]))
b[iu3] = -1
yield (assert_array_equal, b,
array([[-1, -1, -1, -1, -1],
[6, -1, -1, -1, -1],
[11, 12, -1, -1, -1],
[16, 17, 18, -1, -1]]))
# These cover almost the whole array (two diagonals right of the
# main one):
a[iu2] = -10
yield (assert_array_equal, a,
array([[-1, -1, -10, -10],
[5, -1, -1, -10],
[9, 10, -1, -1],
[13, 14, 15, -1]]))
b[iu4] = -10
yield (assert_array_equal, b,
array([[-1, -1, -10, -10, -10],
[6, -1, -1, -10, -10],
[11, 12, -1, -1, -10],
[16, 17, 18, -1, -1]]))
class TestTrilIndicesFrom(object):
def test_exceptions(self):
assert_raises(ValueError, tril_indices_from, np.ones((2,)))
assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2)))
# assert_raises(ValueError, tril_indices_from, np.ones((2, 3)))
class TestTriuIndicesFrom(object):
def test_exceptions(self):
assert_raises(ValueError, triu_indices_from, np.ones((2,)))
assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2)))
# assert_raises(ValueError, triu_indices_from, np.ones((2, 3)))
class TestVander(object):
def test_basic(self):
c = np.array([0, 1, -2, 3])
v = vander(c)
powers = np.array([[0, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
[16, -8, 4, -2, 1],
[81, 27, 9, 3, 1]])
# Check default value of N:
yield (assert_array_equal, v, powers[:, 1:])
# Check a range of N values, including 0 and 5 (greater than default)
m = powers.shape[1]
for n in range(6):
v = vander(c, N=n)
yield (assert_array_equal, v, powers[:, m-n:m])
def test_dtypes(self):
c = array([11, -12, 13], dtype=np.int8)
v = vander(c)
expected = np.array([[121, 11, 1],
[144, -12, 1],
[169, 13, 1]])
yield (assert_array_equal, v, expected)
c = array([1.0+1j, 1.0-1j])
v = vander(c, N=3)
expected = np.array([[2j, 1+1j, 1],
[-2j, 1-1j, 1]])
# The data is floating point, but the values are small integers,
# so assert_array_equal *should* be safe here (rather than, say,
# <API key>).
yield (assert_array_equal, v, expected)
if __name__ == "__main__":
run_module_suite() |
#ifndef <API key>
#define <API key>
#include "base/threading/non_thread_safe.h"
#include "base/time/time.h"
#include "net/base/net_export.h"
namespace net {
// Provides the core logic needed for randomized exponential back-off
// on requests to a given resource, given a back-off policy.
// This utility class knows nothing about network specifics; it is
// intended for reuse in various networking scenarios.
class NET_EXPORT BackoffEntry : NON_EXPORTED_BASE(public base::NonThreadSafe) {
public:
// The set of parameters that define a back-off policy.
struct Policy {
// Number of initial errors (in sequence) to ignore before applying
// exponential back-off rules.
int <API key>;
// Initial delay. The interpretation of this value depends on
// <API key>. It's either how long we wait between
// requests before backoff starts, or how much we delay the first request
// after backoff starts.
int initial_delay_ms;
// Factor by which the waiting time will be multiplied.
double multiply_factor;
// Fuzzing percentage. ex: 10% will spread requests randomly
// between 90%-100% of the calculated time.
double jitter_factor;
// Maximum amount of time we are willing to delay our request, -1
// for no maximum.
int64 maximum_backoff_ms;
// Time to keep an entry from being discarded even when it
// has no significant state, -1 to never discard.
int64 entry_lifetime_ms;
// If true, we always use a delay of initial_delay_ms, even before
// we've seen <API key> errors. Otherwise, initial_delay_ms
// is the first delay once we start exponential backoff.
// So if we're ignoring 1 error, we'll see (N, N, Nm, Nm^2, ...) if true,
// and (0, 0, N, Nm, ...) when false, where N is initial_backoff_ms and
// m is multiply_factor, assuming we've already seen one success.
bool <API key>;
};
// Lifetime of policy must enclose lifetime of BackoffEntry. The
// pointer must be valid but is not dereferenced during construction.
explicit BackoffEntry(const Policy* const policy);
virtual ~BackoffEntry();
// Inform this item that a request for the network resource it is
// tracking was made, and whether it failed or succeeded.
void InformOfRequest(bool succeeded);
// Returns true if a request for the resource this item tracks should
// be rejected at the present time due to exponential back-off policy.
bool ShouldRejectRequest() const;
// Returns the absolute time after which this entry (given its present
// state) will no longer reject requests.
base::TimeTicks GetReleaseTime() const;
// Returns the time until a request can be sent.
base::TimeDelta GetTimeUntilRelease() const;
// Causes this object reject requests until the specified absolute time.
// This can be used to e.g. implement support for a Retry-After header.
void <API key>(const base::TimeTicks& release_time);
// Returns true if this object has no significant state (i.e. you could
// just as well start with a fresh BackoffEntry object), and hasn't
// had for Policy::entry_lifetime_ms.
bool CanDiscard() const;
// Resets this entry to a fresh (as if just constructed) state.
void Reset();
// Returns the failure count for this entry.
int failure_count() const { return failure_count_; }
protected:
// Equivalent to TimeTicks::Now(), virtual so unit tests can override.
virtual base::TimeTicks ImplGetTimeNow() const;
private:
// Calculates when requests should again be allowed through.
base::TimeTicks <API key>() const;
// Timestamp calculated by the exponential back-off algorithm at which we are
// allowed to start sending requests again.
base::TimeTicks <API key>;
// Counts request errors; decremented on success.
int failure_count_;
const Policy* const policy_;
<API key>(BackoffEntry);
};
} // namespace net
#endif // <API key> |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"ERANAMES": [
"avant J\u00e9sus-Christ",
"apr\u00e8s J\u00e9sus-Christ"
],
"ERAS": [
"av. J.-C.",
"ap. J.-C."
],
"FIRSTDAYOFWEEK": 5,
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"STANDALONEMONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "Fdj",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 0,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-dj",
"localeID": "fr_DJ",
"pluralCat": function(n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.