answer
stringlengths 15
1.25M
|
|---|
/*
* Functions related to sysfs handling
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/blktrace_api.h>
#include "blk.h"
struct queue_sysfs_entry {
struct attribute attr;
ssize_t (*show)(struct request_queue *, char *);
ssize_t (*store)(struct request_queue *, const char *, size_t);
};
static ssize_t
queue_var_show(unsigned long var, char *page)
{
return sprintf(page, "%lu\n", var);
}
static ssize_t
queue_var_store(unsigned long *var, const char *page, size_t count)
{
char *p = (char *) page;
*var = simple_strtoul(p, &p, 10);
return count;
}
static ssize_t queue_requests_show(struct request_queue *q, char *page)
{
return queue_var_show(q->nr_requests, (page));
}
static ssize_t
<API key>(struct request_queue *q, const char *page, size_t count)
{
struct request_list *rl = &q->rq;
unsigned long nr;
int ret;
if (!q->request_fn)
return -EINVAL;
ret = queue_var_store(&nr, page, count);
if (nr < BLKDEV_MIN_RQ)
nr = BLKDEV_MIN_RQ;
spin_lock_irq(q->queue_lock);
q->nr_requests = nr;
<API key>(q);
if (rl->count[BLK_RW_SYNC] >= <API key>(q))
<API key>(q, BLK_RW_SYNC);
else if (rl->count[BLK_RW_SYNC] < <API key>(q))
<API key>(q, BLK_RW_SYNC);
if (rl->count[BLK_RW_ASYNC] >= <API key>(q))
<API key>(q, BLK_RW_ASYNC);
else if (rl->count[BLK_RW_ASYNC] < <API key>(q))
<API key>(q, BLK_RW_ASYNC);
if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
blk_set_queue_full(q, BLK_RW_SYNC);
} else {
<API key>(q, BLK_RW_SYNC);
wake_up(&rl->wait[BLK_RW_SYNC]);
}
if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
blk_set_queue_full(q, BLK_RW_ASYNC);
} else {
<API key>(q, BLK_RW_ASYNC);
wake_up(&rl->wait[BLK_RW_ASYNC]);
}
spin_unlock_irq(q->queue_lock);
return ret;
}
static ssize_t queue_ra_show(struct request_queue *q, char *page)
{
unsigned long ra_kb = q->backing_dev_info.ra_pages <<
(PAGE_CACHE_SHIFT - 10);
return queue_var_show(ra_kb, (page));
}
static ssize_t
queue_ra_store(struct request_queue *q, const char *page, size_t count)
{
unsigned long ra_kb;
ssize_t ret = queue_var_store(&ra_kb, page, count);
q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10);
return ret;
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
int max_sectors_kb = queue_max_sectors(q) >> 1;
return queue_var_show(max_sectors_kb, (page));
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return queue_var_show(queue_max_segments(q), (page));
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return queue_var_show(q->limits.<API key>, (page));
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
if (blk_queue_cluster(q))
return queue_var_show(<API key>(q), (page));
return queue_var_show(PAGE_CACHE_SIZE, (page));
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return queue_var_show(<API key>(q), page);
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return queue_var_show(<API key>(q), page);
}
static ssize_t queue_io_min_show(struct request_queue *q, char *page)
{
return queue_var_show(queue_io_min(q), page);
}
static ssize_t queue_io_opt_show(struct request_queue *q, char *page)
{
return queue_var_show(queue_io_opt(q), page);
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return queue_var_show(q->limits.discard_granularity, page);
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return sprintf(page, "%llu\n",
(unsigned long long)q->limits.max_discard_sectors << 9);
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
return queue_var_show(<API key>(q), page);
}
static ssize_t
<API key>(struct request_queue *q, const char *page, size_t count)
{
unsigned long max_sectors_kb,
max_hw_sectors_kb = <API key>(q) >> 1,
page_kb = 1 << (PAGE_CACHE_SHIFT - 10);
ssize_t ret = queue_var_store(&max_sectors_kb, page, count);
if (max_sectors_kb > max_hw_sectors_kb || max_sectors_kb < page_kb)
return -EINVAL;
spin_lock_irq(q->queue_lock);
q->limits.max_sectors = max_sectors_kb << 1;
spin_unlock_irq(q->queue_lock);
return ret;
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
int max_hw_sectors_kb = <API key>(q) >> 1;
return queue_var_show(max_hw_sectors_kb, (page));
}
#define QUEUE_SYSFS_BIT_FNS(name, flag, neg) \
static ssize_t \
queue_show_##name(struct request_queue *q, char *page) \
{ \
int bit; \
bit = test_bit(QUEUE_FLAG_##flag, &q->queue_flags); \
return queue_var_show(neg ? !bit : bit, page); \
} \
static ssize_t \
queue_store_##name(struct request_queue *q, const char *page, size_t count) \
{ \
unsigned long val; \
ssize_t ret; \
ret = queue_var_store(&val, page, count); \
if (neg) \
val = !val; \
\
spin_lock_irq(q->queue_lock); \
if (val) \
queue_flag_set(QUEUE_FLAG_##flag, q); \
else \
queue_flag_clear(QUEUE_FLAG_##flag, q); \
spin_unlock_irq(q->queue_lock); \
return ret; \
}
QUEUE_SYSFS_BIT_FNS(nonrot, NONROT, 1);
QUEUE_SYSFS_BIT_FNS(random, ADD_RANDOM, 0);
QUEUE_SYSFS_BIT_FNS(iostats, IO_STAT, 0);
#undef QUEUE_SYSFS_BIT_FNS
static ssize_t queue_nomerges_show(struct request_queue *q, char *page)
{
return queue_var_show((blk_queue_nomerges(q) << 1) |
blk_queue_noxmerges(q), page);
}
static ssize_t <API key>(struct request_queue *q, const char *page,
size_t count)
{
unsigned long nm;
ssize_t ret = queue_var_store(&nm, page, count);
spin_lock_irq(q->queue_lock);
queue_flag_clear(QUEUE_FLAG_NOMERGES, q);
queue_flag_clear(<API key>, q);
if (nm == 2)
queue_flag_set(QUEUE_FLAG_NOMERGES, q);
else if (nm)
queue_flag_set(<API key>, q);
spin_unlock_irq(q->queue_lock);
return ret;
}
static ssize_t <API key>(struct request_queue *q, char *page)
{
bool set = test_bit(<API key>, &q->queue_flags);
bool force = test_bit(<API key>, &q->queue_flags);
return queue_var_show(set << force, page);
}
static ssize_t
<API key>(struct request_queue *q, const char *page, size_t count)
{
ssize_t ret = -EINVAL;
#if defined(<API key>)
unsigned long val;
ret = queue_var_store(&val, page, count);
spin_lock_irq(q->queue_lock);
if (val == 2) {
queue_flag_set(<API key>, q);
queue_flag_set(<API key>, q);
} else if (val == 1) {
queue_flag_set(<API key>, q);
queue_flag_clear(<API key>, q);
} else if (val == 0) {
queue_flag_clear(<API key>, q);
queue_flag_clear(<API key>, q);
}
spin_unlock_irq(q->queue_lock);
#endif
return ret;
}
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR },
.show = queue_requests_show,
.store = <API key>,
};
static struct queue_sysfs_entry queue_ra_entry = {
.attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR },
.show = queue_ra_show,
.store = queue_ra_store,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "max_sectors_kb", .mode = S_IRUGO | S_IWUSR },
.show = <API key>,
.store = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "max_hw_sectors_kb", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "max_segments", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "<API key>", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "max_segment_size", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry queue_iosched_entry = {
.attr = {.name = "scheduler",
.mode = S_IRUGO | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH },
.show = elv_iosched_show,
.store = elv_iosched_store,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "hw_sector_size", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "logical_block_size", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "physical_block_size", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry queue_io_min_entry = {
.attr = {.name = "minimum_io_size", .mode = S_IRUGO },
.show = queue_io_min_show,
};
static struct queue_sysfs_entry queue_io_opt_entry = {
.attr = {.name = "optimal_io_size", .mode = S_IRUGO },
.show = queue_io_opt_show,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "discard_granularity", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "discard_max_bytes", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "discard_zeroes_data", .mode = S_IRUGO },
.show = <API key>,
};
static struct queue_sysfs_entry queue_nonrot_entry = {
.attr = {.name = "rotational", .mode = S_IRUGO | S_IWUSR },
.show = queue_show_nonrot,
.store = queue_store_nonrot,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "nomerges", .mode = S_IRUGO | S_IWUSR },
.show = queue_nomerges_show,
.store = <API key>,
};
static struct queue_sysfs_entry <API key> = {
.attr = {.name = "rq_affinity", .mode = S_IRUGO | S_IWUSR },
.show = <API key>,
.store = <API key>,
};
static struct queue_sysfs_entry queue_iostats_entry = {
.attr = {.name = "iostats", .mode = S_IRUGO | S_IWUSR },
.show = queue_show_iostats,
.store = queue_store_iostats,
};
static struct queue_sysfs_entry queue_random_entry = {
.attr = {.name = "add_random", .mode = S_IRUGO | S_IWUSR },
.show = queue_show_random,
.store = queue_store_random,
};
static struct attribute *default_attrs[] = {
&<API key>.attr,
&queue_ra_entry.attr,
&<API key>.attr,
&<API key>.attr,
&<API key>.attr,
&<API key>.attr,
&<API key>.attr,
&queue_iosched_entry.attr,
&<API key>.attr,
&<API key>.attr,
&<API key>.attr,
&queue_io_min_entry.attr,
&queue_io_opt_entry.attr,
&<API key>.attr,
&<API key>.attr,
&<API key>.attr,
&queue_nonrot_entry.attr,
&<API key>.attr,
&<API key>.attr,
&queue_iostats_entry.attr,
&queue_random_entry.attr,
NULL,
};
#define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr)
static ssize_t
queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
{
struct queue_sysfs_entry *entry = to_queue(attr);
struct request_queue *q =
container_of(kobj, struct request_queue, kobj);
ssize_t res;
if (!entry->show)
return -EIO;
mutex_lock(&q->sysfs_lock);
if (blk_queue_dead(q)) {
mutex_unlock(&q->sysfs_lock);
return -ENOENT;
}
res = entry->show(q, page);
mutex_unlock(&q->sysfs_lock);
return res;
}
static ssize_t
queue_attr_store(struct kobject *kobj, struct attribute *attr,
const char *page, size_t length)
{
struct queue_sysfs_entry *entry = to_queue(attr);
struct request_queue *q;
ssize_t res;
if (!entry->store)
return -EIO;
q = container_of(kobj, struct request_queue, kobj);
mutex_lock(&q->sysfs_lock);
if (blk_queue_dead(q)) {
mutex_unlock(&q->sysfs_lock);
return -ENOENT;
}
res = entry->store(q, page, length);
mutex_unlock(&q->sysfs_lock);
return res;
}
/**
* blk_release_queue: - release a &struct request_queue when it is no longer needed
* @kobj: the kobj belonging to the request queue to be released
*
* Description:
* blk_release_queue is the pair to blk_init_queue() or
* <API key>(). It should be called when a request queue is
* being released; typically when a block device is being de-registered.
* Currently, its primary task it to free all the &struct request
* structures that were allocated to the queue and the queue itself.
*
* Caveat:
* Hopefully the low level driver will have finished any
* outstanding requests first...
**/
static void blk_release_queue(struct kobject *kobj)
{
struct request_queue *q =
container_of(kobj, struct request_queue, kobj);
struct request_list *rl = &q->rq;
blk_sync_queue(q);
if (q->elevator) {
spin_lock_irq(q->queue_lock);
ioc_clear_queue(q);
spin_unlock_irq(q->queue_lock);
elevator_exit(q->elevator);
}
blk_throtl_exit(q);
if (rl->rq_pool)
mempool_destroy(rl->rq_pool);
if (q->queue_tags)
<API key>(q);
blk_throtl_release(q);
blk_trace_shutdown(q);
bdi_destroy(&q->backing_dev_info);
ida_simple_remove(&blk_queue_ida, q->id);
kmem_cache_free(blk_requestq_cachep, q);
}
static const struct sysfs_ops queue_sysfs_ops = {
.show = queue_attr_show,
.store = queue_attr_store,
};
struct kobj_type blk_queue_ktype = {
.sysfs_ops = &queue_sysfs_ops,
.default_attrs = default_attrs,
.release = blk_release_queue,
};
int blk_register_queue(struct gendisk *disk)
{
int ret;
struct device *dev = disk_to_dev(disk);
struct request_queue *q = disk->queue;
if (WARN_ON(!q))
return -ENXIO;
ret = <API key>(dev);
if (ret)
return ret;
ret = kobject_add(&q->kobj, kobject_get(&dev->kobj), "%s", "queue");
if (ret < 0) {
<API key>(dev);
return ret;
}
kobject_uevent(&q->kobj, KOBJ_ADD);
if (!q->request_fn)
return 0;
ret = elv_register_queue(q);
if (ret) {
kobject_uevent(&q->kobj, KOBJ_REMOVE);
kobject_del(&q->kobj);
<API key>(dev);
kobject_put(&dev->kobj);
return ret;
}
return 0;
}
void <API key>(struct gendisk *disk)
{
struct request_queue *q = disk->queue;
if (WARN_ON(!q))
return;
if (q->request_fn)
<API key>(q);
kobject_uevent(&q->kobj, KOBJ_REMOVE);
kobject_del(&q->kobj);
<API key>(disk_to_dev(disk));
kobject_put(&disk_to_dev(disk)->kobj);
}
|
#include <linux/module.h>
static __init int opl_init(void)
{
return 0;
}
static void __exit opl_exit(void)
{
}
module_init(opl_init);
module_exit(opl_exit);
MODULE_AUTHOR("Freescale Semiconductor, Inc.");
MODULE_DESCRIPTION("OPL Software Rotation/Mirroring");
MODULE_LICENSE("GPL");
|
#include <linux/module.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/leds.h>
#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <linux/i2c/lp5521.h>
#define LP5521_DRIVER_NAME "lp5521"
#define LP5521_REG_R_PWM 0x02
#define LP5521_REG_B_PWM 0x04
#define LP5521_REG_ENABLE 0x00
#define LP5521_REG_OP_MODE 0x01
#define LP5521_REG_G_PWM 0x03
#define LP5521_REG_R_CNTRL 0x05
#define LP5521_REG_G_CNTRL 0x06
#define LP5521_REG_B_CNTRL 0x07
#define LP5521_REG_MISC 0x08
#define <API key> 0x09
#define <API key> 0x0a
#define <API key> 0x0b
#define LP5521_REG_STATUS 0x0c
#define LP5521_REG_RESET 0x0d
#define LP5521_REG_GPO 0x0e
#define <API key> 0x10
#define <API key> 0x30
#define <API key> 0x50
#define LP5521_CURRENT_1m5 0x0f
#define LP5521_CURRENT_3m1 0x1f
#define LP5521_CURRENT_4m7 0x2f
#define LP5521_CURRENT_6m3 0x3f
#define LP5521_CURRENT_7m9 0x4f
#define LP5521_CURRENT_9m5 0x5f
#define LP5521_CURRENT_11m1 0x6f
#define LP5521_CURRENT_12m7 0x7f
#define LP5521_CURRENT_14m3 0x8f
#define LP5521_CURRENT_15m9 0x9f
#define LP5521_CURRENT_17m5 0xaf
#define LP5521_CURRENT_19m1 0xbf
#define LP5521_CURRENT_20m7 0xcf
#define LP5521_CURRENT_22m3 0xdf
#define LP5521_CURRENT_23m9 0xef
#define LP5521_CURRENT_25m5 0xff
#define <API key> 32 /* in bytes */
struct lp5521_chip {
/* device lock */
struct mutex lock;
struct i2c_client *client;
struct work_struct red_work;
struct work_struct green_work;
struct work_struct blue_work;
struct led_classdev ledr;
struct led_classdev ledg;
struct led_classdev ledb;
enum lp5521_mode mode;
int red;
int green;
int blue;
};
static int lp5521_set_mode(struct lp5521_chip *chip, enum lp5521_mode mode);
static inline int lp5521_write(struct i2c_client *client, u8 reg, u8 value)
{
return <API key>(client, reg, value);
}
static inline int lp5521_read(struct i2c_client *client, u8 reg)
{
return <API key>(client, reg);
}
static int lp5521_configure(struct i2c_client *client)
{
int ret = 0;
/* Enable chip and set light to logarithmic mode*/
ret |= lp5521_write(client, LP5521_REG_ENABLE, 0xc0);
/* setting all color pwms to direct control mode */
ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x3f);
/* setting current to 4.7 mA for all channels */
ret |= lp5521_write(client, LP5521_REG_R_CNTRL, LP5521_CURRENT_4m7);
ret |= lp5521_write(client, LP5521_REG_G_CNTRL, LP5521_CURRENT_4m7);
ret |= lp5521_write(client, LP5521_REG_B_CNTRL, LP5521_CURRENT_4m7);
/* Enable auto-powersave, set charge pump to auto, red to battery */
ret |= lp5521_write(client, LP5521_REG_MISC, 0x3c);
/* initialize all channels pwm to zero */
ret |= lp5521_write(client, LP5521_REG_R_PWM, 0);
ret |= lp5521_write(client, LP5521_REG_G_PWM, 0);
ret |= lp5521_write(client, LP5521_REG_B_PWM, 0);
/* Not much can be done about errors at this point */
return ret;
}
static int lp5521_load_program(struct lp5521_chip *chip, u8 *pattern)
{
struct i2c_client *client = chip->client;
int ret = 0;
/* Enter load program mode for all led channels */
ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x15); /* 0001 0101 */
if (ret)
return ret;
if (chip->red)
ret |= <API key>(client,
<API key>,
<API key>,
pattern);
if (chip->green)
ret |= <API key>(client,
<API key>,
<API key>,
pattern);
if (chip->blue)
ret |= <API key>(client,
<API key>,
<API key>,
pattern);
return ret;
}
static int lp5521_run_program(struct lp5521_chip *chip)
{
struct i2c_client *client = chip->client;
int reg;
u8 mask = 0xc0;
u8 exec_state = 0;
reg = lp5521_read(client, LP5521_REG_ENABLE);
if (reg < 0)
return reg;
reg &= mask;
/* set all active channels exec state to countinous run*/
exec_state |= (chip->red << 5);
exec_state |= (chip->green << 3);
exec_state |= (chip->blue << 1);
reg |= exec_state;
if (lp5521_write(client, LP5521_REG_ENABLE, reg))
dev_dbg(&client->dev, "failed writing to register %02x\n",
LP5521_REG_ENABLE);
/* set op-mode to run for active channels, disabled for others */
if (lp5521_write(client, LP5521_REG_OP_MODE, exec_state))
dev_dbg(&client->dev, "failed writing to register %02x\n",
LP5521_REG_OP_MODE);
return 0;
}
/* Sysfs interface */
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct lp5521_chip *chip = dev_get_drvdata(dev);
char channels[4];
int pos = 0;
if (chip->red)
pos += sprintf(channels + pos, "r");
if (chip->green)
pos += sprintf(channels + pos, "g");
if (chip->blue)
pos += sprintf(channels + pos, "b");
channels[pos] = '\0';
return sprintf(buf, "%s\n", channels);
}
static ssize_t <API key>(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct lp5521_chip *chip = dev_get_drvdata(dev);
chip->red = 0;
chip->green = 0;
chip->blue = 0;
if (strchr(buf, 'r') != NULL)
chip->red = 1;
if (strchr(buf, 'b') != NULL)
chip->blue = 1;
if (strchr(buf, 'g') != NULL)
chip->green = 1;
return len;
}
static ssize_t show_color(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
int r, g, b;
r = lp5521_read(client, LP5521_REG_R_PWM);
g = lp5521_read(client, LP5521_REG_G_PWM);
b = lp5521_read(client, LP5521_REG_B_PWM);
if (r < 0 || g < 0 || b < 0)
return -EINVAL;
return sprintf(buf, "%.2x:%.2x:%.2x\n", r, g, b);
}
static ssize_t store_color(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5521_chip *chip = i2c_get_clientdata(client);
int ret;
unsigned r, g, b;
ret = sscanf(buf, "%2x:%2x:%2x", &r, &g, &b);
if (ret != 3)
return -EINVAL;
mutex_lock(&chip->lock);
ret = lp5521_write(client, LP5521_REG_R_PWM, (u8)r);
ret = lp5521_write(client, LP5521_REG_G_PWM, (u8)g);
ret = lp5521_write(client, LP5521_REG_B_PWM, (u8)b);
mutex_unlock(&chip->lock);
return len;
}
static ssize_t store_load(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct lp5521_chip *chip = dev_get_drvdata(dev);
int ret, nrchars, offset = 0, i = 0;
char c[3];
unsigned cmd;
u8 pattern[<API key>] = {0};
while ((offset < len - 1) && (i < <API key>)) {
/* separate sscanfs because length is working only for %s */
ret = sscanf(buf + offset, "%2s%n ", c, &nrchars);
ret = sscanf(c, "%2x", &cmd);
if (ret != 1)
goto fail;
pattern[i] = (u8)cmd;
offset += nrchars;
i++;
}
/* pattern commands are always two bytes long */
if (i % 2)
goto fail;
mutex_lock(&chip->lock);
ret = lp5521_load_program(chip, pattern);
mutex_unlock(&chip->lock);
if (ret) {
dev_err(dev, "lp5521 failed loading pattern\n");
return ret;
}
return len;
fail:
dev_err(dev, "lp5521 wrong pattern format\n");
return -EINVAL;
}
static ssize_t show_mode(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct lp5521_chip *chip = dev_get_drvdata(dev);
char *mode;
mutex_lock(&chip->lock);
switch (chip->mode) {
case LP5521_MODE_RUN:
mode = "run";
break;
case LP5521_MODE_LOAD:
mode = "load";
break;
case <API key>:
mode = "direct";
break;
default:
mode = "undefined";
}
mutex_unlock(&chip->lock);
return sprintf(buf, "%s\n", mode);
}
static ssize_t store_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct lp5521_chip *chip = dev_get_drvdata(dev);
mutex_lock(&chip->lock);
if (sysfs_streq(buf, "run"))
lp5521_set_mode(chip, LP5521_MODE_RUN);
else if (sysfs_streq(buf, "load"))
lp5521_set_mode(chip, LP5521_MODE_LOAD);
else if (sysfs_streq(buf, "direct"))
lp5521_set_mode(chip, <API key>);
else
len = -EINVAL;
mutex_unlock(&chip->lock);
return len;
}
static ssize_t show_current(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
int r, g, b;
r = lp5521_read(client, LP5521_REG_R_CNTRL);
g = lp5521_read(client, LP5521_REG_G_CNTRL);
b = lp5521_read(client, LP5521_REG_B_CNTRL);
if (r < 0 || g < 0 || b < 0)
return -EINVAL;
r >>= 4;
g >>= 4;
b >>= 4;
return sprintf(buf, "%x %x %x\n", r, g, b);
}
static ssize_t store_current(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct lp5521_chip *chip = dev_get_drvdata(dev);
struct i2c_client *client = chip->client;
int ret;
unsigned curr;
ret = sscanf(buf, "%1x", &curr);
if (ret != 1)
return -EINVAL;
/* current level is determined by the 4 upper bits, rest is ones */
curr = (curr << 4) | 0x0f;
mutex_lock(&chip->lock);
ret |= lp5521_write(client, LP5521_REG_R_CNTRL, (u8)curr);
ret |= lp5521_write(client, LP5521_REG_G_CNTRL, (u8)curr);
ret |= lp5521_write(client, LP5521_REG_B_CNTRL, (u8)curr);
mutex_unlock(&chip->lock);
return len;
}
static DEVICE_ATTR(color, S_IRUGO | S_IWUGO, show_color, store_color);
static DEVICE_ATTR(load, S_IWUGO, NULL, store_load);
static DEVICE_ATTR(mode, S_IRUGO | S_IWUGO, show_mode, store_mode);
static DEVICE_ATTR(active_channels, S_IRUGO | S_IWUGO,
<API key>, <API key>);
static DEVICE_ATTR(led_current, S_IRUGO | S_IWUGO, show_current, store_current);
static int <API key>(struct i2c_client *client)
{
struct device *dev = &client->dev;
int ret;
ret = device_create_file(dev, &dev_attr_color);
if (ret)
goto fail1;
ret = device_create_file(dev, &dev_attr_load);
if (ret)
goto fail2;
ret = device_create_file(dev, &<API key>);
if (ret)
goto fail3;
ret = device_create_file(dev, &dev_attr_mode);
if (ret)
goto fail4;
ret = device_create_file(dev, &<API key>);
if (ret)
goto fail5;
return 0;
fail5:
device_remove_file(dev, &dev_attr_mode);
fail4:
device_remove_file(dev, &<API key>);
fail3:
device_remove_file(dev, &dev_attr_load);
fail2:
device_remove_file(dev, &dev_attr_color);
fail1:
return ret;
}
static void <API key>(struct i2c_client *client)
{
struct device *dev = &client->dev;
device_remove_file(dev, &<API key>);
device_remove_file(dev, &dev_attr_mode);
device_remove_file(dev, &<API key>);
device_remove_file(dev, &dev_attr_color);
device_remove_file(dev, &dev_attr_load);
}
/* Set chip operating mode */
static int lp5521_set_mode(struct lp5521_chip *chip, enum lp5521_mode mode)
{
struct i2c_client *client = chip->client ;
int ret = 0;
/* if in that mode already do nothing, except for run */
if (chip->mode == mode && mode != LP5521_MODE_RUN)
return 0;
switch (mode) {
case LP5521_MODE_RUN:
ret = lp5521_run_program(chip);
break;
case LP5521_MODE_LOAD:
ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x15);
break;
case <API key>:
ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x3F);
break;
default:
dev_dbg(&client->dev, "unsupported mode %d\n", mode);
}
chip->mode = mode;
return ret;
}
static void lp5521_red_work(struct work_struct *work)
{
struct lp5521_chip *chip = container_of(work, struct lp5521_chip, red_work);
int ret;
ret = lp5521_configure(chip->client);
if (ret) {
dev_dbg(&chip->client->dev, "could not configure lp5521, %d\n",
ret);
return;
}
ret = lp5521_write(chip->client, LP5521_REG_R_PWM, chip->red);
if (ret)
dev_dbg(&chip->client->dev, "could not set brightness, %d\n",
ret);
}
static void lp5521_red_set(struct led_classdev *led,
enum led_brightness value)
{
struct lp5521_chip *chip = container_of(led, struct lp5521_chip, ledr);
chip->red = value;
schedule_work(&chip->red_work);
}
static void lp5521_green_work(struct work_struct *work)
{
struct lp5521_chip *chip = container_of(work, struct lp5521_chip, green_work);
int ret;
ret = lp5521_configure(chip->client);
if (ret) {
dev_dbg(&chip->client->dev, "could not configure lp5521, %d\n",
ret);
return;
}
ret = lp5521_write(chip->client, LP5521_REG_G_PWM, chip->green);
if (ret)
dev_dbg(&chip->client->dev, "could not set brightness, %d\n",
ret);
}
static void lp5521_green_set(struct led_classdev *led,
enum led_brightness value)
{
struct lp5521_chip *chip = container_of(led, struct lp5521_chip, ledg);
chip->green = value;
schedule_work(&chip->green_work);
}
static void lp5521_blue_work(struct work_struct *work)
{
struct lp5521_chip *chip = container_of(work, struct lp5521_chip, blue_work);
int ret;
ret = lp5521_configure(chip->client);
if (ret) {
dev_dbg(&chip->client->dev, "could not configure lp5521, %d\n",
ret);
return;
}
ret = lp5521_write(chip->client, LP5521_REG_B_PWM, chip->blue);
if (ret)
dev_dbg(&chip->client->dev, "could not set brightness, %d\n",
ret);
}
static void lp5521_blue_set(struct led_classdev *led,
enum led_brightness value)
{
struct lp5521_chip *chip = container_of(led, struct lp5521_chip, ledb);
chip->blue = value;
schedule_work(&chip->blue_work);
}
/* Probe, Attach, Remove */
static int __init lp5521_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct <API key> *pdata = client->dev.platform_data;
struct lp5521_chip *chip;
char name[16];
int ret = 0;
if (!pdata) {
dev_err(&client->dev, "platform_data is missing\n");
return -EINVAL;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
chip->client = client;
strncpy(client->name, LP5521_DRIVER_NAME, I2C_NAME_SIZE);
i2c_set_clientdata(client, chip);
mutex_init(&chip->lock);
INIT_WORK(&chip->red_work, lp5521_red_work);
INIT_WORK(&chip->green_work, lp5521_green_work);
INIT_WORK(&chip->blue_work, lp5521_blue_work);
ret = lp5521_configure(client);
if (ret < 0) {
dev_err(&client->dev, "lp5521 error configuring chip \n");
goto fail1;
}
/* Set default values */
chip->mode = pdata->mode;
chip->red = pdata->red_present;
chip->green = pdata->green_present;
chip->blue = pdata->blue_present;
chip->ledr.brightness_set = lp5521_red_set;
chip->ledr.default_trigger = NULL;
snprintf(name, sizeof(name), "%s::red", pdata->label);
chip->ledr.name = name;
ret = <API key>(&client->dev, &chip->ledr);
if (ret < 0) {
dev_dbg(&client->dev, "failed to register led %s, %d\n",
chip->ledb.name, ret);
goto fail1;
}
chip->ledg.brightness_set = lp5521_green_set;
chip->ledg.default_trigger = NULL;
snprintf(name, sizeof(name), "%s::green", pdata->label);
chip->ledg.name = name;
ret = <API key>(&client->dev, &chip->ledg);
if (ret < 0) {
dev_dbg(&client->dev, "failed to register led %s, %d\n",
chip->ledb.name, ret);
goto fail2;
}
chip->ledb.brightness_set = lp5521_blue_set;
chip->ledb.default_trigger = NULL;
snprintf(name, sizeof(name), "%s::blue", pdata->label);
chip->ledb.name = name;
ret = <API key>(&client->dev, &chip->ledb);
if (ret < 0) {
dev_dbg(&client->dev, "failed to register led %s, %d\n", chip->ledb.name, ret);
goto fail3;
}
ret = <API key>(client);
if (ret) {
dev_err(&client->dev, "lp5521 registering sysfs failed \n");
goto fail4;
}
return 0;
fail4:
<API key>(&chip->ledb);
fail3:
<API key>(&chip->ledg);
fail2:
<API key>(&chip->ledr);
fail1:
i2c_set_clientdata(client, NULL);
kfree(chip);
return ret;
}
static int __exit lp5521_remove(struct i2c_client *client)
{
struct lp5521_chip *chip = i2c_get_clientdata(client);
<API key>(client);
i2c_set_clientdata(client, NULL);
<API key>(&chip->ledb);
<API key>(&chip->ledg);
<API key>(&chip->ledr);
kfree(chip);
return 0;
}
static const struct i2c_device_id lp5521_id[] = {
{ LP5521_DRIVER_NAME, 0},
{ },
};
MODULE_DEVICE_TABLE(i2c, lp5521_id);
static struct i2c_driver lp5521_driver = {
.driver = {
.name = LP5521_DRIVER_NAME,
},
.probe = lp5521_probe,
.remove = __exit_p(lp5521_remove),
.id_table = lp5521_id,
};
static int __init lp5521_init(void)
{
return i2c_add_driver(&lp5521_driver);
}
module_init(lp5521_init);
static void __exit lp5521_exit(void)
{
i2c_del_driver(&lp5521_driver);
}
module_exit(lp5521_exit);
MODULE_AUTHOR("Mathias Nyman <mathias.nyman@nokia.com>");
MODULE_DESCRIPTION("lp5521 LED driver");
MODULE_LICENSE("GPL");
|
<html>
<body>
<span>
This intention used to specify type for expression in docstring.
</span>
</body>
</html>
|
var fs = require('fs');
var path = require('path');
var fis = require('../lib/fis.js');
var _ = fis.file;
var defaultSettings = (require('../lib/config.js')).DEFALUT_SETTINGS;
var expect = require('chai').expect;
var u = fis.util;
var config = null;
describe('config: config',function(){
beforeEach(function(){
fis.project.setProjectRoot(__dirname);
fis.config.init(defaultSettings);
process.env.NODE_ENV = 'dev';
});
it('set / get', function () {
fis.set('namespace', 'common');
expect(fis.get('namespace')).to.equal('common');
fis.set('obj', {a:'a'});
fis.set('obj.b', 'b');
expect(fis.get('obj')).to.deep.equal({a:'a', b:'b'});
expect(fis.get('obj.c', {c: 'c'})).to.deep.equal({c:'c'});
expect(fis.get('obj.a')).to.equal('a');
expect(fis.get('obj.b')).to.equal('b');
});
it('media', function () {
fis.set('a', 'a');
fis.set('b', 'b');
fis.media('prod').set('a', 'aa');
expect(fis.get('a')).to.equal('a');
expect(fis.media('prod').get('a')).to.equal('aa');
expect(fis.media('prod').get('b')).to.equal('b');
expect(fis.media('prod').get('project.charset')).to.equal('utf8');
});
it('fis.match',function(){
fis.match('**', {
release: 'static/$&'
}); // fis.config.match
fis.match('**/js.js', {
domain: 'www.baidu.com',
useHash: false
}, 1);
path = __dirname+'/file/ext/modular/js.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline');
//without domain
// useDomain
fis.match('**/js.js', {
useDomain: false
}, 2);
path = __dirname+'/file/ext/modular/js.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline');
fis.match('**/js.js', {
release: null
}, 3);
//without path
path = __dirname+'/file/ext/modular/js.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline');
// with ()
fis.match('**/v1.0-(*)/(*).html', {
release: '/$1/$2'
});
path = __dirname+'/file/ext/v1.0-layout/test.html?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('/layout/test.html?__inline');
fis.match('!**/js.js', {
release: '/static/$&',
useHash: true,
domain: 'www.baidu.com'
});
//with !
path = __dirname+'/file/ext/modular/js.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline');
// with ! but not match
path = __dirname+'/file/ext/modular/js.less?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('www.baidu.com/static/file/ext/modular/js_'+ f.getHash() +'.less?__inline');
});
it('match ${}', function() {
fis.match('**/*.js', {
release: null,
useHash: false
})
fis.set('coffee', 'js');
fis.match('**/js.js', {
release: '/static/$&'
});
path = __dirname+'/file/ext/modular/js.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('/static/file/ext/modular/js.js?__inline');
path = __dirname+'/file/ext/modular/j.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('/file/ext/modular/j.js?__inline');
});
it('match ', function() {
fis.set('ROOT', 'js');
fis.match('**', {
useHash: false
});
fis.match('(**/${ROOT}.js)', {
release: '/static/js/$1'
});
fis.match('(**/${ROOT}.less)', {
release: '/static/js/$1'
});
path = __dirname+'/file/ext/modular/js.js?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('/static/js/file/ext/modular/js.js?__inline');
path = __dirname+'/file/ext/modular/js.less?__inline';
var f = _.wrap(path);
var url = f.getUrl();
expect(url).to.equal('/static/js/file/ext/modular/js.less?__inline');
});
it('del', function(){
fis.config.del();
var origin = fis.config.get();
fis.set('a.b', 'b');
fis.media('pro').set('a.b', 'b');
fis.config.del('a.b');
expect(fis.get('a')).to.deep.equal({});
expect(fis.media('pro').get('a.b')).to.equal('b');
fis.config.del('a');
expect(fis.get()).to.deep.equal(origin);
fis.media('pro').del('a');
expect(fis.media('pro').get()).to.deep.equal({});
});
it('getSortedMatches', function() {
fis.media('prod').match('a', {
name: ''
});
var matches = fis.media('prod')._matches.concat();
var initIndex = matches[matches.length - 1].index;
fis.match('b', {
name: ''
}, 1)
fis.match('c', {
name: ''
}, 2)
fis.media('prod').match('b', {
name: 'prod'
}, 1)
fis.media('prod').match('c', {
name: 'prod'
}, 2);
var result_gl = [
{
raw: 'b',
reg: u.glob('b'),
negate: false,
properties: {name: ''},
media: 'GLOBAL',
weight: 1,
index: initIndex + 1
},
{
raw: 'c',
reg: u.glob('c'),
negate: false,
properties: {name: ''},
media: 'GLOBAL',
weight: 2,
index: initIndex + 2
}
], result_prod = [
{
raw: 'a',
reg: u.glob('a'),
negate: false,
properties: {name: ''},
media: 'prod',
weight: 0,
index: initIndex + 0
},
{
raw: 'b',
reg: u.glob('b'),
negate: false,
properties: {name: ''},
media: 'GLOBAL',
weight: 1,
index: initIndex + 1
},
{
raw: 'b',
reg: u.glob('b'),
negate: false,
properties: {name: 'prod'},
media: 'prod',
weight: 1,
index: initIndex + 3
},
{
raw: 'c',
reg: u.glob('c'),
negate: false,
properties: {name: ''},
media: 'GLOBAL',
weight: 2,
index: initIndex + 2
},
{
raw: 'c',
reg: u.glob('c'),
negate: false,
properties: {name: 'prod'},
media: 'prod',
weight: 2,
index: initIndex + 4
},
];
var xp = fis.config.getSortedMatches();
expect(xp).to.deep.equal(result_gl);
var xp2 = fis.media('prod').getSortedMatches();
expect(xp2).to.deep.equal(result_prod);
});
it("hook",function(){
fis.config.hook("module");
expect(fis.env().parent.data.modules.hook[1]['__plugin']).to.equal('module');
});
it("unhook",function(){
fis.config.unhook("module");
expect(fis.env().parent.data.modules.hook.length).to.equal(1);
});
});
|
#ifndef <API key>
#define <API key>
#include <string>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/port.h"
#include "base/strings/string_piece.h"
#include "net/base/int128.h"
#include "net/base/net_export.h"
#include "net/quic/quic_protocol.h"
namespace net {
// This class provides facilities for packing QUIC data.
// The QuicDataWriter supports appending primitive values (int, string, etc)
// to a frame instance. The QuicDataWriter grows its internal memory buffer
// dynamically to hold the sequence of primitive values. The internal memory
// buffer is exposed as the "data" of the QuicDataWriter.
class NET_EXPORT_PRIVATE QuicDataWriter {
public:
explicit QuicDataWriter(size_t length);
~QuicDataWriter();
// Returns the size of the QuicDataWriter's data.
size_t length() const { return length_; }
// Takes the buffer from the QuicDataWriter.
char* take();
// Methods for adding to the payload. These values are appended to the end
// of the QuicDataWriter payload. Note - binary integers are written in
// host byte order (little endian) not network byte order (big endian).
bool WriteUInt8(uint8 value);
bool WriteUInt16(uint16 value);
bool WriteUInt32(uint32 value);
bool WriteUInt48(uint64 value);
bool WriteUInt64(uint64 value);
bool WriteUInt128(uint128 value);
bool WriteStringPiece16(base::StringPiece val);
bool WriteBytes(const void* data, size_t data_len);
bool WriteRepeatedByte(uint8 byte, size_t count);
// Fills the remaining buffer with null characters.
void WritePadding();
// Methods for editing the payload at a specific offset, where the
// offset must be within the writer's capacity.
// Return true if there is enough space at that offset, false otherwise.
bool WriteUInt8ToOffset(uint8 value, size_t offset);
bool WriteUInt32ToOffset(uint32 value, size_t offset);
bool WriteUInt48ToOffset(uint64 value, size_t offset);
size_t capacity() const {
return capacity_;
}
protected:
const char* end_of_payload() const { return buffer_ + length_; }
private:
// Returns the location that the data should be written at, or NULL if there
// is not enough room. Call EndWrite with the returned offset and the given
// length to pad out for the next write.
char* BeginWrite(size_t length);
char* buffer_;
size_t capacity_; // Allocation size of payload (or -1 if buffer is const).
size_t length_; // Current length of the buffer.
};
} // namespace net
#endif // <API key>
|
h1, h2, h3, h4, h5 { font-weight: bold; }
p, ol, ul, dl { margin: 0; }
h1 {
position: relative; z-index: 800;
margin: 26px 0 10px;
font-size: 16px; line-height: 20px;
}
.pretitle + h1 {
margin-top: 0;
}
h2 { font-size: 16px; }
h3 { font-size: 14px; }
h4 { font-size: 12px; }
h5 { font-size: 10px; }
a {
text-decoration: none;
outline: none;
}
a:link, a:visited { color: #309bbf; }
a:hover, a:active { color: #444; }
a.inverse:link, a.inverse:visited { color: #444 !important; }
a.inverse:hover, a.inverse:active { color: #309bbf !important; }
/* Images in Links ........................................... */
a img {
border: none;
outline: none;
}
a:link img.preview, a:visited img.preview {
margin-top: 5px; padding: 5px;
border: 1px solid #309bbf;
-moz-border-radius: 3px; -<API key>: 3px; border-radius: 3px;
background: #fff;
}
a:hover img.preview, a:active img.preview {
border-color: #666;
}
/* Section ........................................... */
a.section:link, a.section:visited { color: #fff; }
/* Pretitle ........................................... */
.pretitle {
margin: -16px 0 0;
}
.pretitle a {
font-size: 11px; line-height: 15px; font-weight: bold;
}
a.addlink, a.changelink, a.deletelink,
a.add-another, a.related-lookup,
a.fb_show {
background-repeat: no-repeat;
background-color: transparent;
}
/* Hide Images in Templates ........................................... */
a.add-another img, a.related-lookup img { opacity: 0; }
a.related-lookup img { display: none; }
/* Add, Change, Delete, Add-Another ........................................... */
a.addlink, a.changelink, a.deletelink {
position: relative; top: 0;
margin: 0 0 -1px 10px; padding: 1px 0 0 14px;
background-position: 0 50%;
}
a.addlink:link, a.addlink:visited {
background-image: url('../img/icons/icon-addlink.png');
}
a.addlink:hover, a.addlink:active {
background-image: url('../img/icons/icon-addlink-hover.png');
}
a.changelink:link, a.changelink:visited {
background-image: url('../img/icons/icon-changelink.png');
}
a.changelink:hover, a.changelink:active {
background-image: url('../img/icons/<API key>.png');
}
a.deletelink { margin: 0; }
a.add-another {
position: relative; top: -2px;
margin-left: 3px;
vertical-align: top;
font-size: 11px; line-height: 16px;
background-position: 50% 50%;
}
a.add-another:link, a.add-another:visited {
background-image: url('../img/icons/icon-add_another.png');
}
a.add-another:hover, a.add-another:active {
background-image: url('../img/icons/<API key>.png');
}
.change-list form table tbody td a.add-another, .change-list form table tbody th a.add-another {
position: relative; top: -7px;
}
.radiolist.inline + a.add-another, .checkboxlist.inline + a.add-another {
margin-left: -4px;
}
.<API key> + a.add-another,
.<API key> + a.add-another {
/*margin-left: -8px;*/
}
#changelist .result-list .<API key> + a.add-another,
#changelist .result-list .<API key> + a.add-another {
/*margin-left: -9px;*/
}
/* Related Lookup ........................................... */
a.related-lookup {
background-position: 5px 5px;
}
a.related-lookup:link, a.related-lookup:visited {
position: relative; top: 1px;
padding: 6px 12px 5px;
line-height: 0 !important;
background-image: url('../img/icons/icon-related_lookup.png');
}
a.related-lookup:hover, a.related-lookup:active {
background-image: url('../img/icons/<API key>.png');
}
a.related-lookup + strong {
position: relative; top: 1px; left: -6px;
color: #555; font-size: 11px; font-weight: bold;
}
#changelist .result-list a.related-lookup {
top: -1px;
}
/* Filebrowser ........................................... */
a.fb_show img {
width: 0; height: 0;
opacity: 0;
}
a.fb_show {
background-position: 2px 3px;
}
a.fb_show:link, a.fb_show:visited {
position: relative;
padding: 7px 14px;
line-height: 0 !important;
border: none;
background-image: url('../img/icons/icon-fb_show.png');
}
a.fb_show:hover, a.fb_show:active {
background-image: url('../img/icons/icon-fb_show-hover.png');
}
p { padding: 0; }
h1 + p { margin: 0 0 15px; }
.object-history p {
padding: 5px 10px;
}
ul li { list-style-type: none; padding: 1px 0; }
ul.plainlist { margin-left: 0; }
ul.plainlist li { list-style-type: none; }
#content ul {
font-weight: bold;
}
#content p + ul,
#content ul + ul { margin: 0 0 15px; }
#content li ul {
margin: 5px 0 0 15px;
font-weight: normal;
}
dt {
font-weight: bold;
margin-top: 4px;
}
dd { margin-left: 0; }
blockquote {
margin-left: 2px; padding-left: 4px;
color: #777; font-size: 11px;
border-left: 5px solid #ddd;
}
code, pre {
color: #666; font-size: 11px; font-family: "Bitstream Vera Sans Mono", Monaco, "Courier New", Courier, monospace;
background: inherit;
}
pre.literal-block {
margin-top: 10px; padding: 6px 8px;
background: #eee;
}
code strong { color: #930; }
hr {
clear: both;
margin: 0; padding: 0;
height: 1px;
color: #eee; font-size: 1px; line-height: 1px;
border: none;
background-color: #eee;
}
.small { font-size: 11px; }
.tiny { font-size: 10px; }
p.tiny { margin-top: -2px; }
.mini { font-size: 9px; }
p.mini { margin-top: -3px; }
.help, p.help { color: #999; font-size: 10px; }
p img, h1 img, h2 img, h3 img, h4 img, td img { vertical-align: middle; }
.quiet, a.quiet:link, a.quiet:visited { color: #999 !important; font-weight: normal !important; }
.quiet strong { font-weight: bold !important; }
.float-right { float: right; }
.float-left { float: left; }
.clear { clear: both; }
.align-left { text-align: left; }
.align-right { text-align: right; }
.example {
margin: 10px 0; padding: 5px 10px;
background: #efefef;
}
.nowrap { white-space: nowrap; }
|
(function() {
var add, crispedges, feature, flexbox, fullscreen, gradients, logicalProps, prefix, readOnly, resolution, result, sort, writingMode,
slice = [].slice;
sort = function(array) {
return array.sort(function(a, b) {
var d;
a = a.split(' ');
b = b.split(' ');
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
d = parseFloat(a[1]) - parseFloat(b[1]);
if (d > 0) {
return 1;
} else if (d < 0) {
return -1;
} else {
return 0;
}
}
});
};
feature = function(data, opts, callback) {
var browser, match, need, ref, ref1, support, version, versions;
if (!callback) {
ref = [opts, {}], callback = ref[0], opts = ref[1];
}
match = opts.match || /\sx($|\s)/;
need = [];
ref1 = data.stats;
for (browser in ref1) {
versions = ref1[browser];
for (version in versions) {
support = versions[version];
if (support.match(match)) {
need.push(browser + ' ' + version);
}
}
}
return callback(sort(need));
};
result = {};
prefix = function() {
var data, i, j, k, len, name, names, results;
names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++];
results = [];
for (k = 0, len = names.length; k < len; k++) {
name = names[k];
result[name] = {};
results.push((function() {
var results1;
results1 = [];
for (i in data) {
results1.push(result[name][i] = data[i]);
}
return results1;
})());
}
return results;
};
add = function() {
var data, j, k, len, name, names, results;
names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++];
results = [];
for (k = 0, len = names.length; k < len; k++) {
name = names[k];
results.push(result[name].browsers = sort(result[name].browsers.concat(data.browsers)));
}
return results;
};
module.exports = result;
feature(require('caniuse-db/features-json/border-radius'), function(browsers) {
return prefix('border-radius', '<API key>', '<API key>', '<API key>', '<API key>', {
mistakes: ['-khtml-', '-ms-', '-o-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-boxshadow'), function(browsers) {
return prefix('box-shadow', {
mistakes: ['-khtml-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-animation'), function(browsers) {
return prefix('animation', 'animation-name', 'animation-duration', 'animation-delay', 'animation-direction', 'animation-fill-mode', '<API key>', '<API key>', '<API key>', '@keyframes', {
mistakes: ['-khtml-', '-ms-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-transitions'), function(browsers) {
return prefix('transition', 'transition-property', 'transition-duration', 'transition-delay', '<API key>', {
mistakes: ['-khtml-', '-ms-'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/transforms2d'), function(browsers) {
return prefix('transform', 'transform-origin', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/transforms3d'), function(browsers) {
prefix('perspective', 'perspective-origin', {
browsers: browsers
});
return prefix('transform-style', 'backface-visibility', {
mistakes: ['-ms-', '-o-'],
browsers: browsers
});
});
gradients = require('caniuse-db/features-json/css-gradients');
feature(gradients, {
match: /y\sx/
}, function(browsers) {
return prefix('linear-gradient', '<API key>', 'radial-gradient', '<API key>', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
mistakes: ['-ms-'],
browsers: browsers
});
});
feature(gradients, {
match: /a\sx/
}, function(browsers) {
browsers = browsers.map(function(i) {
if (/op/.test(i)) {
return i;
} else {
return i + " old";
}
});
return add('linear-gradient', '<API key>', 'radial-gradient', '<API key>', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-boxsizing'), function(browsers) {
return prefix('box-sizing', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-filters'), function(browsers) {
return prefix('filter', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-filter-function'), function(browsers) {
return prefix('filter-function', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-backdrop-filter'), function(browsers) {
return prefix('backdrop-filter', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/<API key>'), function(browsers) {
return prefix('element', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/multicolumn'), function(browsers) {
prefix('columns', 'column-width', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', {
browsers: browsers
});
return prefix('column-count', 'column-rule-style', 'column-span', 'column-fill', 'break-before', 'break-after', 'break-inside', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/user-select-none'), function(browsers) {
return prefix('user-select', {
mistakes: ['-khtml-'],
browsers: browsers
});
});
flexbox = require('caniuse-db/features-json/flexbox');
feature(flexbox, {
match: /a\sx/
}, function(browsers) {
browsers = browsers.map(function(i) {
if (/ie|firefox/.test(i)) {
return i;
} else {
return i + " 2009";
}
});
prefix('display-flex', 'inline-flex', {
props: ['display'],
browsers: browsers
});
prefix('flex', 'flex-grow', 'flex-shrink', 'flex-basis', {
browsers: browsers
});
return prefix('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', {
browsers: browsers
});
});
feature(flexbox, {
match: /y\sx/
}, function(browsers) {
add('display-flex', 'inline-flex', {
browsers: browsers
});
add('flex', 'flex-grow', 'flex-shrink', 'flex-basis', {
browsers: browsers
});
return add('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/calc'), function(browsers) {
return prefix('calc', {
props: ['*'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/background-img-opts'), function(browsers) {
return prefix('background-clip', 'background-origin', 'background-size', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/font-feature'), function(browsers) {
return prefix('<API key>', '<API key>', '<API key>', 'font-kerning', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/border-image'), function(browsers) {
return prefix('border-image', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-selection'), function(browsers) {
return prefix('::selection', {
selector: true,
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-placeholder'), function(browsers) {
browsers = browsers.map(function(i) {
var name, ref, version;
ref = i.split(' '), name = ref[0], version = ref[1];
if (name === 'firefox' && parseFloat(version) <= 18) {
return i + ' old';
} else {
return i;
}
});
return prefix('::placeholder', {
selector: true,
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-hyphens'), function(browsers) {
return prefix('hyphens', {
browsers: browsers
});
});
fullscreen = require('caniuse-db/features-json/fullscreen');
feature(fullscreen, function(browsers) {
return prefix(':fullscreen', {
selector: true,
browsers: browsers
});
});
feature(fullscreen, {
match: /x(\s
}, function(browsers) {
return prefix('::backdrop', {
selector: true,
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-tabsize'), function(browsers) {
return prefix('tab-size', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/intrinsic-width'), function(browsers) {
return prefix('max-content', 'min-content', 'fit-content', 'fill-available', {
props: ['width', 'min-width', 'max-width', 'height', 'min-height', 'max-height'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-cursors-newer'), function(browsers) {
return prefix('zoom-in', 'zoom-out', {
props: ['cursor'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css3-cursors-grab'), function(browsers) {
return prefix('grab', 'grabbing', {
props: ['cursor'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-sticky'), function(browsers) {
return prefix('sticky', {
props: ['position'],
browsers: browsers
});
});
feature(require('caniuse-db/features-json/pointer'), function(browsers) {
return prefix('touch-action', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-decoration'), function(browsers) {
return prefix('<API key>', '<API key>', '<API key>', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-size-adjust'), function(browsers) {
return prefix('text-size-adjust', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-masks'), function(browsers) {
prefix('mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-repeat', 'mask-border-repeat', 'mask-border-source', {
browsers: browsers
});
return prefix('clip-path', 'mask', 'mask-position', 'mask-size', 'mask-border', 'mask-border-outset', 'mask-border-width', 'mask-border-slice', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/<API key>'), function(brwsrs) {
return prefix('<API key>', {
browsers: brwsrs
});
});
feature(require('caniuse-db/features-json/object-fit'), function(browsers) {
return prefix('object-fit', 'object-position', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-shapes'), function(browsers) {
return prefix('shape-margin', 'shape-outside', '<API key>', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-overflow'), function(browsers) {
return prefix('text-overflow', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/text-emphasis'), function(browsers) {
return prefix('text-emphasis', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/<API key>'), function(browsers) {
return prefix('@viewport', {
browsers: browsers
});
});
resolution = require('caniuse-db/features-json/<API key>');
feature(resolution, {
match: /( x($| )|a
}, function(browsers) {
return prefix('@resolution', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-text-align-last'), function(browsers) {
return prefix('text-align-last', {
browsers: browsers
});
});
crispedges = require('caniuse-db/features-json/css-crisp-edges');
feature(crispedges, {
match: /y x/
}, function(browsers) {
return prefix('pixelated', {
props: ['image-rendering'],
browsers: browsers
});
});
feature(crispedges, {
match: /a x
}, function(browsers) {
return prefix('image-rendering', {
browsers: browsers
});
});
logicalProps = require('caniuse-db/features-json/css-logical-props');
feature(logicalProps, function(browsers) {
return prefix('border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', '<API key>', 'padding-inline-end', {
browsers: browsers
});
});
feature(logicalProps, {
match: /x\s
}, function(browsers) {
return prefix('border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-appearance'), function(browsers) {
return prefix('appearance', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-snappoints'), function(browsers) {
return prefix('scroll-snap-type', '<API key>', '<API key>', '<API key>', '<API key>', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-regions'), function(browsers) {
return prefix('flow-into', 'flow-from', 'region-fragment', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-image-set'), function(browsers) {
return prefix('image-set', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
writingMode = require('caniuse-db/features-json/css-writing-mode');
feature(writingMode, {
match: /a|x/
}, function(browsers) {
return prefix('writing-mode', {
browsers: browsers
});
});
feature(require('caniuse-db/features-json/css-cross-fade.json'), function(browsers) {
return prefix('cross-fade', {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
browsers: browsers
});
});
readOnly = require('caniuse-db/features-json/css-read-only-write.json');
feature(readOnly, function(browsers) {
return prefix(':read-only', ':read-write', {
selector: true,
browsers: browsers
});
});
}).call(this);
|
export interface IGridItem {
name: string;
}
export class Tests {
public items: <API key><IGridItem>;
public selectedItems: <API key><IGridItem>;
public gridOptionsAlarms: kg.GridOptions<IGridItem>;
constructor() {
this.items = ko.observableArray<IGridItem>();
this.selectedItems = ko.observableArray<IGridItem>();
this.gridOptionsAlarms = this.<API key>(this.items, this.selectedItems);
}
public <API key><Type>(dataArray: <API key><Type>, selectedItems: <API key><Type>): kg.GridOptions<Type> {
return {
data: dataArray,
<API key>: false,
footerVisible: false,
multiSelect: false,
showColumnMenu: false,
plugins: null,
selectedItems: selectedItems
};
}
}
|
<?php
namespace Symfony\Component\Serializer\Mapping;
/**
* Knows how to get the class discriminator mapping for classes and objects.
*
* @author Samuel Roze <samuel.roze@gmail.com>
*/
interface <API key>
{
/**
* @param string $class
*
* @return <API key>|null
*/
public function getMappingForClass(string $class): ?<API key>;
/**
* @param object|string $object
*
* @return <API key>|null
*/
public function <API key>($object): ?<API key>;
/**
* @param object|string $object
*
* @return string|null
*/
public function <API key>($object): ?string;
}
|
package sun.text.resources.sr;
import sun.util.resources.<API key>;
public class FormatData_sr_ME extends <API key> {
protected final Object[][] getContents() {
return new Object[][] {
};
}
}
|
/* @test
@summary Test <API key> getFormat method */
import javax.sound.midi.<API key>;
import javax.sound.midi.Patch;
import javax.sound.sampled.*;
import com.sun.media.sound.*;
public class GetFormat {
private static void assertEquals(Object a, Object b) throws Exception
{
if(!a.equals(b))
throw new RuntimeException("assertEquals fails!");
}
private static void assertTrue(boolean value) throws Exception
{
if(!value)
throw new RuntimeException("assertTrue fails!");
}
public static void main(String[] args) throws Exception {
AudioSynthesizer synth = new SoftSynthesizer();
AudioFormat defformat = synth.getFormat();
assertTrue(defformat != null);
synth.openStream(null, null);
assertTrue(synth.getFormat().toString().equals(defformat.toString()));
synth.close();
AudioFormat custformat = new AudioFormat(8000, 16, 1, true, false);
synth.openStream(custformat, null);
assertTrue(synth.getFormat().toString().equals(custformat.toString()));
synth.close();
}
}
|
package java.lang;
import java.io.DataInputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.zip.InflaterInputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
class CharacterName {
private static SoftReference<byte[]> refStrPool;
private static int[][] lookup;
private static synchronized byte[] initNamePool() {
byte[] strPool = null;
if (refStrPool != null && (strPool = refStrPool.get()) != null)
return strPool;
DataInputStream dis = null;
try {
dis = new DataInputStream(new InflaterInputStream(
AccessController.doPrivileged(new PrivilegedAction<InputStream>()
{
public InputStream run() {
return getClass().getResourceAsStream("uniName.dat");
}
})));
lookup = new int[(Character.MAX_CODE_POINT + 1) >> 8][];
int total = dis.readInt();
int cpEnd = dis.readInt();
byte ba[] = new byte[cpEnd];
dis.readFully(ba);
int nameOff = 0;
int cpOff = 0;
int cp = 0;
do {
int len = ba[cpOff++] & 0xff;
if (len == 0) {
len = ba[cpOff++] & 0xff;
// always big-endian
cp = ((ba[cpOff++] & 0xff) << 16) |
((ba[cpOff++] & 0xff) << 8) |
((ba[cpOff++] & 0xff));
} else {
cp++;
}
int hi = cp >> 8;
if (lookup[hi] == null) {
lookup[hi] = new int[0x100];
}
lookup[hi][cp&0xff] = (nameOff << 8) | len;
nameOff += len;
} while (cpOff < cpEnd);
strPool = new byte[total - cpEnd];
dis.readFully(strPool);
refStrPool = new SoftReference<>(strPool);
} catch (Exception x) {
throw new InternalError(x.getMessage(), x);
} finally {
try {
if (dis != null)
dis.close();
} catch (Exception xx) {}
}
return strPool;
}
public static String get(int cp) {
byte[] strPool = null;
if (refStrPool == null || (strPool = refStrPool.get()) == null)
strPool = initNamePool();
int off = 0;
if (lookup[cp>>8] == null ||
(off = lookup[cp>>8][cp&0xff]) == 0)
return null;
@SuppressWarnings("deprecation")
String result = new String(strPool, 0, off >>> 8, off & 0xff); // ASCII
return result;
}
}
|
#pragma once
#include "DolphinWX/Input/InputConfigDiag.h"
class <API key> final : public InputConfigDialog
{
public:
<API key>(wxWindow* parent, InputConfig& config, const wxString& name,
int port_num = 0);
};
|
'use strict';
var fs = require('fs');
var path = require('path');
var prettyBytes = require('pretty-bytes');
var chalk = require('chalk');
var zlib = require('zlib');
var archiver = require('archiver');
var streamBuffers = require('stream-buffers');
var _ = require('lodash');
module.exports = function(grunt) {
var exports = {
options: {}
};
var fileStatSync = function() {
var filepath = path.join.apply(path, arguments);
if (grunt.file.exists(filepath)) {
return fs.statSync(filepath);
}
return false;
};
// 1 to 1 gziping of files
exports.gzip = function(files, done) {
exports.singleFile(files, zlib.createGzip, 'gz', done);
grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' '
+ grunt.util.pluralize(files.length, 'file/files.'));
};
// 1 to 1 deflate of files
exports.deflate = function(files, done) {
exports.singleFile(files, zlib.createDeflate, 'deflate', done);
grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' '
+ grunt.util.pluralize(files.length, 'file/files.'));
};
// 1 to 1 deflateRaw of files
exports.deflateRaw = function(files, done) {
exports.singleFile(files, zlib.createDeflateRaw, 'deflate', done);
grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' '
+ grunt.util.pluralize(files.length, 'file/files.'));
};
// 1 to 1 compression of files, expects a compatible zlib method to be passed in, see above
exports.singleFile = function(files, algorithm, extension, done) {
grunt.util.async.forEachSeries(files, function(filePair, nextPair) {
grunt.util.async.forEachSeries(filePair.src, function(src, nextFile) {
// Must be a file
if (grunt.file.isDir(src)) {
return nextFile();
}
// Ensure the dest folder exists
grunt.file.mkdir(path.dirname(filePair.dest));
var srcStream = fs.createReadStream(src);
var originalSize = exports.getSize(src);
var destStream;
function initDestStream() {
destStream = fs.createWriteStream(filePair.dest);
destStream.on('close', function() {
var compressedSize = exports.getSize(filePair.dest);
var ratio = Math.round(parseInt(compressedSize, 10) / parseInt(originalSize, 10) * 100) + '%';
grunt.verbose.writeln('Created ' + chalk.cyan(filePair.dest) + ' (' + compressedSize + ') - ' + chalk.cyan(ratio) + ' of the original size');
nextFile();
});
}
// write to memory stream if source and destination are the same
var tmpStream;
if (src === filePair.dest) {
tmpStream = new streamBuffers.<API key>();
tmpStream.on('close', function() {
initDestStream();
destStream.write(this.getContents());
destStream.end();
});
} else {
initDestStream();
}
var compressor = algorithm.call(zlib, exports.options);
compressor.on('error', function(err) {
grunt.log.error(err);
grunt.fail.warn(algorithm + ' failed.');
nextFile();
});
srcStream.pipe(compressor).pipe(tmpStream || destStream);
}, nextPair);
}, done);
};
// Compress with tar, tgz and zip
exports.tar = function(files, done) {
if (typeof exports.options.archive !== 'string' || exports.options.archive.length === 0) {
grunt.fail.warn('Unable to compress; no valid archive file was specified.');
return;
}
var mode = exports.options.mode;
if (mode === 'tgz') {
mode = 'tar';
exports.options.gzip = true;
}
var archive = archiver.create(mode, exports.options);
var dest = exports.options.archive;
var dataWhitelist = ['comment', 'date', 'mode', 'store', 'gid', 'uid'];
var sourcePaths = {};
// Ensure dest folder exists
grunt.file.mkdir(path.dirname(dest));
// Where to write the file
var destStream = fs.createWriteStream(dest);
archive.on('error', function(err) {
grunt.log.error(err);
grunt.fail.warn('Archiving failed.');
});
archive.on('entry', function(file) {
var sp = sourcePaths[file.name] || 'unknown';
grunt.verbose.writeln('Archived ' + chalk.cyan(sp) + ' -> ' + chalk.cyan(dest + '/' + file.name));
});
destStream.on('error', function(err) {
grunt.log.error(err);
grunt.fail.warn('WriteStream failed.');
});
destStream.on('close', function() {
var size = archive.pointer();
grunt.verbose.writeln('Created ' + chalk.cyan(dest) + ' (' + exports.getSize(size) + ')');
done();
});
archive.pipe(destStream);
files.forEach(function(file) {
var isExpandedPair = file.orig.expand || false;
file.src.forEach(function(srcFile) {
var fstat = fileStatSync(srcFile);
if (!fstat) {
grunt.fail.warn('unable to stat srcFile (' + srcFile + ')');
return;
}
var internalFileName = isExpandedPair ? file.dest : exports.unixifyPath(path.join(file.dest || '', srcFile));
// check if internal file name is not a dot, should not be present in an archive
if (internalFileName === '.' || internalFileName === './') {
return;
}
if (fstat.isDirectory() && internalFileName.slice(-1) !== '/') {
srcFile += '/';
internalFileName += '/';
}
var fileData = {
name: internalFileName,
stats: fstat
};
for (var i = 0; i < dataWhitelist.length; i++) {
if (typeof file[dataWhitelist[i]] === 'undefined') {
continue;
}
if (typeof file[dataWhitelist[i]] === 'function') {
fileData[dataWhitelist[i]] = file[dataWhitelist[i]](srcFile);
} else {
fileData[dataWhitelist[i]] = file[dataWhitelist[i]];
}
}
if (fstat.isFile()) {
archive.file(srcFile, fileData);
} else if (fstat.isDirectory()) {
archive.append(null, fileData);
} else {
grunt.fail.warn('srcFile (' + srcFile + ') should be a valid file or directory');
return;
}
sourcePaths[internalFileName] = srcFile;
});
});
grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' '
+ grunt.util.pluralize(files.length, 'file/files.'));
archive.finalize();
};
exports.getSize = function(filename, pretty) {
var size = 0;
if (typeof filename === 'string') {
try {
size = fs.statSync(filename).size;
} catch (e) {}
} else {
size = filename;
}
if (pretty !== false) {
if (!exports.options.pretty) {
return size + ' bytes';
}
return prettyBytes(size);
}
return Number(size);
};
exports.autoDetectMode = function(dest) {
if (exports.options.mode) {
return exports.options.mode;
}
if (!dest) {
return 'gzip';
}
if (_.endsWith(dest, '.tar.gz')) {
return 'tgz';
}
var ext = path.extname(dest).replace('.', '');
if (ext === 'gz') {
return 'gzip';
}
return ext;
};
exports.unixifyPath = function(filepath) {
return process.platform === 'win32' ? filepath.replace(/\\/g, '/') : filepath;
};
return exports;
};
|
#include <sys/time.h>
#include <stdint.h>
#include "../../../../include/wrappers_msa.h"
#include "../../../../include/test_inputs_128.h"
#include "../../../../include/test_utils_128.h"
#define TEST_COUNT_TOTAL ( \
(<API key>) * (<API key>) + \
(<API key>) * (<API key>))
int32_t main(void)
{
char *isa_ase_name = "MSA";
char *group_name = "Int Divide";
char *instruction_name = "DIV_U.H";
int32_t ret;
uint32_t i, j;
struct timeval start, end;
double elapsed_time;
uint64_t b128_result[TEST_COUNT_TOTAL][2];
uint64_t b128_expect[TEST_COUNT_TOTAL][2] = {
{ <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>, <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>, },
{ <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>, <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>, },
{ <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>, <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>, },
{ <API key>, <API key>, },
{ <API key>, <API key>, },
{ <API key>, <API key>, },
{ <API key>, <API key>, },
{ <API key>, <API key>, },
};
reset_msa_registers();
gettimeofday(&start, NULL);
for (i = 0; i < <API key>; i++) {
for (j = 0; j < <API key>; j++) {
do_msa_DIV_U_H(b128_pattern[i], b128_pattern[j],
b128_result[<API key> * i + j]);
}
}
for (i = 0; i < <API key>; i++) {
for (j = 0; j < <API key>; j++) {
do_msa_DIV_U_H(b128_random[i], b128_random[j],
b128_result[((<API key>) *
(<API key>)) +
<API key> * i + j]);
}
}
gettimeofday(&end, NULL);
elapsed_time = (end.tv_sec - start.tv_sec) * 1000.0;
elapsed_time += (end.tv_usec - start.tv_usec) / 1000.0;
ret = check_results_128(isa_ase_name, group_name, instruction_name,
TEST_COUNT_TOTAL, elapsed_time,
&b128_result[0][0], &b128_expect[0][0]);
return ret;
}
|
#!/bin/bash
killall -q JSBSim
pkill -f runsim.py
set -e
set -x
autotest=$(dirname $(readlink -e $0))
cmd="../Tools/autotest/jsbsim/runsim.py --home=-35.362938,149.165085,584,270"
$autotest/<API key>.sh "simulator" $cmd || exit 1
sleep 2
mavproxy.py --out 127.0.0.1:14550 --load-module=HIL $*
|
# $Id: text.rb,v 1.7 2009/02/28 23:52:28 rmagick Exp $
# Text-related classes
module Magick
class RVG
# Base class for Tspan, Tref and Text.
class TextBase
include Stylable
include Duplicatable
private
def initialize(text, &block) #:nodoc:
super()
@text = text.to_s if text
@dx = @dy = 0
@rotation = 0
@tspans = Content.new
yield(self) if block_given?
end
public
# Create a new text chunk. Each chunk can have its own initial position and styles.
# If <tt>x</tt> and <tt>y</tt> are omitted the text starts at the current text
# position.
def tspan(text, x=nil, y=nil)
tspan = Tspan.new(text, x, y)
tspan.parent = self
@tspans << tspan
return tspan
end
# Add <tt>x</tt> and <tt>y</tt> to the current text position.
def d(x, y=0)
@dx, @dy = Magick::RVG.convert_to_float(x, y)
yield(self) if block_given?
self
end
# Rotate the text about the current text position.
def rotate(degrees)
@rotation = Magick::RVG.convert_to_float(degrees)[0]
yield(self) if block_given?
self
end
# We do our own transformations.
def add_primitives(gc) #:nodoc:
if @text || @tspans.length > 0
gc.push
x = self.cx + @dx
y = self.cy + @dy
if @rotation != 0
gc.translate(x, y)
gc.rotate(@rotation)
gc.translate(-x, -y)
end
<API key>(gc)
if @text
x2, y2 = gc.text(x, y, @text)
self.cx = x + x2
self.cy = y + y2
end
@tspans.each do |tspan|
tspan.add_primitives(gc)
end
gc.pop
end
end
end # class TextBase
# Tspan and Tref shared methods - read/update @cx, @cy in parent Text object.
module TextLink #:nodoc:
def add_primitives(gc)
@parent.cx = @x if @x
@parent.cy = @y if @y
super
end
def cx()
@parent.cx
end
def cy()
@parent.cy
end
def cx=(x)
@parent.cx = x
end
def cy=(y)
@parent.cy = y
end
end # module TextLink
class Tref < TextBase #:nodoc:
include TextLink
def initialize(obj, x, y, parent)
@x, @y = Magick::RVG.convert_to_float(x, y, :allow_nil)
super(nil)
@tspans << obj
@parent = parent
end
end # class Tref
class Tspan < TextBase #:nodoc:
include TextLink
attr_accessor :parent
# Define a text segment starting at (<tt>x</tt>, <tt>y</tt>).
# If <tt>x</tt> and <tt>y</tt> are omitted the segment starts
# at the current text position.
# Tspan objects can contain Tspan objects.
def initialize(text=nil, x=nil, y=nil, &block)
@x, @y = Magick::RVG.convert_to_float(x, y, :allow_nil)
super(text, &block)
end
end # class Tspan
class Text < TextBase
attr_accessor :cx, :cy #:nodoc:
# Define a text string starting at [<tt>x</tt>, <tt>y</tt>].
# Use the RVG::TextConstructors#text method to create Text objects in a container.
# container.text(100, 100, "Simple text").styles(:font=>'Arial')
# Text objects can contain Tspan objects.
# container.text(100, 100).styles(:font=>'Arial') do |t|
# t.tspan("Red text").styles(:fill=>'red')
# t.tspan("Blue text").styles(:fill=>'blue')
# end
def initialize(x=0, y=0, text=nil, &block)
@cx, @cy = Magick::RVG.convert_to_float(x, y)
super(text, &block)
end
# Reference a Tspan object. <tt>x</tt> and <tt>y</tt> are just
# like <tt>x</tt> and <tt>y</tt> in RVG::TextBase#tspan
def tref(obj, x=nil, y=nil)
if ! obj.kind_of?(Tspan)
raise ArgumentError, "wrong argument type #{obj.class} (expected Tspan)"
end
obj = obj.deep_copy
obj.parent = self
tref = Tref.new(obj, x, y, self)
@tspans << tref
return tref
end
end # class Text
# Methods that construct text objects within a container
module TextConstructors
# Draw a text string at (<tt>x</tt>,<tt>y</tt>). The string can
# be omitted. Optionally, define text chunks within the associated
# block.
def text(x=0, y=0, text=nil, &block)
t = Text.new(x, y, text, &block)
@content << t
return t
end
end # module TextConstructors
end # class RVG
end # module Magick
|
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="./resources/<API key>.js"></script>
<style>
pre, #log {
position: absolute;
top: 0;
left: 200px;
}
#target {
width: 0px;
height: 0px;
}
</style>
<div id='target'></div>
<script>
var entries = [];
runTestCycle(function() {
var target = document.getElementById('target');
assert_true(!!target, "target exists");
var observer = new <API key>(function(changes) {
entries = entries.concat(changes)
});
observer.observe(target);
entries = entries.concat(observer.takeRecords());
assert_equals(entries.length, 0, "No initial notifications.");
runTestCycle(step0, "First rAF should generate a notification.");
}, "Ensure that a zero-area target intersecting root generates a notification with intersectionRatio == 1");
function step0() {
assert_equals(entries.length, 1, "One notification.");
assert_equals(entries[0].intersectionRatio, 1, "intersectionRatio == 1");
}
</script>
|
tinyMCE.addI18n('th.advimage_dlg',{
tab_general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B",
tab_appearance:"\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30",
tab_advanced:"\u0E02\u0E31\u0E49\u0E19\u0E2A\u0E39\u0E07",
general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B",
title:"\u0E0A\u0E37\u0E48\u0E2D",
preview:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07",
<API key>:"\u0E04\u0E07\u0E2A\u0E31\u0E14\u0E2A\u0E48\u0E27\u0E19",
langdir:"\u0E17\u0E34\u0E28\u0E17\u0E32\u0E07\u0E01\u0E32\u0E23\u0E2D\u0E48\u0E32\u0E19",
langcode:"\u0E42\u0E04\u0E49\u0E14\u0E20\u0E32\u0E29\u0E32",
long_desc:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E25\u0E34\u0E49\u0E07\u0E04\u0E4C",
style:"\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A",
classes:"\u0E04\u0E25\u0E32\u0E2A",
ltr:"\u0E0B\u0E49\u0E32\u0E22\u0E44\u0E1B\u0E02\u0E27\u0E32",
rtl:"\u0E02\u0E27\u0E32\u0E44\u0E1B\u0E0B\u0E49\u0E32\u0E22",
id:"Id",
map:"Image map",
swap_image:"Swap image",
alt_image:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E23\u0E39\u0E1B",
mouseover:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E0A\u0E35\u0E49",
mouseout:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E2D\u0E2D\u0E01",
misc:"\u0E40\u0E1A\u0E47\u0E14\u0E40\u0E15\u0E25\u0E47\u0E14",
example_img:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30\u0E02\u0E2D\u0E07\u0E23\u0E39\u0E1B",
missing_alt:"\u0E04\u0E38\u0E13\u0E41\u0E19\u0E48\u0E43\u0E08\u0E2B\u0E23\u0E37\u0E2D\u0E44\u0E21\u0E48\u0E27\u0E48\u0E32\u0E15\u0E49\u0E2D\u0E07\u0E01\u0E32\u0E23\u0E14\u0E33\u0E40\u0E19\u0E34\u0E19\u0E01\u0E32\u0E23\u0E15\u0E48\u0E2D\u0E42\u0E14\u0E22\u0E44\u0E21\u0E48\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E20\u0E32\u0E1E ? \u0E01\u0E32\u0E23\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E17\u0E33\u0E43\u0E2B\u0E49\u0E1C\u0E39\u0E49\u0E1E\u0E34\u0E01\u0E32\u0E23\u0E17\u0E32\u0E07\u0E2A\u0E32\u0E22\u0E15\u0E32\u0E2A\u0E32\u0E21\u0E32\u0E23\u0E16\u0E23\u0E39\u0E49\u0E44\u0E14\u0E49\u0E27\u0E48\u0E32\u0E23\u0E39\u0E1B\u0E04\u0E38\u0E13\u0E04\u0E37\u0E2D\u0E23\u0E39\u0E1B\u0E2D\u0E30\u0E44\u0E23",
dialog_title:"\u0E40\u0E1E\u0E34\u0E48\u0E21/\u0E41\u0E01\u0E49\u0E44\u0E02 image",
src:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E23\u0E39\u0E1B",
alt:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E23\u0E39\u0E1B",
list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B",
border:"\u0E01\u0E23\u0E2D\u0E1A",
dimensions:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07",
vspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E15\u0E31\u0E49\u0E07",
hspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E19\u0E2D\u0E19",
align:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07\u0E08\u0E31\u0E14\u0E27\u0E32\u0E07",
align_baseline:"\u0E40\u0E2A\u0E49\u0E19\u0E1E\u0E37\u0E49\u0E19",
align_top:"\u0E1A\u0E19",
align_middle:"\u0E01\u0E25\u0E32\u0E07",
align_bottom:"\u0E25\u0E48\u0E32\u0E07",
align_texttop:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E1A\u0E19",
align_textbottom:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E25\u0E48\u0E32\u0E07",
align_left:"\u0E0B\u0E49\u0E32\u0E22",
align_right:"\u0E02\u0E27\u0E32",
image_list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B"
});
|
# Makefile for Sphinx documentation
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXSOURCE = source
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) $(SPHINXSOURCE)
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
|
#include "sdk.h"
#include "cpu_utility/cpu_utility.h"
#include "core/cortex_a9.h"
#include "core/mmu.h"
#include "pmu/pmu_driver.h"
#include "registers/regsccm.h"
#include "registers/regsccmanalog.h"
#include "registers/regspmu.h"
typedef struct cpu_wp_s {
uint32_t cpu_freq; // MHz
uint32_t vdd_pu;
uint32_t vdd_soc;
uint32_t vdd_arm;
} cpu_wp_t;
static cpu_wp_t mx6_cpu_wp[] = {
{
.cpu_freq = 1200,
.vdd_pu = 1275,
.vdd_soc = 1275,
.vdd_arm = 1275,
},
{
.cpu_freq = 996,
.vdd_pu = 1250,
.vdd_soc = 1250,
.vdd_arm = 1250,
},
{
.cpu_freq = 792,
.vdd_pu = 1175,
.vdd_soc = 1175,
.vdd_arm = 1150,
},
{
.cpu_freq = 396,
.vdd_pu = 1175,
.vdd_soc = 1175,
.vdd_arm = 950,
},
};
uint32_t cpu_workpoint_set(cpu_wp_e cpu_wp_mode)
{
unsigned int div = 0;
if (cpu_wp_mode >= <API key>) {
printf("CPU work point mode not exist !!\n");
return 0;
}
cpu_wp_t *wp = &mx6_cpu_wp[cpu_wp_mode];
pmu_init();
/* calculate the pll loop divider. target Fout = Fin * div / 2 */
div = wp->cpu_freq * 2 / 24;
/* first, switch the cpu clock root to step clock */
HW_CCM_CCSR.B.PLL1_SW_CLK_SEL = 1;
/* set clock to target frequency */
<API key>.B.POWERDOWN = 1;
<API key>.B.DIV_SELECT = div;
<API key>.B.POWERDOWN = 0;
while (!<API key>.B.LOCK) ;
<API key>.B.BYPASS = 0;
/* set the power rail */
switch (wp->cpu_freq) {
case 1200:
case 996:
case 792:
case 396:
pmu_set_property(<API key>, <API key>, &wp->vdd_arm);
pmu_set_property(<API key>, <API key>, &wp->vdd_pu);
pmu_set_property(kPMURegulator_SoC, <API key>, &wp->vdd_soc);
break;
default:
printf("Unsupported CPU workpoint mode!!\n");
return 0;
}
/*switch back to PLL1 */
HW_CCM_CCSR.B.PLL1_SW_CLK_SEL = 0;
return wp->cpu_freq;
}
|
/*
THIS FILE WAS AUTOGENERATED BY mode.tmpl.js
*/
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var NSISHighlightRules = require("./<API key>").NSISHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = NSISHighlightRules;
this.foldingRules = new FoldMode();
this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = [";", "
this.blockComment = {start: "/*", end: "*/"};
this.$id = "ace/mode/nsis";
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
/** \file
* \brief Board specific information header for the Micropendous series boards.
* \copydetails <API key>
*
* \note This file should not be included directly. It is automatically included as needed by the Board driver
* dispatch header located in LUFA/Drivers/Board/Board.h.
*/
#ifndef <API key>
#define <API key>
/* Includes: */
#include "../../../../Common/Common.h"
/* Enable C linkage for C++ Compilers: */
#if defined(__cplusplus)
extern "C" {
#endif
/* Preprocessor Checks: */
#if !defined(<API key>)
#error Do not include this file directly. Include LUFA/Drivers/Board/Board.h instead.
#endif
/* Public Interface - May be used in end-application: */
/* Macros: */
#if ((BOARD == <API key>) || (BOARD == <API key>) || \
(BOARD == <API key>) || (BOARD == <API key>) || \
(BOARD == <API key>) || (BOARD == <API key>) || \
(BOARD == <API key>) || (BOARD == <API key>) || \
(BOARD == <API key>) || defined(__DOXYGEN__))
#include "../../Buttons.h"
/** Indicates the board has hardware Buttons mounted. */
#define BOARD_HAS_BUTTONS
#endif
#if ((BOARD == <API key>) || (BOARD == <API key>) || \
(BOARD == <API key>) || defined(__DOXYGEN__))
#include "../../LEDs.h"
/** Indicates the board has hardware LEDs mounted. */
#define BOARD_HAS_LEDS
#endif
/* Disable C linkage for C++ Compilers: */
#if defined(__cplusplus)
}
#endif
#endif
|
<!DOCTYPE html>
<!
Copyright (c) 2012 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION 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.
Authors:
Liu, Jinfeng <jinfengx.liu@intel.com>
<html>
<head>
<title>CSS3 Backgrounds Test: <API key></title>
<link rel="author" title="Intel" href="http:
<link rel="help" href="http://www.w3.org/TR/2012/<API key>/#border-image-repeat" />
<meta name="flags" content="" />
<meta name="assert" content="Check if 'border-image-repeat:repeat-x;border-image-source:url(support/swatch-orange.png);border-image-width:auto' on test div" />
<script type="text/javascript" src="../resources/testharness.js"></script>
<script type="text/javascript" src="../resources/testharnessreport.js"></script>
<script type="text/javascript" src="support/support.js"></script>
<style>
#test{
height: 200px;
width: 300px;
padding: 5px;
border: 5px solid black;
margin: 5px;
background: blue;
}
</style>
</head>
<body>
<div id="log"></div>
<div id="test"></div>
<script type="text/javascript">
var div = document.querySelector("#test");
var t = async_test(document.title, {timeout: 500});
t.step(function () {
div.style[headProp("border-image-repeat")] = "repeat-x";
div.style[headProp("border-image-source")] = "url(support/swatch-orange.png)";
div.style[headProp("border-image-width")] = "auto";
var propvalue = GetCurrentStyle("border-image-repeat");
assert_equals(propvalue, "stretch", "The element border-image-repeat should ");
var borderImageWidth = GetCurrentStyle("border-image-width");
assert_equals(borderImageWidth, "auto", "The element border-image-width should ");
var borderImageSource = GetCurrentStyle("border-image-source");
prop = borderImageSource.indexOf("support/swatch-orange.png") != -1;
assert_true(prop, "The element border-image-source should be url(support/swatch-orange.png)");
});
t.done();
</script>
</body>
</html>
|
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import PasswordTestCase from './PasswordTestCase';
const React = window.React;
function NumberInputs() {
return (
<FixtureSet title="Password inputs">
<TestCase
title="The show password icon"
description={`
Some browsers have an unmask password icon that React accidentally
prevents the display of.
`}
affectedBrowsers="IE Edge, IE 11">
<TestCase.Steps>
<li>Type any string (not an actual password)</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The field should include the "unmasking password" icon.
</TestCase.ExpectedResult>
<PasswordTestCase />
</TestCase>
</FixtureSet>
);
}
export default NumberInputs;
|
#ifndef LDL_LONG
#define LDL_LONG
#endif
#include "ldl.h"
#include "mex.h"
void mexFunction
(
int nargout,
mxArray *pargout[ ],
int nargin,
const mxArray *pargin[ ]
)
{
UF_long i, n, *Pattern, *Flag, *Lp, *Ap, *Ai, *Lnz, *Parent,
*P, *Pinv, nn, k, j, permute ;
double flops, *p ;
/* get inputs and allocate workspace */
if (nargin == 0 || nargin > 2)
{
mexErrMsgTxt ("Usage:\n"
" [Lnz, Parent, flopcount] = ldl (A) ;\n"
" [Lnz, Parent, flopcount] = ldl (A, P) ;\n") ;
}
n = mxGetM (pargin [0]) ;
if (!mxIsSparse (pargin [0]) || n != mxGetN (pargin [0])
|| mxIsComplex (pargin [0]))
{
mexErrMsgTxt ("ldlsymbol: A must be sparse, square, and real") ;
}
nn = (n == 0) ? 1 : n ;
/* get sparse matrix A */
Ap = (UF_long *) mxGetJc (pargin [0]) ;
Ai = (UF_long *) mxGetIr (pargin [0]) ;
/* get fill-reducing ordering, if present */
permute = ((nargin > 1) && !mxIsEmpty (pargin [1])) ;
if (permute)
{
if (mxGetM (pargin [1]) * mxGetN (pargin [1]) != n ||
mxIsSparse (pargin [1]))
{
mexErrMsgTxt ("ldlsymbol: invalid input permutation\n") ;
}
P = (UF_long *) mxMalloc (nn * sizeof (UF_long)) ;
Pinv = (UF_long *) mxMalloc (nn * sizeof (UF_long)) ;
p = mxGetPr (pargin [1]) ;
for (k = 0 ; k < n ; k++)
{
P [k] = p [k] - 1 ; /* convert to 0-based */
}
}
else
{
P = (UF_long *) NULL ;
Pinv = (UF_long *) NULL ;
}
/* allocate first part of L */
Lp = (UF_long *) mxMalloc ((n+1) * sizeof (UF_long)) ;
Parent = (UF_long *) mxMalloc (nn * sizeof (UF_long)) ;
/* get workspace */
Flag = (UF_long *) mxMalloc (nn * sizeof (UF_long)) ;
Pattern = (UF_long *) mxMalloc (nn * sizeof (UF_long)) ;
Lnz = (UF_long *) mxMalloc (nn * sizeof (UF_long)) ;
/* make sure the input P is valid */
if (permute && !ldl_l_valid_perm (n, P, Flag))
{
mexErrMsgTxt ("ldlsymbol: invalid input permutation\n") ;
}
/* note that we assume that the input matrix is valid */
/* symbolic factorization to get Lp, Parent, Lnz, and optionally Pinv */
ldl_l_symbolic (n, Ap, Ai, Lp, Parent, Lnz, Flag, P, Pinv) ;
/* create outputs */
/* create the output Lnz vector */
pargout [0] = <API key> (1, n, mxREAL) ;
p = mxGetPr (pargout [0]) ;
for (j = 0 ; j < n ; j++)
{
p [j] = Lnz [j] ;
}
/* return elimination tree (add 1 to change from 0-based to 1-based) */
if (nargout > 1)
{
pargout [1] = <API key> (1, n, mxREAL) ;
p = mxGetPr (pargout [1]) ;
for (i = 0 ; i < n ; i++)
{
p [i] = Parent [i] + 1 ;
}
}
if (nargout > 2)
{
/* find flop count for ldl_l_numeric */
flops = 0 ;
for (k = 0 ; k < n ; k++)
{
flops += ((double) Lnz [k]) * (Lnz [k] + 2) ;
}
pargout [2] = <API key> (1, 1, mxREAL) ;
p = mxGetPr (pargout [2]) ;
p [0] = flops ;
}
if (permute)
{
mxFree (P) ;
mxFree (Pinv) ;
}
mxFree (Lp) ;
mxFree (Parent) ;
mxFree (Flag) ;
mxFree (Pattern) ;
mxFree (Lnz) ;
}
|
(function( $ ) {
/**
* Activity reply object for the activity index screen
*
* @since 1.6
*/
var activityReply = {
/**
* Attach event handler functions to the relevant elements.
*
* @since 1.6
*/
init : function() {
$(document).on( 'click', '.row-actions a.reply', activityReply.open );
$(document).on( 'click', '#<API key> a.cancel', activityReply.close );
$(document).on( 'click', '#<API key> a.save', activityReply.send );
// Close textarea on escape
$(document).on( 'keyup', '#bp-activities:visible', function( e ) {
if ( 27 == e.which ) {
activityReply.close();
}
});
},
/**
* Reveals the entire row when "reply" is pressed.
*
* @since 1.6
*/
open : function( e ) {
// Hide the container row, and move it to the new location
var box = $( '#<API key>' ).hide();
$( this ).parents( 'tr' ).after( box );
// Fade the whole row in, and set focus on the text area.
box.fadeIn( '300' );
$( '#bp-activities' ).focus();
return false;
},
/**
* Hide and reset the entire row when "cancel", or escape, are pressed.
*
* @since 1.6
*/
close : function( e ) {
// Hide the container row
$('#<API key>').fadeOut( '200', function () {
// Empty and unfocus the text area
$( '#bp-activities' ).val( '' ).blur();
// Remove any error message and disable the spinner
$( '#bp-replysubmit .error' ).html( '' ).hide();
$( '#bp-replysubmit .waiting' ).hide();
});
return false;
},
/**
* Submits "form" via AJAX back to WordPress.
*
* @since 1.6
*/
send : function( e ) {
// Hide any existing error message, and show the loading spinner
$( '#bp-replysubmit .error' ).hide();
$( '#bp-replysubmit .waiting' ).show();
// Grab the nonce
var reply = {};
reply['<API key>'] = $( '#<API key> input[name="<API key>"]' ).val();
// Get the rest of the data
reply.action = '<API key>';
reply.content = $( '#bp-activities' ).val();
reply.parent_id = $( '#<API key>' ).prev().data( 'parent_id' );
reply.root_id = $( '#<API key>' ).prev().data( 'root_id' );
// Make the AJAX call
$.ajax({
data : reply,
type : 'POST',
url : ajaxurl,
// Callbacks
error : function( r ) { activityReply.error( r ); },
success : function( r ) { activityReply.show( r ); }
});
return false;
},
/**
* send() error message handler
*
* @since 1.6
*/
error : function( r ) {
var er = r.statusText;
$('#bp-replysubmit .waiting').hide();
if ( r.responseText ) {
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
}
if ( er ) {
$('#bp-replysubmit .error').html( er ).show();
}
},
/**
* send() success handler
*
* @since 1.6
*/
show : function ( xml ) {
var bg, id, response;
// Handle any errors in the response
if ( typeof( xml ) == 'string' ) {
activityReply.error( { 'responseText': xml } );
return false;
}
response = wpAjax.parseAjaxResponse( xml );
if ( response.errors ) {
activityReply.error( { 'responseText': wpAjax.broken } );
return false;
}
response = response.responses[0];
// Close and reset the reply row, and add the new Activity item into the list.
$('#<API key>').fadeOut( '200', function () {
// Empty and unfocus the text area
$( '#bp-activities' ).val( '' ).blur();
// Remove any error message and disable the spinner
$( '#bp-replysubmit .error' ).html( '' ).hide();
$( '#bp-replysubmit .waiting' ).hide();
// Insert new activity item
$( '#<API key>' ).before( response.data );
// Get background colour and animate the flash
id = $( '#activity-' + response.id );
bg = id.closest( '.widefat' ).css( 'backgroundColor' );
id.animate( { 'backgroundColor': '#CEB' }, 300 ).animate( { 'backgroundColor': bg }, 300 );
});
}
};
$(document).ready( function () {
// Create the Activity reply object after domready event
activityReply.init();
// On the edit screen, unload the close/open toggle js for the action & content metaboxes
$( '#bp_activity_action h3, #bp_activity_content h3' ).unbind( 'click' );
});
})(jQuery);
|
/* DO NOT EDIT THIS FILE
* Automatically generated by <API key>.xsl
* DO NOT EDIT THIS FILE
*/
#ifndef <API key>
#define <API key>
#include "../mach-common/ADSP-EDN-core_def.h"
#include "<API key>.h"
#define CHIPID 0xFFC00014
#define SWRST 0xFFC00100 /* Software Reset Register */
#define SYSCR 0xFFC00104 /* System Configuration register */
#define SRAM_BASE_ADDR 0xFFE00000 /* SRAM Base Address (Read Only) */
#define DMEM_CONTROL 0xFFE00004 /* Data memory control */
#define DCPLB_STATUS 0xFFE00008 /* Data Cache Programmable Look-Aside Buffer Status */
#define DCPLB_FAULT_ADDR 0xFFE0000C /* Data Cache Programmable Look-Aside Buffer Fault Address */
#define DCPLB_ADDR0 0xFFE00100 /* Data Cache Protection Lookaside Buffer 0 */
#define DCPLB_ADDR1 0xFFE00104 /* Data Cache Protection Lookaside Buffer 1 */
#define DCPLB_ADDR2 0xFFE00108 /* Data Cache Protection Lookaside Buffer 2 */
#define DCPLB_ADDR3 0xFFE0010C /* Data Cache Protection Lookaside Buffer 3 */
#define DCPLB_ADDR4 0xFFE00110 /* Data Cache Protection Lookaside Buffer 4 */
#define DCPLB_ADDR5 0xFFE00114 /* Data Cache Protection Lookaside Buffer 5 */
#define DCPLB_ADDR6 0xFFE00118 /* Data Cache Protection Lookaside Buffer 6 */
#define DCPLB_ADDR7 0xFFE0011C /* Data Cache Protection Lookaside Buffer 7 */
#define DCPLB_ADDR8 0xFFE00120 /* Data Cache Protection Lookaside Buffer 8 */
#define DCPLB_ADDR9 0xFFE00124 /* Data Cache Protection Lookaside Buffer 9 */
#define DCPLB_ADDR10 0xFFE00128 /* Data Cache Protection Lookaside Buffer 10 */
#define DCPLB_ADDR11 0xFFE0012C /* Data Cache Protection Lookaside Buffer 11 */
#define DCPLB_ADDR12 0xFFE00130 /* Data Cache Protection Lookaside Buffer 12 */
#define DCPLB_ADDR13 0xFFE00134 /* Data Cache Protection Lookaside Buffer 13 */
#define DCPLB_ADDR14 0xFFE00138 /* Data Cache Protection Lookaside Buffer 14 */
#define DCPLB_ADDR15 0xFFE0013C /* Data Cache Protection Lookaside Buffer 15 */
#define DCPLB_DATA0 0xFFE00200 /* Data Cache 0 Status */
#define DCPLB_DATA1 0xFFE00204 /* Data Cache 1 Status */
#define DCPLB_DATA2 0xFFE00208 /* Data Cache 2 Status */
#define DCPLB_DATA3 0xFFE0020C /* Data Cache 3 Status */
#define DCPLB_DATA4 0xFFE00210 /* Data Cache 4 Status */
#define DCPLB_DATA5 0xFFE00214 /* Data Cache 5 Status */
#define DCPLB_DATA6 0xFFE00218 /* Data Cache 6 Status */
#define DCPLB_DATA7 0xFFE0021C /* Data Cache 7 Status */
#define DCPLB_DATA8 0xFFE00220 /* Data Cache 8 Status */
#define DCPLB_DATA9 0xFFE00224 /* Data Cache 9 Status */
#define DCPLB_DATA10 0xFFE00228 /* Data Cache 10 Status */
#define DCPLB_DATA11 0xFFE0022C /* Data Cache 11 Status */
#define DCPLB_DATA12 0xFFE00230 /* Data Cache 12 Status */
#define DCPLB_DATA13 0xFFE00234 /* Data Cache 13 Status */
#define DCPLB_DATA14 0xFFE00238 /* Data Cache 14 Status */
#define DCPLB_DATA15 0xFFE0023C /* Data Cache 15 Status */
#define DTEST_COMMAND 0xFFE00300 /* Data Test Command Register */
#define DTEST_DATA0 0xFFE00400 /* Data Test Data Register */
#define DTEST_DATA1 0xFFE00404 /* Data Test Data Register */
#define IMEM_CONTROL 0xFFE01004 /* Instruction Memory Control */
#define ICPLB_STATUS 0xFFE01008 /* Instruction Cache Programmable Look-Aside Buffer Status */
#define ICPLB_FAULT_ADDR 0xFFE0100C /* Instruction Cache Programmable Look-Aside Buffer Fault Address */
#define ICPLB_ADDR0 0xFFE01100 /* Instruction Cacheability Protection Lookaside Buffer 0 */
#define ICPLB_ADDR1 0xFFE01104 /* Instruction Cacheability Protection Lookaside Buffer 1 */
#define ICPLB_ADDR2 0xFFE01108 /* Instruction Cacheability Protection Lookaside Buffer 2 */
#define ICPLB_ADDR3 0xFFE0110C /* Instruction Cacheability Protection Lookaside Buffer 3 */
#define ICPLB_ADDR4 0xFFE01110 /* Instruction Cacheability Protection Lookaside Buffer 4 */
#define ICPLB_ADDR5 0xFFE01114 /* Instruction Cacheability Protection Lookaside Buffer 5 */
#define ICPLB_ADDR6 0xFFE01118 /* Instruction Cacheability Protection Lookaside Buffer 6 */
#define ICPLB_ADDR7 0xFFE0111C /* Instruction Cacheability Protection Lookaside Buffer 7 */
#define ICPLB_ADDR8 0xFFE01120 /* Instruction Cacheability Protection Lookaside Buffer 8 */
#define ICPLB_ADDR9 0xFFE01124 /* Instruction Cacheability Protection Lookaside Buffer 9 */
#define ICPLB_ADDR10 0xFFE01128 /* Instruction Cacheability Protection Lookaside Buffer 10 */
#define ICPLB_ADDR11 0xFFE0112C /* Instruction Cacheability Protection Lookaside Buffer 11 */
#define ICPLB_ADDR12 0xFFE01130 /* Instruction Cacheability Protection Lookaside Buffer 12 */
#define ICPLB_ADDR13 0xFFE01134 /* Instruction Cacheability Protection Lookaside Buffer 13 */
#define ICPLB_ADDR14 0xFFE01138 /* Instruction Cacheability Protection Lookaside Buffer 14 */
#define ICPLB_ADDR15 0xFFE0113C /* Instruction Cacheability Protection Lookaside Buffer 15 */
#define ICPLB_DATA0 0xFFE01200 /* Instruction Cache 0 Status */
#define ICPLB_DATA1 0xFFE01204 /* Instruction Cache 1 Status */
#define ICPLB_DATA2 0xFFE01208 /* Instruction Cache 2 Status */
#define ICPLB_DATA3 0xFFE0120C /* Instruction Cache 3 Status */
#define ICPLB_DATA4 0xFFE01210 /* Instruction Cache 4 Status */
#define ICPLB_DATA5 0xFFE01214 /* Instruction Cache 5 Status */
#define ICPLB_DATA6 0xFFE01218 /* Instruction Cache 6 Status */
#define ICPLB_DATA7 0xFFE0121C /* Instruction Cache 7 Status */
#define ICPLB_DATA8 0xFFE01220 /* Instruction Cache 8 Status */
#define ICPLB_DATA9 0xFFE01224 /* Instruction Cache 9 Status */
#define ICPLB_DATA10 0xFFE01228 /* Instruction Cache 10 Status */
#define ICPLB_DATA11 0xFFE0122C /* Instruction Cache 11 Status */
#define ICPLB_DATA12 0xFFE01230 /* Instruction Cache 12 Status */
#define ICPLB_DATA13 0xFFE01234 /* Instruction Cache 13 Status */
#define ICPLB_DATA14 0xFFE01238 /* Instruction Cache 14 Status */
#define ICPLB_DATA15 0xFFE0123C /* Instruction Cache 15 Status */
#define ITEST_COMMAND 0xFFE01300 /* Instruction Test Command Register */
#define ITEST_DATA0 0xFFE01400 /* Instruction Test Data Register */
#define ITEST_DATA1 0xFFE01404 /* Instruction Test Data Register */
#define EVT0 0xFFE02000 /* Event Vector 0 ESR Address */
#define EVT1 0xFFE02004 /* Event Vector 1 ESR Address */
#define EVT2 0xFFE02008 /* Event Vector 2 ESR Address */
#define EVT3 0xFFE0200C /* Event Vector 3 ESR Address */
#define EVT4 0xFFE02010 /* Event Vector 4 ESR Address */
#define EVT5 0xFFE02014 /* Event Vector 5 ESR Address */
#define EVT6 0xFFE02018 /* Event Vector 6 ESR Address */
#define EVT7 0xFFE0201C /* Event Vector 7 ESR Address */
#define EVT8 0xFFE02020 /* Event Vector 8 ESR Address */
#define EVT9 0xFFE02024 /* Event Vector 9 ESR Address */
#define EVT10 0xFFE02028 /* Event Vector 10 ESR Address */
#define EVT11 0xFFE0202C /* Event Vector 11 ESR Address */
#define EVT12 0xFFE02030 /* Event Vector 12 ESR Address */
#define EVT13 0xFFE02034 /* Event Vector 13 ESR Address */
#define EVT14 0xFFE02038 /* Event Vector 14 ESR Address */
#define EVT15 0xFFE0203C /* Event Vector 15 ESR Address */
#define ILAT 0xFFE0210C /* Interrupt Latch Register */
#define IMASK 0xFFE02104 /* Interrupt Mask Register */
#define IPEND 0xFFE02108 /* Interrupt Pending Register */
#define IPRIO 0xFFE02110 /* Interrupt Priority Register */
#define TBUFCTL 0xFFE06000 /* Trace Buffer Control Register */
#define TBUFSTAT 0xFFE06004 /* Trace Buffer Status Register */
#define TBUF 0xFFE06100 /* Trace Buffer */
#define L1_DATA_A_SRAM 0xFF800000 /* 0xFF800000 -> 0xFF803FFF Data Bank A SRAM */
#define L1_DATA_A_SRAM_SIZE (0xFF803FFF - 0xFF800000 + 1)
#define L1_DATA_A_SRAM_END (L1_DATA_A_SRAM + L1_DATA_A_SRAM_SIZE)
#define L1_DATA_B_SRAM 0xFF900000 /* 0xFF900000 -> 0xFF903FFF Data Bank B SRAM */
#define L1_DATA_B_SRAM_SIZE (0xFF903FFF - 0xFF900000 + 1)
#define L1_DATA_B_SRAM_END (L1_DATA_B_SRAM + L1_DATA_B_SRAM_SIZE)
#define L1_INST_SRAM 0xFFA00000 /* 0xFFA00000 -> 0xFFA07FFF Instruction Bank A SRAM */
#define L1_INST_SRAM_SIZE (0xFFA07FFF - 0xFFA00000 + 1)
#define L1_INST_SRAM_END (L1_INST_SRAM + L1_INST_SRAM_SIZE)
#define L1_SRAM_SCRATCH 0xFFB00000 /* 0xFFB00000 -> 0xFFB00FFF Scratchpad SRAM */
#define <API key> (0xFFB00FFF - 0xFFB00000 + 1)
#define L1_SRAM_SCRATCH_END (L1_SRAM_SCRATCH + <API key>)
#define SYSMMR_BASE 0xFFC00000 /* 0xFFC00000 -> 0xFFFFFFFF MMR registers */
#define SYSMMR_BASE_SIZE (0xFFFFFFFF - 0xFFC00000 + 1)
#define SYSMMR_BASE_END (SYSMMR_BASE + SYSMMR_BASE_SIZE)
#endif /* <API key> */
|
/*
* This file contains private information about the H5T module
*/
#ifndef _H5Tprivate_H
#define _H5Tprivate_H
/* Get package's public header */
#include "H5Tpublic.h"
/* Other public headers needed by this file */
#include "H5MMpublic.h" /* Memory management */
/* Private headers needed by this file */
#include "H5private.h" /* Generic Functions */
#include "H5Gprivate.h" /* Groups */
#include "H5Rprivate.h" /* References */
/* Macro for size of temporary buffers to contain a single element */
#define H5T_ELEM_BUF_SIZE 256
/* If the module using this macro is allowed access to the private variables, access them directly */
#ifdef H5T_PACKAGE
#define H5T_GET_SIZE(T) ((T)->shared->size)
#define H5T_GET_SHARED(T) ((T)->shared)
#define <API key>(T, I) ((T)->u.compnd.memb[I].offset)
#define H5T_GET_MEMBER_SIZE(T, I) ((T)->u.compnd.memb[I].shared->size)
#else /* H5T_PACKAGE */
#define H5T_GET_SIZE(T) (H5T_get_size(T))
#define H5T_GET_SHARED(T) (H5T_get_shared(T))
#define <API key>(T, I) (<API key>((T), (I)))
#define H5T_GET_MEMBER_SIZE(T, I) (H5T_get_member_size((T), (I)))
#endif /* H5T_PACKAGE */
/* Forward references of package typedefs (declared in H5Tpkg.h) */
typedef struct H5T_t H5T_t;
typedef struct H5T_stats_t H5T_stats_t;
typedef struct H5T_path_t H5T_path_t;
/* How to copy a datatype */
typedef enum H5T_copy_t {
H5T_COPY_TRANSIENT,
H5T_COPY_ALL,
H5T_COPY_REOPEN
} H5T_copy_t;
/* Location of datatype information */
typedef enum {
H5T_LOC_BADLOC = 0, /* invalid datatype location */
H5T_LOC_MEMORY, /* data stored in memory */
H5T_LOC_DISK, /* data stored on disk */
H5T_LOC_MAXLOC /* highest value (Invalid as true value) */
} H5T_loc_t;
/* VL allocation information */
typedef struct {
H5MM_allocate_t alloc_func; /* Allocation function */
void *alloc_info; /* Allocation information */
H5MM_free_t free_func; /* Free function */
void *free_info; /* Free information */
} <API key>;
/* Structure for conversion callback property */
typedef struct H5T_conv_cb_t {
<API key> func;
void* user_data;
} H5T_conv_cb_t;
/* Values for the optimization of compound data reading and writing. They indicate
* whether the fields of the source and destination are subset of each other and
* there is no conversion needed.
*/
typedef enum {
H5T_SUBSET_BADVALUE = -1, /* Invalid value */
H5T_SUBSET_FALSE = 0, /* Source and destination aren't subset of each other */
H5T_SUBSET_SRC, /* Source is the subset of dest and no conversion is needed */
H5T_SUBSET_DST, /* Dest is the subset of source and no conversion is needed */
H5T_SUBSET_CAP /* Must be the last value */
} H5T_subset_t;
typedef struct H5T_subset_info_t {
H5T_subset_t subset; /* See above */
size_t copy_size; /* Size in bytes, to copy for each element */
} H5T_subset_info_t;
/* Forward declarations for prototype arguments */
struct H5O_t;
/* The native endianess of the platform */
H5_DLLVAR H5T_order_t H5T_native_order_g;
/* Private functions */
H5_DLL herr_t H5TN_init_interface(void);
H5_DLL herr_t H5T_init(void);
H5_DLL H5T_t *H5T_copy(H5T_t *old_dt, H5T_copy_t method);
H5_DLL herr_t H5T_lock(H5T_t *dt, hbool_t immutable);
H5_DLL herr_t H5T_close(H5T_t *dt);
H5_DLL H5T_t *H5T_get_super(const H5T_t *dt);
H5_DLL H5T_class_t H5T_get_class(const H5T_t *dt, htri_t internal);
H5_DLL htri_t H5T_detect_class(const H5T_t *dt, H5T_class_t cls, hbool_t from_api);
H5_DLL size_t H5T_get_size(const H5T_t *dt);
H5_DLL int H5T_cmp(const H5T_t *dt1, const H5T_t *dt2, hbool_t superset);
H5_DLL herr_t H5T_debug(const H5T_t *dt, FILE * stream);
H5_DLL struct H5O_loc_t *H5T_oloc(H5T_t *dt);
H5_DLL H5G_name_t *H5T_nameof(H5T_t *dt);
H5_DLL htri_t H5T_is_immutable(const H5T_t *dt);
H5_DLL htri_t H5T_is_named(const H5T_t *dt);
H5_DLL htri_t H5T_is_relocatable(const H5T_t *dt);
H5_DLL H5T_path_t *H5T_path_find(const H5T_t *src, const H5T_t *dst,
const char *name, H5T_conv_t func, hid_t dxpl_id, hbool_t is_api);
H5_DLL hbool_t H5T_path_noop(const H5T_path_t *p);
H5_DLL H5T_bkg_t H5T_path_bkg(const H5T_path_t *p);
H5_DLL H5T_subset_info_t *<API key>(const H5T_path_t *p);
H5_DLL herr_t H5T_convert(H5T_path_t *tpath, hid_t src_id, hid_t dst_id,
size_t nelmts, size_t buf_stride, size_t bkg_stride, void *buf, void *bkg,
hid_t dset_xfer_plist);
H5_DLL herr_t H5T_vlen_reclaim(void *elem, hid_t type_id, unsigned ndim, const hsize_t *point, void *_op_data);
H5_DLL herr_t <API key>(void *elem, H5T_t *dt, hid_t dxpl_id);
H5_DLL herr_t <API key>(hid_t dxpl_id, <API key> **vl_alloc_info);
H5_DLL htri_t H5T_set_loc(H5T_t *dt, H5F_t *f, H5T_loc_t loc);
H5_DLL htri_t H5T_is_sensible(const H5T_t *dt);
H5_DLL uint32_t H5T_hash(H5F_t * file, const H5T_t *dt);
H5_DLL herr_t <API key>(H5T_t *dt);
H5_DLL herr_t H5T_patch_file(H5T_t *dt, H5F_t *f);
H5_DLL htri_t H5T_is_variable_str(const H5T_t *dt);
/* Reference specific functions */
H5_DLL H5R_type_t H5T_get_ref_type(const H5T_t *dt);
/* Operations on named datatypes */
H5_DLL H5T_t *H5T_open(const H5G_loc_t *loc, hid_t dxpl_id);
H5_DLL htri_t H5T_committed(const H5T_t *type);
H5_DLL int H5T_link(const H5T_t *type, int adjust, hid_t dxpl_id);
H5_DLL herr_t H5T_update_shared(H5T_t *type);
/* Field functions (for both compound & enumerated types) */
H5_DLL int H5T_get_nmembers(const H5T_t *dt);
H5_DLL H5T_t *H5T_get_member_type(const H5T_t *dt, unsigned membno, H5T_copy_t method);
H5_DLL size_t <API key>(const H5T_t *dt, unsigned membno);
/* Atomic functions */
H5_DLL H5T_order_t H5T_get_order(const H5T_t *dt);
H5_DLL size_t H5T_get_precision(const H5T_t *dt);
H5_DLL int H5T_get_offset(const H5T_t *dt);
/* Fixed-point functions */
H5_DLL H5T_sign_t H5T_get_sign(H5T_t const *dt);
#endif /* _H5Tprivate_H */
|
window.selectnav = (function(){
"use strict";
var selectnav = function(element,options){
element = document.getElementById(element);
// return immediately if element doesn't exist
if( ! element){
return;
}
// return immediately if element is not a list
if( ! islist(element) ){
return;
}
// return immediately if no support for insertAdjacentHTML (Firefox 7 and under)
if( ! ('insertAdjacentHTML' in window.document.documentElement) ){
return;
}
// add a js class to <html> tag
document.documentElement.className += " js";
// retreive options and set defaults
var o = options || {},
activeclass = o.activeclass || 'active',
autoselect = typeof(o.autoselect) === "boolean" ? o.autoselect : true,
nested = typeof(o.nested) === "boolean" ? o.nested : true,
indent = o.indent || "→",
label = o.label || "- Navigation -",
// helper variables
level = 0,
selected = " selected ";
// insert the freshly created dropdown navigation after the existing navigation
element.insertAdjacentHTML('afterend', parselist(element) );
var nav = document.getElementById(id());
// autoforward on click
if (nav.addEventListener) {
nav.addEventListener('change',goTo);
}
if (nav.attachEvent) {
nav.attachEvent('onchange', goTo);
}
return nav;
function goTo(e){
var targ;
if (!e) e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType === 3) // defeat Safari bug
targ = targ.parentNode;
if(targ.value) window.location.href = targ.value;
}
function islist(list){
var n = list.nodeName.toLowerCase();
return (n === 'ul' || n === 'ol');
}
function id(nextId){
for(var j=1; document.getElementById('selectnav'+j);j++);
return (nextId) ? 'selectnav'+j : 'selectnav'+(j-1);
}
function parselist(list){
// go one level down
level++;
var length = list.children.length,
html = '',
prefix = '',
k = level-1
;
// return immediately if has no children
if (!length) {
return;
}
if(k) {
while(k
prefix += indent;
}
prefix += " ";
}
for(var i=0; i < length; i++){
var link = list.children[i].children[0];
if(typeof(link) !== 'undefined'){
var text = link.innerText || link.textContent;
var isselected = '';
if(activeclass){
isselected = link.className.search(activeclass) !== -1 || link.parentNode.className.search(activeclass) !== -1 ? selected : '';
}
if(autoselect && !isselected){
isselected = link.href === document.URL ? selected : '';
}
html += '<option value="' + link.href + '" ' + isselected + '>' + prefix + text +'</option>';
if(nested){
var subElement = list.children[i].children[1];
if( subElement && islist(subElement) ){
html += parselist(subElement);
}
}
}
}
// adds label
if(level === 1 && label) {
html = '<option value="">' + label + '</option>' + html;
}
// add <select> tag to the top level of the list
if(level === 1) {
html = '<select class="selectnav" id="'+id(true)+'">' + html + '</select>';
}
// go 1 level up
level
return html;
}
};
return function (element,options) {
selectnav(element,options);
};
})();
|
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/cpu.h>
#include <linux/syscalls.h>
#include <linux/gfp.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/suspend.h>
#include <linux/syscore_ops.h>
#include <linux/rtc.h>
#include <trace/events/power.h>
#include "power.h"
const char *const pm_states[PM_SUSPEND_MAX] = {
#ifdef CONFIG_EARLYSUSPEND
[PM_SUSPEND_ON] = "on",
#endif
[PM_SUSPEND_STANDBY] = "standby",
[PM_SUSPEND_MEM] = "mem",
};
static const struct <API key> *suspend_ops;
/**
* suspend_set_ops - Set the global suspend method table.
* @ops: Suspend operations to use.
*/
void suspend_set_ops(const struct <API key> *ops)
{
lock_system_sleep();
suspend_ops = ops;
unlock_system_sleep();
}
EXPORT_SYMBOL_GPL(suspend_set_ops);
bool valid_state(suspend_state_t state)
{
/*
* All states need lowlevel support and need to be valid to the lowlevel
* implementation, no valid callback implies that none are valid.
*/
return suspend_ops && suspend_ops->valid && suspend_ops->valid(state);
}
/**
* <API key> - Generic memory-only valid callback.
*
* Platform drivers that implement mem suspend only and only need to check for
* that in their .valid() callback can use this instead of rolling their own
* .valid() callback.
*/
int <API key>(suspend_state_t state)
{
return state == PM_SUSPEND_MEM;
}
EXPORT_SYMBOL_GPL(<API key>);
static int suspend_test(int level)
{
#ifdef CONFIG_PM_DEBUG
if (pm_test_level == level) {
printk(KERN_INFO "suspend debug: Waiting for 5 seconds.\n");
mdelay(5000);
return 1;
}
#endif /* !CONFIG_PM_DEBUG */
return 0;
}
/**
* suspend_prepare - Prepare for entering system sleep state.
*
* Common code run for every system sleep state that can be entered (except for
* hibernation). Run suspend notifiers, allocate the "suspend" console and
* freeze processes.
*/
static int suspend_prepare(void)
{
int error;
if (!suspend_ops || !suspend_ops->enter)
return -EPERM;
pm_prepare_console();
error = <API key>(PM_SUSPEND_PREPARE);
if (error)
goto Finish;
error = <API key>();
if (!error)
return 0;
suspend_stats.failed_freeze++;
<API key>(SUSPEND_FREEZE);
Finish:
<API key>(PM_POST_SUSPEND);
pm_restore_console();
return error;
}
/* default implementation */
void __attribute__ ((weak)) <API key>(void)
{
local_irq_disable();
}
/* default implementation */
void __attribute__ ((weak)) <API key>(void)
{
local_irq_enable();
}
/**
* suspend_enter - Make the system enter the given sleep state.
* @state: System sleep state to enter.
* @wakeup: Returns information that the sleep state should not be re-entered.
*
* This function should be called after devices have been suspended.
*/
static int suspend_enter(suspend_state_t state, bool *wakeup)
{
int error;
if (suspend_ops->prepare) {
error = suspend_ops->prepare();
if (error)
goto Platform_finish;
}
error = dpm_suspend_end(PMSG_SUSPEND);
if (error) {
printk(KERN_ERR "PM: Some devices failed to power down\n");
goto Platform_finish;
}
if (suspend_ops->prepare_late) {
error = suspend_ops->prepare_late();
if (error)
goto Platform_wake;
}
if (suspend_test(TEST_PLATFORM))
goto Platform_wake;
error = <API key>();
if (error || suspend_test(TEST_CPUS))
goto Enable_cpus;
<API key>();
BUG_ON(!irqs_disabled());
/*add qcom debug code*/
#ifdef <API key>
print_dpm_list();
printk("print_dpm_list in suspend end\n");
#endif
error = syscore_suspend();
if (!error) {
*wakeup = pm_wakeup_pending();
if (!(suspend_test(TEST_CORE) || *wakeup)) {
error = suspend_ops->enter(state);
<API key> = false;
}
syscore_resume();
}
/*add qcom debug code*/
#ifdef <API key>
print_dpm_list();
printk("print_dpm_list in resume end\n");
#endif
<API key>();
BUG_ON(irqs_disabled());
Enable_cpus:
enable_nonboot_cpus();
Platform_wake:
if (suspend_ops->wake)
suspend_ops->wake();
dpm_resume_start(PMSG_RESUME);
Platform_finish:
if (suspend_ops->finish)
suspend_ops->finish();
return error;
}
/**
* <API key> - Suspend devices and enter system sleep state.
* @state: System sleep state to enter.
*/
int <API key>(suspend_state_t state)
{
int error;
bool wakeup = false;
if (!suspend_ops)
return -ENOSYS;
<API key>(state);
if (suspend_ops->begin) {
error = suspend_ops->begin(state);
if (error)
goto Close;
}
suspend_console();
suspend_test_start();
error = dpm_suspend_start(PMSG_SUSPEND);
if (error) {
printk(KERN_ERR "PM: Some devices failed to suspend\n");
goto Recover_platform;
}
suspend_test_finish("suspend devices");
if (suspend_test(TEST_DEVICES))
goto Recover_platform;
do {
error = suspend_enter(state, &wakeup);
} while (!error && !wakeup
&& suspend_ops->suspend_again && suspend_ops->suspend_again());
Resume_devices:
suspend_test_start();
dpm_resume_end(PMSG_RESUME);
suspend_test_finish("resume devices");
resume_console();
Close:
if (suspend_ops->end)
suspend_ops->end();
<API key>(PWR_EVENT_EXIT);
return error;
Recover_platform:
if (suspend_ops->recover)
suspend_ops->recover();
goto Resume_devices;
}
/**
* suspend_finish - Clean up before finishing the suspend sequence.
*
* Call platform code to clean up, restart processes, and free the console that
* we've allocated. This routine is not called for hibernation.
*/
static void suspend_finish(void)
{
<API key>();
<API key>(PM_POST_SUSPEND);
pm_restore_console();
}
/**
* enter_state - Do common work needed to enter system sleep state.
* @state: System sleep state to enter.
*
* Make sure that no one else is trying to put the system into a sleep state.
* Fail if that's not the case. Otherwise, prepare for system suspend, make the
* system enter the given sleep state and clean up after wakeup.
*/
static int enter_state(suspend_state_t state)
{
int error;
if (!valid_state(state))
return -ENODEV;
if (!mutex_trylock(&pm_mutex))
return -EBUSY;
<API key>();
pr_debug("PM: Preparing system for %s sleep\n", pm_states[state]);
error = suspend_prepare();
if (error)
goto Unlock;
if (suspend_test(TEST_FREEZER))
goto Finish;
pr_debug("PM: Entering %s sleep\n", pm_states[state]);
<API key>();
error = <API key>(state);
pm_restore_gfp_mask();
Finish:
pr_debug("PM: Finishing wakeup.\n");
suspend_finish();
Unlock:
mutex_unlock(&pm_mutex);
return error;
}
static void pm_suspend_marker(char *annotation)
{
struct timespec ts;
struct rtc_time tm;
getnstimeofday(&ts);
rtc_time_to_tm(ts.tv_sec, &tm);
pr_info("PM: suspend %s %d-%02d-%02d %02d:%02d:%02d.%09lu UTC\n",
annotation, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
}
/**
* pm_suspend - Externally visible function for suspending the system.
* @state: System sleep state to enter.
*
* Check if the value of @state represents one of the supported states,
* execute enter_state() and update system suspend statistics.
*/
int pm_suspend(suspend_state_t state)
{
int error;
if (state <= PM_SUSPEND_ON || state >= PM_SUSPEND_MAX)
return -EINVAL;
pm_suspend_marker("entry");
error = enter_state(state);
if (error) {
suspend_stats.fail++;
<API key>(error);
} else {
suspend_stats.success++;
}
pm_suspend_marker("exit");
return error;
}
EXPORT_SYMBOL(pm_suspend);
|
#settings-tour-modal,
#<API key> {
position: fixed;
z-index: 150000;
}
#settings-tour-modal {
background: #F9F9F9;
top: 50%;
left: 50%;
width: 1180px;
margin: -213px 0 0 -590px;
}
#settings-tour-modal #<API key> {
padding: 20px;
}
#settings-tour-modal #<API key> .left-column {
position: relative;
float: left;
width: 460px;
height: 100%;
}
#settings-tour-modal #<API key> .left-column .play-video {
top: 0;
left: 0;
width: 460px;
height: 320px;
background: url("../images/video.png") no-repeat;
position: absolute;
}
#settings-tour-modal #<API key> .left-column img {
border: 1px solid #E0E0E0;
}
#settings-tour-modal #<API key> .right-column {
float: right;
width: 640px;
height: 100%;
}
#settings-tour-modal #<API key> .right-column h2 {
font-weight: 200;
font-size: 28px;
margin: 0.4em 0 1em 0;
color: #505050;
}
#settings-tour-modal #<API key> .right-column p.step-content {
color: #6a6a6a;
font-size: 1.1em;
margin: 1em 0;
}
#settings-tour-modal #<API key> .<API key> {
margin-top: 2em;
}
#settings-tour-modal #<API key> .<API key> .form-table th {
width: 1%;
white-space: nowrap;
padding: 10px 40px 10px 0;
}
#settings-tour-modal #<API key> .<API key> .form-table td {
padding: 0;
}
#settings-tour-modal #<API key> .<API key> .description {
font-size: 0.75em;
}
#settings-tour-modal #<API key> {
background: #FFFFFF;
border-top: 1px solid #dddddd;
padding: 15px 20px;
text-align: right;
}
#settings-tour-modal #<API key> input {
display: inline-block;
margin-left: 6px;
}
#settings-tour-modal #<API key> input:active,
#settings-tour-modal #<API key> input:focus {
outline: none;
}
#settings-tour-modal #<API key> .cancel {
margin-left: 12px;
text-decoration: none;
color: #333333;
}
#settings-tour-modal #<API key> .cancel:hover {
text-decoration: underline;
}
#settings-tour-modal #<API key> .tour-progress {
float: left;
margin-top: 6px;
color: #666666;
}
#settings-tour-modal #<API key> {
margin-top: 0.75em;
float: right;
}
#settings-tour-modal .dashicons,
#settings-tour-modal .tour-next,
#settings-tour-modal .tour-previous {
cursor: pointer;
-<API key>: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#settings-tour-modal .<API key> {
margin-top: 2em;
}
#settings-tour-modal .<API key> .tour-next {
position: relative;
padding-right: 2.25em;
}
#settings-tour-modal .<API key> .tour-next .dashicons {
font-size: 1em;
display: inline;
width: auto;
height: auto;
position: absolute;
top: 50%;
right: 12px;
margin-top: -0.475em;
}
#<API key> {
background: rgba(0, 0, 0, 0.8);
top: 0;
left: 0;
width: 100%;
height: 100%;
}
|
#if !defined(lint) && defined(LIBC_SCCS)
static char rcsid[] = "$OpenBSD: gmon.c,v 1.8 1997/07/23 21:11:27 kstailey Exp $";
#endif
/*
* This file is taken from Cygwin distribution. Please keep it in sync.
* The differences should be within __MINGW32__ guard.
*/
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef __MINGW32__
#include <unistd.h>
#include <sys/param.h>
#endif
#include <sys/types.h>
#include "gmon.h"
#include "profil.h"
/* XXX needed? */
//extern char *minbrk __asm ("minbrk");
#ifdef _WIN64
#define MINUS_ONE_P (-1LL)
#else
#define MINUS_ONE_P (-1)
#endif
#include <string.h>
#define bzero(ptr,size) memset (ptr, 0, size);
struct gmonparam _gmonparam = { GMON_PROF_OFF, NULL, 0, NULL, 0, NULL, 0, 0L,
0, 0, 0, 0};
static int s_scale;
/* see profil(2) where this is describe (incorrectly) */
#define SCALE_1_TO_1 0x10000L
#define ERR(s) write(2, s, sizeof(s))
void moncontrol __P((int));
static void *
fake_sbrk(int size)
{
void *rv = malloc(size);
if (rv)
return rv;
else
return (void *) MINUS_ONE_P;
}
void monstartup (size_t, size_t);
void
monstartup (size_t lowpc, size_t highpc)
{
register size_t o;
char *cp;
struct gmonparam *p = &_gmonparam;
/*
* round lowpc and highpc to multiples of the density we're using
* so the rest of the scaling (here and in gprof) stays in ints.
*/
p->lowpc = ROUNDDOWN(lowpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->highpc = ROUNDUP(highpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->textsize = p->highpc - p->lowpc;
p->kcountsize = p->textsize / HISTFRACTION;
p->hashfraction = HASHFRACTION;
p->fromssize = p->textsize / p->hashfraction;
p->tolimit = p->textsize * ARCDENSITY / 100;
if (p->tolimit < MINARCS)
p->tolimit = MINARCS;
else if (p->tolimit > MAXARCS)
p->tolimit = MAXARCS;
p->tossize = p->tolimit * sizeof(struct tostruct);
cp = fake_sbrk(p->kcountsize + p->fromssize + p->tossize);
if (cp == (char *)MINUS_ONE_P) {
ERR("monstartup: out of memory\n");
return;
}
/* zero out cp as value will be added there */
bzero(cp, p->kcountsize + p->fromssize + p->tossize);
p->tos = (struct tostruct *)cp;
cp += p->tossize;
p->kcount = (u_short *)cp;
cp += p->kcountsize;
p->froms = (u_short *)cp;
/* XXX minbrk needed? */
//minbrk = fake_sbrk(0);
p->tos[0].link = 0;
o = p->highpc - p->lowpc;
if (p->kcountsize < o) {
#ifndef notdef
s_scale = ((float)p->kcountsize / o ) * SCALE_1_TO_1;
#else /* avoid floating point */
int quot = o / p->kcountsize;
if (quot >= 0x10000)
s_scale = 1;
else if (quot >= 0x100)
s_scale = 0x10000 / quot;
else if (o >= 0x800000)
s_scale = 0x1000000 / (o / (p->kcountsize >> 8));
else
s_scale = 0x1000000 / ((o << 8) / p->kcountsize);
#endif
} else
s_scale = SCALE_1_TO_1;
moncontrol(1);
}
void _mcleanup (void);
void
_mcleanup(void)
{
static char gmon_out[] = "gmon.out";
int fd;
int hz;
int fromindex;
int endfrom;
size_t frompc;
int toindex;
struct rawarc rawarc;
struct gmonparam *p = &_gmonparam;
struct gmonhdr gmonhdr, *hdr;
const char *proffile;
#ifdef DEBUG
int log, len;
char dbuf[200];
#endif
if (p->state == GMON_PROF_ERROR)
ERR("_mcleanup: tos overflow\n");
hz = PROF_HZ;
moncontrol(0);
#ifdef nope
if ((profdir = getenv("PROFDIR")) != NULL) {
extern char *__progname;
char *s, *t, *limit;
pid_t pid;
long divisor;
/* If PROFDIR contains a null value, no profiling
output is produced */
if (*profdir == '\0') {
return;
}
limit = buf + sizeof buf - 1 - 10 - 1 -
strlen(__progname) - 1;
t = buf;
s = profdir;
while((*t = *s) != '\0' && t < limit) {
t++;
s++;
}
*t++ = '/';
/*
* Copy and convert pid from a pid_t to a string. For
* best performance, divisor should be initialized to
* the largest power of 10 less than PID_MAX.
*/
pid = getpid();
divisor=10000;
while (divisor > pid) divisor /= 10; /* skip leading zeros */
do {
*t++ = (pid/divisor) + '0';
pid %= divisor;
} while (divisor /= 10);
*t++ = '.';
s = __progname;
while ((*t++ = *s++) != '\0')
;
proffile = buf;
} else {
proffile = gmon_out;
}
#else
proffile = gmon_out;
#endif
fd = open(proffile , O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, 0666);
if (fd < 0) {
perror( proffile );
return;
}
#ifdef DEBUG
log = open("gmon.log", O_CREAT|O_TRUNC|O_WRONLY, 0664);
if (log < 0) {
perror("mcount: gmon.log");
return;
}
len = sprintf(dbuf, "[mcleanup1] kcount 0x%x ssiz %d\n",
p->kcount, p->kcountsize);
write(log, dbuf, len);
#endif
hdr = (struct gmonhdr *)&gmonhdr;
hdr->lpc = p->lowpc;
hdr->hpc = p->highpc;
hdr->ncnt = p->kcountsize + sizeof(gmonhdr);
hdr->version = GMONVERSION;
hdr->profrate = hz;
write(fd, (char *)hdr, sizeof *hdr);
write(fd, p->kcount, p->kcountsize);
endfrom = p->fromssize / sizeof(*p->froms);
for (fromindex = 0; fromindex < endfrom; fromindex++) {
if (p->froms[fromindex] == 0)
continue;
frompc = p->lowpc;
frompc += fromindex * p->hashfraction * sizeof(*p->froms);
for (toindex = p->froms[fromindex]; toindex != 0;
toindex = p->tos[toindex].link) {
#ifdef DEBUG
len = sprintf(dbuf,
"[mcleanup2] frompc 0x%x selfpc 0x%x count %d\n" ,
frompc, p->tos[toindex].selfpc,
p->tos[toindex].count);
write(log, dbuf, len);
#endif
rawarc.raw_frompc = frompc;
rawarc.raw_selfpc = p->tos[toindex].selfpc;
rawarc.raw_count = p->tos[toindex].count;
write(fd, &rawarc, sizeof rawarc);
}
}
close(fd);
}
/*
* Control profiling
* profiling is what mcount checks to see if
* all the data structures are ready.
*/
void
moncontrol(int mode)
{
struct gmonparam *p = &_gmonparam;
if (mode) {
/* start */
profil((char *)p->kcount, p->kcountsize, p->lowpc,
s_scale);
p->state = GMON_PROF_ON;
} else {
/* stop */
profil((char *)0, 0, 0, 0);
p->state = GMON_PROF_OFF;
}
}
|
// A complex number micro parser.
// [ JDG May 10, 2002 ] spirit1
// [ JDG May 9, 2007 ] spirit2
// [ JDG May 12, 2015 ] spirit X3
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <iostream>
#include <string>
#include <complex>
// Our complex number parser/compiler
namespace client
{
template <typename Iterator>
bool parse_complex(Iterator first, Iterator last, std::complex<double>& c)
{
using boost::spirit::x3::double_;
using boost::spirit::x3::_attr;
using boost::spirit::x3::phrase_parse;
using boost::spirit::x3::ascii::space;
double rN = 0.0;
double iN = 0.0;
auto fr = [&](auto& ctx){ rN = _attr(ctx); };
auto fi = [&](auto& ctx){ iN = _attr(ctx); };
bool r = phrase_parse(first, last,
// Begin grammar
(
'(' >> double_[fr]
>> -(',' >> double_[fi]) >> ')'
| double_[fr]
),
// End grammar
space);
if (!r || first != last) // fail if we did not get a full match
return false;
c = std::complex<double>(rN, iN);
return r;
}
}
// Main program
int
main()
{
std::cout << "
std::cout << "\t\tA complex number micro parser for Spirit...\n\n";
std::cout << "
std::cout << "Give me a complex number of the form r or (r) or (r,i) \n";
std::cout << "Type [q or Q] to quit\n\n";
std::string str;
while (getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
std::complex<double> c;
if (client::parse_complex(str.begin(), str.end(), c))
{
std::cout << "
std::cout << "Parsing succeeded\n";
std::cout << "got: " << c << std::endl;
std::cout << "\n
}
else
{
std::cout << "
std::cout << "Parsing failed\n";
std::cout << "
}
}
std::cout << "Bye... :-) \n\n";
return 0;
}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import re
import sys
try:
import ssl
except ImportError: # pragma: no cover
ssl = None
if sys.version_info[0] < 3: # pragma: no cover
from StringIO import StringIO
string_types = basestring,
text_type = unicode
from types import FileType as file_type
import __builtin__ as builtins
import ConfigParser as configparser
from ._backport import shutil
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,
pathname2url, <API key>, splittype)
def quote(s):
if isinstance(s, unicode):
s = s.encode('utf-8')
return _quote(s)
import urllib2
from urllib2 import (Request, urlopen, URLError, HTTPError,
<API key>, HTTPPasswordMgr,
HTTPHandler, HTTPRedirectHandler,
build_opener)
if ssl:
from urllib2 import HTTPSHandler
import httplib
import xmlrpclib
import Queue as queue
from HTMLParser import HTMLParser
import htmlentitydefs
raw_input = raw_input
from itertools import ifilter as filter
from itertools import ifilterfalse as filterfalse
_userprog = None
def splituser(host):
"""splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
global _userprog
if _userprog is None:
import re
_userprog = re.compile('^(.*)@(.*)$')
match = _userprog.match(host)
if match: return match.group(1, 2)
return None, host
else: # pragma: no cover
from io import StringIO
string_types = str,
text_type = str
from io import TextIOWrapper as file_type
import builtins
import configparser
import shutil
from urllib.parse import (urlparse, urlunparse, urljoin, splituser, quote,
unquote, urlsplit, urlunsplit, splittype)
from urllib.request import (urlopen, urlretrieve, Request, url2pathname,
pathname2url,
<API key>, HTTPPasswordMgr,
HTTPHandler, HTTPRedirectHandler,
build_opener)
if ssl:
from urllib.request import HTTPSHandler
from urllib.error import HTTPError, URLError, <API key>
import http.client as httplib
import urllib.request as urllib2
import xmlrpc.client as xmlrpclib
import queue
from html.parser import HTMLParser
import html.entities as htmlentitydefs
raw_input = input
from itertools import filterfalse
filter = filter
try:
from ssl import match_hostname, CertificateError
except ImportError: # pragma: no cover
class CertificateError(ValueError):
pass
def _dnsname_match(dn, hostname, max_wildcards=1):
pats = []
if not dn:
return False
parts = dn.split('.')
leftmost, remainder = parts[0], parts[1:]
wildcards = leftmost.count('*')
if wildcards > max_wildcards:
# Issue #17980: avoid denials of service by refusing more
# than one wildcard per fragment. A survey of established
# policy among SSL implementations showed it to be a
# reasonable choice.
raise CertificateError(
"too many wildcards in certificate DNS name: " + repr(dn))
# speed up common case w/o wildcards
if not wildcards:
return dn.lower() == hostname.lower()
# RFC 6125, section 6.4.3, subitem 1.
# The client SHOULD NOT attempt to match a presented identifier in which
# the wildcard character comprises a label other than the left-most label.
if leftmost == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append('[^.]+')
elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
# RFC 6125, section 6.4.3, subitem 3.
# The client SHOULD NOT attempt to match a presented identifier
# where the wildcard character is embedded within an A-label or
# U-label of an internationalized domain name.
pats.append(re.escape(leftmost))
else:
# Otherwise, '*' matches any dotless string, e.g. www*
pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
# add the remaining fragments, ignore any wildcards
for frag in remainder:
pats.append(re.escape(frag))
pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
return pat.match(hostname)
def match_hostname(cert, hostname):
"""Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
rules are followed, but IP addresses are not accepted for *hostname*.
CertificateError is raised on failure. On success, the function
returns nothing.
"""
if not cert:
raise ValueError("empty or no certificate, match_hostname needs a "
"SSL socket or SSL context with either "
"CERT_OPTIONAL or CERT_REQUIRED")
dnsnames = []
san = cert.get('subjectAltName', ())
for key, value in san:
if key == 'DNS':
if _dnsname_match(value, hostname):
return
dnsnames.append(value)
if not dnsnames:
# The subject is only checked when there is no dNSName entry
# in subjectAltName
for sub in cert.get('subject', ()):
for key, value in sub:
# XXX according to RFC 2818, the most specific Common Name
# must be used.
if key == 'commonName':
if _dnsname_match(value, hostname):
return
dnsnames.append(value)
if len(dnsnames) > 1:
raise CertificateError("hostname %r "
"doesn't match either of %s"
% (hostname, ', '.join(map(repr, dnsnames))))
elif len(dnsnames) == 1:
raise CertificateError("hostname %r "
"doesn't match %r"
% (hostname, dnsnames[0]))
else:
raise CertificateError("no appropriate commonName or "
"subjectAltName fields were found")
try:
from types import SimpleNamespace as Container
except ImportError: # pragma: no cover
class Container(object):
"""
A generic container for when multiple values need to be returned
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
try:
from shutil import which
except ImportError: # pragma: no cover
# Implementation from Python 3.3
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if not os.curdir in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if not normdir in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
# ZipFile is a context manager in 2.7, but not in 2.6
from zipfile import ZipFile as BaseZipFile
if hasattr(BaseZipFile, '__enter__'): # pragma: no cover
ZipFile = BaseZipFile
else: # pragma: no cover
from zipfile import ZipExtFile as BaseZipExtFile
class ZipExtFile(BaseZipExtFile):
def __init__(self, base):
self.__dict__.update(base.__dict__)
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
# return None, so if an exception occurred, it will propagate
class ZipFile(BaseZipFile):
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
# return None, so if an exception occurred, it will propagate
def open(self, *args, **kwargs):
base = BaseZipFile.open(self, *args, **kwargs)
return ZipExtFile(base)
try:
from platform import <API key>
except ImportError: # pragma: no cover
def <API key>():
"""Return a string identifying the Python implementation."""
if 'PyPy' in sys.version:
return 'PyPy'
if os.name == 'java':
return 'Jython'
if sys.version.startswith('IronPython'):
return 'IronPython'
return 'CPython'
try:
import sysconfig
except ImportError: # pragma: no cover
from ._backport import sysconfig
try:
callable = callable
except NameError: # pragma: no cover
from collections.abc import Callable
def callable(obj):
return isinstance(obj, Callable)
try:
fsencode = os.fsencode
fsdecode = os.fsdecode
except AttributeError: # pragma: no cover
# Issue #99: on some systems (e.g. containerised),
# sys.<API key>() returns None, and we need a real value,
# so fall back to utf-8. From the CPython 2.7 docs relating to Unix and
# according to the result of nl_langinfo(CODESET), or None if the
# nl_langinfo(CODESET) failed."
_fsencoding = sys.<API key>() or 'utf-8'
if _fsencoding == 'mbcs':
_fserrors = 'strict'
else:
_fserrors = 'surrogateescape'
def fsencode(filename):
if isinstance(filename, bytes):
return filename
elif isinstance(filename, text_type):
return filename.encode(_fsencoding, _fserrors)
else:
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
def fsdecode(filename):
if isinstance(filename, text_type):
return filename
elif isinstance(filename, bytes):
return filename.decode(_fsencoding, _fserrors)
else:
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
try:
from tokenize import detect_encoding
except ImportError: # pragma: no cover
from codecs import BOM_UTF8, lookup
import re
cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)")
def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c."""
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
return "iso-8859-1"
return orig_enc
def detect_encoding(readline):
"""
The detect_encoding() function is used to detect the encoding that should
be used to decode a Python source file. It requires one argument, readline,
in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used
(as a string) and a list of any lines (left as bytes) it has read in.
It detects the encoding from the presence of a utf-8 bom or an encoding
cookie as specified in pep-0263. If both a bom and a cookie are present,
but disagree, a SyntaxError will be raised. If the encoding cookie is an
invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
'utf-8-sig' is returned.
If no encoding is specified, then the default of 'utf-8' will be returned.
"""
try:
filename = readline.__self__.name
except AttributeError:
filename = None
bom_found = False
encoding = None
default = 'utf-8'
def read_or_stop():
try:
return readline()
except StopIteration:
return b''
def find_cookie(line):
try:
# Decode as UTF-8. Either the line is an encoding declaration,
# in which case it should be pure ASCII, or it must be UTF-8
# per default encoding.
line_string = line.decode('utf-8')
except UnicodeDecodeError:
msg = "invalid or missing encoding declaration"
if filename is not None:
msg = '{} for {!r}'.format(msg, filename)
raise SyntaxError(msg)
matches = cookie_re.findall(line_string)
if not matches:
return None
encoding = _get_normal_name(matches[0])
try:
codec = lookup(encoding)
except LookupError:
# This behaviour mimics the Python interpreter
if filename is None:
msg = "unknown encoding: " + encoding
else:
msg = "unknown encoding for {!r}: {}".format(filename,
encoding)
raise SyntaxError(msg)
if bom_found:
if codec.name != 'utf-8':
# This behaviour mimics the Python interpreter
if filename is None:
msg = 'encoding problem: utf-8'
else:
msg = 'encoding problem for {!r}: utf-8'.format(filename)
raise SyntaxError(msg)
encoding += '-sig'
return encoding
first = read_or_stop()
if first.startswith(BOM_UTF8):
bom_found = True
first = first[3:]
default = 'utf-8-sig'
if not first:
return default, []
encoding = find_cookie(first)
if encoding:
return encoding, [first]
second = read_or_stop()
if not second:
return default, [first]
encoding = find_cookie(second)
if encoding:
return encoding, [first, second]
return default, [first, second]
# For converting & <-> & etc.
try:
from html import escape
except ImportError:
from cgi import escape
if sys.version_info[:2] < (3, 4):
unescape = HTMLParser().unescape
else:
from html import unescape
try:
from collections import ChainMap
except ImportError: # pragma: no cover
from collections import MutableMapping
try:
from reprlib import recursive_repr as _recursive_repr
except ImportError:
def _recursive_repr(fillvalue='...'):
'''
Decorator to make a repr function return fillvalue for a recursive
call
'''
def decorating_function(user_function):
repr_running = set()
def wrapper(self):
key = id(self), get_ident()
if key in repr_running:
return fillvalue
repr_running.add(key)
try:
result = user_function(self)
finally:
repr_running.discard(key)
return result
# Can't use functools.wraps() here because of bootstrap issues
wrapper.__module__ = getattr(user_function, '__module__')
wrapper.__doc__ = getattr(user_function, '__doc__')
wrapper.__name__ = getattr(user_function, '__name__')
wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
return wrapper
return decorating_function
class ChainMap(MutableMapping):
''' A ChainMap groups multiple dicts (or other mappings) together
to create a single, updateable view.
The underlying mappings are stored in a list. That list is public and can
accessed or updated using the *maps* attribute. There is no other state.
Lookups search the underlying mappings successively until a key is found.
In contrast, writes, updates, and deletions only operate on the first
mapping.
'''
def __init__(self, *maps):
'''Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used.
'''
self.maps = list(maps) or [{}] # always at least one map
def __missing__(self, key):
raise KeyError(key)
def __getitem__(self, key):
for mapping in self.maps:
try:
return mapping[key] # can't use 'key in mapping' with defaultdict
except KeyError:
pass
return self.__missing__(key) # support subclasses that define __missing__
def get(self, key, default=None):
return self[key] if key in self else default
def __len__(self):
return len(set().union(*self.maps)) # reuses stored hash values if possible
def __iter__(self):
return iter(set().union(*self.maps))
def __contains__(self, key):
return any(key in m for m in self.maps)
def __bool__(self):
return any(self.maps)
@_recursive_repr()
def __repr__(self):
return '{0.__class__.__name__}({1})'.format(
self, ', '.join(map(repr, self.maps)))
@classmethod
def fromkeys(cls, iterable, *args):
'Create a ChainMap with a single dict created from the iterable.'
return cls(dict.fromkeys(iterable, *args))
def copy(self):
'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
return self.__class__(self.maps[0].copy(), *self.maps[1:])
__copy__ = copy
def new_child(self): # like Django's Context.push()
'New ChainMap with a new dict followed by all previous maps.'
return self.__class__({}, *self.maps)
@property
def parents(self): # like Django's Context.pop()
'New ChainMap from maps[1:].'
return self.__class__(*self.maps[1:])
def __setitem__(self, key, value):
self.maps[0][key] = value
def __delitem__(self, key):
try:
del self.maps[0][key]
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key))
def popitem(self):
'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
try:
return self.maps[0].popitem()
except KeyError:
raise KeyError('No keys found in the first mapping.')
def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
return self.maps[0].pop(key, *args)
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key))
def clear(self):
'Clear maps[0], leaving maps[1:] intact.'
self.maps[0].clear()
try:
from importlib.util import cache_from_source # Python >= 3.4
except ImportError: # pragma: no cover
try:
from imp import cache_from_source
except ImportError: # pragma: no cover
def cache_from_source(path, debug_override=None):
assert path.endswith('.py')
if debug_override is None:
debug_override = __debug__
if debug_override:
suffix = 'c'
else:
suffix = 'o'
return path + suffix
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
pass
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as for regular dictionaries.
# The internal self.__map dictionary maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link which goes at the end of the linked
# list, and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'
root = self.__root
curr = root[1]
while curr is not root:
yield curr[2]
curr = curr[1]
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
root = self.__root
curr = root[0]
while curr is not root:
yield curr[2]
curr = curr[0]
def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except AttributeError:
pass
dict.clear(self)
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root[0]
link_prev = link[0]
link_prev[1] = root
root[0] = link_prev
else:
link = root[1]
link_next = link[1]
root[1] = link_next
link_next[0] = root
key = link[2]
del self.__map[key]
value = dict.pop(self, key)
return key, value
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self]
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) items in od'
for k in self:
yield (k, self[k])
def update(*args, **kwds):
'''od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
'''
if len(args) > 2:
raise TypeError('update() takes at most 2 positional '
'arguments (%d given)' % (len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
# Make progressively weaker assumptions about "other"
other = ()
if len(args) == 2:
other = args[1]
if isinstance(other, dict):
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
def __repr__(self, _repr_running=None):
'od.__repr__() <==> repr(od)'
if not _repr_running: _repr_running = {}
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key]
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).
'''
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
# -- the following methods are only used in Python 2.7 --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
try:
from logging.config import BaseConfigurator, valid_ident
except ImportError: # pragma: no cover
IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
def valid_ident(s):
m = IDENTIFIER.match(s)
if not m:
raise ValueError('Not a valid Python identifier: %r' % s)
return True
# The ConvertingXXX classes are wrappers around standard Python containers,
# and they serve to convert any suitable values in the container. The
# conversion converts base dicts, lists and tuples to their wrapped
# equivalents, whereas strings which match a conversion format are converted
# appropriately.
# Each wrapper should have a configurator attribute holding the actual
# configurator to use for conversion.
class ConvertingDict(dict):
"""A converting dictionary wrapper."""
def __getitem__(self, key):
value = dict.__getitem__(self, key)
result = self.configurator.convert(value)
#If the converted value is different, save for next time
if value is not result:
self[key] = result
if type(result) in (ConvertingDict, ConvertingList,
ConvertingTuple):
result.parent = self
result.key = key
return result
def get(self, key, default=None):
value = dict.get(self, key, default)
result = self.configurator.convert(value)
#If the converted value is different, save for next time
if value is not result:
self[key] = result
if type(result) in (ConvertingDict, ConvertingList,
ConvertingTuple):
result.parent = self
result.key = key
return result
def pop(self, key, default=None):
value = dict.pop(self, key, default)
result = self.configurator.convert(value)
if value is not result:
if type(result) in (ConvertingDict, ConvertingList,
ConvertingTuple):
result.parent = self
result.key = key
return result
class ConvertingList(list):
"""A converting list wrapper."""
def __getitem__(self, key):
value = list.__getitem__(self, key)
result = self.configurator.convert(value)
#If the converted value is different, save for next time
if value is not result:
self[key] = result
if type(result) in (ConvertingDict, ConvertingList,
ConvertingTuple):
result.parent = self
result.key = key
return result
def pop(self, idx=-1):
value = list.pop(self, idx)
result = self.configurator.convert(value)
if value is not result:
if type(result) in (ConvertingDict, ConvertingList,
ConvertingTuple):
result.parent = self
return result
class ConvertingTuple(tuple):
"""A converting tuple wrapper."""
def __getitem__(self, key):
value = tuple.__getitem__(self, key)
result = self.configurator.convert(value)
if value is not result:
if type(result) in (ConvertingDict, ConvertingList,
ConvertingTuple):
result.parent = self
result.key = key
return result
class BaseConfigurator(object):
"""
The configurator base class which defines some useful defaults.
"""
CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
DIGIT_PATTERN = re.compile(r'^\d+$')
value_converters = {
'ext' : 'ext_convert',
'cfg' : 'cfg_convert',
}
# We might want to use a different one, e.g. importlib
importer = staticmethod(__import__)
def __init__(self, config):
self.config = ConvertingDict(config)
self.config.configurator = self
def resolve(self, s):
"""
Resolve strings to objects using standard import and attribute
syntax.
"""
name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in name:
used += '.' + frag
try:
found = getattr(found, frag)
except AttributeError:
self.importer(used)
found = getattr(found, frag)
return found
except ImportError:
e, tb = sys.exc_info()[1:]
v = ValueError('Cannot resolve %r: %s' % (s, e))
v.__cause__, v.__traceback__ = e, tb
raise v
def ext_convert(self, value):
"""Default converter for the ext:// protocol."""
return self.resolve(value)
def cfg_convert(self, value):
"""Default converter for the cfg:// protocol."""
rest = value
m = self.WORD_PATTERN.match(rest)
if m is None:
raise ValueError("Unable to convert %r" % value)
else:
rest = rest[m.end():]
d = self.config[m.groups()[0]]
#print d, rest
while rest:
m = self.DOT_PATTERN.match(rest)
if m:
d = d[m.groups()[0]]
else:
m = self.INDEX_PATTERN.match(rest)
if m:
idx = m.groups()[0]
if not self.DIGIT_PATTERN.match(idx):
d = d[idx]
else:
try:
n = int(idx) # try as number first (most likely)
d = d[n]
except TypeError:
d = d[idx]
if m:
rest = rest[m.end():]
else:
raise ValueError('Unable to convert '
'%r at %r' % (value, rest))
#rest should be empty
return d
def convert(self, value):
"""
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
"""
if not isinstance(value, ConvertingDict) and isinstance(value, dict):
value = ConvertingDict(value)
value.configurator = self
elif not isinstance(value, ConvertingList) and isinstance(value, list):
value = ConvertingList(value)
value.configurator = self
elif not isinstance(value, ConvertingTuple) and\
isinstance(value, tuple):
value = ConvertingTuple(value)
value.configurator = self
elif isinstance(value, string_types):
m = self.CONVERT_PATTERN.match(value)
if m:
d = m.groupdict()
prefix = d['prefix']
converter = self.value_converters.get(prefix, None)
if converter:
suffix = d['suffix']
converter = getattr(self, converter)
value = converter(suffix)
return value
def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not callable(c):
c = self.resolve(c)
props = config.pop('.', None)
# Check for valid identifiers
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
result = c(**kwargs)
if props:
for name, value in props.items():
setattr(result, name, value)
return result
def as_tuple(self, value):
"""Utility function which converts lists to tuples."""
if isinstance(value, list):
value = tuple(value)
return value
|
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2013110500;
$plugin->requires = 2013110500; // Requires this Moodle version
$plugin->component = '<API key>'; // Full name of the plugin (used for diagnostics)
|
<?php
namespace Shopware\Bundle\<API key>\Struct;
/**
* Class CommentStruct
* @package Shopware\Bundle\<API key>\Struct
*/
class CommentStruct implements \JsonSerializable
{
/**
* @var string
*/
private $author;
/**
* @var string
*/
private $text;
/**
* @var string
*/
private $headline;
/**
* @var int
*/
private $rating;
/**
* @var \DateTime
*/
private $creationDate = null;
/**
* @inheritdoc
*/
public function jsonSerialize()
{
return get_object_vars($this);
}
/**
* @return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* @param string $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* @param string $text
*/
public function setText($text)
{
$this->text = $text;
}
/**
* @return string
*/
public function getHeadline()
{
return $this->headline;
}
/**
* @param string $headline
*/
public function setHeadline($headline)
{
$this->headline = $headline;
}
/**
* @return int
*/
public function getRating()
{
return $this->rating;
}
/**
* @param int $rating
*/
public function setRating($rating)
{
$this->rating = $rating;
}
/**
* @return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* @param \DateTime $creationDate
*/
public function setCreationDate(\DateTime $creationDate)
{
$this->creationDate = $creationDate;
}
}
|
#include "PresetMerge.hpp"
#include <iostream>
void PresetMerger::MergePresets(PresetOutputs & A, PresetOutputs & B, mathtype ratio, int gx, int gy)
{
mathtype invratio = mathval(1.0f) - ratio;
//Merge Simple Waveforms
// All the mess is because of Waveform 7, which is two lines.
A.wave_rot = mathmul(A.wave_rot ,invratio) + mathmul(B.wave_rot,ratio);
A.wave_scale = mathmul(A.wave_scale, invratio) + mathmul(B.wave_scale,ratio);
if (!B.draw_wave_as_loop) A.draw_wave_as_loop = false;
if (A.two_waves && B.two_waves)
{
for (int x = 0; x<A.wave_samples;x++)
{
A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio);
A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio);
A.wavearray2[x][0] = mathmul(A.wavearray2[x][0], invratio) + mathmul(B.wavearray2[x][0], ratio);
A.wavearray2[x][1] = mathmul(A.wavearray2[x][1], invratio) + mathmul(B.wavearray2[x][1], ratio);
}
}
else if (A.two_waves)
{
for (int x = 0; x<A.wave_samples;x++)
{
A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio);
A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio);
A.wavearray2[x][0] = mathmul(A.wavearray2[x][0], invratio) + mathmul(B.wavearray[x][0], ratio);
A.wavearray2[x][1] = mathmul(A.wavearray2[x][1], invratio) + mathmul(B.wavearray[x][1], ratio);
}
}
else if (B.two_waves)
{
A.two_waves=true;
for (int x = 0; x<A.wave_samples;x++)
{
A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio);
A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio);
A.wavearray2[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio);
A.wavearray2[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio);
}
}
else
{
for (int x = 0; x<A.wave_samples;x++)
{
A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio);
A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio);
}
}
//Merge Custom Shapes and Custom Waves
for (PresetOutputs::cshape_container::iterator pos = A.customShapes.begin();
pos != A.customShapes.end(); ++pos)
{
(*pos)->a = mathmul((*pos)->a, invratio);
(*pos)->a2 = mathmul((*pos)->a2, invratio);
(*pos)->border_a = mathmul((*pos)->border_a, invratio);
}
for (PresetOutputs::cshape_container::iterator pos = B.customShapes.begin();
pos != B.customShapes.end(); ++pos)
{
(*pos)->a = mathmul((*pos)->a, ratio);
(*pos)->a2 = mathmul((*pos)->a2, ratio);
(*pos)->border_a = mathmul((*pos)->border_a, ratio);
A.customShapes.push_back(*pos);
}
for (PresetOutputs::cwave_container::iterator pos = A.customWaves.begin();
pos != A.customWaves.end(); ++pos)
{
(*pos)->a = mathmul((*pos)->a, invratio);
for (int x=0; x < (*pos)->samples; x++)
{
(*pos)->a_mesh[x]= mathmul((*pos)->a_mesh[x],invratio);
}
}
for (PresetOutputs::cwave_container::iterator pos = B.customWaves.begin();
pos != B.customWaves.end(); ++pos)
{
(*pos)->a = mathmul((*pos)->a,ratio);
for (int x=0; x < (*pos)->samples; x++)
{
(*pos)->a_mesh[x]= mathmul((*pos)->a_mesh[x], ratio);
}
A.customWaves.push_back(*pos);
}
//Interpolate Per-Pixel mesh
for (int x=0;x<gx;x++)
{
for(int y=0;y<gy;y++)
{
A.x_mesh[x][y] = mathmul(A.x_mesh[x][y], invratio) + mathmul(B.x_mesh[x][y], ratio);
}
}
for (int x=0;x<gx;x++)
{
for(int y=0;y<gy;y++)
{
A.y_mesh[x][y] = mathmul(A.y_mesh[x][y], invratio) + mathmul(B.y_mesh[x][y], ratio);
}
}
//Interpolate PerFrame mathtypes
A.decay = mathmul(A.decay , invratio) + mathmul(B.decay, ratio);
A.wave_r = mathmul(A.wave_r, invratio) + mathmul(B.wave_r, ratio);
A.wave_g = mathmul(A.wave_g, invratio) + mathmul(B.wave_g, ratio);
A.wave_b = mathmul(A.wave_b, invratio) + mathmul(B.wave_b, ratio);
A.wave_o = mathmul(A.wave_o, invratio) + mathmul(B.wave_o, ratio);
A.wave_x = mathmul(A.wave_x, invratio) + mathmul(B.wave_x, ratio);
A.wave_y = mathmul(A.wave_y, invratio) + mathmul(B.wave_y, ratio);
A.wave_mystery = mathmul(A.wave_mystery, invratio) + mathmul(B.wave_mystery, ratio);
A.ob_size = mathmul(A.ob_size, invratio) + mathmul(B.ob_size, ratio);
A.ob_r = mathmul(A.ob_r, invratio) + mathmul(B.ob_r, ratio);
A.ob_g = mathmul(A.ob_g, invratio) + mathmul(B.ob_g, ratio);
A.ob_b = mathmul(A.ob_b, invratio) + mathmul(B.ob_b, ratio);
A.ob_a = mathmul(A.ob_a, invratio) + mathmul(B.ob_a, ratio);
A.ib_size = mathmul(A.ib_size, invratio) + mathmul(B.ib_size, ratio);
A.ib_r = mathmul(A.ib_r, invratio) + mathmul(B.ib_r, ratio);
A.ib_g = mathmul(A.ib_g, invratio) + mathmul(B.ib_g, ratio);
A.ib_b = mathmul(A.ib_b, invratio) + mathmul(B.ib_b, ratio);
A.ib_a = mathmul(A.ib_a, invratio) + mathmul(B.ib_a, ratio);
A.mv_a = mathmul(A.mv_a, invratio) + mathmul(B.mv_a, ratio);
A.mv_r = mathmul(A.mv_r, invratio) + mathmul(B.mv_r, ratio);
A.mv_g = mathmul(A.mv_g, invratio) + mathmul(B.mv_g, ratio);
A.mv_b = mathmul(A.mv_b, invratio) + mathmul(B.mv_b, ratio);
A.mv_l = mathmul(A.mv_l, invratio) + mathmul(B.mv_l, ratio);
A.mv_x = mathmul(A.mv_x, invratio) + mathmul(B.mv_x, ratio);
A.mv_y = mathmul(A.mv_y, invratio) + mathmul(B.mv_y, ratio);
A.mv_dy = mathmul(A.mv_dy, invratio) + mathmul(B.mv_dy, ratio);
A.mv_dx = mathmul(A.mv_dx, invratio) + mathmul(B.mv_dx, ratio);
A.fRating = mathmul(A.fRating, invratio) + mathmul(B.fRating, ratio);
A.fGammaAdj = mathmul(A.fGammaAdj, invratio) + mathmul(B.fGammaAdj, ratio);
A.fVideoEchoZoom = mathmul(A.fVideoEchoZoom, invratio) + mathmul(B.fVideoEchoZoom, ratio);
A.fVideoEchoAlpha = mathmul(A.fVideoEchoAlpha, invratio) + mathmul(B.fVideoEchoAlpha, ratio);
A.fWaveAlpha = mathmul(A.fWaveAlpha, invratio) + mathmul(B.fWaveAlpha, ratio);
A.fWaveScale = mathmul(A.fWaveScale, invratio) + mathmul(B.fWaveScale, ratio);
A.fWaveSmoothing = mathmul(A.fWaveSmoothing, invratio) + mathmul(B.fWaveSmoothing, ratio);
A.fWaveParam = mathmul(A.fWaveParam, invratio) + mathmul(B.fWaveParam, ratio);
A.fModWaveAlphaStart = mathmul(A.fModWaveAlphaStart, invratio) + mathmul(B.fModWaveAlphaStart, ratio);
A.fModWaveAlphaEnd = mathmul(A.fModWaveAlphaEnd , invratio) + mathmul(B.fModWaveAlphaEnd , ratio);
A.fWarpAnimSpeed = mathmul(A.fWarpAnimSpeed, invratio) + mathmul(B.fWarpAnimSpeed, ratio);
A.fWarpScale = mathmul(A.fWarpScale, invratio) + mathmul(B.fWarpScale, ratio);
A.fShader = mathmul(A.fShader, invratio) + mathmul(B.fShader, ratio);
//Switch bools and discrete values halfway. Maybe we should do some interesting stuff here.
if (ratio > 0.5)
{
A.<API key> = B.<API key>;
A.nWaveMode = B.nWaveMode;
A.bAdditiveWaves = B.bAdditiveWaves;
A.bWaveDots = B.bWaveDots;
A.bWaveThick = B.bWaveThick;
A.<API key> = B.<API key>;
A.bMaximizeWaveColor = B.bMaximizeWaveColor;
A.bTexWrap = B.bTexWrap;
A.bDarkenCenter = B.bDarkenCenter;
A.bRedBlueStereo = B.bRedBlueStereo;
A.bBrighten = B.bBrighten;
A.bDarken = B.bDarken;
A.bSolarize = B.bSolarize;
A.bInvert = B.bInvert;
A.bMotionVectorsOn = B.bMotionVectorsOn;
}
return;
}
|
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "index";
this.args = arguments[0] || {};
if (arguments[0]) {
{
__processArg(arguments[0], "__parentSymbol");
}
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
$.__views.index = Ti.UI.createWindow({
backgroundColor: "#fff",
fullscreen: false,
exitOnClose: true,
id: "index"
});
$.__views.index && $.addTopLevelView($.__views.index);
$.__views.__alloyId0 = Ti.UI.createLabel({
text: "This app is supported only on iOS",
id: "__alloyId0"
});
$.__views.index.add($.__views.__alloyId0);
exports.destroy = function() {};
_.extend($, $.__views);
$.index.open();
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;
|
`tf.contrib.distributions.<API key>(prior, sigma, s, n)` {#<API key>}
Posterior predictive Normal distribution w. conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `mu` (described by the Normal `prior`)
and known variance `sigma^2`. The "known sigma predictive"
is the distribution of new observations, conditioned on the existing
observations and our prior.
Accepts a prior Normal distribution object, having parameters
`mu0` and `sigma0`, as well as known `sigma` values of the predictive
distribution(s) (also assumed Normal),
and statistical estimates `s` (the sum(s) of the observations) and
`n` (the number(s) of observations).
Calculates the Normal distribution(s) `p(x | sigma^2)`:
p(x | sigma^2) = int N(x | mu, sigma^2) N(mu | prior.mu, prior.sigma^2) dmu
= N(x | prior.mu, 1/(sigma^2 + prior.sigma^2))
Returns the predictive posterior distribution object, with parameters
`(mu', sigma'^2)`, where:
sigma_n^2 = 1/(1/sigma0^2 + n/sigma^2),
mu' = (mu0/sigma0^2 + s/sigma^2) * sigma_n^2.
sigma'^2 = sigma_n^2 + sigma^2,
Distribution parameters from `prior`, as well as `sigma`, `s`, and `n`.
will broadcast in the case of multidimensional sets of parameters.
## Args:
* <b>`prior`</b>: `Normal` object of type `dtype`:
the prior distribution having parameters `(mu0, sigma0)`.
* <b>`sigma`</b>: tensor of type `dtype`, taking values `sigma > 0`.
The known stddev parameter(s).
* <b>`s`</b>: Tensor of type `dtype`. The sum(s) of observations.
* <b>`n`</b>: Tensor of type `int`. The number(s) of observations.
## Returns:
A new Normal predictive distribution object.
## Raises:
* <b>`TypeError`</b>: if dtype of `s` does not match `dtype`, or `prior` is not a
Normal object.
|
<?php
final class <API key>
extends <API key> {
public function getName() {
return pht('Policy');
}
public function getDescription() {
return pht('Options relating to object visibility.');
}
public function getFontIcon() {
return 'fa-lock';
}
public function getGroup() {
return 'apps';
}
public function getOptions() {
$policy_locked_type = 'custom:<API key>';
$<API key> = array(
'people.create.users' => 'admin',
);
$json = new PhutilJSON();
$<API key> = $json->encodeFormatted($<API key>);
return array(
$this->newOption('policy.allow-public', 'bool', false)
->setBoolOptions(
array(
pht('Allow Public Visibility'),
pht('Require Login'),
))
->setSummary(pht('Allow users to set object visibility to public.'))
->setDescription(
pht(
"Phabricator allows you to set the visibility of objects (like ".
"repositories and tasks) to 'Public', which means **anyone ".
"on the internet can see them, without needing to log in or ".
"have an account**.".
"\n\n".
"This is intended for open source projects. Many installs will ".
"never want to make anything public, so this policy is disabled ".
"by default. You can enable it here, which will let you set the ".
"policy for objects to 'Public'.".
"\n\n".
"Enabling this setting will immediately open up some features, ".
"like the user directory. Anyone on the internet will be able to ".
"access these features.".
"\n\n".
"With this setting disabled, the 'Public' policy is not ".
"available, and the most open policy is 'All Users' (which means ".
"users must have accounts and be logged in to view things).")),
$this->newOption('policy.locked', $policy_locked_type, array())
->setLocked(true)
->setSummary(pht(
'Lock specific application policies so they can not be edited.'))
->setDescription(pht(
'Phabricator has application policies which can dictate whether '.
'users can take certain actions, such as creating new users. '."\n\n".
'This setting allows for "locking" these policies such that no '.
'further edits can be made on a per-policy basis.'))
->addExample(
$<API key>,
pht('Lock Create User Policy To Admins')),
);
}
}
|
import datetime
from decimal import Decimal
import types
import six
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_unicode(strings_only=True).
"""
return isinstance(obj, (
six.integer_types +
(types.NoneType,
datetime.datetime, datetime.date, datetime.time,
float, Decimal))
)
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first, saves 30-40% when s is an instance of
# six.text_type. This function gets called often in that setting.
if isinstance(s, six.text_type):
return s
if strings_only and is_protected_type(s):
return s
try:
if not isinstance(s, six.string_types):
if hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding, errors)
else:
s = six.text_type(s)
else:
s = six.text_type(bytes(s), encoding, errors)
else:
# Note: We use .decode() here, instead of six.text_type(s,
# encoding, errors), so that if s is a SafeBytes, it ends up being
# a SafeText at the end.
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise UnicodeDecodeError(*e.args)
else:
# If we get to here, the caller has passed in an Exception
# subclass populated with non-ASCII bytestring data without a
# working unicode method. Try to handle this without raising a
# further exception by individually forcing the exception args
# to unicode.
s = ' '.join([force_unicode(arg, encoding, strings_only,
errors) for arg in s])
return s
|
#include "cpu_profile.h"
#include "cpu_profile_node.h"
namespace nodex {
using v8::Array;
using v8::CpuProfile;
using v8::CpuProfileNode;
using v8::Handle;
using v8::Number;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::ObjectTemplate;
using v8::FunctionTemplate;
using v8::String;
using v8::Function;
using v8::Value;
Nan::Persistent<ObjectTemplate> Profile::profile_template_;
Nan::Persistent<Object> Profile::profiles;
uint32_t Profile::uid_counter = 0;
NAN_METHOD(Profile_EmptyMethod) {
}
void Profile::Initialize () {
Nan::HandleScope scope;
Local<FunctionTemplate> f = Nan::New<FunctionTemplate>(Profile_EmptyMethod);
Local<ObjectTemplate> o = f->InstanceTemplate();
o-><API key>(1);
Nan::SetMethod(o, "delete", Profile::Delete);
profile_template_.Reset(o);
}
NAN_METHOD(Profile::Delete) {
Local<Object> self = info.This();
void* ptr = Nan::<API key>(self, 0);
Local<Object> profiles = Nan::New<Object>(Profile::profiles);
Local<Value> _uid = info.This()->Get(Nan::New<String>("uid").ToLocalChecked());
Local<String> uid = Nan::To<String>(_uid).ToLocalChecked();
profiles->Delete(uid);
static_cast<CpuProfile*>(ptr)->Delete();
}
Local<Value> Profile::New (const CpuProfile* node) {
Nan::<API key> scope;
if (profile_template_.IsEmpty()) {
Profile::Initialize();
}
uid_counter++;
Local<Object> profile = Nan::New(profile_template_)->NewInstance();
Nan::<API key>(profile, 0, const_cast<CpuProfile*>(node));
const uint32_t uid_length = (((sizeof uid_counter) * 8) + 2)/3 + 2;
char _uid[uid_length];
sprintf(_uid, "%d", uid_counter);
Local<Value> CPU = Nan::New<String>("CPU").ToLocalChecked();
Local<Value> uid = Nan::New<String>(_uid).ToLocalChecked();
#if (NODE_MODULE_VERSION >= 45)
Local<String> title = node->GetTitle();
#else
Local<String> title = Nan::New(node->GetTitle());
#endif
if (!title->Length()) {
char _title[8 + uid_length];
sprintf(_title, "Profile %i", uid_counter);
title = Nan::New<String>(_title).ToLocalChecked();
}
Local<Value> head = ProfileNode::New(node->GetTopDownRoot());
profile->Set(Nan::New<String>("typeId").ToLocalChecked(), CPU);
profile->Set(Nan::New<String>("uid").ToLocalChecked(), uid);
profile->Set(Nan::New<String>("title").ToLocalChecked(), title);
profile->Set(Nan::New<String>("head").ToLocalChecked(), head);
#if (NODE_MODULE_VERSION > 0x000B)
Local<Value> start_time = Nan::New<Number>(node->GetStartTime()/1000000);
Local<Value> end_time = Nan::New<Number>(node->GetEndTime()/1000000);
Local<Array> samples = Nan::New<Array>();
Local<Array> timestamps = Nan::New<Array>();
uint32_t count = node->GetSamplesCount();
for (uint32_t index = 0; index < count; ++index) {
samples->Set(index, Nan::New<Integer>(node->GetSample(index)->GetNodeId()));
timestamps->Set(index, Nan::New<Number>(static_cast<double>(node->GetSampleTimestamp(index))));
}
profile->Set(Nan::New<String>("startTime").ToLocalChecked(), start_time);
profile->Set(Nan::New<String>("endTime").ToLocalChecked(), end_time);
profile->Set(Nan::New<String>("samples").ToLocalChecked(), samples);
profile->Set(Nan::New<String>("timestamps").ToLocalChecked(), timestamps);
#endif
Local<Object> profiles = Nan::New<Object>(Profile::profiles);
profiles->Set(uid, profile);
return scope.Escape(profile);
}
}
|
#include <sstream>
#include <fnmatch.h>
#include <linux/limits.h>
#include <boost/filesystem.hpp>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include "osquery/events/linux/inotify.h"
namespace fs = boost::filesystem;
namespace osquery {
int kINotifyMLatency = 200;
static const uint32_t BUFFER_SIZE =
(10 * ((sizeof(struct inotify_event)) + NAME_MAX + 1));
std::map<int, std::string> kMaskActions = {
{IN_ACCESS, "ACCESSED"},
{IN_ATTRIB, "ATTRIBUTES_MODIFIED"},
{IN_CLOSE_WRITE, "UPDATED"},
{IN_CREATE, "CREATED"},
{IN_DELETE, "DELETED"},
{IN_MODIFY, "UPDATED"},
{IN_MOVED_FROM, "MOVED_FROM"},
{IN_MOVED_TO, "MOVED_TO"},
{IN_OPEN, "OPENED"},
};
REGISTER(<API key>, "event_publisher", "inotify");
Status <API key>::setUp() {
inotify_handle_ = ::inotify_init();
// If this does not work throw an exception.
if (inotify_handle_ == -1) {
return Status(1, "Could not start inotify: inotify_init failed");
}
return Status(0, "OK");
}
void <API key>::configure() {
for (auto& sub : subscriptions_) {
// Anytime a configure is called, try to monitor all subscriptions.
// Configure is called as a response to removing/adding subscriptions.
// This means recalculating all monitored paths.
auto sc = <API key>(sub->context);
if (sc->discovered_.size() > 0) {
continue;
}
sc->discovered_ = sc->path;
if (sc->path.find("**") != std::string::npos) {
sc->recursive = true;
sc->discovered_ = sc->path.substr(0, sc->path.find("**"));
sc->path = sc->discovered_;
}
if (sc->path.find('*') != std::string::npos) {
// If the wildcard exists within the file (leaf), remove and monitor the
// directory instead. Apply a fnmatch on fired events to filter leafs.
auto fullpath = fs::path(sc->path);
if (fullpath.filename().string().find('*') != std::string::npos) {
sc->discovered_ = fullpath.parent_path().string();
}
if (sc->discovered_.find('*') != std::string::npos) {
// If a wildcard exists within the tree (stem), resolve at configure
// time and monitor each path.
std::vector<std::string> paths;
resolveFilePattern(sc->discovered_, paths);
for (const auto& _path : paths) {
addMonitor(_path, sc->recursive);
}
sc->recursive_match = sc->recursive;
continue;
}
}
addMonitor(sc->discovered_, sc->recursive);
}
}
void <API key>::tearDown() {
::close(inotify_handle_);
inotify_handle_ = -1;
}
Status <API key>::restartMonitoring(){
if (last_restart_ != 0 && getUnixTime() - last_restart_ < 10) {
return Status(1, "Overflow");
}
last_restart_ = getUnixTime();
VLOG(1) << "inotify was overflown, attempting to restart handle";
for(const auto& desc : descriptors_){
removeMonitor(desc, 1);
}
path_descriptors_.clear();
descriptor_paths_.clear();
configure();
return Status(0, "OK");
}
Status <API key>::run() {
// Get a while wrapper for free.
char buffer[BUFFER_SIZE];
fd_set set;
FD_ZERO(&set);
FD_SET(getHandle(), &set);
struct timeval timeout = {3, 3000};
int selector = ::select(getHandle() + 1, &set, nullptr, nullptr, &timeout);
if (selector == -1) {
LOG(ERROR) << "Could not read inotify handle";
return Status(1, "INotify handle failed");
}
if (selector == 0) {
// Read timeout.
return Status(0, "Continue");
}
ssize_t record_num = ::read(getHandle(), buffer, BUFFER_SIZE);
if (record_num == 0 || record_num == -1) {
return Status(1, "INotify read failed");
}
for (char* p = buffer; p < buffer + record_num;) {
// Cast the inotify struct, make shared pointer, and append to contexts.
auto event = reinterpret_cast<struct inotify_event*>(p);
if (event->mask & IN_Q_OVERFLOW) {
// The inotify queue was overflown (remove all paths).
Status stat = restartMonitoring();
if(!stat.ok()){
return stat;
}
}
if (event->mask & IN_IGNORED) {
// This inotify watch was removed.
removeMonitor(event->wd, false);
} else if (event->mask & IN_MOVE_SELF) {
// This inotify path was moved, but is still watched.
removeMonitor(event->wd, true);
} else if (event->mask & IN_DELETE_SELF) {
// A file was moved to replace the watched path.
removeMonitor(event->wd, false);
} else {
auto ec = <API key>(event);
fire(ec);
}
// Continue to iterate
p += (sizeof(struct inotify_event)) + event->len;
}
osquery::publisherSleep(kINotifyMLatency);
return Status(0, "Continue");
}
<API key> <API key>::<API key>(
struct inotify_event* event) {
auto shared_event = std::make_shared<struct inotify_event>(*event);
auto ec = createEventContext();
ec->event = shared_event;
// Get the pathname the watch fired on.
ec->path = descriptor_paths_[event->wd];
if (event->len > 1) {
ec->path += event->name;
}
for (const auto& action : kMaskActions) {
if (event->mask & action.first) {
ec->action = action.second;
break;
}
}
return ec;
}
bool <API key>::shouldFire(const <API key>& sc,
const <API key>& ec) const {
if (sc->recursive && !sc->recursive_match) {
ssize_t found = ec->path.find(sc->path);
if (found != 0) {
return false;
}
} else if (fnmatch((sc->path + "*").c_str(),
ec->path.c_str(),
FNM_PATHNAME | FNM_CASEFOLD |
((sc->recursive_match) ? FNM_LEADING_DIR : 0)) != 0) {
// Only apply a leading-dir match if this is a recursive watch with a
// match requirement (an inline wildcard with ending recursive wildcard).
return false;
}
// The subscription may supply a required event mask.
if (sc->mask != 0 && !(ec->event->mask & sc->mask)) {
return false;
}
// inotify will not monitor recursively, new directories need watches.
if(sc->recursive && ec->action == "CREATED" && isDirectory(ec->path)){
const_cast<<API key>*>(this)->addMonitor(ec->path + '/', true);
}
return true;
}
bool <API key>::addMonitor(const std::string& path,
bool recursive) {
if (!isPathMonitored(path)) {
int watch = ::inotify_add_watch(getHandle(), path.c_str(), IN_ALL_EVENTS);
if (watch == -1) {
LOG(ERROR) << "Could not add inotify watch on: " << path;
return false;
}
// Keep a list of the watch descriptors
descriptors_.push_back(watch);
// Keep a map of the path -> watch descriptor
path_descriptors_[path] = watch;
// Keep a map of the opposite (descriptor -> path)
descriptor_paths_[watch] = path;
}
if (recursive && isDirectory(path).ok()) {
std::vector<std::string> children;
// Get a list of children of this directory (requested recursive watches).
<API key>(path, children);
for (const auto& child : children) {
addMonitor(child, recursive);
}
}
return true;
}
bool <API key>::removeMonitor(const std::string& path, bool force) {
// If force then remove from INotify, otherwise cleanup file descriptors.
if (path_descriptors_.find(path) == path_descriptors_.end()) {
return false;
}
int watch = path_descriptors_[path];
path_descriptors_.erase(path);
descriptor_paths_.erase(watch);
auto position = std::find(descriptors_.begin(), descriptors_.end(), watch);
descriptors_.erase(position);
if (force) {
::inotify_rm_watch(getHandle(), watch);
}
return true;
}
bool <API key>::removeMonitor(int watch, bool force) {
if (descriptor_paths_.find(watch) == descriptor_paths_.end()) {
return false;
}
auto path = descriptor_paths_[watch];
return removeMonitor(path, force);
}
bool <API key>::isPathMonitored(const std::string& path) {
boost::filesystem::path parent_path;
if (!isDirectory(path).ok()) {
if (path_descriptors_.find(path) != path_descriptors_.end()) {
// Path is a file, and is directly monitored.
return true;
}
if (!getDirectory(path, parent_path).ok()) {
// Could not get parent of unmonitored file.
return false;
}
} else {
parent_path = path;
}
// Directory or parent of file monitoring
auto path_iterator = path_descriptors_.find(parent_path.string());
return (path_iterator != path_descriptors_.end());
}
}
|
#include "webkit/common/gpu/<API key>.h"
#include "third_party/WebKit/public/platform/<API key>.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace webkit {
namespace gpu {
static void <API key>(
const GrGLInterface* interface) {
reinterpret_cast<WebKit::<API key>*>(
interface->fCallbackData)->makeContextCurrent();
}
<API key>::<API key>(
WebKit::<API key>* context3d) {
if (!context3d)
return;
skia::RefPtr<GrGLInterface> interface = skia::AdoptRef(
context3d->createGrGLInterface());
if (!interface)
return;
interface->fCallback = <API key>;
interface->fCallbackData =
reinterpret_cast<<API key>>(context3d);
gr_context_ = skia::AdoptRef(GrContext::Create(
kOpenGL_GrBackend,
reinterpret_cast<GrBackendContext>(interface.get())));
if (!gr_context_)
return;
bool nonzero_allocation = true;
SetMemoryLimit(nonzero_allocation);
}
<API key>::~<API key>() {
if (gr_context_)
gr_context_->contextDestroyed();
}
void <API key>::SetMemoryLimit(bool nonzero_allocation) {
if (!gr_context_)
return;
if (nonzero_allocation) {
// The limit of the number of textures we hold in the GrContext's
// bitmap->texture cache.
static const int <API key> = 2048;
// The limit of the bytes allocated toward textures in the GrContext's
// bitmap->texture cache.
static const size_t <API key> = 96 * 1024 * 1024;
gr_context_-><API key>(
<API key>, <API key>);
} else {
gr_context_->freeGpuResources();
gr_context_-><API key>(0, 0);
}
}
} // namespace gpu
} // namespace webkit
|
layout: default
author_profile: false
<div id="main" role="main">
{% include sidebar.html %}
<div class="archive">
<h1 class="page__title">{{ page.title }}</h1>
{% include base_path %}
{% for post in page.posts %}
{% include archive-single.html %}
{% endfor %}
</div>
</div>
|
CKEDITOR.plugins.setLang("placeholder","sv",{title:"Innehållsrutans egenskaper",toolbar:"Skapa innehållsruta",name:"Innehållsrutans namn",invalidName:"Innehållsrutan får inte vara tom och får inte innehålla någon av följande tecken: [, ], \x3c, \x3e",pathName:"innehållsruta"});
|
# encoding: utf-8
require 'ffaker/address'
module Faker
module AddressDE
include Faker::Address
extend ModuleUtils
extend self
def zip_code
Faker.numerify ZIP_FORMATS.rand
end
def state
STATE.rand
end
def city
CITY.rand
end
def street_name
case rand(2)
when 0 then "#{NameDE.last_name}"
when 1 then "#{NameDE.first_name}"
end << case rand(20)
when 0 then "weg"
when 1 then "gasse"
when 3 then "hain"
else "str."
end
end
def street_address
"#{street_name} #{1+rand(192)}"
end
ZIP_FORMATS = k ['
end
end
|
<?php
namespace Pagekit\Event;
interface <API key>
{
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return array
*/
public function subscribe();
}
|
get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) {
frappe.dom.freeze();
if($.isPlainObject(arg)) arg = JSON.stringify(arg);
return $c('runserverobj',
args={'method': method, 'docs': JSON.stringify(doc), 'arg': arg },
function(r, rt) {
frappe.dom.unfreeze();
if (r.message) {
var d = locals[dt][dn];
var field_dict = r.message;
for(var key in field_dict) {
d[key] = field_dict[key];
if (table_field)
refresh_field(key, d.name, table_field);
else
refresh_field(key);
}
}
if(call_back){
doc = locals[doc.doctype][doc.name];
call_back(doc, dt, dn);
}
}
);
}
set_multiple = function (dt, dn, dict, table_field) {
var d = locals[dt][dn];
for(var key in dict) {
d[key] = dict[key];
if (table_field)
refresh_field(key, d.name, table_field);
else
refresh_field(key);
}
}
refresh_many = function (flist, dn, table_field) {
for(var i in flist) {
if (table_field)
refresh_field(flist[i], dn, table_field);
else
refresh_field(flist[i]);
}
}
set_field_tip = function(n,txt) {
var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname);
if(df)df.description = txt;
if(cur_frm && cur_frm.fields_dict) {
if(cur_frm.fields_dict[n])
cur_frm.fields_dict[n].comment_area.innerHTML = replace_newlines(txt);
else
console.log('[set_field_tip] Unable to set field tip: ' + n);
}
}
refresh_field = function(n, docname, table_field) {
// multiple
if(typeof n==typeof [])
refresh_many(n, docname, table_field);
if(table_field && cur_frm.fields_dict[table_field].grid.<API key>) { // for table
cur_frm.fields_dict[table_field].grid.<API key>[docname].refresh_field(n);
} else if(cur_frm) {
cur_frm.refresh_field(n)
}
}
set_field_options = function(n, txt) {
cur_frm.set_df_property(n, 'options', txt)
}
set_field_permlevel = function(n, level) {
cur_frm.set_df_property(n, 'permlevel', level)
}
toggle_field = function(n, hidden) {
var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname);
if(df) {
df.hidden = hidden;
refresh_field(n);
}
else {
console.log((hidden ? "hide_field" : "unhide_field") + " cannot find field " + n);
}
}
hide_field = function(n) {
if(cur_frm) {
if(n.substr) toggle_field(n, 1);
else { for(var i in n) toggle_field(n[i], 1) }
}
}
unhide_field = function(n) {
if(cur_frm) {
if(n.substr) toggle_field(n, 0);
else { for(var i in n) toggle_field(n[i], 0) }
}
}
get_field_obj = function(fn) {
return cur_frm.fields_dict[fn];
}
// set missing values in given doc
set_missing_values = function(doc, dict) {
// dict contains fieldname as key and "default value" as value
var fields_to_set = {};
$.each(dict, function(i, v) { if (!doc[i]) { fields_to_set[i] = v; } });
if (fields_to_set) { set_multiple(doc.doctype, doc.name, fields_to_set); }
}
_f.Frm.prototype.get_doc = function() {
return locals[this.doctype][this.docname];
}
_f.Frm.prototype.field_map = function(fnames, fn) {
if(typeof fnames==='string') {
if(fnames == '*') {
fnames = keys(this.fields_dict);
} else {
fnames = [fnames];
}
}
$.each(fnames, function(i,fieldname) {
//var field = cur_frm.fields_dict[f]; - much better design
var field = frappe.meta.get_docfield(cur_frm.doctype, fieldname, cur_frm.docname);
if(field) {
fn(field);
cur_frm.refresh_field(fieldname);
};
})
}
_f.Frm.prototype.set_df_property = function(fieldname, property, value) {
var field = frappe.meta.get_docfield(cur_frm.doctype, fieldname, cur_frm.docname)
if(field) {
field[property] = value;
cur_frm.refresh_field(fieldname);
};
}
_f.Frm.prototype.toggle_enable = function(fnames, enable) {
cur_frm.field_map(fnames, function(field) {
field.read_only = enable ? 0 : 1; });
}
_f.Frm.prototype.toggle_reqd = function(fnames, mandatory) {
cur_frm.field_map(fnames, function(field) { field.reqd = mandatory ? true : false; });
}
_f.Frm.prototype.toggle_display = function(fnames, show) {
cur_frm.field_map(fnames, function(field) { field.hidden = show ? 0 : 1; });
}
_f.Frm.prototype.call_server = function(method, args, callback) {
return $c_obj(cur_frm.doc, method, args, callback);
}
_f.Frm.prototype.get_files = function() {
return cur_frm.attachments
? frappe.utils.sort(cur_frm.attachments.get_attachments(), "file_name", "string")
: [] ;
}
_f.Frm.prototype.set_query = function(fieldname, opt1, opt2) {
var func = (typeof opt1=="function") ? opt1 : opt2;
if(opt2) {
this.fields_dict[opt1].grid.get_field(fieldname).get_query = func;
} else {
this.fields_dict[fieldname].get_query = func;
}
}
_f.Frm.prototype.<API key> = function(field, value) {
this.set_value(field, value, true);
}
_f.Frm.prototype.set_value = function(field, value, if_missing) {
var me = this;
var _set = function(f, v) {
var fieldobj = me.fields_dict[f];
if(fieldobj) {
if(!if_missing || !frappe.model.has_value(me.doctype, me.doc.name, f)) {
if(fieldobj.df.fieldtype==="Table" && $.isArray(v)) {
frappe.model.clear_table(me.doc, fieldobj.df.fieldname);
$.each(v, function(i, d) {
var child = frappe.model.add_child(me.doc, fieldobj.df.options,
fieldobj.df.fieldname, i+1);
$.extend(child, d);
});
me.refresh_field(f);
} else {
frappe.model.set_value(me.doctype, me.doc.name, f, v);
}
}
}
}
if(typeof field=="string") {
_set(field, value)
} else if($.isPlainObject(field)) {
$.each(field, function(f, v) {
_set(f, v);
})
}
}
_f.Frm.prototype.call = function(opts) {
var me = this;
if(!opts.doc) {
if(opts.method.indexOf(".")===-1)
opts.method = frappe.model.<API key>(me.doctype) + "." + opts.method;
opts.original_callback = opts.callback;
opts.callback = function(r) {
if($.isPlainObject(r.message)) {
if(opts.child) {
// update child doc
opts.child = locals[opts.child.doctype][opts.child.name];
$.extend(opts.child, r.message);
me.fields_dict[opts.child.parentfield].refresh();
} else {
// update parent doc
me.set_value(r.message);
}
}
opts.original_callback && opts.original_callback(r);
}
} else {
opts.original_callback = opts.callback;
opts.callback = function(r) {
if(!r.exc) me.refresh_fields();
opts.original_callback && opts.original_callback(r);
}
}
return frappe.call(opts);
}
_f.Frm.prototype.get_field = function(field) {
return cur_frm.fields_dict[field];
};
_f.Frm.prototype.new_doc = function(doctype, field) {
frappe._from_link = field; frappe._from_link_scrollY = scrollY;
new_doc(doctype);
}
_f.Frm.prototype.set_read_only = function() {
var perm = [];
$.each(frappe.perm.get_perm(cur_frm.doc.doctype), function(i, p) {
perm[p.permlevel || 0] = {read:1};
});
cur_frm.perm = perm;
}
_f.Frm.prototype.get_formatted = function(fieldname) {
return frappe.format(this.doc[fieldname],
frappe.meta.get_docfield(this.doctype, fieldname, this.docname),
{no_icon:true}, this.doc);
}
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionThumbDown = (props) => (
<SvgIcon {...props}>
<path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v1.91l.01.01L1 14c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z"/>
</SvgIcon>
);
ActionThumbDown = pure(ActionThumbDown);
ActionThumbDown.displayName = 'ActionThumbDown';
ActionThumbDown.muiName = 'SvgIcon';
export default ActionThumbDown;
|
#ifndef BNX2X_CMN_H
#define BNX2X_CMN_H
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include "bnx2x.h"
/* This is used as a replacement for an MCP if it's not present */
extern int load_count[2][3]; /* per-path: 0-common, 1-port0, 2-port1 */
extern int num_queues;
#define BNX2X_PCI_FREE(x, y, size) \
do { \
if (x) { \
dma_free_coherent(&bp->pdev->dev, size, (void *)x, y); \
x = NULL; \
y = 0; \
} \
} while (0)
#define BNX2X_FREE(x) \
do { \
if (x) { \
kfree((void *)x); \
x = NULL; \
} \
} while (0)
#define BNX2X_PCI_ALLOC(x, y, size) \
do { \
x = dma_alloc_coherent(&bp->pdev->dev, size, y, GFP_KERNEL); \
if (x == NULL) \
goto alloc_mem_err; \
memset((void *)x, 0, size); \
} while (0)
#define BNX2X_ALLOC(x, size) \
do { \
x = kzalloc(size, GFP_KERNEL); \
if (x == NULL) \
goto alloc_mem_err; \
} while (0)
/* Init */
/**
* <API key> - request unload mode from the MCP.
*
* @bp: driver handle
* @unload_mode: requested function's unload mode
*
* Return unload mode returned by the MCP: COMMON, PORT or FUNC.
*/
u32 <API key>(struct bnx2x *bp, int unload_mode);
/**
* <API key> - send UNLOAD_DONE command to the MCP.
*
* @bp: driver handle
*/
void <API key>(struct bnx2x *bp);
/**
* bnx2x_config_rss_pf - configure RSS parameters.
*
* @bp: driver handle
* @ind_table: indirection table to configure
* @config_hash: re-configure RSS hash keys configuration
*/
int bnx2x_config_rss_pf(struct bnx2x *bp, u8 *ind_table, bool config_hash);
/**
* <API key> - init function object
*
* @bp: driver handle
*
* Initializes the Function Object with the appropriate
* parameters which include a function slow path driver
* interface.
*/
void <API key>(struct bnx2x *bp);
/**
* bnx2x_setup_queue - setup eth queue.
*
* @bp: driver handle
* @fp: pointer to the fastpath structure
* @leading: boolean
*
*/
int bnx2x_setup_queue(struct bnx2x *bp, struct bnx2x_fastpath *fp,
bool leading);
/**
* bnx2x_setup_leading - bring up a leading eth queue.
*
* @bp: driver handle
*/
int bnx2x_setup_leading(struct bnx2x *bp);
/**
* bnx2x_fw_command - send the MCP a request
*
* @bp: driver handle
* @command: request
* @param: request's parameter
*
* block until there is a reply
*/
u32 bnx2x_fw_command(struct bnx2x *bp, u32 command, u32 param);
/**
* <API key> - initialize link parameters structure variables.
*
* @bp: driver handle
* @load_mode: current mode
*/
u8 <API key>(struct bnx2x *bp, int load_mode);
/**
* bnx2x_link_set - configure hw according to link parameters structure.
*
* @bp: driver handle
*/
void bnx2x_link_set(struct bnx2x *bp);
/**
* bnx2x_link_test - query link status.
*
* @bp: driver handle
* @is_serdes: bool
*
* Returns 0 if link is UP.
*/
u8 bnx2x_link_test(struct bnx2x *bp, u8 is_serdes);
/**
* bnx2x_drv_pulse - write driver pulse to shmem
*
* @bp: driver handle
*
* writes the value in bp->fw_drv_pulse_wr_seq to drv_pulse mbox
* in the shmem.
*/
void bnx2x_drv_pulse(struct bnx2x *bp);
void bnx2x_igu_ack_sb(struct bnx2x *bp, u8 igu_sb_id, u8 segment,
u16 index, u8 op, u8 update);
/* Disable transactions from chip to host */
void bnx2x_pf_disable(struct bnx2x *bp);
/**
* <API key> - handles link status change.
*
* @bp: driver handle
*/
void <API key>(struct bnx2x *bp);
/**
* bnx2x_link_report - report link status to upper layer.
*
* @bp: driver handle
*/
void bnx2x_link_report(struct bnx2x *bp);
/* None-atomic version of bnx2x_link_report() */
void __bnx2x_link_report(struct bnx2x *bp);
/**
* bnx2x_get_mf_speed - calculate MF speed.
*
* @bp: driver handle
*
* Takes into account current linespeed and MF configuration.
*/
u16 bnx2x_get_mf_speed(struct bnx2x *bp);
/**
* bnx2x_msix_sp_int - MSI-X slowpath interrupt handler
*
* @irq: irq number
* @dev_instance: private instance
*/
irqreturn_t bnx2x_msix_sp_int(int irq, void *dev_instance);
/**
* bnx2x_interrupt - non MSI-X interrupt handler
*
* @irq: irq number
* @dev_instance: private instance
*/
irqreturn_t bnx2x_interrupt(int irq, void *dev_instance);
#ifdef BCM_CNIC
/**
* bnx2x_cnic_notify - send command to cnic driver
*
* @bp: driver handle
* @cmd: command
*/
int bnx2x_cnic_notify(struct bnx2x *bp, int cmd);
/**
* <API key> - provides cnic with IRQ information
*
* @bp: driver handle
*/
void <API key>(struct bnx2x *bp);
#endif
/**
* bnx2x_int_enable - enable HW interrupts.
*
* @bp: driver handle
*/
void bnx2x_int_enable(struct bnx2x *bp);
/**
* <API key> - disable interrupts.
*
* @bp: driver handle
* @disable_hw: true, disable HW interrupts.
*
* This function ensures that there are no
* ISRs or SP DPCs (sp_task) are running after it returns.
*/
void <API key>(struct bnx2x *bp, int disable_hw);
/**
* bnx2x_nic_init - init driver internals.
*
* @bp: driver handle
* @load_code: COMMON, PORT or FUNCTION
*
* Initializes:
* - rings
* - status blocks
* - etc.
*/
void bnx2x_nic_init(struct bnx2x *bp, u32 load_code);
/**
* bnx2x_alloc_mem - allocate driver's memory.
*
* @bp: driver handle
*/
int bnx2x_alloc_mem(struct bnx2x *bp);
/**
* bnx2x_free_mem - release driver's memory.
*
* @bp: driver handle
*/
void bnx2x_free_mem(struct bnx2x *bp);
/**
* <API key> - set number of queues according to mode.
*
* @bp: driver handle
*/
void <API key>(struct bnx2x *bp);
/**
* bnx2x_chip_cleanup - cleanup chip internals.
*
* @bp: driver handle
* @unload_mode: COMMON, PORT, FUNCTION
*
* - Cleanup MAC configuration.
* - Closes clients.
* - etc.
*/
void bnx2x_chip_cleanup(struct bnx2x *bp, int unload_mode);
/**
* <API key> - acquire HW lock.
*
* @bp: driver handle
* @resource: resource bit which was locked
*/
int <API key>(struct bnx2x *bp, u32 resource);
/**
* <API key> - release HW lock.
*
* @bp: driver handle
* @resource: resource bit which was locked
*/
int <API key>(struct bnx2x *bp, u32 resource);
/**
* <API key> - release recovery leader lock
*
* @bp: driver handle
*/
int <API key>(struct bnx2x *bp);
/**
* bnx2x_set_eth_mac - configure eth MAC address in the HW
*
* @bp: driver handle
* @set: set or clear
*
* Configures according to the value in netdev->dev_addr.
*/
int bnx2x_set_eth_mac(struct bnx2x *bp, bool set);
/**
* bnx2x_set_rx_mode - set MAC filtering configurations.
*
* @dev: netdevice
*
* called with netif_tx_lock from dev_mcast.c
* If bp->state is OPEN, should be called with
* netif_addr_lock_bh()
*/
void bnx2x_set_rx_mode(struct net_device *dev);
/**
* <API key> - configure MAC filtering rules in a FW.
*
* @bp: driver handle
*
* If bp->state is OPEN, should be called with
* netif_addr_lock_bh().
*/
void <API key>(struct bnx2x *bp);
/**
* bnx2x_set_q_rx_mode - configures rx_mode for a single queue.
*
* @bp: driver handle
* @cl_id: client id
* @rx_mode_flags: rx mode configuration
* @rx_accept_flags: rx accept configuration
* @tx_accept_flags: tx accept configuration (tx switch)
* @ramrod_flags: ramrod configuration
*/
void bnx2x_set_q_rx_mode(struct bnx2x *bp, u8 cl_id,
unsigned long rx_mode_flags,
unsigned long rx_accept_flags,
unsigned long tx_accept_flags,
unsigned long ramrod_flags);
/* Parity errors related */
void bnx2x_inc_load_cnt(struct bnx2x *bp);
u32 bnx2x_dec_load_cnt(struct bnx2x *bp);
bool <API key>(struct bnx2x *bp, bool *global, bool print);
bool bnx2x_reset_is_done(struct bnx2x *bp, int engine);
void <API key>(struct bnx2x *bp);
void <API key>(struct bnx2x *bp);
void <API key>(struct bnx2x *bp);
/**
* bnx2x_sp_event - handle ramrods completion.
*
* @fp: fastpath handle for the event
* @rr_cqe: eth_rx_cqe
*/
void bnx2x_sp_event(struct bnx2x_fastpath *fp, union eth_rx_cqe *rr_cqe);
/**
* bnx2x_ilt_set_info - prepare ILT configurations.
*
* @bp: driver handle
*/
void bnx2x_ilt_set_info(struct bnx2x *bp);
/**
* bnx2x_dcbx_init - initialize dcbx protocol.
*
* @bp: driver handle
*/
void bnx2x_dcbx_init(struct bnx2x *bp);
/**
* <API key> - set power state to the requested value.
*
* @bp: driver handle
* @state: required state D0 or D3hot
*
* Currently only D0 and D3hot are supported.
*/
int <API key>(struct bnx2x *bp, pci_power_t state);
/**
* <API key> - update MAX part of MF configuration in HW.
*
* @bp: driver handle
* @value: new value
*/
void <API key>(struct bnx2x *bp, u32 value);
/* Error handling */
void bnx2x_panic_dump(struct bnx2x *bp);
void bnx2x_fw_dump_lvl(struct bnx2x *bp, const char *lvl);
/* dev_close main block */
int bnx2x_nic_unload(struct bnx2x *bp, int unload_mode);
/* dev_open main block */
int bnx2x_nic_load(struct bnx2x *bp, int load_mode);
/* hard_xmit callback */
netdev_tx_t bnx2x_start_xmit(struct sk_buff *skb, struct net_device *dev);
/* setup_tc callback */
int bnx2x_setup_tc(struct net_device *dev, u8 num_tc);
/* select_queue callback */
u16 bnx2x_select_queue(struct net_device *dev, struct sk_buff *skb);
/* reload helper */
int <API key>(struct net_device *dev);
int <API key>(struct net_device *dev, void *p);
/* NAPI poll Rx part */
int bnx2x_rx_int(struct bnx2x_fastpath *fp, int budget);
void <API key>(struct bnx2x *bp, struct bnx2x_fastpath *fp,
u16 bd_prod, u16 rx_comp_prod, u16 rx_sge_prod);
/* NAPI poll Tx part */
int bnx2x_tx_int(struct bnx2x *bp, struct bnx2x_fp_txdata *txdata);
/* suspend/resume callbacks */
int bnx2x_suspend(struct pci_dev *pdev, pm_message_t state);
int bnx2x_resume(struct pci_dev *pdev);
/* Release IRQ vectors */
void bnx2x_free_irq(struct bnx2x *bp);
void bnx2x_free_fp_mem(struct bnx2x *bp);
int bnx2x_alloc_fp_mem(struct bnx2x *bp);
void bnx2x_init_rx_rings(struct bnx2x *bp);
void bnx2x_free_skbs(struct bnx2x *bp);
void bnx2x_netif_stop(struct bnx2x *bp, int disable_hw);
void bnx2x_netif_start(struct bnx2x *bp);
/**
* bnx2x_enable_msix - set msix configuration.
*
* @bp: driver handle
*
* fills msix_table, requests vectors, updates num_queues
* according to number of available vectors.
*/
int bnx2x_enable_msix(struct bnx2x *bp);
/**
* bnx2x_enable_msi - request msi mode from OS, updated internals accordingly
*
* @bp: driver handle
*/
int bnx2x_enable_msi(struct bnx2x *bp);
/**
* bnx2x_poll - NAPI callback
*
* @napi: napi structure
* @budget:
*
*/
int bnx2x_poll(struct napi_struct *napi, int budget);
/**
* bnx2x_alloc_mem_bp - allocate memories outsize main driver structure
*
* @bp: driver handle
*/
int __devinit bnx2x_alloc_mem_bp(struct bnx2x *bp);
/**
* bnx2x_free_mem_bp - release memories outsize main driver structure
*
* @bp: driver handle
*/
void bnx2x_free_mem_bp(struct bnx2x *bp);
/**
* bnx2x_change_mtu - change mtu netdev callback
*
* @dev: net device
* @new_mtu: requested mtu
*
*/
int bnx2x_change_mtu(struct net_device *dev, int new_mtu);
#if defined(NETDEV_FCOE_WWNN) && defined(BCM_CNIC)
/**
* bnx2x_fcoe_get_wwn - return the requested WWN value for this port
*
* @dev: net_device
* @wwn: output buffer
* @type: WWN type: NETDEV_FCOE_WWNN (node) or NETDEV_FCOE_WWPN (port)
*
*/
int bnx2x_fcoe_get_wwn(struct net_device *dev, u64 *wwn, int type);
#endif
netdev_features_t bnx2x_fix_features(struct net_device *dev,
netdev_features_t features);
int bnx2x_set_features(struct net_device *dev, netdev_features_t features);
/**
* bnx2x_tx_timeout - tx timeout netdev callback
*
* @dev: net device
*/
void bnx2x_tx_timeout(struct net_device *dev);
static inline void <API key>(struct bnx2x_fastpath *fp)
{
barrier(); /* status block is written to by the chip */
fp->fp_hc_idx = fp->sb_running_index[SM_RX_ID];
}
static inline void <API key>(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 bd_prod,
u16 rx_comp_prod, u16 rx_sge_prod, u32 start)
{
struct <API key> rx_prods = {0};
u32 i;
/* Update producers */
rx_prods.bd_prod = bd_prod;
rx_prods.cqe_prod = rx_comp_prod;
rx_prods.sge_prod = rx_sge_prod;
/*
* Make sure that the BD and SGE data is updated before updating the
* producers since FW might read the BD/SGE right after the producer
* is updated.
* This is only applicable for weak-ordered memory model archs such
* as IA-64. The following barrier is also mandatory since FW will
* assumes BDs must have buffers.
*/
wmb();
for (i = 0; i < sizeof(rx_prods)/4; i++)
REG_WR(bp, start + i*4, ((u32 *)&rx_prods)[i]);
mmiowb(); /* keep prod updates ordered */
DP(NETIF_MSG_RX_STATUS,
"queue[%d]: wrote bd_prod %u cqe_prod %u sge_prod %u\n",
fp->index, bd_prod, rx_comp_prod, rx_sge_prod);
}
static inline void <API key>(struct bnx2x *bp, u8 igu_sb_id,
u8 segment, u16 index, u8 op,
u8 update, u32 igu_addr)
{
struct igu_regular cmd_data = {0};
cmd_data.sb_id_and_flags =
((index << <API key>) |
(segment << <API key>) |
(update << <API key>) |
(op << <API key>));
DP(NETIF_MSG_HW, "write 0x%08x to IGU addr 0x%x\n",
cmd_data.sb_id_and_flags, igu_addr);
REG_WR(bp, igu_addr, cmd_data.sb_id_and_flags);
/* Make sure that ACK is written */
mmiowb();
barrier();
}
static inline void <API key>(struct bnx2x *bp, u8 func,
u8 idu_sb_id, bool is_Pf)
{
u32 data, ctl, cnt = 100;
u32 igu_addr_data = <API key>;
u32 igu_addr_ctl = <API key>;
u32 igu_addr_ack = <API key> + (idu_sb_id/32)*4;
u32 sb_bit = 1 << (idu_sb_id%32);
u32 func_encode = func |
((is_Pf == true ? 1 : 0) << <API key>);
u32 addr_encode = <API key> + idu_sb_id;
/* Not supported in BC mode */
if (CHIP_INT_MODE_IS_BC(bp))
return;
data = (<API key>
<< <API key>) |
<API key> |
<API key>;
ctl = addr_encode << <API key> |
func_encode << <API key> |
<API key> << <API key>;
DP(NETIF_MSG_HW, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
data, igu_addr_data);
REG_WR(bp, igu_addr_data, data);
mmiowb();
barrier();
DP(NETIF_MSG_HW, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
ctl, igu_addr_ctl);
REG_WR(bp, igu_addr_ctl, ctl);
mmiowb();
barrier();
/* wait for clean up to finish */
while (!(REG_RD(bp, igu_addr_ack) & sb_bit) && --cnt)
msleep(20);
if (!(REG_RD(bp, igu_addr_ack) & sb_bit)) {
DP(NETIF_MSG_HW, "Unable to finish IGU cleanup: "
"idu_sb_id %d offset %d bit %d (cnt %d)\n",
idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
}
}
static inline void bnx2x_hc_ack_sb(struct bnx2x *bp, u8 sb_id,
u8 storm, u16 index, u8 op, u8 update)
{
u32 hc_addr = (HC_REG_COMMAND_REG + BP_PORT(bp)*32 +
COMMAND_REG_INT_ACK);
struct igu_ack_register igu_ack;
igu_ack.status_block_index = index;
igu_ack.sb_id_and_flags =
((sb_id << <API key>) |
(storm << <API key>) |
(update << <API key>) |
(op << <API key>));
DP(BNX2X_MSG_OFF, "write 0x%08x to HC addr 0x%x\n",
(*(u32 *)&igu_ack), hc_addr);
REG_WR(bp, hc_addr, (*(u32 *)&igu_ack));
/* Make sure that ACK is written */
mmiowb();
barrier();
}
static inline void bnx2x_ack_sb(struct bnx2x *bp, u8 igu_sb_id, u8 storm,
u16 index, u8 op, u8 update)
{
if (bp->common.int_block == INT_BLOCK_HC)
bnx2x_hc_ack_sb(bp, igu_sb_id, storm, index, op, update);
else {
u8 segment;
if (CHIP_INT_MODE_IS_BC(bp))
segment = storm;
else if (igu_sb_id != bp->igu_dsb_id)
segment = IGU_SEG_ACCESS_DEF;
else if (storm == ATTENTION_ID)
segment = IGU_SEG_ACCESS_ATTN;
else
segment = IGU_SEG_ACCESS_DEF;
bnx2x_igu_ack_sb(bp, igu_sb_id, segment, index, op, update);
}
}
static inline u16 bnx2x_hc_ack_int(struct bnx2x *bp)
{
u32 hc_addr = (HC_REG_COMMAND_REG + BP_PORT(bp)*32 +
<API key>);
u32 result = REG_RD(bp, hc_addr);
DP(BNX2X_MSG_OFF, "read 0x%08x from HC addr 0x%x\n",
result, hc_addr);
barrier();
return result;
}
static inline u16 bnx2x_igu_ack_int(struct bnx2x *bp)
{
u32 igu_addr = (BAR_IGU_INTMEM + <API key>*8);
u32 result = REG_RD(bp, igu_addr);
DP(NETIF_MSG_HW, "read 0x%08x from IGU addr 0x%x\n",
result, igu_addr);
barrier();
return result;
}
static inline u16 bnx2x_ack_int(struct bnx2x *bp)
{
barrier();
if (bp->common.int_block == INT_BLOCK_HC)
return bnx2x_hc_ack_int(bp);
else
return bnx2x_igu_ack_int(bp);
}
static inline int <API key>(struct bnx2x_fp_txdata *txdata)
{
/* Tell compiler that consumer and producer can change */
barrier();
return txdata->tx_pkt_prod != txdata->tx_pkt_cons;
}
static inline u16 bnx2x_tx_avail(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata)
{
s16 used;
u16 prod;
u16 cons;
prod = txdata->tx_bd_prod;
cons = txdata->tx_bd_cons;
/* NUM_TX_RINGS = number of "next-page" entries
It will be used as a threshold */
used = SUB_S16(prod, cons) + (s16)NUM_TX_RINGS;
#ifdef BNX2X_STOP_ON_ERROR
WARN_ON(used < 0);
WARN_ON(used > bp->tx_ring_size);
WARN_ON((bp->tx_ring_size - used) > MAX_TX_AVAIL);
#endif
return (s16)(bp->tx_ring_size) - used;
}
static inline int <API key>(struct bnx2x_fp_txdata *txdata)
{
u16 hw_cons;
/* Tell compiler that status block fields can change */
barrier();
hw_cons = le16_to_cpu(*txdata->tx_cons_sb);
return hw_cons != txdata->tx_pkt_cons;
}
static inline bool bnx2x_has_tx_work(struct bnx2x_fastpath *fp)
{
u8 cos;
<API key>(fp, cos)
if (<API key>(&fp->txdata[cos]))
return true;
return false;
}
static inline int bnx2x_has_rx_work(struct bnx2x_fastpath *fp)
{
u16 rx_cons_sb;
/* Tell compiler that status block fields can change */
barrier();
rx_cons_sb = le16_to_cpu(*fp->rx_cons_sb);
if ((rx_cons_sb & MAX_RCQ_DESC_CNT) == MAX_RCQ_DESC_CNT)
rx_cons_sb++;
return (fp->rx_comp_cons != rx_cons_sb);
}
/**
* bnx2x_tx_disable - disables tx from stack point of view
*
* @bp: driver handle
*/
static inline void bnx2x_tx_disable(struct bnx2x *bp)
{
netif_tx_disable(bp->dev);
netif_carrier_off(bp->dev);
}
static inline void bnx2x_free_rx_sge(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
struct sw_rx_page *sw_buf = &fp->rx_page_ring[index];
struct page *page = sw_buf->page;
struct eth_rx_sge *sge = &fp->rx_sge_ring[index];
/* Skip "next page" elements */
if (!page)
return;
dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(sw_buf, mapping),
SGE_PAGE_SIZE*PAGES_PER_SGE, DMA_FROM_DEVICE);
__free_pages(page, PAGES_PER_SGE_SHIFT);
sw_buf->page = NULL;
sge->addr_hi = 0;
sge->addr_lo = 0;
}
static inline void bnx2x_add_all_napi(struct bnx2x *bp)
{
int i;
/* Add NAPI objects */
for_each_rx_queue(bp, i)
netif_napi_add(bp->dev, &bnx2x_fp(bp, i, napi),
bnx2x_poll, BNX2X_NAPI_WEIGHT);
}
static inline void bnx2x_del_all_napi(struct bnx2x *bp)
{
int i;
for_each_rx_queue(bp, i)
netif_napi_del(&bnx2x_fp(bp, i, napi));
}
static inline void bnx2x_disable_msi(struct bnx2x *bp)
{
if (bp->flags & USING_MSIX_FLAG) {
pci_disable_msix(bp->pdev);
bp->flags &= ~USING_MSIX_FLAG;
} else if (bp->flags & USING_MSI_FLAG) {
pci_disable_msi(bp->pdev);
bp->flags &= ~USING_MSI_FLAG;
}
}
static inline int <API key>(struct bnx2x *bp)
{
return num_queues ?
min_t(int, num_queues, BNX2X_MAX_QUEUES(bp)) :
min_t(int, num_online_cpus(), BNX2X_MAX_QUEUES(bp));
}
static inline void <API key>(struct bnx2x_fastpath *fp)
{
int i, j;
for (i = 1; i <= NUM_RX_SGE_PAGES; i++) {
int idx = RX_SGE_CNT * i - 1;
for (j = 0; j < 2; j++) {
BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
idx
}
}
}
static inline void <API key>(struct bnx2x_fastpath *fp)
{
/* Set the mask to all 1-s: it's faster to compare to 0 than to 0xf-s */
memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
/* Clear the two last indices in the page to 1:
these are the indices that correspond to the "next" element,
hence will never be indicated and should be removed from
the calculations. */
<API key>(fp);
}
static inline int bnx2x_alloc_rx_sge(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
struct page *page = alloc_pages(GFP_ATOMIC, PAGES_PER_SGE_SHIFT);
struct sw_rx_page *sw_buf = &fp->rx_page_ring[index];
struct eth_rx_sge *sge = &fp->rx_sge_ring[index];
dma_addr_t mapping;
if (unlikely(page == NULL))
return -ENOMEM;
mapping = dma_map_page(&bp->pdev->dev, page, 0,
SGE_PAGE_SIZE*PAGES_PER_SGE, DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
__free_pages(page, PAGES_PER_SGE_SHIFT);
return -ENOMEM;
}
sw_buf->page = page;
dma_unmap_addr_set(sw_buf, mapping, mapping);
sge->addr_hi = cpu_to_le32(U64_HI(mapping));
sge->addr_lo = cpu_to_le32(U64_LO(mapping));
return 0;
}
static inline int bnx2x_alloc_rx_data(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
u8 *data;
struct sw_rx_bd *rx_buf = &fp->rx_buf_ring[index];
struct eth_rx_bd *rx_bd = &fp->rx_desc_ring[index];
dma_addr_t mapping;
data = kmalloc(fp->rx_buf_size + NET_SKB_PAD, GFP_ATOMIC);
if (unlikely(data == NULL))
return -ENOMEM;
mapping = dma_map_single(&bp->pdev->dev, data + NET_SKB_PAD,
fp->rx_buf_size,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
kfree(data);
return -ENOMEM;
}
rx_buf->data = data;
dma_unmap_addr_set(rx_buf, mapping, mapping);
rx_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
rx_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
return 0;
}
/* note that we are not allocating a new buffer,
* we are just moving one from cons to prod
* we are not creating a new mapping,
* so there is no need to check for dma_mapping_error().
*/
static inline void bnx2x_reuse_rx_data(struct bnx2x_fastpath *fp,
u16 cons, u16 prod)
{
struct sw_rx_bd *cons_rx_buf = &fp->rx_buf_ring[cons];
struct sw_rx_bd *prod_rx_buf = &fp->rx_buf_ring[prod];
struct eth_rx_bd *cons_bd = &fp->rx_desc_ring[cons];
struct eth_rx_bd *prod_bd = &fp->rx_desc_ring[prod];
dma_unmap_addr_set(prod_rx_buf, mapping,
dma_unmap_addr(cons_rx_buf, mapping));
prod_rx_buf->data = cons_rx_buf->data;
*prod_bd = *cons_bd;
}
/**
* bnx2x_func_start - init function
*
* @bp: driver handle
*
* Must be called before sending CLIENT_SETUP for the first client.
*/
static inline int bnx2x_func_start(struct bnx2x *bp)
{
struct <API key> func_params = {0};
struct <API key> *start_params =
&func_params.params.start;
/* Prepare parameters for function state transitions */
__set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
func_params.f_obj = &bp->func_obj;
func_params.cmd = BNX2X_F_CMD_START;
/* Function parameters */
start_params->mf_mode = bp->mf_mode;
start_params->sd_vlan_tag = bp->mf_ov;
if (CHIP_IS_E1x(bp))
start_params->network_cos_mode = OVERRIDE_COS;
else
start_params->network_cos_mode = STATIC_COS;
return <API key>(bp, &func_params);
}
/**
* <API key> - fill in a MAC address in FW format
*
* @fw_hi: pointer to upper part
* @fw_mid: pointer to middle part
* @fw_lo: pointer to lower part
* @mac: pointer to MAC address
*/
static inline void <API key>(u16 *fw_hi, u16 *fw_mid, u16 *fw_lo,
u8 *mac)
{
((u8 *)fw_hi)[0] = mac[1];
((u8 *)fw_hi)[1] = mac[0];
((u8 *)fw_mid)[0] = mac[3];
((u8 *)fw_mid)[1] = mac[2];
((u8 *)fw_lo)[0] = mac[5];
((u8 *)fw_lo)[1] = mac[4];
}
static inline void <API key>(struct bnx2x *bp,
struct bnx2x_fastpath *fp, int last)
{
int i;
if (fp->disable_tpa)
return;
for (i = 0; i < last; i++)
bnx2x_free_rx_sge(bp, fp, i);
}
static inline void bnx2x_free_tpa_pool(struct bnx2x *bp,
struct bnx2x_fastpath *fp, int last)
{
int i;
for (i = 0; i < last; i++) {
struct bnx2x_agg_info *tpa_info = &fp->tpa_info[i];
struct sw_rx_bd *first_buf = &tpa_info->first_buf;
u8 *data = first_buf->data;
if (data == NULL) {
DP(NETIF_MSG_IFDOWN, "tpa bin %d empty on free\n", i);
continue;
}
if (tpa_info->tpa_state == BNX2X_TPA_START)
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(first_buf, mapping),
fp->rx_buf_size, DMA_FROM_DEVICE);
kfree(data);
first_buf->data = NULL;
}
}
static inline void <API key>(struct bnx2x_fp_txdata *txdata)
{
int i;
for (i = 1; i <= NUM_TX_RINGS; i++) {
struct eth_tx_next_bd *tx_next_bd =
&txdata->tx_desc_ring[TX_DESC_CNT * i - 1].next_bd;
tx_next_bd->addr_hi =
cpu_to_le32(U64_HI(txdata->tx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_TX_RINGS)));
tx_next_bd->addr_lo =
cpu_to_le32(U64_LO(txdata->tx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_TX_RINGS)));
}
SET_FLAG(txdata->tx_db.data.header.header, <API key>, 1);
txdata->tx_db.data.zero_fill1 = 0;
txdata->tx_db.data.prod = 0;
txdata->tx_pkt_prod = 0;
txdata->tx_pkt_cons = 0;
txdata->tx_bd_prod = 0;
txdata->tx_bd_cons = 0;
txdata->tx_pkt = 0;
}
static inline void bnx2x_init_tx_rings(struct bnx2x *bp)
{
int i;
u8 cos;
for_each_tx_queue(bp, i)
<API key>(&bp->fp[i], cos)
<API key>(&bp->fp[i].txdata[cos]);
}
static inline void <API key>(struct bnx2x_fastpath *fp)
{
int i;
for (i = 1; i <= NUM_RX_RINGS; i++) {
struct eth_rx_bd *rx_bd;
rx_bd = &fp->rx_desc_ring[RX_DESC_CNT * i - 2];
rx_bd->addr_hi =
cpu_to_le32(U64_HI(fp->rx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_RINGS)));
rx_bd->addr_lo =
cpu_to_le32(U64_LO(fp->rx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_RINGS)));
}
}
static inline void <API key>(struct bnx2x_fastpath *fp)
{
int i;
for (i = 1; i <= NUM_RX_SGE_PAGES; i++) {
struct eth_rx_sge *sge;
sge = &fp->rx_sge_ring[RX_SGE_CNT * i - 2];
sge->addr_hi =
cpu_to_le32(U64_HI(fp->rx_sge_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_SGE_PAGES)));
sge->addr_lo =
cpu_to_le32(U64_LO(fp->rx_sge_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_SGE_PAGES)));
}
}
static inline void <API key>(struct bnx2x_fastpath *fp)
{
int i;
for (i = 1; i <= NUM_RCQ_RINGS; i++) {
struct <API key> *nextpg;
nextpg = (struct <API key> *)
&fp->rx_comp_ring[RCQ_DESC_CNT * i - 1];
nextpg->addr_hi =
cpu_to_le32(U64_HI(fp->rx_comp_mapping +
BCM_PAGE_SIZE*(i % NUM_RCQ_RINGS)));
nextpg->addr_lo =
cpu_to_le32(U64_LO(fp->rx_comp_mapping +
BCM_PAGE_SIZE*(i % NUM_RCQ_RINGS)));
}
}
/* Returns the number of actually allocated BDs */
static inline int bnx2x_alloc_rx_bds(struct bnx2x_fastpath *fp,
int rx_ring_size)
{
struct bnx2x *bp = fp->bp;
u16 ring_prod, cqe_ring_prod;
int i;
fp->rx_comp_cons = 0;
cqe_ring_prod = ring_prod = 0;
/* This routine is called only during fo init so
* fp->eth_q_stats.rx_skb_alloc_failed = 0
*/
for (i = 0; i < rx_ring_size; i++) {
if (bnx2x_alloc_rx_data(bp, fp, ring_prod) < 0) {
fp->eth_q_stats.rx_skb_alloc_failed++;
continue;
}
ring_prod = NEXT_RX_IDX(ring_prod);
cqe_ring_prod = NEXT_RCQ_IDX(cqe_ring_prod);
WARN_ON(ring_prod <= (i - fp->eth_q_stats.rx_skb_alloc_failed));
}
if (fp->eth_q_stats.rx_skb_alloc_failed)
BNX2X_ERR("was only able to allocate "
"%d rx skbs on queue[%d]\n",
(i - fp->eth_q_stats.rx_skb_alloc_failed), fp->index);
fp->rx_bd_prod = ring_prod;
/* Limit the CQE producer by the CQE ring size */
fp->rx_comp_prod = min_t(u16, NUM_RCQ_RINGS*RCQ_DESC_CNT,
cqe_ring_prod);
fp->rx_pkt = fp->rx_calls = 0;
return i - fp->eth_q_stats.rx_skb_alloc_failed;
}
/* Statistics ID are global per chip/path, while Client IDs for E1x are per
* port.
*/
static inline u8 bnx2x_stats_id(struct bnx2x_fastpath *fp)
{
struct bnx2x *bp = fp->bp;
if (!CHIP_IS_E1x(bp)) {
#ifdef BCM_CNIC
/* there are special statistics counters for FCoE 136..140 */
if (IS_FCOE_FP(fp))
return bp->cnic_base_cl_id + (bp->pf_num >> 1);
#endif
return fp->cl_id;
}
return fp->cl_id + BP_PORT(bp) * FP_SB_MAX_E1x;
}
static inline void <API key>(struct bnx2x_fastpath *fp,
bnx2x_obj_type obj_type)
{
struct bnx2x *bp = fp->bp;
/* Configure classification DBs */
bnx2x_init_mac_obj(bp, &fp->mac_obj, fp->cl_id, fp->cid,
BP_FUNC(bp), bnx2x_sp(bp, mac_rdata),
bnx2x_sp_mapping(bp, mac_rdata),
<API key>,
&bp->sp_state, obj_type,
&bp->macs_pool);
}
/**
* <API key> - get number of active functions
*
* @bp: driver handle
*
* Calculates the number of active (not hidden) functions on the
* current path.
*/
static inline u8 <API key>(struct bnx2x *bp)
{
u8 func_num = 0, i;
/* 57710 has only one function per-port */
if (CHIP_IS_E1(bp))
return 1;
/* Calculate a number of functions enabled on the current
* PATH/PORT.
*/
if (CHIP_REV_IS_SLOW(bp)) {
if (IS_MF(bp))
func_num = 4;
else
func_num = 2;
} else {
for (i = 0; i < E1H_FUNC_MAX / 2; i++) {
u32 func_config =
MF_CFG_RD(bp,
func_mf_config[BP_PORT(bp) + 2 * i].
config);
func_num +=
((func_config & <API key>) ? 0 : 1);
}
}
WARN_ON(!func_num);
return func_num;
}
static inline void bnx2x_init_bp_objs(struct bnx2x *bp)
{
/* RX_MODE controlling object */
<API key>(bp, &bp->rx_mode_obj);
/* multicast configuration controlling object */
<API key>(bp, &bp->mcast_obj, bp->fp->cl_id, bp->fp->cid,
BP_FUNC(bp), BP_FUNC(bp),
bnx2x_sp(bp, mcast_rdata),
bnx2x_sp_mapping(bp, mcast_rdata),
<API key>, &bp->sp_state,
BNX2X_OBJ_TYPE_RX);
/* Setup CAM credit pools */
<API key>(bp, &bp->macs_pool, BP_FUNC(bp),
<API key>(bp));
/* RSS configuration object */
<API key>(bp, &bp->rss_conf_obj, bp->fp->cl_id,
bp->fp->cid, BP_FUNC(bp), BP_FUNC(bp),
bnx2x_sp(bp, rss_rdata),
bnx2x_sp_mapping(bp, rss_rdata),
<API key>, &bp->sp_state,
BNX2X_OBJ_TYPE_RX);
}
static inline u8 bnx2x_fp_qzone_id(struct bnx2x_fastpath *fp)
{
if (CHIP_IS_E1x(fp->bp))
return fp->cl_id + BP_PORT(fp->bp) * <API key>;
else
return fp->cl_id;
}
static inline u32 <API key>(struct bnx2x_fastpath *fp)
{
struct bnx2x *bp = fp->bp;
if (!CHIP_IS_E1x(bp))
return <API key>(fp->cl_qzone_id);
else
return <API key>(BP_PORT(bp), fp->cl_id);
}
static inline void bnx2x_init_txdata(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata, u32 cid, int txq_index,
__le16 *tx_cons_sb)
{
txdata->cid = cid;
txdata->txq_index = txq_index;
txdata->tx_cons_sb = tx_cons_sb;
DP(BNX2X_MSG_SP, "created tx data cid %d, txq %d\n",
txdata->cid, txdata->txq_index);
}
#ifdef BCM_CNIC
static inline u8 <API key>(struct bnx2x *bp, u8 cl_idx)
{
return bp->cnic_base_cl_id + cl_idx +
(bp->pf_num >> 1) * <API key>;
}
static inline u8 bnx2x_cnic_fw_sb_id(struct bnx2x *bp)
{
/* the 'first' id is allocated for the cnic */
return bp->base_fw_ndsb;
}
static inline u8 <API key>(struct bnx2x *bp)
{
return bp->igu_base_sb;
}
static inline void bnx2x_init_fcoe_fp(struct bnx2x *bp)
{
struct bnx2x_fastpath *fp = bnx2x_fcoe_fp(bp);
unsigned long q_type = 0;
bnx2x_fcoe(bp, rx_queue) = <API key>(bp);
bnx2x_fcoe(bp, cl_id) = <API key>(bp,
<API key>);
/** Current BNX2X_FCOE_ETH_CID deffinition implies not more than
* 16 ETH clients per function when CNIC is enabled!
*
* Fix it ASAP!!!
*/
bnx2x_fcoe(bp, cid) = BNX2X_FCOE_ETH_CID;
bnx2x_fcoe(bp, fw_sb_id) = DEF_SB_ID;
bnx2x_fcoe(bp, igu_sb_id) = bp->igu_dsb_id;
bnx2x_fcoe(bp, rx_cons_sb) = <API key>;
bnx2x_init_txdata(bp, &bnx2x_fcoe(bp, txdata[0]),
fp->cid, FCOE_TXQ_IDX(bp), <API key>);
DP(BNX2X_MSG_SP, "created fcoe tx data (fp index %d)\n", fp->index);
/* qZone id equals to FW (per path) client id */
bnx2x_fcoe(bp, cl_qzone_id) = bnx2x_fp_qzone_id(fp);
/* init shortcut */
bnx2x_fcoe(bp, <API key>) =
<API key>(fp);
/* Configure Queue State object */
__set_bit(BNX2X_Q_TYPE_HAS_RX, &q_type);
__set_bit(BNX2X_Q_TYPE_HAS_TX, &q_type);
/* No multi-CoS for FCoE L2 client */
BUG_ON(fp->max_cos != 1);
<API key>(bp, &fp->q_obj, fp->cl_id, &fp->cid, 1,
BP_FUNC(bp), bnx2x_sp(bp, q_rdata),
bnx2x_sp_mapping(bp, q_rdata), q_type);
DP(NETIF_MSG_IFUP, "queue[%d]: bnx2x_init_sb(%p,%p) cl_id %d fw_sb %d "
"igu_sb %d\n",
fp->index, bp, fp->status_blk.e2_sb, fp->cl_id, fp->fw_sb_id,
fp->igu_sb_id);
}
#endif
static inline int <API key>(struct bnx2x *bp,
struct bnx2x_fp_txdata *txdata)
{
int cnt = 1000;
while (<API key>(txdata)) {
if (!cnt) {
BNX2X_ERR("timeout waiting for queue[%d]: "
"txdata->tx_pkt_prod(%d) != txdata->tx_pkt_cons(%d)\n",
txdata->txq_index, txdata->tx_pkt_prod,
txdata->tx_pkt_cons);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
return -EBUSY;
#else
break;
#endif
}
cnt
usleep_range(1000, 1000);
}
return 0;
}
int <API key>(struct bnx2x *bp);
static inline void <API key>(struct bnx2x *bp,
u32 addr, size_t size, u32 *data)
{
int i;
for (i = 0; i < size/4; i++)
REG_WR(bp, addr + (i * 4), data[i]);
}
static inline void <API key>(struct bnx2x *bp,
struct <API key> *tcfg,
u16 abs_fid)
{
size_t size = sizeof(struct <API key>);
u32 addr = BAR_TSTRORM_INTMEM +
<API key>(abs_fid);
<API key>(bp, addr, size, (u32 *)tcfg);
}
static inline void storm_memset_cmng(struct bnx2x *bp,
struct <API key> *cmng,
u8 port)
{
size_t size = sizeof(struct <API key>);
u32 addr = BAR_XSTRORM_INTMEM +
<API key>(port);
<API key>(bp, addr, size, (u32 *)cmng);
}
/**
* bnx2x_wait_sp_comp - wait for the outstanding SP commands.
*
* @bp: driver handle
* @mask: bits that need to be cleared
*/
static inline bool bnx2x_wait_sp_comp(struct bnx2x *bp, unsigned long mask)
{
int tout = 5000; /* Wait for 5 secs tops */
while (tout
smp_mb();
netif_addr_lock_bh(bp->dev);
if (!(bp->sp_state & mask)) {
<API key>(bp->dev);
return true;
}
<API key>(bp->dev);
usleep_range(1000, 1000);
}
smp_mb();
netif_addr_lock_bh(bp->dev);
if (bp->sp_state & mask) {
BNX2X_ERR("Filtering completion timed out. sp_state 0x%lx, "
"mask 0x%lx\n", bp->sp_state, mask);
<API key>(bp->dev);
return false;
}
<API key>(bp->dev);
return true;
}
/**
* <API key> - set CDU context validation values
*
* @bp: driver handle
* @cxt: context of the connection on the host memory
* @cid: SW CID of the connection to be configured
*/
void <API key>(struct bnx2x *bp, struct eth_context *cxt,
u32 cid);
void <API key>(struct bnx2x *bp, u8 fw_sb_id,
u8 sb_index, u8 disable, u16 usec);
void <API key>(struct bnx2x *bp);
void <API key>(struct bnx2x *bp);
/**
* <API key> - extract MAX BW part from MF configuration.
*
* @bp: driver handle
* @mf_cfg: MF configuration
*
*/
static inline u16 <API key>(struct bnx2x *bp, u32 mf_cfg)
{
u16 max_cfg = (mf_cfg & <API key>) >>
<API key>;
if (!max_cfg) {
DP(NETIF_MSG_LINK,
"Max BW configured to 0 - using 100 instead\n");
max_cfg = 100;
}
return max_cfg;
}
/**
* <API key> - update iSCSI params according to licensing info.
*
* @bp: driver handle
*
*/
void <API key>(struct bnx2x *bp);
/* returns func by VN for current port */
static inline int func_by_vn(struct bnx2x *bp, int vn)
{
return 2 * vn + BP_PORT(bp);
}
/**
* <API key> - send notification to other functions.
*
* @bp: driver handle
*
*/
static inline void <API key>(struct bnx2x *bp)
{
int func;
int vn;
/* Set the attention towards other drivers on the same port */
for (vn = VN_0; vn < BP_MAX_VN_NUM(bp); vn++) {
if (vn == BP_VN(bp))
continue;
func = func_by_vn(bp, vn);
REG_WR(bp, <API key> +
(<API key> + func)*4, 1);
}
}
/**
* <API key> - update flags in shmem
*
* @bp: driver handle
* @flags: flags to update
* @set: set or clear
*
*/
static inline void <API key>(struct bnx2x *bp, u32 flags, u32 set)
{
if (SHMEM2_HAS(bp, drv_flags)) {
u32 drv_flags;
<API key>(bp, HW_LOCK_DRV_FLAGS);
drv_flags = SHMEM2_RD(bp, drv_flags);
if (set)
SET_FLAGS(drv_flags, flags);
else
RESET_FLAGS(drv_flags, flags);
SHMEM2_WR(bp, drv_flags, drv_flags);
DP(NETIF_MSG_HW, "drv_flags 0x%08x\n", drv_flags);
<API key>(bp, HW_LOCK_DRV_FLAGS);
}
}
static inline bool <API key>(struct bnx2x *bp, u8 *addr)
{
if (is_valid_ether_addr(addr))
return true;
#ifdef BCM_CNIC
if (is_zero_ether_addr(addr) && IS_MF_ISCSI_SD(bp))
return true;
#endif
return false;
}
#endif /* BNX2X_CMN_H */
|
#include <errno.h>
#include <stdlib.h>
/*
static void (*__CTOR_LIST__[1]) __P((void))
__attribute__((__unused__))
__attribute__((section(".ctors"))) = { (void *)0 };
static void (*__DTOR_LIST__[1]) __P((void))
__attribute__((section(".dtors"))) = { (void *)-1 };
*/
extern void (*__DTOR_LIST__[]) __P((void));
static void <API key> __P((void));
static void
<API key>()
{
void (**p)(void) = __DTOR_LIST__ + 1;
while (*p)
(**p++)();
}
static void dummy_fini(void) __attribute__((section(".trash")));
void
dummy_fini(void)
{
static void (* volatile call__dtors)(void) = <API key>;
/*
* Call global destructors.
*/
/* prevent function pointer constant propagation */
__asm__ __volatile__ (".section .fini");
(*call__dtors)();
__asm__ __volatile__ (".section .trash");
}
|
#include "avcodec.h"
#include "dsputil.h"
#include "mpegvideo.h"
#include "h263.h"
#include "mathops.h"
#include "msmpeg4.h"
#include "msmpeg4data.h"
#include "intrax8.h"
#include "wmv2.h"
static void parse_mb_skip(Wmv2Context * w){
int mb_x, mb_y;
MpegEncContext * const s= &w->s;
uint32_t * const mb_type = s->current_picture_ptr->f.mb_type;
w->skip_type= get_bits(&s->gb, 2);
switch(w->skip_type){
case SKIP_TYPE_NONE:
for(mb_y=0; mb_y<s->mb_height; mb_y++){
for(mb_x=0; mb_x<s->mb_width; mb_x++){
mb_type[mb_y*s->mb_stride + mb_x]= MB_TYPE_16x16 | MB_TYPE_L0;
}
}
break;
case SKIP_TYPE_MPEG:
for(mb_y=0; mb_y<s->mb_height; mb_y++){
for(mb_x=0; mb_x<s->mb_width; mb_x++){
mb_type[mb_y*s->mb_stride + mb_x]= (get_bits1(&s->gb) ? MB_TYPE_SKIP : 0) | MB_TYPE_16x16 | MB_TYPE_L0;
}
}
break;
case SKIP_TYPE_ROW:
for(mb_y=0; mb_y<s->mb_height; mb_y++){
if(get_bits1(&s->gb)){
for(mb_x=0; mb_x<s->mb_width; mb_x++){
mb_type[mb_y*s->mb_stride + mb_x]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
}
}else{
for(mb_x=0; mb_x<s->mb_width; mb_x++){
mb_type[mb_y*s->mb_stride + mb_x]= (get_bits1(&s->gb) ? MB_TYPE_SKIP : 0) | MB_TYPE_16x16 | MB_TYPE_L0;
}
}
}
break;
case SKIP_TYPE_COL:
for(mb_x=0; mb_x<s->mb_width; mb_x++){
if(get_bits1(&s->gb)){
for(mb_y=0; mb_y<s->mb_height; mb_y++){
mb_type[mb_y*s->mb_stride + mb_x]= MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;
}
}else{
for(mb_y=0; mb_y<s->mb_height; mb_y++){
mb_type[mb_y*s->mb_stride + mb_x]= (get_bits1(&s->gb) ? MB_TYPE_SKIP : 0) | MB_TYPE_16x16 | MB_TYPE_L0;
}
}
}
break;
}
}
static int decode_ext_header(Wmv2Context *w){
MpegEncContext * const s= &w->s;
GetBitContext gb;
int fps;
int code;
if(s->avctx->extradata_size<4) return -1;
init_get_bits(&gb, s->avctx->extradata, 32);
fps = get_bits(&gb, 5);
s->bit_rate = get_bits(&gb, 11)*1024;
w->mspel_bit = get_bits1(&gb);
s->loop_filter = get_bits1(&gb);
w->abt_flag = get_bits1(&gb);
w->j_type_bit = get_bits1(&gb);
w->top_left_mv_flag= get_bits1(&gb);
w->per_mb_rl_bit = get_bits1(&gb);
code = get_bits(&gb, 3);
if(code==0) return -1;
s->slice_height = s->mb_height / code;
if(s->avctx->debug&FF_DEBUG_PICT_INFO){
av_log(s->avctx, AV_LOG_DEBUG, "fps:%d, br:%d, qpbit:%d, abt_flag:%d, j_type_bit:%d, tl_mv_flag:%d, mbrl_bit:%d, code:%d, loop_filter:%d, slices:%d\n",
fps, s->bit_rate, w->mspel_bit, w->abt_flag, w->j_type_bit, w->top_left_mv_flag, w->per_mb_rl_bit, code, s->loop_filter,
code);
}
return 0;
}
int <API key>(MpegEncContext * s)
{
Wmv2Context * const w= (Wmv2Context*)s;
int code;
if(s->picture_number==0)
decode_ext_header(w);
s->pict_type = get_bits1(&s->gb) + 1;
if(s->pict_type == AV_PICTURE_TYPE_I){
code = get_bits(&s->gb, 7);
av_log(s->avctx, AV_LOG_DEBUG, "I7:%X/\n", code);
}
s->chroma_qscale= s->qscale = get_bits(&s->gb, 5);
if(s->qscale <= 0)
return -1;
return 0;
}
int <API key>(MpegEncContext * s)
{
Wmv2Context * const w= (Wmv2Context*)s;
if (s->pict_type == AV_PICTURE_TYPE_I) {
if(w->j_type_bit) w->j_type= get_bits1(&s->gb);
else w->j_type= 0; //FIXME check
if(!w->j_type){
if(w->per_mb_rl_bit) s->per_mb_rl_table= get_bits1(&s->gb);
else s->per_mb_rl_table= 0;
if(!s->per_mb_rl_table){
s-><API key> = decode012(&s->gb);
s->rl_table_index = decode012(&s->gb);
}
s->dc_table_index = get_bits1(&s->gb);
}
s->inter_intra_pred= 0;
s->no_rounding = 1;
if(s->avctx->debug&FF_DEBUG_PICT_INFO){
av_log(s->avctx, AV_LOG_DEBUG, "qscale:%d rlc:%d rl:%d dc:%d mbrl:%d j_type:%d \n",
s->qscale,
s-><API key>,
s->rl_table_index,
s->dc_table_index,
s->per_mb_rl_table,
w->j_type);
}
}else{
int cbp_index;
w->j_type=0;
parse_mb_skip(w);
cbp_index= decode012(&s->gb);
if(s->qscale <= 10){
int map[3]= {0,2,1};
w->cbp_table_index= map[cbp_index];
}else if(s->qscale <= 20){
int map[3]= {1,0,2};
w->cbp_table_index= map[cbp_index];
}else{
int map[3]= {2,1,0};
w->cbp_table_index= map[cbp_index];
}
if(w->mspel_bit) s->mspel= get_bits1(&s->gb);
else s->mspel= 0; //FIXME check
if(w->abt_flag){
w->per_mb_abt= get_bits1(&s->gb)^1;
if(!w->per_mb_abt){
w->abt_type= decode012(&s->gb);
}
}
if(w->per_mb_rl_bit) s->per_mb_rl_table= get_bits1(&s->gb);
else s->per_mb_rl_table= 0;
if(!s->per_mb_rl_table){
s->rl_table_index = decode012(&s->gb);
s-><API key> = s->rl_table_index;
}
s->dc_table_index = get_bits1(&s->gb);
s->mv_table_index = get_bits1(&s->gb);
s->inter_intra_pred= 0;//(s->width*s->height < 320*240 && s->bit_rate<=II_BITRATE);
s->no_rounding ^= 1;
if(s->avctx->debug&FF_DEBUG_PICT_INFO){
av_log(s->avctx, AV_LOG_DEBUG, "rl:%d rlc:%d dc:%d mv:%d mbrl:%d qp:%d mspel:%d per_mb_abt:%d abt_type:%d cbp:%d ii:%d\n",
s->rl_table_index,
s-><API key>,
s->dc_table_index,
s->mv_table_index,
s->per_mb_rl_table,
s->qscale,
s->mspel,
w->per_mb_abt,
w->abt_type,
w->cbp_table_index,
s->inter_intra_pred);
}
}
s->esc3_level_length= 0;
s->esc3_run_length= 0;
s->picture_number++; //FIXME ?
if(w->j_type){
<API key>(&w->x8, 2*s->qscale, (s->qscale-1)|1 );
return 1;
}
return 0;
}
static inline int wmv2_decode_motion(Wmv2Context *w, int *mx_ptr, int *my_ptr){
MpegEncContext * const s= &w->s;
int ret;
ret= <API key>(s, mx_ptr, my_ptr);
if(ret<0) return -1;
if((((*mx_ptr)|(*my_ptr)) & 1) && s->mspel)
w->hshift= get_bits1(&s->gb);
else
w->hshift= 0;
//printf("%d %d ", *mx_ptr, *my_ptr);
return 0;
}
static int16_t *wmv2_pred_motion(Wmv2Context *w, int *px, int *py){
MpegEncContext * const s= &w->s;
int xy, wrap, diff, type;
int16_t *A, *B, *C, *mot_val;
wrap = s->b8_stride;
xy = s->block_index[0];
mot_val = s->current_picture.f.motion_val[0][xy];
A = s->current_picture.f.motion_val[0][xy - 1];
B = s->current_picture.f.motion_val[0][xy - wrap];
C = s->current_picture.f.motion_val[0][xy + 2 - wrap];
if(s->mb_x && !s->first_slice_line && !s->mspel && w->top_left_mv_flag)
diff= FFMAX(FFABS(A[0] - B[0]), FFABS(A[1] - B[1]));
else
diff=0;
if(diff >= 8)
type= get_bits1(&s->gb);
else
type= 2;
if(type == 0){
*px= A[0];
*py= A[1];
}else if(type == 1){
*px= B[0];
*py= B[1];
}else{
/* special case for first (slice) line */
if (s->first_slice_line) {
*px = A[0];
*py = A[1];
} else {
*px = mid_pred(A[0], B[0], C[0]);
*py = mid_pred(A[1], B[1], C[1]);
}
}
return mot_val;
}
static inline int <API key>(Wmv2Context *w, DCTELEM *block, int n, int cbp){
MpegEncContext * const s= &w->s;
static const int sub_cbp_table[3]= {2,3,1};
int sub_cbp;
if(!cbp){
s->block_last_index[n] = -1;
return 0;
}
if(w->per_block_abt)
w->abt_type= decode012(&s->gb);
w->abt_type_table[n]= w->abt_type;
if(w->abt_type){
// const uint8_t *scantable= w->abt_scantable[w->abt_type-1].permutated;
const uint8_t *scantable= w->abt_scantable[w->abt_type-1].scantable;
// const uint8_t *scantable= w->abt_type-1 ? w->abt_scantable[1].permutated : w->abt_scantable[0].scantable;
sub_cbp= sub_cbp_table[ decode012(&s->gb) ];
// printf("S%d", sub_cbp);
if(sub_cbp&1){
if (<API key>(s, block, n, 1, scantable) < 0)
return -1;
}
if(sub_cbp&2){
if (<API key>(s, w->abt_block2[n], n, 1, scantable) < 0)
return -1;
}
s->block_last_index[n] = 63;
return 0;
}else{
return <API key>(s, block, n, 1, s->inter_scantable.permutated);
}
}
int ff_wmv2_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
{
Wmv2Context * const w= (Wmv2Context*)s;
int cbp, code, i;
uint8_t *coded_val;
if(w->j_type) return 0;
if (s->pict_type == AV_PICTURE_TYPE_P) {
if (IS_SKIP(s->current_picture.f.mb_type[s->mb_y * s->mb_stride + s->mb_x])) {
/* skip mb */
s->mb_intra = 0;
for(i=0;i<6;i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] = 0;
s->mv[0][0][1] = 0;
s->mb_skipped = 1;
w->hshift=0;
return 0;
}
code = get_vlc2(&s->gb, ff_mb_non_intra_vlc[w->cbp_table_index].table, <API key>, 3);
if (code < 0)
return -1;
s->mb_intra = (~code & 0x40) >> 6;
cbp = code & 0x3f;
} else {
s->mb_intra = 1;
code = get_vlc2(&s->gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);
if (code < 0){
av_log(s->avctx, AV_LOG_ERROR, "II-cbp illegal at %d %d\n", s->mb_x, s->mb_y);
return -1;
}
/* predict coded block pattern */
cbp = 0;
for(i=0;i<6;i++) {
int val = ((code >> (5 - i)) & 1);
if (i < 4) {
int pred = <API key>(s, i, &coded_val);
val = val ^ pred;
*coded_val = val;
}
cbp |= val << (5 - i);
}
}
if (!s->mb_intra) {
int mx, my;
//printf("P at %d %d\n", s->mb_x, s->mb_y);
wmv2_pred_motion(w, &mx, &my);
if(cbp){
s->dsp.clear_blocks(s->block[0]);
if(s->per_mb_rl_table){
s->rl_table_index = decode012(&s->gb);
s-><API key> = s->rl_table_index;
}
if(w->abt_flag && w->per_mb_abt){
w->per_block_abt= get_bits1(&s->gb);
if(!w->per_block_abt)
w->abt_type= decode012(&s->gb);
}else
w->per_block_abt=0;
}
if (wmv2_decode_motion(w, &mx, &my) < 0)
return -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
for (i = 0; i < 6; i++) {
if (<API key>(w, block[i], i, (cbp >> (5 - i)) & 1) < 0)
{
av_log(s->avctx, AV_LOG_ERROR, "\nerror while decoding inter block: %d x %d (%d)\n", s->mb_x, s->mb_y, i);
return -1;
}
}
} else {
//if(s->pict_type==AV_PICTURE_TYPE_P)
// printf("%d%d ", s->inter_intra_pred, cbp);
//printf("I at %d %d %d %06X\n", s->mb_x, s->mb_y, ((cbp&3)? 1 : 0) +((cbp&0x3C)? 2 : 0), show_bits(&s->gb, 24));
s->ac_pred = get_bits1(&s->gb);
if(s->inter_intra_pred){
s->h263_aic_dir= get_vlc2(&s->gb, ff_inter_intra_vlc.table, <API key>, 1);
// printf("%d%d %d %d/", s->ac_pred, s->h263_aic_dir, s->mb_x, s->mb_y);
}
if(s->per_mb_rl_table && cbp){
s->rl_table_index = decode012(&s->gb);
s-><API key> = s->rl_table_index;
}
s->dsp.clear_blocks(s->block[0]);
for (i = 0; i < 6; i++) {
if (<API key>(s, block[i], i, (cbp >> (5 - i)) & 1, NULL) < 0)
{
av_log(s->avctx, AV_LOG_ERROR, "\nerror while decoding intra block: %d x %d (%d)\n", s->mb_x, s->mb_y, i);
return -1;
}
}
}
return 0;
}
static av_cold int wmv2_decode_init(AVCodecContext *avctx){
Wmv2Context * const w= avctx->priv_data;
if(avctx->idct_algo==FF_IDCT_AUTO){
avctx->idct_algo=FF_IDCT_WMV2;
}
if(<API key>(avctx) < 0)
return -1;
ff_wmv2_common_init(w);
<API key>(&w->x8,&w->s);
return 0;
}
static av_cold int wmv2_decode_end(AVCodecContext *avctx)
{
Wmv2Context *w = avctx->priv_data;
<API key>(&w->x8);
return ff_h263_decode_end(avctx);
}
AVCodec ff_wmv2_decoder = {
.name = "wmv2",
.type = AVMEDIA_TYPE_VIDEO,
.id = CODEC_ID_WMV2,
.priv_data_size = sizeof(Wmv2Context),
.init = wmv2_decode_init,
.close = wmv2_decode_end,
.decode = <API key>,
.capabilities = <API key> | CODEC_CAP_DR1,
.long_name = <API key>("Windows Media Video 8"),
.pix_fmts= ff_pixfmt_list_420,
};
|
class TagGroupSerializer < <API key>
attributes :id, :name, :tag_names, :parent_tag_name, :one_per_topic
def tag_names
object.tags.map(&:name).sort
end
def parent_tag_name
[object.parent_tag.try(:name)].compact
end
end
|
#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/non_thread_safe.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/media/<API key>.h"
#include "media/base/<API key>.h"
#include "media/video/picture.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/scoped_binders.h"
static void ReportToUMA(
content::VaapiH264Decoder::<API key> failure) {
<API key>(
"Media.VAVDAH264.DecoderFailure",
failure,
content::VaapiH264Decoder::<API key>);
}
namespace content {
#define <API key>(result, log, error_code, ret) \
do { \
if (!(result)) { \
DVLOG(1) << log; \
NotifyError(error_code); \
return ret; \
} \
} while (0)
<API key>::InputBuffer::InputBuffer() : id(0), size(0) {
}
<API key>::InputBuffer::~InputBuffer() {
}
void <API key>::NotifyError(Error error) {
if (message_loop_ != base::MessageLoop::current()) {
DCHECK(<API key>-><API key>());
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::NotifyError, weak_this_, error));
return;
}
// Post Cleanup() as a task so we don't recursively acquire lock_.
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::Cleanup, weak_this_));
DVLOG(1) << "Notifying of error " << error;
if (client_) {
client_->NotifyError(error);
client_ptr_factory_.reset();
}
}
// TFPPicture allocates X Pixmaps and binds them to textures passed
// in PictureBuffers from clients to them. TFPPictures are created as
// a consequence of receiving a set of PictureBuffers from clients and released
// at the end of decode (or when a new set of PictureBuffers is required).
// TFPPictures are used for output, contents of VASurfaces passed from decoder
// are put into the associated pixmap memory and sent to client.
class <API key>::TFPPicture : public base::NonThreadSafe {
public:
~TFPPicture();
static linked_ptr<TFPPicture> Create(
const base::Callback<bool(void)>& <API key>,
const GLXFBConfig& fb_config,
Display* x_display,
int32 picture_buffer_id,
uint32 texture_id,
gfx::Size size);
int32 picture_buffer_id() {
return picture_buffer_id_;
}
gfx::Size size() {
return size_;
}
int x_pixmap() {
return x_pixmap_;
}
// Bind texture to pixmap. Needs to be called every frame.
bool Bind();
private:
TFPPicture(const base::Callback<bool(void)>& <API key>,
Display* x_display,
int32 picture_buffer_id,
uint32 texture_id,
gfx::Size size);
bool Initialize(const GLXFBConfig& fb_config);
base::Callback<bool(void)> <API key>;
Display* x_display_;
// Output id for the client.
int32 picture_buffer_id_;
uint32 texture_id_;
gfx::Size size_;
// Pixmaps bound to this texture.
Pixmap x_pixmap_;
GLXPixmap glx_pixmap_;
<API key>(TFPPicture);
};
<API key>::TFPPicture::TFPPicture(
const base::Callback<bool(void)>& <API key>,
Display* x_display,
int32 picture_buffer_id,
uint32 texture_id,
gfx::Size size)
: <API key>(<API key>),
x_display_(x_display),
picture_buffer_id_(picture_buffer_id),
texture_id_(texture_id),
size_(size),
x_pixmap_(0),
glx_pixmap_(0) {
DCHECK(!<API key>.is_null());
};
linked_ptr<<API key>::TFPPicture>
<API key>::TFPPicture::Create(
const base::Callback<bool(void)>& <API key>,
const GLXFBConfig& fb_config,
Display* x_display,
int32 picture_buffer_id,
uint32 texture_id,
gfx::Size size) {
linked_ptr<TFPPicture> tfp_picture(
new TFPPicture(<API key>, x_display, picture_buffer_id,
texture_id, size));
if (!tfp_picture->Initialize(fb_config))
tfp_picture.reset();
return tfp_picture;
}
bool <API key>::TFPPicture::Initialize(
const GLXFBConfig& fb_config) {
DCHECK(CalledOnValidThread());
if (!<API key>.Run())
return false;
XWindowAttributes win_attr;
int screen = DefaultScreen(x_display_);
<API key>(x_display_, RootWindow(x_display_, screen), &win_attr);
//TODO(posciak): pass the depth required by libva, not the RootWindow's depth
x_pixmap_ = XCreatePixmap(x_display_, RootWindow(x_display_, screen),
size_.width(), size_.height(), win_attr.depth);
if (!x_pixmap_) {
DVLOG(1) << "Failed creating an X Pixmap for TFP";
return false;
}
static const int pixmap_attr[] = {
<API key>, GLX_TEXTURE_2D_EXT,
<API key>, <API key>,
GL_NONE,
};
glx_pixmap_ = glXCreatePixmap(x_display_, fb_config, x_pixmap_, pixmap_attr);
if (!glx_pixmap_) {
// x_pixmap_ will be freed in the destructor.
DVLOG(1) << "Failed creating a GLX Pixmap for TFP";
return false;
}
return true;
}
<API key>::TFPPicture::~TFPPicture() {
DCHECK(CalledOnValidThread());
// Unbind surface from texture and deallocate resources.
if (glx_pixmap_ && <API key>.Run()) {
<API key>(x_display_, glx_pixmap_, GLX_FRONT_LEFT_EXT);
glXDestroyPixmap(x_display_, glx_pixmap_);
}
if (x_pixmap_)
XFreePixmap(x_display_, x_pixmap_);
XSync(x_display_, False); // Needed to work around buggy vdpau-driver.
}
bool <API key>::TFPPicture::Bind() {
DCHECK(CalledOnValidThread());
DCHECK(x_pixmap_);
DCHECK(glx_pixmap_);
if (!<API key>.Run())
return false;
gfx::ScopedTextureBinder texture_binder(GL_TEXTURE_2D, texture_id_);
glXBindTexImageEXT(x_display_, glx_pixmap_, GLX_FRONT_LEFT_EXT, NULL);
return true;
}
<API key>::TFPPicture*
<API key>::TFPPictureById(int32 picture_buffer_id) {
TFPPictures::iterator it = tfp_pictures_.find(picture_buffer_id);
if (it == tfp_pictures_.end()) {
DVLOG(1) << "Picture id " << picture_buffer_id << " does not exist";
return NULL;
}
return it->second.get();
}
<API key>::<API key>(
Display* x_display,
const base::Callback<bool(void)>& <API key>)
: x_display_(x_display),
<API key>(<API key>),
state_(kUninitialized),
input_ready_(&lock_),
surfaces_available_(&lock_),
message_loop_(base::MessageLoop::current()),
decoder_thread_("VaapiDecoderThread"),
<API key>(0),
<API key>(0),
<API key>(false),
<API key>(false),
requested_num_pics_(0),
weak_this_factory_(this) {
weak_this_ = weak_this_factory_.GetWeakPtr();
<API key> = media::BindToCurrentLoop(
base::Bind(&<API key>::RecycleVASurfaceID, weak_this_));
}
<API key>::~<API key>() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
}
class XFreeDeleter {
public:
void operator()(void* x) const {
::XFree(x);
}
};
bool <API key>::InitializeFBConfig() {
const int fbconfig_attr[] = {
GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
<API key>, <API key>,
<API key>, GL_TRUE,
GLX_Y_INVERTED_EXT, GL_TRUE,
GL_NONE,
};
int num_fbconfigs;
scoped_ptr<GLXFBConfig, XFreeDeleter> glx_fb_configs(
glXChooseFBConfig(x_display_, DefaultScreen(x_display_), fbconfig_attr,
&num_fbconfigs));
if (!glx_fb_configs)
return false;
if (!num_fbconfigs)
return false;
fb_config_ = glx_fb_configs.get()[0];
return true;
}
bool <API key>::Initialize(media::VideoCodecProfile profile,
Client* client) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
client_ptr_factory_.reset(new base::WeakPtrFactory<Client>(client));
client_ = client_ptr_factory_->GetWeakPtr();
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, kUninitialized);
DVLOG(2) << "Initializing VAVDA, profile: " << profile;
if (!<API key>.Run())
return false;
if (!InitializeFBConfig()) {
DVLOG(1) << "Could not get a usable FBConfig";
return false;
}
vaapi_wrapper_ = VaapiWrapper::Create(
VaapiWrapper::kDecode,
profile,
x_display_,
base::Bind(&ReportToUMA, content::VaapiH264Decoder::VAAPI_ERROR));
if (!vaapi_wrapper_.get()) {
DVLOG(1) << "Failed initializing VAAPI";
return false;
}
decoder_.reset(
new VaapiH264Decoder(
vaapi_wrapper_.get(),
media::BindToCurrentLoop(base::Bind(
&<API key>::SurfaceReady, weak_this_)),
base::Bind(&ReportToUMA)));
CHECK(decoder_thread_.Start());
<API key> = decoder_thread_.message_loop_proxy();
state_ = kIdle;
return true;
}
void <API key>::SurfaceReady(
int32 input_id,
const scoped_refptr<VASurface>& va_surface) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
DCHECK(!<API key>);
// Drop any requests to output if we are resetting or being destroyed.
if (state_ == kResetting || state_ == kDestroying)
return;
pending_output_cbs_.push(
base::Bind(&<API key>::OutputPicture,
weak_this_, va_surface, input_id));
TryOutputSurface();
}
void <API key>::OutputPicture(
const scoped_refptr<VASurface>& va_surface,
int32 input_id,
TFPPicture* tfp_picture) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
int32 output_id = tfp_picture->picture_buffer_id();
TRACE_EVENT2("Video Decoder", "VAVDA::OutputSurface",
"input_id", input_id,
"output_id", output_id);
DVLOG(3) << "Outputting VASurface " << va_surface->id()
<< " into pixmap bound to picture buffer id " << output_id;
<API key>(tfp_picture->Bind(),
"Failed binding texture to pixmap",
PLATFORM_FAILURE, );
<API key>(
vaapi_wrapper_-><API key>(va_surface->id(),
tfp_picture->x_pixmap(),
tfp_picture->size()),
"Failed putting surface into pixmap", PLATFORM_FAILURE, );
// Notify the client a picture is ready to be displayed.
++<API key>;
TRACE_COUNTER1("Video Decoder", "Textures at client", <API key>);
DVLOG(4) << "Notifying output picture id " << output_id
<< " for input "<< input_id << " is ready";
// TODO(posciak): Use visible size from decoder here instead
// (crbug.com/402760).
if (client_)
client_->PictureReady(
media::Picture(output_id, input_id, gfx::Rect(tfp_picture->size())));
}
void <API key>::TryOutputSurface() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
// Handle Destroy() arriving while pictures are queued for output.
if (!client_)
return;
if (pending_output_cbs_.empty() || output_buffers_.empty())
return;
OutputCB output_cb = pending_output_cbs_.front();
pending_output_cbs_.pop();
TFPPicture* tfp_picture = TFPPictureById(output_buffers_.front());
DCHECK(tfp_picture);
output_buffers_.pop();
output_cb.Run(tfp_picture);
if (<API key> && pending_output_cbs_.empty())
FinishFlush();
}
void <API key>::<API key>(
const media::BitstreamBuffer& bitstream_buffer) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
TRACE_EVENT1("Video Decoder", "<API key>", "input_id",
bitstream_buffer.id());
DVLOG(4) << "Mapping new input buffer id: " << bitstream_buffer.id()
<< " size: " << (int)bitstream_buffer.size();
scoped_ptr<base::SharedMemory> shm(
new base::SharedMemory(bitstream_buffer.handle(), true));
<API key>(shm->Map(bitstream_buffer.size()),
"Failed to map input buffer", UNREADABLE_INPUT,);
base::AutoLock auto_lock(lock_);
// Set up a new input buffer and queue it for later.
linked_ptr<InputBuffer> input_buffer(new InputBuffer());
input_buffer->shm.reset(shm.release());
input_buffer->id = bitstream_buffer.id();
input_buffer->size = bitstream_buffer.size();
++<API key>;
TRACE_COUNTER1("Video Decoder", "Stream buffers at decoder",
<API key>);
input_buffers_.push(input_buffer);
input_ready_.Signal();
}
bool <API key>::<API key>() {
DCHECK(<API key>-><API key>());
lock_.AssertAcquired();
if (curr_input_buffer_.get())
return true;
// Will only wait if it is expected that in current state new buffers will
// be queued from the client via Decode(). The state can change during wait.
while (input_buffers_.empty() && (state_ == kDecoding || state_ == kIdle)) {
input_ready_.Wait();
}
// We could have got woken up in a different state or never got to sleep
// due to current state; check for that.
switch (state_) {
case kFlushing:
// Here we are only interested in finishing up decoding buffers that are
// already queued up. Otherwise will stop decoding.
if (input_buffers_.empty())
return false;
// else fallthrough
case kDecoding:
case kIdle:
DCHECK(!input_buffers_.empty());
curr_input_buffer_ = input_buffers_.front();
input_buffers_.pop();
DVLOG(4) << "New current bitstream buffer, id: "
<< curr_input_buffer_->id
<< " size: " << curr_input_buffer_->size;
decoder_->SetStream(
static_cast<uint8*>(curr_input_buffer_->shm->memory()),
curr_input_buffer_->size, curr_input_buffer_->id);
return true;
default:
// We got woken up due to being destroyed/reset, ignore any already
// queued inputs.
return false;
}
}
void <API key>::<API key>() {
lock_.AssertAcquired();
DCHECK(<API key>-><API key>());
DCHECK(curr_input_buffer_.get());
int32 id = curr_input_buffer_->id;
curr_input_buffer_.reset();
DVLOG(4) << "End of input buffer " << id;
message_loop_->PostTask(FROM_HERE, base::Bind(
&Client::<API key>, client_, id));
--<API key>;
TRACE_COUNTER1("Video Decoder", "Stream buffers at decoder",
<API key>);
}
bool <API key>::<API key>() {
lock_.AssertAcquired();
DCHECK(<API key>-><API key>());
while (<API key>.empty() &&
(state_ == kDecoding || state_ == kFlushing || state_ == kIdle)) {
surfaces_available_.Wait();
}
if (state_ != kDecoding && state_ != kFlushing && state_ != kIdle)
return false;
while (!<API key>.empty()) {
scoped_refptr<VASurface> va_surface(
new VASurface(<API key>.front(), <API key>));
<API key>.pop_front();
decoder_->ReuseSurface(va_surface);
}
return true;
}
void <API key>::DecodeTask() {
DCHECK(<API key>-><API key>());
TRACE_EVENT0("Video Decoder", "VAVDA::DecodeTask");
base::AutoLock auto_lock(lock_);
if (state_ != kDecoding)
return;
// Main decode task.
DVLOG(4) << "Decode task";
// Try to decode what stream data is (still) in the decoder until we run out
// of it.
while (<API key>()) {
DCHECK(curr_input_buffer_.get());
VaapiH264Decoder::DecResult res;
{
// We are OK releasing the lock here, as decoder never calls our methods
// directly and we will reacquire the lock before looking at state again.
// This is the main decode function of the decoder and while keeping
// the lock for its duration would be fine, it would defeat the purpose
// of having a separate decoder thread.
base::AutoUnlock auto_unlock(lock_);
res = decoder_->Decode();
}
switch (res) {
case VaapiH264Decoder::<API key>:
DVLOG(1) << "Decoder requesting a new set of surfaces";
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::<API key>, weak_this_,
decoder_-><API key>(),
decoder_->GetPicSize()));
// We'll get rescheduled once <API key>() finishes.
return;
case VaapiH264Decoder::kRanOutOfStreamData:
<API key>();
break;
case VaapiH264Decoder::kRanOutOfSurfaces:
// No more output buffers in the decoder, try getting more or go to
// sleep waiting for them.
if (!<API key>())
return;
break;
case VaapiH264Decoder::kDecodeError:
<API key>(false, "Error decoding stream",
PLATFORM_FAILURE, );
return;
}
}
}
void <API key>::<API key>(size_t num_pics,
gfx::Size size) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
DCHECK(!<API key>);
// At this point decoder has stopped running and has already posted onto our
// loop any remaining output request callbacks, which executed before we got
// here. Some of them might have been pended though, because we might not
// have had enough TFPictures to output surfaces to. Initiate a wait cycle,
// which will wait for client to return enough PictureBuffers to us, so that
// we can finish all pending output callbacks, releasing associated surfaces.
DVLOG(1) << "Initiating surface set change";
<API key> = true;
requested_num_pics_ = num_pics;
requested_pic_size_ = size;
<API key>();
}
void <API key>::<API key>() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
if (!<API key>)
return;
if (!pending_output_cbs_.empty() ||
tfp_pictures_.size() != <API key>.size()) {
// Either:
// 1. Not all pending pending output callbacks have been executed yet.
// Wait for the client to return enough pictures and retry later.
// 2. The above happened and all surface release callbacks have been posted
// as the result, but not all have executed yet. Post ourselves after them
// to let them release surfaces.
DVLOG(2) << "Awaiting pending output/surface release callbacks to finish";
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::<API key>, weak_this_));
return;
}
// All surfaces released, destroy them and dismiss all PictureBuffers.
<API key> = false;
<API key>.clear();
vaapi_wrapper_->DestroySurfaces();
for (TFPPictures::iterator iter = tfp_pictures_.begin();
iter != tfp_pictures_.end(); ++iter) {
DVLOG(2) << "Dismissing picture id: " << iter->first;
if (client_)
client_-><API key>(iter->first);
}
tfp_pictures_.clear();
// And ask for a new set as requested.
DVLOG(1) << "Requesting " << requested_num_pics_ << " pictures of size: "
<< requested_pic_size_.ToString();
message_loop_->PostTask(FROM_HERE, base::Bind(
&Client::<API key>, client_,
requested_num_pics_, requested_pic_size_, GL_TEXTURE_2D));
}
void <API key>::Decode(
const media::BitstreamBuffer& bitstream_buffer) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
TRACE_EVENT1("Video Decoder", "VAVDA::Decode", "Buffer id",
bitstream_buffer.id());
// We got a new input buffer from the client, map it and queue for later use.
<API key>(bitstream_buffer);
base::AutoLock auto_lock(lock_);
switch (state_) {
case kIdle:
state_ = kDecoding;
<API key>->PostTask(FROM_HERE, base::Bind(
&<API key>::DecodeTask,
base::Unretained(this)));
break;
case kDecoding:
// Decoder already running, fallthrough.
case kResetting:
// When resetting, allow accumulating bitstream buffers, so that
// the client can queue after-seek-buffers while we are finishing with
// the before-seek one.
break;
default:
<API key>(false,
"Decode request from client in invalid state: " << state_,
PLATFORM_FAILURE, );
break;
}
}
void <API key>::RecycleVASurfaceID(
VASurfaceID va_surface_id) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
base::AutoLock auto_lock(lock_);
<API key>.push_back(va_surface_id);
surfaces_available_.Signal();
}
void <API key>::<API key>(
const std::vector<media::PictureBuffer>& buffers) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
base::AutoLock auto_lock(lock_);
DCHECK(tfp_pictures_.empty());
while (!output_buffers_.empty())
output_buffers_.pop();
<API key>(
buffers.size() == requested_num_pics_,
"Got an invalid number of picture buffers. (Got " << buffers.size()
<< ", requested " << requested_num_pics_ << ")", INVALID_ARGUMENT, );
DCHECK(requested_pic_size_ == buffers[0].size());
std::vector<VASurfaceID> va_surface_ids;
<API key>(
vaapi_wrapper_->CreateSurfaces(requested_pic_size_,
buffers.size(),
&va_surface_ids),
"Failed creating VA Surfaces", PLATFORM_FAILURE, );
DCHECK_EQ(va_surface_ids.size(), buffers.size());
for (size_t i = 0; i < buffers.size(); ++i) {
DVLOG(2) << "Assigning picture id: " << buffers[i].id()
<< " to texture id: " << buffers[i].texture_id()
<< " VASurfaceID: " << va_surface_ids[i];
linked_ptr<TFPPicture> tfp_picture(
TFPPicture::Create(<API key>, fb_config_, x_display_,
buffers[i].id(), buffers[i].texture_id(),
requested_pic_size_));
<API key>(
tfp_picture.get(), "Failed assigning picture buffer to a texture.",
PLATFORM_FAILURE, );
bool inserted = tfp_pictures_.insert(std::make_pair(
buffers[i].id(), tfp_picture)).second;
DCHECK(inserted);
output_buffers_.push(buffers[i].id());
<API key>.push_back(va_surface_ids[i]);
surfaces_available_.Signal();
}
state_ = kDecoding;
<API key>->PostTask(FROM_HERE, base::Bind(
&<API key>::DecodeTask, base::Unretained(this)));
}
void <API key>::ReusePictureBuffer(int32 picture_buffer_id) {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
TRACE_EVENT1("Video Decoder", "VAVDA::ReusePictureBuffer", "Picture id",
picture_buffer_id);
--<API key>;
TRACE_COUNTER1("Video Decoder", "Textures at client", <API key>);
output_buffers_.push(picture_buffer_id);
TryOutputSurface();
}
void <API key>::FlushTask() {
DCHECK(<API key>-><API key>());
DVLOG(1) << "Flush task";
// First flush all the pictures that haven't been outputted, notifying the
// client to output them.
bool res = decoder_->Flush();
<API key>(res, "Failed flushing the decoder.",
PLATFORM_FAILURE, );
// Put the decoder in idle state, ready to resume.
decoder_->Reset();
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::FinishFlush, weak_this_));
}
void <API key>::Flush() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
DVLOG(1) << "Got flush request";
base::AutoLock auto_lock(lock_);
state_ = kFlushing;
// Queue a flush task after all existing decoding tasks to clean up.
<API key>->PostTask(FROM_HERE, base::Bind(
&<API key>::FlushTask, base::Unretained(this)));
input_ready_.Signal();
surfaces_available_.Signal();
}
void <API key>::FinishFlush() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
<API key> = false;
base::AutoLock auto_lock(lock_);
if (state_ != kFlushing) {
DCHECK_EQ(state_, kDestroying);
return; // We could've gotten destroyed already.
}
// Still waiting for textures from client to finish outputting all pending
// frames. Try again later.
if (!pending_output_cbs_.empty()) {
<API key> = true;
return;
}
state_ = kIdle;
message_loop_->PostTask(FROM_HERE, base::Bind(
&Client::NotifyFlushDone, client_));
DVLOG(1) << "Flush finished";
}
void <API key>::ResetTask() {
DCHECK(<API key>-><API key>());
DVLOG(1) << "ResetTask";
// All the decoding tasks from before the reset request from client are done
// by now, as this task was scheduled after them and client is expected not
// to call Decode() after Reset() and before NotifyResetDone.
decoder_->Reset();
base::AutoLock auto_lock(lock_);
// Return current input buffer, if present.
if (curr_input_buffer_.get())
<API key>();
// And let client know that we are done with reset.
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::FinishReset, weak_this_));
}
void <API key>::Reset() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
DVLOG(1) << "Got reset request";
// This will make any new decode tasks exit early.
base::AutoLock auto_lock(lock_);
state_ = kResetting;
<API key> = false;
// Drop all remaining input buffers, if present.
while (!input_buffers_.empty()) {
message_loop_->PostTask(FROM_HERE, base::Bind(
&Client::<API key>, client_,
input_buffers_.front()->id));
input_buffers_.pop();
}
<API key>->PostTask(FROM_HERE, base::Bind(
&<API key>::ResetTask, base::Unretained(this)));
input_ready_.Signal();
surfaces_available_.Signal();
}
void <API key>::FinishReset() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
DVLOG(1) << "FinishReset";
base::AutoLock auto_lock(lock_);
if (state_ != kResetting) {
DCHECK(state_ == kDestroying || state_ == kUninitialized) << state_;
return; // We could've gotten destroyed already.
}
// Drop pending outputs.
while (!pending_output_cbs_.empty())
pending_output_cbs_.pop();
if (<API key>) {
// Decoder requested a new surface set while we were waiting for it to
// finish the last DecodeTask, running at the time of Reset().
// Let the surface set change finish first before resetting.
message_loop_->PostTask(FROM_HERE, base::Bind(
&<API key>::FinishReset, weak_this_));
return;
}
<API key> = 0;
state_ = kIdle;
message_loop_->PostTask(FROM_HERE, base::Bind(
&Client::NotifyResetDone, client_));
// The client might have given us new buffers via Decode() while we were
// resetting and might be waiting for our move, and not call Decode() anymore
// until we return something. Post a DecodeTask() so that we won't
// sleep forever waiting for Decode() in that case. Having two of them
// in the pipe is harmless, the additional one will return as soon as it sees
// that we are back in kDecoding state.
if (!input_buffers_.empty()) {
state_ = kDecoding;
<API key>->PostTask(FROM_HERE, base::Bind(
&<API key>::DecodeTask,
base::Unretained(this)));
}
DVLOG(1) << "Reset finished";
}
void <API key>::Cleanup() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
if (state_ == kUninitialized || state_ == kDestroying)
return;
DVLOG(1) << "Destroying VAVDA";
base::AutoLock auto_lock(lock_);
state_ = kDestroying;
client_ptr_factory_.reset();
weak_this_factory_.InvalidateWeakPtrs();
// Signal all potential waiters on the decoder_thread_, let them early-exit,
// as we've just moved to the kDestroying state, and wait for all tasks
// to finish.
input_ready_.Signal();
surfaces_available_.Signal();
{
base::AutoUnlock auto_unlock(lock_);
decoder_thread_.Stop();
}
state_ = kUninitialized;
}
void <API key>::Destroy() {
DCHECK_EQ(message_loop_, base::MessageLoop::current());
Cleanup();
delete this;
}
bool <API key>::CanDecodeOnIOThread() {
return false;
}
} // namespace content
|
#ifndef <API key>
#define <API key>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/time/time.h"
#include "chrome/browser/autocomplete/<API key>.h"
#include "chrome/browser/ui/webui/mojo_web_ui_handler.h"
#include "chrome/browser/ui/webui/omnibox/omnibox.mojom.h"
#include "components/omnibox/autocomplete_input.h"
#include "components/omnibox/autocomplete_match.h"
class <API key>;
class Profile;
// Implementation of <API key>. StartOmniboxQuery() calls to a
// private <API key>. It also listens for updates from the
// <API key> to OnResultChanged() and passes those results to
// the OmniboxPage.
class OmniboxUIHandler : public <API key>,
public mojo::InterfaceImpl<<API key>>,
public MojoWebUIHandler {
public:
explicit OmniboxUIHandler(Profile* profile);
virtual ~OmniboxUIHandler();
// <API key> overrides:
virtual void OnResultChanged(bool <API key>) OVERRIDE;
// ErrorHandler overrides:
virtual void OnConnectionError() OVERRIDE {
// TODO(darin): How should we handle connection error?
}
// <API key> overrides:
virtual void StartOmniboxQuery(const mojo::String& input_string,
int32_t cursor_position,
bool <API key>,
bool prefer_keyword,
int32_t page_classification) OVERRIDE;
private:
// Looks up whether the hostname is a typed host (i.e., has received
// typed visits). Return true if the lookup succeeded; if so, the
// value of |is_typed_host| is set appropriately.
bool LookupIsTypedHost(const base::string16& host, bool* is_typed_host) const;
// Re-initializes the <API key> in preparation for the
// next query.
void ResetController();
// The omnibox <API key> that collects/sorts/dup-
// eliminates the results as they come in.
scoped_ptr<<API key>> controller_;
// Time the user's input was sent to the omnibox to start searching.
// Needed because we also pass timing information in the object we
// hand back to the javascript.
base::Time <API key>;
// The input used when starting the <API key>.
AutocompleteInput input_;
// The Profile* handed to us in our constructor.
Profile* profile_;
<API key>(OmniboxUIHandler);
};
#endif // <API key>
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import java.util.Arrays;
import java.util.Locale;
/**
CharacterReader consumes tokens off a string. To replace the old TokenQueue.
*/
final class CharacterReader {
static final char EOF = (char) -1;
private static final int maxCacheLen = 12;
private final char[] input;
private final int length;
private int pos = 0;
private int mark = 0;
private final String[] stringCache = new String[512]; // holds reused strings in this doc, to lessen garbage
CharacterReader(String input) {
Validate.notNull(input);
this.input = input.toCharArray();
this.length = this.input.length;
}
int pos() {
return pos;
}
boolean isEmpty() {
return pos >= length;
}
char current() {
return pos >= length ? EOF : input[pos];
}
char consume() {
char val = pos >= length ? EOF : input[pos];
pos++;
return val;
}
void unconsume() {
pos
}
void advance() {
pos++;
}
void mark() {
mark = pos;
}
void rewindToMark() {
pos = mark;
}
String consumeAsString() {
return new String(input, pos++, 1);
}
/**
* Returns the number of characters between the current position and the next instance of the input char
* @param c scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(char c) {
// doesn't handle scanning for surrogates
for (int i = pos; i < length; i++) {
if (c == input[i])
return i - pos;
}
return -1;
}
/**
* Returns the number of characters between the current position and the next instance of the input sequence
*
* @param seq scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]) { /* empty */ }
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length && last <= length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++) { /* empty */ }
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
}
String consumeTo(char c) {
int offset = nextIndexOf(c);
if (offset != -1) {
String consumed = cacheString(pos, offset);
pos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeTo(String seq) {
int offset = nextIndexOf(seq);
if (offset != -1) {
String consumed = cacheString(pos, offset);
pos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeToAny(final char... chars) {
final int start = pos;
final int remaining = length;
OUTER: while (pos < remaining) {
for (char c : chars) {
if (input[pos] == c)
break OUTER;
}
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeToAnySorted(final char... chars) {
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
if (Arrays.binarySearch(chars, val[pos]) >= 0)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeData() {
// &, <, null
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
final char c = val[pos];
if (c == '&'|| c == '<' || c == TokeniserState.nullChar)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeTagName() {
// '\t', '\n', '\r', '\f', ' ', '/', '>', nullChar
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
final char c = val[pos];
if (c == '\t'|| c == '\n'|| c == '\r'|| c == '\f'|| c == ' '|| c == '/'|| c == '>'|| c == TokeniserState.nullChar)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeToEnd() {
String data = cacheString(pos, length-pos);
pos = length;
return data;
}
String <API key>() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String <API key>() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
pos++;
else
break;
}
while (!isEmpty()) {
char c = input[pos];
if (c >= '0' && c <= '9')
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeHexSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String <API key>() {
int start = pos;
while (pos < length) {
char c = input[pos];
if (c >= '0' && c <= '9')
pos++;
else
break;
}
return cacheString(start, pos - start);
}
boolean matches(char c) {
return !isEmpty() && input[pos] == c;
}
boolean matches(String seq) {
int scanLength = seq.length();
if (scanLength > length - pos)
return false;
for (int offset = 0; offset < scanLength; offset++)
if (seq.charAt(offset) != input[pos+offset])
return false;
return true;
}
boolean matchesIgnoreCase(String seq) {
int scanLength = seq.length();
if (scanLength > length - pos)
return false;
for (int offset = 0; offset < scanLength; offset++) {
char upScan = Character.toUpperCase(seq.charAt(offset));
char upTarget = Character.toUpperCase(input[pos + offset]);
if (upScan != upTarget)
return false;
}
return true;
}
boolean matchesAny(char... seq) {
if (isEmpty())
return false;
char c = input[pos];
for (char seek : seq) {
if (seek == c)
return true;
}
return false;
}
boolean matchesAnySorted(char[] seq) {
return !isEmpty() && Arrays.binarySearch(seq, input[pos]) >= 0;
}
boolean matchesLetter() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
boolean matchesDigit() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= '0' && c <= '9');
}
boolean matchConsume(String seq) {
if (matches(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
boolean <API key>(String seq) {
if (matchesIgnoreCase(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
boolean containsIgnoreCase(String seq) {
// used to check presence of </title>, </style>. only finds consistent case.
String loScan = seq.toLowerCase(Locale.ENGLISH);
String hiScan = seq.toUpperCase(Locale.ENGLISH);
return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1);
}
@Override
public String toString() {
return new String(input, pos, length - pos);
}
/**
* Caches short strings, as a flywheel pattern, to reduce GC load. Just for this doc, to prevent leaks.
* <p />
* Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list.
* That saves both having to create objects as hash keys, and running through the entry list, at the expense of
* some more duplicates.
*/
private String cacheString(final int start, final int count) {
final char[] val = input;
final String[] cache = stringCache;
// limit (no cache):
if (count > maxCacheLen)
return new String(val, start, count);
// calculate hash:
int hash = 0;
int offset = start;
for (int i = 0; i < count; i++) {
hash = 31 * hash + val[offset++];
}
// get from cache
final int index = hash & cache.length - 1;
String cached = cache[index];
if (cached == null) { // miss, add
cached = new String(val, start, count);
cache[index] = cached;
} else { // hashcode hit, check equality
if (rangeEquals(start, count, cached)) {
// hit
return cached;
} else { // hashcode conflict
cached = new String(val, start, count);
}
}
return cached;
}
/**
* Check if the value of the provided range equals the string.
*/
boolean rangeEquals(final int start, int count, final String cached) {
if (count == cached.length()) {
char one[] = input;
int i = start;
int j = 0;
while (count
if (one[i++] != cached.charAt(j++))
return false;
}
return true;
}
return false;
}
}
|
drop table accounts;
drop table funny_jokes;
drop table companies;
drop table topics;
drop synonym subjects;
drop table developers_projects;
drop table computers;
drop table developers;
drop table projects;
drop table customers;
drop table orders;
drop table movies;
drop table subscribers;
drop table booleantests;
drop table auto_id_tests;
drop table entrants;
drop table colnametests;
drop table mixins;
drop table people;
drop table readers;
drop table binaries;
drop table comments;
drop table authors;
drop table tasks;
drop table categories_posts;
drop table categories;
drop table posts;
drop table fk_test_has_pk;
drop table fk_test_has_fk;
drop table keyboards;
drop table legacy_things;
drop table numeric_data;
drop table mixed_case_monkeys;
drop table minimalistics;
drop sequence accounts_seq;
drop sequence funny_jokes_seq;
drop sequence <API key>;
drop sequence topics_seq;
drop sequence developers_seq;
drop sequence projects_seq;
drop sequence <API key>;
drop sequence customers_seq;
drop sequence orders_seq;
drop sequence movies_seq;
drop sequence subscribers_seq;
drop sequence booleantests_seq;
drop sequence auto_id_tests_seq;
drop sequence entrants_seq;
drop sequence colnametests_seq;
drop sequence mixins_seq;
drop sequence people_seq;
drop sequence binaries_seq;
drop sequence posts_seq;
drop sequence comments_seq;
drop sequence authors_seq;
drop sequence tasks_seq;
drop sequence computers_seq;
drop sequence categories_seq;
drop sequence <API key>;
drop sequence fk_test_has_pk_seq;
drop sequence fk_test_has_fk_seq;
drop sequence keyboards_seq;
drop sequence legacy_things_seq;
drop sequence numeric_data_seq;
drop sequence <API key>;
drop sequence minimalistics_seq;
|
/**
* Module dependencies.
*/
var Connection = require('../../connection')
, mongo = require('mongodb')
, Server = mongo.Server
, ReplSetServers = mongo.ReplSetServers;
/**
* Connection for mongodb-native driver
*
* @api private
*/
function NativeConnection() {
Connection.apply(this, arguments);
};
/**
* Inherits from Connection.
*/
NativeConnection.prototype.__proto__ = Connection.prototype;
/**
* Opens the connection.
*
* Example server options:
* auto_reconnect (default: false)
* poolSize (default: 1)
*
* Example db options:
* pk - custom primary key factory to generate `_id` values
*
* Some of these may break Mongoose. Use at your own risk. You have been warned.
*
* @param {Function} callback
* @api private
*/
NativeConnection.prototype.doOpen = function (fn) {
var server;
if (!this.db) {
server = new mongo.Server(this.host, Number(this.port), this.options.server);
this.db = new mongo.Db(this.name, server, this.options.db);
}
this.db.open(fn);
return this;
};
/**
* Opens a set connection
*
* See description of doOpen for server options. In this case options.replset
* is also passed to ReplSetServers. Some additional options there are
*
* reconnectWait (default: 1000)
* retries (default: 30)
* rs_name (default: false)
* read_secondary (default: false) Are reads allowed from secondaries?
*
* @param {Function} fn
* @api private
*/
NativeConnection.prototype.doOpenSet = function (fn) {
if (!this.db) {
var servers = []
, ports = this.port
, self = this
this.host.forEach(function (host, i) {
servers.push(new mongo.Server(host, Number(ports[i]), self.options.server));
});
var server = new ReplSetServers(servers, this.options.replset);
this.db = new mongo.Db(this.name, server, this.options.db);
}
this.db.open(fn);
return this;
};
/**
* Closes the connection
*
* @param {Function} callback
* @api private
*/
NativeConnection.prototype.doClose = function (fn) {
this.db.close();
if (fn) fn();
return this;
}
/**
* Module exports.
*/
module.exports = NativeConnection;
|
CREATE TABLE country (id NVARCHAR(2) NOT NULL, name NVARCHAR(64) NOT NULL, PRIMARY KEY (id));
INSERT INTO [country] ([id], [name]) VALUES ('AF', 'Afghanistan');
INSERT INTO [country] ([id], [name]) VALUES ('ZA', 'Afrika Selatan');
INSERT INTO [country] ([id], [name]) VALUES ('AL', 'Albania');
INSERT INTO [country] ([id], [name]) VALUES ('DZ', 'Algeria');
INSERT INTO [country] ([id], [name]) VALUES ('US', 'Amerika Serikat');
INSERT INTO [country] ([id], [name]) VALUES ('AD', 'Andora');
INSERT INTO [country] ([id], [name]) VALUES ('AO', 'Angola');
INSERT INTO [country] ([id], [name]) VALUES ('AI', 'Anguilla');
INSERT INTO [country] ([id], [name]) VALUES ('AQ', 'Antarktika');
INSERT INTO [country] ([id], [name]) VALUES ('AG', 'Antigua dan Barbuda');
INSERT INTO [country] ([id], [name]) VALUES ('AN', 'Antilles Belanda');
INSERT INTO [country] ([id], [name]) VALUES ('SA', 'Arab Saudi');
INSERT INTO [country] ([id], [name]) VALUES ('AR', 'Argentina');
INSERT INTO [country] ([id], [name]) VALUES ('AM', 'Armenia');
INSERT INTO [country] ([id], [name]) VALUES ('AW', 'Aruba');
INSERT INTO [country] ([id], [name]) VALUES ('AU', 'Australia');
INSERT INTO [country] ([id], [name]) VALUES ('AT', 'Austria');
INSERT INTO [country] ([id], [name]) VALUES ('AZ', 'Azerbaijan');
INSERT INTO [country] ([id], [name]) VALUES ('BS', 'Bahamas');
INSERT INTO [country] ([id], [name]) VALUES ('BH', 'Bahrain');
INSERT INTO [country] ([id], [name]) VALUES ('BD', 'Bangladesh');
INSERT INTO [country] ([id], [name]) VALUES ('BB', 'Barbados');
INSERT INTO [country] ([id], [name]) VALUES ('BY', 'Belarusia');
INSERT INTO [country] ([id], [name]) VALUES ('BE', 'Belgia');
INSERT INTO [country] ([id], [name]) VALUES ('BZ', 'Belize');
INSERT INTO [country] ([id], [name]) VALUES ('BJ', 'Benin');
INSERT INTO [country] ([id], [name]) VALUES ('BM', 'Bermuda');
INSERT INTO [country] ([id], [name]) VALUES ('BT', 'Bhutan');
INSERT INTO [country] ([id], [name]) VALUES ('BO', 'Bolivia');
INSERT INTO [country] ([id], [name]) VALUES ('BA', 'Bosnia dan Herzegovina');
INSERT INTO [country] ([id], [name]) VALUES ('BW', 'Botswana');
INSERT INTO [country] ([id], [name]) VALUES ('BR', 'Brazil');
INSERT INTO [country] ([id], [name]) VALUES ('IO', 'British Indian Ocean Territory');
INSERT INTO [country] ([id], [name]) VALUES ('BN', 'Brunei');
INSERT INTO [country] ([id], [name]) VALUES ('BG', 'Bulgaria');
INSERT INTO [country] ([id], [name]) VALUES ('BF', 'Burkina Faso');
INSERT INTO [country] ([id], [name]) VALUES ('BI', 'Burundi');
INSERT INTO [country] ([id], [name]) VALUES ('TD', 'Chad');
INSERT INTO [country] ([id], [name]) VALUES ('CL', 'Chili');
INSERT INTO [country] ([id], [name]) VALUES ('CN', 'Cina');
INSERT INTO [country] ([id], [name]) VALUES ('DK', 'Denmark');
INSERT INTO [country] ([id], [name]) VALUES ('DM', 'Dominika');
INSERT INTO [country] ([id], [name]) VALUES ('EC', 'Ekuador');
INSERT INTO [country] ([id], [name]) VALUES ('SV', 'El Salvador');
INSERT INTO [country] ([id], [name]) VALUES ('ER', 'Eritrea');
INSERT INTO [country] ([id], [name]) VALUES ('EE', 'Estonia');
INSERT INTO [country] ([id], [name]) VALUES ('ET', 'Ethiopia');
INSERT INTO [country] ([id], [name]) VALUES ('FJ', 'Fiji');
INSERT INTO [country] ([id], [name]) VALUES ('PH', 'Filipina');
INSERT INTO [country] ([id], [name]) VALUES ('FI', 'Finlandia');
INSERT INTO [country] ([id], [name]) VALUES ('GA', 'Gabon');
INSERT INTO [country] ([id], [name]) VALUES ('GM', 'Gambia');
INSERT INTO [country] ([id], [name]) VALUES ('GE', 'Georgia');
INSERT INTO [country] ([id], [name]) VALUES ('GS', 'Georgia Selatan dan Kepulauan Sandwich Selatan');
INSERT INTO [country] ([id], [name]) VALUES ('GH', 'Ghana');
INSERT INTO [country] ([id], [name]) VALUES ('GI', 'Gibraltar');
INSERT INTO [country] ([id], [name]) VALUES ('GL', 'Greenland');
INSERT INTO [country] ([id], [name]) VALUES ('GD', 'Grenada');
INSERT INTO [country] ([id], [name]) VALUES ('GP', 'Guadeloupe');
INSERT INTO [country] ([id], [name]) VALUES ('GU', 'Guam');
INSERT INTO [country] ([id], [name]) VALUES ('GT', 'Guatemala');
INSERT INTO [country] ([id], [name]) VALUES ('GG', 'Guernsey');
INSERT INTO [country] ([id], [name]) VALUES ('GN', 'Guinea');
INSERT INTO [country] ([id], [name]) VALUES ('GQ', 'Guinea Khatulistiwa');
INSERT INTO [country] ([id], [name]) VALUES ('GW', 'Guinea-Bissau');
INSERT INTO [country] ([id], [name]) VALUES ('GY', 'Guyana');
INSERT INTO [country] ([id], [name]) VALUES ('GF', 'Guyana Perancis');
INSERT INTO [country] ([id], [name]) VALUES ('HT', 'Haiti');
INSERT INTO [country] ([id], [name]) VALUES ('HN', 'Honduras');
INSERT INTO [country] ([id], [name]) VALUES ('HK', 'Hong Kong S.A.R., Cina');
INSERT INTO [country] ([id], [name]) VALUES ('HU', 'Hungaria');
INSERT INTO [country] ([id], [name]) VALUES ('IN', 'India');
INSERT INTO [country] ([id], [name]) VALUES ('ID', 'Indonesia');
INSERT INTO [country] ([id], [name]) VALUES ('GB', 'Inggris Raya');
INSERT INTO [country] ([id], [name]) VALUES ('IR', 'Iran');
INSERT INTO [country] ([id], [name]) VALUES ('IQ', 'Iraq');
INSERT INTO [country] ([id], [name]) VALUES ('IE', 'Irlandia');
INSERT INTO [country] ([id], [name]) VALUES ('IS', 'Islandia');
INSERT INTO [country] ([id], [name]) VALUES ('IM', 'Isle of Man');
INSERT INTO [country] ([id], [name]) VALUES ('IL', 'Israel');
INSERT INTO [country] ([id], [name]) VALUES ('IT', 'Itali');
INSERT INTO [country] ([id], [name]) VALUES ('JM', 'Jamaika');
INSERT INTO [country] ([id], [name]) VALUES ('JP', 'Jepang');
INSERT INTO [country] ([id], [name]) VALUES ('DE', 'Jerman');
INSERT INTO [country] ([id], [name]) VALUES ('JE', 'Jersey');
INSERT INTO [country] ([id], [name]) VALUES ('DJ', 'Jibouti');
INSERT INTO [country] ([id], [name]) VALUES ('NC', 'Kaledonia Baru');
INSERT INTO [country] ([id], [name]) VALUES ('KH', 'Kamboja');
INSERT INTO [country] ([id], [name]) VALUES ('CM', 'Kamerun');
INSERT INTO [country] ([id], [name]) VALUES ('CA', 'Kanada');
INSERT INTO [country] ([id], [name]) VALUES ('KZ', 'Kazakhstan');
INSERT INTO [country] ([id], [name]) VALUES ('KE', 'Kenya');
INSERT INTO [country] ([id], [name]) VALUES ('MP', 'Kepualuan Mariana Utara');
INSERT INTO [country] ([id], [name]) VALUES ('BV', 'Kepulauan Bouvet');
INSERT INTO [country] ([id], [name]) VALUES ('VG', 'Kepulauan British Virgin');
INSERT INTO [country] ([id], [name]) VALUES ('CC', 'Kepulauan Cocos');
INSERT INTO [country] ([id], [name]) VALUES ('CK', 'Kepulauan Cook');
INSERT INTO [country] ([id], [name]) VALUES ('FK', 'Kepulauan Falkland');
INSERT INTO [country] ([id], [name]) VALUES ('FO', 'Kepulauan Faroe');
INSERT INTO [country] ([id], [name]) VALUES ('KY', 'Kepulauan Kayman');
INSERT INTO [country] ([id], [name]) VALUES ('MH', 'Kepulauan Marshall');
INSERT INTO [country] ([id], [name]) VALUES ('NF', 'Kepulauan Norfolk');
INSERT INTO [country] ([id], [name]) VALUES ('SB', 'Kepulauan Solomon');
INSERT INTO [country] ([id], [name]) VALUES ('TC', 'Kepulauan Turks dan Caicos');
INSERT INTO [country] ([id], [name]) VALUES ('VI', 'Kepulauan U.S. Virgin');
INSERT INTO [country] ([id], [name]) VALUES ('UM', 'Kepulauan minor sekitar Amerika Serikat');
INSERT INTO [country] ([id], [name]) VALUES ('KI', 'Kiribati');
INSERT INTO [country] ([id], [name]) VALUES ('CO', 'Kolombia');
INSERT INTO [country] ([id], [name]) VALUES ('KM', 'Komoros');
INSERT INTO [country] ([id], [name]) VALUES ('CG', 'Kongo');
INSERT INTO [country] ([id], [name]) VALUES ('KR', 'Korea Selatan');
INSERT INTO [country] ([id], [name]) VALUES ('KP', 'Korea Utara');
INSERT INTO [country] ([id], [name]) VALUES ('CR', 'Kosta Rika');
INSERT INTO [country] ([id], [name]) VALUES ('HR', 'Kroasia');
INSERT INTO [country] ([id], [name]) VALUES ('CU', 'Kuba');
INSERT INTO [country] ([id], [name]) VALUES ('KW', 'Kuwait');
INSERT INTO [country] ([id], [name]) VALUES ('KG', 'Kyrgyzstan');
INSERT INTO [country] ([id], [name]) VALUES ('LA', 'Laos');
INSERT INTO [country] ([id], [name]) VALUES ('LV', 'Latvia');
INSERT INTO [country] ([id], [name]) VALUES ('LB', 'Lebanon');
INSERT INTO [country] ([id], [name]) VALUES ('LS', 'Lesotho');
INSERT INTO [country] ([id], [name]) VALUES ('LR', 'Liberia');
INSERT INTO [country] ([id], [name]) VALUES ('LY', 'Libya');
INSERT INTO [country] ([id], [name]) VALUES ('LI', 'Liechtenstein');
INSERT INTO [country] ([id], [name]) VALUES ('LT', 'Lithuania');
INSERT INTO [country] ([id], [name]) VALUES ('LU', 'Luxembourg');
INSERT INTO [country] ([id], [name]) VALUES ('MK', 'Macedonia');
INSERT INTO [country] ([id], [name]) VALUES ('MG', 'Madagaskar');
INSERT INTO [country] ([id], [name]) VALUES ('MO', 'Makao S.A.R. Cina');
INSERT INTO [country] ([id], [name]) VALUES ('MW', 'Malawi');
INSERT INTO [country] ([id], [name]) VALUES ('MY', 'Malaysia');
INSERT INTO [country] ([id], [name]) VALUES ('MV', 'Maldives');
INSERT INTO [country] ([id], [name]) VALUES ('ML', 'Mali');
INSERT INTO [country] ([id], [name]) VALUES ('MT', 'Malta');
INSERT INTO [country] ([id], [name]) VALUES ('MA', 'Maroko');
INSERT INTO [country] ([id], [name]) VALUES ('MQ', 'Martinique');
INSERT INTO [country] ([id], [name]) VALUES ('MR', 'Mauritania');
INSERT INTO [country] ([id], [name]) VALUES ('MU', 'Mauritius');
INSERT INTO [country] ([id], [name]) VALUES ('YT', 'Mayotte');
INSERT INTO [country] ([id], [name]) VALUES ('EG', 'Mesir');
INSERT INTO [country] ([id], [name]) VALUES ('MX', 'Mexico');
INSERT INTO [country] ([id], [name]) VALUES ('FM', 'Mikronesia');
INSERT INTO [country] ([id], [name]) VALUES ('MD', 'Moldova');
INSERT INTO [country] ([id], [name]) VALUES ('MC', 'Monaco');
INSERT INTO [country] ([id], [name]) VALUES ('MN', 'Mongolia');
INSERT INTO [country] ([id], [name]) VALUES ('ME', 'Montenegro');
INSERT INTO [country] ([id], [name]) VALUES ('MS', 'Montserrat');
INSERT INTO [country] ([id], [name]) VALUES ('MZ', 'Mozambique');
INSERT INTO [country] ([id], [name]) VALUES ('MM', 'Myanmar');
INSERT INTO [country] ([id], [name]) VALUES ('NA', 'Namibia');
INSERT INTO [country] ([id], [name]) VALUES ('NR', 'Nauru');
INSERT INTO [country] ([id], [name]) VALUES ('NP', 'Nepal');
INSERT INTO [country] ([id], [name]) VALUES ('NL', 'Netherlands');
INSERT INTO [country] ([id], [name]) VALUES ('NI', 'Nicaragua');
INSERT INTO [country] ([id], [name]) VALUES ('NE', 'Niger');
INSERT INTO [country] ([id], [name]) VALUES ('NG', 'Nigeria');
INSERT INTO [country] ([id], [name]) VALUES ('NU', 'Niue');
INSERT INTO [country] ([id], [name]) VALUES ('NO', 'Norwegia');
INSERT INTO [country] ([id], [name]) VALUES ('OM', 'Oman');
INSERT INTO [country] ([id], [name]) VALUES ('PS', 'Otoritas Palestina');
INSERT INTO [country] ([id], [name]) VALUES ('PK', 'Pakistan');
INSERT INTO [country] ([id], [name]) VALUES ('PW', 'Palau');
INSERT INTO [country] ([id], [name]) VALUES ('PA', 'Panama');
INSERT INTO [country] ([id], [name]) VALUES ('CI', 'Pantai Gading');
INSERT INTO [country] ([id], [name]) VALUES ('PG', 'Papua Nugini');
INSERT INTO [country] ([id], [name]) VALUES ('PY', 'Paraguay');
INSERT INTO [country] ([id], [name]) VALUES ('FR', 'Perancis');
INSERT INTO [country] ([id], [name]) VALUES ('PE', 'Peru');
INSERT INTO [country] ([id], [name]) VALUES ('PN', 'Pitcairn');
INSERT INTO [country] ([id], [name]) VALUES ('PL', 'Polandia');
INSERT INTO [country] ([id], [name]) VALUES ('PF', 'Polynesia Perancis');
INSERT INTO [country] ([id], [name]) VALUES ('PT', 'Portugis');
INSERT INTO [country] ([id], [name]) VALUES ('PR', 'Puerto Riko');
INSERT INTO [country] ([id], [name]) VALUES ('CX', 'Pulau Christmas');
INSERT INTO [country] ([id], [name]) VALUES ('HM', 'Pulau Heard dan Kepulauan McDonald');
INSERT INTO [country] ([id], [name]) VALUES ('QA', 'Qatar');
INSERT INTO [country] ([id], [name]) VALUES ('CF', 'Republik Afrika Tengah');
INSERT INTO [country] ([id], [name]) VALUES ('CZ', 'Republik Ceko');
INSERT INTO [country] ([id], [name]) VALUES ('CD', 'Republik Demokratik Kongo');
INSERT INTO [country] ([id], [name]) VALUES ('DO', 'Republik Dominika');
INSERT INTO [country] ([id], [name]) VALUES ('RO', 'Romania');
INSERT INTO [country] ([id], [name]) VALUES ('RU', 'Rusia');
INSERT INTO [country] ([id], [name]) VALUES ('RW', 'Rwanda');
INSERT INTO [country] ([id], [name]) VALUES ('RE', 'Réunion');
INSERT INTO [country] ([id], [name]) VALUES ('EH', 'Sahara Barat');
INSERT INTO [country] ([id], [name]) VALUES ('SH', 'Saint Helena');
INSERT INTO [country] ([id], [name]) VALUES ('KN', 'Saint Kitts dan Nevis');
INSERT INTO [country] ([id], [name]) VALUES ('PM', 'Saint Pierre dan Miquelon');
INSERT INTO [country] ([id], [name]) VALUES ('VC', 'Saint Vincent dan Grenadines');
INSERT INTO [country] ([id], [name]) VALUES ('WS', 'Samoa');
INSERT INTO [country] ([id], [name]) VALUES ('AS', 'Samoa Amerika');
INSERT INTO [country] ([id], [name]) VALUES ('SM', 'San Marino');
INSERT INTO [country] ([id], [name]) VALUES ('LC', 'Santa Lusia');
INSERT INTO [country] ([id], [name]) VALUES ('ST', 'Sao Tome dan Principe');
INSERT INTO [country] ([id], [name]) VALUES ('NZ', 'Selandia Baru');
INSERT INTO [country] ([id], [name]) VALUES ('SN', 'Senegal');
INSERT INTO [country] ([id], [name]) VALUES ('RS', 'Serbia');
INSERT INTO [country] ([id], [name]) VALUES ('CS', 'Serbia dan Montenegro');
INSERT INTO [country] ([id], [name]) VALUES ('SC', 'Seychelles');
INSERT INTO [country] ([id], [name]) VALUES ('SL', 'Sierra Leone');
INSERT INTO [country] ([id], [name]) VALUES ('SG', 'Singapura');
INSERT INTO [country] ([id], [name]) VALUES ('CY', 'Siprus');
INSERT INTO [country] ([id], [name]) VALUES ('SK', 'Slovakia');
INSERT INTO [country] ([id], [name]) VALUES ('SI', 'Slovenia');
INSERT INTO [country] ([id], [name]) VALUES ('SO', 'Somalia');
INSERT INTO [country] ([id], [name]) VALUES ('ES', 'Spanyol');
INSERT INTO [country] ([id], [name]) VALUES ('LK', 'Sri Lanka');
INSERT INTO [country] ([id], [name]) VALUES ('SD', 'Sudan');
INSERT INTO [country] ([id], [name]) VALUES ('SR', 'Suriname');
INSERT INTO [country] ([id], [name]) VALUES ('SJ', 'Svalbard dan Jan Mayen');
INSERT INTO [country] ([id], [name]) VALUES ('SZ', 'Swaziland');
INSERT INTO [country] ([id], [name]) VALUES ('SE', 'Sweden');
INSERT INTO [country] ([id], [name]) VALUES ('CH', 'Swiss');
INSERT INTO [country] ([id], [name]) VALUES ('SY', 'Syria');
INSERT INTO [country] ([id], [name]) VALUES ('TW', 'Taiwan');
INSERT INTO [country] ([id], [name]) VALUES ('TJ', 'Tajikistan');
INSERT INTO [country] ([id], [name]) VALUES ('CV', 'Tanjung Verde');
INSERT INTO [country] ([id], [name]) VALUES ('TZ', 'Tanzania');
INSERT INTO [country] ([id], [name]) VALUES ('TH', 'Thailand');
INSERT INTO [country] ([id], [name]) VALUES ('TL', 'Timor Timur');
INSERT INTO [country] ([id], [name]) VALUES ('TG', 'Togo');
INSERT INTO [country] ([id], [name]) VALUES ('TK', 'Tokelau');
INSERT INTO [country] ([id], [name]) VALUES ('TO', 'Tonga');
INSERT INTO [country] ([id], [name]) VALUES ('TT', 'Trinidad dan Tobago');
INSERT INTO [country] ([id], [name]) VALUES ('TN', 'Tunisia');
INSERT INTO [country] ([id], [name]) VALUES ('TR', 'Turkey');
INSERT INTO [country] ([id], [name]) VALUES ('TM', 'Turkmenistan');
INSERT INTO [country] ([id], [name]) VALUES ('TV', 'Tuvalu');
INSERT INTO [country] ([id], [name]) VALUES ('UG', 'Uganda');
INSERT INTO [country] ([id], [name]) VALUES ('UA', 'Ukraina');
INSERT INTO [country] ([id], [name]) VALUES ('AE', 'Uni Emirat Arab');
INSERT INTO [country] ([id], [name]) VALUES ('UY', 'Uruguay');
INSERT INTO [country] ([id], [name]) VALUES ('UZ', 'Uzbekistan');
INSERT INTO [country] ([id], [name]) VALUES ('VU', 'Vanuatu');
INSERT INTO [country] ([id], [name]) VALUES ('VA', 'Vatikan');
INSERT INTO [country] ([id], [name]) VALUES ('VE', 'Venezuela');
INSERT INTO [country] ([id], [name]) VALUES ('VN', 'Vietnam');
INSERT INTO [country] ([id], [name]) VALUES ('WF', 'Wallis dan Futuna');
INSERT INTO [country] ([id], [name]) VALUES ('TF', 'Wilayah Prancis Selatan');
INSERT INTO [country] ([id], [name]) VALUES ('YE', 'Yaman');
INSERT INTO [country] ([id], [name]) VALUES ('JO', 'Yordania');
INSERT INTO [country] ([id], [name]) VALUES ('GR', 'Yunani');
INSERT INTO [country] ([id], [name]) VALUES ('ZM', 'Zambia');
INSERT INTO [country] ([id], [name]) VALUES ('ZW', 'Zimbabwe');
INSERT INTO [country] ([id], [name]) VALUES ('AX', 'Land Islands');
|
<?php
// autoload_namespaces.php generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Twig_Extensions_' => $vendorDir . '/twig/extensions/lib/',
'Twig_' => $vendorDir . '/twig/twig/lib/',
'Symfony\\Bundle\\SwiftmailerBundle' => $vendorDir . '/symfony/swiftmailer-bundle/',
'Symfony\\Bundle\\MonologBundle' => $vendorDir . '/symfony/monolog-bundle/',
'Symfony\\Bundle\\AsseticBundle' => $vendorDir . '/symfony/assetic-bundle/',
'Symfony\\' => $vendorDir . '/symfony/symfony/src/',
'Sensio\\Bundle\\GeneratorBundle' => $vendorDir . '/sensio/generator-bundle/',
'Sensio\\Bundle\\<API key>' => $vendorDir . '/sensio/<API key>/',
'Sensio\\Bundle\\DistributionBundle' => $vendorDir . '/sensio/distribution-bundle/',
'Psr\\Log\\' => $vendorDir . '/psr/log/',
'PhpOption\\' => $vendorDir . '/phpoption/phpoption/src/',
'Monolog' => $vendorDir . '/monolog/monolog/src/',
'Metadata\\' => $vendorDir . '/jms/metadata/src/',
'JMS\\SecurityExtraBundle' => $vendorDir . '/jms/<API key>/',
'JMS\\DiExtraBundle' => $vendorDir . '/jms/di-extra-bundle/',
'JMS\\AopBundle' => $vendorDir . '/jms/aop-bundle/',
'JMS\\' => $vendorDir . '/jms/parser-lib/src/',
'Doctrine\\ORM' => $vendorDir . '/doctrine/orm/lib/',
'Doctrine\\DBAL' => $vendorDir . '/doctrine/dbal/lib/',
'Doctrine\\Common' => $vendorDir . '/doctrine/common/lib/',
'Doctrine\\Bundle\\DoctrineBundle' => $vendorDir . '/doctrine/doctrine-bundle/',
'CG\\' => $vendorDir . '/jms/cg/src/',
'Assetic' => $vendorDir . '/kriswallsmith/assetic/src/',
'' => $baseDir . '/src/',
);
|
/*
* TEST SUITE FOR MB/WC FUNCTIONS IN C LIBRARY
*
* FILE: dat_towctrans.c
*
* TOWCTRANS: wint_t towctrans (wint_t wc, wctrans_t charclass);
*/
#include <errno.h>
#include <stdlib.h>
#include <wctype.h>
#include "tst_types.h"
#include "tgn_locdef.h"
/*
* NOTE:
* Set ret_flg = 1, when a return value is expected to be 0 (FALSE).
* Set ret_flg = 0, when a return value is expected to be non-zero (TRUE).
*
* Since the functions return *non*-zero value for TRUE, can't
* compare an actual return value with an expected return value.
* Set the ret_flg=0 for TRUE cases and the tst_isw*() will check
* the non-zero value.
*
* { { WEOF }, { 0,0,1,0 } },
* | |
* | ret_val: an expected return value
* ret_flg: if 1, compare an actual return value with the
* ret_val; if 0, the test program checks
* the actual return value.
*
* CAUTION: if a charclass is invalid, the test function gives
* towctrans() an invalid wctrans object instead of a return value
* from wctrans() which is supposed to be 0.
*/
TST_TOWCTRANS tst_towctrans_loc [] = {
{
{ Ttowctrans, TST_LOC_C },
{
#ifdef SHOJI_IS_RIGHT
{ { 0x0010, "xxxxxxx" }, { EINVAL,1,0x0010 } },
#else
{ { 0x0010, "xxxxxxx" }, { 0, 1,0x0010 } },
#endif
{ { 0x007F, "tolower" }, { 0, 1,0x007F } },
{ { 0x0061, "toupper" }, { 0, 1,0x0041 } },
{ { 0x0041, "tolower" }, { 0, 1,0x0061 } },
{ .is_last = 1 }
}
},
{
{ Ttowctrans, TST_LOC_de },
{
#ifdef SHOJI_IS_RIGHT
{ { 0x0010, "tojkata" }, { EINVAL,1,0x0010 } },
#else
{ { 0x0010, "tojkata" }, { 0, 1,0x0010 } },
#endif
{ { 0x0080, "tolower" }, { 0, 1,0x0080 } },
{ { 0x00EC, "toupper" }, { 0, 1,0x00CC } },
{ { 0x00CC, "tolower" }, { 0, 1,0x00EC } },
{ .is_last = 1 }
}
},
{
{ Ttowctrans, TST_LOC_enUS },
{
#ifdef SHOJI_IS_RIGHT
{ { 0x0010, "xxxxxxx" }, { EINVAL,1,0x0010 } },
#else
{ { 0x0010, "xxxxxxx" }, { 0, 1,0x0010 } },
#endif
{ { 0x007F, "tolower" }, { 0, 1,0x007F } },
{ { 0x0061, "toupper" }, { 0, 1,0x0041 } },
{ { 0x0041, "tolower" }, { 0, 1,0x0061 } },
{ .is_last = 1 }
}
},
{
{ Ttowctrans, TST_LOC_eucJP },
{
{ { 0xFF21, "tolower" }, { 0, 1,0xFF41 } },
{ { 0xFF41, "toupper" }, { 0, 1,0xFF21 } },
{ { 0x30A1, "tojhira" }, { 0, 1,0x3041 } },
{ { 0x3041, "tojkata" }, { 0, 1,0x30A1 } },
{ .is_last = 1 }
}
},
{
{ Ttowctrans, TST_LOC_end }
}
};
|
// $Id: ajax.js,v 1.26.2.2 2009/11/30 22:47:05 merlinofchaos Exp $
/**
* @file ajax_admin.js
*
* Handles AJAX submission and response in Views UI.
*/
Drupal.Views.Ajax = Drupal.Views.Ajax || {};
/**
* Handles the simple process of setting the ajax form area with new data.
*/
Drupal.Views.Ajax.setForm = function(title, output) {
$(Drupal.settings.views.ajax.title).html(title);
$(Drupal.settings.views.ajax.id).html(output);
}
/**
* An ajax responder that accepts a packet of JSON data and acts appropriately.
*
* The following fields control behavior.
* - 'display': Display the associated data in the form area; bind the new
* form to 'url' if appropriate. The 'title' field may also be used.
* - 'add': This is a keyed array of HTML output to add via append. The key is
* the id to append via $(key).append(value)
* - 'replace': This is a keyed array of HTML output to add via replace. The key is
* the id to append via $(key).html(value)
*
*/
Drupal.Views.Ajax.ajaxResponse = function(data) {
$('a.views-throbbing').removeClass('views-throbbing');
$('span.views-throbbing').remove();
if (data.debug) {
alert(data.debug);
}
// See if we have any settings to extend. Do this first so that behaviors
// can access the new settings easily.
if (Drupal.settings.viewsAjax) {
Drupal.settings.viewsAjax = {};
}
if (data.js) {
$.extend(Drupal.settings, data.js);
}
// Check the 'display' for data.
if (data.display) {
Drupal.Views.Ajax.setForm(data.title, data.display);
// if a URL was supplied, bind the form to it.
if (data.url) {
var ajax_area = Drupal.settings.views.ajax.id;
var ajax_title = Drupal.settings.views.ajax.title;
// Bind a click to the button to set the value for the button.
$('input[type=submit], button', ajax_area).unbind('click');
$('input[type=submit], button', ajax_area).click(function() {
$('form', ajax_area).append('<input type="hidden" name="'
+ $(this).attr('name') + '" value="' + $(this).val() + '">');
$(this).after('<span class="views-throbbing"> </span>');
});
// Bind forms to ajax submit.
$('form', ajax_area).unbind('submit'); // be safe here.
$('form', ajax_area).submit(function(arg) {
$(this).ajaxSubmit({
url: data.url,
data: { 'js': 1 },
type: 'POST',
success: Drupal.Views.Ajax.ajaxResponse,
error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': data.url})); },
dataType: 'json'
});
return false;
});
}
Drupal.attachBehaviors(ajax_area);
}
else {
// If no display, reset the form.
Drupal.Views.Ajax.setForm('', Drupal.settings.views.ajax.defaultForm);
//Enable the save button.
$('#edit-save').removeAttr('disabled');
// Trigger an update for the live preview when we reach this state:
$('#<API key>').trigger('submit');
}
// Go through the 'add' array and add any new content we're instructed to add.
if (data.add) {
for (id in data.add) {
var newContent = $(id).append(data.add[id]);
Drupal.attachBehaviors(newContent);
}
}
// Go through the 'replace' array and replace any content we're instructed to.
if (data.replace) {
for (id in data.replace) {
$(id).html(data.replace[id]);
Drupal.attachBehaviors(id);
}
}
// Go through and add any requested tabs
if (data.tab) {
for (id in data.tab) {
$('#views-tabset').addTab(id, data.tab[id]['title'], 0);
$(id).html(data.tab[id]['body']);
$(id).addClass('views-tab');
Drupal.attachBehaviors(id);
// This is kind of annoying, but we have to actually to find where the new
// tab is.
var instance = $.ui.tabs.instances[$('#views-tabset').get(0).UI_TABS_UUID];
$('#views-tabset').clickTab(instance.$tabs.length);
}
}
if (data.hilite) {
$('.hilited').removeClass('hilited');
$(data.hilite).addClass('hilited');
}
if (data.changed) {
$('div.views-basic-info').addClass('changed');
}
}
/**
* An ajax responder that accepts a packet of JSON data and acts appropriately.
* This one specifically responds to the Views live preview area, so it's
* hardcoded and specialized.
*/
Drupal.Views.Ajax.previewResponse = function(data) {
$('a.views-throbbing').removeClass('views-throbbing');
$('span.views-throbbing').remove();
if (data.debug) {
alert(data.debug);
}
// See if we have any settings to extend. Do this first so that behaviors
// can access the new settings easily.
// Clear any previous viewsAjax settings.
if (Drupal.settings.viewsAjax) {
Drupal.settings.viewsAjax = {};
}
if (data.js) {
$.extend(Drupal.settings, data.js);
}
// Check the 'display' for data.
if (data.display) {
var ajax_area = 'div#views-live-preview';
$(ajax_area).html(data.display);
var url = $(ajax_area, 'form').attr('action');
// if a URL was supplied, bind the form to it.
if (url) {
// Bind a click to the button to set the value for the button.
$('input[type=submit], button', ajax_area).unbind('click');
$('input[type=submit], button', ajax_area).click(function() {
$('form', ajax_area).append('<input type="hidden" name="'
+ $(this).attr('name') + '" value="' + $(this).val() + '">');
$(this).after('<span class="views-throbbing"> </span>');
});
// Bind forms to ajax submit.
$('form', ajax_area).unbind('submit'); // be safe here.
$('form', ajax_area).submit(function() {
$(this).ajaxSubmit({
url: url,
data: { 'js': 1 },
type: 'POST',
success: Drupal.Views.Ajax.previewResponse,
error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); },
dataType: 'json'
});
return false;
});
}
Drupal.attachBehaviors(ajax_area);
}
}
Drupal.Views.updatePreviewForm = function() {
var url = $(this).attr('action');
url = url.replace('nojs', 'ajax');
$('input[type=submit], button', this).after('<span class="views-throbbing"> </span>');
$(this).ajaxSubmit({
url: url,
data: { 'js': 1 },
type: 'POST',
success: Drupal.Views.Ajax.previewResponse,
error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); },
dataType: 'json'
});
return false;
}
Drupal.Views.<API key> = function() {
var url = $(this).attr('action');
url = url.replace('nojs', 'ajax');
$('input[type=submit], button', this).after('<span class="views-throbbing"> </span>');
$('input[name=q]', this).remove(); // remove 'q' for live preview.
$(this).ajaxSubmit({
url: url,
data: { 'js': 1 },
type: 'GET',
success: Drupal.Views.Ajax.previewResponse,
error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); },
dataType: 'json'
});
return false;
}
Drupal.Views.updatePreviewLink = function() {
var url = $(this).attr('href');
url = url.replace('nojs', 'ajax');
if (url.substring(0, 18) != '/admin/build/views') {
return true;
}
$(this).addClass('views-throbbing');
$.ajax({
url: url,
data: 'js=1',
type: 'POST',
success: Drupal.Views.Ajax.previewResponse,
error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': url})); },
dataType: 'json'
});
return false;
}
Drupal.behaviors.ViewsAjaxLinks = function() {
// Make specified links ajaxy.
$('a.views-ajax-link:not(.views-processed)').addClass('views-processed').click(function() {
// Translate the href on the link to the ajax href. That way this degrades
// into a nice, normal link.
var url = $(this).attr('href');
url = url.replace('nojs', 'ajax');
// Turn on the hilite to indicate this is in use.
$(this).addClass('hilite');
// Disable the save button.
$('#edit-save').attr('disabled', 'true');
$(this).addClass('views-throbbing');
$.ajax({
type: "POST",
url: url,
data: 'js=1',
success: Drupal.Views.Ajax.ajaxResponse,
error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': url})); },
dataType: 'json'
});
return false;
});
$('form.views-ajax-form:not(.views-processed)').addClass('views-processed').submit(function(arg) {
// Translate the href on the link to the ajax href. That way this degrades
// into a nice, normal link.
var url = $(this).attr('action');
url = url.replace('nojs', 'ajax');
// $('input[@type=submit]', this).after('<span class="views-throbbing"> </span>');
$(this).ajaxSubmit({
url: url,
data: { 'js': 1 },
type: 'POST',
success: Drupal.Views.Ajax.ajaxResponse,
error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); },
dataType: 'json'
});
return false;
});
// Bind the live preview to where it's supposed to go.
$('form#<API key>:not(.views-processed)')
.addClass('views-processed')
.submit(Drupal.Views.updatePreviewForm);
$('div#views-live-preview form:not(.views-processed)')
.addClass('views-processed')
.submit(Drupal.Views.<API key>);
$('div#views-live-preview a:not(.views-processed)')
.addClass('views-processed')
.click(Drupal.Views.updatePreviewLink);
}
/**
* Get rid of irritating tabledrag messages
*/
Drupal.theme.<API key> = function () {
return '<div></div>';
}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def <API key>():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def <API key>():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def <API key>():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def <API key>():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def <API key>():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def <API key>():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def <API key>():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def <API key>():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def <API key>():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def <API key>():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
|
#ifndef _FSL_CMP_H_
#define _FSL_CMP_H_
#include "fsl_common.h"
/*!
* @addtogroup cmp
* @{
*/
/*! @name Driver version */
/*! @brief CMP driver version 2.0.0. */
#define <API key> (MAKE_VERSION(2, 0, 0))
/*!
* @brief Interrupt enable/disable mask.
*/
enum <API key>
{
<API key> = CMP_SCR_IER_MASK, /*!< Comparator interrupt enable rising. */
<API key> = CMP_SCR_IEF_MASK, /*!< Comparator interrupt enable falling. */
};
/*!
* @brief Status flags' mask.
*/
enum _cmp_status_flags
{
<API key> = CMP_SCR_CFR_MASK, /*!< Rising-edge on the comparison output has occurred. */
<API key> = CMP_SCR_CFF_MASK, /*!< Falling-edge on the comparison output has occurred. */
<API key> = CMP_SCR_COUT_MASK, /*!< Return the current value of the analog comparator output. */
};
/*!
* @brief CMP Hysteresis mode.
*/
typedef enum <API key>
{
<API key> = 0U, /*!< Hysteresis level 0. */
<API key> = 1U, /*!< Hysteresis level 1. */
<API key> = 2U, /*!< Hysteresis level 2. */
<API key> = 3U, /*!< Hysteresis level 3. */
} <API key>;
/*!
* @brief CMP Voltage Reference source.
*/
typedef enum <API key>
{
kCMP_VrefSourceVin1 = 0U, /*!< Vin1 is selected as a resistor ladder network supply reference Vin. */
kCMP_VrefSourceVin2 = 1U, /*!< Vin2 is selected as a resistor ladder network supply reference Vin. */
} <API key>;
/*!
* @brief Configures the comparator.
*/
typedef struct _cmp_config
{
bool enableCmp; /*!< Enable the CMP module. */
<API key> hysteresisMode; /*!< CMP Hysteresis mode. */
bool enableHighSpeed; /*!< Enable High-speed (HS) comparison mode. */
bool enableInvertOutput; /*!< Enable the inverted comparator output. */
bool useUnfilteredOutput; /*!< Set the compare output(COUT) to equal COUTA(true) or COUT(false). */
bool enablePinOut; /*!< The comparator output is available on the associated pin. */
#if defined(<API key>) && <API key>
bool enableTriggerMode; /*!< Enable the trigger mode. */
#endif /* <API key> */
} cmp_config_t;
/*!
* @brief Configures the filter.
*/
typedef struct _cmp_filter_config
{
#if defined(<API key>) && <API key>
bool enableSample; /*!< Using the external SAMPLE as a sampling clock input or using a divided bus clock. */
#endif /* <API key> */
uint8_t filterCount; /*!< Filter Sample Count. Available range is 1-7; 0 disables the filter.*/
uint8_t filterPeriod; /*!< Filter Sample Period. The divider to the bus clock. Available range is 0-255. */
} cmp_filter_config_t;
/*!
* @brief Configures the internal DAC.
*/
typedef struct _cmp_dac_config
{
<API key> <API key>; /*!< Supply voltage reference source. */
uint8_t DACValue; /*!< Value for the DAC Output Voltage. Available range is 0-63.*/
} cmp_dac_config_t;
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @name Initialization
* @{
*/
/*!
* @brief Initializes the CMP.
*
* This function initializes the CMP module. The operations included are as follows.
* - Enabling the clock for CMP module.
* - Configuring the comparator.
* - Enabling the CMP module.
* Note that for some devices, multiple CMP instances share the same clock gate. In this case, to enable the clock for
* any instance enables all CMPs. See the appropriate MCU reference manual for the clock assignment of the CMP.
*
* @param base CMP peripheral base address.
* @param config Pointer to the configuration structure.
*/
void CMP_Init(CMP_Type *base, const cmp_config_t *config);
/*!
* @brief De-initializes the CMP module.
*
* This function de-initializes the CMP module. The operations included are as follows.
* - Disabling the CMP module.
* - Disabling the clock for CMP module.
*
* This function disables the clock for the CMP.
* Note that for some devices, multiple CMP instances share the same clock gate. In this case, before disabling the
* clock for the CMP, ensure that all the CMP instances are not used.
*
* @param base CMP peripheral base address.
*/
void CMP_Deinit(CMP_Type *base);
/*!
* @brief Enables/disables the CMP module.
*
* @param base CMP peripheral base address.
* @param enable Enables or disables the module.
*/
static inline void CMP_Enable(CMP_Type *base, bool enable)
{
if (enable)
{
base->CR1 |= CMP_CR1_EN_MASK;
}
else
{
base->CR1 &= ~CMP_CR1_EN_MASK;
}
}
/*!
* @brief Initializes the CMP user configuration structure.
*
* This function initializes the user configuration structure to these default values.
* @code
* config->enableCmp = true;
* config->hysteresisMode = <API key>;
* config->enableHighSpeed = false;
* config->enableInvertOutput = false;
* config->useUnfilteredOutput = false;
* config->enablePinOut = false;
* config->enableTriggerMode = false;
* @endcode
* @param config Pointer to the configuration structure.
*/
void <API key>(cmp_config_t *config);
/*!
* @brief Sets the input channels for the comparator.
*
* This function sets the input channels for the comparator.
* Note that two input channels cannot be set the same way in the application. When the user selects the same input
* from the analog mux to the positive and negative port, the comparator is disabled automatically.
*
* @param base CMP peripheral base address.
* @param positiveChannel Positive side input channel number. Available range is 0-7.
* @param negativeChannel Negative side input channel number. Available range is 0-7.
*/
void <API key>(CMP_Type *base, uint8_t positiveChannel, uint8_t negativeChannel);
/*!
* @name Advanced Features
* @{
*/
#if defined(<API key>) && <API key>
/*!
* @brief Enables/disables the DMA request for rising/falling events.
*
* This function enables/disables the DMA request for rising/falling events. Either event triggers the generation of
* the DMA request from CMP if the DMA feature is enabled. Both events are ignored for generating the DMA request from the CMP
* if the DMA is disabled.
*
* @param base CMP peripheral base address.
* @param enable Enables or disables the feature.
*/
void CMP_EnableDMA(CMP_Type *base, bool enable);
#endif /* <API key> */
#if defined(<API key>) && <API key>
/*!
* @brief Enables/disables the window mode.
*
* @param base CMP peripheral base address.
* @param enable Enables or disables the feature.
*/
static inline void <API key>(CMP_Type *base, bool enable)
{
if (enable)
{
base->CR1 |= CMP_CR1_WE_MASK;
}
else
{
base->CR1 &= ~CMP_CR1_WE_MASK;
}
}
#endif /* <API key> */
#if defined(<API key>) && <API key>
/*!
* @brief Enables/disables the pass through mode.
*
* @param base CMP peripheral base address.
* @param enable Enables or disables the feature.
*/
static inline void <API key>(CMP_Type *base, bool enable)
{
if (enable)
{
base->MUXCR |= CMP_MUXCR_PSTM_MASK;
}
else
{
base->MUXCR &= ~CMP_MUXCR_PSTM_MASK;
}
}
#endif /* <API key> */
/*!
* @brief Configures the filter.
*
* @param base CMP peripheral base address.
* @param config Pointer to the configuration structure.
*/
void CMP_SetFilterConfig(CMP_Type *base, const cmp_filter_config_t *config);
/*!
* @brief Configures the internal DAC.
*
* @param base CMP peripheral base address.
* @param config Pointer to the configuration structure. "NULL" disables the feature.
*/
void CMP_SetDACConfig(CMP_Type *base, const cmp_dac_config_t *config);
/*!
* @brief Enables the interrupts.
*
* @param base CMP peripheral base address.
* @param mask Mask value for interrupts. See "<API key>".
*/
void <API key>(CMP_Type *base, uint32_t mask);
/*!
* @brief Disables the interrupts.
*
* @param base CMP peripheral base address.
* @param mask Mask value for interrupts. See "<API key>".
*/
void <API key>(CMP_Type *base, uint32_t mask);
/*!
* @name Results
* @{
*/
/*!
* @brief Gets the status flags.
*
* @param base CMP peripheral base address.
*
* @return Mask value for the asserted flags. See "_cmp_status_flags".
*/
uint32_t CMP_GetStatusFlags(CMP_Type *base);
/*!
* @brief Clears the status flags.
*
* @param base CMP peripheral base address.
* @param mask Mask value for the flags. See "_cmp_status_flags".
*/
void <API key>(CMP_Type *base, uint32_t mask);
#if defined(__cplusplus)
}
#endif
#endif /* _FSL_CMP_H_ */
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<title>Página web no disponible</title>
<style type="text/css">
body { margin-top: 0px; padding-top: 0px; }
h2 { margin-top: 5px; padding-top: 0px; }
</style>
<body>
<img src="file:///android_asset/webkit/android-weberror.png" align="top" />
<h2>Página web no disponible</h2>
<p>La página web <a href="%s">%s</a> no se ha podido cargar como:</p>
<!-- The %e is replaced by a localized error string -->
<p>%e</p>
</body>
</head>
</html>
|
esprima.tokenize(null);
|
!function(e){e.calendarsPicker.regionalOptions.km={renderer:e.calendarsPicker.defaultRenderer,prevText:"ថយក្រោយ",prevStatus:"",prevJumpText:"&
|
<!DOCTYPE html>
<html>
<head>
<title>
Test case for https://bugs.webkit.org/show_bug.cgi?id=61338
</title>
<style>
.rotated {
transform:rotate(50deg);
}
</style>
<script src="resources/text-based-repaint.js" type="text/javascript"></script>
<script>
function repaintTest() {
document.getElementById('rel').classList.remove('rotated');
}
</script>
</head>
<body onload="runRepaintTest()">
<!
<p> Bug <a href="https://bugs.webkit.org/show_bug.cgi?id=61338">61338</a>: Element not fully repainted after application and removal of transform </p>
<p> The test PASSES only if all the four borders of the box are displayed in green</p>
<div id="rel" class="rotated" style="height:50px; width:200px; background-color:yellow ; border:10px solid green;"> </div>
</body>
</html>
|
#include "mojo/public/cpp/bindings/lib/<API key>.h"
#include "mojo/public/cpp/bindings/lib/bindings_internal.h"
#include "mojo/public/cpp/bindings/lib/bounds_checker.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/cpp/environment/logging.h"
namespace mojo {
namespace internal {
namespace {
const size_t kAlignment = 8;
template<typename T>
T AlignImpl(T t) {
return t + (kAlignment - (t % kAlignment)) % kAlignment;
}
} // namespace
size_t Align(size_t size) {
return AlignImpl(size);
}
char* AlignPointer(char* ptr) {
return reinterpret_cast<char*>(AlignImpl(reinterpret_cast<uintptr_t>(ptr)));
}
bool IsAligned(const void* ptr) {
return !(reinterpret_cast<uintptr_t>(ptr) % kAlignment);
}
void EncodePointer(const void* ptr, uint64_t* offset) {
if (!ptr) {
*offset = 0;
return;
}
const char* p_obj = reinterpret_cast<const char*>(ptr);
const char* p_slot = reinterpret_cast<const char*>(offset);
MOJO_DCHECK(p_obj > p_slot);
*offset = static_cast<uint64_t>(p_obj - p_slot);
}
const void* DecodePointerRaw(const uint64_t* offset) {
if (!*offset)
return NULL;
return reinterpret_cast<const char*>(offset) + *offset;
}
bool <API key>(const uint64_t* offset) {
// Cast to uintptr_t so overflow behavior is well defined.
return reinterpret_cast<uintptr_t>(offset) + *offset >=
reinterpret_cast<uintptr_t>(offset);
}
void EncodeHandle(Handle* handle, std::vector<Handle>* handles) {
if (handle->is_valid()) {
handles->push_back(*handle);
handle->set_value(static_cast<MojoHandle>(handles->size() - 1));
} else {
handle->set_value(<API key>);
}
}
void DecodeHandle(Handle* handle, std::vector<Handle>* handles) {
if (handle->value() == <API key>) {
*handle = Handle();
return;
}
MOJO_DCHECK(handle->value() < handles->size());
// Just leave holes in the vector so we don't screw up other indices.
*handle = FetchAndReset(&handles->at(handle->value()));
}
bool <API key>(const void* data,
uint32_t min_num_bytes,
uint32_t min_num_fields,
BoundsChecker* bounds_checker) {
MOJO_DCHECK(min_num_bytes >= sizeof(StructHeader));
if (!IsAligned(data)) {
<API key>(<API key>);
return false;
}
if (!bounds_checker->IsValidRange(data, sizeof(StructHeader))) {
<API key>(<API key>);
return false;
}
const StructHeader* header = static_cast<const StructHeader*>(data);
// TODO(yzshen): Currently our binding code cannot handle structs of smaller
// size or with fewer fields than the version that it sees. That needs to be
// changed in order to provide backward compatibility.
if (header->num_bytes < min_num_bytes ||
header->num_fields < min_num_fields) {
<API key>(<API key>);
return false;
}
if (!bounds_checker->ClaimMemory(data, header->num_bytes)) {
<API key>(<API key>);
return false;
}
return true;
}
} // namespace internal
} // namespace mojo
|
#include <stddef.h>
#include <stdint.h>
#include "base/files/memory_mapped_file.h"
#include "media/base/test_data_util.h"
#include "media/filters/ivf_parser.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
TEST(IvfParserTest, StreamFileParsing) {
base::FilePath file_path = GetTestDataFilePath("test-25fps.vp8");
base::MemoryMappedFile stream;
ASSERT_TRUE(stream.Initialize(file_path)) << "Couldn't open stream file: "
<< file_path.MaybeAsASCII();
IvfParser parser;
IvfFileHeader file_header = {};
EXPECT_TRUE(parser.Initialize(stream.data(), stream.length(), &file_header));
// Check file header fields.
EXPECT_EQ(0, memcmp(file_header.signature, kIvfHeaderSignature,
sizeof(file_header.signature)));
EXPECT_EQ(0, file_header.version);
EXPECT_EQ(sizeof(IvfFileHeader), file_header.header_size);
EXPECT_EQ(0x30385056u, file_header.fourcc); // VP80
EXPECT_EQ(320u, file_header.width);
EXPECT_EQ(240u, file_header.height);
EXPECT_EQ(50u, file_header.timebase_denum);
EXPECT_EQ(2u, file_header.timebase_num);
EXPECT_EQ(250u, file_header.num_frames);
IvfFrameHeader frame_header;
size_t num_parsed_frames = 0;
const uint8_t* payload = nullptr;
while (parser.ParseNextFrame(&frame_header, &payload)) {
++num_parsed_frames;
EXPECT_TRUE(payload != nullptr);
// Only check the first frame.
if (num_parsed_frames == 1u) {
EXPECT_EQ(14788u, frame_header.frame_size);
EXPECT_EQ(0u, frame_header.timestamp);
EXPECT_EQ(
static_cast<ptrdiff_t>(sizeof(file_header) + sizeof(frame_header)),
payload - stream.data());
}
}
EXPECT_EQ(file_header.num_frames, num_parsed_frames);
}
} // namespace media
|
using Orchard.ContentManagement.MetaData;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
namespace Orchard.CustomForms {
public class Migrations : DataMigrationImpl {
public int Create() {
<API key>.AlterTypeDefinition("CustomForm",
cfg => cfg
.WithPart("CommonPart")
.WithPart("TitlePart")
.WithPart("AutoroutePart", builder => builder
.WithSetting("AutorouteSettings.AllowCustomPattern", "true")
.WithSetting("AutorouteSettings.<API key>", "false")
.WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Title', Pattern: '{Content.Slug}', Description: 'my-form'}]")
.WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))
.WithPart("MenuPart")
.WithPart("CustomFormPart")
.DisplayedAs("Custom Form")
.Draftable()
);
SchemaBuilder.CreateTable("<API key>", table => table.<API key>()
.Column<string>("ContentType", c => c.WithLength(255))
.Column<bool>("CustomMessage")
.Column<string>("Message", c => c.Unlimited())
.Column<bool>("Redirect")
.Column<string>("RedirectUrl", c => c.Unlimited())
.Column<bool>("SaveContentItem")
);
return 1;
}
public int UpdateFrom1() {
<API key>.AlterTypeDefinition("CustomFormWidget",
cfg => cfg
.WithPart("WidgetPart")
.WithPart("CommonPart")
.WithPart("IdentityPart")
.WithPart("CustomFormPart")
.WithSetting("Stereotype", "Widget")
);
return 2;
}
public void Uninstall() {
<API key>.<API key>("CustomForm");
}
}
}
|
/*
* Driver for the Texas Instruments TMP421 SMBus temperature sensor IC.
* Supported models: TMP421, TMP422, TMP423
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x2a, 0x4c, 0x4d, 0x4e, 0x4f,
I2C_CLIENT_END };
enum chips { tmp421, tmp422, tmp423 };
/* The TMP421 registers */
#define TMP421_CONFIG_REG_1 0x09
#define <API key> 0x0B
#define <API key> 0xFE
#define <API key> 0xFF
static const u8 TMP421_TEMP_MSB[4] = { 0x00, 0x01, 0x02, 0x03 };
static const u8 TMP421_TEMP_LSB[4] = { 0x10, 0x11, 0x12, 0x13 };
/* Flags */
#define <API key> 0x40
#define TMP421_CONFIG_RANGE 0x04
/* Manufacturer / Device ID's */
#define <API key> 0x55
#define TMP421_DEVICE_ID 0x21
#define TMP422_DEVICE_ID 0x22
#define TMP423_DEVICE_ID 0x23
static const struct i2c_device_id tmp421_id[] = {
{ "tmp421", 2 },
{ "tmp422", 3 },
{ "tmp423", 4 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tmp421_id);
struct tmp421_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid;
unsigned long last_updated;
int channels;
u8 config;
s16 temp[4];
};
static int temp_from_s16(s16 reg)
{
/* Mask out status bits */
int temp = reg & ~0xf;
return (temp * 1000 + 128) / 256;
}
static int temp_from_u16(u16 reg)
{
/* Mask out status bits */
int temp = reg & ~0xf;
/* Add offset for extended temperature range. */
temp -= 64 * 256;
return (temp * 1000 + 128) / 256;
}
static struct tmp421_data *<API key>(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct tmp421_data *data = i2c_get_clientdata(client);
int i;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + 2 * HZ) || !data->valid) {
data->config = <API key>(client,
TMP421_CONFIG_REG_1);
for (i = 0; i < data->channels; i++) {
data->temp[i] = <API key>(client,
TMP421_TEMP_MSB[i]) << 8;
data->temp[i] |= <API key>(client,
TMP421_TEMP_LSB[i]);
}
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_temp_value(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp421_data *data = <API key>(dev);
int temp;
mutex_lock(&data->update_lock);
if (data->config & TMP421_CONFIG_RANGE)
temp = temp_from_u16(data->temp[index]);
else
temp = temp_from_s16(data->temp[index]);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
static ssize_t show_fault(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int index = to_sensor_dev_attr(devattr)->index;
struct tmp421_data *data = <API key>(dev);
/*
* The OPEN bit signals a fault. This is bit 0 of the temperature
* register (low byte).
*/
if (data->temp[index] & 0x01)
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static umode_t tmp421_is_visible(struct kobject *kobj, struct attribute *a,
int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct tmp421_data *data = dev_get_drvdata(dev);
struct device_attribute *devattr;
unsigned int index;
devattr = container_of(a, struct device_attribute, attr);
index = to_sensor_dev_attr(devattr)->index;
if (index < data->channels)
return a->mode;
return 0;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp_value, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_temp_value, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_fault, NULL, 1);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_temp_value, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_fault, NULL, 2);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_temp_value, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_fault, S_IRUGO, show_fault, NULL, 3);
static struct attribute *tmp421_attr[] = {
&<API key>.dev_attr.attr,
&<API key>.dev_attr.attr,
&<API key>.dev_attr.attr,
&<API key>.dev_attr.attr,
&<API key>.dev_attr.attr,
&<API key>.dev_attr.attr,
&<API key>.dev_attr.attr,
NULL
};
static const struct attribute_group tmp421_group = {
.attrs = tmp421_attr,
.is_visible = tmp421_is_visible,
};
static int tmp421_init_client(struct i2c_client *client)
{
int config, config_orig;
/* Set the conversion rate to 2 Hz */
<API key>(client, <API key>, 0x05);
/* Start conversions (disable shutdown if necessary) */
config = <API key>(client, TMP421_CONFIG_REG_1);
if (config < 0) {
dev_err(&client->dev, "Could not read configuration"
" register (%d)\n", config);
return -ENODEV;
}
config_orig = config;
config &= ~<API key>;
if (config != config_orig) {
dev_info(&client->dev, "Enable monitoring chip\n");
<API key>(client, TMP421_CONFIG_REG_1, config);
}
return 0;
}
static int tmp421_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
enum chips kind;
struct i2c_adapter *adapter = client->adapter;
const char *names[] = { "TMP421", "TMP422", "TMP423" };
u8 reg;
if (!<API key>(adapter, <API key>))
return -ENODEV;
reg = <API key>(client, <API key>);
if (reg != <API key>)
return -ENODEV;
reg = <API key>(client, <API key>);
switch (reg) {
case TMP421_DEVICE_ID:
kind = tmp421;
break;
case TMP422_DEVICE_ID:
kind = tmp422;
break;
case TMP423_DEVICE_ID:
kind = tmp423;
break;
default:
return -ENODEV;
}
strlcpy(info->type, tmp421_id[kind].name, I2C_NAME_SIZE);
dev_info(&adapter->dev, "Detected TI %s chip at 0x%02x\n",
names[kind], client->addr);
return 0;
}
static int tmp421_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct tmp421_data *data;
int err;
data = devm_kzalloc(&client->dev, sizeof(struct tmp421_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
data->channels = id->driver_data;
err = tmp421_init_client(client);
if (err)
return err;
err = sysfs_create_group(&client->dev.kobj, &tmp421_group);
if (err)
return err;
data->hwmon_dev = <API key>(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto exit_remove;
}
return 0;
exit_remove:
sysfs_remove_group(&client->dev.kobj, &tmp421_group);
return err;
}
static int tmp421_remove(struct i2c_client *client)
{
struct tmp421_data *data = i2c_get_clientdata(client);
<API key>(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &tmp421_group);
return 0;
}
static struct i2c_driver tmp421_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "tmp421",
},
.probe = tmp421_probe,
.remove = tmp421_remove,
.id_table = tmp421_id,
.detect = tmp421_detect,
.address_list = normal_i2c,
};
module_i2c_driver(tmp421_driver);
MODULE_AUTHOR("Andre Prendel <andre.prendel@gmx.de>");
MODULE_DESCRIPTION("Texas Instruments TMP421/422/423 temperature sensor"
" driver");
MODULE_LICENSE("GPL");
|
#include "CCLabelTTF.h"
#include "CCDirector.h"
#include "shaders/CCGLProgram.h"
#include "shaders/CCShaderCache.h"
#include "CCApplication.h"
NS_CC_BEGIN
#if CC_USE_LA88_LABELS
#define SHADER_PROGRAM <API key>
#else
#define SHADER_PROGRAM <API key>
#endif
//CCLabelTTF
CCLabelTTF::CCLabelTTF()
: m_hAlignment(<API key>)
, m_vAlignment(<API key>)
, m_pFontName(NULL)
, m_fFontSize(0.0)
, m_string("")
, m_shadowEnabled(false)
, m_strokeEnabled(false)
, m_textFillColor(ccWHITE)
{
}
CCLabelTTF::~CCLabelTTF()
{
CC_SAFE_DELETE(m_pFontName);
}
CCLabelTTF * CCLabelTTF::create()
{
CCLabelTTF * pRet = new CCLabelTTF();
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
CCLabelTTF * CCLabelTTF::create(const char *string, const char *fontName, float fontSize)
{
return CCLabelTTF::create(string, fontName, fontSize,
CCSizeZero, <API key>, <API key>);
}
CCLabelTTF * CCLabelTTF::create(const char *string, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment hAlignment)
{
return CCLabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, <API key>);
}
CCLabelTTF* CCLabelTTF::create(const char *string, const char *fontName, float fontSize,
const CCSize &dimensions, CCTextAlignment hAlignment,
<API key> vAlignment)
{
CCLabelTTF *pRet = new CCLabelTTF();
if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
CCLabelTTF * CCLabelTTF::<API key>(const char *string, ccFontDefinition &textDefinition)
{
CCLabelTTF *pRet = new CCLabelTTF();
if(pRet && pRet-><API key>(string, textDefinition))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCLabelTTF::init()
{
return this->initWithString("", "Helvetica", 12);
}
bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment alignment)
{
return this->initWithString(label, fontName, fontSize, dimensions, alignment, <API key>);
}
bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize)
{
return this->initWithString(label, fontName, fontSize,
CCSizeZero, <API key>, <API key>);
}
bool CCLabelTTF::initWithString(const char *string, const char *fontName, float fontSize,
const cocos2d::CCSize &dimensions, CCTextAlignment hAlignment,
<API key> vAlignment)
{
if (CCSprite::init())
{
// shader program
this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM));
m_tDimensions = CCSizeMake(dimensions.width, dimensions.height);
m_hAlignment = hAlignment;
m_vAlignment = vAlignment;
m_pFontName = new std::string(fontName);
m_fFontSize = fontSize;
this->setString(string);
return true;
}
return false;
}
bool CCLabelTTF::<API key>(const char *string, ccFontDefinition &textDefinition)
{
if (CCSprite::init())
{
// shader program
this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM));
// prepare everythin needed to render the label
<API key>(textDefinition, false);
// set the string
this->setString(string);
return true;
}
else
{
return false;
}
}
void CCLabelTTF::setString(const char *string)
{
CCAssert(string != NULL, "Invalid string");
if (m_string.compare(string))
{
m_string = string;
this->updateTexture();
}
}
const char* CCLabelTTF::getString(void)
{
return m_string.c_str();
}
const char* CCLabelTTF::description()
{
return CCString::createWithFormat("<CCLabelTTF | FontName = %s, FontSize = %.1f>", m_pFontName->c_str(), m_fFontSize)->getCString();
}
CCTextAlignment CCLabelTTF::<API key>()
{
return m_hAlignment;
}
void CCLabelTTF::<API key>(CCTextAlignment alignment)
{
if (alignment != m_hAlignment)
{
m_hAlignment = alignment;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
<API key> CCLabelTTF::<API key>()
{
return m_vAlignment;
}
void CCLabelTTF::<API key>(<API key> verticalAlignment)
{
if (verticalAlignment != m_vAlignment)
{
m_vAlignment = verticalAlignment;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
CCSize CCLabelTTF::getDimensions()
{
return m_tDimensions;
}
void CCLabelTTF::setDimensions(const CCSize &dim)
{
if (dim.width != m_tDimensions.width || dim.height != m_tDimensions.height)
{
m_tDimensions = dim;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
float CCLabelTTF::getFontSize()
{
return m_fFontSize;
}
void CCLabelTTF::setFontSize(float fontSize)
{
if (m_fFontSize != fontSize)
{
m_fFontSize = fontSize;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
const char* CCLabelTTF::getFontName()
{
return m_pFontName->c_str();
}
void CCLabelTTF::setFontName(const char *fontName)
{
if (m_pFontName->compare(fontName))
{
delete m_pFontName;
m_pFontName = new std::string(fontName);
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
// Helper
bool CCLabelTTF::updateTexture()
{
CCTexture2D *tex;
tex = new CCTexture2D();
if (!tex)
return false;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
ccFontDefinition texDef = <API key>(true);
tex->initWithString( m_string.c_str(), &texDef );
#else
tex->initWithString( m_string.c_str(),
m_pFontName->c_str(),
m_fFontSize * <API key>(),
<API key>(m_tDimensions),
m_hAlignment,
m_vAlignment);
#endif
// set the texture
this->setTexture(tex);
// release it
tex->release();
// set the size in the sprite
CCRect rect =CCRectZero;
rect.size = m_pobTexture->getContentSize();
this->setTextureRect(rect);
return true;
}
void CCLabelTTF::enableShadow(const CCSize &shadowOffset, float shadowOpacity, float shadowBlur, bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
bool valueChanged = false;
if (false == m_shadowEnabled)
{
m_shadowEnabled = true;
valueChanged = true;
}
if ( (m_shadowOffset.width != shadowOffset.width) || (m_shadowOffset.height!=shadowOffset.height) )
{
m_shadowOffset.width = shadowOffset.width;
m_shadowOffset.height = shadowOffset.height;
valueChanged = true;
}
if (m_shadowOpacity != shadowOpacity )
{
m_shadowOpacity = shadowOpacity;
valueChanged = true;
}
if (m_shadowBlur != shadowBlur)
{
m_shadowBlur = shadowBlur;
valueChanged = true;
}
if ( valueChanged && updateTexture )
{
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::disableShadow(bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (m_shadowEnabled)
{
m_shadowEnabled = false;
if (updateTexture)
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::enableStroke(const ccColor3B &strokeColor, float strokeSize, bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
bool valueChanged = false;
if(m_strokeEnabled == false)
{
m_strokeEnabled = true;
valueChanged = true;
}
if ( (m_strokeColor.r != strokeColor.r) || (m_strokeColor.g != strokeColor.g) || (m_strokeColor.b != strokeColor.b) )
{
m_strokeColor = strokeColor;
valueChanged = true;
}
if (m_strokeSize!=strokeSize)
{
m_strokeSize = strokeSize;
valueChanged = true;
}
if ( valueChanged && updateTexture )
{
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::disableStroke(bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (m_strokeEnabled)
{
m_strokeEnabled = false;
if (updateTexture)
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::setFontFillColor(const ccColor3B &tintColor, bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (m_textFillColor.r != tintColor.r || m_textFillColor.g != tintColor.g || m_textFillColor.b != tintColor.b)
{
m_textFillColor = tintColor;
if (updateTexture)
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::setTextDefinition(ccFontDefinition *theDefinition)
{
if (theDefinition)
{
<API key>(*theDefinition, true);
}
}
ccFontDefinition *CCLabelTTF::getTextDefinition()
{
ccFontDefinition *tempDefinition = new ccFontDefinition;
*tempDefinition = <API key>(false);
return tempDefinition;
}
void CCLabelTTF::<API key>(ccFontDefinition & textDefinition, bool mustUpdateTexture)
{
m_tDimensions = CCSizeMake(textDefinition.m_dimensions.width, textDefinition.m_dimensions.height);
m_hAlignment = textDefinition.m_alignment;
m_vAlignment = textDefinition.m_vertAlignment;
m_pFontName = new std::string(textDefinition.m_fontName);
m_fFontSize = textDefinition.m_fontSize;
// shadow
if ( textDefinition.m_shadow.m_shadowEnabled )
{
enableShadow(textDefinition.m_shadow.m_shadowOffset, textDefinition.m_shadow.m_shadowOpacity, textDefinition.m_shadow.m_shadowBlur, false);
}
// stroke
if ( textDefinition.m_stroke.m_strokeEnabled )
{
enableStroke(textDefinition.m_stroke.m_strokeColor, textDefinition.m_stroke.m_strokeSize, false);
}
// fill color
setFontFillColor(textDefinition.m_fontFillColor, false);
if (mustUpdateTexture)
updateTexture();
}
ccFontDefinition CCLabelTTF::<API key>(bool adjustForResolution)
{
ccFontDefinition texDef;
if (adjustForResolution)
texDef.m_fontSize = m_fFontSize * <API key>();
else
texDef.m_fontSize = m_fFontSize;
texDef.m_fontName = *m_pFontName;
texDef.m_alignment = m_hAlignment;
texDef.m_vertAlignment = m_vAlignment;
if (adjustForResolution)
texDef.m_dimensions = <API key>(m_tDimensions);
else
texDef.m_dimensions = m_tDimensions;
// stroke
if ( m_strokeEnabled )
{
texDef.m_stroke.m_strokeEnabled = true;
texDef.m_stroke.m_strokeColor = m_strokeColor;
if (adjustForResolution)
texDef.m_stroke.m_strokeSize = m_strokeSize * <API key>();
else
texDef.m_stroke.m_strokeSize = m_strokeSize;
}
else
{
texDef.m_stroke.m_strokeEnabled = false;
}
// shadow
if ( m_shadowEnabled )
{
texDef.m_shadow.m_shadowEnabled = true;
texDef.m_shadow.m_shadowBlur = m_shadowBlur;
texDef.m_shadow.m_shadowOpacity = m_shadowOpacity;
if (adjustForResolution)
texDef.m_shadow.m_shadowOffset = <API key>(m_shadowOffset);
else
texDef.m_shadow.m_shadowOffset = m_shadowOffset;
}
else
{
texDef.m_shadow.m_shadowEnabled = false;
}
// text tint
texDef.m_fontFillColor = m_textFillColor;
return texDef;
}
NS_CC_END
|
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.DirectoryServices.ActiveDirectory
{
public class GlobalCatalog : DomainController
{
// private variables
private <API key> _schema = null;
private bool _disabled = false;
#region constructors
internal GlobalCatalog(DirectoryContext context, string globalCatalogName)
: base(context, globalCatalogName)
{ }
internal GlobalCatalog(DirectoryContext context, string globalCatalogName, <API key> directoryEntryMgr)
: base(context, globalCatalogName, directoryEntryMgr)
{ }
#endregion constructors
#region public methods
public static GlobalCatalog GetGlobalCatalog(DirectoryContext context)
{
string gcDnsName = null;
bool isGlobalCatalog = false;
<API key> directoryEntryMgr = null;
// check that the context argument is not null
if (context == null)
throw new <API key>("context");
// target should be GC
if (context.ContextType != <API key>.DirectoryServer)
{
throw new ArgumentException(SR.TargetShouldBeGC, "context");
}
// target should be a server
if (!(context.isServer()))
{
throw new <API key>(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
// work with copy of the context
context = new DirectoryContext(context);
try
{
// Get dns name of the dc
// by binding to root dse and getting the "dnsHostName" attribute
// (also check that the "<API key>" attribute is true)
directoryEntryMgr = new <API key>(context);
DirectoryEntry rootDSE = <API key>.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
throw new <API key>(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
isGlobalCatalog = (bool)Boolean.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.<API key>));
if (!isGlobalCatalog)
{
throw new <API key>(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
throw new <API key>(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
else
{
throw ExceptionHelper.<API key>(context, e);
}
}
return new GlobalCatalog(context, gcDnsName, directoryEntryMgr);
}
public static new GlobalCatalog FindOne(DirectoryContext context)
{
if (context == null)
{
throw new <API key>("context");
}
if (context.ContextType != <API key>.Forest)
{
throw new ArgumentException(SR.<API key>, "context");
}
return <API key>(context, null, 0);
}
public static new GlobalCatalog FindOne(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new <API key>("context");
}
if (context.ContextType != <API key>.Forest)
{
throw new ArgumentException(SR.<API key>, "context");
}
if (siteName == null)
{
throw new <API key>("siteName");
}
return <API key>(context, siteName, 0);
}
public static new GlobalCatalog FindOne(DirectoryContext context, LocatorOptions flag)
{
if (context == null)
{
throw new <API key>("context");
}
if (context.ContextType != <API key>.Forest)
{
throw new ArgumentException(SR.<API key>, "context");
}
return <API key>(context, null, flag);
}
public static new GlobalCatalog FindOne(DirectoryContext context, string siteName, LocatorOptions flag)
{
if (context == null)
{
throw new <API key>("context");
}
if (context.ContextType != <API key>.Forest)
{
throw new ArgumentException(SR.<API key>, "context");
}
if (siteName == null)
{
throw new <API key>("siteName");
}
return <API key>(context, siteName, flag);
}
public static new <API key> FindAll(DirectoryContext context)
{
if (context == null)
{
throw new <API key>("context");
}
if (context.ContextType != <API key>.Forest)
{
throw new ArgumentException(SR.<API key>, "context");
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, null);
}
public static new <API key> FindAll(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new <API key>("context");
}
if (context.ContextType != <API key>.Forest)
{
throw new ArgumentException(SR.<API key>, "context");
}
if (siteName == null)
{
throw new <API key>("siteName");
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, siteName);
}
public override GlobalCatalog EnableGlobalCatalog()
{
CheckIfDisposed();
throw new <API key>(SR.<API key>);
}
public DomainController <API key>()
{
CheckIfDisposed();
CheckIfDisabled();
// bind to the server object
DirectoryEntry serverNtdsaEntry = directoryEntryMgr.<API key>(NtdsaObjectName);
// reset the NTDSDSA_OPT_IS_GC flag on the "options" property
int options = 0;
try
{
if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null)
{
options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value;
}
serverNtdsaEntry.Properties[PropertyManager.Options].Value = options & (~1);
serverNtdsaEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.<API key>(context, e);
}
// mark as disbaled
_disabled = true;
// return a domain controller object
return new DomainController(context, Name);
}
public override bool IsGlobalCatalog()
{
CheckIfDisposed();
CheckIfDisabled();
// since this is a global catalog object, this should always return true
return true;
}
public <API key> FindAllProperties()
{
CheckIfDisposed();
CheckIfDisabled();
// create an <API key> object
if (_schema == null)
{
string schemaNC = null;
try
{
schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
}
catch (COMException e)
{
throw ExceptionHelper.<API key>(context, e);
}
DirectoryContext schemaContext = Utils.<API key>(Name, <API key>.DirectoryServer, context);
_schema = new <API key>(context, schemaNC);
}
// return the global catalog replicated properties
return _schema.FindAllProperties(PropertyTypes.InGlobalCatalog);
}
public override DirectorySearcher <API key>()
{
CheckIfDisposed();
CheckIfDisabled();
return <API key>();
}
#endregion public methods
#region private methods
private void CheckIfDisabled()
{
if (_disabled)
{
throw new <API key>(SR.GCDisabled);
}
}
internal static new GlobalCatalog <API key>(DirectoryContext context, string siteName, LocatorOptions flag)
{
GlobalCatalog gc;
bool retry = false;
bool credsValidated = false;
// work with copy of the context
context = new DirectoryContext(context);
// authenticate against this GC to validate the credentials
gc = FindOneInternal(context, context.Name, siteName, flag);
try
{
ValidateCredential(gc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down , so try again with force rediscovery if the flags did not already contain force rediscovery
if ((flag & LocatorOptions.ForceRediscovery) == 0)
{
retry = true;
}
else
{
throw new <API key>(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
}
else
{
throw ExceptionHelper.<API key>(context, e);
}
}
finally
{
if (!credsValidated)
{
gc.Dispose();
}
}
if (retry)
{
credsValidated = false;
gc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery);
try
{
ValidateCredential(gc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down
throw new <API key>(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
else
{
throw ExceptionHelper.<API key>(context, e);
}
}
finally
{
if (!credsValidated)
{
gc.Dispose();
}
}
}
return gc;
}
internal static new GlobalCatalog FindOneInternal(DirectoryContext context, string forestName, string siteName, LocatorOptions flag)
{
<API key> <API key>;
int errorCode = 0;
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.<API key>, "siteName");
}
// check that the flags passed have only the valid bits set
if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0)
{
throw new ArgumentException(SR.InvalidFlags, "flag");
}
if (forestName == null)
{
// get the dns name of the logged on forest
<API key> <API key>;
int error = Locator.DsGetDcNameWrapper(null, DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.<API key>, out <API key>);
if (error == NativeMethods.<API key>)
{
// throw not found exception
throw new <API key>(SR.<API key>, typeof(GlobalCatalog), null);
}
else if (error != 0)
{
throw ExceptionHelper.<API key>(errorCode);
}
Debug.Assert(<API key>.DnsForestName != null);
forestName = <API key>.DnsForestName;
}
// call DsGetDcName
errorCode = Locator.DsGetDcNameWrapper(null, forestName, siteName, (long)flag | (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.<API key>), out <API key>);
if (errorCode == NativeMethods.<API key>)
{
throw new <API key>(SR.Format(SR.GCNotFoundInForest , forestName), typeof(GlobalCatalog), null);
}
// this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid)
if (errorCode == NativeMethods.ERROR_INVALID_FLAGS)
{
throw new ArgumentException(SR.InvalidFlags, "flag");
}
else if (errorCode != 0)
{
throw ExceptionHelper.<API key>(errorCode);
}
// create a GlobalCatalog object
// the name is returned in the form "\\servername", so skip the "\\"
Debug.Assert(<API key>.<API key>.Length > 2);
string globalCatalogName = <API key>.<API key>.Substring(2);
// create a new context object for the global catalog
DirectoryContext gcContext = Utils.<API key>(globalCatalogName, <API key>.DirectoryServer, context);
return new GlobalCatalog(gcContext, globalCatalogName);
}
internal static <API key> FindAllInternal(DirectoryContext context, string siteName)
{
ArrayList gcList = new ArrayList();
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.<API key>, "siteName");
}
foreach (string gcName in Utils.GetReplicaList(context, null /* not specific to any partition */, siteName, false /* isDefaultNC */, false /* isADAM */, true /* mustBeGC */))
{
DirectoryContext gcContext = Utils.<API key>(gcName, <API key>.DirectoryServer, context);
gcList.Add(new GlobalCatalog(gcContext, gcName));
}
return new <API key>(gcList);
}
private DirectorySearcher <API key>()
{
DirectoryEntry de = new DirectoryEntry("GC://" + Name);
de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind;
de.Username = context.UserName;
de.Password = context.Password;
return new DirectorySearcher(de);
}
#endregion
}
}
|
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <asm/gt64120.h>
#define PCI_ACCESS_READ 0
#define PCI_ACCESS_WRITE 1
#define <API key> 0
#define <API key> 8
#define <API key> 0
#define <API key> 8
#define <API key> 11
#define <API key> 16
static int <API key>(unsigned char access_type,
struct pci_bus *bus, unsigned int devfn, int where, u32 * data)
{
unsigned char busnum = bus->number;
u32 intr;
if ((busnum == 0) && (devfn >= PCI_DEVFN(31, 0)))
return -1;
GT_WRITE(GT_INTRCAUSE_OFS, ~(<API key> |
<API key>));
GT_WRITE(GT_PCI0_CFGADDR_OFS,
(busnum << <API key>) |
(devfn << <API key>) |
((where / 4) << <API key>) |
<API key>);
if (access_type == PCI_ACCESS_WRITE) {
if (busnum == 0 && PCI_SLOT(devfn) == 0) {
GT_WRITE(GT_PCI0_CFGDATA_OFS, *data);
} else
__GT_WRITE(GT_PCI0_CFGDATA_OFS, *data);
} else {
if (busnum == 0 && PCI_SLOT(devfn) == 0) {
*data = GT_READ(GT_PCI0_CFGDATA_OFS);
} else
*data = __GT_READ(GT_PCI0_CFGDATA_OFS);
}
intr = GT_READ(GT_INTRCAUSE_OFS);
if (intr & (<API key> | <API key>)) {
GT_WRITE(GT_INTRCAUSE_OFS, ~(<API key> |
<API key>));
return -1;
}
return 0;
}
static int <API key>(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 * val)
{
u32 data = 0;
if (<API key>(PCI_ACCESS_READ, bus, devfn,
where, &data))
return <API key>;
if (size == 1)
*val = (data >> ((where & 3) << 3)) & 0xff;
else if (size == 2)
*val = (data >> ((where & 3) << 3)) & 0xffff;
else
*val = data;
return PCIBIOS_SUCCESSFUL;
}
static int <API key>(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
u32 data = 0;
if (size == 4)
data = val;
else {
if (<API key>(PCI_ACCESS_READ, bus,
devfn, where, &data))
return <API key>;
if (size == 1)
data = (data & ~(0xff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else if (size == 2)
data = (data & ~(0xffff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
}
if (<API key>(PCI_ACCESS_WRITE, bus, devfn,
where, &data))
return <API key>;
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops gt64xxx_pci0_ops = {
.read = <API key>,
.write = <API key>
};
|
#ifndef MSP3400_DRIVER_H
#define MSP3400_DRIVER_H
#include <media/msp3400.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ctrls.h>
#define MSP_CARRIER(freq) ((int)((float)(freq / 18.432) * (1 << 24)))
#define MSP_MODE_AM_DETECT 0
#define MSP_MODE_FM_RADIO 2
#define MSP_MODE_FM_TERRA 3
#define MSP_MODE_FM_SAT 4
#define MSP_MODE_FM_NICAM1 5
#define MSP_MODE_FM_NICAM2 6
#define MSP_MODE_AM_NICAM 7
#define MSP_MODE_BTSC 8
#define MSP_MODE_EXTERN 9
#define SCART_IN1 0
#define SCART_IN2 1
#define SCART_IN3 2
#define SCART_IN4 3
#define SCART_IN1_DA 4
#define SCART_IN2_DA 5
#define SCART_MONO 6
#define SCART_MUTE 7
#define SCART_DSP_IN 0
#define SCART1_OUT 1
#define SCART2_OUT 2
#define OPMODE_AUTO -1
#define OPMODE_MANUAL 0
#define OPMODE_AUTODETECT 1
#define OPMODE_AUTOSELECT 2
extern int msp_debug;
extern bool msp_once;
extern bool msp_amsound;
extern int msp_standard;
extern bool msp_dolby;
extern int msp_stereo_thresh;
struct msp_state {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
int rev1, rev2;
int ident;
u8 has_nicam;
u8 has_radio;
u8 has_headphones;
u8 has_ntsc_jp_d_k3;
u8 has_scart2;
u8 has_scart3;
u8 has_scart4;
u8 has_scart2_out;
u8 <API key>;
u8 has_i2s_conf;
u8 has_subwoofer;
u8 <API key>;
u8 <API key>;
u8 has_dolby_pro_logic;
u8 force_btsc;
int radio;
int opmode;
int std;
int mode;
v4l2_std_id v4l2_std, detected_std;
int nicam_on;
int acb;
int in_scart;
int i2s_mode;
int main, second;
int input;
u32 route_in;
u32 route_out;
int audmode;
int rxsubchans;
struct {
struct v4l2_ctrl *volume;
struct v4l2_ctrl *muted;
};
int scan_in_progress;
struct task_struct *kthread;
wait_queue_head_t wq;
unsigned int restart:1;
unsigned int watch_stereo:1;
};
static inline struct msp_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct msp_state, sd);
}
static inline struct msp_state *ctrl_to_state(struct v4l2_ctrl *ctrl)
{
return container_of(ctrl->handler, struct msp_state, hdl);
}
int msp_write_dem(struct i2c_client *client, int addr, int val);
int msp_write_dsp(struct i2c_client *client, int addr, int val);
int msp_read_dem(struct i2c_client *client, int addr);
int msp_read_dsp(struct i2c_client *client, int addr);
int msp_reset(struct i2c_client *client);
void msp_set_scart(struct i2c_client *client, int in, int out);
void msp_update_volume(struct msp_state *state);
int msp_sleep(struct msp_state *state, int timeout);
const char *<API key>(int std);
void msp_set_audmode(struct i2c_client *client);
int msp_detect_stereo(struct i2c_client *client);
int msp3400c_thread(void *data);
int msp3410d_thread(void *data);
int msp34xxg_thread(void *data);
void msp3400c_set_mode(struct i2c_client *client, int mode);
void <API key>(struct i2c_client *client, int cdo1, int cdo2);
#endif
|
#ifndef _IP6T_LOG_H
#define _IP6T_LOG_H
#warning "Please update iptables, this file will be removed soon!"
#define IP6T_LOG_TCPSEQ 0x01
#define IP6T_LOG_TCPOPT 0x02
#define IP6T_LOG_IPOPT 0x04
#define IP6T_LOG_UID 0x08
#define IP6T_LOG_NFLOG 0x10
#define IP6T_LOG_MACDECODE 0x20
#define IP6T_LOG_MASK 0x2f
struct ip6t_log_info {
unsigned char level;
unsigned char logflags;
char prefix[30];
};
#endif
|
#ifndef <API key>
#define <API key>
#include <linux/types.h>
#include <linux/ssb/ssb.h>
extern int <API key>(struct ssb_bus *bus, u32 ticks);
u32 ssb_gpio_in(struct ssb_bus *bus, u32 mask);
u32 ssb_gpio_out(struct ssb_bus *bus, u32 mask, u32 value);
u32 ssb_gpio_outen(struct ssb_bus *bus, u32 mask, u32 value);
u32 ssb_gpio_control(struct ssb_bus *bus, u32 mask, u32 value);
u32 ssb_gpio_intmask(struct ssb_bus *bus, u32 mask, u32 value);
u32 ssb_gpio_polarity(struct ssb_bus *bus, u32 mask, u32 value);
#endif
|
#ifndef _SPARC_PGALLOC_H
#define _SPARC_PGALLOC_H
#include <linux/kernel.h>
#include <linux/sched.h>
#include <asm/page.h>
#include <asm/btfixup.h>
struct page;
extern struct <API key> {
unsigned long *pgd_cache;
unsigned long *pte_cache;
unsigned long pgtable_cache_sz;
unsigned long pgd_cache_sz;
} pgt_quicklists;
#define pgd_quicklist (pgt_quicklists.pgd_cache)
#define pmd_quicklist ((unsigned long *)0)
#define pte_quicklist (pgt_quicklists.pte_cache)
#define pgtable_cache_size (pgt_quicklists.pgtable_cache_sz)
#define pgd_cache_size (pgt_quicklists.pgd_cache_sz)
extern void check_pgt_cache(void);
BTFIXUPDEF_CALL(void, do_check_pgt_cache, int, int)
#define do_check_pgt_cache(low,high) BTFIXUP_CALL(do_check_pgt_cache)(low,high)
BTFIXUPDEF_CALL(pgd_t *, get_pgd_fast, void)
#define get_pgd_fast() BTFIXUP_CALL(get_pgd_fast)()
BTFIXUPDEF_CALL(void, free_pgd_fast, pgd_t *)
#define free_pgd_fast(pgd) BTFIXUP_CALL(free_pgd_fast)(pgd)
#define pgd_free(mm, pgd) free_pgd_fast(pgd)
#define pgd_alloc(mm) get_pgd_fast()
BTFIXUPDEF_CALL(void, pgd_set, pgd_t *, pmd_t *)
#define pgd_set(pgdp,pmdp) BTFIXUP_CALL(pgd_set)(pgdp,pmdp)
#define pgd_populate(MM, PGD, PMD) pgd_set(PGD, PMD)
BTFIXUPDEF_CALL(pmd_t *, pmd_alloc_one, struct mm_struct *, unsigned long)
#define pmd_alloc_one(mm, address) BTFIXUP_CALL(pmd_alloc_one)(mm, address)
BTFIXUPDEF_CALL(void, free_pmd_fast, pmd_t *)
#define free_pmd_fast(pmd) BTFIXUP_CALL(free_pmd_fast)(pmd)
#define pmd_free(mm, pmd) free_pmd_fast(pmd)
#define __pmd_free_tlb(tlb, pmd, addr) pmd_free((tlb)->mm, pmd)
BTFIXUPDEF_CALL(void, pmd_populate, pmd_t *, struct page *)
#define pmd_populate(MM, PMD, PTE) BTFIXUP_CALL(pmd_populate)(PMD, PTE)
#define pmd_pgtable(pmd) pmd_page(pmd)
BTFIXUPDEF_CALL(void, pmd_set, pmd_t *, pte_t *)
#define pmd_populate_kernel(MM, PMD, PTE) BTFIXUP_CALL(pmd_set)(PMD, PTE)
BTFIXUPDEF_CALL(pgtable_t , pte_alloc_one, struct mm_struct *, unsigned long)
#define pte_alloc_one(mm, address) BTFIXUP_CALL(pte_alloc_one)(mm, address)
BTFIXUPDEF_CALL(pte_t *, <API key>, struct mm_struct *, unsigned long)
#define <API key>(mm, addr) BTFIXUP_CALL(<API key>)(mm, addr)
BTFIXUPDEF_CALL(void, free_pte_fast, pte_t *)
#define pte_free_kernel(mm, pte) BTFIXUP_CALL(free_pte_fast)(pte)
BTFIXUPDEF_CALL(void, pte_free, pgtable_t )
#define pte_free(mm, pte) BTFIXUP_CALL(pte_free)(pte)
#define __pte_free_tlb(tlb, pte, addr) pte_free((tlb)->mm, pte)
#endif
|
#ifndef <API key>
#define <API key>
#define MPP(_num, _sel, _in, _out, _F5181l, _F5182, _F5281) ( \
((_num) & 0xff) | \
(((_sel) & 0xf) << 8) | \
((!!(_in)) << 12) | \
((!!(_out)) << 13) | \
((!!(_F5181l)) << 14) | \
((!!(_F5182)) << 15) | \
((!!(_F5281)) << 16))
#define MPP_F5181_MASK MPP(0, 0x0, 0, 0, 1, 0, 0)
#define MPP_F5182_MASK MPP(0, 0x0, 0, 0, 0, 1, 0)
#define MPP_F5281_MASK MPP(0, 0x0, 0, 0, 0, 0, 1)
#define MPP0_UNUSED MPP(0, 0x3, 0, 0, 1, 1, 1)
#define MPP0_GPIO MPP(0, 0x3, 1, 1, 1, 1, 1)
#define MPP0_PCIE_RST_OUTn MPP(0, 0x0, 0, 0, 1, 1, 1)
#define MPP0_PCI_ARB MPP(0, 0x2, 0, 0, 1, 1, 1)
#define MPP1_UNUSED MPP(1, 0x0, 0, 0, 1, 1, 1)
#define MPP1_GPIO MPP(1, 0x0, 1, 1, 1, 1, 1)
#define MPP1_PCI_ARB MPP(1, 0x2, 0, 0, 1, 1, 1)
#define MPP2_UNUSED MPP(2, 0x0, 0, 0, 1, 1, 1)
#define MPP2_GPIO MPP(2, 0x0, 1, 1, 1, 1, 1)
#define MPP2_PCI_ARB MPP(2, 0x2, 0, 0, 1, 1, 1)
#define MPP2_PCI_PMEn MPP(2, 0x3, 0, 0, 1, 1, 1)
#define MPP3_UNUSED MPP(3, 0x0, 0, 0, 1, 1, 1)
#define MPP3_GPIO MPP(3, 0x0, 1, 1, 1, 1, 1)
#define MPP3_PCI_ARB MPP(3, 0x2, 0, 0, 1, 1, 1)
#define MPP4_UNUSED MPP(4, 0x0, 0, 0, 1, 1, 1)
#define MPP4_GPIO MPP(4, 0x0, 1, 1, 1, 1, 1)
#define MPP4_PCI_ARB MPP(4, 0x2, 0, 0, 1, 1, 1)
#define MPP4_NAND MPP(4, 0x4, 0, 0, 0, 1, 1)
#define MPP4_SATA_LED MPP(4, 0x5, 0, 0, 0, 1, 0)
#define MPP5_UNUSED MPP(5, 0x0, 0, 0, 1, 1, 1)
#define MPP5_GPIO MPP(5, 0x0, 1, 1, 1, 1, 1)
#define MPP5_PCI_ARB MPP(5, 0x2, 0, 0, 1, 1, 1)
#define MPP5_NAND MPP(5, 0x4, 0, 0, 0, 1, 1)
#define MPP5_SATA_LED MPP(5, 0x5, 0, 0, 0, 1, 0)
#define MPP6_UNUSED MPP(6, 0x0, 0, 0, 1, 1, 1)
#define MPP6_GPIO MPP(6, 0x0, 1, 1, 1, 1, 1)
#define MPP6_PCI_ARB MPP(6, 0x2, 0, 0, 1, 1, 1)
#define MPP6_NAND MPP(6, 0x4, 0, 0, 0, 1, 1)
#define MPP6_PCI_CLK MPP(6, 0x5, 0, 0, 1, 0, 0)
#define MPP6_SATA_LED MPP(6, 0x5, 0, 0, 0, 1, 0)
#define MPP7_UNUSED MPP(7, 0x0, 0, 0, 1, 1, 1)
#define MPP7_GPIO MPP(7, 0x0, 1, 1, 1, 1, 1)
#define MPP7_PCI_ARB MPP(7, 0x2, 0, 0, 1, 1, 1)
#define MPP7_NAND MPP(7, 0x4, 0, 0, 0, 1, 1)
#define MPP7_PCI_CLK MPP(7, 0x5, 0, 0, 1, 0, 0)
#define MPP7_SATA_LED MPP(7, 0x5, 0, 0, 0, 1, 0)
#define MPP8_UNUSED MPP(8, 0x0, 0, 0, 1, 1, 1)
#define MPP8_GPIO MPP(8, 0x0, 1, 1, 1, 1, 1)
#define MPP8_GIGE MPP(8, 0x1, 0, 0, 1, 1, 1)
#define MPP9_UNUSED MPP(9, 0x0, 0, 0, 1, 1, 1)
#define MPP9_GPIO MPP(9, 0x0, 1, 1, 1, 1, 1)
#define MPP9_GIGE MPP(9, 0x1, 0, 0, 1, 1, 1)
#define MPP10_UNUSED MPP(10, 0x0, 0, 0, 1, 1, 1)
#define MPP10_GPIO MPP(10, 0x0, 1, 1, 1, 1, 1)
#define MPP10_GIGE MPP(10, 0x1, 0, 0, 1, 1, 1)
#define MPP11_UNUSED MPP(11, 0x0, 0, 0, 1, 1, 1)
#define MPP11_GPIO MPP(11, 0x0, 1, 1, 1, 1, 1)
#define MPP11_GIGE MPP(11, 0x1, 0, 0, 1, 1, 1)
#define MPP12_UNUSED MPP(12, 0x0, 0, 0, 1, 1, 1)
#define MPP12_GPIO MPP(12, 0x0, 1, 1, 1, 1, 1)
#define MPP12_GIGE MPP(12, 0x1, 0, 0, 1, 1, 1)
#define MPP12_NAND MPP(12, 0x4, 0, 0, 0, 1, 1)
#define MPP12_SATA_LED MPP(12, 0x5, 0, 0, 0, 1, 0)
#define MPP13_UNUSED MPP(13, 0x0, 0, 0, 1, 1, 1)
#define MPP13_GPIO MPP(13, 0x0, 1, 1, 1, 1, 1)
#define MPP13_GIGE MPP(13, 0x1, 0, 0, 1, 1, 1)
#define MPP13_NAND MPP(13, 0x4, 0, 0, 0, 1, 1)
#define MPP13_SATA_LED MPP(13, 0x5, 0, 0, 0, 1, 0)
#define MPP14_UNUSED MPP(14, 0x0, 0, 0, 1, 1, 1)
#define MPP14_GPIO MPP(14, 0x0, 1, 1, 1, 1, 1)
#define MPP14_GIGE MPP(14, 0x1, 0, 0, 1, 1, 1)
#define MPP14_NAND MPP(14, 0x4, 0, 0, 0, 1, 1)
#define MPP14_SATA_LED MPP(14, 0x5, 0, 0, 0, 1, 0)
#define MPP15_UNUSED MPP(15, 0x0, 0, 0, 1, 1, 1)
#define MPP15_GPIO MPP(15, 0x0, 1, 1, 1, 1, 1)
#define MPP15_GIGE MPP(15, 0x1, 0, 0, 1, 1, 1)
#define MPP15_NAND MPP(15, 0x4, 0, 0, 0, 1, 1)
#define MPP15_SATA_LED MPP(15, 0x5, 0, 0, 0, 1, 0)
#define MPP16_UNUSED MPP(16, 0x0, 0, 0, 1, 1, 1)
#define MPP16_GPIO MPP(16, 0x5, 1, 1, 0, 1, 0)
#define MPP16_GIGE MPP(16, 0x1, 0, 0, 1, 1, 1)
#define MPP16_NAND MPP(16, 0x4, 0, 0, 0, 1, 1)
#define MPP16_UART MPP(16, 0x0, 0, 0, 0, 1, 1)
#define MPP17_UNUSED MPP(17, 0x0, 0, 0, 1, 1, 1)
#define MPP17_GPIO MPP(17, 0x5, 1, 1, 0, 1, 0)
#define MPP17_GIGE MPP(17, 0x1, 0, 0, 1, 1, 1)
#define MPP17_NAND MPP(17, 0x4, 0, 0, 0, 1, 1)
#define MPP17_UART MPP(17, 0x0, 0, 0, 0, 1, 1)
#define MPP18_UNUSED MPP(18, 0x0, 0, 0, 1, 1, 1)
#define MPP18_GPIO MPP(18, 0x5, 1, 1, 0, 1, 0)
#define MPP18_GIGE MPP(18, 0x1, 0, 0, 1, 1, 1)
#define MPP18_UART MPP(18, 0x0, 0, 0, 0, 1, 1)
#define MPP19_UNUSED MPP(19, 0x0, 0, 0, 1, 1, 1)
#define MPP19_GPIO MPP(19, 0x5, 1, 1, 0, 1, 0)
#define MPP19_GIGE MPP(19, 0x1, 0, 0, 1, 1, 1)
#define MPP19_UART MPP(19, 0x0, 0, 0, 0, 1, 1)
#define MPP_MAX 19
void orion5x_mpp_conf(unsigned int *mpp_list);
#endif
|
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/info.h>
#include <sound/control.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/initval.h>
#include <asm/io.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("S3 SonicVibes PCI");
MODULE_LICENSE("GPL");
<API key>("{{S3,SonicVibes PCI}}");
#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(<API key>))
#define SUPPORT_JOYSTICK 1
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = <API key>;
static bool reverb[SNDRV_CARDS];
static bool mge[SNDRV_CARDS];
static unsigned int dmaio = 0x7a00;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for S3 SonicVibes soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for S3 SonicVibes soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable S3 SonicVibes soundcard.");
module_param_array(reverb, bool, NULL, 0444);
MODULE_PARM_DESC(reverb, "Enable reverb (SRAM is present) for S3 SonicVibes soundcard.");
module_param_array(mge, bool, NULL, 0444);
MODULE_PARM_DESC(mge, "MIC Gain Enable for S3 SonicVibes soundcard.");
module_param(dmaio, uint, 0444);
MODULE_PARM_DESC(dmaio, "DDMA i/o base address for S3 SonicVibes soundcard.");
#define SV_REG(sonic, x) ((sonic)->enh_port + SV_REG_
#define SV_REG_CONTROL 0x00
#define SV_ENHANCED 0x01
#define SV_TEST 0x02
#define SV_REVERB 0x04
#define SV_WAVETABLE 0x08
#define SV_INTA 0x20
#define SV_RESET 0x80
#define SV_REG_IRQMASK 0x01
#define SV_DMAA_MASK 0x01
#define SV_DMAC_MASK 0x04
#define SV_SPEC_MASK 0x08
#define SV_UD_MASK 0x40
#define SV_MIDI_MASK 0x80
#define SV_REG_STATUS 0x02
#define SV_DMAA_IRQ 0x01
#define SV_DMAC_IRQ 0x04
#define SV_SPEC_IRQ 0x08
#define SV_UD_IRQ 0x40
#define SV_MIDI_IRQ 0x80
#define SV_REG_INDEX 0x04
#define SV_MCE 0x40
#define SV_TRD 0x80
#define SV_REG_DATA 0x05
#define SV_IREG_LEFT_ADC 0x00
#define SV_IREG_RIGHT_ADC 0x01
#define SV_IREG_LEFT_AUX1 0x02
#define SV_IREG_RIGHT_AUX1 0x03
#define SV_IREG_LEFT_CD 0x04
#define SV_IREG_RIGHT_CD 0x05
#define SV_IREG_LEFT_LINE 0x06
#define SV_IREG_RIGHT_LINE 0x07
#define SV_IREG_MIC 0x08
#define SV_IREG_GAME_PORT 0x09
#define SV_IREG_LEFT_SYNTH 0x0a
#define SV_IREG_RIGHT_SYNTH 0x0b
#define SV_IREG_LEFT_AUX2 0x0c
#define SV_IREG_RIGHT_AUX2 0x0d
#define SV_IREG_LEFT_ANALOG 0x0e
#define <API key> 0x0f
#define SV_IREG_LEFT_PCM 0x10
#define SV_IREG_RIGHT_PCM 0x11
#define <API key> 0x12
#define SV_IREG_PC_ENABLE 0x13
#define SV_IREG_UD_BUTTON 0x14
#define SV_IREG_REVISION 0x15
#define <API key> 0x16
#define SV_IREG_DMA_A_UPPER 0x18
#define SV_IREG_DMA_A_LOWER 0x19
#define SV_IREG_DMA_C_UPPER 0x1c
#define SV_IREG_DMA_C_LOWER 0x1d
#define <API key> 0x1e
#define <API key> 0x1f
#define <API key> 0x20
#define <API key> 0x21
#define SV_IREG_ADC_CLOCK 0x22
#define <API key> 0x23
#define SV_IREG_ADC_PLL_M 0x24
#define SV_IREG_ADC_PLL_N 0x25
#define SV_IREG_SYNTH_PLL_M 0x26
#define SV_IREG_SYNTH_PLL_N 0x27
#define SV_IREG_MPU401 0x2a
#define SV_IREG_DRIVE_CTRL 0x2b
#define SV_IREG_SRS_SPACE 0x2c
#define SV_IREG_SRS_CENTER 0x2d
#define SV_IREG_WAVE_SOURCE 0x2e
#define <API key> 0x30
#define <API key> 0x31
#define SV_IREG_ADC_PLL SV_IREG_ADC_PLL_M
#define SV_IREG_SYNTH_PLL SV_IREG_SYNTH_PLL_M
#define SV_DMA_ADDR0 0x00
#define SV_DMA_ADDR1 0x01
#define SV_DMA_ADDR2 0x02
#define SV_DMA_ADDR3 0x03
#define SV_DMA_COUNT0 0x04
#define SV_DMA_COUNT1 0x05
#define SV_DMA_COUNT2 0x06
#define SV_DMA_MODE 0x0b
#define SV_DMA_RESET 0x0d
#define SV_DMA_MASK 0x0f
#define SV_RECSRC_RESERVED (0x00<<5)
#define SV_RECSRC_CD (0x01<<5)
#define SV_RECSRC_DAC (0x02<<5)
#define SV_RECSRC_AUX2 (0x03<<5)
#define SV_RECSRC_LINE (0x04<<5)
#define SV_RECSRC_AUX1 (0x05<<5)
#define SV_RECSRC_MIC (0x06<<5)
#define SV_RECSRC_OUT (0x07<<5)
#define SV_FULLRATE 48000
#define SV_REFFREQUENCY 24576000
#define SV_ADCMULT 512
#define SV_MODE_PLAY 1
#define SV_MODE_CAPTURE 2
struct sonicvibes {
unsigned long dma1size;
unsigned long dma2size;
int irq;
unsigned long sb_port;
unsigned long enh_port;
unsigned long synth_port;
unsigned long midi_port;
unsigned long game_port;
unsigned int dmaa_port;
struct resource *res_dmaa;
unsigned int dmac_port;
struct resource *res_dmac;
unsigned char enable;
unsigned char irqmask;
unsigned char revision;
unsigned char format;
unsigned char srs_space;
unsigned char srs_center;
unsigned char mpu_switch;
unsigned char wave_source;
unsigned int mode;
struct pci_dev *pci;
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_pcm_substream *playback_substream;
struct snd_pcm_substream *capture_substream;
struct snd_rawmidi *rmidi;
struct snd_hwdep *fmsynth;
spinlock_t reg_lock;
unsigned int p_dma_size;
unsigned int c_dma_size;
struct snd_kcontrol *master_mute;
struct snd_kcontrol *master_volume;
#ifdef SUPPORT_JOYSTICK
struct gameport *gameport;
#endif
};
static <API key>(snd_sonic_ids) = {
{ PCI_VDEVICE(S3, 0xca00), 0, },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, snd_sonic_ids);
static struct snd_ratden <API key> = {
.num_min = 4000 * 65536,
.num_max = 48000UL * 65536,
.num_step = 1,
.den = 65536,
};
static struct <API key> <API key> = {
.nrats = 1,
.rats = &<API key>,
};
static inline void <API key>(struct sonicvibes * sonic,
unsigned int addr,
unsigned int count)
{
count
outl(addr, sonic->dmaa_port + SV_DMA_ADDR0);
outl(count, sonic->dmaa_port + SV_DMA_COUNT0);
outb(0x18, sonic->dmaa_port + SV_DMA_MODE);
#if 0
printk(KERN_DEBUG "program dmaa: addr = 0x%x, paddr = 0x%x\n",
addr, inl(sonic->dmaa_port + SV_DMA_ADDR0));
#endif
}
static inline void <API key>(struct sonicvibes * sonic,
unsigned int addr,
unsigned int count)
{
count >>= 1;
count
outl(addr, sonic->dmac_port + SV_DMA_ADDR0);
outl(count, sonic->dmac_port + SV_DMA_COUNT0);
outb(0x14, sonic->dmac_port + SV_DMA_MODE);
#if 0
printk(KERN_DEBUG "program dmac: addr = 0x%x, paddr = 0x%x\n",
addr, inl(sonic->dmac_port + SV_DMA_ADDR0));
#endif
}
static inline unsigned int <API key>(struct sonicvibes * sonic)
{
return (inl(sonic->dmaa_port + SV_DMA_COUNT0) & 0xffffff) + 1;
}
static inline unsigned int <API key>(struct sonicvibes * sonic)
{
return ((inl(sonic->dmac_port + SV_DMA_COUNT0) & 0xffffff) + 1) << 1;
}
static void snd_sonicvibes_out1(struct sonicvibes * sonic,
unsigned char reg,
unsigned char value)
{
outb(reg, SV_REG(sonic, INDEX));
udelay(10);
outb(value, SV_REG(sonic, DATA));
udelay(10);
}
static void snd_sonicvibes_out(struct sonicvibes * sonic,
unsigned char reg,
unsigned char value)
{
unsigned long flags;
spin_lock_irqsave(&sonic->reg_lock, flags);
outb(reg, SV_REG(sonic, INDEX));
udelay(10);
outb(value, SV_REG(sonic, DATA));
udelay(10);
<API key>(&sonic->reg_lock, flags);
}
static unsigned char snd_sonicvibes_in1(struct sonicvibes * sonic, unsigned char reg)
{
unsigned char value;
outb(reg, SV_REG(sonic, INDEX));
udelay(10);
value = inb(SV_REG(sonic, DATA));
udelay(10);
return value;
}
static unsigned char snd_sonicvibes_in(struct sonicvibes * sonic, unsigned char reg)
{
unsigned long flags;
unsigned char value;
spin_lock_irqsave(&sonic->reg_lock, flags);
outb(reg, SV_REG(sonic, INDEX));
udelay(10);
value = inb(SV_REG(sonic, DATA));
udelay(10);
<API key>(&sonic->reg_lock, flags);
return value;
}
#if 0
static void <API key>(struct sonicvibes * sonic)
{
printk(KERN_DEBUG
"SV REGS: INDEX = 0x%02x ", inb(SV_REG(sonic, INDEX)));
printk(" STATUS = 0x%02x\n", inb(SV_REG(sonic, STATUS)));
printk(KERN_DEBUG
" 0x00: left input = 0x%02x ", snd_sonicvibes_in(sonic, 0x00));
printk(" 0x20: synth rate low = 0x%02x\n", snd_sonicvibes_in(sonic, 0x20));
printk(KERN_DEBUG
" 0x01: right input = 0x%02x ", snd_sonicvibes_in(sonic, 0x01));
printk(" 0x21: synth rate high = 0x%02x\n", snd_sonicvibes_in(sonic, 0x21));
printk(KERN_DEBUG
" 0x02: left AUX1 = 0x%02x ", snd_sonicvibes_in(sonic, 0x02));
printk(" 0x22: ADC clock = 0x%02x\n", snd_sonicvibes_in(sonic, 0x22));
printk(KERN_DEBUG
" 0x03: right AUX1 = 0x%02x ", snd_sonicvibes_in(sonic, 0x03));
printk(" 0x23: ADC alt rate = 0x%02x\n", snd_sonicvibes_in(sonic, 0x23));
printk(KERN_DEBUG
" 0x04: left CD = 0x%02x ", snd_sonicvibes_in(sonic, 0x04));
printk(" 0x24: ADC pll M = 0x%02x\n", snd_sonicvibes_in(sonic, 0x24));
printk(KERN_DEBUG
" 0x05: right CD = 0x%02x ", snd_sonicvibes_in(sonic, 0x05));
printk(" 0x25: ADC pll N = 0x%02x\n", snd_sonicvibes_in(sonic, 0x25));
printk(KERN_DEBUG
" 0x06: left line = 0x%02x ", snd_sonicvibes_in(sonic, 0x06));
printk(" 0x26: Synth pll M = 0x%02x\n", snd_sonicvibes_in(sonic, 0x26));
printk(KERN_DEBUG
" 0x07: right line = 0x%02x ", snd_sonicvibes_in(sonic, 0x07));
printk(" 0x27: Synth pll N = 0x%02x\n", snd_sonicvibes_in(sonic, 0x27));
printk(KERN_DEBUG
" 0x08: MIC = 0x%02x ", snd_sonicvibes_in(sonic, 0x08));
printk(" 0x28: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x28));
printk(KERN_DEBUG
" 0x09: Game port = 0x%02x ", snd_sonicvibes_in(sonic, 0x09));
printk(" 0x29: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x29));
printk(KERN_DEBUG
" 0x0a: left synth = 0x%02x ", snd_sonicvibes_in(sonic, 0x0a));
printk(" 0x2a: MPU401 = 0x%02x\n", snd_sonicvibes_in(sonic, 0x2a));
printk(KERN_DEBUG
" 0x0b: right synth = 0x%02x ", snd_sonicvibes_in(sonic, 0x0b));
printk(" 0x2b: drive ctrl = 0x%02x\n", snd_sonicvibes_in(sonic, 0x2b));
printk(KERN_DEBUG
" 0x0c: left AUX2 = 0x%02x ", snd_sonicvibes_in(sonic, 0x0c));
printk(" 0x2c: SRS space = 0x%02x\n", snd_sonicvibes_in(sonic, 0x2c));
printk(KERN_DEBUG
" 0x0d: right AUX2 = 0x%02x ", snd_sonicvibes_in(sonic, 0x0d));
printk(" 0x2d: SRS center = 0x%02x\n", snd_sonicvibes_in(sonic, 0x2d));
printk(KERN_DEBUG
" 0x0e: left analog = 0x%02x ", snd_sonicvibes_in(sonic, 0x0e));
printk(" 0x2e: wave source = 0x%02x\n", snd_sonicvibes_in(sonic, 0x2e));
printk(KERN_DEBUG
" 0x0f: right analog = 0x%02x ", snd_sonicvibes_in(sonic, 0x0f));
printk(" 0x2f: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x2f));
printk(KERN_DEBUG
" 0x10: left PCM = 0x%02x ", snd_sonicvibes_in(sonic, 0x10));
printk(" 0x30: analog power = 0x%02x\n", snd_sonicvibes_in(sonic, 0x30));
printk(KERN_DEBUG
" 0x11: right PCM = 0x%02x ", snd_sonicvibes_in(sonic, 0x11));
printk(" 0x31: analog power = 0x%02x\n", snd_sonicvibes_in(sonic, 0x31));
printk(KERN_DEBUG
" 0x12: DMA data format = 0x%02x ", snd_sonicvibes_in(sonic, 0x12));
printk(" 0x32: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x32));
printk(KERN_DEBUG
" 0x13: P/C enable = 0x%02x ", snd_sonicvibes_in(sonic, 0x13));
printk(" 0x33: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x33));
printk(KERN_DEBUG
" 0x14: U/D button = 0x%02x ", snd_sonicvibes_in(sonic, 0x14));
printk(" 0x34: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x34));
printk(KERN_DEBUG
" 0x15: revision = 0x%02x ", snd_sonicvibes_in(sonic, 0x15));
printk(" 0x35: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x35));
printk(KERN_DEBUG
" 0x16: ADC output ctrl = 0x%02x ", snd_sonicvibes_in(sonic, 0x16));
printk(" 0x36: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x36));
printk(KERN_DEBUG
" 0x17: --- = 0x%02x ", snd_sonicvibes_in(sonic, 0x17));
printk(" 0x37: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x37));
printk(KERN_DEBUG
" 0x18: DMA A upper cnt = 0x%02x ", snd_sonicvibes_in(sonic, 0x18));
printk(" 0x38: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x38));
printk(KERN_DEBUG
" 0x19: DMA A lower cnt = 0x%02x ", snd_sonicvibes_in(sonic, 0x19));
printk(" 0x39: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x39));
printk(KERN_DEBUG
" 0x1a: --- = 0x%02x ", snd_sonicvibes_in(sonic, 0x1a));
printk(" 0x3a: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x3a));
printk(KERN_DEBUG
" 0x1b: --- = 0x%02x ", snd_sonicvibes_in(sonic, 0x1b));
printk(" 0x3b: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x3b));
printk(KERN_DEBUG
" 0x1c: DMA C upper cnt = 0x%02x ", snd_sonicvibes_in(sonic, 0x1c));
printk(" 0x3c: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x3c));
printk(KERN_DEBUG
" 0x1d: DMA C upper cnt = 0x%02x ", snd_sonicvibes_in(sonic, 0x1d));
printk(" 0x3d: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x3d));
printk(KERN_DEBUG
" 0x1e: PCM rate low = 0x%02x ", snd_sonicvibes_in(sonic, 0x1e));
printk(" 0x3e: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x3e));
printk(KERN_DEBUG
" 0x1f: PCM rate high = 0x%02x ", snd_sonicvibes_in(sonic, 0x1f));
printk(" 0x3f: --- = 0x%02x\n", snd_sonicvibes_in(sonic, 0x3f));
}
#endif
static void <API key>(struct sonicvibes * sonic,
unsigned char mask,
unsigned char value)
{
unsigned long flags;
spin_lock_irqsave(&sonic->reg_lock, flags);
outb(SV_MCE | <API key>, SV_REG(sonic, INDEX));
if (mask) {
sonic->format = inb(SV_REG(sonic, DATA));
udelay(10);
}
sonic->format = (sonic->format & mask) | value;
outb(sonic->format, SV_REG(sonic, DATA));
udelay(10);
outb(0, SV_REG(sonic, INDEX));
udelay(10);
<API key>(&sonic->reg_lock, flags);
}
static void snd_sonicvibes_pll(unsigned int rate,
unsigned int *res_r,
unsigned int *res_m,
unsigned int *res_n)
{
unsigned int r, m = 0, n = 0;
unsigned int xm, xn, xr, xd, metric = ~0U;
if (rate < 625000 / SV_ADCMULT)
rate = 625000 / SV_ADCMULT;
if (rate > 150000000 / SV_ADCMULT)
rate = 150000000 / SV_ADCMULT;
for (r = 0; rate < 75000000 / SV_ADCMULT; r += 0x20, rate <<= 1);
for (xn = 3; xn < 33; xn++)
for (xm = 3; xm < 257; xm++) {
xr = ((SV_REFFREQUENCY / SV_ADCMULT) * xm) / xn;
if (xr >= rate)
xd = xr - rate;
else
xd = rate - xr;
if (xd < metric) {
metric = xd;
m = xm - 2;
n = xn - 2;
}
}
*res_r = r;
*res_m = m;
*res_n = n;
#if 0
printk(KERN_DEBUG "metric = %i, xm = %i, xn = %i\n", metric, xm, xn);
printk(KERN_DEBUG "pll: m = 0x%x, r = 0x%x, n = 0x%x\n", reg, m, r, n);
#endif
}
static void <API key>(struct sonicvibes * sonic,
unsigned char reg,
unsigned int rate)
{
unsigned long flags;
unsigned int r, m, n;
snd_sonicvibes_pll(rate, &r, &m, &n);
if (sonic != NULL) {
spin_lock_irqsave(&sonic->reg_lock, flags);
snd_sonicvibes_out1(sonic, reg, m);
snd_sonicvibes_out1(sonic, reg + 1, r | n);
<API key>(&sonic->reg_lock, flags);
}
}
static void <API key>(struct sonicvibes * sonic, unsigned int rate)
{
unsigned long flags;
unsigned int div;
unsigned char clock;
div = 48000 / rate;
if (div > 8)
div = 8;
if ((48000 / div) == rate) {
clock = 0x10;
} else {
clock = 0x00;
<API key>(sonic, SV_IREG_ADC_PLL, rate);
}
spin_lock_irqsave(&sonic->reg_lock, flags);
snd_sonicvibes_out1(sonic, <API key>, (div - 1) << 4);
snd_sonicvibes_out1(sonic, SV_IREG_ADC_CLOCK, clock);
<API key>(&sonic->reg_lock, flags);
}
static int <API key>(struct snd_pcm_hw_params *params,
struct snd_pcm_hw_rule *rule)
{
unsigned int rate, div, r, m, n;
if (hw_param_interval(params, <API key>)->min ==
hw_param_interval(params, <API key>)->max) {
rate = hw_param_interval(params, <API key>)->min;
div = 48000 / rate;
if (div > 8)
div = 8;
if ((48000 / div) == rate) {
params->rate_num = rate;
params->rate_den = 1;
} else {
snd_sonicvibes_pll(rate, &r, &m, &n);
snd_BUG_ON(SV_REFFREQUENCY % 16);
snd_BUG_ON(SV_ADCMULT % 512);
params->rate_num = (SV_REFFREQUENCY/16) * (n+2) * r;
params->rate_den = (SV_ADCMULT/512) * (m+2);
}
}
return 0;
}
static void <API key>(struct sonicvibes * sonic, unsigned int rate)
{
unsigned int div;
unsigned long flags;
div = (rate * 65536 + SV_FULLRATE / 2) / SV_FULLRATE;
if (div > 65535)
div = 65535;
spin_lock_irqsave(&sonic->reg_lock, flags);
snd_sonicvibes_out1(sonic, <API key>, div >> 8);
snd_sonicvibes_out1(sonic, <API key>, div);
<API key>(&sonic->reg_lock, flags);
}
static int <API key>(struct sonicvibes * sonic, int what, int cmd)
{
int result = 0;
spin_lock(&sonic->reg_lock);
if (cmd == <API key>) {
if (!(sonic->enable & what)) {
sonic->enable |= what;
snd_sonicvibes_out1(sonic, SV_IREG_PC_ENABLE, sonic->enable);
}
} else if (cmd == <API key>) {
if (sonic->enable & what) {
sonic->enable &= ~what;
snd_sonicvibes_out1(sonic, SV_IREG_PC_ENABLE, sonic->enable);
}
} else {
result = -EINVAL;
}
spin_unlock(&sonic->reg_lock);
return result;
}
static irqreturn_t <API key>(int irq, void *dev_id)
{
struct sonicvibes *sonic = dev_id;
unsigned char status;
status = inb(SV_REG(sonic, STATUS));
if (!(status & (SV_DMAA_IRQ | SV_DMAC_IRQ | SV_MIDI_IRQ)))
return IRQ_NONE;
if (status == 0xff) {
outb(sonic->irqmask = ~0, SV_REG(sonic, IRQMASK));
snd_printk(KERN_ERR "IRQ failure - interrupts disabled!!\n");
return IRQ_HANDLED;
}
if (sonic->pcm) {
if (status & SV_DMAA_IRQ)
<API key>(sonic->playback_substream);
if (status & SV_DMAC_IRQ)
<API key>(sonic->capture_substream);
}
if (sonic->rmidi) {
if (status & SV_MIDI_IRQ)
<API key>(irq, sonic->rmidi->private_data);
}
if (status & SV_UD_IRQ) {
unsigned char udreg;
int vol, oleft, oright, mleft, mright;
spin_lock(&sonic->reg_lock);
udreg = snd_sonicvibes_in1(sonic, SV_IREG_UD_BUTTON);
vol = udreg & 0x3f;
if (!(udreg & 0x40))
vol = -vol;
oleft = mleft = snd_sonicvibes_in1(sonic, SV_IREG_LEFT_ANALOG);
oright = mright = snd_sonicvibes_in1(sonic, <API key>);
oleft &= 0x1f;
oright &= 0x1f;
oleft += vol;
if (oleft < 0)
oleft = 0;
if (oleft > 0x1f)
oleft = 0x1f;
oright += vol;
if (oright < 0)
oright = 0;
if (oright > 0x1f)
oright = 0x1f;
if (udreg & 0x80) {
mleft ^= 0x80;
mright ^= 0x80;
}
oleft |= mleft & 0x80;
oright |= mright & 0x80;
snd_sonicvibes_out1(sonic, SV_IREG_LEFT_ANALOG, oleft);
snd_sonicvibes_out1(sonic, <API key>, oright);
spin_unlock(&sonic->reg_lock);
snd_ctl_notify(sonic->card, <API key>, &sonic->master_mute->id);
snd_ctl_notify(sonic->card, <API key>, &sonic->master_volume->id);
}
return IRQ_HANDLED;
}
static int <API key>(struct snd_pcm_substream *substream,
int cmd)
{
struct sonicvibes *sonic = <API key>(substream);
return <API key>(sonic, 1, cmd);
}
static int <API key>(struct snd_pcm_substream *substream,
int cmd)
{
struct sonicvibes *sonic = <API key>(substream);
return <API key>(sonic, 2, cmd);
}
static int <API key>(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return <API key>(substream, params_buffer_bytes(hw_params));
}
static int <API key>(struct snd_pcm_substream *substream)
{
return <API key>(substream);
}
static int <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned char fmt = 0;
unsigned int size = <API key>(substream);
unsigned int count = <API key>(substream);
sonic->p_dma_size = size;
count
if (runtime->channels > 1)
fmt |= 1;
if (<API key>(runtime->format) == 16)
fmt |= 2;
<API key>(sonic, ~3, fmt);
<API key>(sonic, runtime->rate);
spin_lock_irq(&sonic->reg_lock);
<API key>(sonic, runtime->dma_addr, size);
snd_sonicvibes_out1(sonic, SV_IREG_DMA_A_UPPER, count >> 8);
snd_sonicvibes_out1(sonic, SV_IREG_DMA_A_LOWER, count);
spin_unlock_irq(&sonic->reg_lock);
return 0;
}
static int <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned char fmt = 0;
unsigned int size = <API key>(substream);
unsigned int count = <API key>(substream);
sonic->c_dma_size = size;
count >>= 1;
count
if (runtime->channels > 1)
fmt |= 0x10;
if (<API key>(runtime->format) == 16)
fmt |= 0x20;
<API key>(sonic, ~0x30, fmt);
<API key>(sonic, runtime->rate);
spin_lock_irq(&sonic->reg_lock);
<API key>(sonic, runtime->dma_addr, size);
snd_sonicvibes_out1(sonic, SV_IREG_DMA_C_UPPER, count >> 8);
snd_sonicvibes_out1(sonic, SV_IREG_DMA_C_LOWER, count);
spin_unlock_irq(&sonic->reg_lock);
return 0;
}
static snd_pcm_uframes_t <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
size_t ptr;
if (!(sonic->enable & 1))
return 0;
ptr = sonic->p_dma_size - <API key>(sonic);
return bytes_to_frames(substream->runtime, ptr);
}
static snd_pcm_uframes_t <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
size_t ptr;
if (!(sonic->enable & 2))
return 0;
ptr = sonic->c_dma_size - <API key>(sonic);
return bytes_to_frames(substream->runtime, ptr);
}
static struct snd_pcm_hardware <API key> =
{
.info = (SNDRV_PCM_INFO_MMAP | <API key> |
<API key> |
<API key>),
.formats = SNDRV_PCM_FMTBIT_U8 | <API key>,
.rates = <API key> | <API key>,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 32,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware <API key> =
{
.info = (SNDRV_PCM_INFO_MMAP | <API key> |
<API key> |
<API key>),
.formats = SNDRV_PCM_FMTBIT_U8 | <API key>,
.rates = <API key> | <API key>,
.rate_min = 4000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (128*1024),
.period_bytes_min = 32,
.period_bytes_max = (128*1024),
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 0,
};
static int <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
sonic->mode |= SV_MODE_PLAY;
sonic->playback_substream = substream;
runtime->hw = <API key>;
snd_pcm_hw_rule_add(runtime, 0, <API key>, <API key>, NULL, <API key>, -1);
return 0;
}
static int <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
sonic->mode |= SV_MODE_CAPTURE;
sonic->capture_substream = substream;
runtime->hw = <API key>;
<API key>(runtime, 0, <API key>,
&<API key>);
return 0;
}
static int <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
sonic->playback_substream = NULL;
sonic->mode &= ~SV_MODE_PLAY;
return 0;
}
static int <API key>(struct snd_pcm_substream *substream)
{
struct sonicvibes *sonic = <API key>(substream);
sonic->capture_substream = NULL;
sonic->mode &= ~SV_MODE_CAPTURE;
return 0;
}
static struct snd_pcm_ops <API key> = {
.open = <API key>,
.close = <API key>,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = <API key>,
.hw_free = <API key>,
.prepare = <API key>,
.trigger = <API key>,
.pointer = <API key>,
};
static struct snd_pcm_ops <API key> = {
.open = <API key>,
.close = <API key>,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = <API key>,
.hw_free = <API key>,
.prepare = <API key>,
.trigger = <API key>,
.pointer = <API key>,
};
static int __devinit snd_sonicvibes_pcm(struct sonicvibes * sonic, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if ((err = snd_pcm_new(sonic->card, "s3_86c617", device, 1, 1, &pcm)) < 0)
return err;
if (snd_BUG_ON(!pcm))
return -EINVAL;
snd_pcm_set_ops(pcm, <API key>, &<API key>);
snd_pcm_set_ops(pcm, <API key>, &<API key>);
pcm->private_data = sonic;
pcm->info_flags = 0;
strcpy(pcm->name, "S3 SonicVibes");
sonic->pcm = pcm;
<API key>(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(sonic->pci), 64*1024, 128*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
#define SONICVIBES_MUX(xname, xindex) \
{ .iface = <API key>, .name = xname, .index = xindex, \
.info = <API key>, \
.get = <API key>, .put = <API key> }
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
static char *texts[7] = {
"CD", "PCM", "Aux1", "Line", "Aux0", "Mic", "Mix"
};
uinfo->type = <API key>;
uinfo->count = 2;
uinfo->value.enumerated.items = 7;
if (uinfo->value.enumerated.item >= 7)
uinfo->value.enumerated.item = 6;
strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]);
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&sonic->reg_lock);
ucontrol->value.enumerated.item[0] = ((snd_sonicvibes_in1(sonic, SV_IREG_LEFT_ADC) & SV_RECSRC_OUT) >> 5) - 1;
ucontrol->value.enumerated.item[1] = ((snd_sonicvibes_in1(sonic, SV_IREG_RIGHT_ADC) & SV_RECSRC_OUT) >> 5) - 1;
spin_unlock_irq(&sonic->reg_lock);
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
unsigned short left, right, oval1, oval2;
int change;
if (ucontrol->value.enumerated.item[0] >= 7 ||
ucontrol->value.enumerated.item[1] >= 7)
return -EINVAL;
left = (ucontrol->value.enumerated.item[0] + 1) << 5;
right = (ucontrol->value.enumerated.item[1] + 1) << 5;
spin_lock_irq(&sonic->reg_lock);
oval1 = snd_sonicvibes_in1(sonic, SV_IREG_LEFT_ADC);
oval2 = snd_sonicvibes_in1(sonic, SV_IREG_RIGHT_ADC);
left = (oval1 & ~SV_RECSRC_OUT) | left;
right = (oval2 & ~SV_RECSRC_OUT) | right;
change = left != oval1 || right != oval2;
snd_sonicvibes_out1(sonic, SV_IREG_LEFT_ADC, left);
snd_sonicvibes_out1(sonic, SV_IREG_RIGHT_ADC, right);
spin_unlock_irq(&sonic->reg_lock);
return change;
}
#define SONICVIBES_SINGLE(xname, xindex, reg, shift, mask, invert) \
{ .iface = <API key>, .name = xname, .index = xindex, \
.info = <API key>, \
.get = <API key>, .put = <API key>, \
.private_value = reg | (shift << 8) | (mask << 16) | (invert << 24) }
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 16) & 0xff;
uinfo->type = mask == 1 ? <API key> : <API key>;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
spin_lock_irq(&sonic->reg_lock);
ucontrol->value.integer.value[0] = (snd_sonicvibes_in1(sonic, reg)>> shift) & mask;
spin_unlock_irq(&sonic->reg_lock);
if (invert)
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int change;
unsigned short val, oval;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = mask - val;
val <<= shift;
spin_lock_irq(&sonic->reg_lock);
oval = snd_sonicvibes_in1(sonic, reg);
val = (oval & ~(mask << shift)) | val;
change = val != oval;
snd_sonicvibes_out1(sonic, reg, val);
spin_unlock_irq(&sonic->reg_lock);
return change;
}
#define SONICVIBES_DOUBLE(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert) \
{ .iface = <API key>, .name = xname, .index = xindex, \
.info = <API key>, \
.get = <API key>, .put = <API key>, \
.private_value = left_reg | (right_reg << 8) | (shift_left << 16) | (shift_right << 19) | (mask << 24) | (invert << 22) }
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 24) & 0xff;
uinfo->type = mask == 1 ? <API key> : <API key>;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
spin_lock_irq(&sonic->reg_lock);
ucontrol->value.integer.value[0] = (snd_sonicvibes_in1(sonic, left_reg) >> shift_left) & mask;
ucontrol->value.integer.value[1] = (snd_sonicvibes_in1(sonic, right_reg) >> shift_right) & mask;
spin_unlock_irq(&sonic->reg_lock);
if (invert) {
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
ucontrol->value.integer.value[1] = mask - ucontrol->value.integer.value[1];
}
return 0;
}
static int <API key>(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
int change;
unsigned short val1, val2, oval1, oval2;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
if (invert) {
val1 = mask - val1;
val2 = mask - val2;
}
val1 <<= shift_left;
val2 <<= shift_right;
spin_lock_irq(&sonic->reg_lock);
oval1 = snd_sonicvibes_in1(sonic, left_reg);
oval2 = snd_sonicvibes_in1(sonic, right_reg);
val1 = (oval1 & ~(mask << shift_left)) | val1;
val2 = (oval2 & ~(mask << shift_right)) | val2;
change = val1 != oval1 || val2 != oval2;
snd_sonicvibes_out1(sonic, left_reg, val1);
snd_sonicvibes_out1(sonic, right_reg, val2);
spin_unlock_irq(&sonic->reg_lock);
return change;
}
static struct snd_kcontrol_new <API key>[] __devinitdata = {
SONICVIBES_DOUBLE("Capture Volume", 0, SV_IREG_LEFT_ADC, SV_IREG_RIGHT_ADC, 0, 0, 15, 0),
SONICVIBES_DOUBLE("Aux Playback Switch", 0, SV_IREG_LEFT_AUX1, SV_IREG_RIGHT_AUX1, 7, 7, 1, 1),
SONICVIBES_DOUBLE("Aux Playback Volume", 0, SV_IREG_LEFT_AUX1, SV_IREG_RIGHT_AUX1, 0, 0, 31, 1),
SONICVIBES_DOUBLE("CD Playback Switch", 0, SV_IREG_LEFT_CD, SV_IREG_RIGHT_CD, 7, 7, 1, 1),
SONICVIBES_DOUBLE("CD Playback Volume", 0, SV_IREG_LEFT_CD, SV_IREG_RIGHT_CD, 0, 0, 31, 1),
SONICVIBES_DOUBLE("Line Playback Switch", 0, SV_IREG_LEFT_LINE, SV_IREG_RIGHT_LINE, 7, 7, 1, 1),
SONICVIBES_DOUBLE("Line Playback Volume", 0, SV_IREG_LEFT_LINE, SV_IREG_RIGHT_LINE, 0, 0, 31, 1),
SONICVIBES_SINGLE("Mic Playback Switch", 0, SV_IREG_MIC, 7, 1, 1),
SONICVIBES_SINGLE("Mic Playback Volume", 0, SV_IREG_MIC, 0, 15, 1),
SONICVIBES_SINGLE("Mic Boost", 0, SV_IREG_LEFT_ADC, 4, 1, 0),
SONICVIBES_DOUBLE("Synth Playback Switch", 0, SV_IREG_LEFT_SYNTH, SV_IREG_RIGHT_SYNTH, 7, 7, 1, 1),
SONICVIBES_DOUBLE("Synth Playback Volume", 0, SV_IREG_LEFT_SYNTH, SV_IREG_RIGHT_SYNTH, 0, 0, 31, 1),
SONICVIBES_DOUBLE("Aux Playback Switch", 1, SV_IREG_LEFT_AUX2, SV_IREG_RIGHT_AUX2, 7, 7, 1, 1),
SONICVIBES_DOUBLE("Aux Playback Volume", 1, SV_IREG_LEFT_AUX2, SV_IREG_RIGHT_AUX2, 0, 0, 31, 1),
SONICVIBES_DOUBLE("Master Playback Switch", 0, SV_IREG_LEFT_ANALOG, <API key>, 7, 7, 1, 1),
SONICVIBES_DOUBLE("Master Playback Volume", 0, SV_IREG_LEFT_ANALOG, <API key>, 0, 0, 31, 1),
SONICVIBES_DOUBLE("PCM Playback Switch", 0, SV_IREG_LEFT_PCM, SV_IREG_RIGHT_PCM, 7, 7, 1, 1),
SONICVIBES_DOUBLE("PCM Playback Volume", 0, SV_IREG_LEFT_PCM, SV_IREG_RIGHT_PCM, 0, 0, 63, 1),
SONICVIBES_SINGLE("Loopback Capture Switch", 0, <API key>, 0, 1, 0),
SONICVIBES_SINGLE("Loopback Capture Volume", 0, <API key>, 2, 63, 1),
SONICVIBES_MUX("Capture Source", 0)
};
static void <API key>(struct snd_kcontrol *kcontrol)
{
struct sonicvibes *sonic = snd_kcontrol_chip(kcontrol);
sonic->master_mute = NULL;
sonic->master_volume = NULL;
}
static int __devinit <API key>(struct sonicvibes * sonic)
{
struct snd_card *card;
struct snd_kcontrol *kctl;
unsigned int idx;
int err;
if (snd_BUG_ON(!sonic || !sonic->card))
return -EINVAL;
card = sonic->card;
strcpy(card->mixername, "S3 SonicVibes");
for (idx = 0; idx < ARRAY_SIZE(<API key>); idx++) {
if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&<API key>[idx], sonic))) < 0)
return err;
switch (idx) {
case 0:
case 1: kctl->private_free = <API key>; break;
}
}
return 0;
}
static void <API key>(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct sonicvibes *sonic = entry->private_data;
unsigned char tmp;
tmp = sonic->srs_space & 0x0f;
snd_iprintf(buffer, "SRS 3D : %s\n",
sonic->srs_space & 0x80 ? "off" : "on");
snd_iprintf(buffer, "SRS Space : %s\n",
tmp == 0x00 ? "100%" :
tmp == 0x01 ? "75%" :
tmp == 0x02 ? "50%" :
tmp == 0x03 ? "25%" : "0%");
tmp = sonic->srs_center & 0x0f;
snd_iprintf(buffer, "SRS Center : %s\n",
tmp == 0x00 ? "100%" :
tmp == 0x01 ? "75%" :
tmp == 0x02 ? "50%" :
tmp == 0x03 ? "25%" : "0%");
tmp = sonic->wave_source & 0x03;
snd_iprintf(buffer, "WaveTable Source : %s\n",
tmp == 0x00 ? "on-board ROM" :
tmp == 0x01 ? "PCI bus" : "on-board ROM + PCI bus");
tmp = sonic->mpu_switch;
snd_iprintf(buffer, "Onboard synth : %s\n", tmp & 0x01 ? "on" : "off");
snd_iprintf(buffer, "Ext. Rx to synth : %s\n", tmp & 0x02 ? "on" : "off");
snd_iprintf(buffer, "MIDI to ext. Tx : %s\n", tmp & 0x04 ? "on" : "off");
}
static void __devinit <API key>(struct sonicvibes * sonic)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(sonic->card, "sonicvibes", &entry))
<API key>(entry, sonic, <API key>);
}
#ifdef SUPPORT_JOYSTICK
static struct snd_kcontrol_new <API key> __devinitdata =
SONICVIBES_SINGLE("Joystick Speed", 0, SV_IREG_GAME_PORT, 1, 15, 0);
static int __devinit <API key>(struct sonicvibes *sonic)
{
struct gameport *gp;
sonic->gameport = gp = <API key>();
if (!gp) {
printk(KERN_ERR "sonicvibes: cannot allocate memory for gameport\n");
return -ENOMEM;
}
gameport_set_name(gp, "SonicVibes Gameport");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(sonic->pci));
<API key>(gp, &sonic->pci->dev);
gp->io = sonic->game_port;
<API key>(gp);
snd_ctl_add(sonic->card, snd_ctl_new1(&<API key>, sonic));
return 0;
}
static void <API key>(struct sonicvibes *sonic)
{
if (sonic->gameport) {
<API key>(sonic->gameport);
sonic->gameport = NULL;
}
}
#else
static inline int <API key>(struct sonicvibes *sonic) { return -ENOSYS; }
static inline void <API key>(struct sonicvibes *sonic) { }
#endif
static int snd_sonicvibes_free(struct sonicvibes *sonic)
{
<API key>(sonic);
<API key>(sonic->pci, 0x40, sonic->dmaa_port);
<API key>(sonic->pci, 0x48, sonic->dmac_port);
if (sonic->irq >= 0)
free_irq(sonic->irq, sonic);
<API key>(sonic->res_dmaa);
<API key>(sonic->res_dmac);
pci_release_regions(sonic->pci);
pci_disable_device(sonic->pci);
kfree(sonic);
return 0;
}
static int <API key>(struct snd_device *device)
{
struct sonicvibes *sonic = device->device_data;
return snd_sonicvibes_free(sonic);
}
static int __devinit <API key>(struct snd_card *card,
struct pci_dev *pci,
int reverb,
int mge,
struct sonicvibes ** rsonic)
{
struct sonicvibes *sonic;
unsigned int dmaa, dmac;
int err;
static struct snd_device_ops ops = {
.dev_free = <API key>,
};
*rsonic = NULL;
if ((err = pci_enable_device(pci)) < 0)
return err;
if (pci_set_dma_mask(pci, DMA_BIT_MASK(24)) < 0 ||
<API key>(pci, DMA_BIT_MASK(24)) < 0) {
snd_printk(KERN_ERR "architecture does not support 24bit PCI busmaster DMA\n");
pci_disable_device(pci);
return -ENXIO;
}
sonic = kzalloc(sizeof(*sonic), GFP_KERNEL);
if (sonic == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&sonic->reg_lock);
sonic->card = card;
sonic->pci = pci;
sonic->irq = -1;
if ((err = pci_request_regions(pci, "S3 SonicVibes")) < 0) {
kfree(sonic);
pci_disable_device(pci);
return err;
}
sonic->sb_port = pci_resource_start(pci, 0);
sonic->enh_port = pci_resource_start(pci, 1);
sonic->synth_port = pci_resource_start(pci, 2);
sonic->midi_port = pci_resource_start(pci, 3);
sonic->game_port = pci_resource_start(pci, 4);
if (request_irq(pci->irq, <API key>, IRQF_SHARED,
KBUILD_MODNAME, sonic)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_sonicvibes_free(sonic);
return -EBUSY;
}
sonic->irq = pci->irq;
<API key>(pci, 0x40, &dmaa);
<API key>(pci, 0x48, &dmac);
dmaio &= ~0x0f;
dmaa &= ~0x0f;
dmac &= ~0x0f;
if (!dmaa) {
dmaa = dmaio;
dmaio += 0x10;
snd_printk(KERN_INFO "BIOS did not allocate DDMA channel A i/o, allocated at 0x%x\n", dmaa);
}
if (!dmac) {
dmac = dmaio;
dmaio += 0x10;
snd_printk(KERN_INFO "BIOS did not allocate DDMA channel C i/o, allocated at 0x%x\n", dmac);
}
<API key>(pci, 0x40, dmaa);
<API key>(pci, 0x48, dmac);
if ((sonic->res_dmaa = request_region(dmaa, 0x10, "S3 SonicVibes DDMA-A")) == NULL) {
snd_sonicvibes_free(sonic);
snd_printk(KERN_ERR "unable to grab DDMA-A port at 0x%x-0x%x\n", dmaa, dmaa + 0x10 - 1);
return -EBUSY;
}
if ((sonic->res_dmac = request_region(dmac, 0x10, "S3 SonicVibes DDMA-C")) == NULL) {
snd_sonicvibes_free(sonic);
snd_printk(KERN_ERR "unable to grab DDMA-C port at 0x%x-0x%x\n", dmac, dmac + 0x10 - 1);
return -EBUSY;
}
<API key>(pci, 0x40, &sonic->dmaa_port);
<API key>(pci, 0x48, &sonic->dmac_port);
sonic->dmaa_port &= ~0x0f;
sonic->dmac_port &= ~0x0f;
<API key>(pci, 0x40, sonic->dmaa_port | 9);
<API key>(pci, 0x48, sonic->dmac_port | 9);
outb(SV_RESET, SV_REG(sonic, CONTROL));
udelay(100);
outb(0, SV_REG(sonic, CONTROL));
udelay(100);
outb(SV_ENHANCED | SV_INTA | (reverb ? SV_REVERB : 0), SV_REG(sonic, CONTROL));
inb(SV_REG(sonic, STATUS));
#if 1
snd_sonicvibes_out(sonic, SV_IREG_DRIVE_CTRL, 0);
#else
snd_sonicvibes_out(sonic, SV_IREG_DRIVE_CTRL, 0x40);
#endif
snd_sonicvibes_out(sonic, SV_IREG_PC_ENABLE, sonic->enable = 0);
outb(sonic->irqmask = ~(SV_DMAA_MASK | SV_DMAC_MASK | SV_UD_MASK), SV_REG(sonic, IRQMASK));
inb(SV_REG(sonic, STATUS));
snd_sonicvibes_out(sonic, SV_IREG_ADC_CLOCK, 0);
snd_sonicvibes_out(sonic, <API key>, 0);
snd_sonicvibes_out(sonic, <API key>, 0);
<API key>(sonic, SV_IREG_ADC_PLL, 8000);
snd_sonicvibes_out(sonic, SV_IREG_SRS_SPACE, sonic->srs_space = 0x80);
snd_sonicvibes_out(sonic, SV_IREG_SRS_CENTER, sonic->srs_center = 0x00);
snd_sonicvibes_out(sonic, SV_IREG_MPU401, sonic->mpu_switch = 0x05);
snd_sonicvibes_out(sonic, SV_IREG_WAVE_SOURCE, sonic->wave_source = 0x00);
snd_sonicvibes_out(sonic, <API key>, (8000 * 65536 / SV_FULLRATE) & 0xff);
snd_sonicvibes_out(sonic, <API key>, ((8000 * 65536 / SV_FULLRATE) >> 8) & 0xff);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_ADC, mge ? 0xd0 : 0xc0);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_ADC, 0xc0);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_AUX1, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_AUX1, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_CD, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_CD, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_LINE, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_LINE, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_MIC, 0x8f);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_SYNTH, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_SYNTH, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_AUX2, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_AUX2, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_ANALOG, 0x9f);
snd_sonicvibes_out(sonic, <API key>, 0x9f);
snd_sonicvibes_out(sonic, SV_IREG_LEFT_PCM, 0xbf);
snd_sonicvibes_out(sonic, SV_IREG_RIGHT_PCM, 0xbf);
snd_sonicvibes_out(sonic, <API key>, 0xfc);
#if 0
<API key>(sonic);
#endif
sonic->revision = snd_sonicvibes_in(sonic, SV_IREG_REVISION);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, sonic, &ops)) < 0) {
snd_sonicvibes_free(sonic);
return err;
}
<API key>(sonic);
snd_card_set_dev(card, &pci->dev);
*rsonic = sonic;
return 0;
}
static struct snd_kcontrol_new <API key>[] __devinitdata = {
SONICVIBES_SINGLE("SonicVibes Wave Source RAM", 0, SV_IREG_WAVE_SOURCE, 0, 1, 0),
SONICVIBES_SINGLE("SonicVibes Wave Source RAM+ROM", 0, SV_IREG_WAVE_SOURCE, 1, 1, 0),
SONICVIBES_SINGLE("SonicVibes Onboard Synth", 0, SV_IREG_MPU401, 0, 1, 0),
SONICVIBES_SINGLE("SonicVibes External Rx to Synth", 0, SV_IREG_MPU401, 1, 1, 0),
SONICVIBES_SINGLE("SonicVibes External Tx", 0, SV_IREG_MPU401, 2, 1, 0)
};
static int <API key>(struct snd_mpu401 * mpu)
{
struct sonicvibes *sonic = mpu->private_data;
outb(sonic->irqmask &= ~SV_MIDI_MASK, SV_REG(sonic, IRQMASK));
return 0;
}
static void <API key>(struct snd_mpu401 * mpu)
{
struct sonicvibes *sonic = mpu->private_data;
outb(sonic->irqmask |= SV_MIDI_MASK, SV_REG(sonic, IRQMASK));
}
static int __devinit snd_sonicvibes_midi(struct sonicvibes * sonic,
struct snd_rawmidi *rmidi)
{
struct snd_mpu401 * mpu = rmidi->private_data;
struct snd_card *card = sonic->card;
struct snd_rawmidi_str *dir;
unsigned int idx;
int err;
mpu->private_data = sonic;
mpu->open_input = <API key>;
mpu->close_input = <API key>;
dir = &rmidi->streams[<API key>];
for (idx = 0; idx < ARRAY_SIZE(<API key>); idx++)
if ((err = snd_ctl_add(card, snd_ctl_new1(&<API key>[idx], sonic))) < 0)
return err;
return 0;
}
static int __devinit snd_sonic_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct sonicvibes *sonic;
struct snd_rawmidi *midi_uart;
struct snd_opl3 *opl3;
int idx, err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
for (idx = 0; idx < 5; idx++) {
if (pci_resource_start(pci, idx) == 0 ||
!(pci_resource_flags(pci, idx) & IORESOURCE_IO)) {
snd_card_free(card);
return -ENODEV;
}
}
if ((err = <API key>(card, pci,
reverb[dev] ? 1 : 0,
mge[dev] ? 1 : 0,
&sonic)) < 0) {
snd_card_free(card);
return err;
}
strcpy(card->driver, "SonicVibes");
strcpy(card->shortname, "S3 SonicVibes");
sprintf(card->longname, "%s rev %i at 0x%llx, irq %i",
card->shortname,
sonic->revision,
(unsigned long long)pci_resource_start(pci, 1),
sonic->irq);
if ((err = snd_sonicvibes_pcm(sonic, 0, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = <API key>(sonic)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_mpu401_uart_new(card, 0, <API key>,
sonic->midi_port,
<API key> |
<API key>,
-1, &midi_uart)) < 0) {
snd_card_free(card);
return err;
}
snd_sonicvibes_midi(sonic, midi_uart);
if ((err = snd_opl3_create(card, sonic->synth_port,
sonic->synth_port + 2,
OPL3_HW_OPL3_SV, 1, &opl3)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
snd_card_free(card);
return err;
}
<API key>(sonic);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void __devexit snd_sonic_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
static struct pci_driver driver = {
.name = KBUILD_MODNAME,
.id_table = snd_sonic_ids,
.probe = snd_sonic_probe,
.remove = __devexit_p(snd_sonic_remove),
};
static int __init <API key>(void)
{
return pci_register_driver(&driver);
}
static void __exit <API key>(void)
{
<API key>(&driver);
}
module_init(<API key>)
module_exit(<API key>)
|
#include <linux/buffer_head.h>
#include <linux/hdreg.h>
#include <linux/slab.h>
#include <asm/dasd.h>
#include <asm/ebcdic.h>
#include <asm/uaccess.h>
#include <asm/vtoc.h>
#include "check.h"
#include "ibm.h"
static sector_t
cchh2blk (struct vtoc_cchh *ptr, struct hd_geometry *geo) {
sector_t cyl;
__u16 head;
cyl = ptr->hh & 0xFFF0;
cyl <<= 12;
cyl |= ptr->cc;
head = ptr->hh & 0x000F;
return cyl * geo->heads * geo->sectors +
head * geo->sectors;
}
static sector_t
cchhb2blk (struct vtoc_cchhb *ptr, struct hd_geometry *geo) {
sector_t cyl;
__u16 head;
cyl = ptr->hh & 0xFFF0;
cyl <<= 12;
cyl |= ptr->cc;
head = ptr->hh & 0x000F;
return cyl * geo->heads * geo->sectors +
head * geo->sectors +
ptr->b;
}
int ibm_partition(struct parsed_partitions *state)
{
struct block_device *bdev = state->bdev;
int blocksize, res;
loff_t i_size, offset, size, fmt_size;
dasd_information2_t *info;
struct hd_geometry *geo;
char type[5] = {0,};
char name[7] = {0,};
union label_t {
struct <API key> vol;
struct <API key> lnx;
struct vtoc_cms_label cms;
} *label;
unsigned char *data;
Sector sect;
sector_t labelsect;
char tmp[64];
res = 0;
blocksize = <API key>(bdev);
if (blocksize <= 0)
goto out_exit;
i_size = i_size_read(bdev->bd_inode);
if (i_size == 0)
goto out_exit;
info = kmalloc(sizeof(dasd_information2_t), GFP_KERNEL);
if (info == NULL)
goto out_exit;
geo = kmalloc(sizeof(struct hd_geometry), GFP_KERNEL);
if (geo == NULL)
goto out_nogeo;
label = kmalloc(sizeof(union label_t), GFP_KERNEL);
if (label == NULL)
goto out_nolab;
if (ioctl_by_bdev(bdev, BIODASDINFO2, (unsigned long)info) != 0 ||
ioctl_by_bdev(bdev, HDIO_GETGEO, (unsigned long)geo) != 0)
goto out_freeall;
if ((info->cu_type == 0x6310 && info->dev_type == 0x9336) ||
(info->cu_type == 0x3880 && info->dev_type == 0x3370))
labelsect = info->label_block;
else
labelsect = info->label_block * (blocksize >> 9);
data = read_part_sector(state, labelsect, §);
if (data == NULL)
goto out_readerr;
memcpy(label, data, sizeof(union label_t));
put_dev_sector(sect);
if ((!info->FBA_layout) && (!strcmp(info->type, "ECKD"))) {
strncpy(type, label->vol.vollbl, 4);
strncpy(name, label->vol.volid, 6);
} else {
strncpy(type, label->lnx.vollbl, 4);
strncpy(name, label->lnx.volid, 6);
}
EBCASC(type, 4);
EBCASC(name, 6);
res = 1;
if (info->format == DASD_FORMAT_LDL) {
if (strncmp(type, "CMS1", 4) == 0) {
blocksize = label->cms.block_size;
if (label->cms.disk_offset != 0) {
snprintf(tmp, sizeof(tmp), "CMS1/%8s(MDSK):", name);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
offset = label->cms.disk_offset;
size = (label->cms.block_count - 1)
* (blocksize >> 9);
} else {
snprintf(tmp, sizeof(tmp), "CMS1/%8s:", name);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
offset = (info->label_block + 1);
size = label->cms.block_count
* (blocksize >> 9);
}
put_partition(state, 1, offset*(blocksize >> 9),
size-offset*(blocksize >> 9));
} else {
if (strncmp(type, "LNX1", 4) == 0) {
snprintf(tmp, sizeof(tmp), "LNX1/%8s:", name);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
if (label->lnx.ldl_version == 0xf2) {
fmt_size = label->lnx.formatted_blocks
* (blocksize >> 9);
} else if (!strcmp(info->type, "ECKD")) {
fmt_size = geo->cylinders * geo->heads
* geo->sectors * (blocksize >> 9);
} else {
fmt_size = i_size >> 9;
}
size = i_size >> 9;
if (fmt_size < size)
size = fmt_size;
offset = (info->label_block + 1);
} else {
strlcat(state->pp_buf, "(nonl)", PAGE_SIZE);
size = i_size >> 9;
offset = (info->label_block + 1);
}
put_partition(state, 1, offset*(blocksize >> 9),
size-offset*(blocksize >> 9));
}
} else if (info->format == DASD_FORMAT_CDL) {
sector_t blk;
int counter;
if (strncmp(type, "VOL1", 4) == 0) {
snprintf(tmp, sizeof(tmp), "VOL1/%8s:", name);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
blk = cchhb2blk(&label->vol.vtoc, geo) + 1;
counter = 0;
data = read_part_sector(state, blk * (blocksize/512),
§);
while (data != NULL) {
struct vtoc_format1_label f1;
memcpy(&f1, data,
sizeof(struct vtoc_format1_label));
put_dev_sector(sect);
if (f1.DS1FMTID == _ascebc['4']
|| f1.DS1FMTID == _ascebc['5']
|| f1.DS1FMTID == _ascebc['7']
|| f1.DS1FMTID == _ascebc['9']) {
blk++;
data = read_part_sector(state,
blk * (blocksize/512), §);
continue;
}
if (f1.DS1FMTID != _ascebc['1'] &&
f1.DS1FMTID != _ascebc['8'])
break;
offset = cchh2blk(&f1.DS1EXT1.llimit, geo);
size = cchh2blk(&f1.DS1EXT1.ulimit, geo) -
offset + geo->sectors;
if (counter >= state->limit)
break;
put_partition(state, counter + 1,
offset * (blocksize >> 9),
size * (blocksize >> 9));
counter++;
blk++;
data = read_part_sector(state,
blk * (blocksize/512), §);
}
if (!data)
goto out_readerr;
} else
printk(KERN_WARNING "Warning, expected Label VOL1 not "
"found, treating as CDL formated Disk");
}
strlcat(state->pp_buf, "\n", PAGE_SIZE);
goto out_freeall;
out_readerr:
res = -1;
out_freeall:
kfree(label);
out_nolab:
kfree(geo);
out_nogeo:
kfree(info);
out_exit:
return res;
}
|
#ifndef <API key>
#define <API key>
#define __ALIGN .align 0
#define __ALIGN_STR ".align 0"
#endif
|
#include <linux/mISDNif.h>
#include <linux/slab.h>
#include "core.h"
#include "fsm.h"
#include "layer2.h"
static u_int *debug;
static
struct Fsm l2fsm = {NULL, 0, 0, NULL, NULL};
static char *strL2State[] =
{
"ST_L2_1",
"ST_L2_2",
"ST_L2_3",
"ST_L2_4",
"ST_L2_5",
"ST_L2_6",
"ST_L2_7",
"ST_L2_8",
};
enum {
EV_L2_UI,
EV_L2_SABME,
EV_L2_DISC,
EV_L2_DM,
EV_L2_UA,
EV_L2_FRMR,
EV_L2_SUPER,
EV_L2_I,
EV_L2_DL_DATA,
EV_L2_ACK_PULL,
EV_L2_DL_UNITDATA,
<API key>,
<API key>,
EV_L2_MDL_ASSIGN,
EV_L2_MDL_REMOVE,
EV_L2_MDL_ERROR,
EV_L1_DEACTIVATE,
EV_L2_T200,
EV_L2_T203,
EV_L2_SET_OWN_BUSY,
<API key>,
EV_L2_FRAME_ERROR,
};
#define L2_EVENT_COUNT (EV_L2_FRAME_ERROR + 1)
static char *strL2Event[] =
{
"EV_L2_UI",
"EV_L2_SABME",
"EV_L2_DISC",
"EV_L2_DM",
"EV_L2_UA",
"EV_L2_FRMR",
"EV_L2_SUPER",
"EV_L2_I",
"EV_L2_DL_DATA",
"EV_L2_ACK_PULL",
"EV_L2_DL_UNITDATA",
"<API key>",
"<API key>",
"EV_L2_MDL_ASSIGN",
"EV_L2_MDL_REMOVE",
"EV_L2_MDL_ERROR",
"EV_L1_DEACTIVATE",
"EV_L2_T200",
"EV_L2_T203",
"EV_L2_SET_OWN_BUSY",
"<API key>",
"EV_L2_FRAME_ERROR",
};
static void
l2m_debug(struct FsmInst *fi, char *fmt, ...)
{
struct layer2 *l2 = fi->userdata;
struct va_format vaf;
va_list va;
if (!(*debug & DEBUG_L2_FSM))
return;
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
printk(KERN_DEBUG "l2 (sapi %d tei %d): %pV\n",
l2->sapi, l2->tei, &vaf);
va_end(va);
}
inline u_int
l2headersize(struct layer2 *l2, int ui)
{
return ((test_bit(FLG_MOD128, &l2->flag) && (!ui)) ? 2 : 1) +
(test_bit(FLG_LAPD, &l2->flag) ? 2 : 1);
}
inline u_int
l2addrsize(struct layer2 *l2)
{
return test_bit(FLG_LAPD, &l2->flag) ? 2 : 1;
}
static u_int
l2_newid(struct layer2 *l2)
{
u_int id;
id = l2->next_id++;
if (id == 0x7fff)
l2->next_id = 1;
id <<= 16;
id |= l2->tei << 8;
id |= l2->sapi;
return id;
}
static void
l2up(struct layer2 *l2, u_int prim, struct sk_buff *skb)
{
int err;
if (!l2->up)
return;
mISDN_HEAD_PRIM(skb) = prim;
mISDN_HEAD_ID(skb) = (l2->ch.nr << 16) | l2->ch.addr;
err = l2->up->send(l2->up, skb);
if (err) {
printk(KERN_WARNING "%s: err=%d\n", __func__, err);
dev_kfree_skb(skb);
}
}
static void
l2up_create(struct layer2 *l2, u_int prim, int len, void *arg)
{
struct sk_buff *skb;
struct mISDNhead *hh;
int err;
if (!l2->up)
return;
skb = mI_alloc_skb(len, GFP_ATOMIC);
if (!skb)
return;
hh = mISDN_HEAD_P(skb);
hh->prim = prim;
hh->id = (l2->ch.nr << 16) | l2->ch.addr;
if (len)
memcpy(skb_put(skb, len), arg, len);
err = l2->up->send(l2->up, skb);
if (err) {
printk(KERN_WARNING "%s: err=%d\n", __func__, err);
dev_kfree_skb(skb);
}
}
static int
l2down_skb(struct layer2 *l2, struct sk_buff *skb) {
int ret;
ret = l2->ch.recv(l2->ch.peer, skb);
if (ret && (*debug & DEBUG_L2_RECV))
printk(KERN_DEBUG "l2down_skb: ret(%d)\n", ret);
return ret;
}
static int
l2down_raw(struct layer2 *l2, struct sk_buff *skb)
{
struct mISDNhead *hh = mISDN_HEAD_P(skb);
if (hh->prim == PH_DATA_REQ) {
if (test_and_set_bit(FLG_L1_NOTREADY, &l2->flag)) {
skb_queue_tail(&l2->down_queue, skb);
return 0;
}
l2->down_id = mISDN_HEAD_ID(skb);
}
return l2down_skb(l2, skb);
}
static int
l2down(struct layer2 *l2, u_int prim, u_int id, struct sk_buff *skb)
{
struct mISDNhead *hh = mISDN_HEAD_P(skb);
hh->prim = prim;
hh->id = id;
return l2down_raw(l2, skb);
}
static int
l2down_create(struct layer2 *l2, u_int prim, u_int id, int len, void *arg)
{
struct sk_buff *skb;
int err;
struct mISDNhead *hh;
skb = mI_alloc_skb(len, GFP_ATOMIC);
if (!skb)
return -ENOMEM;
hh = mISDN_HEAD_P(skb);
hh->prim = prim;
hh->id = id;
if (len)
memcpy(skb_put(skb, len), arg, len);
err = l2down_raw(l2, skb);
if (err)
dev_kfree_skb(skb);
return err;
}
static int
ph_data_confirm(struct layer2 *l2, struct mISDNhead *hh, struct sk_buff *skb) {
struct sk_buff *nskb = skb;
int ret = -EAGAIN;
if (test_bit(FLG_L1_NOTREADY, &l2->flag)) {
if (hh->id == l2->down_id) {
nskb = skb_dequeue(&l2->down_queue);
if (nskb) {
l2->down_id = mISDN_HEAD_ID(nskb);
if (l2down_skb(l2, nskb)) {
dev_kfree_skb(nskb);
l2->down_id = MISDN_ID_NONE;
}
} else
l2->down_id = MISDN_ID_NONE;
if (ret) {
dev_kfree_skb(skb);
ret = 0;
}
if (l2->down_id == MISDN_ID_NONE) {
test_and_clear_bit(FLG_L1_NOTREADY, &l2->flag);
mISDN_FsmEvent(&l2->l2m, EV_L2_ACK_PULL, NULL);
}
}
}
if (!test_and_set_bit(FLG_L1_NOTREADY, &l2->flag)) {
nskb = skb_dequeue(&l2->down_queue);
if (nskb) {
l2->down_id = mISDN_HEAD_ID(nskb);
if (l2down_skb(l2, nskb)) {
dev_kfree_skb(nskb);
l2->down_id = MISDN_ID_NONE;
test_and_clear_bit(FLG_L1_NOTREADY, &l2->flag);
}
} else
test_and_clear_bit(FLG_L1_NOTREADY, &l2->flag);
}
return ret;
}
static int
l2mgr(struct layer2 *l2, u_int prim, void *arg) {
long c = (long)arg;
printk(KERN_WARNING
"l2mgr: addr:%x prim %x %c\n", l2->id, prim, (char)c);
if (test_bit(FLG_LAPD, &l2->flag) &&
!test_bit(FLG_FIXED_TEI, &l2->flag)) {
switch (c) {
case 'C':
case 'D':
case 'G':
case 'H':
l2_tei(l2, prim, (u_long)arg);
break;
}
}
return 0;
}
static void
set_peer_busy(struct layer2 *l2) {
test_and_set_bit(FLG_PEER_BUSY, &l2->flag);
if (skb_queue_len(&l2->i_queue) || skb_queue_len(&l2->ui_queue))
test_and_set_bit(FLG_L2BLOCK, &l2->flag);
}
static void
clear_peer_busy(struct layer2 *l2) {
if (test_and_clear_bit(FLG_PEER_BUSY, &l2->flag))
test_and_clear_bit(FLG_L2BLOCK, &l2->flag);
}
static void
InitWin(struct layer2 *l2)
{
int i;
for (i = 0; i < MAX_WINDOW; i++)
l2->windowar[i] = NULL;
}
static int
freewin(struct layer2 *l2)
{
int i, cnt = 0;
for (i = 0; i < MAX_WINDOW; i++) {
if (l2->windowar[i]) {
cnt++;
dev_kfree_skb(l2->windowar[i]);
l2->windowar[i] = NULL;
}
}
return cnt;
}
static void
ReleaseWin(struct layer2 *l2)
{
int cnt = freewin(l2);
if (cnt)
printk(KERN_WARNING
"isdnl2 freed %d skbuffs in release\n", cnt);
}
inline unsigned int
cansend(struct layer2 *l2)
{
unsigned int p1;
if (test_bit(FLG_MOD128, &l2->flag))
p1 = (l2->vs - l2->va) % 128;
else
p1 = (l2->vs - l2->va) % 8;
return (p1 < l2->window) && !test_bit(FLG_PEER_BUSY, &l2->flag);
}
inline void
clear_exception(struct layer2 *l2)
{
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
test_and_clear_bit(FLG_REJEXC, &l2->flag);
test_and_clear_bit(FLG_OWN_BUSY, &l2->flag);
clear_peer_busy(l2);
}
static int
sethdraddr(struct layer2 *l2, u_char *header, int rsp)
{
u_char *ptr = header;
int crbit = rsp;
if (test_bit(FLG_LAPD, &l2->flag)) {
if (test_bit(FLG_LAPD_NET, &l2->flag))
crbit = !crbit;
*ptr++ = (l2->sapi << 2) | (crbit ? 2 : 0);
*ptr++ = (l2->tei << 1) | 1;
return 2;
} else {
if (test_bit(FLG_ORIG, &l2->flag))
crbit = !crbit;
if (crbit)
*ptr++ = l2->addr.B;
else
*ptr++ = l2->addr.A;
return 1;
}
}
static inline void
enqueue_super(struct layer2 *l2, struct sk_buff *skb)
{
if (l2down(l2, PH_DATA_REQ, l2_newid(l2), skb))
dev_kfree_skb(skb);
}
static inline void
enqueue_ui(struct layer2 *l2, struct sk_buff *skb)
{
if (l2->tm)
l2_tei(l2, MDL_STATUS_UI_IND, 0);
if (l2down(l2, PH_DATA_REQ, l2_newid(l2), skb))
dev_kfree_skb(skb);
}
inline int
IsUI(u_char *data)
{
return (data[0] & 0xef) == UI;
}
inline int
IsUA(u_char *data)
{
return (data[0] & 0xef) == UA;
}
inline int
IsDM(u_char *data)
{
return (data[0] & 0xef) == DM;
}
inline int
IsDISC(u_char *data)
{
return (data[0] & 0xef) == DISC;
}
inline int
IsRR(u_char *data, struct layer2 *l2)
{
if (test_bit(FLG_MOD128, &l2->flag))
return data[0] == RR;
else
return (data[0] & 0xf) == 1;
}
inline int
IsSFrame(u_char *data, struct layer2 *l2)
{
register u_char d = *data;
if (!test_bit(FLG_MOD128, &l2->flag))
d &= 0xf;
return ((d & 0xf3) == 1) && ((d & 0x0c) != 0x0c);
}
inline int
IsSABME(u_char *data, struct layer2 *l2)
{
u_char d = data[0] & ~0x10;
return test_bit(FLG_MOD128, &l2->flag) ? d == SABME : d == SABM;
}
inline int
IsREJ(u_char *data, struct layer2 *l2)
{
return test_bit(FLG_MOD128, &l2->flag) ?
data[0] == REJ : (data[0] & 0xf) == REJ;
}
inline int
IsFRMR(u_char *data)
{
return (data[0] & 0xef) == FRMR;
}
inline int
IsRNR(u_char *data, struct layer2 *l2)
{
return test_bit(FLG_MOD128, &l2->flag) ?
data[0] == RNR : (data[0] & 0xf) == RNR;
}
static int
iframe_error(struct layer2 *l2, struct sk_buff *skb)
{
u_int i;
int rsp = *skb->data & 0x2;
i = l2addrsize(l2) + (test_bit(FLG_MOD128, &l2->flag) ? 2 : 1);
if (test_bit(FLG_ORIG, &l2->flag))
rsp = !rsp;
if (rsp)
return 'L';
if (skb->len < i)
return 'N';
if ((skb->len - i) > l2->maxlen)
return 'O';
return 0;
}
static int
super_error(struct layer2 *l2, struct sk_buff *skb)
{
if (skb->len != l2addrsize(l2) +
(test_bit(FLG_MOD128, &l2->flag) ? 2 : 1))
return 'N';
return 0;
}
static int
unnum_error(struct layer2 *l2, struct sk_buff *skb, int wantrsp)
{
int rsp = (*skb->data & 0x2) >> 1;
if (test_bit(FLG_ORIG, &l2->flag))
rsp = !rsp;
if (rsp != wantrsp)
return 'L';
if (skb->len != l2addrsize(l2) + 1)
return 'N';
return 0;
}
static int
UI_error(struct layer2 *l2, struct sk_buff *skb)
{
int rsp = *skb->data & 0x2;
if (test_bit(FLG_ORIG, &l2->flag))
rsp = !rsp;
if (rsp)
return 'L';
if (skb->len > l2->maxlen + l2addrsize(l2) + 1)
return 'O';
return 0;
}
static int
FRMR_error(struct layer2 *l2, struct sk_buff *skb)
{
u_int headers = l2addrsize(l2) + 1;
u_char *datap = skb->data + headers;
int rsp = *skb->data & 0x2;
if (test_bit(FLG_ORIG, &l2->flag))
rsp = !rsp;
if (!rsp)
return 'L';
if (test_bit(FLG_MOD128, &l2->flag)) {
if (skb->len < headers + 5)
return 'N';
else if (*debug & DEBUG_L2)
l2m_debug(&l2->l2m,
"FRMR information %2x %2x %2x %2x %2x",
datap[0], datap[1], datap[2], datap[3], datap[4]);
} else {
if (skb->len < headers + 3)
return 'N';
else if (*debug & DEBUG_L2)
l2m_debug(&l2->l2m,
"FRMR information %2x %2x %2x",
datap[0], datap[1], datap[2]);
}
return 0;
}
static unsigned int
legalnr(struct layer2 *l2, unsigned int nr)
{
if (test_bit(FLG_MOD128, &l2->flag))
return ((nr - l2->va) % 128) <= ((l2->vs - l2->va) % 128);
else
return ((nr - l2->va) % 8) <= ((l2->vs - l2->va) % 8);
}
static void
setva(struct layer2 *l2, unsigned int nr)
{
struct sk_buff *skb;
while (l2->va != nr) {
l2->va++;
if (test_bit(FLG_MOD128, &l2->flag))
l2->va %= 128;
else
l2->va %= 8;
if (l2->windowar[l2->sow]) {
skb_trim(l2->windowar[l2->sow], 0);
skb_queue_tail(&l2->tmp_queue, l2->windowar[l2->sow]);
l2->windowar[l2->sow] = NULL;
}
l2->sow = (l2->sow + 1) % l2->window;
}
skb = skb_dequeue(&l2->tmp_queue);
while (skb) {
dev_kfree_skb(skb);
skb = skb_dequeue(&l2->tmp_queue);
}
}
static void
send_uframe(struct layer2 *l2, struct sk_buff *skb, u_char cmd, u_char cr)
{
u_char tmp[MAX_L2HEADER_LEN];
int i;
i = sethdraddr(l2, tmp, cr);
tmp[i++] = cmd;
if (skb)
skb_trim(skb, 0);
else {
skb = mI_alloc_skb(i, GFP_ATOMIC);
if (!skb) {
printk(KERN_WARNING "%s: can't alloc skbuff\n",
__func__);
return;
}
}
memcpy(skb_put(skb, i), tmp, i);
enqueue_super(l2, skb);
}
inline u_char
get_PollFlag(struct layer2 *l2, struct sk_buff *skb)
{
return skb->data[l2addrsize(l2)] & 0x10;
}
inline u_char
get_PollFlagFree(struct layer2 *l2, struct sk_buff *skb)
{
u_char PF;
PF = get_PollFlag(l2, skb);
dev_kfree_skb(skb);
return PF;
}
inline void
start_t200(struct layer2 *l2, int i)
{
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, i);
test_and_set_bit(FLG_T200_RUN, &l2->flag);
}
inline void
restart_t200(struct layer2 *l2, int i)
{
<API key>(&l2->t200, l2->T200, EV_L2_T200, NULL, i);
test_and_set_bit(FLG_T200_RUN, &l2->flag);
}
inline void
stop_t200(struct layer2 *l2, int i)
{
if (test_and_clear_bit(FLG_T200_RUN, &l2->flag))
mISDN_FsmDelTimer(&l2->t200, i);
}
inline void
st5_dl_release_l2l3(struct layer2 *l2)
{
int pr;
if (test_and_clear_bit(FLG_PEND_REL, &l2->flag))
pr = DL_RELEASE_CNF;
else
pr = DL_RELEASE_IND;
l2up_create(l2, pr, 0, NULL);
}
inline void
<API key>(struct layer2 *l2, int f)
{
if (test_bit(FLG_LAPB, &l2->flag))
l2down_create(l2, PH_DEACTIVATE_REQ, l2_newid(l2), 0, NULL);
l2up_create(l2, f, 0, NULL);
}
static void
establishlink(struct FsmInst *fi)
{
struct layer2 *l2 = fi->userdata;
u_char cmd;
clear_exception(l2);
l2->rc = 0;
cmd = (test_bit(FLG_MOD128, &l2->flag) ? SABME : SABM) | 0x10;
send_uframe(l2, NULL, cmd, CMD);
mISDN_FsmDelTimer(&l2->t203, 1);
restart_t200(l2, 1);
test_and_clear_bit(FLG_PEND_REL, &l2->flag);
freewin(l2);
<API key>(fi, ST_L2_5);
}
static void
l2_mdl_error_ua(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
if (get_PollFlagFree(l2, skb))
l2mgr(l2, MDL_ERROR_IND, (void *) 'C');
else
l2mgr(l2, MDL_ERROR_IND, (void *) 'D');
}
static void
l2_mdl_error_dm(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
if (get_PollFlagFree(l2, skb))
l2mgr(l2, MDL_ERROR_IND, (void *) 'B');
else {
l2mgr(l2, MDL_ERROR_IND, (void *) 'E');
establishlink(fi);
test_and_clear_bit(FLG_L3_INIT, &l2->flag);
}
}
static void
l2_st8_mdl_error_dm(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
if (get_PollFlagFree(l2, skb))
l2mgr(l2, MDL_ERROR_IND, (void *) 'B');
else
l2mgr(l2, MDL_ERROR_IND, (void *) 'E');
establishlink(fi);
test_and_clear_bit(FLG_L3_INIT, &l2->flag);
}
static void
l2_go_st3(struct FsmInst *fi, int event, void *arg)
{
dev_kfree_skb((struct sk_buff *)arg);
<API key>(fi, ST_L2_3);
}
static void
l2_mdl_assign(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
<API key>(fi, ST_L2_3);
dev_kfree_skb((struct sk_buff *)arg);
l2_tei(l2, MDL_ASSIGN_IND, 0);
}
static void
l2_queue_ui_assign(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_tail(&l2->ui_queue, skb);
<API key>(fi, ST_L2_2);
l2_tei(l2, MDL_ASSIGN_IND, 0);
}
static void
l2_queue_ui(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_tail(&l2->ui_queue, skb);
}
static void
tx_ui(struct layer2 *l2)
{
struct sk_buff *skb;
u_char header[MAX_L2HEADER_LEN];
int i;
i = sethdraddr(l2, header, CMD);
if (test_bit(FLG_LAPD_NET, &l2->flag))
header[1] = 0xff;
header[i++] = UI;
while ((skb = skb_dequeue(&l2->ui_queue))) {
memcpy(skb_push(skb, i), header, i);
enqueue_ui(l2, skb);
}
}
static void
l2_send_ui(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_tail(&l2->ui_queue, skb);
tx_ui(l2);
}
static void
l2_got_ui(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_pull(skb, l2headersize(l2, 1));
if (l2->tm)
l2_tei(l2, MDL_STATUS_UI_IND, 0);
l2up(l2, DL_UNITDATA_IND, skb);
}
static void
l2_establish(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
establishlink(fi);
test_and_set_bit(FLG_L3_INIT, &l2->flag);
dev_kfree_skb(skb);
}
static void
l2_discard_i_setl3(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->i_queue);
test_and_set_bit(FLG_L3_INIT, &l2->flag);
test_and_clear_bit(FLG_PEND_REL, &l2->flag);
dev_kfree_skb(skb);
}
static void
l2_l3_reestablish(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->i_queue);
establishlink(fi);
test_and_set_bit(FLG_L3_INIT, &l2->flag);
dev_kfree_skb(skb);
}
static void
l2_release(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_trim(skb, 0);
l2up(l2, DL_RELEASE_CNF, skb);
}
static void
l2_pend_rel(struct FsmInst *fi, int event, void *arg)
{
struct sk_buff *skb = arg;
struct layer2 *l2 = fi->userdata;
test_and_set_bit(FLG_PEND_REL, &l2->flag);
dev_kfree_skb(skb);
}
static void
l2_disconnect(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_purge(&l2->i_queue);
freewin(l2);
<API key>(fi, ST_L2_6);
l2->rc = 0;
send_uframe(l2, NULL, DISC | 0x10, CMD);
mISDN_FsmDelTimer(&l2->t203, 1);
restart_t200(l2, 2);
if (skb)
dev_kfree_skb(skb);
}
static void
l2_start_multi(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
l2->vs = 0;
l2->va = 0;
l2->vr = 0;
l2->sow = 0;
clear_exception(l2);
send_uframe(l2, NULL, UA | get_PollFlag(l2, skb), RSP);
<API key>(fi, ST_L2_7);
mISDN_FsmAddTimer(&l2->t203, l2->T203, EV_L2_T203, NULL, 3);
skb_trim(skb, 0);
l2up(l2, DL_ESTABLISH_IND, skb);
if (l2->tm)
l2_tei(l2, MDL_STATUS_UP_IND, 0);
}
static void
l2_send_UA(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
send_uframe(l2, skb, UA | get_PollFlag(l2, skb), RSP);
}
static void
l2_send_DM(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
send_uframe(l2, skb, DM | get_PollFlag(l2, skb), RSP);
}
static void
l2_restart_multi(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
int est = 0;
send_uframe(l2, skb, UA | get_PollFlag(l2, skb), RSP);
l2mgr(l2, MDL_ERROR_IND, (void *) 'F');
if (l2->vs != l2->va) {
skb_queue_purge(&l2->i_queue);
est = 1;
}
clear_exception(l2);
l2->vs = 0;
l2->va = 0;
l2->vr = 0;
l2->sow = 0;
<API key>(fi, ST_L2_7);
stop_t200(l2, 3);
<API key>(&l2->t203, l2->T203, EV_L2_T203, NULL, 3);
if (est)
l2up_create(l2, DL_ESTABLISH_IND, 0, NULL);
if (skb_queue_len(&l2->i_queue) && cansend(l2))
mISDN_FsmEvent(fi, EV_L2_ACK_PULL, NULL);
}
static void
l2_stop_multi(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
<API key>(fi, ST_L2_4);
mISDN_FsmDelTimer(&l2->t203, 3);
stop_t200(l2, 4);
send_uframe(l2, skb, UA | get_PollFlag(l2, skb), RSP);
skb_queue_purge(&l2->i_queue);
freewin(l2);
<API key>(l2, DL_RELEASE_IND);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
}
static void
l2_connected(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
int pr = -1;
if (!get_PollFlag(l2, skb)) {
l2_mdl_error_ua(fi, event, arg);
return;
}
dev_kfree_skb(skb);
if (test_and_clear_bit(FLG_PEND_REL, &l2->flag))
l2_disconnect(fi, event, NULL);
if (test_and_clear_bit(FLG_L3_INIT, &l2->flag)) {
pr = DL_ESTABLISH_CNF;
} else if (l2->vs != l2->va) {
skb_queue_purge(&l2->i_queue);
pr = DL_ESTABLISH_IND;
}
stop_t200(l2, 5);
l2->vr = 0;
l2->vs = 0;
l2->va = 0;
l2->sow = 0;
<API key>(fi, ST_L2_7);
mISDN_FsmAddTimer(&l2->t203, l2->T203, EV_L2_T203, NULL, 4);
if (pr != -1)
l2up_create(l2, pr, 0, NULL);
if (skb_queue_len(&l2->i_queue) && cansend(l2))
mISDN_FsmEvent(fi, EV_L2_ACK_PULL, NULL);
if (l2->tm)
l2_tei(l2, MDL_STATUS_UP_IND, 0);
}
static void
l2_released(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (!get_PollFlag(l2, skb)) {
l2_mdl_error_ua(fi, event, arg);
return;
}
dev_kfree_skb(skb);
stop_t200(l2, 6);
<API key>(l2, DL_RELEASE_CNF);
<API key>(fi, ST_L2_4);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
}
static void
l2_reestablish(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (!get_PollFlagFree(l2, skb)) {
establishlink(fi);
test_and_set_bit(FLG_L3_INIT, &l2->flag);
}
}
static void
l2_st5_dm_release(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (get_PollFlagFree(l2, skb)) {
stop_t200(l2, 7);
if (!test_bit(FLG_L3_INIT, &l2->flag))
skb_queue_purge(&l2->i_queue);
if (test_bit(FLG_LAPB, &l2->flag))
l2down_create(l2, PH_DEACTIVATE_REQ,
l2_newid(l2), 0, NULL);
st5_dl_release_l2l3(l2);
<API key>(fi, ST_L2_4);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
}
}
static void
l2_st6_dm_release(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (get_PollFlagFree(l2, skb)) {
stop_t200(l2, 8);
<API key>(l2, DL_RELEASE_CNF);
<API key>(fi, ST_L2_4);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
}
}
static void
enquiry_cr(struct layer2 *l2, u_char typ, u_char cr, u_char pf)
{
struct sk_buff *skb;
u_char tmp[MAX_L2HEADER_LEN];
int i;
i = sethdraddr(l2, tmp, cr);
if (test_bit(FLG_MOD128, &l2->flag)) {
tmp[i++] = typ;
tmp[i++] = (l2->vr << 1) | (pf ? 1 : 0);
} else
tmp[i++] = (l2->vr << 5) | typ | (pf ? 0x10 : 0);
skb = mI_alloc_skb(i, GFP_ATOMIC);
if (!skb) {
printk(KERN_WARNING
"isdnl2 can't alloc sbbuff for enquiry_cr\n");
return;
}
memcpy(skb_put(skb, i), tmp, i);
enqueue_super(l2, skb);
}
inline void
enquiry_response(struct layer2 *l2)
{
if (test_bit(FLG_OWN_BUSY, &l2->flag))
enquiry_cr(l2, RNR, RSP, 1);
else
enquiry_cr(l2, RR, RSP, 1);
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
}
inline void
transmit_enquiry(struct layer2 *l2)
{
if (test_bit(FLG_OWN_BUSY, &l2->flag))
enquiry_cr(l2, RNR, CMD, 1);
else
enquiry_cr(l2, RR, CMD, 1);
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
start_t200(l2, 9);
}
static void
nrerrorrecovery(struct FsmInst *fi)
{
struct layer2 *l2 = fi->userdata;
l2mgr(l2, MDL_ERROR_IND, (void *) 'J');
establishlink(fi);
test_and_clear_bit(FLG_L3_INIT, &l2->flag);
}
static void
<API key>(struct layer2 *l2, unsigned int nr)
{
u_int p1;
if (l2->vs != nr) {
while (l2->vs != nr) {
(l2->vs)
if (test_bit(FLG_MOD128, &l2->flag)) {
l2->vs %= 128;
p1 = (l2->vs - l2->va) % 128;
} else {
l2->vs %= 8;
p1 = (l2->vs - l2->va) % 8;
}
p1 = (p1 + l2->sow) % l2->window;
if (l2->windowar[p1])
skb_queue_head(&l2->i_queue, l2->windowar[p1]);
else
printk(KERN_WARNING
"%s: windowar[%d] is NULL\n",
__func__, p1);
l2->windowar[p1] = NULL;
}
mISDN_FsmEvent(&l2->l2m, EV_L2_ACK_PULL, NULL);
}
}
static void
l2_st7_got_super(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
int PollFlag, rsp, typ = RR;
unsigned int nr;
rsp = *skb->data & 0x2;
if (test_bit(FLG_ORIG, &l2->flag))
rsp = !rsp;
skb_pull(skb, l2addrsize(l2));
if (IsRNR(skb->data, l2)) {
set_peer_busy(l2);
typ = RNR;
} else
clear_peer_busy(l2);
if (IsREJ(skb->data, l2))
typ = REJ;
if (test_bit(FLG_MOD128, &l2->flag)) {
PollFlag = (skb->data[1] & 0x1) == 0x1;
nr = skb->data[1] >> 1;
} else {
PollFlag = (skb->data[0] & 0x10);
nr = (skb->data[0] >> 5) & 0x7;
}
dev_kfree_skb(skb);
if (PollFlag) {
if (rsp)
l2mgr(l2, MDL_ERROR_IND, (void *) 'A');
else
enquiry_response(l2);
}
if (legalnr(l2, nr)) {
if (typ == REJ) {
setva(l2, nr);
<API key>(l2, nr);
stop_t200(l2, 10);
if (mISDN_FsmAddTimer(&l2->t203, l2->T203,
EV_L2_T203, NULL, 6))
l2m_debug(&l2->l2m, "Restart T203 ST7 REJ");
} else if ((nr == l2->vs) && (typ == RR)) {
setva(l2, nr);
stop_t200(l2, 11);
<API key>(&l2->t203, l2->T203,
EV_L2_T203, NULL, 7);
} else if ((l2->va != nr) || (typ == RNR)) {
setva(l2, nr);
if (typ != RR)
mISDN_FsmDelTimer(&l2->t203, 9);
restart_t200(l2, 12);
}
if (skb_queue_len(&l2->i_queue) && (typ == RR))
mISDN_FsmEvent(fi, EV_L2_ACK_PULL, NULL);
} else
nrerrorrecovery(fi);
}
static void
l2_feed_i_if_reest(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (!test_bit(FLG_L3_INIT, &l2->flag))
skb_queue_tail(&l2->i_queue, skb);
else
dev_kfree_skb(skb);
}
static void
l2_feed_i_pull(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_tail(&l2->i_queue, skb);
mISDN_FsmEvent(fi, EV_L2_ACK_PULL, NULL);
}
static void
l2_feed_iqueue(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_tail(&l2->i_queue, skb);
}
static void
l2_got_iframe(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
int PollFlag, i;
u_int ns, nr;
i = l2addrsize(l2);
if (test_bit(FLG_MOD128, &l2->flag)) {
PollFlag = ((skb->data[i + 1] & 0x1) == 0x1);
ns = skb->data[i] >> 1;
nr = (skb->data[i + 1] >> 1) & 0x7f;
} else {
PollFlag = (skb->data[i] & 0x10);
ns = (skb->data[i] >> 1) & 0x7;
nr = (skb->data[i] >> 5) & 0x7;
}
if (test_bit(FLG_OWN_BUSY, &l2->flag)) {
dev_kfree_skb(skb);
if (PollFlag)
enquiry_response(l2);
} else {
if (l2->vr == ns) {
l2->vr++;
if (test_bit(FLG_MOD128, &l2->flag))
l2->vr %= 128;
else
l2->vr %= 8;
test_and_clear_bit(FLG_REJEXC, &l2->flag);
if (PollFlag)
enquiry_response(l2);
else
test_and_set_bit(FLG_ACK_PEND, &l2->flag);
skb_pull(skb, l2headersize(l2, 0));
l2up(l2, DL_DATA_IND, skb);
} else {
dev_kfree_skb(skb);
if (test_and_set_bit(FLG_REJEXC, &l2->flag)) {
if (PollFlag)
enquiry_response(l2);
} else {
enquiry_cr(l2, REJ, RSP, PollFlag);
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
}
}
}
if (legalnr(l2, nr)) {
if (!test_bit(FLG_PEER_BUSY, &l2->flag) &&
(fi->state == ST_L2_7)) {
if (nr == l2->vs) {
stop_t200(l2, 13);
<API key>(&l2->t203, l2->T203,
EV_L2_T203, NULL, 7);
} else if (nr != l2->va)
restart_t200(l2, 14);
}
setva(l2, nr);
} else {
nrerrorrecovery(fi);
return;
}
if (skb_queue_len(&l2->i_queue) && (fi->state == ST_L2_7))
mISDN_FsmEvent(fi, EV_L2_ACK_PULL, NULL);
if (test_and_clear_bit(FLG_ACK_PEND, &l2->flag))
enquiry_cr(l2, RR, RSP, 0);
}
static void
l2_got_tei(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
u_int info;
l2->tei = (signed char)(long)arg;
set_channel_address(&l2->ch, l2->sapi, l2->tei);
info = DL_INFO_L2_CONNECT;
l2up_create(l2, DL_INFORMATION_IND, sizeof(info), &info);
if (fi->state == ST_L2_3) {
establishlink(fi);
test_and_set_bit(FLG_L3_INIT, &l2->flag);
} else
<API key>(fi, ST_L2_4);
if (skb_queue_len(&l2->ui_queue))
tx_ui(l2);
}
static void
l2_st5_tout_200(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
if (test_bit(FLG_LAPD, &l2->flag) &&
test_bit(FLG_DCHAN_BUSY, &l2->flag)) {
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, 9);
} else if (l2->rc == l2->N200) {
<API key>(fi, ST_L2_4);
test_and_clear_bit(FLG_T200_RUN, &l2->flag);
skb_queue_purge(&l2->i_queue);
l2mgr(l2, MDL_ERROR_IND, (void *) 'G');
if (test_bit(FLG_LAPB, &l2->flag))
l2down_create(l2, PH_DEACTIVATE_REQ,
l2_newid(l2), 0, NULL);
st5_dl_release_l2l3(l2);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
} else {
l2->rc++;
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, 9);
send_uframe(l2, NULL, (test_bit(FLG_MOD128, &l2->flag) ?
SABME : SABM) | 0x10, CMD);
}
}
static void
l2_st6_tout_200(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
if (test_bit(FLG_LAPD, &l2->flag) &&
test_bit(FLG_DCHAN_BUSY, &l2->flag)) {
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, 9);
} else if (l2->rc == l2->N200) {
<API key>(fi, ST_L2_4);
test_and_clear_bit(FLG_T200_RUN, &l2->flag);
l2mgr(l2, MDL_ERROR_IND, (void *) 'H');
<API key>(l2, DL_RELEASE_CNF);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
} else {
l2->rc++;
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200,
NULL, 9);
send_uframe(l2, NULL, DISC | 0x10, CMD);
}
}
static void
l2_st7_tout_200(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
if (test_bit(FLG_LAPD, &l2->flag) &&
test_bit(FLG_DCHAN_BUSY, &l2->flag)) {
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, 9);
return;
}
test_and_clear_bit(FLG_T200_RUN, &l2->flag);
l2->rc = 0;
<API key>(fi, ST_L2_8);
transmit_enquiry(l2);
l2->rc++;
}
static void
l2_st8_tout_200(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
if (test_bit(FLG_LAPD, &l2->flag) &&
test_bit(FLG_DCHAN_BUSY, &l2->flag)) {
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, 9);
return;
}
test_and_clear_bit(FLG_T200_RUN, &l2->flag);
if (l2->rc == l2->N200) {
l2mgr(l2, MDL_ERROR_IND, (void *) 'I');
establishlink(fi);
test_and_clear_bit(FLG_L3_INIT, &l2->flag);
} else {
transmit_enquiry(l2);
l2->rc++;
}
}
static void
l2_st7_tout_203(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
if (test_bit(FLG_LAPD, &l2->flag) &&
test_bit(FLG_DCHAN_BUSY, &l2->flag)) {
mISDN_FsmAddTimer(&l2->t203, l2->T203, EV_L2_T203, NULL, 9);
return;
}
<API key>(fi, ST_L2_8);
transmit_enquiry(l2);
l2->rc = 0;
}
static void
l2_pull_iqueue(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb, *nskb, *oskb;
u_char header[MAX_L2HEADER_LEN];
u_int i, p1;
if (!cansend(l2))
return;
skb = skb_dequeue(&l2->i_queue);
if (!skb)
return;
if (test_bit(FLG_MOD128, &l2->flag))
p1 = (l2->vs - l2->va) % 128;
else
p1 = (l2->vs - l2->va) % 8;
p1 = (p1 + l2->sow) % l2->window;
if (l2->windowar[p1]) {
printk(KERN_WARNING "isdnl2 try overwrite ack queue entry %d\n",
p1);
dev_kfree_skb(l2->windowar[p1]);
}
l2->windowar[p1] = skb;
i = sethdraddr(l2, header, CMD);
if (test_bit(FLG_MOD128, &l2->flag)) {
header[i++] = l2->vs << 1;
header[i++] = l2->vr << 1;
l2->vs = (l2->vs + 1) % 128;
} else {
header[i++] = (l2->vr << 5) | (l2->vs << 1);
l2->vs = (l2->vs + 1) % 8;
}
nskb = skb_clone(skb, GFP_ATOMIC);
p1 = skb_headroom(nskb);
if (p1 >= i)
memcpy(skb_push(nskb, i), header, i);
else {
printk(KERN_WARNING
"isdnl2 pull_iqueue skb header(%d/%d) too short\n", i, p1);
oskb = nskb;
nskb = mI_alloc_skb(oskb->len + i, GFP_ATOMIC);
if (!nskb) {
dev_kfree_skb(oskb);
printk(KERN_WARNING "%s: no skb mem\n", __func__);
return;
}
memcpy(skb_put(nskb, i), header, i);
memcpy(skb_put(nskb, oskb->len), oskb->data, oskb->len);
dev_kfree_skb(oskb);
}
l2down(l2, PH_DATA_REQ, l2_newid(l2), nskb);
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
if (!test_and_set_bit(FLG_T200_RUN, &l2->flag)) {
mISDN_FsmDelTimer(&l2->t203, 13);
mISDN_FsmAddTimer(&l2->t200, l2->T200, EV_L2_T200, NULL, 11);
}
}
static void
l2_st8_got_super(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
int PollFlag, rsp, rnr = 0;
unsigned int nr;
rsp = *skb->data & 0x2;
if (test_bit(FLG_ORIG, &l2->flag))
rsp = !rsp;
skb_pull(skb, l2addrsize(l2));
if (IsRNR(skb->data, l2)) {
set_peer_busy(l2);
rnr = 1;
} else
clear_peer_busy(l2);
if (test_bit(FLG_MOD128, &l2->flag)) {
PollFlag = (skb->data[1] & 0x1) == 0x1;
nr = skb->data[1] >> 1;
} else {
PollFlag = (skb->data[0] & 0x10);
nr = (skb->data[0] >> 5) & 0x7;
}
dev_kfree_skb(skb);
if (rsp && PollFlag) {
if (legalnr(l2, nr)) {
if (rnr) {
restart_t200(l2, 15);
} else {
stop_t200(l2, 16);
mISDN_FsmAddTimer(&l2->t203, l2->T203,
EV_L2_T203, NULL, 5);
setva(l2, nr);
}
<API key>(l2, nr);
<API key>(fi, ST_L2_7);
if (skb_queue_len(&l2->i_queue) && cansend(l2))
mISDN_FsmEvent(fi, EV_L2_ACK_PULL, NULL);
} else
nrerrorrecovery(fi);
} else {
if (!rsp && PollFlag)
enquiry_response(l2);
if (legalnr(l2, nr))
setva(l2, nr);
else
nrerrorrecovery(fi);
}
}
static void
l2_got_FRMR(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_pull(skb, l2addrsize(l2) + 1);
if (!(skb->data[0] & 1) || ((skb->data[0] & 3) == 1) ||
(IsUA(skb->data) && (fi->state == ST_L2_7))) {
l2mgr(l2, MDL_ERROR_IND, (void *) 'K');
establishlink(fi);
test_and_clear_bit(FLG_L3_INIT, &l2->flag);
}
dev_kfree_skb(skb);
}
static void
l2_st24_tei_remove(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->ui_queue);
l2->tei = GROUP_TEI;
<API key>(fi, ST_L2_1);
}
static void
l2_st3_tei_remove(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->ui_queue);
l2->tei = GROUP_TEI;
l2up_create(l2, DL_RELEASE_IND, 0, NULL);
<API key>(fi, ST_L2_1);
}
static void
l2_st5_tei_remove(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->i_queue);
skb_queue_purge(&l2->ui_queue);
freewin(l2);
l2->tei = GROUP_TEI;
stop_t200(l2, 17);
st5_dl_release_l2l3(l2);
<API key>(fi, ST_L2_1);
}
static void
l2_st6_tei_remove(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->ui_queue);
l2->tei = GROUP_TEI;
stop_t200(l2, 18);
l2up_create(l2, DL_RELEASE_IND, 0, NULL);
<API key>(fi, ST_L2_1);
}
static void
l2_tei_remove(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
skb_queue_purge(&l2->i_queue);
skb_queue_purge(&l2->ui_queue);
freewin(l2);
l2->tei = GROUP_TEI;
stop_t200(l2, 17);
mISDN_FsmDelTimer(&l2->t203, 19);
l2up_create(l2, DL_RELEASE_IND, 0, NULL);
<API key>(fi, ST_L2_1);
}
static void
<API key>(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_purge(&l2->i_queue);
skb_queue_purge(&l2->ui_queue);
if (test_and_clear_bit(FLG_ESTAB_PEND, &l2->flag))
l2up(l2, DL_RELEASE_IND, skb);
else
dev_kfree_skb(skb);
}
static void
<API key>(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_purge(&l2->i_queue);
skb_queue_purge(&l2->ui_queue);
freewin(l2);
stop_t200(l2, 19);
st5_dl_release_l2l3(l2);
<API key>(fi, ST_L2_4);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
dev_kfree_skb(skb);
}
static void
<API key>(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_purge(&l2->ui_queue);
stop_t200(l2, 20);
l2up(l2, DL_RELEASE_CNF, skb);
<API key>(fi, ST_L2_4);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
}
static void
l2_persistent_da(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
skb_queue_purge(&l2->i_queue);
skb_queue_purge(&l2->ui_queue);
freewin(l2);
stop_t200(l2, 19);
mISDN_FsmDelTimer(&l2->t203, 19);
l2up(l2, DL_RELEASE_IND, skb);
<API key>(fi, ST_L2_4);
if (l2->tm)
l2_tei(l2, MDL_STATUS_DOWN_IND, 0);
}
static void
l2_set_own_busy(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (!test_and_set_bit(FLG_OWN_BUSY, &l2->flag)) {
enquiry_cr(l2, RNR, RSP, 0);
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
}
if (skb)
dev_kfree_skb(skb);
}
static void
l2_clear_own_busy(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
struct sk_buff *skb = arg;
if (!test_and_clear_bit(FLG_OWN_BUSY, &l2->flag)) {
enquiry_cr(l2, RR, RSP, 0);
test_and_clear_bit(FLG_ACK_PEND, &l2->flag);
}
if (skb)
dev_kfree_skb(skb);
}
static void
l2_frame_error(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
l2mgr(l2, MDL_ERROR_IND, arg);
}
static void
<API key>(struct FsmInst *fi, int event, void *arg)
{
struct layer2 *l2 = fi->userdata;
l2mgr(l2, MDL_ERROR_IND, arg);
establishlink(fi);
test_and_clear_bit(FLG_L3_INIT, &l2->flag);
}
static struct FsmNode L2FnList[] =
{
{ST_L2_1, <API key>, l2_mdl_assign},
{ST_L2_2, <API key>, l2_go_st3},
{ST_L2_4, <API key>, l2_establish},
{ST_L2_5, <API key>, l2_discard_i_setl3},
{ST_L2_7, <API key>, l2_l3_reestablish},
{ST_L2_8, <API key>, l2_l3_reestablish},
{ST_L2_4, <API key>, l2_release},
{ST_L2_5, <API key>, l2_pend_rel},
{ST_L2_7, <API key>, l2_disconnect},
{ST_L2_8, <API key>, l2_disconnect},
{ST_L2_5, EV_L2_DL_DATA, l2_feed_i_if_reest},
{ST_L2_7, EV_L2_DL_DATA, l2_feed_i_pull},
{ST_L2_8, EV_L2_DL_DATA, l2_feed_iqueue},
{ST_L2_1, EV_L2_DL_UNITDATA, l2_queue_ui_assign},
{ST_L2_2, EV_L2_DL_UNITDATA, l2_queue_ui},
{ST_L2_3, EV_L2_DL_UNITDATA, l2_queue_ui},
{ST_L2_4, EV_L2_DL_UNITDATA, l2_send_ui},
{ST_L2_5, EV_L2_DL_UNITDATA, l2_send_ui},
{ST_L2_6, EV_L2_DL_UNITDATA, l2_send_ui},
{ST_L2_7, EV_L2_DL_UNITDATA, l2_send_ui},
{ST_L2_8, EV_L2_DL_UNITDATA, l2_send_ui},
{ST_L2_1, EV_L2_MDL_ASSIGN, l2_got_tei},
{ST_L2_2, EV_L2_MDL_ASSIGN, l2_got_tei},
{ST_L2_3, EV_L2_MDL_ASSIGN, l2_got_tei},
{ST_L2_2, EV_L2_MDL_ERROR, l2_st24_tei_remove},
{ST_L2_3, EV_L2_MDL_ERROR, l2_st3_tei_remove},
{ST_L2_4, EV_L2_MDL_REMOVE, l2_st24_tei_remove},
{ST_L2_5, EV_L2_MDL_REMOVE, l2_st5_tei_remove},
{ST_L2_6, EV_L2_MDL_REMOVE, l2_st6_tei_remove},
{ST_L2_7, EV_L2_MDL_REMOVE, l2_tei_remove},
{ST_L2_8, EV_L2_MDL_REMOVE, l2_tei_remove},
{ST_L2_4, EV_L2_SABME, l2_start_multi},
{ST_L2_5, EV_L2_SABME, l2_send_UA},
{ST_L2_6, EV_L2_SABME, l2_send_DM},
{ST_L2_7, EV_L2_SABME, l2_restart_multi},
{ST_L2_8, EV_L2_SABME, l2_restart_multi},
{ST_L2_4, EV_L2_DISC, l2_send_DM},
{ST_L2_5, EV_L2_DISC, l2_send_DM},
{ST_L2_6, EV_L2_DISC, l2_send_UA},
{ST_L2_7, EV_L2_DISC, l2_stop_multi},
{ST_L2_8, EV_L2_DISC, l2_stop_multi},
{ST_L2_4, EV_L2_UA, l2_mdl_error_ua},
{ST_L2_5, EV_L2_UA, l2_connected},
{ST_L2_6, EV_L2_UA, l2_released},
{ST_L2_7, EV_L2_UA, l2_mdl_error_ua},
{ST_L2_8, EV_L2_UA, l2_mdl_error_ua},
{ST_L2_4, EV_L2_DM, l2_reestablish},
{ST_L2_5, EV_L2_DM, l2_st5_dm_release},
{ST_L2_6, EV_L2_DM, l2_st6_dm_release},
{ST_L2_7, EV_L2_DM, l2_mdl_error_dm},
{ST_L2_8, EV_L2_DM, l2_st8_mdl_error_dm},
{ST_L2_1, EV_L2_UI, l2_got_ui},
{ST_L2_2, EV_L2_UI, l2_got_ui},
{ST_L2_3, EV_L2_UI, l2_got_ui},
{ST_L2_4, EV_L2_UI, l2_got_ui},
{ST_L2_5, EV_L2_UI, l2_got_ui},
{ST_L2_6, EV_L2_UI, l2_got_ui},
{ST_L2_7, EV_L2_UI, l2_got_ui},
{ST_L2_8, EV_L2_UI, l2_got_ui},
{ST_L2_7, EV_L2_FRMR, l2_got_FRMR},
{ST_L2_8, EV_L2_FRMR, l2_got_FRMR},
{ST_L2_7, EV_L2_SUPER, l2_st7_got_super},
{ST_L2_8, EV_L2_SUPER, l2_st8_got_super},
{ST_L2_7, EV_L2_I, l2_got_iframe},
{ST_L2_8, EV_L2_I, l2_got_iframe},
{ST_L2_5, EV_L2_T200, l2_st5_tout_200},
{ST_L2_6, EV_L2_T200, l2_st6_tout_200},
{ST_L2_7, EV_L2_T200, l2_st7_tout_200},
{ST_L2_8, EV_L2_T200, l2_st8_tout_200},
{ST_L2_7, EV_L2_T203, l2_st7_tout_203},
{ST_L2_7, EV_L2_ACK_PULL, l2_pull_iqueue},
{ST_L2_7, EV_L2_SET_OWN_BUSY, l2_set_own_busy},
{ST_L2_8, EV_L2_SET_OWN_BUSY, l2_set_own_busy},
{ST_L2_7, <API key>, l2_clear_own_busy},
{ST_L2_8, <API key>, l2_clear_own_busy},
{ST_L2_4, EV_L2_FRAME_ERROR, l2_frame_error},
{ST_L2_5, EV_L2_FRAME_ERROR, l2_frame_error},
{ST_L2_6, EV_L2_FRAME_ERROR, l2_frame_error},
{ST_L2_7, EV_L2_FRAME_ERROR, <API key>},
{ST_L2_8, EV_L2_FRAME_ERROR, <API key>},
{ST_L2_1, EV_L1_DEACTIVATE, <API key>},
{ST_L2_2, EV_L1_DEACTIVATE, l2_st24_tei_remove},
{ST_L2_3, EV_L1_DEACTIVATE, l2_st3_tei_remove},
{ST_L2_4, EV_L1_DEACTIVATE, <API key>},
{ST_L2_5, EV_L1_DEACTIVATE, <API key>},
{ST_L2_6, EV_L1_DEACTIVATE, <API key>},
{ST_L2_7, EV_L1_DEACTIVATE, l2_persistent_da},
{ST_L2_8, EV_L1_DEACTIVATE, l2_persistent_da},
};
static int
ph_data_indication(struct layer2 *l2, struct mISDNhead *hh, struct sk_buff *skb)
{
u_char *datap = skb->data;
int ret = -EINVAL;
int psapi, ptei;
u_int l;
int c = 0;
l = l2addrsize(l2);
if (skb->len <= l) {
mISDN_FsmEvent(&l2->l2m, EV_L2_FRAME_ERROR, (void *) 'N');
return ret;
}
if (test_bit(FLG_LAPD, &l2->flag)) {
psapi = *datap++;
ptei = *datap++;
if ((psapi & 1) || !(ptei & 1)) {
printk(KERN_WARNING
"l2 D-channel frame wrong EA0/EA1\n");
return ret;
}
psapi >>= 2;
ptei >>= 1;
if (psapi != l2->sapi) {
if (*debug & DEBUG_L2)
printk(KERN_DEBUG "%s: sapi %d/%d mismatch\n",
__func__, psapi, l2->sapi);
dev_kfree_skb(skb);
return 0;
}
if ((ptei != l2->tei) && (ptei != GROUP_TEI)) {
if (*debug & DEBUG_L2)
printk(KERN_DEBUG "%s: tei %d/%d mismatch\n",
__func__, ptei, l2->tei);
dev_kfree_skb(skb);
return 0;
}
} else
datap += l;
if (!(*datap & 1)) {
c = iframe_error(l2, skb);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_I, skb);
} else if (IsSFrame(datap, l2)) {
c = super_error(l2, skb);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_SUPER, skb);
} else if (IsUI(datap)) {
c = UI_error(l2, skb);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_UI, skb);
} else if (IsSABME(datap, l2)) {
c = unnum_error(l2, skb, CMD);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_SABME, skb);
} else if (IsUA(datap)) {
c = unnum_error(l2, skb, RSP);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_UA, skb);
} else if (IsDISC(datap)) {
c = unnum_error(l2, skb, CMD);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_DISC, skb);
} else if (IsDM(datap)) {
c = unnum_error(l2, skb, RSP);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_DM, skb);
} else if (IsFRMR(datap)) {
c = FRMR_error(l2, skb);
if (!c)
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_FRMR, skb);
} else
c = 'L';
if (c) {
printk(KERN_WARNING "l2 D-channel frame error %c\n", c);
mISDN_FsmEvent(&l2->l2m, EV_L2_FRAME_ERROR, (void *)(long)c);
}
return ret;
}
static int
l2_send(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct layer2 *l2 = container_of(ch, struct layer2, ch);
struct mISDNhead *hh = mISDN_HEAD_P(skb);
int ret = -EINVAL;
if (*debug & DEBUG_L2_RECV)
printk(KERN_DEBUG "%s: prim(%x) id(%x) sapi(%d) tei(%d)\n",
__func__, hh->prim, hh->id, l2->sapi, l2->tei);
switch (hh->prim) {
case PH_DATA_IND:
ret = ph_data_indication(l2, hh, skb);
break;
case PH_DATA_CNF:
ret = ph_data_confirm(l2, hh, skb);
break;
case PH_ACTIVATE_IND:
test_and_set_bit(FLG_L1_ACTIV, &l2->flag);
l2up_create(l2, MPH_ACTIVATE_IND, 0, NULL);
if (test_and_clear_bit(FLG_ESTAB_PEND, &l2->flag))
ret = mISDN_FsmEvent(&l2->l2m,
<API key>, skb);
break;
case PH_DEACTIVATE_IND:
test_and_clear_bit(FLG_L1_ACTIV, &l2->flag);
l2up_create(l2, MPH_DEACTIVATE_IND, 0, NULL);
ret = mISDN_FsmEvent(&l2->l2m, EV_L1_DEACTIVATE, skb);
break;
case MPH_INFORMATION_IND:
if (!l2->up)
break;
ret = l2->up->send(l2->up, skb);
break;
case DL_DATA_REQ:
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_DL_DATA, skb);
break;
case DL_UNITDATA_REQ:
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_DL_UNITDATA, skb);
break;
case DL_ESTABLISH_REQ:
if (test_bit(FLG_LAPB, &l2->flag))
test_and_set_bit(FLG_ORIG, &l2->flag);
if (test_bit(FLG_L1_ACTIV, &l2->flag)) {
if (test_bit(FLG_LAPD, &l2->flag) ||
test_bit(FLG_ORIG, &l2->flag))
ret = mISDN_FsmEvent(&l2->l2m,
<API key>, skb);
} else {
if (test_bit(FLG_LAPD, &l2->flag) ||
test_bit(FLG_ORIG, &l2->flag)) {
test_and_set_bit(FLG_ESTAB_PEND,
&l2->flag);
}
ret = l2down(l2, PH_ACTIVATE_REQ, l2_newid(l2),
skb);
}
break;
case DL_RELEASE_REQ:
if (test_bit(FLG_LAPB, &l2->flag))
l2down_create(l2, PH_DEACTIVATE_REQ,
l2_newid(l2), 0, NULL);
ret = mISDN_FsmEvent(&l2->l2m, <API key>,
skb);
break;
default:
if (*debug & DEBUG_L2)
l2m_debug(&l2->l2m, "l2 unknown pr %04x",
hh->prim);
}
if (ret) {
dev_kfree_skb(skb);
ret = 0;
}
return ret;
}
int
tei_l2(struct layer2 *l2, u_int cmd, u_long arg)
{
int ret = -EINVAL;
if (*debug & DEBUG_L2_TEI)
printk(KERN_DEBUG "%s: cmd(%x)\n", __func__, cmd);
switch (cmd) {
case (MDL_ASSIGN_REQ):
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_MDL_ASSIGN, (void *)arg);
break;
case (MDL_REMOVE_REQ):
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_MDL_REMOVE, NULL);
break;
case (MDL_ERROR_IND):
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_MDL_ERROR, NULL);
break;
case (MDL_ERROR_RSP):
printk(KERN_NOTICE "MDL_ERROR|REQ (tei_l2)\n");
ret = mISDN_FsmEvent(&l2->l2m, EV_L2_MDL_ERROR, NULL);
break;
}
return ret;
}
static void
release_l2(struct layer2 *l2)
{
mISDN_FsmDelTimer(&l2->t200, 21);
mISDN_FsmDelTimer(&l2->t203, 16);
skb_queue_purge(&l2->i_queue);
skb_queue_purge(&l2->ui_queue);
skb_queue_purge(&l2->down_queue);
ReleaseWin(l2);
if (test_bit(FLG_LAPD, &l2->flag)) {
TEIrelease(l2);
if (l2->ch.st)
l2->ch.st->dev->D.ctrl(&l2->ch.st->dev->D,
CLOSE_CHANNEL, NULL);
}
kfree(l2);
}
static int
l2_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct layer2 *l2 = container_of(ch, struct layer2, ch);
u_int info;
if (*debug & DEBUG_L2_CTRL)
printk(KERN_DEBUG "%s:(%x)\n", __func__, cmd);
switch (cmd) {
case OPEN_CHANNEL:
if (test_bit(FLG_LAPD, &l2->flag)) {
set_channel_address(&l2->ch, l2->sapi, l2->tei);
info = DL_INFO_L2_CONNECT;
l2up_create(l2, DL_INFORMATION_IND,
sizeof(info), &info);
}
break;
case CLOSE_CHANNEL:
if (l2->ch.peer)
l2->ch.peer->ctrl(l2->ch.peer, CLOSE_CHANNEL, NULL);
release_l2(l2);
break;
}
return 0;
}
struct layer2 *
create_l2(struct mISDNchannel *ch, u_int protocol, u_long options, int tei,
int sapi)
{
struct layer2 *l2;
struct channel_req rq;
l2 = kzalloc(sizeof(struct layer2), GFP_KERNEL);
if (!l2) {
printk(KERN_ERR "kzalloc layer2 failed\n");
return NULL;
}
l2->next_id = 1;
l2->down_id = MISDN_ID_NONE;
l2->up = ch;
l2->ch.st = ch->st;
l2->ch.send = l2_send;
l2->ch.ctrl = l2_ctrl;
switch (protocol) {
case ISDN_P_LAPD_NT:
test_and_set_bit(FLG_LAPD, &l2->flag);
test_and_set_bit(FLG_LAPD_NET, &l2->flag);
test_and_set_bit(FLG_MOD128, &l2->flag);
l2->sapi = sapi;
l2->maxlen = MAX_DFRAME_LEN;
if (test_bit(OPTION_L2_PMX, &options))
l2->window = 7;
else
l2->window = 1;
if (test_bit(OPTION_L2_PTP, &options))
test_and_set_bit(FLG_PTP, &l2->flag);
if (test_bit(OPTION_L2_FIXEDTEI, &options))
test_and_set_bit(FLG_FIXED_TEI, &l2->flag);
l2->tei = tei;
l2->T200 = 1000;
l2->N200 = 3;
l2->T203 = 10000;
if (test_bit(OPTION_L2_PMX, &options))
rq.protocol = ISDN_P_NT_E1;
else
rq.protocol = ISDN_P_NT_S0;
rq.adr.channel = 0;
l2->ch.st->dev->D.ctrl(&l2->ch.st->dev->D, OPEN_CHANNEL, &rq);
break;
case ISDN_P_LAPD_TE:
test_and_set_bit(FLG_LAPD, &l2->flag);
test_and_set_bit(FLG_MOD128, &l2->flag);
test_and_set_bit(FLG_ORIG, &l2->flag);
l2->sapi = sapi;
l2->maxlen = MAX_DFRAME_LEN;
if (test_bit(OPTION_L2_PMX, &options))
l2->window = 7;
else
l2->window = 1;
if (test_bit(OPTION_L2_PTP, &options))
test_and_set_bit(FLG_PTP, &l2->flag);
if (test_bit(OPTION_L2_FIXEDTEI, &options))
test_and_set_bit(FLG_FIXED_TEI, &l2->flag);
l2->tei = tei;
l2->T200 = 1000;
l2->N200 = 3;
l2->T203 = 10000;
if (test_bit(OPTION_L2_PMX, &options))
rq.protocol = ISDN_P_TE_E1;
else
rq.protocol = ISDN_P_TE_S0;
rq.adr.channel = 0;
l2->ch.st->dev->D.ctrl(&l2->ch.st->dev->D, OPEN_CHANNEL, &rq);
break;
case ISDN_P_B_X75SLP:
test_and_set_bit(FLG_LAPB, &l2->flag);
l2->window = 7;
l2->maxlen = MAX_DATA_SIZE;
l2->T200 = 1000;
l2->N200 = 4;
l2->T203 = 5000;
l2->addr.A = 3;
l2->addr.B = 1;
break;
default:
printk(KERN_ERR "layer2 create failed prt %x\n",
protocol);
kfree(l2);
return NULL;
}
skb_queue_head_init(&l2->i_queue);
skb_queue_head_init(&l2->ui_queue);
skb_queue_head_init(&l2->down_queue);
skb_queue_head_init(&l2->tmp_queue);
InitWin(l2);
l2->l2m.fsm = &l2fsm;
if (test_bit(FLG_LAPB, &l2->flag) ||
test_bit(FLG_PTP, &l2->flag) ||
test_bit(FLG_LAPD_NET, &l2->flag))
l2->l2m.state = ST_L2_4;
else
l2->l2m.state = ST_L2_1;
l2->l2m.debug = *debug;
l2->l2m.userdata = l2;
l2->l2m.userint = 0;
l2->l2m.printdebug = l2m_debug;
mISDN_FsmInitTimer(&l2->l2m, &l2->t200);
mISDN_FsmInitTimer(&l2->l2m, &l2->t203);
return l2;
}
static int
x75create(struct channel_req *crq)
{
struct layer2 *l2;
if (crq->protocol != ISDN_P_B_X75SLP)
return -EPROTONOSUPPORT;
l2 = create_l2(crq->ch, crq->protocol, 0, 0, 0);
if (!l2)
return -ENOMEM;
crq->ch = &l2->ch;
crq->protocol = ISDN_P_B_HDLC;
return 0;
}
static struct Bprotocol X75SLP = {
.Bprotocols = (1 << (ISDN_P_B_X75SLP & ISDN_P_B_MASK)),
.name = "X75SLP",
.create = x75create
};
int
Isdnl2_Init(u_int *deb)
{
debug = deb;
<API key>(&X75SLP);
l2fsm.state_count = L2_STATE_COUNT;
l2fsm.event_count = L2_EVENT_COUNT;
l2fsm.strEvent = strL2Event;
l2fsm.strState = strL2State;
mISDN_FsmNew(&l2fsm, L2FnList, ARRAY_SIZE(L2FnList));
TEIInit(deb);
return 0;
}
void
Isdnl2_cleanup(void)
{
<API key>(&X75SLP);
TEIFree();
mISDN_FsmFree(&l2fsm);
}
|
<?php
/**
* Test class for JFacebookGroup.
*
* @package Joomla.UnitTest
* @subpackage Facebook
* @since 13.1
*/
class JFacebookGroupTest extends TestCase
{
/**
* @var JRegistry Options for the Facebook object.
* @since 13.1
*/
protected $options;
/**
* @var JHttp Mock client object.
* @since 13.1
*/
protected $client;
/**
* @var JFacebookGroup Object under test.
* @since 13.1
*/
protected $object;
/**
* @var JFacebookOauth Facebook OAuth 2 client
* @since 13.1
*/
protected $oauth;
/**
* @var string Sample JSON string.
* @since 13.1
*/
protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
/**
* @var string Sample JSON error message.
* @since 13.1
*/
protected $errorString = '{"error": {"message": "Generic Error."}}';
/**
* @var string Sample URL string.
* @since 13.1
*/
protected $sampleUrl = '"https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash2/<API key>.jpg"';
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @return void
*
* @since 13.1
*/
protected function setUp()
{
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$app_id = "app_id";
$app_secret = "app_secret";
$my_url = "http://localhost/gsoc/joomla-platform/facebook_test.php";
$access_token = array(
'access_token' => 'token',
'expires' => '51837673', 'created' => '2443672521');
$this->options = new JRegistry;
$this->client = $this->getMock('JHttp', array('get', 'post', 'delete', 'put'));
$this->input = new JInput;
$this->oauth = new JFacebookOauth($this->options, $this->client, $this->input);
$this->oauth->setToken($access_token);
$this->object = new JFacebookGroup($this->options, $this->client, $this->oauth);
$this->options->set('clientid', $app_id);
$this->options->set('clientsecret', $app_secret);
$this->options->set('redirecturi', $my_url);
$this->options->set('sendheaders', true);
$this->options->set('authmethod', 'get');
parent::setUp();
}
/**
* Tests the getGroup method
*
* @return void
*
* @since 13.1
*/
public function testGetGroup()
{
$token = $this->oauth->getToken();
$group = '124346363456';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('get')
->with($group . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getGroup($group),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getGroup method - failure
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function testGetGroupFailure()
{
$token = $this->oauth->getToken();
$group = '124346363456';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('get')
->with($group . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->getGroup($group);
}
/**
* Tests the getFeed method.
*
* @return void
*
* @since 13.1
*/
public function testGetFeed()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('get')
->with($group . '/feed?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getFeed($group),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getFeed method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function testGetFeedFailure()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('get')
->with($group . '/feed?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->getFeed($group);
}
/**
* Tests the getMembers method.
*
* @return void
*
* @since 13.1
*/
public function testGetMembers()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('get')
->with($group . '/members?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getMembers($group),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getMembers method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('get')
->with($group . '/members?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->getMembers($group);
}
/**
* Tests the getDocs method.
*
* @return void
*
* @since 13.1
*/
public function testGetDocs()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('get')
->with($group . '/docs?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getDocs($group),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getDocs method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function testGetDocsFailure()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('get')
->with($group . '/docs?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->getDocs($group);
}
/**
* Tests the getPicture method.
*
* @return void
*
* @since 13.1
*/
public function testGetPicture()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$type = 'large';
$returnData = new JHttpResponse;
$returnData->code = 302;
$returnData->headers['Location'] = $this->sampleUrl;
$this->client->expects($this->once())
->method('get')
->with($group . '/picture?type=' . $type . '&access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getPicture($group, $type),
$this->equalTo($this->sampleUrl)
);
}
/**
* Tests the getPicture method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$type = 'large';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('get')
->with($group . '/picture?type=' . $type . '&access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->getPicture($group, $type);
}
/**
* Tests the createLink method.
*
* @return void
*
* @since 13.1
*/
public function testCreateLink()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$link = 'www.example.com';
$message = 'This is a message';
// Set POST request parameters.
$data = array();
$data['link'] = $link;
$data['message'] = $message;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('post')
->with($group . '/feed' . '?access_token=' . $token['access_token'], $data)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->createLink($group, $link, $message),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the createLink method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$group = '156174391080008';
$link = 'www.example.com';
$message = 'This is a message';
// Set POST request parameters.
$data = array();
$data['link'] = $link;
$data['message'] = $message;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('post')
->with($group . '/feed' . '?access_token=' . $token['access_token'], $data)
->will($this->returnValue($returnData));
$this->object->createLink($group, $link, $message);
}
/**
* Tests the deleteLink method.
*
* @return void
*
* @since 13.1
*/
public function testDeleteLink()
{
$token = $this->oauth->getToken();
$link = '<API key>';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = true;
$this->client->expects($this->once())
->method('delete')
->with($link . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->deleteLink($link),
$this->equalTo(true)
);
}
/**
* Tests the deleteLink method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$link = '<API key>';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('delete')
->with($link . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->deleteLink($link);
}
/**
* Tests the createPost method.
*
* @return void
*
* @since 13.1
*/
public function testCreatePost()
{
$token = $this->oauth->getToken();
$group = '134534252';
$message = 'message';
$link = 'www.example.com';
$picture = 'thumbnail.example.com';
$name = 'name';
$caption = 'caption';
$description = 'description';
$actions = array('{"name":"Share","link":"http://networkedblogs.com/hGWk3?a=share"}');
// Set POST request parameters.
$data = array();
$data['message'] = $message;
$data['link'] = $link;
$data['name'] = $name;
$data['caption'] = $caption;
$data['description'] = $description;
$data['actions'] = $actions;
$data['picture'] = $picture;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('post')
->with($group . '/feed' . '?access_token=' . $token['access_token'], $data)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->createPost(
$group, $message, $link, $picture, $name,
$caption, $description, $actions
),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the createPost method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$group = '134534252';
$message = 'message';
$link = 'www.example.com';
$picture = 'thumbnail.example.com';
$name = 'name';
$caption = 'caption';
$description = 'description';
$actions = array('{"name":"Share","link":"http://networkedblogs.com/hGWk3?a=share"}');
// Set POST request parameters.
$data = array();
$data['message'] = $message;
$data['link'] = $link;
$data['name'] = $name;
$data['caption'] = $caption;
$data['description'] = $description;
$data['actions'] = $actions;
$data['picture'] = $picture;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('post')
->with($group . '/feed' . '?access_token=' . $token['access_token'], $data)
->will($this->returnValue($returnData));
$this->object->createPost(
$group, $message, $link, $picture, $name,
$caption, $description, $actions
);
}
/**
* Tests the deletePost method.
*
* @return void
*
* @since 13.1
*/
public function testDeletePost()
{
$token = $this->oauth->getToken();
$post = '5148941614_234324';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = true;
$this->client->expects($this->once())
->method('delete')
->with($post . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->deletePost($post),
$this->equalTo(true)
);
}
/**
* Tests the deletePost method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$post = '5148941614_234324';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('delete')
->with($post . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->deletePost($post);
}
/**
* Tests the createStatus method.
*
* @return void
*
* @since 13.1
*/
public function testCreateStatus()
{
$token = $this->oauth->getToken();
$group = '134534252457';
$message = 'This is a message';
// Set POST request parameters.
$data = array();
$data['message'] = $message;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('post')
->with($group . '/feed' . '?access_token=' . $token['access_token'], $data)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->createStatus($group, $message),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the createStatus method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$group = '134534252457';
$message = 'This is a message';
// Set POST request parameters.
$data = array();
$data['message'] = $message;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('post')
->with($group . '/feed' . '?access_token=' . $token['access_token'], $data)
->will($this->returnValue($returnData));
$this->object->createStatus($group, $message);
}
/**
* Tests the deleteStatus method.
*
* @return void
*
* @since 13.1
*/
public function testDeleteStatus()
{
$token = $this->oauth->getToken();
$status = '<API key>';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = true;
$this->client->expects($this->once())
->method('delete')
->with($status . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->deleteStatus($status),
$this->equalTo(true)
);
}
/**
* Tests the deleteStatus method - failure.
*
* @return void
*
* @since 13.1
* @expectedException RuntimeException
*/
public function <API key>()
{
$token = $this->oauth->getToken();
$status = '<API key>';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('delete')
->with($status . '?access_token=' . $token['access_token'])
->will($this->returnValue($returnData));
$this->object->deleteStatus($status);
}
}
|
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
#include <linux/cgroup.h>
#include <linux/rcupdate.h>
#include <linux/atomic.h>
#include <net/rtnetlink.h>
#include <net/pkt_cls.h>
#include <net/sock.h>
#include <net/netprio_cgroup.h>
static struct cgroup_subsys_state *cgrp_create(struct cgroup *cgrp);
static void cgrp_destroy(struct cgroup *cgrp);
static int cgrp_populate(struct cgroup_subsys *ss, struct cgroup *cgrp);
struct cgroup_subsys net_prio_subsys = {
.name = "net_prio",
.create = cgrp_create,
.destroy = cgrp_destroy,
.populate = cgrp_populate,
#ifdef <API key>
.subsys_id = net_prio_subsys_id,
#endif
.module = THIS_MODULE
};
#define PRIOIDX_SZ 128
static unsigned long prioidx_map[PRIOIDX_SZ];
static DEFINE_SPINLOCK(prioidx_map_lock);
static atomic_t max_prioidx = ATOMIC_INIT(0);
static inline struct <API key> *cgrp_netprio_state(struct cgroup *cgrp)
{
return container_of(cgroup_subsys_state(cgrp, net_prio_subsys_id),
struct <API key>, css);
}
static int get_prioidx(u32 *prio)
{
unsigned long flags;
u32 prioidx;
spin_lock_irqsave(&prioidx_map_lock, flags);
prioidx = find_first_zero_bit(prioidx_map, sizeof(unsigned long) * PRIOIDX_SZ);
if (prioidx == sizeof(unsigned long) * PRIOIDX_SZ) {
<API key>(&prioidx_map_lock, flags);
return -ENOSPC;
}
set_bit(prioidx, prioidx_map);
<API key>(&prioidx_map_lock, flags);
atomic_set(&max_prioidx, prioidx);
*prio = prioidx;
return 0;
}
static void put_prioidx(u32 idx)
{
unsigned long flags;
spin_lock_irqsave(&prioidx_map_lock, flags);
clear_bit(idx, prioidx_map);
<API key>(&prioidx_map_lock, flags);
}
static void extend_netdev_table(struct net_device *dev, u32 new_len)
{
size_t new_size = sizeof(struct netprio_map) +
((sizeof(u32) * new_len));
struct netprio_map *new_priomap = kzalloc(new_size, GFP_KERNEL);
struct netprio_map *old_priomap;
int i;
old_priomap = rtnl_dereference(dev->priomap);
if (!new_priomap) {
printk(KERN_WARNING "Unable to alloc new priomap!\n");
return;
}
for (i = 0;
old_priomap && (i < old_priomap->priomap_len);
i++)
new_priomap->priomap[i] = old_priomap->priomap[i];
new_priomap->priomap_len = new_len;
rcu_assign_pointer(dev->priomap, new_priomap);
if (old_priomap)
kfree_rcu(old_priomap, rcu);
}
static void <API key>(void)
{
struct net_device *dev;
u32 max_len = atomic_read(&max_prioidx) + 1;
struct netprio_map *map;
rtnl_lock();
for_each_netdev(&init_net, dev) {
map = rtnl_dereference(dev->priomap);
if ((!map) ||
(map->priomap_len < max_len))
extend_netdev_table(dev, max_len);
}
rtnl_unlock();
}
static struct cgroup_subsys_state *cgrp_create(struct cgroup *cgrp)
{
struct <API key> *cs;
int ret;
cs = kzalloc(sizeof(*cs), GFP_KERNEL);
if (!cs)
return ERR_PTR(-ENOMEM);
if (cgrp->parent && cgrp_netprio_state(cgrp->parent)->prioidx) {
kfree(cs);
return ERR_PTR(-EINVAL);
}
ret = get_prioidx(&cs->prioidx);
if (ret != 0) {
printk(KERN_WARNING "No space in priority index array\n");
kfree(cs);
return ERR_PTR(ret);
}
return &cs->css;
}
static void cgrp_destroy(struct cgroup *cgrp)
{
struct <API key> *cs;
struct net_device *dev;
struct netprio_map *map;
cs = cgrp_netprio_state(cgrp);
rtnl_lock();
for_each_netdev(&init_net, dev) {
map = rtnl_dereference(dev->priomap);
if (map)
map->priomap[cs->prioidx] = 0;
}
rtnl_unlock();
put_prioidx(cs->prioidx);
kfree(cs);
}
static u64 read_prioidx(struct cgroup *cgrp, struct cftype *cft)
{
return (u64)cgrp_netprio_state(cgrp)->prioidx;
}
static int read_priomap(struct cgroup *cont, struct cftype *cft,
struct cgroup_map_cb *cb)
{
struct net_device *dev;
u32 prioidx = cgrp_netprio_state(cont)->prioidx;
u32 priority;
struct netprio_map *map;
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
map = rcu_dereference(dev->priomap);
priority = map ? map->priomap[prioidx] : 0;
cb->fill(cb, dev->name, priority);
}
rcu_read_unlock();
return 0;
}
static int write_priomap(struct cgroup *cgrp, struct cftype *cft,
const char *buffer)
{
char *devname = kstrdup(buffer, GFP_KERNEL);
int ret = -EINVAL;
u32 prioidx = cgrp_netprio_state(cgrp)->prioidx;
unsigned long priority;
char *priostr;
struct net_device *dev;
struct netprio_map *map;
if (!devname)
return -ENOMEM;
if (strlen(devname) < 3)
goto out_free_devname;
priostr = strstr(devname, " ");
if (!priostr)
goto out_free_devname;
*priostr = '\0';
priostr++;
if (*priostr == '\0')
goto out_free_devname;
ret = kstrtoul(priostr, 10, &priority);
if (ret < 0)
goto out_free_devname;
ret = -ENODEV;
dev = dev_get_by_name(&init_net, devname);
if (!dev)
goto out_free_devname;
<API key>();
ret = 0;
rcu_read_lock();
map = rcu_dereference(dev->priomap);
if (map)
map->priomap[prioidx] = priority;
rcu_read_unlock();
dev_put(dev);
out_free_devname:
kfree(devname);
return ret;
}
static struct cftype ss_files[] = {
{
.name = "prioidx",
.read_u64 = read_prioidx,
},
{
.name = "ifpriomap",
.read_map = read_priomap,
.write_string = write_priomap,
},
};
static int cgrp_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
{
return cgroup_add_files(cgrp, ss, ss_files, ARRAY_SIZE(ss_files));
}
static int <API key>(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct netprio_map *old;
switch (event) {
case NETDEV_UNREGISTER:
old = rtnl_dereference(dev->priomap);
RCU_INIT_POINTER(dev->priomap, NULL);
if (old)
kfree_rcu(old, rcu);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block <API key> = {
.notifier_call = <API key>
};
static int __init init_cgroup_netprio(void)
{
int ret;
ret = cgroup_load_subsys(&net_prio_subsys);
if (ret)
goto out;
#ifndef <API key>
smp_wmb();
net_prio_subsys_id = net_prio_subsys.subsys_id;
#endif
<API key>(&<API key>);
out:
return ret;
}
static void __exit exit_cgroup_netprio(void)
{
struct netprio_map *old;
struct net_device *dev;
<API key>(&<API key>);
<API key>(&net_prio_subsys);
#ifndef <API key>
net_prio_subsys_id = -1;
synchronize_rcu();
#endif
rtnl_lock();
for_each_netdev(&init_net, dev) {
old = rtnl_dereference(dev->priomap);
RCU_INIT_POINTER(dev->priomap, NULL);
if (old)
kfree_rcu(old, rcu);
}
rtnl_unlock();
}
module_init(init_cgroup_netprio);
module_exit(exit_cgroup_netprio);
MODULE_LICENSE("GPL v2");
|
#ifndef _IPA_H_
#define _IPA_H_
#include <linux/msm_ipa.h>
#include <linux/skbuff.h>
#include <linux/types.h>
#include <linux/msm-sps.h>
#include <linux/if_ether.h>
#define <API key> 200
/**
* enum ipa_nat_en_type - NAT setting type in IPA end-point
*/
enum ipa_nat_en_type {
IPA_BYPASS_NAT,
IPA_SRC_NAT,
IPA_DST_NAT,
};
/**
* enum ipa_mode_type - mode setting type in IPA end-point
* @BASIC: basic mode
* @ENABLE_FRAMING_HDLC: not currently supported
* @<API key>: not currently supported
* @DMA: all data arriving IPA will not go through IPA logic blocks, this
* allows IPA to work as DMA for specific pipes.
*/
enum ipa_mode_type {
IPA_BASIC,
<API key>,
<API key>,
IPA_DMA,
};
/**
* enum ipa_aggr_en_type - aggregation setting type in IPA
* end-point
*/
enum ipa_aggr_en_type {
IPA_BYPASS_AGGR,
IPA_ENABLE_AGGR,
IPA_ENABLE_DEAGGR,
};
/**
* enum ipa_aggr_type - type of aggregation in IPA end-point
*/
enum ipa_aggr_type {
IPA_MBIM_16 = 0,
IPA_HDLC = 1,
IPA_TLP = 2,
IPA_RNDIS = 3,
IPA_GENERIC = 4,
IPA_QCMAP = 6,
};
/**
* enum ipa_aggr_mode - global aggregation mode
*/
enum ipa_aggr_mode {
IPA_MBIM,
IPA_QCNCM,
};
/**
* enum ipa_dp_evt_type - type of event client callback is
* invoked for on data path
* @IPA_RECEIVE: data is struct sk_buff
* @IPA_WRITE_DONE: data is struct sk_buff
*/
enum ipa_dp_evt_type {
IPA_RECEIVE,
IPA_WRITE_DONE,
};
/**
* enum <API key> - type vof alue held by TOTAL_LEN_OR_PAD
* field in header configuration register.
* @IPA_HDR_PAD: field is used as padding length
* @IPA_HDR_TOTAL_LEN: field is used as total length
*/
enum <API key> {
IPA_HDR_PAD = 0,
IPA_HDR_TOTAL_LEN = 1,
};
/**
* struct ipa_ep_cfg_nat - NAT configuration in IPA end-point
* @nat_en: This defines the default NAT mode for the pipe: in case of
* filter miss - the default NAT mode defines the NATing operation
* on the packet. Valid for Input Pipes only (IPA consumer)
*/
struct ipa_ep_cfg_nat {
enum ipa_nat_en_type nat_en;
};
/**
* struct ipa_ep_cfg_hdr - header configuration in IPA end-point
*
* @hdr_len:Header length in bytes to be added/removed. Assuming
* header len is constant per endpoint. Valid for
* both Input and Output Pipes
* @<API key>: 0: Metadata_Ofst value is invalid, i.e., no
* metadata within header.
* 1: Metadata_Ofst value is valid, i.e., metadata
* within header is in offset Metadata_Ofst Valid
* for Input Pipes only (IPA Consumer) (for output
* pipes, metadata already set within the header)
* @hdr_ofst_metadata: Offset within header in which metadata resides
* Size of metadata - 4bytes
* Example - Stream ID/SSID/mux ID.
* Valid for Input Pipes only (IPA Consumer) (for output
* pipes, metadata already set within the header)
* @<API key>: Defines the constant length that should be added
* to the payload length in order for IPA to update
* correctly the length field within the header
* (valid only in case <API key>=1)
* Valid for Output Pipes (IPA Producer)
* @<API key>: 0: Hdr_Ofst_Pkt_Size value is invalid, i.e., no
* length field within the inserted header
* 1: Hdr_Ofst_Pkt_Size value is valid, i.e., a
* packet length field resides within the header
* Valid for Output Pipes (IPA Producer)
* @hdr_ofst_pkt_size: Offset within header in which packet size reside. Upon
* Header Insertion, IPA will update this field within the
* header with the packet length . Assumption is that
* header length field size is constant and is 2Bytes
* Valid for Output Pipes (IPA Producer)
* @hdr_a5_mux: Determines whether A5 Mux header should be added to the packet.
* This bit is valid only when Hdr_En=01(Header Insertion)
* SW should set this bit for IPA-to-A5 pipes.
* 0: Do not insert A5 Mux Header
* 1: Insert A5 Mux Header
* Valid for Output Pipes (IPA Producer)
* @<API key>: bool switch, remove more of the header
* based on the aggregation configuration (register
* <API key>)
* @<API key>: bool switch, metadata from
* register INIT_HDR_METADATA_n is valid.
* (relevant only for IPA Consumer pipes)
*/
struct ipa_ep_cfg_hdr {
u32 hdr_len;
u32 <API key>;
u32 hdr_ofst_metadata;
u32 <API key>;
u32 <API key>;
u32 hdr_ofst_pkt_size;
u32 hdr_a5_mux;
u32 <API key>;
u32 <API key>;
};
struct ipa_ep_cfg_hdr_ext {
u32 <API key>;
u32 <API key>;
bool <API key>;
enum <API key> <API key>;
bool <API key>;
bool hdr_little_endian;
};
/**
* struct ipa_ep_cfg_mode - mode configuration in IPA end-point
* @mode: Valid for Input Pipes only (IPA Consumer)
* @dst: This parameter specifies the output pipe to which the packets
* will be routed to.
* This parameter is valid for Mode=DMA and not valid for
* Mode=Basic
* Valid for Input Pipes only (IPA Consumer)
*/
struct ipa_ep_cfg_mode {
enum ipa_mode_type mode;
enum ipa_client_type dst;
};
/**
* struct ipa_ep_cfg_aggr - aggregation configuration in IPA end-point
*
* @aggr_en: Valid for both Input and Output Pipes
* @aggr: aggregation type (Valid for both Input and Output Pipes)
* @aggr_byte_limit: Limit of aggregated packet size in KB (<=32KB) When set
* to 0, there is no size limitation on the aggregation.
* When both, Aggr_Byte_Limit and Aggr_Time_Limit are set
* to 0, there is no aggregation, every packet is sent
* independently according to the aggregation structure
* Valid for Output Pipes only (IPA Producer )
* @aggr_time_limit: Timer to close aggregated packet (<=32ms) When set to 0,
* there is no time limitation on the aggregation. When
* both, Aggr_Byte_Limit and Aggr_Time_Limit are set to 0,
* there is no aggregation, every packet is sent
* independently according to the aggregation structure
* Valid for Output Pipes only (IPA Producer)
* @aggr_pkt_limit: Defines if EOF close aggregation or not. if set to false
* HW closes aggregation (sends EOT) only based on its
* aggregation config (byte/time limit, etc). if set to
* true EOF closes aggregation in addition to HW based
* aggregation closure. Valid for Output Pipes only (IPA
* Producer). EOF affects only Pipes configured for
* generic aggregation.
*/
struct ipa_ep_cfg_aggr {
enum ipa_aggr_en_type aggr_en;
enum ipa_aggr_type aggr;
u32 aggr_byte_limit;
u32 aggr_time_limit;
u32 aggr_pkt_limit;
};
/**
* struct ipa_ep_cfg_route - route configuration in IPA end-point
* @rt_tbl_hdl: Defines the default routing table index to be used in case there
* is no filter rule matching, valid for Input Pipes only (IPA
* Consumer). Clients should set this to 0 which will cause default
* v4 and v6 routes setup internally by IPA driver to be used for
* this end-point
*/
struct ipa_ep_cfg_route {
u32 rt_tbl_hdl;
};
/**
* struct ipa_ep_cfg_holb - head of line blocking configuration in IPA end-point
* @en: enable(1 => ok to drop pkt)/disable(0 => never drop pkt)
* @tmr_val: duration in units of 128 IPA clk clock cyles [0,511], 1 clk=1.28us
* IPAv2.5 support 32 bit HOLB timeout value, previous versions
* supports 16 bit
*/
struct ipa_ep_cfg_holb {
u16 en;
u32 tmr_val;
};
struct ipa_ep_cfg_deaggr {
u32 deaggr_hdr_len;
bool packet_offset_valid;
u32 <API key>;
u32 max_packet_len;
};
/**
* enum ipa_cs_offload - checksum offload setting
*/
enum ipa_cs_offload {
<API key>,
<API key>,
<API key>,
IPA_CS_RSVD
};
/**
* struct ipa_ep_cfg_cfg - IPA ENDP_INIT Configuration register
* @frag_offload_en: - 0 - IP packet fragment handling is disabled. IP packet
* fragments should be sent to SW. SW is responsible for
* configuring filter rules, and IP packet filter exception should be
* used to send all fragments to SW. 1 - IP packet fragment
* handling is enabled. IPA checks for fragments and uses frag
* rules table for processing fragments. Valid only for Input Pipes
* (IPA Consumer)
* @cs_offload_en: Checksum offload enable: 00: Disable checksum offload, 01:
* Enable checksum calculation offload (UL) - For output pipe
* (IPA producer) specifies that checksum trailer is to be added.
* For input pipe (IPA consumer) specifies presence of checksum
* header and IPA checksum calculation accordingly. 10: Enable
* checksum calculation offload (DL) - For output pipe (IPA
* producer) specifies that checksum trailer is to be added. For
* input pipe (IPA consumer) specifies IPA checksum calculation.
* 11: Reserved
* @<API key>: Offset in Words (4 bytes) within header in which
* checksum meta info header (4 bytes) starts (UL). Values are 0-15, which
* mean 0 - 60 byte checksum header offset. Valid for input
* pipes only (IPA consumer)
*/
struct ipa_ep_cfg_cfg {
bool frag_offload_en;
enum ipa_cs_offload cs_offload_en;
u8 <API key>;
};
/**
* struct <API key> - Endpoint initialization hdr metadata mask
* @metadata_mask: Mask specifying which metadata bits to write to
* IPA_ENDP_INIT_HDR_n.s HDR_OFST_METADATA. Only
* masked metadata bits (set to 1) will be written. Valid for Output
* Pipes only (IPA Producer)
*/
struct <API key> {
u32 metadata_mask;
};
/**
* struct ipa_ep_cfg_metadata - Meta Data configuration in IPA end-point
* @md: This defines the meta data from tx data descriptor
* @qmap_id: qmap id
*/
struct ipa_ep_cfg_metadata {
u32 qmap_id;
};
/**
* struct ipa_ep_cfg - configuration of IPA end-point
* @nat: NAT parmeters
* @hdr: Header parameters
* @hdr_ext: Extended header parameters
* @mode: Mode parameters
* @aggr: Aggregation parameters
* @deaggr: Deaggregation params
* @route: Routing parameters
* @cfg: Configuration register data
* @metadata_mask: Hdr metadata mask
* @meta: Meta Data
*/
struct ipa_ep_cfg {
struct ipa_ep_cfg_nat nat;
struct ipa_ep_cfg_hdr hdr;
struct ipa_ep_cfg_hdr_ext hdr_ext;
struct ipa_ep_cfg_mode mode;
struct ipa_ep_cfg_aggr aggr;
struct ipa_ep_cfg_deaggr deaggr;
struct ipa_ep_cfg_route route;
struct ipa_ep_cfg_cfg cfg;
struct <API key> metadata_mask;
struct ipa_ep_cfg_metadata meta;
};
/**
* struct ipa_ep_cfg_ctrl - Control configuration in IPA end-point
* @ipa_ep_suspend: 0 - ENDP is enabled, 1 - ENDP is suspended (disabled).
* Valid for PROD Endpoints
* @ipa_ep_delay: 0 - ENDP is free-running, 1 - ENDP is delayed.
* SW controls the data flow of an endpoint usind this bit.
* Valid for CONS Endpoints
*/
struct ipa_ep_cfg_ctrl {
bool ipa_ep_suspend;
bool ipa_ep_delay;
};
/**
* x should be in bytes
*/
#define <API key>(x) (x/sizeof(struct sps_iovec))
typedef void (*ipa_notify_cb)(void *priv, enum ipa_dp_evt_type evt,
unsigned long data);
/**
* struct ipa_connect_params - low-level client connect input parameters. Either
* client allocates the data and desc FIFO and specifies that in data+desc OR
* specifies sizes and pipe_mem pref and IPA does the allocation.
*
* @ipa_ep_cfg: IPA EP configuration
* @client: type of "client"
* @client_bam_hdl: client SPS handle
* @client_ep_idx: client PER EP index
* @priv: callback cookie
* @notify: callback
* priv - callback cookie evt - type of event data - data relevant
* to event. May not be valid. See event_type enum for valid
* cases.
* @desc_fifo_sz: size of desc FIFO
* @data_fifo_sz: size of data FIFO
* @pipe_mem_preferred: if true, try to alloc the FIFOs in pipe mem, fallback
* to sys mem if pipe mem alloc fails
* @desc: desc FIFO meta-data when client has allocated it
* @data: data FIFO meta-data when client has allocated it
* @skip_ep_cfg: boolean field that determines if EP should be configured
* by IPA driver
* @keep_ipa_awake: when true, IPA will not be clock gated
*/
struct ipa_connect_params {
struct ipa_ep_cfg ipa_ep_cfg;
enum ipa_client_type client;
unsigned long client_bam_hdl;
u32 client_ep_idx;
void *priv;
ipa_notify_cb notify;
u32 desc_fifo_sz;
u32 data_fifo_sz;
bool pipe_mem_preferred;
struct sps_mem_buffer desc;
struct sps_mem_buffer data;
bool skip_ep_cfg;
bool keep_ipa_awake;
};
/**
* struct ipa_sps_params - SPS related output parameters resulting from
* low/high level client connect
* @ipa_bam_hdl: IPA SPS handle
* @ipa_ep_idx: IPA PER EP index
* @desc: desc FIFO meta-data
* @data: data FIFO meta-data
*/
struct ipa_sps_params {
unsigned long ipa_bam_hdl;
u32 ipa_ep_idx;
struct sps_mem_buffer desc;
struct sps_mem_buffer data;
};
/**
* struct ipa_tx_intf - interface tx properties
* @num_props: number of tx properties
* @prop: the tx properties array
*/
struct ipa_tx_intf {
u32 num_props;
struct <API key> *prop;
};
/**
* struct ipa_rx_intf - interface rx properties
* @num_props: number of rx properties
* @prop: the rx properties array
*/
struct ipa_rx_intf {
u32 num_props;
struct <API key> *prop;
};
/**
* struct ipa_ext_intf - interface ext properties
* @excp_pipe_valid: is next field valid?
* @excp_pipe: exception packets should be routed to this pipe
* @num_props: number of ext properties
* @prop: the ext properties array
*/
struct ipa_ext_intf {
bool excp_pipe_valid;
enum ipa_client_type excp_pipe;
u32 num_props;
struct <API key> *prop;
};
/**
* struct <API key> - information needed to setup an IPA end-point
* in system-BAM mode
* @ipa_ep_cfg: IPA EP configuration
* @client: the type of client who "owns" the EP
* @desc_fifo_sz: size of desc FIFO
* @priv: callback cookie
* @notify: callback
* priv - callback cookie
* evt - type of event
* data - data relevant to event. May not be valid. See event_type
* enum for valid cases.
* @skip_ep_cfg: boolean field that determines if EP should be configured
* by IPA driver
* @keep_ipa_awake: when true, IPA will not be clock gated
*/
struct <API key> {
struct ipa_ep_cfg ipa_ep_cfg;
enum ipa_client_type client;
u32 desc_fifo_sz;
void *priv;
ipa_notify_cb notify;
bool skip_ep_cfg;
bool keep_ipa_awake;
};
/**
* struct ipa_tx_meta - meta-data for the TX packet
* @mbim_stream_id: the stream ID used in NDP signature
* @<API key>: is above field valid?
* @dma_address: dma mapped address of TX packet
* @dma_address_valid: is above field valid?
*/
struct ipa_tx_meta {
u8 mbim_stream_id;
bool <API key>;
u8 pkt_init_dst_ep;
bool <API key>;
bool <API key>;
dma_addr_t dma_address;
bool dma_address_valid;
};
/**
* typedef ipa_msg_free_fn - callback function
* @param buff - [in] the message payload to free
* @param len - [in] size of message payload
* @param type - [in] the message type
*
* Message callback registered by kernel client with IPA driver to
* free message payload after IPA driver processing is complete
*
* No return value
*/
typedef void (*ipa_msg_free_fn)(void *buff, u32 len, u32 type);
/**
* typedef ipa_msg_pull_fn - callback function
* @param buff - [in] where to copy message payload
* @param len - [in] size of buffer to copy payload into
* @param type - [in] the message type
*
* Message callback registered by kernel client with IPA driver for
* IPA driver to pull messages from the kernel client upon demand from
* user-space
*
* Returns how many bytes were copied into the buffer.
*/
typedef int (*ipa_msg_pull_fn)(void *buff, u32 len, u32 type);
/**
* enum ipa_voltage_level - IPA Voltage levels
*/
enum ipa_voltage_level {
<API key>,
IPA_VOLTAGE_SVS = <API key>,
IPA_VOLTAGE_NOMINAL,
IPA_VOLTAGE_MAX,
};
/**
* enum ipa_rm_event - IPA RM events
*
* Indicate the resource state change
*/
enum ipa_rm_event {
<API key>,
<API key>
};
typedef void (*ipa_rm_notify_cb)(void *user_data,
enum ipa_rm_event event,
unsigned long data);
/**
* struct <API key> - information needed to
* register IPA RM client with IPA RM
*
* @user_data: IPA RM client provided information
* to be passed to notify_cb callback below
* @notify_cb: callback which is called by resource
* to notify the IPA RM client about its state
* change IPA RM client is expected to perform non
* blocking operations only in notify_cb and
* release notification context as soon as
* possible.
*/
struct <API key> {
void *user_data;
ipa_rm_notify_cb notify_cb;
};
/**
* struct <API key> - information needed to initialize
* the resource
* @name: resource name
* @floor_voltage: floor voltage needed for client to operate in maximum
* bandwidth.
* @reg_params: register parameters, contains are ignored
* for consumer resource NULL should be provided
* for consumer resource
* @request_resource: function which should be called to request resource,
* NULL should be provided for producer resource
* @release_resource: function which should be called to release resource,
* NULL should be provided for producer resource
*
* IPA RM client is expected to perform non blocking operations only
* in request_resource and release_resource functions and
* release notification context as soon as possible.
*/
struct <API key> {
enum <API key> name;
enum ipa_voltage_level floor_voltage;
struct <API key> reg_params;
int (*request_resource)(void);
int (*release_resource)(void);
};
/**
* struct ipa_rm_perf_profile - information regarding IPA RM client performance
* profile
*
* @max_bandwidth_mbps: maximum bandwidth need of the client in Mbps
*/
struct ipa_rm_perf_profile {
u32 <API key>;
};
#define <API key> "dmux_hdr_v4_"
#define <API key> "dmux_hdr_v6_"
/**
* enum teth_tethering_mode - Tethering mode (Rmnet / MBIM)
*/
enum teth_tethering_mode {
<API key>,
<API key>,
<API key>,
};
/**
* <API key> - Parameters used for in/out USB API
* @usb_notify_cb: Callback function which should be used by the caller.
* Output parameter.
* @private_data: Data for the callback function. Should be used by the
* caller. Output parameter.
* @skip_ep_cfg: boolean field that determines if Apps-processor
* should or should not confiugre this end-point.
*/
struct <API key> {
ipa_notify_cb usb_notify_cb;
void *private_data;
enum ipa_client_type client;
bool skip_ep_cfg;
};
/**
* struct <API key> - Parameters used in teth_bridge_connect()
* @ipa_usb_pipe_hdl: IPA to USB pipe handle, returned from ipa_connect()
* @usb_ipa_pipe_hdl: USB to IPA pipe handle, returned from ipa_connect()
* @tethering_mode: Rmnet or MBIM
* @ipa_client_type: IPA "client" name (IPA_CLIENT_USB#_PROD)
*/
struct <API key> {
u32 ipa_usb_pipe_hdl;
u32 usb_ipa_pipe_hdl;
enum teth_tethering_mode tethering_mode;
enum ipa_client_type client_type;
};
/**
* struct ipa_tx_data_desc - information needed
* to send data packet to HW link: link to data descriptors
* priv: client specific private data
* @pyld_buffer: pointer to the data buffer that holds frame
* @pyld_len: length of the data packet
*/
struct ipa_tx_data_desc {
struct list_head link;
void *priv;
void *pyld_buffer;
u16 pyld_len;
};
/**
* struct ipa_rx_data - information needed
* to send to wlan driver on receiving data from ipa hw
* @skb: skb
* @dma_addr: DMA address of this Rx packet
*/
struct ipa_rx_data {
struct sk_buff *skb;
dma_addr_t dma_addr;
};
enum ipa_irq_type {
<API key> = 0,
IPA_EOT_COAL_IRQ,
IPA_UC_IRQ_0,
IPA_UC_IRQ_1,
IPA_UC_IRQ_2,
IPA_UC_IRQ_3,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
IPA_RX_ERR_IRQ,
IPA_DEAGGR_ERR_IRQ,
IPA_TX_ERR_IRQ,
IPA_STEP_MODE_IRQ,
IPA_PROC_ERR_IRQ,
IPA_TX_SUSPEND_IRQ = 16,
<API key> = 17,
IPA_IRQ_MAX
};
/**
* struct <API key> - interrupt data for IPA_TX_SUSPEND_IRQ
* @endpoints: bitmask of endpoints which case IPA_TX_SUSPEND_IRQ interrupt
* @dma_addr: DMA address of this Rx packet
*/
struct <API key> {
u32 endpoints;
};
/**
* typedef ipa_irq_handler_t - irq handler/callback type
* @param ipa_irq_type - [in] interrupt type
* @param private_data - [in, out] the client private data
* @param interrupt_data - [out] interrupt information data
*
* callback registered by <API key> function to
* handle a specific interrupt type
*
* No return value
*/
typedef void (*ipa_irq_handler_t)(enum ipa_irq_type interrupt,
void *private_data,
void *interrupt_data);
/**
* struct IpaHwBamStats_t - Strucuture holding the BAM statistics
*
* @bamFifoFull : Number of times Bam Fifo got full - For In Ch: Good,
* For Out Ch: Bad
* @bamFifoEmpty : Number of times Bam Fifo got empty - For In Ch: Bad,
* For Out Ch: Good
* @bamFifoUsageHigh : Number of times Bam fifo usage went above 75% -
* For In Ch: Good, For Out Ch: Bad
* @bamFifoUsageLow : Number of times Bam fifo usage went below 25% -
* For In Ch: Bad, For Out Ch: Good
*/
struct IpaHwBamStats_t {
u32 bamFifoFull;
u32 bamFifoEmpty;
u32 bamFifoUsageHigh;
u32 bamFifoUsageLow;
} __packed;
/**
* struct IpaHwRingStats_t - Strucuture holding the Ring statistics
*
* @ringFull : Number of times Transfer Ring got full - For In Ch: Good,
* For Out Ch: Bad
* @ringEmpty : Number of times Transfer Ring got empty - For In Ch: Bad,
* For Out Ch: Good
* @ringUsageHigh : Number of times Transfer Ring usage went above 75% -
* For In Ch: Good, For Out Ch: Bad
* @ringUsageLow : Number of times Transfer Ring usage went below 25% -
* For In Ch: Bad, For Out Ch: Good
*/
struct IpaHwRingStats_t {
u32 ringFull;
u32 ringEmpty;
u32 ringUsageHigh;
u32 ringUsageLow;
} __packed;
/**
* struct <API key> - Structure holding the WDI Rx channel
* structures
*
* @<API key> : Number of outstanding packets in Rx Ring
* @num_pkts_processed : Number of packets processed - cumulative
* @rx_ring_rp_value : Read pointer last advertized to the WLAN FW
* @rx_ind_ring_stats : Ring info
* @bam_stats : BAM info
* @num_bam_int_handled : Number of Bam Interrupts handled by FW
* @num_db : Number of times the doorbell was rung
* @num_unexpected_db : Number of unexpected doorbells
*/
struct <API key> {
u32 <API key>;
u32 num_pkts_processed;
u32 rx_ring_rp_value;
struct IpaHwRingStats_t rx_ind_ring_stats;
struct IpaHwBamStats_t bam_stats;
u32 num_bam_int_handled;
u32 num_db;
u32 num_unexpected_db;
u32 reserved1;
u32 reserved2;
} __packed;
/**
* struct <API key> - Structure holding the WDI Tx channel
* structures
*
* @num_pkts_processed : Number of packets processed - cumulative
* @<API key> : latest value of doorbell written to copy engine
* @num_db_fired : Number of DB from uC FW to Copy engine
* @tx_comp_ring_stats : ring info
* @bam_stats : BAM info
* @num_db : Number of times the doorbell was rung
* @num_unexpected_db : Number of unexpected doorbells
* @num_bam_int_handled : Number of Bam Interrupts handled by FW
* @<API key> : Number of Bam interrupts while not in
* Running state
* @num_qmb_int_handled : Number of QMB interrupts handled
*/
struct <API key> {
u32 num_pkts_processed;
u32 <API key>;
u32 num_db_fired;
struct IpaHwRingStats_t tx_comp_ring_stats;
struct IpaHwBamStats_t bam_stats;
u32 num_db;
u32 num_unexpected_db;
u32 num_bam_int_handled;
u32 <API key>;
u32 num_qmb_int_handled;
} __packed;
/**
* struct <API key> - Structure holding the WDI channel structures
*
* @rx_ch_stats : RX stats
* @tx_ch_stats : TX stats
*/
struct <API key> {
struct <API key> rx_ch_stats;
struct <API key> tx_ch_stats;
} __packed;
/**
* struct ipa_wdi_ul_params - WDI_RX configuration
* @rdy_ring_base_pa: physical address of the base of the Rx ring (containing
* Rx buffers)
* @rdy_ring_size: size of the Rx ring in bytes
* @rdy_ring_rp_pa: physical address of the location through which IPA uc is
* expected to communicate about the Read pointer into the Rx Ring
*/
struct ipa_wdi_ul_params {
phys_addr_t rdy_ring_base_pa;
u32 rdy_ring_size;
phys_addr_t rdy_ring_rp_pa;
};
/**
* struct ipa_wdi_dl_params - WDI_TX configuration
* @comp_ring_base_pa: physical address of the base of the Tx completion ring
* @comp_ring_size: size of the Tx completion ring in bytes
* @ce_ring_base_pa: physical address of the base of the Copy Engine Source
* Ring
* @ce_door_bell_pa: physical address of the doorbell that the IPA uC has to
* write into to trigger the copy engine
* @ce_ring_size: Copy Engine Ring size in bytes
* @num_tx_buffers: Number of pkt buffers allocated
*/
struct ipa_wdi_dl_params {
phys_addr_t comp_ring_base_pa;
u32 comp_ring_size;
phys_addr_t ce_ring_base_pa;
phys_addr_t ce_door_bell_pa;
u32 ce_ring_size;
u32 num_tx_buffers;
};
/**
* struct ipa_wdi_in_params - information provided by WDI client
* @sys: IPA EP configuration info
* @ul: WDI_RX configuration info
* @dl: WDI_TX configuration info
*/
struct ipa_wdi_in_params {
struct <API key> sys;
union {
struct ipa_wdi_ul_params ul;
struct ipa_wdi_dl_params dl;
} u;
};
/**
* struct ipa_wdi_out_params - information provided to WDI client
* @uc_door_bell_pa: physical address of IPA uc doorbell
* @clnt_hdl: opaque handle assigned to client
*/
struct ipa_wdi_out_params {
phys_addr_t uc_door_bell_pa;
u32 clnt_hdl;
};
/**
* struct ipa_wdi_db_params - information provided to retrieve
* physical address of uC doorbell
* @client: type of "client" (IPA_CLIENT_WLAN#_PROD/CONS)
* @uc_door_bell_pa: physical address of IPA uc doorbell
*/
struct ipa_wdi_db_params {
enum ipa_client_type client;
phys_addr_t uc_door_bell_pa;
};
/**
* struct <API key> - uC ready CB parameters
* @is_uC_ready: uC loaded or not
* @priv : callback cookie
* @notify: callback
*/
typedef void (*ipa_uc_ready_cb)(void *priv);
struct <API key> {
bool is_uC_ready;
void *priv;
ipa_uc_ready_cb notify;
};
/**
* struct odu_bridge_params - parameters for odu bridge initialization API
*
* @netdev_name: network interface name
* @priv: private data that will be supplied to client's callback
* @tx_dp_notify: callback for handling SKB. the following event are supported:
* IPA_WRITE_DONE: will be called after client called to odu_bridge_tx_dp()
* Client is expected to free the skb.
* IPA_RECEIVE: will be called for delivering skb to APPS.
* Client is expected to deliver the skb to network stack.
* @send_dl_skb: callback for sending skb on downlink direction to adapter.
* Client is expected to free the skb.
* @device_ethaddr: device Ethernet address in network order.
* @ipa_desc_size: IPA Sys Pipe Desc Size
*/
struct odu_bridge_params {
const char *netdev_name;
void *priv;
ipa_notify_cb tx_dp_notify;
int (*send_dl_skb)(void *priv, struct sk_buff *skb);
u8 device_ethaddr[ETH_ALEN];
u32 ipa_desc_size;
};
/**
* enum ipa_mhi_event_type - event type for mhi callback
*
* @IPA_MHI_EVENT_READY: IPA MHI is ready and IPA uC is loaded. After getting
* this event MHI client is expected to call to ipa_mhi_start() API
* @<API key>: downlink data available on MHI channel
*/
enum ipa_mhi_event_type {
IPA_MHI_EVENT_READY,
<API key>,
IPA_MHI_EVENT_MAX,
};
typedef void (*mhi_client_cb)(void *priv, enum ipa_mhi_event_type event,
unsigned long data);
/**
* struct ipa_mhi_msi_info - parameters for MSI (Message Signaled Interrupts)
* @addr_low: MSI lower base physical address
* @addr_hi: MSI higher base physical address
* @data: Data Pattern to use when generating the MSI
* @mask: Mask indicating number of messages assigned by the host to device
*
* msi value is written according to this formula:
* ((data & ~mask) | (mmio.msiVec & mask))
*/
struct ipa_mhi_msi_info {
u32 addr_low;
u32 addr_hi;
u32 data;
u32 mask;
};
/**
* struct ipa_mhi_init_params - parameters for IPA MHI initialization API
*
* @msi: MSI (Message Signaled Interrupts) parameters
* @mmio_addr: MHI MMIO physical address
* @first_ch_idx: First channel ID for hardware accelerated channels.
* @first_er_idx: First event ring ID for hardware accelerated channels.
* @notify: client callback
* @priv: client private data to be provided in client callback
*/
struct ipa_mhi_init_params {
struct ipa_mhi_msi_info msi;
u32 mmio_addr;
u32 first_ch_idx;
u32 first_er_idx;
mhi_client_cb notify;
void *priv;
};
/**
* struct <API key> - parameters for IPA MHI start API
*
* @host_ctrl_addr: Base address of MHI control data structures
* @host_data_addr: Base address of MHI data buffers
*/
struct <API key> {
u32 host_ctrl_addr;
u32 host_data_addr;
};
/**
* struct <API key> - parameters for IPA MHI channel connect API
*
* @sys: IPA EP configuration info
* @channel_id: MHI channel id
*/
struct <API key> {
struct <API key> sys;
u8 channel_id;
};
#ifdef CONFIG_IPA
/*
* Connect / Disconnect
*/
int ipa_connect(const struct ipa_connect_params *in, struct ipa_sps_params *sps,
u32 *clnt_hdl);
int ipa_disconnect(u32 clnt_hdl);
/*
* Resume / Suspend
*/
int ipa_reset_endpoint(u32 clnt_hdl);
/*
* Configuration
*/
int ipa_cfg_ep(u32 clnt_hdl, const struct ipa_ep_cfg *ipa_ep_cfg);
int ipa_cfg_ep_nat(u32 clnt_hdl, const struct ipa_ep_cfg_nat *ipa_ep_cfg);
int ipa_cfg_ep_hdr(u32 clnt_hdl, const struct ipa_ep_cfg_hdr *ipa_ep_cfg);
int ipa_cfg_ep_hdr_ext(u32 clnt_hdl,
const struct ipa_ep_cfg_hdr_ext *ipa_ep_cfg);
int ipa_cfg_ep_mode(u32 clnt_hdl, const struct ipa_ep_cfg_mode *ipa_ep_cfg);
int ipa_cfg_ep_aggr(u32 clnt_hdl, const struct ipa_ep_cfg_aggr *ipa_ep_cfg);
int ipa_cfg_ep_deaggr(u32 clnt_hdl,
const struct ipa_ep_cfg_deaggr *ipa_ep_cfg);
int ipa_cfg_ep_route(u32 clnt_hdl, const struct ipa_ep_cfg_route *ipa_ep_cfg);
int ipa_cfg_ep_holb(u32 clnt_hdl, const struct ipa_ep_cfg_holb *ipa_ep_cfg);
int ipa_cfg_ep_cfg(u32 clnt_hdl, const struct ipa_ep_cfg_cfg *ipa_ep_cfg);
int <API key>(u32 clnt_hdl, const struct <API key>
*ipa_ep_cfg);
int <API key>(enum ipa_client_type client,
const struct ipa_ep_cfg_holb *ipa_ep_cfg);
int ipa_cfg_ep_ctrl(u32 clnt_hdl, const struct ipa_ep_cfg_ctrl *ep_ctrl);
/*
* Header removal / addition
*/
int ipa_add_hdr(struct ipa_ioc_add_hdr *hdrs);
int ipa_del_hdr(struct ipa_ioc_del_hdr *hdls);
int ipa_commit_hdr(void);
int ipa_reset_hdr(void);
int ipa_get_hdr(struct ipa_ioc_get_hdr *lookup);
int ipa_put_hdr(u32 hdr_hdl);
int ipa_copy_hdr(struct ipa_ioc_copy_hdr *copy);
/*
* Header Processing Context
*/
int <API key>(struct <API key> *proc_ctxs);
int <API key>(struct <API key> *hdls);
/*
* Routing
*/
int ipa_add_rt_rule(struct ipa_ioc_add_rt_rule *rules);
int ipa_del_rt_rule(struct ipa_ioc_del_rt_rule *hdls);
int ipa_commit_rt(enum ipa_ip_type ip);
int ipa_reset_rt(enum ipa_ip_type ip);
int ipa_get_rt_tbl(struct ipa_ioc_get_rt_tbl *lookup);
int ipa_put_rt_tbl(u32 rt_tbl_hdl);
int ipa_query_rt_index(struct <API key> *in);
int ipa_mdfy_rt_rule(struct <API key> *rules);
/*
* Filtering
*/
int ipa_add_flt_rule(struct <API key> *rules);
int ipa_del_flt_rule(struct <API key> *hdls);
int ipa_mdfy_flt_rule(struct <API key> *rules);
int ipa_commit_flt(enum ipa_ip_type ip);
int ipa_reset_flt(enum ipa_ip_type ip);
/*
* NAT
*/
int allocate_nat_device(struct <API key> *mem);
int ipa_nat_init_cmd(struct ipa_ioc_v4_nat_init *init);
int ipa_nat_dma_cmd(struct ipa_ioc_nat_dma_cmd *dma);
int ipa_nat_del_cmd(struct ipa_ioc_v4_nat_del *del);
/*
* Messaging
*/
int ipa_send_msg(struct ipa_msg_meta *meta, void *buff,
ipa_msg_free_fn callback);
int <API key>(struct ipa_msg_meta *meta, ipa_msg_pull_fn callback);
int <API key>(struct ipa_msg_meta *meta);
/*
* Interface
*/
int ipa_register_intf(const char *name, const struct ipa_tx_intf *tx,
const struct ipa_rx_intf *rx);
int <API key>(const char *name, const struct ipa_tx_intf *tx,
const struct ipa_rx_intf *rx,
const struct ipa_ext_intf *ext);
int ipa_deregister_intf(const char *name);
/*
* Aggregation
*/
int ipa_set_aggr_mode(enum ipa_aggr_mode mode);
int <API key>(char sig[3]);
int <API key>(bool enable);
/*
* Data path
*/
int ipa_tx_dp(enum ipa_client_type dst, struct sk_buff *skb,
struct ipa_tx_meta *metadata);
/*
* To transfer multiple data packets
* While passing the data descriptor list, the anchor node
* should be of type struct ipa_tx_data_desc not list_head
*/
int ipa_tx_dp_mul(enum ipa_client_type dst,
struct ipa_tx_data_desc *data_desc);
void ipa_free_skb(struct ipa_rx_data *);
/*
* System pipes
*/
int ipa_setup_sys_pipe(struct <API key> *sys_in, u32 *clnt_hdl);
int <API key>(u32 clnt_hdl);
int <API key>(struct ipa_wdi_in_params *in,
struct ipa_wdi_out_params *out);
int <API key>(u32 clnt_hdl);
int ipa_enable_wdi_pipe(u32 clnt_hdl);
int <API key>(u32 clnt_hdl);
int ipa_resume_wdi_pipe(u32 clnt_hdl);
int <API key>(u32 clnt_hdl);
int ipa_get_wdi_stats(struct <API key> *stats);
u16 <API key>(void);
/*
* To retrieve doorbell physical address of
* wlan pipes
*/
int ipa_uc_wdi_get_dbpa(struct ipa_wdi_db_params *out);
/*
* To register uC ready callback if uC not ready
* and also check uC readiness
* if uC not ready only, register callback
*/
int ipa_uc_reg_rdyCB(struct <API key> *param);
/*
* To de-register uC ready callback
*/
int ipa_uc_dereg_rdyCB(void);
/*
* Resource manager
*/
int <API key>(struct <API key> *create_params);
int <API key>(enum <API key> resource_name);
int ipa_rm_register(enum <API key> resource_name,
struct <API key> *reg_params);
int ipa_rm_deregister(enum <API key> resource_name,
struct <API key> *reg_params);
int <API key>(enum <API key> resource_name,
struct ipa_rm_perf_profile *profile);
int <API key>(enum <API key> resource_name,
enum <API key> depends_on_name);
int <API key>(enum <API key> resource_name,
enum <API key> depends_on_name);
int <API key>(enum <API key> resource_name);
int <API key>(enum <API key> resource_name);
int <API key>(enum ipa_rm_event event,
enum <API key> resource_name);
int <API key>(enum <API key> resource_name,
unsigned long msecs);
int <API key>(enum <API key> resource_name);
int <API key>(
enum <API key> resource_name);
int <API key>(
enum <API key> resource_name);
/*
* Tethering bridge (Rmnet / MBIM)
*/
int teth_bridge_init(struct <API key> *params);
int <API key>(enum ipa_client_type client);
int teth_bridge_connect(struct <API key> *connect_params);
/*
* Tethering client info
*/
void ipa_set_client(int index, enum ipacm_client_enum client, bool uplink);
enum ipacm_client_enum ipa_get_client(int pipe_idx);
bool <API key>(int pipe_idx);
/*
* ODU bridge
*/
int odu_bridge_init(struct odu_bridge_params *params);
int odu_bridge_connect(void);
int <API key>(void);
int odu_bridge_tx_dp(struct sk_buff *skb, struct ipa_tx_meta *metadata);
int odu_bridge_cleanup(void);
/*
* IPADMA
*/
int ipa_dma_init(void);
int ipa_dma_enable(void);
int ipa_dma_disable(void);
int ipa_dma_sync_memcpy(phys_addr_t dest, phys_addr_t src, int len);
int <API key>(phys_addr_t dest, phys_addr_t src, int len,
void (*user_cb)(void *user1), void *user_param);
int ipa_dma_uc_memcpy(phys_addr_t dest, phys_addr_t src, int len);
void ipa_dma_destroy(void);
/*
* MHI
*/
int ipa_mhi_init(struct ipa_mhi_init_params *params);
int ipa_mhi_start(struct <API key> *params);
int <API key>(struct <API key> *in, u32 *clnt_hdl);
int <API key>(u32 clnt_hdl);
int ipa_mhi_suspend(bool force);
int ipa_mhi_resume(void);
int ipa_mhi_destroy(void);
/*
* mux id
*/
int ipa_write_qmap_id(struct <API key> *param_in);
/*
* interrupts
*/
int <API key>(enum ipa_irq_type interrupt,
ipa_irq_handler_t handler,
bool deferred_flag,
void *private_data);
int <API key>(enum ipa_irq_type interrupt);
/*
* Miscellaneous
*/
void ipa_bam_reg_dump(void);
bool <API key>(void);
int ipa_get_ep_mapping(enum ipa_client_type client);
bool ipa_is_ready(void);
void ipa_proxy_clk_vote(void);
void <API key>(void);
enum ipa_hw_type ipa_get_hw_type(void);
bool <API key>(u32 clnt_hdl);
enum ipa_client_type <API key>(int pipe_idx);
enum <API key> <API key>(int pipe_idx);
#else /* CONFIG_IPA */
/*
* Connect / Disconnect
*/
static inline int ipa_connect(const struct ipa_connect_params *in,
struct ipa_sps_params *sps, u32 *clnt_hdl)
{
return -EPERM;
}
static inline int ipa_disconnect(u32 clnt_hdl)
{
return -EPERM;
}
/*
* Resume / Suspend
*/
static inline int ipa_reset_endpoint(u32 clnt_hdl)
{
return -EPERM;
}
/*
* Configuration
*/
static inline int ipa_cfg_ep(u32 clnt_hdl,
const struct ipa_ep_cfg *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_nat(u32 clnt_hdl,
const struct ipa_ep_cfg_nat *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_hdr(u32 clnt_hdl,
const struct ipa_ep_cfg_hdr *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_hdr_ext(u32 clnt_hdl,
const struct ipa_ep_cfg_hdr_ext *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_mode(u32 clnt_hdl,
const struct ipa_ep_cfg_mode *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_aggr(u32 clnt_hdl,
const struct ipa_ep_cfg_aggr *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_deaggr(u32 clnt_hdl,
const struct ipa_ep_cfg_deaggr *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_route(u32 clnt_hdl,
const struct ipa_ep_cfg_route *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_holb(u32 clnt_hdl,
const struct ipa_ep_cfg_holb *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_cfg(u32 clnt_hdl,
const struct ipa_ep_cfg_cfg *ipa_ep_cfg)
{
return -EPERM;
}
static inline int <API key>(u32 clnt_hdl,
const struct <API key> *ipa_ep_cfg)
{
return -EPERM;
}
static inline int ipa_cfg_ep_ctrl(u32 clnt_hdl,
const struct ipa_ep_cfg_ctrl *ep_ctrl)
{
return -EPERM;
}
/*
* Header removal / addition
*/
static inline int ipa_add_hdr(struct ipa_ioc_add_hdr *hdrs)
{
return -EPERM;
}
static inline int ipa_del_hdr(struct ipa_ioc_del_hdr *hdls)
{
return -EPERM;
}
static inline int ipa_commit_hdr(void)
{
return -EPERM;
}
static inline int ipa_reset_hdr(void)
{
return -EPERM;
}
static inline int ipa_get_hdr(struct ipa_ioc_get_hdr *lookup)
{
return -EPERM;
}
static inline int ipa_put_hdr(u32 hdr_hdl)
{
return -EPERM;
}
static inline int ipa_copy_hdr(struct ipa_ioc_copy_hdr *copy)
{
return -EPERM;
}
/*
* Header Processing Context
*/
static inline int <API key>(
struct <API key> *proc_ctxs)
{
return -EPERM;
}
static inline int <API key>(struct <API key> *hdls)
{
return -EPERM;
}
/*
* Routing
*/
static inline int ipa_add_rt_rule(struct ipa_ioc_add_rt_rule *rules)
{
return -EPERM;
}
static inline int ipa_del_rt_rule(struct ipa_ioc_del_rt_rule *hdls)
{
return -EPERM;
}
static inline int ipa_commit_rt(enum ipa_ip_type ip)
{
return -EPERM;
}
static inline int ipa_reset_rt(enum ipa_ip_type ip)
{
return -EPERM;
}
static inline int ipa_get_rt_tbl(struct ipa_ioc_get_rt_tbl *lookup)
{
return -EPERM;
}
static inline int ipa_put_rt_tbl(u32 rt_tbl_hdl)
{
return -EPERM;
}
static inline int ipa_query_rt_index(struct <API key> *in)
{
return -EPERM;
}
static inline int ipa_mdfy_rt_rule(struct <API key> *rules)
{
return -EPERM;
}
/*
* Filtering
*/
static inline int ipa_add_flt_rule(struct <API key> *rules)
{
return -EPERM;
}
static inline int ipa_del_flt_rule(struct <API key> *hdls)
{
return -EPERM;
}
static inline int ipa_mdfy_flt_rule(struct <API key> *rules)
{
return -EPERM;
}
static inline int ipa_commit_flt(enum ipa_ip_type ip)
{
return -EPERM;
}
static inline int ipa_reset_flt(enum ipa_ip_type ip)
{
return -EPERM;
}
/*
* NAT
*/
static inline int allocate_nat_device(struct <API key> *mem)
{
return -EPERM;
}
static inline int ipa_nat_init_cmd(struct ipa_ioc_v4_nat_init *init)
{
return -EPERM;
}
static inline int ipa_nat_dma_cmd(struct ipa_ioc_nat_dma_cmd *dma)
{
return -EPERM;
}
static inline int ipa_nat_del_cmd(struct ipa_ioc_v4_nat_del *del)
{
return -EPERM;
}
/*
* Messaging
*/
static inline int ipa_send_msg(struct ipa_msg_meta *meta, void *buff,
ipa_msg_free_fn callback)
{
return -EPERM;
}
static inline int <API key>(struct ipa_msg_meta *meta,
ipa_msg_pull_fn callback)
{
return -EPERM;
}
static inline int <API key>(struct ipa_msg_meta *meta)
{
return -EPERM;
}
/*
* Interface
*/
static inline int ipa_register_intf(const char *name,
const struct ipa_tx_intf *tx,
const struct ipa_rx_intf *rx)
{
return -EPERM;
}
static inline int <API key>(const char *name,
const struct ipa_tx_intf *tx,
const struct ipa_rx_intf *rx,
const struct ipa_ext_intf *ext)
{
return -EPERM;
}
static inline int ipa_deregister_intf(const char *name)
{
return -EPERM;
}
/*
* Aggregation
*/
static inline int ipa_set_aggr_mode(enum ipa_aggr_mode mode)
{
return -EPERM;
}
static inline int <API key>(char sig[3])
{
return -EPERM;
}
static inline int <API key>(bool enable)
{
return -EPERM;
}
/*
* Data path
*/
static inline int ipa_tx_dp(enum ipa_client_type dst, struct sk_buff *skb,
struct ipa_tx_meta *metadata)
{
return -EPERM;
}
/*
* To transfer multiple data packets
*/
static inline int ipa_tx_dp_mul(
enum ipa_client_type dst,
struct ipa_tx_data_desc *data_desc)
{
return -EPERM;
}
static inline void ipa_free_skb(struct ipa_rx_data *rx_in)
{
return;
}
/*
* System pipes
*/
static inline u16 <API key>(void)
{
return -EPERM;
}
static inline int ipa_setup_sys_pipe(struct <API key> *sys_in,
u32 *clnt_hdl)
{
return -EPERM;
}
static inline int <API key>(u32 clnt_hdl)
{
return -EPERM;
}
static inline int <API key>(struct ipa_wdi_in_params *in,
struct ipa_wdi_out_params *out)
{
return -EPERM;
}
static inline int <API key>(u32 clnt_hdl)
{
return -EPERM;
}
static inline int ipa_enable_wdi_pipe(u32 clnt_hdl)
{
return -EPERM;
}
static inline int <API key>(u32 clnt_hdl)
{
return -EPERM;
}
static inline int ipa_resume_wdi_pipe(u32 clnt_hdl)
{
return -EPERM;
}
static inline int <API key>(u32 clnt_hdl)
{
return -EPERM;
}
static inline int ipa_uc_wdi_get_dbpa(
struct ipa_wdi_db_params *out)
{
return -EPERM;
}
static inline int ipa_uc_reg_rdyCB(
struct <API key> *param)
{
return -EPERM;
}
static inline int ipa_uc_dereg_rdyCB(void)
{
return -EPERM;
}
/*
* Resource manager
*/
static inline int <API key>(
struct <API key> *create_params)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name)
{
return -EPERM;
}
static inline int ipa_rm_register(enum <API key> resource_name,
struct <API key> *reg_params)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name,
struct ipa_rm_perf_profile *profile)
{
return -EPERM;
}
static inline int ipa_rm_deregister(enum <API key> resource_name,
struct <API key> *reg_params)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name,
enum <API key> depends_on_name)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name,
enum <API key> depends_on_name)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name)
{
return -EPERM;
}
static inline int <API key>(enum ipa_rm_event event,
enum <API key> resource_name)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name,
unsigned long msecs)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name)
{
return -EPERM;
}
static inline int <API key>(
enum <API key> resource_name)
{
return -EPERM;
}
/*
* Tethering bridge (Rmnet / MBIM)
*/
static inline int teth_bridge_init(struct <API key> *params)
{
return -EPERM;
}
static inline int <API key>(enum ipa_client_type client)
{
return -EPERM;
}
static inline int teth_bridge_connect(struct <API key>
*connect_params)
{
return -EPERM;
}
/*
* Tethering client info
*/
static inline void ipa_set_client(int index, enum ipacm_client_enum client,
bool uplink)
{
}
static inline enum ipacm_client_enum ipa_get_client(int pipe_idx)
{
return -EPERM;
}
static inline bool <API key>(int pipe_idx)
{
return -EPERM;
}
/*
* ODU bridge
*/
static inline int odu_bridge_init(struct odu_bridge_params *params)
{
return -EPERM;
}
static inline int <API key>(void)
{
return -EPERM;
}
static inline int odu_bridge_connect(void)
{
return -EPERM;
}
static inline int odu_bridge_tx_dp(struct sk_buff *skb,
struct ipa_tx_meta *metadata)
{
return -EPERM;
}
static inline int odu_bridge_cleanup(void)
{
return -EPERM;
}
/*
* IPADMA
*/
static inline int ipa_dma_init(void)
{
return -EPERM;
}
static inline int ipa_dma_enable(void)
{
return -EPERM;
}
static inline int ipa_dma_disable(void)
{
return -EPERM;
}
static inline int ipa_dma_sync_memcpy(phys_addr_t dest, phys_addr_t src
, int len)
{
return -EPERM;
}
static inline int <API key>(phys_addr_t dest, phys_addr_t src
, int len, void (*user_cb)(void *user1),
void *user_param)
{
return -EPERM;
}
static inline int ipa_dma_uc_memcpy(phys_addr_t dest, phys_addr_t src, int len)
{
return -EPERM;
}
static inline void ipa_dma_destroy(void)
{
return;
}
/*
* MHI
*/
static inline int ipa_mhi_init(struct ipa_mhi_init_params *params)
{
return -EPERM;
}
static inline int ipa_mhi_start(struct <API key> *params)
{
return -EPERM;
}
static inline int <API key>(struct <API key> *in,
u32 *clnt_hdl)
{
return -EPERM;
}
static inline int <API key>(u32 clnt_hdl)
{
return -EPERM;
}
static inline int ipa_mhi_suspend(bool force)
{
return -EPERM;
}
static inline int ipa_mhi_resume(void)
{
return -EPERM;
}
static inline int ipa_mhi_destroy(void)
{
return -EPERM;
}
/*
* mux id
*/
static inline int ipa_write_qmap_id(struct <API key> *param_in)
{
return -EPERM;
}
/*
* interrupts
*/
static inline int <API key>(enum ipa_irq_type interrupt,
ipa_irq_handler_t handler,
bool deferred_flag,
void *private_data)
{
return -EPERM;
}
static inline int <API key>(enum ipa_irq_type interrupt)
{
return -EPERM;
}
/*
* Miscellaneous
*/
static inline void ipa_bam_reg_dump(void)
{
return;
}
static inline bool <API key>(void)
{
return false;
}
static inline int ipa_get_wdi_stats(struct <API key> *stats)
{
return -EPERM;
}
static inline int ipa_get_ep_mapping(enum ipa_client_type client)
{
return -EPERM;
}
static inline bool ipa_is_ready(void)
{
return false;
}
static inline void ipa_proxy_clk_vote(void)
{
}
static inline void <API key>(void)
{
}
static inline enum ipa_hw_type ipa_get_hw_type(void)
{
return IPA_HW_None;
}
static inline bool <API key>(u32 clnt_hdl)
{
return -EINVAL;
}
static inline enum ipa_client_type <API key>(int pipe_idx)
{
return -EINVAL;
}
static inline enum <API key> <API key>(
int pipe_idx)
{
return -EFAULT;
}
#endif /* CONFIG_IPA*/
#endif /* _IPA_H_ */
|
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
require_once(__DIR__.'/../../config.php');
require_once("{$CFG->libdir}/completionlib.php");
/**
* Configuration
*/
define('<API key>', 25);
define('<API key>', true);
// Get course
$courseid = required_param('course', PARAM_INT);
$format = optional_param('format','',PARAM_ALPHA);
$sort = optional_param('sort','',PARAM_ALPHA);
$edituser = optional_param('edituser', 0, PARAM_INT);
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
$context = context_course::instance($course->id);
$url = new moodle_url('/report/completion/index.php', array('course'=>$course->id));
$PAGE->set_url($url);
$PAGE->set_pagelayout('report');
$firstnamesort = ($sort == 'firstname');
$excel = ($format == 'excelcsv');
$csv = ($format == 'csv' || $excel);
// Load CSV library
if ($csv) {
require_once("{$CFG->libdir}/csvlib.class.php");
}
// Paging
$start = optional_param('start', 0, PARAM_INT);
$sifirst = optional_param('sifirst', 'all', PARAM_NOTAGS);
$silast = optional_param('silast', 'all', PARAM_NOTAGS);
// Whether to show extra user identity information
$extrafields = <API key>($context);
$leftcols = 1 + count($extrafields);
require_login($course);
require_capability('report/completion:view', $context);
// Get group mode
$group = <API key>($course, true); // Supposed to verify group
if ($group === 0 && $course->groupmode == SEPARATEGROUPS) {
require_capability('moodle/site:accessallgroups',$context);
}
/**
* Load data
*/
// Retrieve course_module data for all modules in the course
$modinfo = get_fast_modinfo($course);
// Get criteria for course
$completion = new completion_info($course);
if (!$completion->has_criteria()) {
print_error('nocriteriaset', 'completion', $CFG->wwwroot.'/course/report.php?id='.$course->id);
}
// Get criteria and put in correct order
$criteria = array();
foreach ($completion->get_criteria(<API key>) as $criterion) {
$criteria[] = $criterion;
}
foreach ($completion->get_criteria(<API key>) as $criterion) {
$criteria[] = $criterion;
}
foreach ($completion->get_criteria() as $criterion) {
if (!in_array($criterion->criteriatype, array(
<API key>, <API key>))) {
$criteria[] = $criterion;
}
}
// Can logged in user mark users as complete?
// (if the logged in user has a role defined in the role criteria)
$allow_marking = false;
$<API key> = null;
if (!$csv) {
// Get role criteria
$rcriteria = $completion->get_criteria(<API key>);
if (!empty($rcriteria)) {
foreach ($rcriteria as $rcriterion) {
$users = get_role_users($rcriterion->role, $context, true);
// If logged in user has this role, allow marking complete
if ($users && in_array($USER->id, array_keys($users))) {
$allow_marking = true;
$<API key> = $rcriterion->id;
break;
}
}
}
}
/*
* Setup page header
*/
if ($csv) {
$shortname = format_string($course->shortname, true, array('context' => $context));
$shortname = preg_replace('/[^a-z0-9-]/', '_',core_text::strtolower(strip_tags($shortname)));
$export = new csv_export_writer();
$export->set_filename('completion-'.$shortname);
} else {
// Navigation and header
$strcompletion = get_string('coursecompletion');
$PAGE->set_title($strcompletion);
$PAGE->set_heading($course->fullname);
echo $OUTPUT->header();
// Handle groups (if enabled)
<API key>($course, $CFG->wwwroot.'/report/completion/index.php?course='.$course->id);
}
if ($sifirst !== 'all') {
set_user_preference('ifirst', $sifirst);
}
if ($silast !== 'all') {
set_user_preference('ilast', $silast);
}
if (!empty($USER->preference['ifirst'])) {
$sifirst = $USER->preference['ifirst'];
} else {
$sifirst = 'all';
}
if (!empty($USER->preference['ilast'])) {
$silast = $USER->preference['ilast'];
} else {
$silast = 'all';
}
// Generate where clause
$where = array();
$where_params = array();
if ($sifirst !== 'all') {
$where[] = $DB->sql_like('u.firstname', ':sifirst', false);
$where_params['sifirst'] = $sifirst.'%';
}
if ($silast !== 'all') {
$where[] = $DB->sql_like('u.lastname', ':silast', false);
$where_params['silast'] = $silast.'%';
}
// Get user match count
$total = $completion-><API key>(implode(' AND ', $where), $where_params, $group);
// Total user count
$grandtotal = $completion-><API key>('', array(), $group);
// If no users in this course what-so-ever
if (!$grandtotal) {
echo $OUTPUT->container(get_string('err_nousers', 'completion'), 'errorbox errorboxcontent');
echo $OUTPUT->footer();
exit;
}
// Get user data
$progress = array();
if ($total) {
$progress = $completion->get_progress_all(
implode(' AND ', $where),
$where_params,
$group,
$firstnamesort ? 'u.firstname ASC' : 'u.lastname ASC',
$csv ? 0 : <API key>,
$csv ? 0 : $start,
$context
);
}
// Build link for paging
$link = $CFG->wwwroot.'/report/completion/index.php?course='.$course->id;
if (strlen($sort)) {
$link .= '&sort='.$sort;
}
$link .= '&start=';
$pagingbar = '';
// Initials bar.
$prefixfirst = 'sifirst';
$prefixlast = 'silast';
$pagingbar .= $OUTPUT->initials_bar($sifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $url);
$pagingbar .= $OUTPUT->initials_bar($silast, 'lastinitial', get_string('lastname'), $prefixlast, $url);
// Do we need a paging bar?
if ($total > <API key>) {
// Paging bar
$pagingbar .= '<div class="paging">';
$pagingbar .= get_string('page').': ';
$sistrings = array();
if ($sifirst != 'all') {
$sistrings[] = "sifirst={$sifirst}";
}
if ($silast != 'all') {
$sistrings[] = "silast={$silast}";
}
$sistring = !empty($sistrings) ? '&'.implode('&', $sistrings) : '';
// Display previous link
if ($start > 0) {
$pstart = max($start - <API key>, 0);
$pagingbar .= "(<a class=\"previous\" href=\"{$link}{$pstart}{$sistring}\">".get_string('previous').'</a>) ';
}
// Create page links
$curstart = 0;
$curpage = 0;
while ($curstart < $total) {
$curpage++;
if ($curstart == $start) {
$pagingbar .= ' '.$curpage.' ';
}
else {
$pagingbar .= " <a href=\"{$link}{$curstart}{$sistring}\">$curpage</a> ";
}
$curstart += <API key>;
}
// Display next link
$nstart = $start + <API key>;
if ($nstart < $total) {
$pagingbar .= " (<a class=\"next\" href=\"{$link}{$nstart}{$sistring}\">".get_string('next').'</a>)';
}
$pagingbar .= '</div>';
}
/*
* Draw table header
*/
// Start of table
if (!$csv) {
print '<br class="clearer"/>'; // ugh
$total_header = ($total == $grandtotal) ? $total : "{$total}/{$grandtotal}";
echo $OUTPUT->heading(get_string('allparticipants').": {$total_header}", 3);
print $pagingbar;
if (!$total) {
echo $OUTPUT->heading(get_string('nothingtodisplay'), 2);
echo $OUTPUT->footer();
exit;
}
print '<table id="completion-progress" class="table table-bordered generaltable flexible boxaligncenter
completionreport" style="text-align: left" cellpadding="5" border="1">';
// Print criteria group names
print PHP_EOL.'<thead><tr style="vertical-align: top">';
echo '<th scope="row" class="rowheader" colspan="' . $leftcols . '">' .
get_string('criteriagroup', 'completion') . '</th>';
$current_group = false;
$col_count = 0;
for ($i = 0; $i <= count($criteria); $i++) {
if (isset($criteria[$i])) {
$criterion = $criteria[$i];
if ($current_group && $criterion->criteriatype === $current_group->criteriatype) {
++$col_count;
continue;
}
}
// Print header cell
if ($col_count) {
print '<th scope="col" colspan="'.$col_count.'" class="colheader criteriagroup">'.$current_group->get_type_title().'</th>';
}
if (isset($criteria[$i])) {
// Move to next criteria type
$current_group = $criterion;
$col_count = 1;
}
}
// Overall course completion status
print '<th style="text-align: center;">'.get_string('course').'</th>';
print '</tr>';
// Print aggregation methods
print PHP_EOL.'<tr style="vertical-align: top">';
echo '<th scope="row" class="rowheader" colspan="' . $leftcols . '">' .
get_string('aggregationmethod', 'completion').'</th>';
$current_group = false;
$col_count = 0;
for ($i = 0; $i <= count($criteria); $i++) {
if (isset($criteria[$i])) {
$criterion = $criteria[$i];
if ($current_group && $criterion->criteriatype === $current_group->criteriatype) {
++$col_count;
continue;
}
}
// Print header cell
if ($col_count) {
$has_agg = array(
<API key>,
<API key>,
<API key>,
);
if (in_array($current_group->criteriatype, $has_agg)) {
// Try load a aggregation method
$method = $completion-><API key>($current_group->criteriatype);
$method = $method == 1 ? get_string('all') : get_string('any');
} else {
$method = '-';
}
print '<th scope="col" colspan="'.$col_count.'" class="colheader aggheader">'.$method.'</th>';
}
if (isset($criteria[$i])) {
// Move to next criteria type
$current_group = $criterion;
$col_count = 1;
}
}
// Overall course aggregation method
print '<th scope="col" class="colheader aggheader aggcriteriacourse">';
// Get course aggregation
$method = $completion-><API key>();
print $method == 1 ? get_string('all') : get_string('any');
print '</th>';
print '</tr>';
// Print criteria titles
if (<API key>) {
print PHP_EOL.'<tr>';
echo '<th scope="row" class="rowheader" colspan="' . $leftcols . '">' .
get_string('criteria', 'completion') . '</th>';
foreach ($criteria as $criterion) {
// Get criteria details
$details = $criterion->get_title_detailed();
print '<th scope="col" class="colheader criterianame">';
print '<div class="<API key>"><span class="rotated-text">'.$details.'</span></div>';
print '</th>';
}
// Overall course completion status
print '<th scope="col" class="colheader criterianame">';
print '<div class="<API key>"><span class="rotated-text">'.get_string('coursecomplete', 'completion').'</span></div>';
print '</th></tr>';
}
// Print user heading and icons
print '<tr>';
// User heading / sort option
print '<th scope="col" class="<API key>" style="clear: both;">';
$sistring = "&silast={$silast}&sifirst={$sifirst}";
if ($firstnamesort) {
print
get_string('firstname')." / <a href=\"./index.php?course={$course->id}{$sistring}\">".
get_string('lastname').'</a>';
} else {
print "<a href=\"./index.php?course={$course->id}&sort=firstname{$sistring}\">".
get_string('firstname').'</a> / '.
get_string('lastname');
}
print '</th>';
// Print user identity columns
foreach ($extrafields as $field) {
echo '<th scope="col" class="<API key>">' .
get_user_field_name($field) . '</th>';
}
Print criteria icons
foreach ($criteria as $criterion) {
// Generate icon details
$iconlink = '';
$iconalt = ''; // Required
$iconattributes = array('class' => 'icon');
switch ($criterion->criteriatype) {
case <API key>:
// Display icon
$iconlink = $CFG->wwwroot.'/mod/'.$criterion->module.'/view.php?id='.$criterion->moduleinstance;
$iconattributes['title'] = $modinfo->cms[$criterion->moduleinstance]->get_formatted_name();
$iconalt = get_string('modulename', $criterion->module);
break;
case <API key>:
// Load course
$crs = $DB->get_record('course', array('id' => $criterion->courseinstance));
// Display icon
$iconlink = $CFG->wwwroot.'/course/view.php?id='.$criterion->courseinstance;
$iconattributes['title'] = format_string($crs->fullname, true, array('context' => context_course::instance($crs->id, MUST_EXIST)));
$iconalt = format_string($crs->shortname, true, array('context' => context_course::instance($crs->id)));
break;
case <API key>:
// Load role
$role = $DB->get_record('role', array('id' => $criterion->role));
// Display icon
$iconalt = $role->name;
break;
}
// Create icon alt if not supplied
if (!$iconalt) {
$iconalt = $criterion->get_title();
}
// Print icon and cell
print '<th class="criteriaicon">';
print ($iconlink ? '<a href="'.$iconlink.'" title="'.$iconattributes['title'].'">' : '');
print $OUTPUT->render($criterion->get_icon($iconalt, $iconattributes));
print ($iconlink ? '</a>' : '');
print '</th>';
}
// Overall course completion status
print '<th class="criteriaicon">';
print $OUTPUT->pix_icon('i/course', get_string('coursecomplete', 'completion'));
print '</th>';
print '</tr></thead>';
echo '<tbody>';
} else {
// The CSV headers
$row = array();
$row[] = get_string('id', 'report_completion');
$row[] = get_string('name', 'report_completion');
foreach ($extrafields as $field) {
$row[] = get_user_field_name($field);
}
// Add activity headers
foreach ($criteria as $criterion) {
// Handle activity completion differently
if ($criterion->criteriatype == <API key>) {
// Load activity
$mod = $criterion->get_mod_instance();
$row[] = $formattedname = format_string($mod->name, true,
array('context' => context_module::instance($criterion->moduleinstance)));
$row[] = $formattedname . ' - ' . get_string('completiondate', 'report_completion');
}
else {
// Handle all other criteria
$row[] = strip_tags($criterion->get_title_detailed());
}
}
$row[] = get_string('coursecomplete', 'completion');
$export->add_data($row);
}
Display a row for each user
foreach ($progress as $user) {
// User name
if ($csv) {
$row = array();
$row[] = $user->id;
$row[] = fullname($user);
foreach ($extrafields as $field) {
$row[] = $user->{$field};
}
} else {
print PHP_EOL.'<tr id="user-'.$user->id.'">';
if (<API key>($user->id, $course)) {
$userurl = new moodle_url('/blocks/completionstatus/details.php', array('course' => $course->id, 'user' => $user->id));
} else {
$userurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
}
print '<th scope="row"><a href="'.$userurl->out().'">'.fullname($user).'</a></th>';
foreach ($extrafields as $field) {
echo '<td>'.s($user->{$field}).'</td>';
}
}
// Progress for each course completion criteria
foreach ($criteria as $criterion) {
$criteria_completion = $completion->get_user_completion($user->id, $criterion);
$is_complete = $criteria_completion->is_complete();
// Handle activity completion differently
if ($criterion->criteriatype == <API key>) {
// Load activity
$activity = $modinfo->cms[$criterion->moduleinstance];
// Get progress information and state
if (array_key_exists($activity->id, $user->progress)) {
$state = $user->progress[$activity->id]->completionstate;
} else if ($is_complete) {
$state = COMPLETION_COMPLETE;
} else {
$state = <API key>;
}
if ($is_complete) {
$date = userdate($criteria_completion->timecompleted, get_string('<API key>', 'langconfig'));
} else {
$date = '';
}
// Work out how it corresponds to an icon
switch($state) {
case <API key> : $completiontype = 'n'; break;
case COMPLETION_COMPLETE : $completiontype = 'y'; break;
case <API key> : $completiontype = 'pass'; break;
case <API key> : $completiontype = 'fail'; break;
}
$auto = $activity->completion == <API key>;
$completionicon = 'completion-'.($auto ? 'auto' : 'manual').'-'.$completiontype;
$describe = get_string('completion-'.$completiontype, 'completion');
$a = new StdClass();
$a->state = $describe;
$a->date = $date;
$a->user = fullname($user);
$a->activity = $activity->get_formatted_name();
$fulldescribe = get_string('progress-title', 'completion', $a);
if ($csv) {
$row[] = $describe;
$row[] = $date;
} else {
print '<td class="<API key>">';
print $OUTPUT->pix_icon('i/' . $completionicon, $fulldescribe);
print '</td>';
}
continue;
}
// Handle all other criteria
$completiontype = $is_complete ? 'y' : 'n';
$completionicon = 'completion-auto-'.$completiontype;
$describe = get_string('completion-'.$completiontype, 'completion');
$a = new stdClass();
$a->state = $describe;
if ($is_complete) {
$a->date = userdate($criteria_completion->timecompleted, get_string('<API key>', 'langconfig'));
} else {
$a->date = '';
}
$a->user = fullname($user);
$a->activity = strip_tags($criterion->get_title());
$fulldescribe = get_string('progress-title', 'completion', $a);
if ($csv) {
$row[] = $a->date;
} else {
print '<td class="<API key>">';
if ($<API key> === $criterion->id) {
$describe = get_string('completion-'.$completiontype, 'completion');
$toggleurl = new moodle_url(
'/course/togglecompletion.php',
array(
'user' => $user->id,
'course' => $course->id,
'rolec' => $<API key>,
'sesskey' => sesskey()
)
);
print '<a href="'.$toggleurl->out().'" title="'.s(get_string('<API key>', 'report_completion')).'">' .
$OUTPUT->pix_icon('i/completion-manual-' . ($is_complete ? 'y' : 'n'), $describe) . '</a></td>';
} else {
print $OUTPUT->pix_icon('i/' . $completionicon, $fulldescribe) . '</td>';
}
print '</td>';
}
}
// Handle overall course completion
// Load course completion
$params = array(
'userid' => $user->id,
'course' => $course->id
);
$ccompletion = new <API key>($params);
$completiontype = $ccompletion->is_complete() ? 'y' : 'n';
$describe = get_string('completion-'.$completiontype, 'completion');
$a = new StdClass;
if ($ccompletion->is_complete()) {
$a->date = userdate($ccompletion->timecompleted, get_string('<API key>', 'langconfig'));
} else {
$a->date = '';
}
$a->state = $describe;
$a->user = fullname($user);
$a->activity = strip_tags(get_string('coursecomplete', 'completion'));
$fulldescribe = get_string('progress-title', 'completion', $a);
if ($csv) {
$row[] = $a->date;
} else {
print '<td class="<API key>">';
// Display course completion status icon
print $OUTPUT->pix_icon('i/completion-auto-' . $completiontype, $fulldescribe);
print '</td>';
}
if ($csv) {
$export->add_data($row);
} else {
print '</tr>';
}
}
if ($csv) {
$export->download_file();
} else {
echo '</tbody>';
}
print '</table>';
print $pagingbar;
$csvurl = new moodle_url('/report/completion/index.php', array('course' => $course->id, 'format' => 'csv'));
$excelurl = new moodle_url('/report/completion/index.php', array('course' => $course->id, 'format' => 'excelcsv'));
print '<ul class="export-actions">';
print '<li><a href="'.$csvurl->out().'">'.get_string('csvdownload','completion').'</a></li>';
print '<li><a href="'.$excelurl->out().'">'.get_string('excelcsvdownload','completion').'</a></li>';
print '</ul>';
echo $OUTPUT->footer($course);
// Trigger a report viewed event.
$event = \report_completion\event\report_viewed::create(array('context' => $context));
$event->trigger();
|
{% spaceless %}
{% block js %}
<script type="text/javascript">
alert("test using multiple inheritance and block.super");
</script>
{% endblock %}
{% block css %}
<style type="text/css">
body {
background: red;
}
</style>
{% endblock %}
{% endspaceless %}
|
-*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#include <AP_Math/AP_Math.h>
#include <AP_HAL/AP_HAL.h>
#include "AP_Compass_LSM303D.h"
extern const AP_HAL::HAL& hal;
#if CONFIG_HAL_BOARD == HAL_BOARD_LINUX
#include <AP_HAL_Linux/GPIO.h>
#if <API key> == <API key>
#define LSM303D_DRDY_M_PIN RPI_GPIO_27
#endif
#endif
#ifndef LSM303D_DRDY_M_PIN
#define LSM303D_DRDY_M_PIN -1
#endif
/* SPI protocol address bits */
#define DIR_READ (1<<7)
#define DIR_WRITE (0<<7)
#define ADDR_INCREMENT (1<<6)
/* register addresses: A: accel, M: mag, T: temp */
#define ADDR_WHO_AM_I 0x0F
#define WHO_I_AM 0x49
#define ADDR_OUT_TEMP_L 0x05
#define ADDR_OUT_TEMP_H 0x06
#define ADDR_STATUS_M 0x07
#define ADDR_OUT_X_L_M 0x08
#define ADDR_OUT_X_H_M 0x09
#define ADDR_OUT_Y_L_M 0x0A
#define ADDR_OUT_Y_H_M 0x0B
#define ADDR_OUT_Z_L_M 0x0C
#define ADDR_OUT_Z_H_M 0x0D
#define ADDR_INT_CTRL_M 0x12
#define ADDR_INT_SRC_M 0x13
#define ADDR_REFERENCE_X 0x1c
#define ADDR_REFERENCE_Y 0x1d
#define ADDR_REFERENCE_Z 0x1e
#define ADDR_STATUS_A 0x27
#define ADDR_OUT_X_L_A 0x28
#define ADDR_OUT_X_H_A 0x29
#define ADDR_OUT_Y_L_A 0x2A
#define ADDR_OUT_Y_H_A 0x2B
#define ADDR_OUT_Z_L_A 0x2C
#define ADDR_OUT_Z_H_A 0x2D
#define ADDR_CTRL_REG0 0x1F
#define ADDR_CTRL_REG1 0x20
#define ADDR_CTRL_REG2 0x21
#define ADDR_CTRL_REG3 0x22
#define ADDR_CTRL_REG4 0x23
#define ADDR_CTRL_REG5 0x24
#define ADDR_CTRL_REG6 0x25
#define ADDR_CTRL_REG7 0x26
#define ADDR_FIFO_CTRL 0x2e
#define ADDR_FIFO_SRC 0x2f
#define ADDR_IG_CFG1 0x30
#define ADDR_IG_SRC1 0x31
#define ADDR_IG_THS1 0x32
#define ADDR_IG_DUR1 0x33
#define ADDR_IG_CFG2 0x34
#define ADDR_IG_SRC2 0x35
#define ADDR_IG_THS2 0x36
#define ADDR_IG_DUR2 0x37
#define ADDR_CLICK_CFG 0x38
#define ADDR_CLICK_SRC 0x39
#define ADDR_CLICK_THS 0x3a
#define ADDR_TIME_LIMIT 0x3b
#define ADDR_TIME_LATENCY 0x3c
#define ADDR_TIME_WINDOW 0x3d
#define ADDR_ACT_THS 0x3e
#define ADDR_ACT_DUR 0x3f
#define REG1_RATE_BITS_A ((1<<7) | (1<<6) | (1<<5) | (1<<4))
#define REG1_POWERDOWN_A ((0<<7) | (0<<6) | (0<<5) | (0<<4))
#define REG1_RATE_3_125HZ_A ((0<<7) | (0<<6) | (0<<5) | (1<<4))
#define REG1_RATE_6_25HZ_A ((0<<7) | (0<<6) | (1<<5) | (0<<4))
#define REG1_RATE_12_5HZ_A ((0<<7) | (0<<6) | (1<<5) | (1<<4))
#define REG1_RATE_25HZ_A ((0<<7) | (1<<6) | (0<<5) | (0<<4))
#define REG1_RATE_50HZ_A ((0<<7) | (1<<6) | (0<<5) | (1<<4))
#define REG1_RATE_100HZ_A ((0<<7) | (1<<6) | (1<<5) | (0<<4))
#define REG1_RATE_200HZ_A ((0<<7) | (1<<6) | (1<<5) | (1<<4))
#define REG1_RATE_400HZ_A ((1<<7) | (0<<6) | (0<<5) | (0<<4))
#define REG1_RATE_800HZ_A ((1<<7) | (0<<6) | (0<<5) | (1<<4))
#define REG1_RATE_1600HZ_A ((1<<7) | (0<<6) | (1<<5) | (0<<4))
#define REG1_BDU_UPDATE (1<<3)
#define REG1_Z_ENABLE_A (1<<2)
#define REG1_Y_ENABLE_A (1<<1)
#define REG1_X_ENABLE_A (1<<0)
#define <API key> ((1<<7) | (1<<6))
#define <API key> ((0<<7) | (0<<6))
#define <API key> ((0<<7) | (1<<6))
#define <API key> ((1<<7) | (0<<6))
#define <API key> ((1<<7) | (1<<6))
#define <API key> ((1<<5) | (1<<4) | (1<<3))
#define <API key> ((0<<5) | (0<<4) | (0<<3))
#define <API key> ((0<<5) | (0<<4) | (1<<3))
#define <API key> ((0<<5) | (1<<4) | (0<<3))
#define <API key> ((0<<5) | (1<<4) | (1<<3))
#define <API key> ((1<<5) | (0<<4) | (0<<3))
#define REG5_ENABLE_T (1<<7)
#define REG5_RES_HIGH_M ((1<<6) | (1<<5))
#define REG5_RES_LOW_M ((0<<6) | (0<<5))
#define REG5_RATE_BITS_M ((1<<4) | (1<<3) | (1<<2))
#define REG5_RATE_3_125HZ_M ((0<<4) | (0<<3) | (0<<2))
#define REG5_RATE_6_25HZ_M ((0<<4) | (0<<3) | (1<<2))
#define REG5_RATE_12_5HZ_M ((0<<4) | (1<<3) | (0<<2))
#define REG5_RATE_25HZ_M ((0<<4) | (1<<3) | (1<<2))
#define REG5_RATE_50HZ_M ((1<<4) | (0<<3) | (0<<2))
#define REG5_RATE_100HZ_M ((1<<4) | (0<<3) | (1<<2))
#define <API key> ((1<<4) | (1<<3) | (0<<2))
#define <API key> ((1<<6) | (1<<5))
#define <API key> ((0<<6) | (0<<5))
#define <API key> ((0<<6) | (1<<5))
#define <API key> ((1<<6) | (0<<5))
#define <API key> ((1<<6) | (1<<5))
#define REG7_CONT_MODE_M ((0<<1) | (0<<0))
#define INT_CTRL_M 0x12
#define INT_SRC_M 0x13
/* default values for this device */
#define <API key> 8
#define <API key> 800
#define <API key> 50
#define <API key> 30
#define <API key> 2
#define <API key> 100
#define LSM303D_DEBUG 0
#if LSM303D_DEBUG
#include <stdio.h>
#define error(...) fprintf(stderr, __VA_ARGS__)
#define debug(...) hal.console->printf(__VA_ARGS__)
#define ASSERT(x) assert(x)
#else
#define error(...)
#define debug(...)
#define ASSERT(x)
#endif
// constructor
AP_Compass_LSM303D::AP_Compass_LSM303D(Compass &compass):
AP_Compass_Backend(compass)
{}
// detect the sensor
AP_Compass_Backend *AP_Compass_LSM303D::detect_spi(Compass &compass)
{
AP_Compass_LSM303D *sensor = new AP_Compass_LSM303D(compass);
if (sensor == NULL) {
return NULL;
}
if (!sensor->init()) {
delete sensor;
return NULL;
}
return sensor;
}
uint8_t AP_Compass_LSM303D::_register_read(uint8_t reg)
{
uint8_t addr = reg | 0x80; // Set most significant bit
uint8_t tx[2];
uint8_t rx[2];
tx[0] = addr;
tx[1] = 0;
_spi->transaction(tx, rx, 2);
return rx[1];
}
void AP_Compass_LSM303D::_register_write(uint8_t reg, uint8_t val)
{
uint8_t tx[2];
uint8_t rx[2];
tx[0] = reg;
tx[1] = val;
_spi->transaction(tx, rx, 2);
}
void AP_Compass_LSM303D::_register_modify(uint8_t reg, uint8_t clearbits, uint8_t setbits)
{
uint8_t val;
val = _register_read(reg);
val &= ~clearbits;
val |= setbits;
_register_write(reg, val);
}
/**
* Return true if the LSM303D has new data available for both the mag and
* the accels.
*/
bool AP_Compass_LSM303D::_data_ready()
{
return (_drdy_pin_m->read()) != 0;
}
// Read Sensor data
bool AP_Compass_LSM303D::_read_raw()
{
if (_register_read(ADDR_CTRL_REG7) != _reg7_expected) {
hal.console->println_P(
PSTR("LSM303D <API key>: _reg7_expected unexpected"));
// reset();
return false;
}
if (!_data_ready()) {
return false;
}
struct PACKED {
uint8_t cmd;
uint8_t status;
int16_t x;
int16_t y;
int16_t z;
} raw_mag_report_tx;
struct PACKED {
uint8_t cmd;
uint8_t status;
int16_t x;
int16_t y;
int16_t z;
} raw_mag_report_rx;
/* fetch data from the sensor */
memset(&raw_mag_report_tx, 0, sizeof(raw_mag_report_tx));
memset(&raw_mag_report_rx, 0, sizeof(raw_mag_report_rx));
raw_mag_report_tx.cmd = ADDR_STATUS_M | DIR_READ | ADDR_INCREMENT;
_spi->transaction((uint8_t *)&raw_mag_report_tx, (uint8_t *)&raw_mag_report_rx, sizeof(raw_mag_report_tx));
_mag_x = raw_mag_report_rx.x;
_mag_y = raw_mag_report_rx.y;
_mag_z = raw_mag_report_rx.z;
if (is_zero(_mag_x) && is_zero(_mag_y) && is_zero(_mag_z)) {
return false;
}
return true;
}
// Public Methods //////////////////////////////////////////////////////////////
bool
AP_Compass_LSM303D::init()
{
// TODO: support users without data ready pin
if (LSM303D_DRDY_M_PIN < 0)
return false;
hal.scheduler->suspend_timer_procs();
_spi = hal.spi->device(AP_HAL::SPIDevice_LSM303D);
_spi_sem = _spi->get_semaphore();
_drdy_pin_m = hal.gpio->channel(LSM303D_DRDY_M_PIN);
_drdy_pin_m->mode(HAL_GPIO_INPUT);
// Test WHOAMI
uint8_t whoami = _register_read(ADDR_WHO_AM_I);
if (whoami != WHO_I_AM) {
hal.console->printf("LSM303D: unexpected WHOAMI 0x%x\n", (unsigned)whoami);
hal.scheduler->panic(PSTR("LSM303D: bad WHOAMI"));
}
uint8_t tries = 0;
do {
// TODO: don't try to init 25 times
bool success = _hardware_init();
if (success) {
hal.scheduler->delay(5+2);
if (!_spi_sem->take(100)) {
hal.scheduler->panic(PSTR("LSM303D: Unable to get semaphore"));
}
if (_data_ready()) {
_spi_sem->give();
break;
} else {
hal.console->println_P(
PSTR("LSM303D startup failed: no data ready"));
}
_spi_sem->give();
}
if (tries++ > 5) {
hal.scheduler->panic(PSTR("PANIC: failed to boot LSM303D 5 times"));
}
} while (1);
_scaling[0] = 1.0;
_scaling[1] = 1.0;
_scaling[2] = 1.0;
/* register the compass instance in the frontend */
_compass_instance = register_compass();
set_dev_id(_compass_instance, get_dev_id());
#if CONFIG_HAL_BOARD == HAL_BOARD_LINUX && <API key> == <API key>
set_external(_compass_instance, false);
#endif
hal.scheduler-><API key>(FUNCTOR_BIND_MEMBER(&AP_Compass_LSM303D::_update, void));
<API key>(_compass_instance, 1.0f);
_spi_sem->give();
hal.scheduler->resume_timer_procs();
_initialised = true;
return _initialised;
}
uint32_t AP_Compass_LSM303D::get_dev_id()
{
return <API key>;
}
bool AP_Compass_LSM303D::_hardware_init(void)
{
if (!_spi_sem->take(100)) {
hal.scheduler->panic(PSTR("LSM303D: Unable to get semaphore"));
}
// initially run the bus at low speed
_spi->set_bus_speed(AP_HAL::SPIDeviceDriver::SPI_SPEED_LOW);
// ensure the chip doesn't interpret any other bus traffic as I2C
_disable_i2c();
/* enable mag */
_reg7_expected = REG7_CONT_MODE_M;
_register_write(ADDR_CTRL_REG7, _reg7_expected);
_register_write(ADDR_CTRL_REG5, REG5_RES_HIGH_M);
_register_write(ADDR_CTRL_REG4, 0x04); // DRDY on MAG on INT2
_mag_set_range(<API key>);
_mag_set_samplerate(<API key>);
// TODO: Software filtering
// now that we have initialised, we set the SPI bus speed to high
_spi->set_bus_speed(AP_HAL::SPIDeviceDriver::SPI_SPEED_HIGH);
_spi_sem->give();
return true;
}
void AP_Compass_LSM303D::_update()
{
if (hal.scheduler->micros() - <API key> < 10000) {
return;
}
if (!_spi_sem->take_nonblocking()) {
return;
}
_collect_samples();
<API key> = hal.scheduler->micros();
_spi_sem->give();
}
void AP_Compass_LSM303D::_collect_samples()
{
if (!_initialised) {
return;
}
if (!_read_raw()) {
error("_read_raw() failed\n");
} else {
Vector3f raw_field = Vector3f(_mag_x, _mag_y, _mag_z) * _mag_range_scale;
uint32_t time_us = hal.scheduler->micros();
// rotate raw_field from sensor frame to body frame
rotate_field(raw_field, _compass_instance);
// publish raw_field (uncorrected point sample) for _scaling use
publish_raw_field(raw_field, time_us, _compass_instance);
// correct raw_field for known errors
correct_field(raw_field, _compass_instance);
// publish raw_field (corrected point sample) for EKF use
<API key>(raw_field, time_us, _compass_instance);
_mag_x_accum += raw_field.x;
_mag_y_accum += raw_field.y;
_mag_z_accum += raw_field.z;
_accum_count++;
if (_accum_count == 10) {
_mag_x_accum /= 2;
_mag_y_accum /= 2;
_mag_z_accum /= 2;
_accum_count = 5;
}
}
}
// Read Sensor data
void AP_Compass_LSM303D::read()
{
if (!_initialised) {
// someone has tried to enable a compass for the first time
// mid-flight .... we can't do that yet (especially as we won't
// have the right orientation!)
return;
}
if (_accum_count == 0) {
/* We're not ready to publish*/
return;
}
hal.scheduler->suspend_timer_procs();
Vector3f field(_mag_x_accum * _scaling[0],
_mag_y_accum * _scaling[1],
_mag_z_accum * _scaling[2]);
field /= _accum_count;
_accum_count = 0;
_mag_x_accum = _mag_y_accum = _mag_z_accum = 0;
hal.scheduler->resume_timer_procs();
<API key>(field, _compass_instance);
}
void AP_Compass_LSM303D::_disable_i2c(void)
{
// TODO: use the register names
uint8_t a = _register_read(0x02);
_register_write(0x02, (0x10 | a));
a = _register_read(0x02);
_register_write(0x02, (0xF7 & a));
a = _register_read(0x15);
_register_write(0x15, (0x80 | a));
a = _register_read(0x02);
_register_write(0x02, (0xE7 & a));
}
uint8_t AP_Compass_LSM303D::_mag_set_range(uint8_t max_ga)
{
uint8_t setbits = 0;
uint8_t clearbits = <API key>;
float new_scale_ga_digit = 0.0f;
if (max_ga == 0)
max_ga = 12;
if (max_ga <= 2) {
_mag_range_ga = 2;
setbits |= <API key>;
new_scale_ga_digit = 0.080f;
} else if (max_ga <= 4) {
_mag_range_ga = 4;
setbits |= <API key>;
new_scale_ga_digit = 0.160f;
} else if (max_ga <= 8) {
_mag_range_ga = 8;
setbits |= <API key>;
new_scale_ga_digit = 0.320f;
} else if (max_ga <= 12) {
_mag_range_ga = 12;
setbits |= <API key>;
new_scale_ga_digit = 0.479f;
} else {
return -1;
}
_mag_range_scale = new_scale_ga_digit;
_register_modify(ADDR_CTRL_REG6, clearbits, setbits);
return 0;
}
uint8_t AP_Compass_LSM303D::_mag_set_samplerate(uint16_t frequency)
{
uint8_t setbits = 0;
uint8_t clearbits = REG5_RATE_BITS_M;
if (frequency == 0)
frequency = 100;
if (frequency <= 25) {
setbits |= REG5_RATE_25HZ_M;
_mag_samplerate = 25;
} else if (frequency <= 50) {
setbits |= REG5_RATE_50HZ_M;
_mag_samplerate = 50;
} else if (frequency <= 100) {
setbits |= REG5_RATE_100HZ_M;
_mag_samplerate = 100;
} else {
return -1;
}
_register_modify(ADDR_CTRL_REG5, clearbits, setbits);
return 0;
}
|
<?php
namespace Leafo\ScssPhp;
use Leafo\ScssPhp\Block;
use Leafo\ScssPhp\Compiler;
use Leafo\ScssPhp\Exception\ParserException;
use Leafo\ScssPhp\Node;
use Leafo\ScssPhp\Type;
/**
* Parser
*
* @author Leaf Corcoran <leafot@gmail.com>
*/
class Parser
{
const SOURCE_INDEX = -1;
const SOURCE_LINE = -2;
const SOURCE_COLUMN = -3;
/**
* @var array
*/
protected static $precedence = [
'=' => 0,
'or' => 1,
'and' => 2,
'==' => 3,
'!=' => 3,
'<=>' => 3,
'<=' => 4,
'>=' => 4,
'<' => 4,
'>' => 4,
'+' => 5,
'-' => 5,
'*' => 6,
'/' => 6,
'%' => 6,
];
protected static $commentPattern;
protected static $operatorPattern;
protected static $whitePattern;
private $sourceName;
private $sourceIndex;
private $sourcePositions;
private $charset;
private $count;
private $env;
private $inParens;
private $eatWhiteDefault;
private $buffer;
private $utf8;
private $encoding;
private $patternModifiers;
/**
* Constructor
*
* @api
*
* @param string $sourceName
* @param integer $sourceIndex
* @param string $encoding
*/
public function __construct($sourceName, $sourceIndex = 0, $encoding = 'utf-8')
{
$this->sourceName = $sourceName ?: '(stdin)';
$this->sourceIndex = $sourceIndex;
$this->charset = null;
$this->utf8 = ! $encoding || strtolower($encoding) === 'utf-8';
$this->patternModifiers = $this->utf8 ? 'Aisu' : 'Ais';
if (empty(static::$operatorPattern)) {
static::$operatorPattern = '([*\/%+-]|[!=]\=|\>\=?|\<\=\>|\<\=?|and|or)';
$commentSingle = '\/\/';
$commentMultiLeft = '\/\*';
$commentMultiRight = '\*\/';
static::$commentPattern = $commentMultiLeft . '.*?' . $commentMultiRight;
static::$whitePattern = $this->utf8
? '/' . $commentSingle . '[^\n]*\s*|(' . static::$commentPattern . ')\s*|\s+/AisuS'
: '/' . $commentSingle . '[^\n]*\s*|(' . static::$commentPattern . ')\s*|\s+/AisS';
}
}
/**
* Get source file name
*
* @api
*
* @return string
*/
public function getSourceName()
{
return $this->sourceName;
}
/**
* Throw parser error
*
* @api
*
* @param string $msg
*
* @throws \Leafo\ScssPhp\Exception\ParserException
*/
public function throwParseError($msg = 'parse error')
{
list($line, /* $column */) = $this->getSourcePosition($this->count);
$loc = empty($this->sourceName) ? "line: $line" : "$this->sourceName on line $line";
if ($this->peek("(.*?)(\n|$)", $m, $this->count)) {
throw new ParserException("$msg: failed at `$m[1]` $loc");
}
throw new ParserException("$msg: $loc");
}
/**
* Parser buffer
*
* @api
*
* @param string $buffer
*
* @return \Leafo\ScssPhp\Block
*/
public function parse($buffer)
{
// strip BOM (byte order marker)
if (substr($buffer, 0, 3) === "\xef\xbb\xbf") {
$buffer = substr($buffer, 3);
}
$this->buffer = rtrim($buffer, "\x00..\x1f");
$this->count = 0;
$this->env = null;
$this->inParens = false;
$this->eatWhiteDefault = true;
$this->saveEncoding();
$this->extractLineNumbers($buffer);
$this->pushBlock(null); // root block
$this->whitespace();
$this->pushBlock(null);
$this->popBlock();
while ($this->parseChunk()) {
;
}
if ($this->count !== strlen($this->buffer)) {
$this->throwParseError();
}
if (! empty($this->env->parent)) {
$this->throwParseError('unclosed block');
}
if ($this->charset) {
array_unshift($this->env->children, $this->charset);
}
$this->env->isRoot = true;
$this->restoreEncoding();
return $this->env;
}
/**
* Parse a value or value list
*
* @api
*
* @param string $buffer
* @param string $out
*
* @return boolean
*/
public function parseValue($buffer, &$out)
{
$this->count = 0;
$this->env = null;
$this->inParens = false;
$this->eatWhiteDefault = true;
$this->buffer = (string) $buffer;
$this->saveEncoding();
$list = $this->valueList($out);
$this->restoreEncoding();
return $list;
}
/**
* Parse a selector or selector list
*
* @api
*
* @param string $buffer
* @param string $out
*
* @return boolean
*/
public function parseSelector($buffer, &$out)
{
$this->count = 0;
$this->env = null;
$this->inParens = false;
$this->eatWhiteDefault = true;
$this->buffer = (string) $buffer;
$this->saveEncoding();
$selector = $this->selectors($out);
$this->restoreEncoding();
return $selector;
}
/**
* Parse a single chunk off the head of the buffer and append it to the
* current parse environment.
*
* Returns false when the buffer is empty, or when there is an error.
*
* This function is called repeatedly until the entire document is
* parsed.
*
* This parser is most similar to a recursive descent parser. Single
* functions represent discrete grammatical rules for the language, and
* they are able to capture the text that represents those rules.
*
* Consider the function Compiler::keyword(). (All parse functions are
* structured the same.)
*
* The function takes a single reference argument. When calling the
* function it will attempt to match a keyword on the head of the buffer.
* If it is successful, it will place the keyword in the referenced
* argument, advance the position in the buffer, and return true. If it
* fails then it won't advance the buffer and it will return false.
*
* All of these parse functions are powered by Compiler::match(), which behaves
* the same way, but takes a literal regular expression. Sometimes it is
* more convenient to use match instead of creating a new function.
*
* Because of the format of the functions, to parse an entire string of
* grammatical rules, you can chain them together using &&.
*
* But, if some of the rules in the chain succeed before one fails, then
* the buffer position will be left at an invalid state. In order to
* avoid this, Compiler::seek() is used to remember and set buffer positions.
*
* Before parsing a chain, use $s = $this->seek() to remember the current
* position into $s. Then if a chain fails, use $this->seek($s) to
* go back where we started.
*
* @return boolean
*/
protected function parseChunk()
{
$s = $this->seek();
// the directives
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] === '@') {
if ($this->literal('@at-root') &&
($this->selectors($selector) || true) &&
($this->map($with) || true) &&
$this->literal('{')
) {
$atRoot = $this->pushSpecialBlock(Type::T_AT_ROOT, $s);
$atRoot->selector = $selector;
$atRoot->with = $with;
return true;
}
$this->seek($s);
if ($this->literal('@media') && $this->mediaQueryList($mediaQueryList) && $this->literal('{')) {
$media = $this->pushSpecialBlock(Type::T_MEDIA, $s);
$media->queryList = $mediaQueryList[2];
return true;
}
$this->seek($s);
if ($this->literal('@mixin') &&
$this->keyword($mixinName) &&
($this->argumentDef($args) || true) &&
$this->literal('{')
) {
$mixin = $this->pushSpecialBlock(Type::T_MIXIN, $s);
$mixin->name = $mixinName;
$mixin->args = $args;
return true;
}
$this->seek($s);
if ($this->literal('@include') &&
$this->keyword($mixinName) &&
($this->literal('(') &&
($this->argValues($argValues) || true) &&
$this->literal(')') || true) &&
($this->end() ||
$this->literal('{') && $hasBlock = true)
) {
$child = [Type::T_INCLUDE, $mixinName, isset($argValues) ? $argValues : null, null];
if (! empty($hasBlock)) {
$include = $this->pushSpecialBlock(Type::T_INCLUDE, $s);
$include->child = $child;
} else {
$this->append($child, $s);
}
return true;
}
$this->seek($s);
if ($this->literal('@scssphp-import-once') &&
$this->valueList($importPath) &&
$this->end()
) {
$this->append([Type::<API key>, $importPath], $s);
return true;
}
$this->seek($s);
if ($this->literal('@import') &&
$this->valueList($importPath) &&
$this->end()
) {
$this->append([Type::T_IMPORT, $importPath], $s);
return true;
}
$this->seek($s);
if ($this->literal('@import') &&
$this->url($importPath) &&
$this->end()
) {
$this->append([Type::T_IMPORT, $importPath], $s);
return true;
}
$this->seek($s);
if ($this->literal('@extend') &&
$this->selectors($selectors) &&
$this->end()
) {
// check for '!flag'
$optional = $this->stripOptionalFlag($selectors);
$this->append([Type::T_EXTEND, $selectors, $optional], $s);
return true;
}
$this->seek($s);
if ($this->literal('@function') &&
$this->keyword($fnName) &&
$this->argumentDef($args) &&
$this->literal('{')
) {
$func = $this->pushSpecialBlock(Type::T_FUNCTION, $s);
$func->name = $fnName;
$func->args = $args;
return true;
}
$this->seek($s);
if ($this->literal('@break') && $this->end()) {
$this->append([Type::T_BREAK], $s);
return true;
}
$this->seek($s);
if ($this->literal('@continue') && $this->end()) {
$this->append([Type::T_CONTINUE], $s);
return true;
}
$this->seek($s);
if ($this->literal('@return') && ($this->valueList($retVal) || true) && $this->end()) {
$this->append([Type::T_RETURN, isset($retVal) ? $retVal : [Type::T_NULL]], $s);
return true;
}
$this->seek($s);
if ($this->literal('@each') &&
$this->genericList($varNames, 'variable', ',', false) &&
$this->literal('in') &&
$this->valueList($list) &&
$this->literal('{')
) {
$each = $this->pushSpecialBlock(Type::T_EACH, $s);
foreach ($varNames[2] as $varName) {
$each->vars[] = $varName[1];
}
$each->list = $list;
return true;
}
$this->seek($s);
if ($this->literal('@while') &&
$this->expression($cond) &&
$this->literal('{')
) {
$while = $this->pushSpecialBlock(Type::T_WHILE, $s);
$while->cond = $cond;
return true;
}
$this->seek($s);
if ($this->literal('@for') &&
$this->variable($varName) &&
$this->literal('from') &&
$this->expression($start) &&
($this->literal('through') ||
($forUntil = true && $this->literal('to'))) &&
$this->expression($end) &&
$this->literal('{')
) {
$for = $this->pushSpecialBlock(Type::T_FOR, $s);
$for->var = $varName[1];
$for->start = $start;
$for->end = $end;
$for->until = isset($forUntil);
return true;
}
$this->seek($s);
if ($this->literal('@if') && $this->valueList($cond) && $this->literal('{')) {
$if = $this->pushSpecialBlock(Type::T_IF, $s);
$if->cond = $cond;
$if->cases = [];
return true;
}
$this->seek($s);
if ($this->literal('@debug') &&
$this->valueList($value) &&
$this->end()
) {
$this->append([Type::T_DEBUG, $value], $s);
return true;
}
$this->seek($s);
if ($this->literal('@warn') &&
$this->valueList($value) &&
$this->end()
) {
$this->append([Type::T_WARN, $value], $s);
return true;
}
$this->seek($s);
if ($this->literal('@error') &&
$this->valueList($value) &&
$this->end()
) {
$this->append([Type::T_ERROR, $value], $s);
return true;
}
$this->seek($s);
if ($this->literal('@content') && $this->end()) {
$this->append([Type::T_MIXIN_CONTENT], $s);
return true;
}
$this->seek($s);
$last = $this->last();
if (isset($last) && $last[0] === Type::T_IF) {
list(, $if) = $last;
if ($this->literal('@else')) {
if ($this->literal('{')) {
$else = $this->pushSpecialBlock(Type::T_ELSE, $s);
} elseif ($this->literal('if') && $this->valueList($cond) && $this->literal('{')) {
$else = $this->pushSpecialBlock(Type::T_ELSEIF, $s);
$else->cond = $cond;
}
if (isset($else)) {
$else->dontAppend = true;
$if->cases[] = $else;
return true;
}
}
$this->seek($s);
}
// only retain the first @charset directive encountered
if ($this->literal('@charset') &&
$this->valueList($charset) &&
$this->end()
) {
if (! isset($this->charset)) {
$statement = [Type::T_CHARSET, $charset];
list($line, $column) = $this->getSourcePosition($s);
$statement[static::SOURCE_LINE] = $line;
$statement[static::SOURCE_COLUMN] = $column;
$statement[static::SOURCE_INDEX] = $this->sourceIndex;
$this->charset = $statement;
}
return true;
}
$this->seek($s);
// doesn't match built in directive, do generic one
if ($this->literal('@', false) &&
$this->keyword($dirName) &&
($this->variable($dirValue) || $this->openString('{', $dirValue) || true) &&
$this->literal('{')
) {
if ($dirName === 'media') {
$directive = $this->pushSpecialBlock(Type::T_MEDIA, $s);
} else {
$directive = $this->pushSpecialBlock(Type::T_DIRECTIVE, $s);
$directive->name = $dirName;
}
if (isset($dirValue)) {
$directive->value = $dirValue;
}
return true;
}
$this->seek($s);
return false;
}
// property shortcut
// captures most properties before having to parse a selector
if ($this->keyword($name, false) &&
$this->literal(': ') &&
$this->valueList($value) &&
$this->end()
) {
$name = [Type::T_STRING, '', [$name]];
$this->append([Type::T_ASSIGN, $name, $value], $s);
return true;
}
$this->seek($s);
// variable assigns
if ($this->variable($name) &&
$this->literal(':') &&
$this->valueList($value) &&
$this->end()
) {
// check for '!flag'
$assignmentFlags = $this-><API key>($value);
$this->append([Type::T_ASSIGN, $name, $value, $assignmentFlags], $s);
return true;
}
$this->seek($s);
// misc
if ($this->literal('
return true;
}
// opening css block
if ($this->selectors($selectors) && $this->literal('{')) {
$this->pushBlock($selectors, $s);
return true;
}
$this->seek($s);
// property assign, or nested assign
if ($this->propertyName($name) && $this->literal(':')) {
$foundSomething = false;
if ($this->valueList($value)) {
$this->append([Type::T_ASSIGN, $name, $value], $s);
$foundSomething = true;
}
if ($this->literal('{')) {
$propBlock = $this->pushSpecialBlock(Type::T_NESTED_PROPERTY, $s);
$propBlock->prefix = $name;
$foundSomething = true;
} elseif ($foundSomething) {
$foundSomething = $this->end();
}
if ($foundSomething) {
return true;
}
}
$this->seek($s);
// closing a block
if ($this->literal('}')) {
$block = $this->popBlock();
if (isset($block->type) && $block->type === Type::T_INCLUDE) {
$include = $block->child;
unset($block->child);
$include[3] = $block;
$this->append($include, $s);
} elseif (empty($block->dontAppend)) {
$type = isset($block->type) ? $block->type : Type::T_BLOCK;
$this->append([$type, $block], $s);
}
return true;
}
// extra stuff
if ($this->literal(';') ||
$this->literal('<!
) {
return true;
}
return false;
}
/**
* Push block onto parse tree
*
* @param array $selectors
* @param integer $pos
*
* @return \Leafo\ScssPhp\Block
*/
protected function pushBlock($selectors, $pos = 0)
{
list($line, $column) = $this->getSourcePosition($pos);
$b = new Block;
$b->sourceName = $this->sourceName;
$b->sourceLine = $line;
$b->sourceColumn = $column;
$b->sourceIndex = $this->sourceIndex;
$b->selectors = $selectors;
$b->comments = [];
$b->parent = $this->env;
if (! $this->env) {
$b->children = [];
} elseif (empty($this->env->children)) {
$this->env->children = $this->env->comments;
$b->children = [];
$this->env->comments = [];
} else {
$b->children = $this->env->comments;
$this->env->comments = [];
}
$this->env = $b;
return $b;
}
/**
* Push special (named) block onto parse tree
*
* @param string $type
* @param integer $pos
*
* @return \Leafo\ScssPhp\Block
*/
protected function pushSpecialBlock($type, $pos)
{
$block = $this->pushBlock(null, $pos);
$block->type = $type;
return $block;
}
/**
* Pop scope and return last block
*
* @return \Leafo\ScssPhp\Block
*
* @throws \Exception
*/
protected function popBlock()
{
$block = $this->env;
if (empty($block->parent)) {
$this->throwParseError('unexpected }');
}
$this->env = $block->parent;
unset($block->parent);
$comments = $block->comments;
if (count($comments)) {
$this->env->comments = $comments;
unset($block->comments);
}
return $block;
}
/**
* Peek input stream
*
* @param string $regex
* @param array $out
* @param integer $from
*
* @return integer
*/
protected function peek($regex, &$out, $from = null)
{
if (! isset($from)) {
$from = $this->count;
}
$r = '/' . $regex . '/' . $this->patternModifiers;
$result = preg_match($r, $this->buffer, $out, null, $from);
return $result;
}
/**
* Seek to position in input stream (or return current position in input stream)
*
* @param integer $where
*
* @return integer
*/
protected function seek($where = null)
{
if ($where === null) {
return $this->count;
}
$this->count = $where;
return true;
}
/**
* Match string looking for either ending delim, escape, or string interpolation
*
* {@internal This is a workaround for preg_match's 250K string match limit. }}
*
* @param array $m Matches (passed by reference)
* @param string $delim Delimeter
*
* @return boolean True if match; false otherwise
*/
protected function matchString(&$m, $delim)
{
$token = null;
$end = strlen($this->buffer);
// look for either ending delim, escape, or string interpolation
foreach (['#{', '\\', $delim] as $lookahead) {
$pos = strpos($this->buffer, $lookahead, $this->count);
if ($pos !== false && $pos < $end) {
$end = $pos;
$token = $lookahead;
}
}
if (! isset($token)) {
return false;
}
$match = substr($this->buffer, $this->count, $end - $this->count);
$m = [
$match . $token,
$match,
$token
];
$this->count = $end + strlen($token);
return true;
}
/**
* Try to match something on head of buffer
*
* @param string $regex
* @param array $out
* @param boolean $eatWhitespace
*
* @return boolean
*/
protected function match($regex, &$out, $eatWhitespace = null)
{
if (! isset($eatWhitespace)) {
$eatWhitespace = $this->eatWhiteDefault;
}
$r = '/' . $regex . '/' . $this->patternModifiers;
if (preg_match($r, $this->buffer, $out, null, $this->count)) {
$this->count += strlen($out[0]);
if ($eatWhitespace) {
$this->whitespace();
}
return true;
}
return false;
}
/**
* Match literal string
*
* @param string $what
* @param boolean $eatWhitespace
*
* @return boolean
*/
protected function literal($what, $eatWhitespace = null)
{
if (! isset($eatWhitespace)) {
$eatWhitespace = $this->eatWhiteDefault;
}
$len = strlen($what);
if (strcasecmp(substr($this->buffer, $this->count, $len), $what) === 0) {
$this->count += $len;
if ($eatWhitespace) {
$this->whitespace();
}
return true;
}
return false;
}
/**
* Match some whitespace
*
* @return boolean
*/
protected function whitespace()
{
$gotWhite = false;
while (preg_match(static::$whitePattern, $this->buffer, $m, null, $this->count)) {
if (isset($m[1]) && empty($this->commentsSeen[$this->count])) {
$this->appendComment([Type::T_COMMENT, $m[1]]);
$this->commentsSeen[$this->count] = true;
}
$this->count += strlen($m[0]);
$gotWhite = true;
}
return $gotWhite;
}
/**
* Append comment to current block
*
* @param array $comment
*/
protected function appendComment($comment)
{
$comment[1] = substr(preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], $comment[1]), 1);
$this->env->comments[] = $comment;
}
/**
* Append statement to current block
*
* @param array $statement
* @param integer $pos
*/
protected function append($statement, $pos = null)
{
if ($pos !== null) {
list($line, $column) = $this->getSourcePosition($pos);
$statement[static::SOURCE_LINE] = $line;
$statement[static::SOURCE_COLUMN] = $column;
$statement[static::SOURCE_INDEX] = $this->sourceIndex;
}
$this->env->children[] = $statement;
$comments = $this->env->comments;
if (count($comments)) {
$this->env->children = array_merge($this->env->children, $comments);
$this->env->comments = [];
}
}
/**
* Returns last child was appended
*
* @return array|null
*/
protected function last()
{
$i = count($this->env->children) - 1;
if (isset($this->env->children[$i])) {
return $this->env->children[$i];
}
}
/**
* Parse media query list
*
* @param array $out
*
* @return boolean
*/
protected function mediaQueryList(&$out)
{
return $this->genericList($out, 'mediaQuery', ',', false);
}
/**
* Parse media query
*
* @param array $out
*
* @return boolean
*/
protected function mediaQuery(&$out)
{
$expressions = null;
$parts = [];
if (($this->literal('only') && ($only = true) || $this->literal('not') && ($not = true) || true) &&
$this->mixedKeyword($mediaType)
) {
$prop = [Type::T_MEDIA_TYPE];
if (isset($only)) {
$prop[] = [Type::T_KEYWORD, 'only'];
}
if (isset($not)) {
$prop[] = [Type::T_KEYWORD, 'not'];
}
$media = [Type::T_LIST, '', []];
foreach ((array) $mediaType as $type) {
if (is_array($type)) {
$media[2][] = $type;
} else {
$media[2][] = [Type::T_KEYWORD, $type];
}
}
$prop[] = $media;
$parts[] = $prop;
}
if (empty($parts) || $this->literal('and')) {
$this->genericList($expressions, 'mediaExpression', 'and', false);
if (is_array($expressions)) {
$parts = array_merge($parts, $expressions[2]);
}
}
$out = $parts;
return true;
}
/**
* Parse media expression
*
* @param array $out
*
* @return boolean
*/
protected function mediaExpression(&$out)
{
$s = $this->seek();
$value = null;
if ($this->literal('(') &&
$this->expression($feature) &&
($this->literal(':') && $this->expression($value) || true) &&
$this->literal(')')
) {
$out = [Type::T_MEDIA_EXPRESSION, $feature];
if ($value) {
$out[] = $value;
}
return true;
}
$this->seek($s);
return false;
}
/**
* Parse argument values
*
* @param array $out
*
* @return boolean
*/
protected function argValues(&$out)
{
if ($this->genericList($list, 'argValue', ',', false)) {
$out = $list[2];
return true;
}
return false;
}
/**
* Parse argument value
*
* @param array $out
*
* @return boolean
*/
protected function argValue(&$out)
{
$s = $this->seek();
$keyword = null;
if (! $this->variable($keyword) || ! $this->literal(':')) {
$this->seek($s);
$keyword = null;
}
if ($this->genericList($value, 'expression')) {
$out = [$keyword, $value, false];
$s = $this->seek();
if ($this->literal('...')) {
$out[2] = true;
} else {
$this->seek($s);
}
return true;
}
return false;
}
/**
* Parse comma separated value list
*
* @param string $out
*
* @return boolean
*/
protected function valueList(&$out)
{
return $this->genericList($out, 'spaceList', ',');
}
/**
* Parse space separated value list
*
* @param array $out
*
* @return boolean
*/
protected function spaceList(&$out)
{
return $this->genericList($out, 'expression');
}
/**
* Parse generic list
*
* @param array $out
* @param callable $parseItem
* @param string $delim
* @param boolean $flatten
*
* @return boolean
*/
protected function genericList(&$out, $parseItem, $delim = '', $flatten = true)
{
$s = $this->seek();
$items = [];
while ($this->$parseItem($value)) {
$items[] = $value;
if ($delim) {
if (! $this->literal($delim)) {
break;
}
}
}
if (count($items) === 0) {
$this->seek($s);
return false;
}
if ($flatten && count($items) === 1) {
$out = $items[0];
} else {
$out = [Type::T_LIST, $delim, $items];
}
return true;
}
/**
* Parse expression
*
* @param array $out
*
* @return boolean
*/
protected function expression(&$out)
{
$s = $this->seek();
if ($this->literal('(')) {
if ($this->literal(')')) {
$out = [Type::T_LIST, '', []];
return true;
}
if ($this->valueList($out) && $this->literal(')') && $out[0] === Type::T_LIST) {
return true;
}
$this->seek($s);
if ($this->map($out)) {
return true;
}
$this->seek($s);
}
if ($this->value($lhs)) {
$out = $this->expHelper($lhs, 0);
return true;
}
return false;
}
/**
* Parse left-hand side of subexpression
*
* @param array $lhs
* @param integer $minP
*
* @return array
*/
protected function expHelper($lhs, $minP)
{
$operators = static::$operatorPattern;
$ss = $this->seek();
$whiteBefore = isset($this->buffer[$this->count - 1]) &&
ctype_space($this->buffer[$this->count - 1]);
while ($this->match($operators, $m, false) && static::$precedence[$m[1]] >= $minP) {
$whiteAfter = isset($this->buffer[$this->count]) &&
ctype_space($this->buffer[$this->count]);
$varAfter = isset($this->buffer[$this->count]) &&
$this->buffer[$this->count] === '$';
$this->whitespace();
$op = $m[1];
// don't turn negative numbers into expressions
if ($op === '-' && $whiteBefore && ! $whiteAfter && ! $varAfter) {
break;
}
if (! $this->value($rhs)) {
break;
}
// peek and see if rhs belongs to next operator
if ($this->peek($operators, $next) && static::$precedence[$next[1]] > static::$precedence[$op]) {
$rhs = $this->expHelper($rhs, static::$precedence[$next[1]]);
}
$lhs = [Type::T_EXPRESSION, $op, $lhs, $rhs, $this->inParens, $whiteBefore, $whiteAfter];
$ss = $this->seek();
$whiteBefore = isset($this->buffer[$this->count - 1]) &&
ctype_space($this->buffer[$this->count - 1]);
}
$this->seek($ss);
return $lhs;
}
/**
* Parse value
*
* @param array $out
*
* @return boolean
*/
protected function value(&$out)
{
$s = $this->seek();
if ($this->literal('not', false) && $this->whitespace() && $this->value($inner)) {
$out = [Type::T_UNARY, 'not', $inner, $this->inParens];
return true;
}
$this->seek($s);
if ($this->literal('not', false) && $this->parenValue($inner)) {
$out = [Type::T_UNARY, 'not', $inner, $this->inParens];
return true;
}
$this->seek($s);
if ($this->literal('+') && $this->value($inner)) {
$out = [Type::T_UNARY, '+', $inner, $this->inParens];
return true;
}
$this->seek($s);
// negation
if ($this->literal('-', false) &&
($this->variable($inner) ||
$this->unit($inner) ||
$this->parenValue($inner))
) {
$out = [Type::T_UNARY, '-', $inner, $this->inParens];
return true;
}
$this->seek($s);
if ($this->parenValue($out) ||
$this->interpolation($out) ||
$this->variable($out) ||
$this->color($out) ||
$this->unit($out) ||
$this->string($out) ||
$this->func($out) ||
$this->progid($out)
) {
return true;
}
if ($this->keyword($keyword)) {
if ($keyword === 'null') {
$out = [Type::T_NULL];
} else {
$out = [Type::T_KEYWORD, $keyword];
}
return true;
}
return false;
}
/**
* Parse parenthesized value
*
* @param array $out
*
* @return boolean
*/
protected function parenValue(&$out)
{
$s = $this->seek();
$inParens = $this->inParens;
if ($this->literal('(')) {
if ($this->literal(')')) {
$out = [Type::T_LIST, '', []];
return true;
}
$this->inParens = true;
if ($this->expression($exp) && $this->literal(')')) {
$out = $exp;
$this->inParens = $inParens;
return true;
}
}
$this->inParens = $inParens;
$this->seek($s);
return false;
}
/**
* Parse "progid:"
*
* @param array $out
*
* @return boolean
*/
protected function progid(&$out)
{
$s = $this->seek();
if ($this->literal('progid:', false) &&
$this->openString('(', $fn) &&
$this->literal('(')
) {
$this->openString(')', $args, '(');
if ($this->literal(')')) {
$out = [Type::T_STRING, '', [
'progid:', $fn, '(', $args, ')'
]];
return true;
}
}
$this->seek($s);
return false;
}
/**
* Parse function call
*
* @param array $out
*
* @return boolean
*/
protected function func(&$func)
{
$s = $this->seek();
if ($this->keyword($name, false) &&
$this->literal('(')
) {
if ($name === 'alpha' && $this->argumentList($args)) {
$func = [Type::T_FUNCTION, $name, [Type::T_STRING, '', $args]];
return true;
}
if ($name !== 'expression' && ! preg_match('/^(-[a-z]+-)?calc$/', $name)) {
$ss = $this->seek();
if ($this->argValues($args) && $this->literal(')')) {
$func = [Type::T_FUNCTION_CALL, $name, $args];
return true;
}
$this->seek($ss);
}
if (($this->openString(')', $str, '(') || true) &&
$this->literal(')')
) {
$args = [];
if (! empty($str)) {
$args[] = [null, [Type::T_STRING, '', [$str]]];
}
$func = [Type::T_FUNCTION_CALL, $name, $args];
return true;
}
}
$this->seek($s);
return false;
}
/**
* Parse function call argument list
*
* @param array $out
*
* @return boolean
*/
protected function argumentList(&$out)
{
$s = $this->seek();
$this->literal('(');
$args = [];
while ($this->keyword($var)) {
if ($this->literal('=') && $this->expression($exp)) {
$args[] = [Type::T_STRING, '', [$var . '=']];
$arg = $exp;
} else {
break;
}
$args[] = $arg;
if (! $this->literal(',')) {
break;
}
$args[] = [Type::T_STRING, '', [', ']];
}
if (! $this->literal(')') || ! count($args)) {
$this->seek($s);
return false;
}
$out = $args;
return true;
}
/**
* Parse mixin/function definition argument list
*
* @param array $out
*
* @return boolean
*/
protected function argumentDef(&$out)
{
$s = $this->seek();
$this->literal('(');
$args = [];
while ($this->variable($var)) {
$arg = [$var[1], null, false];
$ss = $this->seek();
if ($this->literal(':') && $this->genericList($defaultVal, 'expression')) {
$arg[1] = $defaultVal;
} else {
$this->seek($ss);
}
$ss = $this->seek();
if ($this->literal('...')) {
$sss = $this->seek();
if (! $this->literal(')')) {
$this->throwParseError('... has to be after the final argument');
}
$arg[2] = true;
$this->seek($sss);
} else {
$this->seek($ss);
}
$args[] = $arg;
if (! $this->literal(',')) {
break;
}
}
if (! $this->literal(')')) {
$this->seek($s);
return false;
}
$out = $args;
return true;
}
/**
* Parse map
*
* @param array $out
*
* @return boolean
*/
protected function map(&$out)
{
$s = $this->seek();
if (! $this->literal('(')) {
return false;
}
$keys = [];
$values = [];
while ($this->genericList($key, 'expression') && $this->literal(':') &&
$this->genericList($value, 'expression')
) {
$keys[] = $key;
$values[] = $value;
if (! $this->literal(',')) {
break;
}
}
if (! count($keys) || ! $this->literal(')')) {
$this->seek($s);
return false;
}
$out = [Type::T_MAP, $keys, $values];
return true;
}
/**
* Parse color
*
* @param array $out
*
* @return boolean
*/
protected function color(&$out)
{
$color = [Type::T_COLOR];
if ($this->match('(#([0-9a-f]{6})|#([0-9a-f]{3}))', $m)) {
if (isset($m[3])) {
$num = hexdec($m[3]);
foreach ([3, 2, 1] as $i) {
$t = $num & 0xf;
$color[$i] = $t << 4 | $t;
$num >>= 4;
}
} else {
$num = hexdec($m[2]);
foreach ([3, 2, 1] as $i) {
$color[$i] = $num & 0xff;
$num >>= 8;
}
}
$out = $color;
return true;
}
return false;
}
/**
* Parse number with unit
*
* @param array $out
*
* @return boolean
*/
protected function unit(&$unit)
{
if ($this->match('([0-9]*(\.)?[0-9]+)([%a-zA-Z]+)?', $m)) {
$unit = new Node\Number($m[1], empty($m[3]) ? '' : $m[3]);
return true;
}
return false;
}
/**
* Parse string
*
* @param array $out
*
* @return boolean
*/
protected function string(&$out)
{
$s = $this->seek();
if ($this->literal('"', false)) {
$delim = '"';
} elseif ($this->literal("'", false)) {
$delim = "'";
} else {
return false;
}
$content = [];
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
$hasInterpolation = false;
while ($this->matchString($m, $delim)) {
if ($m[1] !== '') {
$content[] = $m[1];
}
if ($m[2] === '
$this->count -= strlen($m[2]);
if ($this->interpolation($inter, false)) {
$content[] = $inter;
$hasInterpolation = true;
} else {
$this->count += strlen($m[2]);
$content[] = '#{'; // ignore it
}
} elseif ($m[2] === '\\') {
if ($this->literal('"', false)) {
$content[] = $m[2] . '"';
} elseif ($this->literal("'", false)) {
$content[] = $m[2] . "'";
} else {
$content[] = $m[2];
}
} else {
$this->count -= strlen($delim);
break; // delim
}
}
$this->eatWhiteDefault = $oldWhite;
if ($this->literal($delim)) {
if ($hasInterpolation) {
$delim = '"';
foreach ($content as &$string) {
if ($string === "\\'") {
$string = "'";
} elseif ($string === '\\"') {
$string = '"';
}
}
}
$out = [Type::T_STRING, $delim, $content];
return true;
}
$this->seek($s);
return false;
}
/**
* Parse keyword or interpolation
*
* @param array $out
*
* @return boolean
*/
protected function mixedKeyword(&$out)
{
$parts = [];
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
for (;;) {
if ($this->keyword($key)) {
$parts[] = $key;
continue;
}
if ($this->interpolation($inter)) {
$parts[] = $inter;
continue;
}
break;
}
$this->eatWhiteDefault = $oldWhite;
if (count($parts) === 0) {
return false;
}
if ($this->eatWhiteDefault) {
$this->whitespace();
}
$out = $parts;
return true;
}
/**
* Parse an unbounded string stopped by $end
*
* @param string $end
* @param array $out
* @param string $nestingOpen
*
* @return boolean
*/
protected function openString($end, &$out, $nestingOpen = null)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
$patt = '(.*?)([\'"]|#\{|' . $this->pregQuote($end) . '|' . static::$commentPattern . ')';
$nestingLevel = 0;
$content = [];
while ($this->match($patt, $m, false)) {
if (isset($m[1]) && $m[1] !== '') {
$content[] = $m[1];
if ($nestingOpen) {
$nestingLevel += substr_count($m[1], $nestingOpen);
}
}
$tok = $m[2];
$this->count-= strlen($tok);
if ($tok === $end && ! $nestingLevel
break;
}
if (($tok === "'" || $tok === '"') && $this->string($str)) {
$content[] = $str;
continue;
}
if ($tok === '#{' && $this->interpolation($inter)) {
$content[] = $inter;
continue;
}
$content[] = $tok;
$this->count+= strlen($tok);
}
$this->eatWhiteDefault = $oldWhite;
if (count($content) === 0) {
return false;
}
// trim the end
if (is_string(end($content))) {
$content[count($content) - 1] = rtrim(end($content));
}
$out = [Type::T_STRING, '', $content];
return true;
}
/**
* Parser interpolation
*
* @param array $out
* @param boolean $lookWhite save information about whitespace before and after
*
* @return boolean
*/
protected function interpolation(&$out, $lookWhite = true)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = true;
$s = $this->seek();
if ($this->literal('#{') && $this->valueList($value) && $this->literal('}', false)) {
if ($lookWhite) {
$left = preg_match('/\s/', $this->buffer[$s - 1]) ? ' ' : '';
$right = preg_match('/\s/', $this->buffer[$this->count]) ? ' ': '';
} else {
$left = $right = false;
}
$out = [Type::T_INTERPOLATE, $value, $left, $right];
$this->eatWhiteDefault = $oldWhite;
if ($this->eatWhiteDefault) {
$this->whitespace();
}
return true;
}
$this->seek($s);
$this->eatWhiteDefault = $oldWhite;
return false;
}
/**
* Parse property name (as an array of parts or a string)
*
* @param array $out
*
* @return boolean
*/
protected function propertyName(&$out)
{
$parts = [];
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
for (;;) {
if ($this->interpolation($inter)) {
$parts[] = $inter;
continue;
}
if ($this->keyword($text)) {
$parts[] = $text;
continue;
}
if (count($parts) === 0 && $this->match('[:.#]', $m, false)) {
// css hacks
$parts[] = $m[0];
continue;
}
break;
}
$this->eatWhiteDefault = $oldWhite;
if (count($parts) === 0) {
return false;
}
// match comment hack
if (preg_match(
static::$whitePattern,
$this->buffer,
$m,
null,
$this->count
)) {
if (! empty($m[0])) {
$parts[] = $m[0];
$this->count += strlen($m[0]);
}
}
$this->whitespace(); // get any extra whitespace
$out = [Type::T_STRING, '', $parts];
return true;
}
/**
* Parse comma separated selector list
*
* @param array $out
*
* @return boolean
*/
protected function selectors(&$out)
{
$s = $this->seek();
$selectors = [];
while ($this->selector($sel)) {
$selectors[] = $sel;
if (! $this->literal(',')) {
break;
}
while ($this->literal(',')) {
; // ignore extra
}
}
if (count($selectors) === 0) {
$this->seek($s);
return false;
}
$out = $selectors;
return true;
}
/**
* Parse whitespace separated selector list
*
* @param array $out
*
* @return boolean
*/
protected function selector(&$out)
{
$selector = [];
for (;;) {
if ($this->match('[>+~]+', $m)) {
$selector[] = [$m[0]];
continue;
}
if ($this->selectorSingle($part)) {
$selector[] = $part;
$this->match('\s+', $m);
continue;
}
if ($this->match('\/[^\/]+\/', $m)) {
$selector[] = [$m[0]];
continue;
}
break;
}
if (count($selector) === 0) {
return false;
}
$out = $selector;
return true;
}
/**
* Parse the parts that make up a selector
*
* {@internal
* div[yes=no]#something.hello.world:nth-child(-2n+1)%placeholder
* }}
*
* @param array $out
*
* @return boolean
*/
protected function selectorSingle(&$out)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
$parts = [];
if ($this->literal('*', false)) {
$parts[] = '*';
}
for (;;) {
// see if we can stop early
if ($this->match('\s*[{,]', $m)) {
$this->count
break;
}
$s = $this->seek();
// self
if ($this->literal('&', false)) {
$parts[] = Compiler::$selfSelector;
continue;
}
if ($this->literal('.', false)) {
$parts[] = '.';
continue;
}
if ($this->literal('|', false)) {
$parts[] = '|';
continue;
}
if ($this->match('\\\\\S', $m)) {
$parts[] = $m[0];
continue;
}
// for keyframes
if ($this->unit($unit)) {
$parts[] = $unit;
continue;
}
if ($this->keyword($name)) {
$parts[] = $name;
continue;
}
if ($this->interpolation($inter)) {
$parts[] = $inter;
continue;
}
if ($this->literal('%', false) && $this->placeholder($placeholder)) {
$parts[] = '%';
$parts[] = $placeholder;
continue;
}
if ($this->literal('#', false)) {
$parts[] = '
continue;
}
// a pseudo selector
if ($this->match('::?', $m) && $this->mixedKeyword($nameParts)) {
$parts[] = $m[0];
foreach ($nameParts as $sub) {
$parts[] = $sub;
}
$ss = $this->seek();
if ($this->literal('(') &&
($this->openString(')', $str, '(') || true) &&
$this->literal(')')
) {
$parts[] = '(';
if (! empty($str)) {
$parts[] = $str;
}
$parts[] = ')';
} else {
$this->seek($ss);
}
continue;
}
$this->seek($s);
// attribute selector
if ($this->literal('[') &&
($this->openString(']', $str, '[') || true) &&
$this->literal(']')
) {
$parts[] = '[';
if (! empty($str)) {
$parts[] = $str;
}
$parts[] = ']';
continue;
}
$this->seek($s);
break;
}
$this->eatWhiteDefault = $oldWhite;
if (count($parts) === 0) {
return false;
}
$out = $parts;
return true;
}
/**
* Parse a variable
*
* @param array $out
*
* @return boolean
*/
protected function variable(&$out)
{
$s = $this->seek();
if ($this->literal('$', false) && $this->keyword($name)) {
$out = [Type::T_VARIABLE, $name];
return true;
}
$this->seek($s);
return false;
}
/**
* Parse a keyword
*
* @param string $word
* @param boolean $eatWhitespace
*
* @return boolean
*/
protected function keyword(&$word, $eatWhitespace = null)
{
if ($this->match(
$this->utf8
? '(([\pL\w_\-\*!"\']|[\\\\].)([\pL\w\-_"\']|[\\\\].)*)'
: '(([\w_\-\*!"\']|[\\\\].)([\w\-_"\']|[\\\\].)*)',
$m,
$eatWhitespace
)) {
$word = $m[1];
return true;
}
return false;
}
/**
* Parse a placeholder
*
* @param string $placeholder
*
* @return boolean
*/
protected function placeholder(&$placeholder)
{
if ($this->match(
$this->utf8
? '([\pL\w\-_]+|#[{][$][\pL\w\-_]+[}])'
: '([\w\-_]+|
$m
)) {
$placeholder = $m[1];
return true;
}
return false;
}
/**
* Parse a url
*
* @param array $out
*
* @return boolean
*/
protected function url(&$out)
{
if ($this->match('(url\(\s*(["\']?)([^)]+)\2\s*\))', $m)) {
$out = [Type::T_STRING, '', ['url(' . $m[2] . $m[3] . $m[2] . ')']];
return true;
}
return false;
}
/**
* Consume an end of statement delimiter
*
* @return boolean
*/
protected function end()
{
if ($this->literal(';')) {
return true;
}
if ($this->count === strlen($this->buffer) || $this->buffer[$this->count] === '}') {
// if there is end of file or a closing block next then we don't need a ;
return true;
}
return false;
}
/**
* Strip assignment flag from the list
*
* @param array $value
*
* @return array
*/
protected function <API key>(&$value)
{
$flags = [];
for ($token = &$value; $token[0] === Type::T_LIST && ($s = count($token[2])); $token = &$lastNode) {
$lastNode = &$token[2][$s - 1];
while ($lastNode[0] === Type::T_KEYWORD && in_array($lastNode[1], ['!default', '!global'])) {
array_pop($token[2]);
$node = end($token[2]);
$token = $this->flattenList($token);
$flags[] = $lastNode[1];
$lastNode = $node;
}
}
return $flags;
}
/**
* Strip optional flag from selector list
*
* @param array $selectors
*
* @return string
*/
protected function stripOptionalFlag(&$selectors)
{
$optional = false;
$selector = end($selectors);
$part = end($selector);
if ($part === ['!optional']) {
array_pop($selectors[count($selectors) - 1]);
$optional = true;
}
return $optional;
}
/**
* Turn list of length 1 into value type
*
* @param array $value
*
* @return array
*/
protected function flattenList($value)
{
if ($value[0] === Type::T_LIST && count($value[2]) === 1) {
return $this->flattenList($value[2][0]);
}
return $value;
}
/**
* @deprecated
*
* {@internal
* advance counter to next occurrence of $what
* $until - don't include $what in advance
* $allowNewline, if string, will be used as valid char set
* }}
*/
protected function to($what, &$out, $until = false, $allowNewline = false)
{
if (is_string($allowNewline)) {
$validChars = $allowNewline;
} else {
$validChars = $allowNewline ? '.' : "[^\n]";
}
if (! $this->match('(' . $validChars . '*?)' . $this->pregQuote($what), $m, ! $until)) {
return false;
}
if ($until) {
$this->count -= strlen($what); // give back $what
}
$out = $m[1];
return true;
}
/**
* @deprecated
*/
protected function show()
{
if ($this->peek("(.*?)(\n|$)", $m, $this->count)) {
return $m[1];
}
return '';
}
/**
* Quote regular expression
*
* @param string $what
*
* @return string
*/
private function pregQuote($what)
{
return preg_quote($what, '/');
}
/**
* Extract line numbers from buffer
*
* @param string $buffer
*/
private function extractLineNumbers($buffer)
{
$this->sourcePositions = [0 => 0];
$prev = 0;
while (($pos = strpos($buffer, "\n", $prev)) !== false) {
$this->sourcePositions[] = $pos;
$prev = $pos + 1;
}
$this->sourcePositions[] = strlen($buffer);
if (substr($buffer, -1) !== "\n") {
$this->sourcePositions[] = strlen($buffer) + 1;
}
}
/**
* Get source line number and column (given character position in the buffer)
*
* @param integer $pos
*
* @return integer
*/
private function getSourcePosition($pos)
{
$low = 0;
$high = count($this->sourcePositions);
while ($low < $high) {
$mid = (int) (($high + $low) / 2);
if ($pos < $this->sourcePositions[$mid]) {
$high = $mid - 1;
continue;
}
if ($pos >= $this->sourcePositions[$mid + 1]) {
$low = $mid + 1;
continue;
}
return [$mid + 1, $pos - $this->sourcePositions[$mid]];
}
return [$low + 1, $pos - $this->sourcePositions[$low]];
}
/**
* Save internal encoding
*/
private function saveEncoding()
{
if (version_compare(PHP_VERSION, '7.2.0') >= 0) {
return;
}
$iniDirective = 'mbstring' . '.func_overload'; // deprecated in PHP 7.2
if (ini_get($iniDirective) & 2) {
$this->encoding = <API key>();
<API key>('iso-8859-1');
}
}
/**
* Restore internal encoding
*/
private function restoreEncoding()
{
if ($this->encoding) {
<API key>($this->encoding);
}
}
}
|
/**
* @file
* SNMP Agent message handling structures.
*/
#ifndef __LWIP_SNMP_MSG_H__
#define __LWIP_SNMP_MSG_H__
#include "lwip/opt.h"
#include "lwip/snmp.h"
#include "lwip/snmp_structs.h"
#include "lwip/ip_addr.h"
#include "lwip/err.h"
#if LWIP_SNMP
#if SNMP_PRIVATE_MIB
/* When using a private MIB, you have to create a file 'private_mib.h' that contains
* a 'struct mib_array_node mib_private' which contains your MIB. */
#include "private_mib.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* The listen port of the SNMP agent. Clients have to make their requests to
this port. Most standard clients won't work if you change this! */
#ifndef SNMP_IN_PORT
#define SNMP_IN_PORT 161
#endif
/* The remote port the SNMP agent sends traps to. Most standard trap sinks won't
work if you change this! */
#ifndef SNMP_TRAP_PORT
#define SNMP_TRAP_PORT 162
#endif
#define SNMP_ES_NOERROR 0
#define SNMP_ES_TOOBIG 1
#define SNMP_ES_NOSUCHNAME 2
#define SNMP_ES_BADVALUE 3
#define SNMP_ES_READONLY 4
#define SNMP_ES_GENERROR 5
#define <API key> 0
#define <API key> 1
#define <API key> 4
#define <API key> 6
struct snmp_varbind
{
/* next pointer, NULL for last in list */
struct snmp_varbind *next;
/* previous pointer, NULL for first in list */
struct snmp_varbind *prev;
/* object identifier length (in s32_t) */
u8_t ident_len;
/* object identifier array */
s32_t *ident;
/* object value ASN1 type */
u8_t value_type;
/* object value length (in u8_t) */
u8_t value_len;
/* object value */
void *value;
/* encoding varbind seq length length */
u8_t seqlenlen;
/* encoding object identifier length length */
u8_t olenlen;
/* encoding object value length length */
u8_t vlenlen;
/* encoding varbind seq length */
u16_t seqlen;
/* encoding object identifier length */
u16_t olen;
/* encoding object value length */
u16_t vlen;
};
struct snmp_varbind_root
{
struct snmp_varbind *head;
struct snmp_varbind *tail;
/* number of variable bindings in list */
u8_t count;
/* encoding varbind-list seq length length */
u8_t seqlenlen;
/* encoding varbind-list seq length */
u16_t seqlen;
};
/** output response message header length fields */
struct <API key>
{
/* encoding error-index length length */
u8_t erridxlenlen;
/* encoding error-status length length */
u8_t errstatlenlen;
/* encoding request id length length */
u8_t ridlenlen;
/* encoding pdu length length */
u8_t pdulenlen;
/* encoding community length length */
u8_t comlenlen;
/* encoding version length length */
u8_t verlenlen;
/* encoding sequence length length */
u8_t seqlenlen;
/* encoding error-index length */
u16_t erridxlen;
/* encoding error-status length */
u16_t errstatlen;
/* encoding request id length */
u16_t ridlen;
/* encoding pdu length */
u16_t pdulen;
/* encoding community length */
u16_t comlen;
/* encoding version length */
u16_t verlen;
/* encoding sequence length */
u16_t seqlen;
};
/** output response message header length fields */
struct <API key>
{
/* encoding timestamp length length */
u8_t tslenlen;
/* encoding specific-trap length length */
u8_t strplenlen;
/* encoding generic-trap length length */
u8_t gtrplenlen;
/* encoding agent-addr length length */
u8_t aaddrlenlen;
/* encoding enterprise-id length length */
u8_t eidlenlen;
/* encoding pdu length length */
u8_t pdulenlen;
/* encoding community length length */
u8_t comlenlen;
/* encoding version length length */
u8_t verlenlen;
/* encoding sequence length length */
u8_t seqlenlen;
/* encoding timestamp length */
u16_t tslen;
/* encoding specific-trap length */
u16_t strplen;
/* encoding generic-trap length */
u16_t gtrplen;
/* encoding agent-addr length */
u16_t aaddrlen;
/* encoding enterprise-id length */
u16_t eidlen;
/* encoding pdu length */
u16_t pdulen;
/* encoding community length */
u16_t comlen;
/* encoding version length */
u16_t verlen;
/* encoding sequence length */
u16_t seqlen;
};
/* Accepting new SNMP messages. */
#define SNMP_MSG_EMPTY 0
/* Search for matching object for variable binding. */
#define SNMP_MSG_SEARCH_OBJ 1
/* Perform SNMP operation on in-memory object.
Pass-through states, for symmetry only. */
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
/* Perform SNMP operation on object located externally.
In theory this could be used for building a proxy agent.
Practical use is for an enterprise spc. app. gateway. */
#define <API key> 7
#define <API key> 8
#define <API key> 9
#define <API key> 10
#define <API key> 11
#define <API key> 64
struct snmp_msg_pstat
{
/* lwIP local port (161) binding */
struct udp_pcb *pcb;
/* source IP address */
ip_addr_t sip;
/* source UDP port */
u16_t sp;
/* request type */
u8_t rt;
/* request ID */
s32_t rid;
/* error status */
s32_t error_status;
/* error index */
s32_t error_index;
/* community name (zero terminated) */
u8_t community[<API key> + 1];
/* community string length (exclusive zero term) */
u8_t com_strlen;
/* one out of MSG_EMPTY, MSG_DEMUX, MSG_INTERNAL, MSG_EXTERNAL_x */
u8_t state;
/* saved arguments for MSG_EXTERNAL_x */
struct mib_external_node *ext_mib_node;
struct snmp_name_ptr ext_name_ptr;
struct obj_def ext_object_def;
struct snmp_obj_id ext_oid;
/* index into input variable binding list */
u8_t vb_idx;
/* ptr into input variable binding list */
struct snmp_varbind *vb_ptr;
/* list of variable bindings from input */
struct snmp_varbind_root invb;
/* list of variable bindings to output */
struct snmp_varbind_root outvb;
/* output response lengths used in ASN encoding */
struct <API key> rhl;
};
struct snmp_msg_trap
{
/* lwIP local port (161) binding */
struct udp_pcb *pcb;
/* destination IP address in network order */
ip_addr_t dip;
/* source enterprise ID (sysObjectID) */
struct snmp_obj_id *enterprise;
/* source IP address, raw network order format */
u8_t sip_raw[4];
/* generic trap code */
u32_t gen_trap;
/* specific trap code */
u32_t spc_trap;
/* timestamp */
u32_t ts;
/* list of variable bindings to output */
struct snmp_varbind_root outvb;
/* output trap lengths used in ASN encoding */
struct <API key> thl;
};
/** Agent Version constant, 0 = v1 oddity */
extern const s32_t snmp_version;
/** Agent default "public" community string */
extern const char <API key>[7];
extern struct snmp_msg_trap trap_msg;
/** Agent setup, start listening to port 161. */
void snmp_init(void);
void snmp_deinit(void);
void <API key>(u8_t dst_idx, u8_t enable);
void <API key>(u8_t dst_idx, ip_addr_t *dst);
/** Varbind-list functions. */
struct snmp_varbind* snmp_varbind_alloc(struct snmp_obj_id *oid, u8_t type, u8_t len);
void snmp_varbind_free(struct snmp_varbind *vb);
void <API key>(struct snmp_varbind_root *root);
void <API key>(struct snmp_varbind_root *root, struct snmp_varbind *vb);
struct snmp_varbind* <API key>(struct snmp_varbind_root *root);
/** Handle an internal (recv) or external (private response) event. */
void snmp_msg_event(u8_t request_id);
err_t snmp_send_response(struct snmp_msg_pstat *m_stat);
err_t snmp_send_trap(s8_t generic_trap, struct snmp_obj_id *eoid, s32_t specific_trap);
void snmp_coldstart_trap(void);
void snmp_authfail_trap(void);
#ifdef __cplusplus
}
#endif
#endif /* LWIP_SNMP */
#endif /* __LWIP_SNMP_MSG_H__ */
|
/**
* @file
* YUV and RGB subsampled formats conversion.
*
* @author Jose Fonseca <jfonseca@vmware.com>
*/
#include "util/u_format_yuv.h"
void
<API key>(float *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
float *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
float r, g0, g1, b;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
r = ubyte_to_float((value >> 0) & 0xff);
g0 = ubyte_to_float((value >> 8) & 0xff);
b = ubyte_to_float((value >> 16) & 0xff);
g1 = ubyte_to_float((value >> 24) & 0xff);
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 1.0f;
dst += 4;
dst[0] = r;
dst[1] = g1;
dst[2] = b;
dst[3] = 1.0f;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
r = ubyte_to_float((value >> 0) & 0xff);
g0 = ubyte_to_float((value >> 8) & 0xff);
b = ubyte_to_float((value >> 16) & 0xff);
g1 = ubyte_to_float((value >> 24) & 0xff);
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 1.0f;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
uint8_t *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
uint8_t r, g0, g1, b;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
r = (value >> 0) & 0xff;
g0 = (value >> 8) & 0xff;
b = (value >> 16) & 0xff;
g1 = (value >> 24) & 0xff;
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 0xff;
dst += 4;
dst[0] = r;
dst[1] = g1;
dst[2] = b;
dst[3] = 0xff;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
r = (value >> 0) & 0xff;
g0 = (value >> 8) & 0xff;
b = (value >> 16) & 0xff;
g1 = (value >> 24) & 0xff;
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 0xff;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const float *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const float *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
float r, g0, g1, b;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
r = 0.5f*(src[0] + src[4]);
g0 = src[1];
g1 = src[5];
b = 0.5f*(src[2] + src[6]);
value = float_to_ubyte(r);
value |= float_to_ubyte(g0) << 8;
value |= float_to_ubyte(b) << 16;
value |= float_to_ubyte(g1) << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
r = src[0];
g0 = src[1];
g1 = 0;
b = src[2];
value = float_to_ubyte(r);
value |= float_to_ubyte(g0) << 8;
value |= float_to_ubyte(b) << 16;
value |= float_to_ubyte(g1) << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const uint8_t *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
uint32_t r, g0, g1, b;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
r = (src[0] + src[4] + 1) >> 1;
g0 = src[1];
g1 = src[5];
b = (src[2] + src[6] + 1) >> 1;
value = r;
value |= g0 << 8;
value |= b << 16;
value |= g1 << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
r = src[0];
g0 = src[1];
g1 = 0;
b = src[2];
value = r;
value |= g0 << 8;
value |= b << 16;
value |= g1 << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(float *dst, const uint8_t *src,
unsigned i, unsigned j)
{
assert(i < 2);
assert(j < 1);
dst[0] = ubyte_to_float(src[0]);
dst[1] = ubyte_to_float(src[1 + 2*i]);
dst[2] = ubyte_to_float(src[2]);
dst[3] = 1.0f;
}
void
<API key>(float *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
float *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
float r, g0, g1, b;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
g0 = ubyte_to_float((value >> 0) & 0xff);
r = ubyte_to_float((value >> 8) & 0xff);
g1 = ubyte_to_float((value >> 16) & 0xff);
b = ubyte_to_float((value >> 24) & 0xff);
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 1.0f;
dst += 4;
dst[0] = r;
dst[1] = g1;
dst[2] = b;
dst[3] = 1.0f;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
g0 = ubyte_to_float((value >> 0) & 0xff);
r = ubyte_to_float((value >> 8) & 0xff);
g1 = ubyte_to_float((value >> 16) & 0xff);
b = ubyte_to_float((value >> 24) & 0xff);
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 1.0f;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
uint8_t *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
uint8_t r, g0, g1, b;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
g0 = (value >> 0) & 0xff;
r = (value >> 8) & 0xff;
g1 = (value >> 16) & 0xff;
b = (value >> 24) & 0xff;
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 0xff;
dst += 4;
dst[0] = r;
dst[1] = g1;
dst[2] = b;
dst[3] = 0xff;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
g0 = (value >> 0) & 0xff;
r = (value >> 8) & 0xff;
g1 = (value >> 16) & 0xff;
b = (value >> 24) & 0xff;
dst[0] = r;
dst[1] = g0;
dst[2] = b;
dst[3] = 0xff;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const float *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const float *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
float r, g0, g1, b;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
r = 0.5f*(src[0] + src[4]);
g0 = src[1];
g1 = src[5];
b = 0.5f*(src[2] + src[6]);
value = float_to_ubyte(g0);
value |= float_to_ubyte(r) << 8;
value |= float_to_ubyte(g1) << 16;
value |= float_to_ubyte(b) << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
r = src[0];
g0 = src[1];
g1 = 0;
b = src[2];
value = float_to_ubyte(g0);
value |= float_to_ubyte(r) << 8;
value |= float_to_ubyte(g1) << 16;
value |= float_to_ubyte(b) << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const uint8_t *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
uint32_t r, g0, g1, b;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
r = (src[0] + src[4] + 1) >> 1;
g0 = src[1];
g1 = src[5];
b = (src[2] + src[6] + 1) >> 1;
value = g0;
value |= r << 8;
value |= g1 << 16;
value |= b << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
r = src[0];
g0 = src[1];
g1 = 0;
b = src[2];
value = g0;
value |= r << 8;
value |= g1 << 16;
value |= b << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(float *dst, const uint8_t *src,
unsigned i, unsigned j)
{
assert(i < 2);
assert(j < 1);
dst[0] = ubyte_to_float(src[1]);
dst[1] = ubyte_to_float(src[0 + 2*i]);
dst[2] = ubyte_to_float(src[3]);
dst[3] = 1.0f;
}
void
<API key>(float *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
float *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
uint8_t y0, y1, u, v;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
u = (value >> 0) & 0xff;
y0 = (value >> 8) & 0xff;
v = (value >> 16) & 0xff;
y1 = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
dst += 4;
<API key>(y1, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
u = (value >> 0) & 0xff;
y0 = (value >> 8) & 0xff;
v = (value >> 16) & 0xff;
y1 = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
uint8_t *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
uint8_t y0, y1, u, v;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
u = (value >> 0) & 0xff;
y0 = (value >> 8) & 0xff;
v = (value >> 16) & 0xff;
y1 = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 0xff;
dst += 4;
<API key>(y1, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 0xff;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
u = (value >> 0) & 0xff;
y0 = (value >> 8) & 0xff;
v = (value >> 16) & 0xff;
y1 = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 0xff;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const float *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const float *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
uint8_t y0, y1, u, v;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
uint8_t y0, y1, u0, u1, v0, v1, u, v;
<API key>(src[0], src[1], src[2],
&y0, &u0, &v0);
<API key>(src[4], src[5], src[6],
&y1, &u1, &v1);
u = (u0 + u1 + 1) >> 1;
v = (v0 + v1 + 1) >> 1;
value = u;
value |= y0 << 8;
value |= v << 16;
value |= y1 << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
<API key>(src[0], src[1], src[2],
&y0, &u, &v);
y1 = 0;
value = u;
value |= y0 << 8;
value |= v << 16;
value |= y1 << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const uint8_t *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
uint8_t y0, y1, u, v;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
uint8_t y0, y1, u0, u1, v0, v1, u, v;
<API key>(src[0], src[1], src[2],
&y0, &u0, &v0);
<API key>(src[4], src[5], src[6],
&y1, &u1, &v1);
u = (u0 + u1 + 1) >> 1;
v = (v0 + v1 + 1) >> 1;
value = u;
value |= y0 << 8;
value |= v << 16;
value |= y1 << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
<API key>(src[0], src[1], src[2],
&y0, &u, &v);
y1 = 0;
value = u;
value |= y0 << 8;
value |= v << 16;
value |= y1 << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(float *dst, const uint8_t *src,
unsigned i, unsigned j)
{
uint8_t y, u, v;
assert(i < 2);
assert(j < 1);
y = src[1 + i*2];
u = src[0];
v = src[2];
<API key>(y, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
}
void
<API key>(float *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
float *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
uint8_t y0, y1, u, v;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
y0 = (value >> 0) & 0xff;
u = (value >> 8) & 0xff;
y1 = (value >> 16) & 0xff;
v = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
dst += 4;
<API key>(y1, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
y0 = (value >> 0) & 0xff;
u = (value >> 8) & 0xff;
y1 = (value >> 16) & 0xff;
v = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
uint8_t *dst = dst_row;
const uint32_t *src = (const uint32_t *)src_row;
uint32_t value;
uint8_t y0, y1, u, v;
for (x = 0; x + 1 < width; x += 2) {
value = *src++;
#ifdef <API key>
value = util_bswap32(value);
#endif
y0 = (value >> 0) & 0xff;
u = (value >> 8) & 0xff;
y1 = (value >> 16) & 0xff;
v = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 0xff;
dst += 4;
<API key>(y1, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 0xff;
dst += 4;
}
if (x < width) {
value = *src;
#ifdef <API key>
value = util_bswap32(value);
#endif
y0 = (value >> 0) & 0xff;
u = (value >> 8) & 0xff;
y1 = (value >> 16) & 0xff;
v = (value >> 24) & 0xff;
<API key>(y0, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 0xff;
}
src_row += src_stride/sizeof(*src_row);
dst_row += dst_stride/sizeof(*dst_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const float *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const float *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
uint8_t y0, y1, u, v;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
uint8_t y0, y1, u0, u1, v0, v1, u, v;
<API key>(src[0], src[1], src[2],
&y0, &u0, &v0);
<API key>(src[4], src[5], src[6],
&y1, &u1, &v1);
u = (u0 + u1 + 1) >> 1;
v = (v0 + v1 + 1) >> 1;
value = y0;
value |= u << 8;
value |= y1 << 16;
value |= v << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
<API key>(src[0], src[1], src[2],
&y0, &u, &v);
y1 = 0;
value = y0;
value |= u << 8;
value |= y1 << 16;
value |= v << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(uint8_t *dst_row, unsigned dst_stride,
const uint8_t *src_row, unsigned src_stride,
unsigned width, unsigned height)
{
unsigned x, y;
for (y = 0; y < height; y += 1) {
const uint8_t *src = src_row;
uint32_t *dst = (uint32_t *)dst_row;
uint8_t y0, y1, u, v;
uint32_t value;
for (x = 0; x + 1 < width; x += 2) {
uint8_t y0, y1, u0, u1, v0, v1, u, v;
<API key>(src[0], src[1], src[2],
&y0, &u0, &v0);
<API key>(src[4], src[5], src[6],
&y1, &u1, &v1);
u = (u0 + u1 + 1) >> 1;
v = (v0 + v1 + 1) >> 1;
value = y0;
value |= u << 8;
value |= y1 << 16;
value |= v << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst++ = value;
src += 8;
}
if (x < width) {
<API key>(src[0], src[1], src[2],
&y0, &u, &v);
y1 = 0;
value = y0;
value |= u << 8;
value |= y1 << 16;
value |= v << 24;
#ifdef <API key>
value = util_bswap32(value);
#endif
*dst = value;
}
dst_row += dst_stride/sizeof(*dst_row);
src_row += src_stride/sizeof(*src_row);
}
}
void
<API key>(float *dst, const uint8_t *src,
unsigned i, unsigned j)
{
uint8_t y, u, v;
assert(i < 2);
assert(j < 1);
y = src[0 + i*2];
u = src[1];
v = src[3];
<API key>(y, u, v, &dst[0], &dst[1], &dst[2]);
dst[3] = 1.0f;
}
|
# provided that the following conditions are met:
# with the distribution.
# * Neither the name of the <API key> contributors nor the names of its contributors
# may be used to endorse or promote products derived from this software without specific prior
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# 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.
# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*-
# vim: ft=zsh sw=2 ts=2 et
BUFFER='\sh'
<API key>=(
"1 3 command" # \sh (runs 'sh', bypassing aliases)
)
|
require 'shellwords'
require 'optparse'
require 'rake/task_manager'
require 'rake/file_list'
require 'rake/thread_pool'
require 'rake/<API key>'
require 'rake/trace_output'
require 'rake/win32'
module Rake
<API key> = Class.new(StandardError)
# Rake main application object. When invoking +rake+ from the
# command line, a Rake::Application object is created and run.
class Application
include TaskManager
include TraceOutput
# The name of the application (typically 'rake')
attr_reader :name
# The original directory where rake was invoked.
attr_reader :original_dir
# Name of the actual rakefile used.
attr_reader :rakefile
# Number of columns on the terminal
attr_accessor :terminal_columns
# List of the top level task names (task names from the command line).
attr_reader :top_level_tasks
DEFAULT_RAKEFILES = [
'rakefile',
'Rakefile',
'rakefile.rb',
'Rakefile.rb'
].freeze
# Initialize a Rake::Application object.
def initialize
super
@name = 'rake'
@rakefiles = DEFAULT_RAKEFILES.dup
@rakefile = nil
@pending_imports = []
@imported = []
@loaders = {}
@default_loader = Rake::DefaultLoader.new
@original_dir = Dir.pwd
@top_level_tasks = []
add_loader('rb', DefaultLoader.new)
add_loader('rf', DefaultLoader.new)
add_loader('rake', DefaultLoader.new)
@tty_output = STDOUT.tty?
@terminal_columns = ENV['RAKE_COLUMNS'].to_i
end
# Run the Rake application. The run method performs the following
# three steps:
# * Initialize the command line options (+init+).
# * Define the tasks (+load_rakefile+).
# * Run the top level tasks (+top_level+).
# If you wish to build a custom rake command, you should call
# +init+ on your application. Then define any tasks. Finally,
# call +top_level+ to run your top level tasks.
def run
<API key> do
init
load_rakefile
top_level
end
end
# Initialize the command line parameters and app name.
def init(app_name='rake')
<API key> do
@name = app_name
args = handle_options
<API key>(args)
end
end
# Find the rakefile and then load it and any pending imports.
def load_rakefile
<API key> do
raw_load_rakefile
end
end
# Run the top level tasks of a Rake application.
def top_level
run_with_threads do
if options.show_tasks
<API key>
elsif options.show_prereqs
<API key>
else
top_level_tasks.each { |task_name| invoke_task(task_name) }
end
end
end
# Run the given block with the thread startup and shutdown.
def run_with_threads
thread_pool.gather_history if options.job_stats == :history
yield
thread_pool.join
if options.job_stats
stats = thread_pool.statistics
puts "Maximum active threads: #{stats[:max_active_threads]} + main"
puts "Total threads in play: #{stats[:<API key>]} + main"
end
<API key>.new(thread_pool.history).show if
options.job_stats == :history
end
# Add a loader to handle imported files ending in the extension
# +ext+.
def add_loader(ext, loader)
ext = ".#{ext}" unless ext =~ /^\./
@loaders[ext] = loader
end
# Application options from the command line
def options
@options ||= OpenStruct.new
end
# Return the thread pool used for multithreaded processing.
def thread_pool # :nodoc:
@thread_pool ||= ThreadPool.new(options.thread_pool_size || Rake.<API key>)
end
# Invokes a task with arguments that are extracted from +task_string+
def invoke_task(task_string) # :nodoc:
name, args = parse_task_string(task_string)
t = self[name]
t.invoke(*args)
end
def parse_task_string(string) # :nodoc:
/^([^\[]+)(?:\[(.*)\])$/ =~ string.to_s
name = $1
remaining_args = $2
return string, [] unless name
return name, [] if remaining_args.empty?
args = []
begin
/((?:[^\\,]|\\.)*?)\s*(?:,\s*(.*))?$/ =~ remaining_args
remaining_args = $2
args << $1.gsub(/\\(.)/, '\1')
end while remaining_args
return name, args
end
# Provide standard exception handling for the given block.
def <API key> # :nodoc:
yield
rescue SystemExit
# Exit silently with current status
raise
rescue OptionParser::InvalidOption => ex
$stderr.puts ex.message
exit(false)
rescue Exception => ex
# Exit with error message
<API key>(ex)
<API key>(ex)
end
# Exit the program because of an unhandled exception.
# (may be overridden by subclasses)
def <API key>(ex) # :nodoc:
exit(false)
end
# Display the error message that caused the exception.
def <API key>(ex) # :nodoc:
trace "#{name} aborted!"
<API key>(ex)
trace "Tasks: #{ex.chain}" if has_chain?(ex)
trace "(See full trace by running task with --trace)" unless
options.backtrace
end
def <API key>(ex) # :nodoc:
seen = Thread.current[:<API key>] ||= []
return if seen.include? ex
seen << ex
<API key>(ex)
<API key>(ex)
<API key>(ex.cause) if has_cause?(ex)
end
def has_cause?(ex) # :nodoc:
ex.respond_to?(:cause) && ex.cause
end
def <API key>(ex) # :nodoc:
if ex.instance_of?(RuntimeError)
trace ex.message
else
trace "#{ex.class.name}: #{ex.message}"
end
end
def <API key>(ex) # :nodoc:
if options.backtrace
trace ex.backtrace.join("\n")
else
trace Backtrace.collapse(ex.backtrace).join("\n")
end
end
# Warn about deprecated usage.
# Example:
# Rake.application.deprecate("import", "Rake.import", caller.first)
def deprecate(old_usage, new_usage, call_site) # :nodoc:
unless options.ignore_deprecate
$stderr.puts "WARNING: '#{old_usage}' is deprecated. " +
"Please use '#{new_usage}' instead.\n" +
" at #{call_site}"
end
end
# Does the exception have a task invocation chain?
def has_chain?(exception) # :nodoc:
exception.respond_to?(:chain) && exception.chain
end
private :has_chain?
# True if one of the files in RAKEFILES is in the current directory.
# If a match is found, it is copied into @rakefile.
def have_rakefile # :nodoc:
@rakefiles.each do |fn|
if File.exist?(fn)
others = FileList.glob(fn, File::FNM_CASEFOLD)
return others.size == 1 ? others.first : fn
elsif fn == ''
return fn
end
end
return nil
end
# True if we are outputting to TTY, false otherwise
def tty_output? # :nodoc:
@tty_output
end
# Override the detected TTY output state (mostly for testing)
def tty_output=(tty_output_state) # :nodoc:
@tty_output = tty_output_state
end
# We will truncate output if we are outputting to a TTY or if we've been
# given an explicit column width to honor
def truncate_output? # :nodoc:
tty_output? || @terminal_columns.nonzero?
end
# Display the tasks and comments.
def <API key> # :nodoc:
displayable_tasks = tasks.select { |t|
(options.show_all_tasks || t.comment) &&
t.name =~ options.show_task_pattern
}
case options.show_tasks
when :tasks
width = displayable_tasks.map { |t| t.name_with_args.length }.max || 10
if truncate_output?
max_column = terminal_width - name.size - width - 7
else
max_column = nil
end
displayable_tasks.each do |t|
printf("#{name} %-#{width}s # %s\n",
t.name_with_args,
max_column ? truncate(t.comment, max_column) : t.comment)
end
when :describe
displayable_tasks.each do |t|
puts "#{name} #{t.name_with_args}"
comment = t.full_comment || ""
comment.split("\n").each do |line|
puts " #{line}"
end
puts
end
when :lines
displayable_tasks.each do |t|
t.locations.each do |loc|
printf "#{name} %-30s %s\n", t.name_with_args, loc
end
end
else
fail "Unknown show task mode: '#{options.show_tasks}'"
end
end
def terminal_width # :nodoc:
if @terminal_columns.nonzero?
result = @terminal_columns
else
result = unix? ? dynamic_width : 80
end
(result < 10) ? 80 : result
rescue
80
end
# Calculate the dynamic width of the
def dynamic_width # :nodoc:
@dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
end
def dynamic_width_stty # :nodoc:
%x{stty size 2>/dev/null}.split[1].to_i
end
def dynamic_width_tput # :nodoc:
%x{tput cols 2>/dev/null}.to_i
end
def unix? # :nodoc:
RbConfig::CONFIG['host_os'] =~
/(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
end
def windows? # :nodoc:
Win32.windows?
end
def truncate(string, width) # :nodoc:
if string.nil?
""
elsif string.length <= width
string
else
(string[0, width - 3] || "") + "..."
end
end
# Display the tasks and prerequisites
def <API key> # :nodoc:
tasks.each do |t|
puts "#{name} #{t.name}"
t.prerequisites.each { |pre| puts " #{pre}" }
end
end
def trace(*strings) # :nodoc:
options.trace_output ||= $stderr
trace_on(options.trace_output, *strings)
end
def sort_options(options) # :nodoc:
options.sort_by { |opt|
opt.select { |o| o =~ /^-/ }.map { |o| o.downcase }.sort.reverse
}
end
private :sort_options
# A list of all the standard options used in rake, suitable for
# passing to OptionParser.
def <API key> # :nodoc:
sort_options(
[
['--all', '-A',
"Show all tasks, even uncommented ones (in combination with -T or -D)",
lambda { |value|
options.show_all_tasks = value
}
],
['--backtrace=[OUT]',
"Enable full backtrace. OUT can be stderr (default) or stdout.",
lambda { |value|
options.backtrace = true
select_trace_output(options, 'backtrace', value)
}
],
['--build-all', '-B',
"Build all prerequisites, including those which are up-to-date.",
lambda { |value|
options.build_all = true
}
],
['--comments',
"Show commented tasks only",
lambda { |value|
options.show_all_tasks = !value
}
],
['--describe', '-D [PATTERN]',
"Describe the tasks (matching optional PATTERN), then exit.",
lambda { |value|
<API key>(options, :describe, value)
}
],
['--dry-run', '-n',
"Do a dry run without executing actions.",
lambda { |value|
Rake.verbose(true)
Rake.nowrite(true)
options.dryrun = true
options.trace = true
}
],
['--execute', '-e CODE',
"Execute some Ruby code and exit.",
lambda { |value|
eval(value)
exit
}
],
['--execute-print', '-p CODE',
"Execute some Ruby code, print the result, then exit.",
lambda { |value|
puts eval(value)
exit
}
],
['--execute-continue', '-E CODE',
"Execute some Ruby code, " +
"then continue with normal task processing.",
lambda { |value| eval(value) }
],
['--jobs', '-j [NUMBER]',
"Specifies the maximum number of tasks to execute in parallel. " +
"(default is number of CPU cores + 4)",
lambda { |value|
if value.nil? || value == ''
value = FIXNUM_MAX
elsif value =~ /^\d+$/
value = value.to_i
else
value = Rake.<API key>
end
value = 1 if value < 1
options.thread_pool_size = value - 1
}
],
['--job-stats [LEVEL]',
"Display job statistics. " +
"LEVEL=history displays a complete job list",
lambda { |value|
if value =~ /^history/i
options.job_stats = :history
else
options.job_stats = true
end
}
],
['--libdir', '-I LIBDIR',
"Include LIBDIR in the search path for required modules.",
lambda { |value| $:.push(value) }
],
['--multitask', '-m',
"Treat all tasks as multitasks.",
lambda { |value| options.always_multitask = true }
],
['--no-search', '--nosearch',
'-N', "Do not search parent directories for the Rakefile.",
lambda { |value| options.nosearch = true }
],
['--prereqs', '-P',
"Display the tasks and dependencies, then exit.",
lambda { |value| options.show_prereqs = true }
],
['--quiet', '-q',
"Do not log messages to standard output.",
lambda { |value| Rake.verbose(false) }
],
['--rakefile', '-f [FILENAME]',
"Use FILENAME as the rakefile to search for.",
lambda { |value|
value ||= ''
@rakefiles.clear
@rakefiles << value
}
],
['--rakelibdir', '--rakelib', '-R RAKELIBDIR',
"Auto-import any .rake files in RAKELIBDIR. " +
"(default is 'rakelib')",
lambda { |value|
options.rakelib = value.split(File::PATH_SEPARATOR)
}
],
['--require', '-r MODULE',
"Require MODULE before executing rakefile.",
lambda { |value|
begin
require value
rescue LoadError => ex
begin
rake_require value
rescue LoadError
raise ex
end
end
}
],
['--rules',
"Trace the rules resolution.",
lambda { |value| options.trace_rules = true }
],
['--silent', '-s',
"Like --quiet, but also suppresses the " +
"'in directory' announcement.",
lambda { |value|
Rake.verbose(false)
options.silent = true
}
],
['--suppress-backtrace PATTERN',
"Suppress backtrace lines matching regexp PATTERN. " +
"Ignored if --trace is on.",
lambda { |value|
options.<API key> = Regexp.new(value)
}
],
['--system', '-g',
"Using system wide (global) rakefiles " +
|
function gi() { curl http://gitignore.io/api/$@ ;}
<API key>() {
curl -s http://gitignore.io/api/list | tr "," "\n"
}
_gitignireio () {
compset -P '*,'
compadd -S '' `<API key>`
}
compdef _gitignireio gi
|
import {Date, DateWrapper} from 'angular2/src/facade/lang';
import {Map} from 'angular2/src/facade/collection';
export class MeasureValues {
constructor(public runIndex: number, public timeStamp: Date,
public values: {[key: string]: any}) {}
toJson() {
return {
'timeStamp': DateWrapper.toJson(this.timeStamp),
'runIndex': this.runIndex,
'values': this.values
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.