code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
{template 'common/header'}
<div class="main">
<form class="form-horizontal form" action="site.php" method="post" role="form">
<h4> {$express['name']} - 报价</h4>
<table class="table table-hover">
<thead class="navbar-inner">
<tr>
<th class="row-hover" style="width: 15%;">省</th>
<th class="row-hover" style="width: 15%;">市</th>
<th class="row-hover" style="width: 15%;">县</th>
<th class="row-hover" style="width: 15%;">首重</th>
<th class="row-hover" style="width: 15%;">首重金额</th>
<th class="row-hover" style="width: 15%;">续重单价</th>
<th class="row-hover" style="text-align:right;">操作</th>
</tr>
</thead>
<tbody id="status-items">
{loop $list $e}
<tr>
<td><input name="fees[{$e['id']}][province]" type="text" value="{$e['province']}"></td>
<td><input name="fees[{$e['id']}][city]" type="text" value="{$e['city']}"></td>
<td><input name="fees[{$e['id']}][district]" type="text" value="{$e['district']}"></td>
<td><input name="fees[{$e['id']}][pricefirst]" type="text" value="{$e['pricefirst']}"></td>
<td><input name="fees[{$e['id']}][weightfirst]" type="text" value="{$e['weightfirst']}"></td>
<td><input name="fees[{$e['id']}][priceaddition]" type="text" value="{$e['priceaddition']}"></td>
<td style="text-align:right;">
<a onclick="if (confirm('删除操作不可恢复,确认吗?')){ $(this).parent().parent().remove(); return true;} else {return false;}" href="{php echo $this->createWebUrl('expressFee', array('op' => 'delete', 'id' => $e['id']))}" class="btn btn-mini" title="删除"><i class="icon-remove"></i></a>
</td>
</tr>
{/loop}
</tbody>
</table>
<table class="tb">
<tr>
<td>
<span class="help-block">新增费用,格式为: "省名称:市名称:区名称:首重:首重金额:续重金额", 同时填多个另起一行</span>
<textarea rows="10" cols="80" style="width: 98%;" class="form-control" name="content"></textarea>
</td>
</tr>
<tr>
<td>
<button type="submit" class="btn btn-primary span3" name="submit" value="提交">提交</button>
<input type="hidden" name="act" value="{$_GPC['act']}" />
<input type="hidden" name="do" value="{$_GPC['do']}" />
<input type="hidden" name="name" value="{$_GPC['name']}" />
<input type="hidden" name="id" value="{$express['id']}" />
<input type="hidden" name="token" value="{$_W['token']}" />
</td>
</tr>
</table>
</form>
</div>
{template 'common/footer'} | JoelPub/wordpress-amazon | order/source/modules/community/template/expressFee.html | HTML | gpl-2.0 | 2,541 |
/*
* linux/drivers/cpufreq/cpufreq.c
*
* Copyright (C) 2001 Russell King
* (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de>
*
* Oct 2005 - Ashok Raj <ashok.raj@intel.com>
* Added handling for CPU hotplug
* Feb 2006 - Jacob Shin <jacob.shin@amd.com>
* Fix handling for CPU hotplug -- affected CPUs
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <asm/cputime.h>
#include <linux/kernel.h>
#include <linux/kernel_stat.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/notifier.h>
#include <linux/cpufreq.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/tick.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/syscore_ops.h>
#include <trace/events/power.h>
/**
* The "cpufreq driver" - the arch- or hardware-dependent low
* level driver of CPUFreq support, and its spinlock. This lock
* also protects the cpufreq_cpu_data array.
*/
static struct cpufreq_driver *cpufreq_driver;
static DEFINE_PER_CPU(struct cpufreq_policy *, cpufreq_cpu_data);
#ifdef CONFIG_HOTPLUG_CPU
/* This one keeps track of the previously set governor of a removed CPU */
struct cpufreq_cpu_save_data {
char gov[CPUFREQ_NAME_LEN];
unsigned int max, min;
};
static DEFINE_PER_CPU(struct cpufreq_cpu_save_data, cpufreq_policy_save);
#endif
static DEFINE_SPINLOCK(cpufreq_driver_lock);
static struct kset *cpufreq_kset;
static struct kset *cpudev_kset;
/*
* cpu_policy_rwsem is a per CPU reader-writer semaphore designed to cure
* all cpufreq/hotplug/workqueue/etc related lock issues.
*
* The rules for this semaphore:
* - Any routine that wants to read from the policy structure will
* do a down_read on this semaphore.
* - Any routine that will write to the policy structure and/or may take away
* the policy altogether (eg. CPU hotplug), will hold this lock in write
* mode before doing so.
*
* Additional rules:
* - All holders of the lock should check to make sure that the CPU they
* are concerned with are online after they get the lock.
* - Governor routines that can be called in cpufreq hotplug path should not
* take this sem as top level hotplug notifier handler takes this.
* - Lock should not be held across
* __cpufreq_governor(data, CPUFREQ_GOV_STOP);
*/
static DEFINE_PER_CPU(int, cpufreq_policy_cpu);
static DEFINE_PER_CPU(struct rw_semaphore, cpu_policy_rwsem);
#define lock_policy_rwsem(mode, cpu) \
int lock_policy_rwsem_##mode \
(int cpu) \
{ \
int policy_cpu = per_cpu(cpufreq_policy_cpu, cpu); \
BUG_ON(policy_cpu == -1); \
down_##mode(&per_cpu(cpu_policy_rwsem, policy_cpu)); \
\
return 0; \
}
lock_policy_rwsem(read, cpu);
lock_policy_rwsem(write, cpu);
static void unlock_policy_rwsem_read(int cpu)
{
int policy_cpu = per_cpu(cpufreq_policy_cpu, cpu);
BUG_ON(policy_cpu == -1);
up_read(&per_cpu(cpu_policy_rwsem, policy_cpu));
}
void unlock_policy_rwsem_write(int cpu)
{
int policy_cpu = per_cpu(cpufreq_policy_cpu, cpu);
BUG_ON(policy_cpu == -1);
up_write(&per_cpu(cpu_policy_rwsem, policy_cpu));
}
/* internal prototypes */
static int __cpufreq_governor(struct cpufreq_policy *policy,
unsigned int event);
static unsigned int __cpufreq_get(unsigned int cpu);
static void handle_update(struct work_struct *work);
/**
* Two notifier lists: the "policy" list is involved in the
* validation process for a new CPU frequency policy; the
* "transition" list for kernel code that needs to handle
* changes to devices when the CPU clock speed changes.
* The mutex locks both lists.
*/
static BLOCKING_NOTIFIER_HEAD(cpufreq_policy_notifier_list);
static struct srcu_notifier_head cpufreq_transition_notifier_list;
static bool init_cpufreq_transition_notifier_list_called;
static int __init init_cpufreq_transition_notifier_list(void)
{
srcu_init_notifier_head(&cpufreq_transition_notifier_list);
init_cpufreq_transition_notifier_list_called = true;
return 0;
}
pure_initcall(init_cpufreq_transition_notifier_list);
static int off __read_mostly;
int cpufreq_disabled(void)
{
return off;
}
void disable_cpufreq(void)
{
off = 1;
}
static LIST_HEAD(cpufreq_governor_list);
static DEFINE_MUTEX(cpufreq_governor_mutex);
static inline u64 get_cpu_idle_time_jiffy(unsigned int cpu, u64 *wall)
{
u64 idle_time;
u64 cur_wall_time;
u64 busy_time;
cur_wall_time = jiffies64_to_cputime64(get_jiffies_64());
busy_time = kcpustat_cpu(cpu).cpustat[CPUTIME_USER];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_SYSTEM];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_IRQ];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_SOFTIRQ];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_STEAL];
busy_time += kcpustat_cpu(cpu).cpustat[CPUTIME_NICE];
idle_time = cur_wall_time - busy_time;
if (wall)
*wall = cputime_to_usecs(cur_wall_time);
return cputime_to_usecs(idle_time);
}
u64 get_cpu_idle_time(unsigned int cpu, u64 *wall, int io_busy)
{
u64 idle_time = get_cpu_idle_time_us(cpu, io_busy ? wall : NULL);
if (idle_time == -1ULL)
return get_cpu_idle_time_jiffy(cpu, wall);
else if (!io_busy)
idle_time += get_cpu_iowait_time_us(cpu, wall);
return idle_time;
}
EXPORT_SYMBOL_GPL(get_cpu_idle_time);
static struct cpufreq_policy *__cpufreq_cpu_get(unsigned int cpu, int sysfs)
{
struct cpufreq_policy *data;
unsigned long flags;
if (cpu >= nr_cpu_ids)
goto err_out;
/* get the cpufreq driver */
spin_lock_irqsave(&cpufreq_driver_lock, flags);
if (!cpufreq_driver)
goto err_out_unlock;
if (!try_module_get(cpufreq_driver->owner))
goto err_out_unlock;
/* get the CPU */
data = per_cpu(cpufreq_cpu_data, cpu);
if (!data)
goto err_out_put_module;
if (!sysfs && !kobject_get(&data->kobj))
goto err_out_put_module;
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
return data;
err_out_put_module:
module_put(cpufreq_driver->owner);
err_out_unlock:
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
err_out:
return NULL;
}
struct cpufreq_policy *cpufreq_cpu_get(unsigned int cpu)
{
return __cpufreq_cpu_get(cpu, 0);
}
EXPORT_SYMBOL_GPL(cpufreq_cpu_get);
static struct cpufreq_policy *cpufreq_cpu_get_sysfs(unsigned int cpu)
{
return __cpufreq_cpu_get(cpu, 1);
}
static void __cpufreq_cpu_put(struct cpufreq_policy *data, int sysfs)
{
if (!sysfs)
kobject_put(&data->kobj);
module_put(cpufreq_driver->owner);
}
void cpufreq_cpu_put(struct cpufreq_policy *data)
{
__cpufreq_cpu_put(data, 0);
}
EXPORT_SYMBOL_GPL(cpufreq_cpu_put);
static void cpufreq_cpu_put_sysfs(struct cpufreq_policy *data)
{
__cpufreq_cpu_put(data, 1);
}
/*********************************************************************
* EXTERNALLY AFFECTING FREQUENCY CHANGES *
*********************************************************************/
/**
* adjust_jiffies - adjust the system "loops_per_jiffy"
*
* This function alters the system "loops_per_jiffy" for the clock
* speed change. Note that loops_per_jiffy cannot be updated on SMP
* systems as each CPU might be scaled differently. So, use the arch
* per-CPU loops_per_jiffy value wherever possible.
*/
#ifndef CONFIG_SMP
static unsigned long l_p_j_ref;
static unsigned int l_p_j_ref_freq;
static void adjust_jiffies(unsigned long val, struct cpufreq_freqs *ci)
{
if (ci->flags & CPUFREQ_CONST_LOOPS)
return;
if (!l_p_j_ref_freq) {
l_p_j_ref = loops_per_jiffy;
l_p_j_ref_freq = ci->old;
pr_debug("saving %lu as reference value for loops_per_jiffy; "
"freq is %u kHz\n", l_p_j_ref, l_p_j_ref_freq);
}
if ((val == CPUFREQ_POSTCHANGE && ci->old != ci->new) ||
(val == CPUFREQ_RESUMECHANGE || val == CPUFREQ_SUSPENDCHANGE)) {
loops_per_jiffy = cpufreq_scale(l_p_j_ref, l_p_j_ref_freq,
ci->new);
pr_debug("scaling loops_per_jiffy to %lu "
"for frequency %u kHz\n", loops_per_jiffy, ci->new);
}
}
#else
static inline void adjust_jiffies(unsigned long val, struct cpufreq_freqs *ci)
{
return;
}
#endif
void __cpufreq_notify_transition(struct cpufreq_policy *policy,
struct cpufreq_freqs *freqs, unsigned int state)
{
BUG_ON(irqs_disabled());
freqs->flags = cpufreq_driver->flags;
pr_debug("notification %u of frequency transition to %u kHz\n",
state, freqs->new);
switch (state) {
case CPUFREQ_PRECHANGE:
/* detect if the driver reported a value as "old frequency"
* which is not equal to what the cpufreq core thinks is
* "old frequency".
*/
if (!(cpufreq_driver->flags & CPUFREQ_CONST_LOOPS)) {
if ((policy) && (policy->cpu == freqs->cpu) &&
(policy->cur) && (policy->cur != freqs->old)) {
pr_debug("Warning: CPU frequency is"
" %u, cpufreq assumed %u kHz.\n",
freqs->old, policy->cur);
freqs->old = policy->cur;
}
}
srcu_notifier_call_chain(&cpufreq_transition_notifier_list,
CPUFREQ_PRECHANGE, freqs);
adjust_jiffies(CPUFREQ_PRECHANGE, freqs);
break;
case CPUFREQ_POSTCHANGE:
adjust_jiffies(CPUFREQ_POSTCHANGE, freqs);
pr_debug("FREQ: %lu - CPU: %lu", (unsigned long)freqs->new,
(unsigned long)freqs->cpu);
trace_power_frequency(POWER_PSTATE, freqs->new, freqs->cpu);
trace_cpu_frequency(freqs->new, freqs->cpu);
srcu_notifier_call_chain(&cpufreq_transition_notifier_list,
CPUFREQ_POSTCHANGE, freqs);
if (likely(policy) && likely(policy->cpu == freqs->cpu)) {
policy->cur = freqs->new;
sysfs_notify(&policy->kobj, NULL, "scaling_cur_freq");
}
break;
}
}
/**
* cpufreq_notify_transition - call notifier chain and adjust_jiffies
* on frequency transition.
*
* This function calls the transition notifiers and the "adjust_jiffies"
* function. It is called twice on all CPU frequency changes that have
* external effects.
*/
void cpufreq_notify_transition(struct cpufreq_policy *policy,
struct cpufreq_freqs *freqs, unsigned int state)
{
for_each_cpu(freqs->cpu, policy->cpus)
__cpufreq_notify_transition(policy, freqs, state);
}
EXPORT_SYMBOL_GPL(cpufreq_notify_transition);
/**
* cpufreq_notify_utilization - notify CPU userspace about CPU utilization
* change
*
* This function is called everytime the CPU load is evaluated by the
* ondemand governor. It notifies userspace of cpu load changes via sysfs.
*/
void cpufreq_notify_utilization(struct cpufreq_policy *policy,
unsigned int util)
{
if (policy)
policy->util = util;
if (policy->util >= MIN_CPU_UTIL_NOTIFY)
sysfs_notify(&policy->kobj, NULL, "cpu_utilization");
}
/*********************************************************************
* SYSFS INTERFACE *
*********************************************************************/
static struct cpufreq_governor *__find_governor(const char *str_governor)
{
struct cpufreq_governor *t;
list_for_each_entry(t, &cpufreq_governor_list, governor_list)
if (!strnicmp(str_governor, t->name, CPUFREQ_NAME_LEN))
return t;
return NULL;
}
/**
* cpufreq_parse_governor - parse a governor string
*/
static int cpufreq_parse_governor(char *str_governor, unsigned int *policy,
struct cpufreq_governor **governor)
{
int err = -EINVAL;
if (!cpufreq_driver)
goto out;
if (cpufreq_driver->setpolicy) {
if (!strnicmp(str_governor, "performance", CPUFREQ_NAME_LEN)) {
*policy = CPUFREQ_POLICY_PERFORMANCE;
err = 0;
} else if (!strnicmp(str_governor, "powersave",
CPUFREQ_NAME_LEN)) {
*policy = CPUFREQ_POLICY_POWERSAVE;
err = 0;
}
} else if (cpufreq_driver->target) {
struct cpufreq_governor *t;
mutex_lock(&cpufreq_governor_mutex);
t = __find_governor(str_governor);
if (t == NULL) {
int ret;
mutex_unlock(&cpufreq_governor_mutex);
ret = request_module("cpufreq_%s", str_governor);
mutex_lock(&cpufreq_governor_mutex);
if (ret == 0)
t = __find_governor(str_governor);
}
if (t != NULL) {
*governor = t;
err = 0;
}
mutex_unlock(&cpufreq_governor_mutex);
}
out:
return err;
}
/**
* cpufreq_per_cpu_attr_read() / show_##file_name() -
* print out cpufreq information
*
* Write out information from cpufreq_driver->policy[cpu]; object must be
* "unsigned int".
*/
#define show_one(file_name, object) \
static ssize_t show_##file_name \
(struct cpufreq_policy *policy, char *buf) \
{ \
return sprintf(buf, "%u\n", policy->object); \
}
show_one(cpuinfo_min_freq, cpuinfo.min_freq);
show_one(cpuinfo_max_freq, cpuinfo.max_freq);
show_one(cpuinfo_transition_latency, cpuinfo.transition_latency);
show_one(scaling_min_freq, min);
show_one(scaling_max_freq, max);
show_one(scaling_cur_freq, cur);
show_one(cpu_utilization, util);
static int __cpufreq_set_policy(struct cpufreq_policy *data,
struct cpufreq_policy *policy);
/**
* cpufreq_per_cpu_attr_write() / store_##file_name() - sysfs write access
*/
#define store_one(file_name, object) \
static ssize_t store_##file_name \
(struct cpufreq_policy *policy, const char *buf, size_t count) \
{ \
unsigned int ret = -EINVAL; \
struct cpufreq_policy new_policy; \
\
ret = cpufreq_get_policy(&new_policy, policy->cpu); \
if (ret) \
return -EINVAL; \
\
ret = sscanf(buf, "%u", &new_policy.object); \
if (ret != 1) \
return -EINVAL; \
\
ret = cpufreq_driver->verify(&new_policy); \
if (ret) \
pr_err("cpufreq: Frequency verification failed\n"); \
\
policy->user_policy.object = new_policy.object; \
ret = __cpufreq_set_policy(policy, &new_policy); \
\
return ret ? ret : count; \
}
store_one(scaling_min_freq, min);
store_one(scaling_max_freq, max);
/**
* show_cpuinfo_cur_freq - current CPU frequency as detected by hardware
*/
static ssize_t show_cpuinfo_cur_freq(struct cpufreq_policy *policy,
char *buf)
{
unsigned int cur_freq = __cpufreq_get(policy->cpu);
if (!cur_freq)
return sprintf(buf, "<unknown>");
return sprintf(buf, "%u\n", cur_freq);
}
/**
* show_scaling_governor - show the current policy for the specified CPU
*/
static ssize_t show_scaling_governor(struct cpufreq_policy *policy, char *buf)
{
if (policy->policy == CPUFREQ_POLICY_POWERSAVE)
return sprintf(buf, "powersave\n");
else if (policy->policy == CPUFREQ_POLICY_PERFORMANCE)
return sprintf(buf, "performance\n");
else if (policy->governor)
return scnprintf(buf, CPUFREQ_NAME_LEN, "%s\n",
policy->governor->name);
return -EINVAL;
}
/**
* store_scaling_governor - store policy for the specified CPU
*/
static ssize_t store_scaling_governor(struct cpufreq_policy *policy,
const char *buf, size_t count)
{
unsigned int ret = -EINVAL;
char str_governor[16];
struct cpufreq_policy new_policy;
ret = cpufreq_get_policy(&new_policy, policy->cpu);
if (ret)
return ret;
ret = sscanf(buf, "%15s", str_governor);
if (ret != 1)
return -EINVAL;
if (cpufreq_parse_governor(str_governor, &new_policy.policy,
&new_policy.governor))
return -EINVAL;
/* Do not use cpufreq_set_policy here or the user_policy.max
will be wrongly overridden */
ret = __cpufreq_set_policy(policy, &new_policy);
policy->user_policy.policy = policy->policy;
policy->user_policy.governor = policy->governor;
sysfs_notify(&policy->kobj, NULL, "scaling_governor");
kobject_uevent(cpufreq_global_kobject, KOBJ_ADD);
if (ret)
return ret;
else
return count;
}
/**
* show_scaling_driver - show the cpufreq driver currently loaded
*/
static ssize_t show_scaling_driver(struct cpufreq_policy *policy, char *buf)
{
return scnprintf(buf, CPUFREQ_NAME_LEN, "%s\n", cpufreq_driver->name);
}
/**
* show_scaling_available_governors - show the available CPUfreq governors
*/
static ssize_t show_scaling_available_governors(struct cpufreq_policy *policy,
char *buf)
{
ssize_t i = 0;
struct cpufreq_governor *t;
if (!cpufreq_driver->target) {
i += sprintf(buf, "performance powersave");
goto out;
}
list_for_each_entry(t, &cpufreq_governor_list, governor_list) {
if (i >= (ssize_t) ((PAGE_SIZE / sizeof(char))
- (CPUFREQ_NAME_LEN + 2)))
goto out;
i += scnprintf(&buf[i], CPUFREQ_NAME_LEN, "%s ", t->name);
}
out:
i += sprintf(&buf[i], "\n");
return i;
}
static ssize_t show_cpus(const struct cpumask *mask, char *buf)
{
ssize_t i = 0;
unsigned int cpu;
for_each_cpu(cpu, mask) {
if (i)
i += scnprintf(&buf[i], (PAGE_SIZE - i - 2), " ");
i += scnprintf(&buf[i], (PAGE_SIZE - i - 2), "%u", cpu);
if (i >= (PAGE_SIZE - 5))
break;
}
i += sprintf(&buf[i], "\n");
return i;
}
/**
* show_related_cpus - show the CPUs affected by each transition even if
* hw coordination is in use
*/
static ssize_t show_related_cpus(struct cpufreq_policy *policy, char *buf)
{
return show_cpus(policy->related_cpus, buf);
}
/**
* show_affected_cpus - show the CPUs affected by each transition
*/
static ssize_t show_affected_cpus(struct cpufreq_policy *policy, char *buf)
{
return show_cpus(policy->cpus, buf);
}
static ssize_t store_scaling_setspeed(struct cpufreq_policy *policy,
const char *buf, size_t count)
{
unsigned int freq = 0;
unsigned int ret;
if (!policy->governor || !policy->governor->store_setspeed)
return -EINVAL;
ret = sscanf(buf, "%u", &freq);
if (ret != 1)
return -EINVAL;
policy->governor->store_setspeed(policy, freq);
return count;
}
static ssize_t show_scaling_setspeed(struct cpufreq_policy *policy, char *buf)
{
if (!policy->governor || !policy->governor->show_setspeed)
return sprintf(buf, "<unsupported>\n");
return policy->governor->show_setspeed(policy, buf);
}
/**
* show_scaling_driver - show the current cpufreq HW/BIOS limitation
*/
static ssize_t show_bios_limit(struct cpufreq_policy *policy, char *buf)
{
unsigned int limit;
int ret;
if (cpufreq_driver->bios_limit) {
ret = cpufreq_driver->bios_limit(policy->cpu, &limit);
if (!ret)
return sprintf(buf, "%u\n", limit);
}
return sprintf(buf, "%u\n", policy->cpuinfo.max_freq);
}
cpufreq_freq_attr_ro_perm(cpuinfo_cur_freq, 0400);
cpufreq_freq_attr_ro(cpuinfo_min_freq);
cpufreq_freq_attr_ro(cpuinfo_max_freq);
cpufreq_freq_attr_ro(cpuinfo_transition_latency);
cpufreq_freq_attr_ro(scaling_available_governors);
cpufreq_freq_attr_ro(scaling_driver);
cpufreq_freq_attr_ro(scaling_cur_freq);
cpufreq_freq_attr_ro(bios_limit);
cpufreq_freq_attr_ro(related_cpus);
cpufreq_freq_attr_ro(affected_cpus);
cpufreq_freq_attr_ro(cpu_utilization);
cpufreq_freq_attr_rw(scaling_min_freq);
cpufreq_freq_attr_rw(scaling_max_freq);
cpufreq_freq_attr_rw(scaling_governor);
cpufreq_freq_attr_rw(scaling_setspeed);
static struct attribute *default_attrs[] = {
&cpuinfo_min_freq.attr,
&cpuinfo_max_freq.attr,
&cpuinfo_transition_latency.attr,
&scaling_min_freq.attr,
&scaling_max_freq.attr,
&affected_cpus.attr,
&cpu_utilization.attr,
&related_cpus.attr,
&scaling_governor.attr,
&scaling_driver.attr,
&scaling_available_governors.attr,
&scaling_setspeed.attr,
NULL
};
struct kobject *cpufreq_global_kobject;
EXPORT_SYMBOL(cpufreq_global_kobject);
#define to_policy(k) container_of(k, struct cpufreq_policy, kobj)
#define to_attr(a) container_of(a, struct freq_attr, attr)
static ssize_t show(struct kobject *kobj, struct attribute *attr, char *buf)
{
struct cpufreq_policy *policy = to_policy(kobj);
struct freq_attr *fattr = to_attr(attr);
ssize_t ret = -EINVAL;
policy = cpufreq_cpu_get_sysfs(policy->cpu);
if (!policy)
goto no_policy;
if (lock_policy_rwsem_read(policy->cpu) < 0)
goto fail;
if (fattr->show)
ret = fattr->show(policy, buf);
else
ret = -EIO;
unlock_policy_rwsem_read(policy->cpu);
fail:
cpufreq_cpu_put_sysfs(policy);
no_policy:
return ret;
}
static ssize_t store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct cpufreq_policy *policy = to_policy(kobj);
struct freq_attr *fattr = to_attr(attr);
ssize_t ret = -EINVAL;
policy = cpufreq_cpu_get_sysfs(policy->cpu);
if (!policy)
goto no_policy;
if (lock_policy_rwsem_write(policy->cpu) < 0)
goto fail;
if (fattr->store)
ret = fattr->store(policy, buf, count);
else
ret = -EIO;
unlock_policy_rwsem_write(policy->cpu);
fail:
cpufreq_cpu_put_sysfs(policy);
no_policy:
return ret;
}
static void cpufreq_sysfs_release(struct kobject *kobj)
{
struct cpufreq_policy *policy = to_policy(kobj);
blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
CPUFREQ_REMOVE_POLICY, policy);
pr_debug("last reference is dropped\n");
complete(&policy->kobj_unregister);
}
static const struct sysfs_ops sysfs_ops = {
.show = show,
.store = store,
};
static struct kobj_type ktype_cpufreq = {
.sysfs_ops = &sysfs_ops,
.default_attrs = default_attrs,
.release = cpufreq_sysfs_release,
};
/* symlink affected CPUs */
static int cpufreq_add_dev_symlink(unsigned int cpu,
struct cpufreq_policy *policy)
{
unsigned int j;
int ret = 0;
for_each_cpu(j, policy->cpus) {
struct cpufreq_policy *managed_policy;
struct device *cpu_dev;
if (j == cpu)
continue;
pr_debug("CPU %u already managed, adding link\n", j);
managed_policy = cpufreq_cpu_get(cpu);
cpu_dev = get_cpu_device(j);
ret = sysfs_create_link(&cpu_dev->kobj, &policy->kobj,
"cpufreq");
if (ret) {
cpufreq_cpu_put(managed_policy);
return ret;
}
}
return ret;
}
static int cpufreq_add_dev_interface(unsigned int cpu,
struct cpufreq_policy *policy,
struct device *dev)
{
struct cpufreq_policy new_policy;
struct freq_attr **drv_attr;
unsigned long flags;
int ret = 0;
unsigned int j;
/* prepare interface data */
ret = kobject_init_and_add(&policy->kobj, &ktype_cpufreq,
&dev->kobj, "cpufreq");
if (ret)
return ret;
/* create cpu device kset */
if (!cpudev_kset) {
cpudev_kset = kset_create_and_add("kset", NULL, &dev->kobj);
BUG_ON(!cpudev_kset);
dev->kobj.kset = cpudev_kset;
}
/* send uevent when cpu device is added */
kobject_uevent(&dev->kobj, KOBJ_ADD);
/* set up files for this cpu device */
drv_attr = cpufreq_driver->attr;
while ((drv_attr) && (*drv_attr)) {
ret = sysfs_create_file(&policy->kobj, &((*drv_attr)->attr));
if (ret)
goto err_out_kobj_put;
drv_attr++;
}
if (cpufreq_driver->get) {
ret = sysfs_create_file(&policy->kobj, &cpuinfo_cur_freq.attr);
if (ret)
goto err_out_kobj_put;
}
if (cpufreq_driver->target) {
ret = sysfs_create_file(&policy->kobj, &scaling_cur_freq.attr);
if (ret)
goto err_out_kobj_put;
}
if (cpufreq_driver->bios_limit) {
ret = sysfs_create_file(&policy->kobj, &bios_limit.attr);
if (ret)
goto err_out_kobj_put;
}
spin_lock_irqsave(&cpufreq_driver_lock, flags);
for_each_cpu(j, policy->cpus) {
per_cpu(cpufreq_cpu_data, j) = policy;
per_cpu(cpufreq_policy_cpu, j) = policy->cpu;
}
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
ret = cpufreq_add_dev_symlink(cpu, policy);
if (ret)
goto err_out_kobj_put;
memcpy(&new_policy, policy, sizeof(struct cpufreq_policy));
/* assure that the starting sequence is run in __cpufreq_set_policy */
policy->governor = NULL;
/* set default policy */
ret = __cpufreq_set_policy(policy, &new_policy);
policy->user_policy.policy = policy->policy;
policy->user_policy.governor = policy->governor;
if (ret) {
pr_debug("setting policy failed\n");
if (cpufreq_driver->exit)
cpufreq_driver->exit(policy);
}
blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
CPUFREQ_CREATE_POLICY, policy);
return ret;
err_out_kobj_put:
kobject_put(&policy->kobj);
wait_for_completion(&policy->kobj_unregister);
return ret;
}
#ifdef CONFIG_HOTPLUG_CPU
static int cpufreq_add_policy_cpu(unsigned int cpu, unsigned int sibling,
struct device *dev)
{
struct cpufreq_policy *policy;
int ret = 0;
unsigned long flags;
policy = cpufreq_cpu_get(sibling);
WARN_ON(!policy);
per_cpu(cpufreq_policy_cpu, cpu) = policy->cpu;
lock_policy_rwsem_write(cpu);
__cpufreq_governor(policy, CPUFREQ_GOV_STOP);
spin_lock_irqsave(&cpufreq_driver_lock, flags);
cpumask_set_cpu(cpu, policy->cpus);
per_cpu(cpufreq_cpu_data, cpu) = policy;
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
__cpufreq_governor(policy, CPUFREQ_GOV_START);
__cpufreq_governor(policy, CPUFREQ_GOV_LIMITS);
unlock_policy_rwsem_write(cpu);
ret = sysfs_create_link(&dev->kobj, &policy->kobj, "cpufreq");
if (ret) {
cpufreq_cpu_put(policy);
return ret;
}
return 0;
}
#endif
/**
* cpufreq_add_dev - add a CPU device
*
* Adds the cpufreq interface for a CPU device.
*
* The Oracle says: try running cpufreq registration/unregistration concurrently
* with with cpu hotplugging and all hell will break loose. Tried to clean this
* mess up, but more thorough testing is needed. - Mathieu
*/
static int cpufreq_add_dev(struct device *dev, struct subsys_interface *sif)
{
unsigned int j, cpu = dev->id;
int ret = -ENOMEM, found = 0;
struct cpufreq_policy *policy;
unsigned long flags;
#ifdef CONFIG_HOTPLUG_CPU
struct cpufreq_governor *gov;
int sibling;
#endif
if (cpu_is_offline(cpu))
return 0;
pr_debug("adding CPU %u\n", cpu);
#ifdef CONFIG_SMP
/* check whether a different CPU already registered this
* CPU because it is in the same boat. */
policy = cpufreq_cpu_get(cpu);
if (unlikely(policy)) {
cpufreq_cpu_put(policy);
return 0;
}
#ifdef CONFIG_HOTPLUG_CPU
/* Check if this cpu was hot-unplugged earlier and has siblings */
for_each_online_cpu(sibling) {
struct cpufreq_policy *cp = per_cpu(cpufreq_cpu_data, sibling);
if (cp && cpumask_test_cpu(cpu, cp->related_cpus))
return cpufreq_add_policy_cpu(cpu, sibling, dev);
}
#endif
#endif
if (!try_module_get(cpufreq_driver->owner)) {
ret = -EINVAL;
goto module_out;
}
policy = kzalloc(sizeof(struct cpufreq_policy), GFP_KERNEL);
if (!policy)
goto nomem_out;
if (!alloc_cpumask_var(&policy->cpus, GFP_KERNEL))
goto err_free_policy;
if (!zalloc_cpumask_var(&policy->related_cpus, GFP_KERNEL))
goto err_free_cpumask;
policy->cpu = cpu;
cpumask_copy(policy->cpus, cpumask_of(cpu));
/* Initially set CPU itself as the policy_cpu */
per_cpu(cpufreq_policy_cpu, cpu) = cpu;
ret = (lock_policy_rwsem_write(cpu) < 0);
WARN_ON(ret);
init_completion(&policy->kobj_unregister);
INIT_WORK(&policy->update, handle_update);
/* Set governor before ->init, so that driver could check it */
#ifdef CONFIG_HOTPLUG_CPU
for_each_online_cpu(sibling) {
struct cpufreq_policy *cp = per_cpu(cpufreq_cpu_data, sibling);
if (cp && cp->governor &&
(cpumask_test_cpu(cpu, cp->related_cpus))) {
policy->governor = cp->governor;
found = 1;
break;
}
}
#endif
if (!found)
policy->governor = CPUFREQ_DEFAULT_GOVERNOR;
/* call driver. From then on the cpufreq must be able
* to accept all calls to ->verify and ->setpolicy for this CPU
*/
ret = cpufreq_driver->init(policy);
if (ret) {
pr_debug("initialization failed\n");
goto err_unlock_policy;
}
/* related cpus should atleast have policy->cpus */
cpumask_or(policy->related_cpus, policy->related_cpus, policy->cpus);
/*
* affected cpus must always be the one, which are online. We aren't
* managing offline cpus here.
*/
cpumask_and(policy->cpus, policy->cpus, cpu_online_mask);
policy->user_policy.min = policy->min;
policy->user_policy.max = policy->max;
blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
CPUFREQ_START, policy);
#ifdef CONFIG_HOTPLUG_CPU
gov = __find_governor(per_cpu(cpufreq_policy_save, cpu).gov);
if (gov) {
policy->governor = gov;
pr_debug("Restoring governor %s for cpu %d\n",
policy->governor->name, cpu);
}
#endif
ret = cpufreq_add_dev_interface(cpu, policy, dev);
if (ret)
goto err_out_unregister;
unlock_policy_rwsem_write(cpu);
kobject_uevent(&policy->kobj, KOBJ_ADD);
module_put(cpufreq_driver->owner);
pr_debug("initialization complete\n");
return 0;
err_out_unregister:
spin_lock_irqsave(&cpufreq_driver_lock, flags);
for_each_cpu(j, policy->cpus)
per_cpu(cpufreq_cpu_data, j) = NULL;
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
kobject_put(&policy->kobj);
wait_for_completion(&policy->kobj_unregister);
err_unlock_policy:
unlock_policy_rwsem_write(cpu);
free_cpumask_var(policy->related_cpus);
err_free_cpumask:
free_cpumask_var(policy->cpus);
err_free_policy:
kfree(policy);
nomem_out:
module_put(cpufreq_driver->owner);
module_out:
return ret;
}
/**
* __cpufreq_remove_dev - remove a CPU device
*
* Removes the cpufreq interface for a CPU device.
* Caller should already have policy_rwsem in write mode for this CPU.
* This routine frees the rwsem before returning.
*/
static int __cpufreq_remove_dev(struct device *dev, struct subsys_interface *sif)
{
unsigned int cpu = dev->id;
unsigned long flags;
struct cpufreq_policy *data;
struct kobject *kobj;
struct completion *cmp;
#ifdef CONFIG_SMP
struct device *cpu_dev;
unsigned int j;
#endif
pr_debug("unregistering CPU %u\n", cpu);
spin_lock_irqsave(&cpufreq_driver_lock, flags);
data = per_cpu(cpufreq_cpu_data, cpu);
if (!data) {
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
unlock_policy_rwsem_write(cpu);
return -EINVAL;
}
per_cpu(cpufreq_cpu_data, cpu) = NULL;
#ifdef CONFIG_SMP
/* if this isn't the CPU which is the parent of the kobj, we
* only need to unlink, put and exit
*/
if (unlikely(cpu != data->cpu)) {
pr_debug("removing link\n");
__cpufreq_governor(data, CPUFREQ_GOV_STOP);
cpumask_clear_cpu(cpu, data->cpus);
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
__cpufreq_governor(data, CPUFREQ_GOV_START);
__cpufreq_governor(data, CPUFREQ_GOV_LIMITS);
kobj = &dev->kobj;
cpufreq_cpu_put(data);
unlock_policy_rwsem_write(cpu);
sysfs_remove_link(kobj, "cpufreq");
return 0;
}
#endif
#ifdef CONFIG_SMP
#ifdef CONFIG_HOTPLUG_CPU
strncpy(per_cpu(cpufreq_policy_save, cpu).gov, data->governor->name,
CPUFREQ_NAME_LEN);
per_cpu(cpufreq_policy_save, cpu).min = data->user_policy.min;
per_cpu(cpufreq_policy_save, cpu).max = data->user_policy.max;
pr_debug("Saving CPU%d user policy min %d and max %d\n",
cpu, data->user_policy.min, data->user_policy.max);
#endif
/* if we have other CPUs still registered, we need to unlink them,
* or else wait_for_completion below will lock up. Clean the
* per_cpu(cpufreq_cpu_data) while holding the lock, and remove
* the sysfs links afterwards.
*/
if (unlikely(cpumask_weight(data->cpus) > 1)) {
for_each_cpu(j, data->cpus) {
if (j == cpu)
continue;
per_cpu(cpufreq_cpu_data, j) = NULL;
}
}
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
if (unlikely(cpumask_weight(data->cpus) > 1)) {
for_each_cpu(j, data->cpus) {
if (j == cpu)
continue;
pr_debug("removing link for cpu %u\n", j);
#ifdef CONFIG_HOTPLUG_CPU
strncpy(per_cpu(cpufreq_policy_save, j).gov,
data->governor->name, CPUFREQ_NAME_LEN);
per_cpu(cpufreq_policy_save, j).min
= data->user_policy.min;
per_cpu(cpufreq_policy_save, j).max
= data->user_policy.max;
pr_debug("Saving CPU%d user policy min %d and max %d\n",
j, data->min, data->max);
#endif
cpu_dev = get_cpu_device(j);
kobj = &cpu_dev->kobj;
unlock_policy_rwsem_write(cpu);
sysfs_remove_link(kobj, "cpufreq");
lock_policy_rwsem_write(cpu);
cpufreq_cpu_put(data);
}
}
#else
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
#endif
if (cpufreq_driver->target)
__cpufreq_governor(data, CPUFREQ_GOV_STOP);
kobj = &data->kobj;
cmp = &data->kobj_unregister;
unlock_policy_rwsem_write(cpu);
kobject_put(kobj);
/* we need to make sure that the underlying kobj is actually
* not referenced anymore by anybody before we proceed with
* unloading.
*/
pr_debug("waiting for dropping of refcount\n");
wait_for_completion(cmp);
pr_debug("wait complete\n");
lock_policy_rwsem_write(cpu);
if (cpufreq_driver->exit)
cpufreq_driver->exit(data);
unlock_policy_rwsem_write(cpu);
#ifdef CONFIG_HOTPLUG_CPU
/* when the CPU which is the parent of the kobj is hotplugged
* offline, check for siblings, and create cpufreq sysfs interface
* and symlinks
*/
if (unlikely(cpumask_weight(data->cpus) > 1)) {
/* first sibling now owns the new sysfs dir */
cpumask_clear_cpu(cpu, data->cpus);
cpufreq_add_dev(get_cpu_device(cpumask_first(data->cpus)), NULL);
/* finally remove our own symlink */
lock_policy_rwsem_write(cpu);
__cpufreq_remove_dev(dev, sif);
}
#endif
free_cpumask_var(data->related_cpus);
free_cpumask_var(data->cpus);
kfree(data);
return 0;
}
static int cpufreq_remove_dev(struct device *dev, struct subsys_interface *sif)
{
unsigned int cpu = dev->id;
int retval;
if (cpu_is_offline(cpu))
return 0;
if (unlikely(lock_policy_rwsem_write(cpu)))
BUG();
retval = __cpufreq_remove_dev(dev, sif);
return retval;
}
static void handle_update(struct work_struct *work)
{
struct cpufreq_policy *policy =
container_of(work, struct cpufreq_policy, update);
unsigned int cpu = policy->cpu;
pr_debug("handle_update for cpu %u called\n", cpu);
cpufreq_update_policy(cpu);
}
/**
* cpufreq_out_of_sync - If actual and saved CPU frequency differs, we're in deep trouble.
* @cpu: cpu number
* @old_freq: CPU frequency the kernel thinks the CPU runs at
* @new_freq: CPU frequency the CPU actually runs at
*
* We adjust to current frequency first, and need to clean up later.
* So either call to cpufreq_update_policy() or schedule handle_update()).
*/
static void cpufreq_out_of_sync(unsigned int cpu, unsigned int old_freq,
unsigned int new_freq)
{
struct cpufreq_policy *policy;
struct cpufreq_freqs freqs;
unsigned long flags;
pr_debug("Warning: CPU frequency out of sync: cpufreq and timing "
"core thinks of %u, is %u kHz.\n", old_freq, new_freq);
freqs.old = old_freq;
freqs.new = new_freq;
spin_lock_irqsave(&cpufreq_driver_lock, flags);
policy = per_cpu(cpufreq_cpu_data, cpu);
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
cpufreq_notify_transition(policy, &freqs, CPUFREQ_PRECHANGE);
cpufreq_notify_transition(policy, &freqs, CPUFREQ_POSTCHANGE);
}
/**
* cpufreq_quick_get - get the CPU frequency (in kHz) from policy->cur
* @cpu: CPU number
*
* This is the last known freq, without actually getting it from the driver.
* Return value will be same as what is shown in scaling_cur_freq in sysfs.
*/
unsigned int cpufreq_quick_get(unsigned int cpu)
{
struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
unsigned int ret_freq = 0;
if (policy) {
ret_freq = policy->cur;
cpufreq_cpu_put(policy);
}
return ret_freq;
}
EXPORT_SYMBOL(cpufreq_quick_get);
/**
* cpufreq_quick_get_max - get the max reported CPU frequency for this CPU
* @cpu: CPU number
*
* Just return the max possible frequency for a given CPU.
*/
unsigned int cpufreq_quick_get_max(unsigned int cpu)
{
struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
unsigned int ret_freq = 0;
if (policy) {
ret_freq = policy->max;
cpufreq_cpu_put(policy);
}
return ret_freq;
}
EXPORT_SYMBOL(cpufreq_quick_get_max);
static unsigned int __cpufreq_get(unsigned int cpu)
{
struct cpufreq_policy *policy = per_cpu(cpufreq_cpu_data, cpu);
unsigned int ret_freq = 0;
if (!cpufreq_driver->get)
return ret_freq;
ret_freq = cpufreq_driver->get(cpu);
if (ret_freq && policy->cur &&
!(cpufreq_driver->flags & CPUFREQ_CONST_LOOPS)) {
/* verify no discrepancy between actual and
saved value exists */
if (unlikely(ret_freq != policy->cur)) {
cpufreq_out_of_sync(cpu, policy->cur, ret_freq);
schedule_work(&policy->update);
}
}
return ret_freq;
}
/**
* cpufreq_get - get the current CPU frequency (in kHz)
* @cpu: CPU number
*
* Get the CPU current (static) CPU frequency
*/
unsigned int cpufreq_get(unsigned int cpu)
{
unsigned int ret_freq = 0;
struct cpufreq_policy *policy = cpufreq_cpu_get(cpu);
if (!policy)
goto out;
if (unlikely(lock_policy_rwsem_read(cpu)))
goto out_policy;
ret_freq = __cpufreq_get(cpu);
unlock_policy_rwsem_read(cpu);
out_policy:
cpufreq_cpu_put(policy);
out:
return ret_freq;
}
EXPORT_SYMBOL(cpufreq_get);
static struct subsys_interface cpufreq_interface = {
.name = "cpufreq",
.subsys = &cpu_subsys,
.add_dev = cpufreq_add_dev,
.remove_dev = cpufreq_remove_dev,
};
/**
* cpufreq_bp_suspend - Prepare the boot CPU for system suspend.
*
* This function is only executed for the boot processor. The other CPUs
* have been put offline by means of CPU hotplug.
*/
static int cpufreq_bp_suspend(void)
{
int ret = 0;
int cpu = smp_processor_id();
struct cpufreq_policy *cpu_policy;
pr_debug("suspending cpu %u\n", cpu);
/* If there's no policy for the boot CPU, we have nothing to do. */
cpu_policy = cpufreq_cpu_get(cpu);
if (!cpu_policy)
return 0;
if (cpufreq_driver->suspend) {
ret = cpufreq_driver->suspend(cpu_policy);
if (ret)
printk(KERN_ERR "cpufreq: suspend failed in ->suspend "
"step on CPU %u\n", cpu_policy->cpu);
}
cpufreq_cpu_put(cpu_policy);
return ret;
}
/**
* cpufreq_bp_resume - Restore proper frequency handling of the boot CPU.
*
* 1.) resume CPUfreq hardware support (cpufreq_driver->resume())
* 2.) schedule call cpufreq_update_policy() ASAP as interrupts are
* restored. It will verify that the current freq is in sync with
* what we believe it to be. This is a bit later than when it
* should be, but nonethteless it's better than calling
* cpufreq_driver->get() here which might re-enable interrupts...
*
* This function is only executed for the boot CPU. The other CPUs have not
* been turned on yet.
*/
static void cpufreq_bp_resume(void)
{
int ret = 0;
int cpu = smp_processor_id();
struct cpufreq_policy *cpu_policy;
pr_debug("resuming cpu %u\n", cpu);
/* If there's no policy for the boot CPU, we have nothing to do. */
cpu_policy = cpufreq_cpu_get(cpu);
if (!cpu_policy)
return;
if (cpufreq_driver->resume) {
ret = cpufreq_driver->resume(cpu_policy);
if (ret) {
printk(KERN_ERR "cpufreq: resume failed in ->resume "
"step on CPU %u\n", cpu_policy->cpu);
goto fail;
}
}
schedule_work(&cpu_policy->update);
fail:
cpufreq_cpu_put(cpu_policy);
}
static struct syscore_ops cpufreq_syscore_ops = {
.suspend = cpufreq_bp_suspend,
.resume = cpufreq_bp_resume,
};
/*********************************************************************
* NOTIFIER LISTS INTERFACE *
*********************************************************************/
/**
* cpufreq_register_notifier - register a driver with cpufreq
* @nb: notifier function to register
* @list: CPUFREQ_TRANSITION_NOTIFIER or CPUFREQ_POLICY_NOTIFIER
*
* Add a driver to one of two lists: either a list of drivers that
* are notified about clock rate changes (once before and once after
* the transition), or a list of drivers that are notified about
* changes in cpufreq policy.
*
* This function may sleep, and has the same return conditions as
* blocking_notifier_chain_register.
*/
int cpufreq_register_notifier(struct notifier_block *nb, unsigned int list)
{
int ret;
WARN_ON(!init_cpufreq_transition_notifier_list_called);
switch (list) {
case CPUFREQ_TRANSITION_NOTIFIER:
ret = srcu_notifier_chain_register(
&cpufreq_transition_notifier_list, nb);
break;
case CPUFREQ_POLICY_NOTIFIER:
ret = blocking_notifier_chain_register(
&cpufreq_policy_notifier_list, nb);
break;
default:
ret = -EINVAL;
}
return ret;
}
EXPORT_SYMBOL(cpufreq_register_notifier);
/**
* cpufreq_unregister_notifier - unregister a driver with cpufreq
* @nb: notifier block to be unregistered
* @list: CPUFREQ_TRANSITION_NOTIFIER or CPUFREQ_POLICY_NOTIFIER
*
* Remove a driver from the CPU frequency notifier list.
*
* This function may sleep, and has the same return conditions as
* blocking_notifier_chain_unregister.
*/
int cpufreq_unregister_notifier(struct notifier_block *nb, unsigned int list)
{
int ret;
switch (list) {
case CPUFREQ_TRANSITION_NOTIFIER:
ret = srcu_notifier_chain_unregister(
&cpufreq_transition_notifier_list, nb);
break;
case CPUFREQ_POLICY_NOTIFIER:
ret = blocking_notifier_chain_unregister(
&cpufreq_policy_notifier_list, nb);
break;
default:
ret = -EINVAL;
}
return ret;
}
EXPORT_SYMBOL(cpufreq_unregister_notifier);
/*********************************************************************
* GOVERNORS *
*********************************************************************/
int __cpufreq_driver_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
int retval = -EINVAL;
if (cpufreq_disabled())
return -ENODEV;
pr_debug("target for CPU %u: %u kHz, relation %u\n", policy->cpu,
target_freq, relation);
if (cpufreq_driver->target)
retval = cpufreq_driver->target(policy, target_freq, relation);
return retval;
}
EXPORT_SYMBOL_GPL(__cpufreq_driver_target);
int cpufreq_driver_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
int ret = -EINVAL;
policy = cpufreq_cpu_get(policy->cpu);
if (!policy)
goto no_policy;
if (unlikely(lock_policy_rwsem_write(policy->cpu)))
goto fail;
ret = __cpufreq_driver_target(policy, target_freq, relation);
unlock_policy_rwsem_write(policy->cpu);
fail:
cpufreq_cpu_put(policy);
no_policy:
return ret;
}
EXPORT_SYMBOL_GPL(cpufreq_driver_target);
int __cpufreq_driver_getavg(struct cpufreq_policy *policy, unsigned int cpu)
{
int ret = 0;
if (!cpufreq_driver->getavg)
return 0;
policy = cpufreq_cpu_get(policy->cpu);
if (!policy)
return -EINVAL;
ret = cpufreq_driver->getavg(policy, cpu);
cpufreq_cpu_put(policy);
return ret;
}
EXPORT_SYMBOL_GPL(__cpufreq_driver_getavg);
/*
* when "event" is CPUFREQ_GOV_LIMITS
*/
static int __cpufreq_governor(struct cpufreq_policy *policy,
unsigned int event)
{
int ret;
/* Only must be defined when default governor is known to have latency
restrictions, like e.g. conservative or ondemand.
That this is the case is already ensured in Kconfig
*/
#ifdef CONFIG_CPU_FREQ_GOV_PERFORMANCE
struct cpufreq_governor *gov = &cpufreq_gov_performance;
#else
struct cpufreq_governor *gov = NULL;
#endif
if (policy->governor->max_transition_latency &&
policy->cpuinfo.transition_latency >
policy->governor->max_transition_latency) {
if (!gov)
return -EINVAL;
else {
printk(KERN_WARNING "%s governor failed, too long"
" transition latency of HW, fallback"
" to %s governor\n",
policy->governor->name,
gov->name);
policy->governor = gov;
}
}
if (!try_module_get(policy->governor->owner))
return -EINVAL;
pr_debug("__cpufreq_governor for CPU %u, event %u\n",
policy->cpu, event);
ret = policy->governor->governor(policy, event);
/* we keep one module reference alive for
each CPU governed by this CPU */
if ((event != CPUFREQ_GOV_START) || ret)
module_put(policy->governor->owner);
if ((event == CPUFREQ_GOV_STOP) && !ret)
module_put(policy->governor->owner);
return ret;
}
int cpufreq_register_governor(struct cpufreq_governor *governor)
{
int err;
if (!governor)
return -EINVAL;
if (cpufreq_disabled())
return -ENODEV;
mutex_lock(&cpufreq_governor_mutex);
err = -EBUSY;
if (__find_governor(governor->name) == NULL) {
err = 0;
list_add(&governor->governor_list, &cpufreq_governor_list);
}
mutex_unlock(&cpufreq_governor_mutex);
return err;
}
EXPORT_SYMBOL_GPL(cpufreq_register_governor);
void cpufreq_unregister_governor(struct cpufreq_governor *governor)
{
#ifdef CONFIG_HOTPLUG_CPU
int cpu;
#endif
if (!governor)
return;
if (cpufreq_disabled())
return;
#ifdef CONFIG_HOTPLUG_CPU
for_each_present_cpu(cpu) {
if (cpu_online(cpu))
continue;
if (!strcmp(per_cpu(cpufreq_policy_save, cpu).gov,
governor->name))
strcpy(per_cpu(cpufreq_policy_save, cpu).gov, "\0");
per_cpu(cpufreq_policy_save, cpu).min = 0;
per_cpu(cpufreq_policy_save, cpu).max = 0;
}
#endif
mutex_lock(&cpufreq_governor_mutex);
list_del(&governor->governor_list);
mutex_unlock(&cpufreq_governor_mutex);
return;
}
EXPORT_SYMBOL_GPL(cpufreq_unregister_governor);
/*********************************************************************
* POLICY INTERFACE *
*********************************************************************/
/**
* cpufreq_get_policy - get the current cpufreq_policy
* @policy: struct cpufreq_policy into which the current cpufreq_policy
* is written
*
* Reads the current cpufreq policy.
*/
int cpufreq_get_policy(struct cpufreq_policy *policy, unsigned int cpu)
{
struct cpufreq_policy *cpu_policy;
if (!policy)
return -EINVAL;
cpu_policy = cpufreq_cpu_get(cpu);
if (!cpu_policy)
return -EINVAL;
memcpy(policy, cpu_policy, sizeof(struct cpufreq_policy));
cpufreq_cpu_put(cpu_policy);
return 0;
}
EXPORT_SYMBOL(cpufreq_get_policy);
/*
* data : current policy.
* policy : policy to be set.
*/
static int __cpufreq_set_policy(struct cpufreq_policy *data,
struct cpufreq_policy *policy)
{
int ret = 0;
struct cpufreq_policy *cpu0_policy = NULL;
pr_debug("setting new policy for CPU %u: %u - %u kHz\n", policy->cpu,
policy->min, policy->max);
memcpy(&policy->cpuinfo, &data->cpuinfo,
sizeof(struct cpufreq_cpuinfo));
if (policy->min > data->user_policy.max
|| policy->max < data->user_policy.min) {
ret = -EINVAL;
goto error_out;
}
/* verify the cpu speed can be set within this limit */
ret = cpufreq_driver->verify(policy);
if (ret)
goto error_out;
/* adjust if necessary - all reasons */
blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
CPUFREQ_ADJUST, policy);
/* adjust if necessary - hardware incompatibility*/
blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
CPUFREQ_INCOMPATIBLE, policy);
/* verify the cpu speed can be set within this limit,
which might be different to the first one */
ret = cpufreq_driver->verify(policy);
if (ret)
goto error_out;
/* notification of the new policy */
blocking_notifier_call_chain(&cpufreq_policy_notifier_list,
CPUFREQ_NOTIFY, policy);
if (policy->cpu) {
cpu0_policy = cpufreq_cpu_get(0);
data->min = cpu0_policy->min;
data->max = cpu0_policy->max;
} else {
data->min = policy->min;
data->max = policy->max;
}
pr_debug("new min and max freqs are %u - %u kHz\n",
data->min, data->max);
if (cpufreq_driver->setpolicy) {
data->policy = policy->policy;
pr_debug("setting range\n");
ret = cpufreq_driver->setpolicy(policy);
} else {
if (policy->governor != data->governor) {
/* save old, working values */
struct cpufreq_governor *old_gov = data->governor;
pr_debug("governor switch\n");
/* end old governor */
if (data->governor)
__cpufreq_governor(data, CPUFREQ_GOV_STOP);
/* start new governor */
if (policy->cpu >= 1 && cpu0_policy) {
data->governor = cpu0_policy->governor;
} else {
data->governor = policy->governor;
}
if (__cpufreq_governor(data, CPUFREQ_GOV_START)) {
/* new governor failed, so re-start old one */
pr_debug("starting governor %s failed\n",
data->governor->name);
if (old_gov) {
data->governor = old_gov;
__cpufreq_governor(data,
CPUFREQ_GOV_START);
}
ret = -EINVAL;
goto error_out;
}
/* might be a policy change, too, so fall through */
}
pr_debug("governor: change or update limits\n");
__cpufreq_governor(data, CPUFREQ_GOV_LIMITS);
}
error_out:
return ret;
}
/**
* cpufreq_update_policy - re-evaluate an existing cpufreq policy
* @cpu: CPU which shall be re-evaluated
*
* Useful for policy notifiers which have different necessities
* at different times.
*/
int cpufreq_update_policy(unsigned int cpu)
{
struct cpufreq_policy *data = cpufreq_cpu_get(cpu);
struct cpufreq_policy policy;
int ret;
if (!data) {
ret = -ENODEV;
goto no_policy;
}
if (unlikely(lock_policy_rwsem_write(cpu))) {
ret = -EINVAL;
goto fail;
}
pr_debug("updating policy for CPU %u\n", cpu);
memcpy(&policy, data, sizeof(struct cpufreq_policy));
policy.min = data->user_policy.min;
policy.max = data->user_policy.max;
policy.policy = data->user_policy.policy;
policy.governor = data->user_policy.governor;
/* BIOS might change freq behind our back
-> ask driver for current freq and notify governors about a change */
if (cpufreq_driver->get) {
policy.cur = cpufreq_driver->get(cpu);
if (!data->cur) {
pr_debug("Driver did not initialize current freq");
data->cur = policy.cur;
} else {
if (data->cur != policy.cur)
cpufreq_out_of_sync(cpu, data->cur,
policy.cur);
}
}
ret = __cpufreq_set_policy(data, &policy);
unlock_policy_rwsem_write(cpu);
fail:
cpufreq_cpu_put(data);
no_policy:
return ret;
}
EXPORT_SYMBOL(cpufreq_update_policy);
static int cpufreq_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct device *dev;
dev = get_cpu_device(cpu);
if (dev) {
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
cpufreq_add_dev(dev, NULL);
break;
case CPU_DOWN_PREPARE:
case CPU_DOWN_PREPARE_FROZEN:
if (unlikely(lock_policy_rwsem_write(cpu)))
BUG();
__cpufreq_remove_dev(dev, NULL);
break;
case CPU_DOWN_FAILED:
case CPU_DOWN_FAILED_FROZEN:
cpufreq_add_dev(dev, NULL);
break;
}
}
return NOTIFY_OK;
}
static struct notifier_block __refdata cpufreq_cpu_notifier = {
.notifier_call = cpufreq_cpu_callback,
};
/*********************************************************************
* REGISTER / UNREGISTER CPUFREQ DRIVER *
*********************************************************************/
/**
* cpufreq_register_driver - register a CPU Frequency driver
* @driver_data: A struct cpufreq_driver containing the values#
* submitted by the CPU Frequency driver.
*
* Registers a CPU Frequency driver to this core code. This code
* returns zero on success, -EBUSY when another driver got here first
* (and isn't unregistered in the meantime).
*
*/
int cpufreq_register_driver(struct cpufreq_driver *driver_data)
{
unsigned long flags;
int ret;
if (cpufreq_disabled())
return -ENODEV;
if (!driver_data || !driver_data->verify || !driver_data->init ||
((!driver_data->setpolicy) && (!driver_data->target)))
return -EINVAL;
pr_debug("trying to register driver %s\n", driver_data->name);
if (driver_data->setpolicy)
driver_data->flags |= CPUFREQ_CONST_LOOPS;
spin_lock_irqsave(&cpufreq_driver_lock, flags);
if (cpufreq_driver) {
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
return -EBUSY;
}
cpufreq_driver = driver_data;
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
ret = subsys_interface_register(&cpufreq_interface);
if (ret)
goto err_null_driver;
if (!(cpufreq_driver->flags & CPUFREQ_STICKY)) {
int i;
ret = -ENODEV;
/* check for at least one working CPU */
for (i = 0; i < nr_cpu_ids; i++)
if (cpu_possible(i) && per_cpu(cpufreq_cpu_data, i)) {
ret = 0;
break;
}
/* if all ->init() calls failed, unregister */
if (ret) {
pr_debug("no CPU initialized for driver %s\n",
driver_data->name);
goto err_if_unreg;
}
}
register_hotcpu_notifier(&cpufreq_cpu_notifier);
pr_debug("driver %s up and running\n", driver_data->name);
return 0;
err_if_unreg:
subsys_interface_unregister(&cpufreq_interface);
err_null_driver:
spin_lock_irqsave(&cpufreq_driver_lock, flags);
cpufreq_driver = NULL;
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(cpufreq_register_driver);
/**
* cpufreq_unregister_driver - unregister the current CPUFreq driver
*
* Unregister the current CPUFreq driver. Only call this if you have
* the right to do so, i.e. if you have succeeded in initialising before!
* Returns zero if successful, and -EINVAL if the cpufreq_driver is
* currently not initialised.
*/
int cpufreq_unregister_driver(struct cpufreq_driver *driver)
{
unsigned long flags;
if (!cpufreq_driver || (driver != cpufreq_driver))
return -EINVAL;
pr_debug("unregistering driver %s\n", driver->name);
subsys_interface_unregister(&cpufreq_interface);
unregister_hotcpu_notifier(&cpufreq_cpu_notifier);
spin_lock_irqsave(&cpufreq_driver_lock, flags);
cpufreq_driver = NULL;
spin_unlock_irqrestore(&cpufreq_driver_lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_unregister_driver);
static int __init cpufreq_core_init(void)
{
int cpu;
if (cpufreq_disabled())
return -ENODEV;
for_each_possible_cpu(cpu) {
per_cpu(cpufreq_policy_cpu, cpu) = -1;
init_rwsem(&per_cpu(cpu_policy_rwsem, cpu));
}
cpufreq_global_kobject = kobject_create_and_add("cpufreq", &cpu_subsys.dev_root->kobj);
BUG_ON(!cpufreq_global_kobject);
/* create cpufreq kset */
cpufreq_kset = kset_create_and_add("kset", NULL, cpufreq_global_kobject);
BUG_ON(!cpufreq_kset);
cpufreq_global_kobject->kset = cpufreq_kset;
register_syscore_ops(&cpufreq_syscore_ops);
return 0;
}
core_initcall(cpufreq_core_init);
| aatjitra/cm12 | drivers/cpufreq/cpufreq.c | C | gpl-2.0 | 53,432 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Thu Jul 27 09:16:47 EDT 2017 -->
<title>D-Index</title>
<meta name="date" content="2017-07-27">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="D-Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-3.html">Prev Letter</a></li>
<li><a href="index-5.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-4.html" target="_top">Frames</a></li>
<li><a href="index-4.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">I</a> <a href="index-9.html">J</a> <a href="index-10.html">L</a> <a href="index-11.html">M</a> <a href="index-12.html">N</a> <a href="index-13.html">O</a> <a href="index-14.html">R</a> <a href="index-15.html">S</a> <a href="index-16.html">T</a> <a href="index-17.html">V</a> <a href="index-18.html">Z</a> <a name="I:D">
<!-- -->
</a>
<h2 class="title">D</h2>
<dl>
<dt><a href="../org/paces/Stata/Variables/DataColumn.html" title="class in org.paces.Stata.Variables"><span class="typeNameLink">DataColumn</span></a> - Class in <a href="../org/paces/Stata/Variables/package-summary.html">org.paces.Stata.Variables</a></dt>
<dd>
<div class="block">Class to return all values of a single Stata variable.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/Variables/DataColumn.html#DataColumn-java.lang.Integer-">DataColumn(Integer)</a></span> - Constructor for class org.paces.Stata.Variables.<a href="../org/paces/Stata/Variables/DataColumn.html" title="class in org.paces.Stata.Variables">DataColumn</a></dt>
<dd>
<div class="block">Generic constructor for the class</div>
</dd>
<dt><a href="../org/paces/Stata/DataRecords/DataRecord.html" title="class in org.paces.Stata.DataRecords"><span class="typeNameLink">DataRecord</span></a> - Class in <a href="../org/paces/Stata/DataRecords/package-summary.html">org.paces.Stata.DataRecords</a></dt>
<dd>
<div class="block">A POJO representation of a single observation from the Stata dataset
loaded in memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecord.html#DataRecord-java.lang.Long-org.paces.Stata.MetaData.Meta-">DataRecord(Long, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecord.html" title="class in org.paces.Stata.DataRecords">DataRecord</a></dt>
<dd>
<div class="block">Constructor method for DataRecord class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecord.html#DataRecord-java.lang.Integer-org.paces.Stata.MetaData.Meta-">DataRecord(Integer, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecord.html" title="class in org.paces.Stata.DataRecords">DataRecord</a></dt>
<dd>
<div class="block">Constructor method for DataRecord class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecord.html#DataRecord-java.lang.Long-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecord(Long, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecord.html" title="class in org.paces.Stata.DataRecords">DataRecord</a></dt>
<dd>
<div class="block">Constructor method for DataRecord class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecord.html#DataRecord-java.lang.Integer-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecord(Integer, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecord.html" title="class in org.paces.Stata.DataRecords">DataRecord</a></dt>
<dd>
<div class="block">Constructor method for DataRecord class</div>
</dd>
<dt><a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html" title="class in org.paces.Stata.DataRecords"><span class="typeNameLink">DataRecordByteArray</span></a> - Class in <a href="../org/paces/Stata/DataRecords/package-summary.html">org.paces.Stata.DataRecords</a></dt>
<dd>
<div class="block">Creates an Array of Bytes for Individual Observation</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html#DataRecordByteArray-java.lang.Long-org.paces.Stata.MetaData.Meta-">DataRecordByteArray(Long, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html" title="class in org.paces.Stata.DataRecords">DataRecordByteArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordByteArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html#DataRecordByteArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-">DataRecordByteArray(Integer, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html" title="class in org.paces.Stata.DataRecords">DataRecordByteArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html#DataRecordByteArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordByteArray(Integer, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html" title="class in org.paces.Stata.DataRecords">DataRecordByteArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html#DataRecordByteArray-java.lang.Long-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordByteArray(Long, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordByteArray.html" title="class in org.paces.Stata.DataRecords">DataRecordByteArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordByteArray class</div>
</dd>
<dt><a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html" title="class in org.paces.Stata.DataRecords"><span class="typeNameLink">DataRecordDoubleArray</span></a> - Class in <a href="../org/paces/Stata/DataRecords/package-summary.html">org.paces.Stata.DataRecords</a></dt>
<dd>
<div class="block">Creates an Array of Doubles for Individual Observation</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html#DataRecordDoubleArray-java.lang.Long-org.paces.Stata.MetaData.Meta-">DataRecordDoubleArray(Long, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html" title="class in org.paces.Stata.DataRecords">DataRecordDoubleArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordDoubleArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html#DataRecordDoubleArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-">DataRecordDoubleArray(Integer, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html" title="class in org.paces.Stata.DataRecords">DataRecordDoubleArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordDoubleArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html#DataRecordDoubleArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordDoubleArray(Integer, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html" title="class in org.paces.Stata.DataRecords">DataRecordDoubleArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html#DataRecordDoubleArray-java.lang.Long-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordDoubleArray(Long, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordDoubleArray.html" title="class in org.paces.Stata.DataRecords">DataRecordDoubleArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordDoubleArray class</div>
</dd>
<dt><a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html" title="class in org.paces.Stata.DataRecords"><span class="typeNameLink">DataRecordIntArray</span></a> - Class in <a href="../org/paces/Stata/DataRecords/package-summary.html">org.paces.Stata.DataRecords</a></dt>
<dd>
<div class="block">Creates an Array of Integers for Individual Observation</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html#DataRecordIntArray-java.lang.Long-org.paces.Stata.MetaData.Meta-">DataRecordIntArray(Long, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html" title="class in org.paces.Stata.DataRecords">DataRecordIntArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordIntArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html#DataRecordIntArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-">DataRecordIntArray(Integer, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html" title="class in org.paces.Stata.DataRecords">DataRecordIntArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html#DataRecordIntArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordIntArray(Integer, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html" title="class in org.paces.Stata.DataRecords">DataRecordIntArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html#DataRecordIntArray-java.lang.Long-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordIntArray(Long, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordIntArray.html" title="class in org.paces.Stata.DataRecords">DataRecordIntArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordIntArray class</div>
</dd>
<dt><a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html" title="class in org.paces.Stata.DataRecords"><span class="typeNameLink">DataRecordLongArray</span></a> - Class in <a href="../org/paces/Stata/DataRecords/package-summary.html">org.paces.Stata.DataRecords</a></dt>
<dd>
<div class="block">Creates an Array of Longs for Individual Observation</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html#DataRecordLongArray-java.lang.Long-org.paces.Stata.MetaData.Meta-">DataRecordLongArray(Long, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html" title="class in org.paces.Stata.DataRecords">DataRecordLongArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordLongArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html#DataRecordLongArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-">DataRecordLongArray(Integer, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html" title="class in org.paces.Stata.DataRecords">DataRecordLongArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html#DataRecordLongArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordLongArray(Integer, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html" title="class in org.paces.Stata.DataRecords">DataRecordLongArray</a></dt>
<dd>
<div class="block">Constructor for use with Stata 13 API</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html#DataRecordLongArray-java.lang.Long-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordLongArray(Long, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordLongArray.html" title="class in org.paces.Stata.DataRecords">DataRecordLongArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordLongArray class</div>
</dd>
<dt><a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html" title="class in org.paces.Stata.DataRecords"><span class="typeNameLink">DataRecordStringArray</span></a> - Class in <a href="../org/paces/Stata/DataRecords/package-summary.html">org.paces.Stata.DataRecords</a></dt>
<dd>
<div class="block">Creates an Array of Strings for Individual Observation</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html#DataRecordStringArray-java.lang.Long-org.paces.Stata.MetaData.Meta-">DataRecordStringArray(Long, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html" title="class in org.paces.Stata.DataRecords">DataRecordStringArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordStringArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html#DataRecordStringArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-">DataRecordStringArray(Integer, Meta)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html" title="class in org.paces.Stata.DataRecords">DataRecordStringArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordStringArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html#DataRecordStringArray-java.lang.Integer-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordStringArray(Integer, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html" title="class in org.paces.Stata.DataRecords">DataRecordStringArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordStringArray class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html#DataRecordStringArray-java.lang.Long-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataRecordStringArray(Long, Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataRecords.<a href="../org/paces/Stata/DataRecords/DataRecordStringArray.html" title="class in org.paces.Stata.DataRecords">DataRecordStringArray</a></dt>
<dd>
<div class="block">Constructor method for DataRecordStringArray class</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSet.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSet</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">A POJO representation of the Stata dataset currently in memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSet.html#DataSet-org.paces.Stata.MetaData.Meta-">DataSet(Meta)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSet.html" title="class in org.paces.Stata.DataSets">DataSet</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSetByteArrays.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSetByteArrays</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">A 2d Array of Bytes containing the data from the active data set in memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetByteArrays.html#DataSetByteArrays-org.paces.Stata.MetaData.Meta-">DataSetByteArrays(Meta)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetByteArrays.html" title="class in org.paces.Stata.DataSets">DataSetByteArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetByteArrays.html#DataSetByteArrays-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataSetByteArrays(Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetByteArrays.html" title="class in org.paces.Stata.DataSets">DataSetByteArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSetDoubleArrays.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSetDoubleArrays</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">A 2d Array of Doubles containing the data from the active data set in memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetDoubleArrays.html#DataSetDoubleArrays-org.paces.Stata.MetaData.Meta-">DataSetDoubleArrays(Meta)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetDoubleArrays.html" title="class in org.paces.Stata.DataSets">DataSetDoubleArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetDoubleArrays.html#DataSetDoubleArrays-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataSetDoubleArrays(Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetDoubleArrays.html" title="class in org.paces.Stata.DataSets">DataSetDoubleArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSetFactory.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSetFactory</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">Object used to initialize DataSet class objects given the dataset meta
data and an argument defining the return type to be created by the
method.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetFactory.html#DataSetFactory--">DataSetFactory()</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetFactory.html" title="class in org.paces.Stata.DataSets">DataSetFactory</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetFactory.html#dataSetFactory-java.lang.String-org.paces.Stata.MetaData.Meta-">dataSetFactory(String, Meta)</a></span> - Static method in class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetFactory.html" title="class in org.paces.Stata.DataSets">DataSetFactory</a></dt>
<dd>
<div class="block">Method to create a DataSet class object</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSetIntArrays.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSetIntArrays</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">A 2d Array of Integers containing the data from the active data set in
memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetIntArrays.html#DataSetIntArrays-org.paces.Stata.MetaData.Meta-">DataSetIntArrays(Meta)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetIntArrays.html" title="class in org.paces.Stata.DataSets">DataSetIntArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetIntArrays.html#DataSetIntArrays-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataSetIntArrays(Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetIntArrays.html" title="class in org.paces.Stata.DataSets">DataSetIntArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSetLongArrays.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSetLongArrays</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">A 2d Array of Longs containing the data from the active data set in memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetLongArrays.html#DataSetLongArrays-org.paces.Stata.MetaData.Meta-">DataSetLongArrays(Meta)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetLongArrays.html" title="class in org.paces.Stata.DataSets">DataSetLongArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetLongArrays.html#DataSetLongArrays-org.paces.Stata.MetaData.Meta-java.lang.Number-">DataSetLongArrays(Meta, Number)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetLongArrays.html" title="class in org.paces.Stata.DataSets">DataSetLongArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><a href="../org/paces/Stata/DataSets/DataSetStringArrays.html" title="class in org.paces.Stata.DataSets"><span class="typeNameLink">DataSetStringArrays</span></a> - Class in <a href="../org/paces/Stata/DataSets/package-summary.html">org.paces.Stata.DataSets</a></dt>
<dd>
<div class="block">A 2d Array of Strings containing the data from the active data set in memory.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/DataSets/DataSetStringArrays.html#DataSetStringArrays-org.paces.Stata.MetaData.Meta-">DataSetStringArrays(Meta)</a></span> - Constructor for class org.paces.Stata.DataSets.<a href="../org/paces/Stata/DataSets/DataSetStringArrays.html" title="class in org.paces.Stata.DataSets">DataSetStringArrays</a></dt>
<dd>
<div class="block">Generic constructor method for the class</div>
</dd>
<dt><a href="../org/paces/Stata/MetaData/DataSource.html" title="class in org.paces.Stata.MetaData"><span class="typeNameLink">DataSource</span></a> - Class in <a href="../org/paces/Stata/MetaData/package-summary.html">org.paces.Stata.MetaData</a></dt>
<dd>
<div class="block">Class with Static Methods to retrieve data about the source of the Stata data
files.</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/MetaData/DataSource.html#DataSource--">DataSource()</a></span> - Constructor for class org.paces.Stata.MetaData.<a href="../org/paces/Stata/MetaData/DataSource.html" title="class in org.paces.Stata.MetaData">DataSource</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/Observations/Obs13.html#dataType">dataType</a></span> - Variable in class org.paces.Stata.Observations.<a href="../org/paces/Stata/Observations/Obs13.html" title="class in org.paces.Stata.Observations">Obs13</a></dt>
<dd>
<div class="block">Member used to pass type parameters to accessor methods</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/Observations/Obs14.html#dataType">dataType</a></span> - Variable in class org.paces.Stata.Observations.<a href="../org/paces/Stata/Observations/Obs14.html" title="class in org.paces.Stata.Observations">Obs14</a></dt>
<dd>
<div class="block">Member used to pass type parameters to accessor methods</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/Variables/VarDisplay.html#datefmt">datefmt</a></span> - Static variable in class org.paces.Stata.Variables.<a href="../org/paces/Stata/Variables/VarDisplay.html" title="class in org.paces.Stata.Variables">VarDisplay</a></dt>
<dd>
<div class="block">Private member that defines regular expression to match any of the
basic Date/DateTime formats in Stata</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/MetaData/Variables.html#displayFmt">displayFmt</a></span> - Variable in class org.paces.Stata.MetaData.<a href="../org/paces/Stata/MetaData/Variables.html" title="class in org.paces.Stata.MetaData">Variables</a></dt>
<dd>
<div class="block">Class containing display formats (used to test if variabel contains
date/date time values)</div>
</dd>
<dt><span class="memberNameLink"><a href="../org/paces/Stata/Missing/StataMissings.html#doubleMissing--">doubleMissing()</a></span> - Static method in class org.paces.Stata.Missing.<a href="../org/paces/Stata/Missing/StataMissings.html" title="class in org.paces.Stata.Missing">StataMissings</a></dt>
<dd>
<div class="block">Method returning a map object containing Stata missing values and
their string masks (e.g., .a - .z)</div>
</dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">I</a> <a href="index-9.html">J</a> <a href="index-10.html">L</a> <a href="index-11.html">M</a> <a href="index-12.html">N</a> <a href="index-13.html">O</a> <a href="index-14.html">R</a> <a href="index-15.html">S</a> <a href="index-16.html">T</a> <a href="index-17.html">V</a> <a href="index-18.html">Z</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-3.html">Prev Letter</a></li>
<li><a href="index-5.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-4.html" target="_top">Frames</a></li>
<li><a href="index-4.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| wbuchanan/StataJavaUtilities | docs/index-files/index-4.html | HTML | gpl-2.0 | 30,269 |
<?php
if (extension_loaded('xhprof')) {
include_once '/usr/share/php/xhprof_lib/utils/xhprof_lib.php';
include_once '/usr/share/php/xhprof_lib/utils/xhprof_runs.php';
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
}
require_once '../DSON.php';
use \zegl\dson\DSON;
$tests = array(
array('poop' => json_decode('"\ud83d\udca9"')),
'Hej, jag är en text med fina krumilurer'
);
foreach ($tests as $v)
{
var_dump($v);
$encode = DSON::encode($v);
$decode = DSON::decode($encode, true);
var_dump($decode);
}
if (extension_loaded('xhprof')) {
$xhprof_data = xhprof_disable();
$xhprof_runs = new XHProfRuns_Default('/storage/xhprof/');
$a = $xhprof_runs->save_run($xhprof_data, 'dson');
var_dump($a);
}
| zegl/dson-php | tests/misc.php | PHP | gpl-2.0 | 761 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if !ENABLE_EFI
# include <errno.h>
#endif
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "sd-id128.h"
#include "efi/loader-features.h"
#include "time-util.h"
#define EFI_VENDOR_LOADER SD_ID128_MAKE(4a,67,b0,82,0a,4c,41,cf,b6,c7,44,0b,29,bb,8c,4f)
#define EFI_VENDOR_GLOBAL SD_ID128_MAKE(8b,e4,df,61,93,ca,11,d2,aa,0d,00,e0,98,03,2b,8c)
#define EFI_VENDOR_SYSTEMD SD_ID128_MAKE(8c,f2,64,4b,4b,0b,42,8f,93,87,6d,87,60,50,dc,67)
#define EFI_VARIABLE_NON_VOLATILE 0x0000000000000001
#define EFI_VARIABLE_BOOTSERVICE_ACCESS 0x0000000000000002
#define EFI_VARIABLE_RUNTIME_ACCESS 0x0000000000000004
#if ENABLE_EFI
char* efi_variable_path(sd_id128_t vendor, const char *name);
int efi_get_variable(sd_id128_t vendor, const char *name, uint32_t *attribute, void **value, size_t *size);
int efi_get_variable_string(sd_id128_t vendor, const char *name, char **p);
int efi_set_variable(sd_id128_t vendor, const char *name, const void *value, size_t size);
int efi_set_variable_string(sd_id128_t vendor, const char *name, const char *p);
bool is_efi_boot(void);
bool is_efi_secure_boot(void);
bool is_efi_secure_boot_setup_mode(void);
int cache_efi_options_variable(void);
int systemd_efi_options_variable(char **line);
#else
static inline char* efi_variable_path(sd_id128_t vendor, const char *name) {
return NULL;
}
static inline int efi_get_variable(sd_id128_t vendor, const char *name, uint32_t *attribute, void **value, size_t *size) {
return -EOPNOTSUPP;
}
static inline int efi_get_variable_string(sd_id128_t vendor, const char *name, char **p) {
return -EOPNOTSUPP;
}
static inline int efi_set_variable(sd_id128_t vendor, const char *name, const void *value, size_t size) {
return -EOPNOTSUPP;
}
static inline int efi_set_variable_string(sd_id128_t vendor, const char *name, const char *p) {
return -EOPNOTSUPP;
}
static inline bool is_efi_boot(void) {
return false;
}
static inline bool is_efi_secure_boot(void) {
return false;
}
static inline bool is_efi_secure_boot_setup_mode(void) {
return false;
}
static inline int cache_efi_options_variable(void) {
return -EOPNOTSUPP;
}
static inline int systemd_efi_options_variable(char **line) {
return -ENODATA;
}
#endif
| endlessm/systemd | src/basic/efivars.h | C | gpl-2.0 | 2,362 |
package utilities;
/**
* A class that contains user's roles
* @author Alexander
*/
public class CMRoles {
public static final int GUEST_USER = 0;
public static final String GUEST_DESCRIPTION = "Guest User";
public static final int SIMPLE_USER = 1;
public static final String SIMPLE_DESCRIPTION = "Simple User";
public static final int MODERATOR_USER = 2;
public static final String MODERATOR_DESCRIPTION = "Moderator User";
public static final int ADMINISTRATOR_USER = 3;
public static final String ADMINISTRATOR_DESCRIPTION = "Administrator User";
public static String getDescription(int role){
switch (role){
case GUEST_USER:
return GUEST_DESCRIPTION;
case SIMPLE_USER:
return SIMPLE_DESCRIPTION;
case MODERATOR_USER:
return MODERATOR_DESCRIPTION;
case ADMINISTRATOR_USER:
return ADMINISTRATOR_DESCRIPTION;
default:
return "Role not defined";
}
}
}
| am1120/CarMechanic | webapp/src/java/utilities/CMRoles.java | Java | gpl-2.0 | 1,157 |
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands;
/**
* @link http://redis.io/commands/zcard
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ZSetCardinality extends Command
{
/**
* {@inheritdoc}
*/
public function getId()
{
return 'ZCARD';
}
}
| nickteagle/redis | sites/all/modules/contrib/redis_ssi/predis/lib/Predis/Commands/ZSetCardinality.php | PHP | gpl-2.0 | 513 |
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/*
* Nautilus
*
* Copyright (C) 1999, 2000 Eazel, Inc.
*
* Nautilus is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* Nautilus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Authors: John Sullivan <sullivan@eazel.com>
*/
/* nautilus-bookmark-list.c - implementation of centralized list of bookmarks.
*/
#include <config.h>
#include "nautilus-bookmark-list.h"
#include <libnautilus-private/nautilus-file-utilities.h>
#include <libnautilus-private/nautilus-file.h>
#include <libnautilus-private/nautilus-icon-names.h>
#include <eel/eel-glib-extensions.h>
#include <eel/eel-string.h>
#include <gio/gio.h>
#define MAX_BOOKMARK_LENGTH 80
enum {
CONTENTS_CHANGED,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL];
static char *window_geometry;
/* forward declarations */
static void destroy (GtkObject *object);
static void nautilus_bookmark_list_load_file (NautilusBookmarkList *bookmarks);
static void nautilus_bookmark_list_save_file (NautilusBookmarkList *bookmarks);
G_DEFINE_TYPE(NautilusBookmarkList, nautilus_bookmark_list, GTK_TYPE_OBJECT)
static NautilusBookmark *
new_bookmark_from_uri (const char *uri, const char *label)
{
NautilusBookmark *new_bookmark;
NautilusFile *file;
char *name;
GIcon *icon;
gboolean has_label;
GFile *location;
location = NULL;
if (uri) {
location = g_file_new_for_uri (uri);
}
has_label = FALSE;
if (!label) {
name = nautilus_compute_title_for_location (location);
} else {
name = g_strdup (label);
has_label = TRUE;
}
new_bookmark = NULL;
if (uri) {
file = nautilus_file_get (location);
icon = NULL;
if (nautilus_file_check_if_ready (file,
NAUTILUS_FILE_ATTRIBUTES_FOR_ICON)) {
icon = nautilus_file_get_gicon (file, 0);
}
nautilus_file_unref (file);
if (icon == NULL) {
icon = g_themed_icon_new (NAUTILUS_ICON_FOLDER);
}
new_bookmark = nautilus_bookmark_new_with_icon (location, name, has_label, icon);
g_object_unref (icon);
}
g_free (name);
g_object_unref (location);
return new_bookmark;
}
static GFile *
nautilus_bookmark_list_get_file (void)
{
char *filename;
GFile *file;
filename = g_build_filename (g_get_home_dir (),
".gtk-bookmarks",
NULL);
file = g_file_new_for_path (filename);
g_free (filename);
return file;
}
/* Initialization. */
static void
nautilus_bookmark_list_class_init (NautilusBookmarkListClass *class)
{
GtkObjectClass *object_class;
object_class = GTK_OBJECT_CLASS (class);
object_class->destroy = destroy;
signals[CONTENTS_CHANGED] =
g_signal_new ("contents_changed",
G_TYPE_FROM_CLASS (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NautilusBookmarkListClass,
contents_changed),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
}
static void
bookmark_monitor_changed_cb (GFileMonitor *monitor,
GFile *child,
GFile *other_file,
GFileMonitorEvent eflags,
gpointer user_data)
{
if (eflags == G_FILE_MONITOR_EVENT_CHANGED ||
eflags == G_FILE_MONITOR_EVENT_CREATED) {
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (NAUTILUS_BOOKMARK_LIST (user_data)));
nautilus_bookmark_list_load_file (NAUTILUS_BOOKMARK_LIST (user_data));
g_signal_emit (user_data, signals[CONTENTS_CHANGED], 0);
}
}
static void
nautilus_bookmark_list_init (NautilusBookmarkList *bookmarks)
{
GFile *file;
nautilus_bookmark_list_load_file (bookmarks);
file = nautilus_bookmark_list_get_file ();
bookmarks->monitor = g_file_monitor_file (file, 0, NULL, NULL);
g_signal_connect (bookmarks->monitor, "changed",
G_CALLBACK (bookmark_monitor_changed_cb), bookmarks);
g_object_unref (file);
}
static void
bookmark_in_list_changed_callback (NautilusBookmark *bookmark,
NautilusBookmarkList *bookmarks)
{
g_assert (NAUTILUS_IS_BOOKMARK (bookmark));
g_assert (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
/* Save changes so we'll have the good icon next time. */
nautilus_bookmark_list_contents_changed (bookmarks);
}
static void
stop_monitoring_bookmark (NautilusBookmarkList *bookmarks,
NautilusBookmark *bookmark)
{
g_signal_handlers_disconnect_by_func (bookmark,
bookmark_in_list_changed_callback,
bookmarks);
}
static void
stop_monitoring_one (gpointer data, gpointer user_data)
{
g_assert (NAUTILUS_IS_BOOKMARK (data));
g_assert (NAUTILUS_IS_BOOKMARK_LIST (user_data));
stop_monitoring_bookmark (NAUTILUS_BOOKMARK_LIST (user_data),
NAUTILUS_BOOKMARK (data));
}
static void
clear (NautilusBookmarkList *bookmarks)
{
g_list_foreach (bookmarks->list, stop_monitoring_one, bookmarks);
eel_g_object_list_free (bookmarks->list);
bookmarks->list = NULL;
}
static void
destroy (GtkObject *object)
{
if (NAUTILUS_BOOKMARK_LIST (object)->monitor != NULL) {
g_file_monitor_cancel (NAUTILUS_BOOKMARK_LIST (object)->monitor);
NAUTILUS_BOOKMARK_LIST (object)->monitor = NULL;
}
clear (NAUTILUS_BOOKMARK_LIST (object));
}
static void
insert_bookmark_internal (NautilusBookmarkList *bookmarks,
NautilusBookmark *bookmark,
int index)
{
bookmarks->list = g_list_insert (bookmarks->list, bookmark, index);
g_signal_connect_object (bookmark, "appearance_changed",
G_CALLBACK (bookmark_in_list_changed_callback), bookmarks, 0);
g_signal_connect_object (bookmark, "contents_changed",
G_CALLBACK (bookmark_in_list_changed_callback), bookmarks, 0);
}
/**
* nautilus_bookmark_list_append:
*
* Append a bookmark to a bookmark list.
* @bookmarks: NautilusBookmarkList to append to.
* @bookmark: Bookmark to append a copy of.
**/
void
nautilus_bookmark_list_append (NautilusBookmarkList *bookmarks,
NautilusBookmark *bookmark)
{
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
g_return_if_fail (NAUTILUS_IS_BOOKMARK (bookmark));
insert_bookmark_internal (bookmarks,
nautilus_bookmark_copy (bookmark),
-1);
nautilus_bookmark_list_contents_changed (bookmarks);
}
/**
* nautilus_bookmark_list_contains:
*
* Check whether a bookmark with matching name and url is already in the list.
* @bookmarks: NautilusBookmarkList to check contents of.
* @bookmark: NautilusBookmark to match against.
*
* Return value: TRUE if matching bookmark is in list, FALSE otherwise
**/
gboolean
nautilus_bookmark_list_contains (NautilusBookmarkList *bookmarks,
NautilusBookmark *bookmark)
{
g_return_val_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks), FALSE);
g_return_val_if_fail (NAUTILUS_IS_BOOKMARK (bookmark), FALSE);
return g_list_find_custom (bookmarks->list,
(gpointer)bookmark,
nautilus_bookmark_compare_with)
!= NULL;
}
/**
* nautilus_bookmark_list_contents_changed:
*
* Save the bookmark list to disk, and emit the contents_changed signal.
* @bookmarks: NautilusBookmarkList whose contents have been modified.
**/
void
nautilus_bookmark_list_contents_changed (NautilusBookmarkList *bookmarks)
{
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
nautilus_bookmark_list_save_file (bookmarks);
g_signal_emit (bookmarks, signals[CONTENTS_CHANGED], 0);
}
/**
* nautilus_bookmark_list_delete_item_at:
*
* Delete the bookmark at the specified position.
* @bookmarks: the list of bookmarks.
* @index: index, must be less than length of list.
**/
void
nautilus_bookmark_list_delete_item_at (NautilusBookmarkList *bookmarks,
guint index)
{
GList *doomed;
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
g_return_if_fail (index < g_list_length (bookmarks->list));
doomed = g_list_nth (bookmarks->list, index);
bookmarks->list = g_list_remove_link (bookmarks->list, doomed);
g_assert (NAUTILUS_IS_BOOKMARK (doomed->data));
stop_monitoring_bookmark (bookmarks, NAUTILUS_BOOKMARK (doomed->data));
g_object_unref (doomed->data);
g_list_free_1 (doomed);
nautilus_bookmark_list_contents_changed (bookmarks);
}
/**
* nautilus_bookmark_list_delete_items_with_uri:
*
* Delete all bookmarks with the given uri.
* @bookmarks: the list of bookmarks.
* @uri: The uri to match.
**/
void
nautilus_bookmark_list_delete_items_with_uri (NautilusBookmarkList *bookmarks,
const char *uri)
{
GList *node, *next;
gboolean list_changed;
char *bookmark_uri;
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
g_return_if_fail (uri != NULL);
list_changed = FALSE;
for (node = bookmarks->list; node != NULL; node = next) {
next = node->next;
bookmark_uri = nautilus_bookmark_get_uri (NAUTILUS_BOOKMARK (node->data));
if (eel_strcmp (bookmark_uri, uri) == 0) {
bookmarks->list = g_list_remove_link (bookmarks->list, node);
stop_monitoring_bookmark (bookmarks, NAUTILUS_BOOKMARK (node->data));
g_object_unref (node->data);
g_list_free_1 (node);
list_changed = TRUE;
}
g_free (bookmark_uri);
}
if (list_changed) {
nautilus_bookmark_list_contents_changed (bookmarks);
}
}
/**
* nautilus_bookmark_list_get_window_geometry:
*
* Get a string representing the bookmark_list's window's geometry.
* This is the value set earlier by nautilus_bookmark_list_set_window_geometry.
* @bookmarks: the list of bookmarks associated with the window.
* Return value: string representation of window's geometry, suitable for
* passing to gnome_parse_geometry(), or NULL if
* no window geometry has yet been saved for this bookmark list.
**/
const char *
nautilus_bookmark_list_get_window_geometry (NautilusBookmarkList *bookmarks)
{
return window_geometry;
}
/**
* nautilus_bookmark_list_insert_item:
*
* Insert a bookmark at a specified position.
* @bookmarks: the list of bookmarks.
* @index: the position to insert the bookmark at.
* @new_bookmark: the bookmark to insert a copy of.
**/
void
nautilus_bookmark_list_insert_item (NautilusBookmarkList *bookmarks,
NautilusBookmark *new_bookmark,
guint index)
{
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
g_return_if_fail (index <= g_list_length (bookmarks->list));
insert_bookmark_internal (bookmarks,
nautilus_bookmark_copy (new_bookmark),
index);
nautilus_bookmark_list_contents_changed (bookmarks);
}
/**
* nautilus_bookmark_list_item_at:
*
* Get the bookmark at the specified position.
* @bookmarks: the list of bookmarks.
* @index: index, must be less than length of list.
*
* Return value: the bookmark at position @index in @bookmarks.
**/
NautilusBookmark *
nautilus_bookmark_list_item_at (NautilusBookmarkList *bookmarks, guint index)
{
g_return_val_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks), NULL);
g_return_val_if_fail (index < g_list_length (bookmarks->list), NULL);
return NAUTILUS_BOOKMARK (g_list_nth_data (bookmarks->list, index));
}
/**
* nautilus_bookmark_list_length:
*
* Get the number of bookmarks in the list.
* @bookmarks: the list of bookmarks.
*
* Return value: the length of the bookmark list.
**/
guint
nautilus_bookmark_list_length (NautilusBookmarkList *bookmarks)
{
g_return_val_if_fail (NAUTILUS_IS_BOOKMARK_LIST(bookmarks), 0);
return g_list_length (bookmarks->list);
}
/**
* nautilus_bookmark_list_load_file:
*
* Reads bookmarks from file, clobbering contents in memory.
* @bookmarks: the list of bookmarks to fill with file contents.
**/
static void
nautilus_bookmark_list_load_file (NautilusBookmarkList *bookmarks)
{
GFile *file;
char *contents;
GError *error = NULL;
file = nautilus_bookmark_list_get_file ();
/* Wipe out old list. */
clear (bookmarks);
if (g_file_load_contents (file, NULL, &contents, NULL, NULL, &error)) {
char **lines;
int i;
lines = g_strsplit (contents, "\n", -1);
for (i = 0; lines[i]; i++) {
/* Ignore empty or invalid lines that cannot be parsed properly */
if (lines[i][0] != '\0' && lines[i][0] != ' ') {
/* gtk 2.7/2.8 might have labels appended to bookmarks which are separated by a space */
/* we must seperate the bookmark uri and the potential label */
char *space, *label;
label = NULL;
space = strchr (lines[i], ' ');
if (space) {
*space = '\0';
label = g_strdup (space + 1);
}
insert_bookmark_internal (bookmarks,
new_bookmark_from_uri (lines[i], label),
-1);
g_free (label);
}
}
g_free (contents);
g_strfreev (lines);
}
else if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
g_warning ("Could not load bookmark file: %s\n", error->message);
g_error_free (error);
}
g_object_unref (file);
}
/**
* nautilus_bookmark_list_new:
*
* Create a new bookmark_list, with contents read from disk.
*
* Return value: A pointer to the new widget.
**/
NautilusBookmarkList *
nautilus_bookmark_list_new (void)
{
NautilusBookmarkList *list;
list = NAUTILUS_BOOKMARK_LIST (g_object_new (NAUTILUS_TYPE_BOOKMARK_LIST, NULL));
return g_object_ref_sink (list);
}
/**
* nautilus_bookmark_list_save_file:
*
* Save bookmarks to disk.
* @bookmarks: the list of bookmarks to save.
**/
static void
nautilus_bookmark_list_save_file (NautilusBookmarkList *bookmarks)
{
GFile *file;
GOutputStream *out;
GError *error = NULL;
GList *l;
/* temporarily disable bookmark file monitoring when writing file */
if (bookmarks->monitor != NULL) {
g_file_monitor_cancel (bookmarks->monitor);
bookmarks->monitor = NULL;
}
file = nautilus_bookmark_list_get_file ();
out = (GOutputStream *)g_file_replace (file, NULL, FALSE, 0, NULL, &error);
if (out == NULL) {
g_warning ("Error opening bookmark file: %s\n", error->message);
goto error;
}
for (l = bookmarks->list; l; l = l->next) {
NautilusBookmark *bookmark;
char *bookmark_string;
bookmark = NAUTILUS_BOOKMARK (l->data);
/* make sure we save label if it has one for compatibility with GTK 2.7 and 2.8 */
if (nautilus_bookmark_get_has_custom_name (bookmark)) {
char *label, *uri;
label = nautilus_bookmark_get_name (bookmark);
uri = nautilus_bookmark_get_uri (bookmark);
bookmark_string = g_strconcat (uri, " ", label, "\n", NULL);
g_free (uri);
g_free (label);
} else {
char *uri;
uri = nautilus_bookmark_get_uri (bookmark);
bookmark_string = g_strconcat (uri, "\n", NULL);
g_free (uri);
}
if (!g_output_stream_write_all (out,
bookmark_string,
strlen (bookmark_string),
NULL, NULL,
&error)) {
g_warning ("writing %s to bookmark file failed: %s\n",
bookmark_string, error->message);
g_free (bookmark_string);
goto error;
}
g_free (bookmark_string);
}
if (!g_output_stream_close (out, NULL, &error)) {
g_warning ("Error closing bookmark file: %s\n", error->message);
}
error:
if (error)
g_error_free (error);
/* re-enable bookmark file monitoring */
bookmarks->monitor = g_file_monitor_file (file, 0, NULL, NULL);
g_signal_connect (bookmarks->monitor, "changed",
G_CALLBACK (bookmark_monitor_changed_cb), bookmarks);
if (out)
g_object_unref (out);
g_object_unref (file);
}
/**
* nautilus_bookmark_list_set_window_geometry:
*
* Set a bookmarks window's geometry (position & size), in string form. This is
* stored to disk by this class, and can be retrieved later in
* the same session or in a future session.
* @bookmarks: the list of bookmarks associated with the window.
* @geometry: the new window geometry string.
**/
void
nautilus_bookmark_list_set_window_geometry (NautilusBookmarkList *bookmarks,
const char *geometry)
{
g_return_if_fail (NAUTILUS_IS_BOOKMARK_LIST (bookmarks));
g_return_if_fail (geometry != NULL);
g_free (window_geometry);
window_geometry = g_strdup (geometry);
nautilus_bookmark_list_save_file (bookmarks);
}
| awalton/nautilus | src/nautilus-bookmark-list.c | C | gpl-2.0 | 16,576 |
// Code generated by entc, DO NOT EDIT.
package model
import (
"context"
"errors"
"fmt"
"hello-ent/model/person"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// PersonCreate is the builder for creating a Person entity.
type PersonCreate struct {
config
mutation *PersonMutation
hooks []Hook
}
// SetEmail sets the "email" field.
func (pc *PersonCreate) SetEmail(s string) *PersonCreate {
pc.mutation.SetEmail(s)
return pc
}
// SetAge sets the "age" field.
func (pc *PersonCreate) SetAge(i int) *PersonCreate {
pc.mutation.SetAge(i)
return pc
}
// SetFirstName sets the "first_name" field.
func (pc *PersonCreate) SetFirstName(s string) *PersonCreate {
pc.mutation.SetFirstName(s)
return pc
}
// SetLastName sets the "last_name" field.
func (pc *PersonCreate) SetLastName(s string) *PersonCreate {
pc.mutation.SetLastName(s)
return pc
}
// SetCreatedAt sets the "created_at" field.
func (pc *PersonCreate) SetCreatedAt(t time.Time) *PersonCreate {
pc.mutation.SetCreatedAt(t)
return pc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (pc *PersonCreate) SetNillableCreatedAt(t *time.Time) *PersonCreate {
if t != nil {
pc.SetCreatedAt(*t)
}
return pc
}
// Mutation returns the PersonMutation object of the builder.
func (pc *PersonCreate) Mutation() *PersonMutation {
return pc.mutation
}
// Save creates the Person in the database.
func (pc *PersonCreate) Save(ctx context.Context) (*Person, error) {
var (
err error
node *Person
)
pc.defaults()
if len(pc.hooks) == 0 {
if err = pc.check(); err != nil {
return nil, err
}
node, err = pc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PersonMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = pc.check(); err != nil {
return nil, err
}
pc.mutation = mutation
node, err = pc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(pc.hooks) - 1; i >= 0; i-- {
mut = pc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, pc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (pc *PersonCreate) SaveX(ctx context.Context) *Person {
v, err := pc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// defaults sets the default values of the builder before save.
func (pc *PersonCreate) defaults() {
if _, ok := pc.mutation.CreatedAt(); !ok {
v := person.DefaultCreatedAt()
pc.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (pc *PersonCreate) check() error {
if _, ok := pc.mutation.Email(); !ok {
return &ValidationError{Name: "email", err: errors.New("model: missing required field \"email\"")}
}
if _, ok := pc.mutation.Age(); !ok {
return &ValidationError{Name: "age", err: errors.New("model: missing required field \"age\"")}
}
if _, ok := pc.mutation.FirstName(); !ok {
return &ValidationError{Name: "first_name", err: errors.New("model: missing required field \"first_name\"")}
}
if _, ok := pc.mutation.LastName(); !ok {
return &ValidationError{Name: "last_name", err: errors.New("model: missing required field \"last_name\"")}
}
if _, ok := pc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New("model: missing required field \"created_at\"")}
}
return nil
}
func (pc *PersonCreate) sqlSave(ctx context.Context) (*Person, error) {
_node, _spec := pc.createSpec()
if err := sqlgraph.CreateNode(ctx, pc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (pc *PersonCreate) createSpec() (*Person, *sqlgraph.CreateSpec) {
var (
_node = &Person{config: pc.config}
_spec = &sqlgraph.CreateSpec{
Table: person.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: person.FieldID,
},
}
)
if value, ok := pc.mutation.Email(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: person.FieldEmail,
})
_node.Email = value
}
if value, ok := pc.mutation.Age(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: person.FieldAge,
})
_node.Age = value
}
if value, ok := pc.mutation.FirstName(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: person.FieldFirstName,
})
_node.FirstName = value
}
if value, ok := pc.mutation.LastName(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: person.FieldLastName,
})
_node.LastName = value
}
if value, ok := pc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: person.FieldCreatedAt,
})
_node.CreatedAt = value
}
return _node, _spec
}
// PersonCreateBulk is the builder for creating many Person entities in bulk.
type PersonCreateBulk struct {
config
builders []*PersonCreate
}
// Save creates the Person entities in the database.
func (pcb *PersonCreateBulk) Save(ctx context.Context) ([]*Person, error) {
specs := make([]*sqlgraph.CreateSpec, len(pcb.builders))
nodes := make([]*Person, len(pcb.builders))
mutators := make([]Mutator, len(pcb.builders))
for i := range pcb.builders {
func(i int, root context.Context) {
builder := pcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PersonMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, pcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, pcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, pcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (pcb *PersonCreateBulk) SaveX(ctx context.Context) []*Person {
v, err := pcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
| 1995parham/Learning | go/hello-ent/model/person_create.go | GO | gpl-2.0 | 7,144 |
<?php
Yii::import('console.helpers.RateableDbManagerHelper');
Yii::import('console.helpers.CommentableDbManagerHelper');
class m140329_200625_add_vote_comment_and_rate extends EDbMigration
{
public function safeUp()
{
RateableDbManagerHelper::createTables('vote', $this);
CommentableDbManagerHelper::createTables('vote', $this);
}
public function safeDown()
{
RateableDbManagerHelper::dropTables('vote', $this);
CommentableDbManagerHelper::dropTables('vote', $this);
}
} | odsfn/aes | console/migrations/m140329_200625_add_vote_comment_and_rate.php | PHP | gpl-2.0 | 528 |
@echo off
:network
ipconfig /renew
ipconfig /flushdns
echo Done...
pause >nul | sithsiri/fixme | FixMe/FixMe/fixnet.bat | Batchfile | gpl-2.0 | 79 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "BatteryService"
#include "JNIHelp.h"
#include "jni.h"
#include <utils/Log.h>
#include <utils/misc.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <linux/ioctl.h>
namespace android {
#define POWER_SUPPLY_PATH "/sys/class/power_supply"
struct FieldIds {
// members
jfieldID mAcOnline;
jfieldID mUsbOnline;
jfieldID mWirelessOnline;
jfieldID mBatteryStatus;
jfieldID mBatteryHealth;
jfieldID mBatteryPresent;
jfieldID mBatteryLevel;
jfieldID mBatteryVoltage;
jfieldID mBatteryTemperature;
jfieldID mBatteryTechnology;
};
static FieldIds gFieldIds;
struct BatteryManagerConstants {
jint statusUnknown;
jint statusCharging;
jint statusDischarging;
jint statusNotCharging;
jint statusFull;
jint healthUnknown;
jint healthGood;
jint healthOverheat;
jint healthDead;
jint healthOverVoltage;
jint healthUnspecifiedFailure;
jint healthCold;
};
static BatteryManagerConstants gConstants;
struct PowerSupplyPaths {
char* acOnlinePath;
char* usbOnlinePath;
char* wirelessOnlinePath;
char* batteryStatusPath;
char* batteryHealthPath;
char* batteryPresentPath;
char* batteryCapacityPath;
char* batteryVoltagePath;
char* batteryTemperaturePath;
char* batteryTechnologyPath;
};
static PowerSupplyPaths gPaths;
static int gVoltageDivisor = 1;
static jint getBatteryStatus(const char* status)
{
switch (status[0]) {
case 'C': return gConstants.statusCharging; // Charging
case 'D': return gConstants.statusDischarging; // Discharging
case 'F': return gConstants.statusFull; // Full
case 'N': return gConstants.statusNotCharging; // Not charging
case 'U': return gConstants.statusUnknown; // Unknown
default: {
ALOGW("Unknown battery status '%s'", status);
return gConstants.statusUnknown;
}
}
}
static jint getBatteryHealth(const char* status)
{
switch (status[0]) {
case 'C': return gConstants.healthCold; // Cold
case 'D': return gConstants.healthDead; // Dead
case 'G': return gConstants.healthGood; // Good
case 'O': {
if (strcmp(status, "Overheat") == 0) {
return gConstants.healthOverheat;
} else if (strcmp(status, "Over voltage") == 0) {
return gConstants.healthOverVoltage;
}
ALOGW("Unknown battery health[1] '%s'", status);
return gConstants.healthUnknown;
}
case 'U': {
if (strcmp(status, "Unspecified failure") == 0) {
return gConstants.healthUnspecifiedFailure;
} else if (strcmp(status, "Unknown") == 0) {
return gConstants.healthUnknown;
}
// fall through
}
default: {
ALOGW("Unknown battery health[2] '%s'", status);
return gConstants.healthUnknown;
}
}
}
static int readFromFile(const char* path, char* buf, size_t size)
{
if (!path)
return -1;
int fd = open(path, O_RDONLY, 0);
if (fd == -1) {
ALOGE("Could not open '%s'", path);
return -1;
}
ssize_t count = read(fd, buf, size);
if (count > 0) {
while (count > 0 && buf[count-1] == '\n')
count--;
buf[count] = '\0';
} else {
buf[0] = '\0';
}
close(fd);
return count;
}
static void setBooleanField(JNIEnv* env, jobject obj, const char* path, jfieldID fieldID)
{
const int SIZE = 16;
char buf[SIZE];
jboolean value = false;
if (readFromFile(path, buf, SIZE) > 0) {
if (buf[0] != '0') {
value = true;
}
}
env->SetBooleanField(obj, fieldID, value);
}
static void setIntField(JNIEnv* env, jobject obj, const char* path, jfieldID fieldID)
{
const int SIZE = 128;
char buf[SIZE];
jint value = 0;
if (readFromFile(path, buf, SIZE) > 0) {
value = atoi(buf);
}
env->SetIntField(obj, fieldID, value);
}
static void setVoltageField(JNIEnv* env, jobject obj, const char* path, jfieldID fieldID)
{
const int SIZE = 128;
char buf[SIZE];
jint value = 0;
if (readFromFile(path, buf, SIZE) > 0) {
value = atoi(buf);
value /= gVoltageDivisor;
}
env->SetIntField(obj, fieldID, value);
}
static void android_server_BatteryService_update(JNIEnv* env, jobject obj)
{
setBooleanField(env, obj, gPaths.acOnlinePath, gFieldIds.mAcOnline);
setBooleanField(env, obj, gPaths.usbOnlinePath, gFieldIds.mUsbOnline);
setBooleanField(env, obj, gPaths.wirelessOnlinePath, gFieldIds.mWirelessOnline);
setBooleanField(env, obj, gPaths.batteryPresentPath, gFieldIds.mBatteryPresent);
setIntField(env, obj, gPaths.batteryCapacityPath, gFieldIds.mBatteryLevel);
setVoltageField(env, obj, gPaths.batteryVoltagePath, gFieldIds.mBatteryVoltage);
setIntField(env, obj, gPaths.batteryTemperaturePath, gFieldIds.mBatteryTemperature);
const int SIZE = 128;
char buf[SIZE];
if (readFromFile(gPaths.batteryStatusPath, buf, SIZE) > 0)
env->SetIntField(obj, gFieldIds.mBatteryStatus, getBatteryStatus(buf));
else
env->SetIntField(obj, gFieldIds.mBatteryStatus,
gConstants.statusUnknown);
if (readFromFile(gPaths.batteryHealthPath, buf, SIZE) > 0)
env->SetIntField(obj, gFieldIds.mBatteryHealth, getBatteryHealth(buf));
if (readFromFile(gPaths.batteryTechnologyPath, buf, SIZE) > 0)
env->SetObjectField(obj, gFieldIds.mBatteryTechnology, env->NewStringUTF(buf));
}
static JNINativeMethod sMethods[] = {
/* name, signature, funcPtr */
{"native_update", "()V", (void*)android_server_BatteryService_update},
};
int register_android_server_BatteryService(JNIEnv* env)
{
char path[PATH_MAX];
struct dirent* entry;
DIR* dir = opendir(POWER_SUPPLY_PATH);
if (dir == NULL) {
ALOGE("Could not open %s\n", POWER_SUPPLY_PATH);
} else {
while ((entry = readdir(dir))) {
const char* name = entry->d_name;
// ignore "." and ".."
if (name[0] == '.' && (name[1] == 0 || (name[1] == '.' && name[2] == 0))) {
continue;
}
char buf[20];
// Look for "type" file in each subdirectory
snprintf(path, sizeof(path), "%s/%s/type", POWER_SUPPLY_PATH, name);
int length = readFromFile(path, buf, sizeof(buf));
if (length > 0) {
if (buf[length - 1] == '\n')
buf[length - 1] = 0;
if (strcmp(buf, "Mains") == 0) {
snprintf(path, sizeof(path), "%s/%s/online", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.acOnlinePath = strdup(path);
}
else if (strcmp(buf, "USB") == 0) {
snprintf(path, sizeof(path), "%s/%s/online", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.usbOnlinePath = strdup(path);
}
else if (strcmp(buf, "Wireless") == 0) {
snprintf(path, sizeof(path), "%s/%s/online", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.wirelessOnlinePath = strdup(path);
}
else if (strcmp(buf, "Battery") == 0) {
snprintf(path, sizeof(path), "%s/%s/status", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryStatusPath = strdup(path);
snprintf(path, sizeof(path), "%s/%s/health", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryHealthPath = strdup(path);
snprintf(path, sizeof(path), "%s/%s/present", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryPresentPath = strdup(path);
snprintf(path, sizeof(path), "%s/%s/capacity", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryCapacityPath = strdup(path);
snprintf(path, sizeof(path), "%s/%s/voltage_now", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0) {
gPaths.batteryVoltagePath = strdup(path);
// voltage_now is in microvolts, not millivolts
gVoltageDivisor = 1000;
} else {
snprintf(path, sizeof(path), "%s/%s/batt_vol", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryVoltagePath = strdup(path);
}
snprintf(path, sizeof(path), "%s/%s/temp", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0) {
gPaths.batteryTemperaturePath = strdup(path);
} else {
snprintf(path, sizeof(path), "%s/%s/batt_temp", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryTemperaturePath = strdup(path);
}
snprintf(path, sizeof(path), "%s/%s/technology", POWER_SUPPLY_PATH, name);
if (access(path, R_OK) == 0)
gPaths.batteryTechnologyPath = strdup(path);
}
}
}
closedir(dir);
}
if (!gPaths.acOnlinePath)
ALOGE("acOnlinePath not found");
if (!gPaths.usbOnlinePath)
ALOGE("usbOnlinePath not found");
if (!gPaths.wirelessOnlinePath)
ALOGE("wirelessOnlinePath not found");
if (!gPaths.batteryStatusPath)
ALOGE("batteryStatusPath not found");
if (!gPaths.batteryHealthPath)
ALOGE("batteryHealthPath not found");
if (!gPaths.batteryPresentPath)
ALOGE("batteryPresentPath not found");
if (!gPaths.batteryCapacityPath)
ALOGE("batteryCapacityPath not found");
if (!gPaths.batteryVoltagePath)
ALOGE("batteryVoltagePath not found");
if (!gPaths.batteryTemperaturePath)
ALOGE("batteryTemperaturePath not found");
if (!gPaths.batteryTechnologyPath)
ALOGE("batteryTechnologyPath not found");
jclass clazz = env->FindClass("com/android/server/BatteryService");
if (clazz == NULL) {
ALOGE("Can't find com/android/server/BatteryService");
return -1;
}
gFieldIds.mAcOnline = env->GetFieldID(clazz, "mAcOnline", "Z");
gFieldIds.mUsbOnline = env->GetFieldID(clazz, "mUsbOnline", "Z");
gFieldIds.mWirelessOnline = env->GetFieldID(clazz, "mWirelessOnline", "Z");
gFieldIds.mBatteryStatus = env->GetFieldID(clazz, "mBatteryStatus", "I");
gFieldIds.mBatteryHealth = env->GetFieldID(clazz, "mBatteryHealth", "I");
gFieldIds.mBatteryPresent = env->GetFieldID(clazz, "mBatteryPresent", "Z");
gFieldIds.mBatteryLevel = env->GetFieldID(clazz, "mBatteryLevel", "I");
gFieldIds.mBatteryTechnology = env->GetFieldID(clazz, "mBatteryTechnology", "Ljava/lang/String;");
gFieldIds.mBatteryVoltage = env->GetFieldID(clazz, "mBatteryVoltage", "I");
gFieldIds.mBatteryTemperature = env->GetFieldID(clazz, "mBatteryTemperature", "I");
LOG_FATAL_IF(gFieldIds.mAcOnline == NULL, "Unable to find BatteryService.AC_ONLINE_PATH");
LOG_FATAL_IF(gFieldIds.mUsbOnline == NULL, "Unable to find BatteryService.USB_ONLINE_PATH");
LOG_FATAL_IF(gFieldIds.mWirelessOnline == NULL, "Unable to find BatteryService.WIRELESS_ONLINE_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryStatus == NULL, "Unable to find BatteryService.BATTERY_STATUS_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryHealth == NULL, "Unable to find BatteryService.BATTERY_HEALTH_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryPresent == NULL, "Unable to find BatteryService.BATTERY_PRESENT_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryLevel == NULL, "Unable to find BatteryService.BATTERY_CAPACITY_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryVoltage == NULL, "Unable to find BatteryService.BATTERY_VOLTAGE_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryTemperature == NULL, "Unable to find BatteryService.BATTERY_TEMPERATURE_PATH");
LOG_FATAL_IF(gFieldIds.mBatteryTechnology == NULL, "Unable to find BatteryService.BATTERY_TECHNOLOGY_PATH");
clazz = env->FindClass("android/os/BatteryManager");
if (clazz == NULL) {
ALOGE("Can't find android/os/BatteryManager");
return -1;
}
gConstants.statusUnknown = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_STATUS_UNKNOWN", "I"));
gConstants.statusCharging = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_STATUS_CHARGING", "I"));
gConstants.statusDischarging = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_STATUS_DISCHARGING", "I"));
gConstants.statusNotCharging = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_STATUS_NOT_CHARGING", "I"));
gConstants.statusFull = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_STATUS_FULL", "I"));
gConstants.healthUnknown = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_UNKNOWN", "I"));
gConstants.healthGood = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_GOOD", "I"));
gConstants.healthOverheat = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_OVERHEAT", "I"));
gConstants.healthDead = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_DEAD", "I"));
gConstants.healthOverVoltage = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_OVER_VOLTAGE", "I"));
gConstants.healthUnspecifiedFailure = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_UNSPECIFIED_FAILURE", "I"));
gConstants.healthCold = env->GetStaticIntField(clazz,
env->GetStaticFieldID(clazz, "BATTERY_HEALTH_COLD", "I"));
return jniRegisterNativeMethods(env, "com/android/server/BatteryService", sMethods, NELEM(sMethods));
}
} /* namespace android */
| rex-xxx/mt6572_x201 | frameworks/base/services/jni/com_android_server_BatteryService.cpp | C++ | gpl-2.0 | 15,556 |
# -*- coding: utf-8 -*-
#
# M4Baker
# Copyright (C) 2010 Kilian Lackhove
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
Module implementing MainWindow.
"""
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from Ui_mainWindow import Ui_MainWindow
from baseclasses import *
from splitDialog import splitDialog
from aboutDialog import aboutDialog
TITLE, CHAPTER, TRACK, DURATION, STARTTIME, FILENAME, ENDTIME = range(7)
def makeClickable(widget):
class clickFilter(QObject):
clicked = pyqtSignal()
def eventFilter(self, obj, event):
if obj == widget:
if event.type() == QEvent.MouseButtonRelease:
self.clicked.emit()
return True
return False
filter = clickFilter(widget)
widget.installEventFilter(filter)
return filter.clicked
class MainWindow(QMainWindow, Ui_MainWindow):
"""
Class documentation goes here.
"""
def __init__(self, parent = None):
"""
Constructor
"""
class delkeyFilter(QObject):
delkeyPressed = pyqtSignal()
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Delete:
self.delkeyPressed.emit()
return True
return False
class returnkeyFilter(QObject):
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Return:
current = obj.currentIndex()
current = obj.indexBelow(current)
obj.setCurrentIndex(current)
return False
self.audiobookList = audiobookContainer()
self.currentDir = os.getcwd()
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.stackedWidget.setCurrentWidget(self.infoPage)
makeClickable(self.coverLabel).connect(self.on_coverLabel_clicked)
self.model = audiobookTreeModel()
self.dataTreeView.setModel(self.model)
self.progessDelegate = progressBarDelegate()
self.dataTreeView.setItemDelegateForColumn(1, self.progessDelegate)
self.connect(self.dataTreeView.selectionModel(),
SIGNAL('currentChanged(QModelIndex, QModelIndex)'),
self.on_dataTreeView_currentItemChanged)
self.connect(self.model, SIGNAL('dataChanged(QModelIndex,QModelIndex)'), self.dataChanged)
self.connect(self.model, SIGNAL('expand(QModelIndex)'), self.dataTreeView.expand)
#trying the new style of connecting signals
self.model.processingDone.connect(self.on_processingDone)
self.delfilter = delkeyFilter()
self.dataTreeView.installEventFilter(self.delfilter)
self.connect(self.delfilter, SIGNAL('delkeyPressed()'),
self.on_actionRemove_triggered)
self.returnFilter = returnkeyFilter()
self.dataTreeView.installEventFilter(self.returnFilter)
#allow only numbers in yearEdit
self.yearEdit.setValidator(QRegExpValidator(QRegExp(r'\d*'), self))
#set icons
self.actionMoveDown.setIcon(QIcon.fromTheme('go-down'))
self.actionMoveUp_2.setIcon(QIcon.fromTheme('go-up'))
#TODO: clean the name of this action
self.actionRemove.setIcon(QIcon.fromTheme('edit-delete'))
self.actionAddAudiobook.setIcon(QIcon.fromTheme('address-book-new'))
self.actionAddChapter.setIcon(QIcon.fromTheme('document-new'))
self.action_About.setIcon(QIcon.fromTheme('help-about'))
self.action_help.setIcon(QIcon.fromTheme('help-browser'))
self.actionExit.setIcon(QIcon.fromTheme('application-exit'))
self.actionProcess.setIcon(QIcon.fromTheme('system-run'))
self.chapterFileButton.setIcon(QIcon.fromTheme('document-open'))
self.outfileButton.setIcon(QIcon.fromTheme('document-open'))
self.updateTree()
def okToQuit(self):
reply = QMessageBox.question(self,"M4Baker - really quit?", \
"Really quit?",QMessageBox.Yes|QMessageBox.Cancel)
if reply == QMessageBox.Cancel:
return False
elif reply == QMessageBox.Yes:
return True
def closeEvent(self, event):
if not self.okToQuit():
event.ignore()
@pyqtSignature("")
def on_actionAddAudiobook_triggered(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
formats = ["*%s" % format for format in supportedInputFiles]
fnames = QFileDialog.getOpenFileNames(
self,
"Choose audio files to create audiobook from",
self.currentDir,
'audio files (%s)' % " ".join(formats))
if fnames:
#fnames = [unicode(element) for element in fnames]
self.currentDir = fnames[-1].section(os.sep,0,-2)
newbook = audiobook([chapter(element) for element in fnames])
self.model.addAudiobooks(newbook, current)
self.updateTree()
@pyqtSignature("")
def on_actionMoveDown_triggered(self):
"""
Slot documentation goes here.
"""
indexes = self.dataTreeView.selectionModel().selectedIndexes()
#clean indexes list from double entries
cleanIndexes = []
for index in indexes:
if index.column() == 0:
cleanIndexes.append(index)
indexes = cleanIndexes
self.model.move(indexes, 'down')
@pyqtSignature("")
def on_actionRemove_triggered(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
indexes = self.dataTreeView.selectionModel().selectedIndexes()
#clean indexes list from double entries
cleanIndexes = []
for index in indexes:
if index.column() == 0:
cleanIndexes.append(index)
indexes = cleanIndexes
self.model.remove(indexes)
self.updateTree()
@pyqtSignature("")
def on_actionAddChapter_triggered(self):
"""
Slot documentation goes here.
"""
formats = ["*%s" % format for format in supportedInputFiles]
fnames = QFileDialog.getOpenFileNames(
self,
"Choose audio files to append to audiobook",
self.currentDir,
'audio files (%s)' % " ".join(formats))
if fnames:
self.currentDir = fnames[-1].section(os.sep,0,-2)
#fnames = [unicode(element) for element in fnames]
chaplist = [chapter(element) for element in fnames]
current = self.dataTreeView.currentIndex()
self.model.addChapters(chaplist, current)
self.updateTree()
#TODO: maybe it is smarter to add the chapter after current item?
@pyqtSignature("")
def on_actionSortByFilename_triggered(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
self.model.sort(current, 'filename')
self.updateTree()
@pyqtSignature("")
def on_actionSortByTracknumber_triggered(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
self.model.sort(current, 'trackNumber')
self.updateTree()
@pyqtSignature("")
def on_actionProcess_triggered(self):
"""
Slot documentation goes here.
"""
uiElements = (self.actionAddChapter, self.actionMoveDown,
self.actionMoveUp_2, self.actionProcess, self.actionRemove, self.actionSortByFilename,
self.actionSortByTracknumber, self.actionSplit, self.actionAddAudiobook)
for element in uiElements:
element.setEnabled(False)
#switch to about docker to prevent data from being changed
self.stackedWidget.setCurrentWidget(self.infoPage)
#disable treeview
self.dataTreeView.setEnabled(False)
self.model.process()
@pyqtSignature("")
def on_actionMoveUp_2_triggered(self):
"""
Slot documentation goes here.
"""
indexes = self.dataTreeView.selectionModel().selectedIndexes()
#clean indexes list from double entries
cleanIndexes = []
for index in indexes:
if index.column() == 0:
cleanIndexes.append(index)
indexes = cleanIndexes
self.model.move(indexes, 'up')
def populateChapterProperties(self):
#current must be a chapter, otherwise this method wont be called
current = self.dataTreeView.currentIndex()
title = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.DisplayRole).toString()
startTime = self.model.data(self.model.index(current.row(), STARTTIME, current.parent()),
Qt.DisplayRole).toString()
duration = self.model.data(self.model.index(current.row(), DURATION, current.parent()),
Qt.DisplayRole).toString()
filename = self.model.data(self.model.index(current.row(), FILENAME, current.parent()),
Qt.DisplayRole).toString()
endTime= self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['endTime']
endTime = u'%.2d:%.2d:%#06.3f' % secConverter(endTime)
self.chapterTitleEdit.setText(title)
self.startTimeEdit.setText(startTime)
self.durationEdit.setText(duration)
self.chapterFileEdit.setText(filename)
self.endTimeEdit.setText(endTime)
def populateAudiobookProperties(self):
current = self.dataTreeView.currentIndex()
title = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['title']
booknum = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['booknum']
author = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['author']
encodeString = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['encodeString']
outfileName = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['outfileName']
year = self.model.data(self.model.index(current.row(), TITLE, current.parent()),
Qt.UserRole)['year']
self.authorEdit.setText(author)
self.titleEdit.setText(title)
self.yearEdit.setText(year)
self.faacEdit.setText(encodeString)
self.outfileEdit.setText(outfileName)
pixmap = self.model.data(self.model.index(current.row(), 0, current.parent()), Qt.UserRole).get('cover')
if pixmap:
pixmap = self.model.data(self.model.index(current.row(), 0, current.parent()), Qt.UserRole)['cover']
width = self.coverLabel.size().width()
pixmap = pixmap.scaledToWidth(width)
self.coverLabel.setPixmap(pixmap)
else:
self.coverLabel.setText('(click to change)')
@pyqtSignature("QModelIndex*, QModelIndex*")
def on_dataTreeView_currentItemChanged(self, current, previous):
"""
Slot documentation goes here.
"""
uiElements = (self.actionAddChapter, self.actionMoveDown,
self.actionMoveUp_2, self.actionProcess, self.actionRemove, self.actionSortByFilename,
self.actionSortByTracknumber, self.actionSplit)
if not current.isValid():
#current is rootItem
for element in uiElements:
element.setDisabled(True)
return
else:
for element in uiElements:
element.setEnabled(True)
if not current.parent().isValid():
#current is audiobook
self.stackedWidget.setCurrentWidget(self.audiobookPropertiesPage)
self.populateAudiobookProperties()
if current.row() == 0:
#current is first audiobook
self.actionMoveUp_2.setEnabled(False)
if current.row() == self.model.rowCount(current.parent()) -1:
#current is last audiobook
self.actionMoveDown.setEnabled(False)
else:
#current is chapter
self.stackedWidget.setCurrentWidget(self.chapterPropertiesPage)
self.populateChapterProperties()
if current.row() == 0:
#current is the first chapter of its book
if current.parent().row() == 0:
#current is the first chapter of the first book
self.actionMoveUp_2.setEnabled(False)
if current.row() == self.model.rowCount(current.parent()) -1:
#current is the last chapter of its book
if current.parent().row() == self.model.rowCount(current.parent().parent()) -1:
#current is the last chapter of the last book
self.actionMoveDown.setEnabled(False)
@pyqtSignature("")
def on_chapterFileButton_clicked(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
formats = ["*%s" % format for format in supportedInputFiles]
fname = QFileDialog.getOpenFileName(
self,
"change chapter source file",
self.currentDir,
'audio files (%s)' % " ".join(formats))
if not fname.isEmpty():
self.currentDir = fname.section(os.sep,0,-2)
self.model.setData(self.model.index(current.row(), FILENAME, current.parent()), QVariant(fname))
self.populateChapterProperties()
@pyqtSignature("")
def on_outfileButton_clicked(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
fname = QFileDialog.getSaveFileName(
self,
'choose audiobook output file',
self.currentDir,
"Audiobook files (*.m4b)")
if not fname.isEmpty():
self.currentDir = fname.section(os.sep,0,-2)
if not fname.endsWith('.m4b'):
fname += ".m4b"
self.model.setData(self.model.index(current.row(), FILENAME, current.parent()), QVariant(fname))
self.populateAudiobookProperties()
@pyqtSignature("")
def on_action_About_triggered(self):
dialog = aboutDialog()
if dialog.exec_():
pass
@pyqtSignature("")
def on_actionSplit_triggered(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
if not current.parent().isValid():
#audiobook
pass
else:
#chapter
current = current.parent()
minSplitDuration = self.model.data(current, Qt.UserRole)['minSplitDuration']
hours, minutes, seconds = secConverter(minSplitDuration)
minSplitDuration = QTime(hours, minutes, seconds+1)
dialog = splitDialog(minSplitDuration)
if dialog.exec_():
maxSplitDuration = dialog.getMaxSplitDuration()
self.model.split(current, maxSplitDuration)
self.updateTree()
@pyqtSignature("")
def on_coverLabel_clicked(self):
current = self.dataTreeView.currentIndex()
fname = QFileDialog.getOpenFileName(
self,
"Choose a cover file",
self.currentDir,
"image files (*.png *.jpg *.jpeg *.bmp *.gif *.pbm *.pgm *ppm *xpm *xpm)",
"cover.png"
)
if not fname.isEmpty():
self.currentDir = fname.section(os.sep,0,-2)
self.model.setData(self.model.index(current.row(), 0, current.parent()),
{'cover':QPixmap(fname)}, Qt.UserRole)
self.populateAudiobookProperties()
def updateTree(self):
for i in range(6):
self.dataTreeView.resizeColumnToContents(i)
def dataChanged(self, topLeft, bottomRight):
current = self.dataTreeView.currentIndex()
if not current.parent().isValid():
#audiobook
self.populateAudiobookProperties()
else:
#chapter
self.populateChapterProperties()
def on_processingDone(self):
self.actionProcess.setEnabled(True)
self.actionAddAudiobook.setEnabled(True)
self.dataTreeView.setEnabled(True)
self.dataTreeView.reset()
@pyqtSignature("")
def on_chapterTitleEdit_editingFinished(self):
"""
Slot documentation goes here.
"""
current = self.dataTreeView.currentIndex()
text = self.chapterTitleEdit.text()
self.model.setData(self.model.index(current.row(), TITLE, current.parent()), QVariant(text))
@pyqtSignature("")
def on_faacEdit_editingFinished(self):
"""
Slot documentation goes here.
"""
text = self.faacEdit.text()
current = self.dataTreeView.currentIndex()
value = {'encodeString':QVariant(text)}
self.model.setData(self.model.index(current.row(), 0, QModelIndex()), value, Qt.UserRole)
@pyqtSignature("")
def on_titleEdit_editingFinished(self):
"""
Slot documentation goes here.
"""
text = self.titleEdit.text()
current = self.dataTreeView.currentIndex()
self.model.setData(self.model.index(current.row(), TITLE, QModelIndex()), QVariant(text))
@pyqtSignature("")
def on_yearEdit_editingFinished(self):
"""
Slot documentation goes here.
"""
text = self.titleEdit.text()
current = self.dataTreeView.currentIndex()
self.model.setData(self.model.index(current.row(), TITLE, QModelIndex()), QVariant(text))
@pyqtSignature("")
def on_authorEdit_editingFinished(self):
"""
Slot documentation goes here.
"""
text = self.authorEdit.text()
current = self.dataTreeView.currentIndex()
value = {'author':QVariant(text)}
self.model.setData(self.model.index(current.row(), 0, QModelIndex()), value, Qt.UserRole)
@pyqtSignature("")
def on_action_help_triggered(self):
"""
Slot documentation goes here.
"""
self.stackedWidget.setCurrentWidget(self.infoPage)
| crabmanX/m4baker | src/mainWindow.py | Python | gpl-2.0 | 21,163 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudLifeSciences_Metadata extends Google_Collection
{
protected $collection_key = 'events';
public $createTime;
public $endTime;
protected $eventsType = 'Google_Service_CloudLifeSciences_Event';
protected $eventsDataType = 'array';
public $labels;
protected $pipelineType = 'Google_Service_CloudLifeSciences_Pipeline';
protected $pipelineDataType = '';
public $pubSubTopic;
public $startTime;
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
}
public function getCreateTime()
{
return $this->createTime;
}
public function setEndTime($endTime)
{
$this->endTime = $endTime;
}
public function getEndTime()
{
return $this->endTime;
}
/**
* @param Google_Service_CloudLifeSciences_Event[]
*/
public function setEvents($events)
{
$this->events = $events;
}
/**
* @return Google_Service_CloudLifeSciences_Event[]
*/
public function getEvents()
{
return $this->events;
}
public function setLabels($labels)
{
$this->labels = $labels;
}
public function getLabels()
{
return $this->labels;
}
/**
* @param Google_Service_CloudLifeSciences_Pipeline
*/
public function setPipeline(Google_Service_CloudLifeSciences_Pipeline $pipeline)
{
$this->pipeline = $pipeline;
}
/**
* @return Google_Service_CloudLifeSciences_Pipeline
*/
public function getPipeline()
{
return $this->pipeline;
}
public function setPubSubTopic($pubSubTopic)
{
$this->pubSubTopic = $pubSubTopic;
}
public function getPubSubTopic()
{
return $this->pubSubTopic;
}
public function setStartTime($startTime)
{
$this->startTime = $startTime;
}
public function getStartTime()
{
return $this->startTime;
}
}
| palasthotel/grid-wordpress-box-social | vendor/google/apiclient-services/src/Google/Service/CloudLifeSciences/Metadata.php | PHP | gpl-2.0 | 2,398 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "../include/message.h"
int main(int argc, char *argv[]) {
char *buffer = (char *)malloc(sizeof(char) * 8);
char *buffert = (char *)malloc(sizeof(char) * 8);
size_t data_size = sizeof(char) * 8;
int op = 1; int who = 2;
strncpy(buffer, "MENSAGEM", data_size);
// strncpy(buffert, "AAAAAAAA", data_size);
//
printf("%d SIZE PREPROC %d SIZE POSTPROC\n", strlen(USER_NICKNAME),
strlen("\\nick"));
MESSAGE *msg;
msg = MESSAGE_new(op, who, data_size, buffer);
printf("NEW: %d %d %u\n", msg->op, msg->who, msg->data_size);
puts(msg->data);
unsigned char uc;
char c;
char_serialize(&uc, 'c');
char_deserialize(&uc, &c);
printf("%u\n", c);
printf("%u\n", uc);
unsigned char *iuc = (unsigned char *)malloc(sizeof(unsigned char) *
sizeof(int));
int_serialize(iuc, 182);
int *n = (int *) malloc(sizeof(int));;
int_deserialize(iuc, n);
printf("N: %d\n", *n);
/*
unsigned char *ser_msg = MESSAGE_serialize(msg);
puts(ser_msg);
MESSAGE *rebuilt_msg = MESSAGE_deserialize(ser_msg);
printf("REBUILT: %d %d %u\n", rebuilt_msg->op, rebuilt_msg->who,
rebuilt_msg->data_size);
puts(rebuilt_msg->data);
*/
return 0;
}
| prlanzarin/chat-service | src/msg_tst.c | C | gpl-2.0 | 1,232 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Copyright (C) 2006 - 2012 Red Hat, Inc.
* Copyright (C) 2006 - 2008 Novell, Inc.
*/
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <glib.h>
#include "NetworkManagerUtils.h"
#include "nm-supplicant-interface.h"
#include "nm-supplicant-manager.h"
#include "nm-logging.h"
#include "nm-supplicant-config.h"
#include "nm-dbus-manager.h"
#include "nm-call-store.h"
#include "nm-dbus-glib-types.h"
#include "nm-glib-compat.h"
#define WPAS_DBUS_IFACE_INTERFACE WPAS_DBUS_INTERFACE ".Interface"
#define WPAS_DBUS_IFACE_BSS WPAS_DBUS_INTERFACE ".BSS"
#define WPAS_DBUS_IFACE_NETWORK WPAS_DBUS_INTERFACE ".Network"
#define WPAS_ERROR_INVALID_IFACE WPAS_DBUS_INTERFACE ".InvalidInterface"
#define WPAS_ERROR_EXISTS_ERROR WPAS_DBUS_INTERFACE ".InterfaceExists"
G_DEFINE_TYPE (NMSupplicantInterface, nm_supplicant_interface, G_TYPE_OBJECT)
static void wpas_iface_properties_changed (DBusGProxy *proxy,
GHashTable *props,
gpointer user_data);
static void wpas_iface_scan_done (DBusGProxy *proxy,
gboolean success,
gpointer user_data);
static void wpas_iface_get_props (NMSupplicantInterface *self);
#define NM_SUPPLICANT_INTERFACE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
NM_TYPE_SUPPLICANT_INTERFACE, \
NMSupplicantInterfacePrivate))
/* Signals */
enum {
STATE, /* change in the interface's state */
REMOVED, /* interface was removed by the supplicant */
NEW_BSS, /* interface saw a new access point from a scan */
BSS_UPDATED, /* a BSS property changed */
BSS_REMOVED, /* supplicant removed BSS from its scan list */
SCAN_DONE, /* wifi scan is complete */
CONNECTION_ERROR, /* an error occurred during a connection request */
CREDENTIALS_REQUEST, /* 802.1x identity or password requested */
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
/* Properties */
enum {
PROP_0 = 0,
PROP_SCANNING,
LAST_PROP
};
typedef struct {
NMSupplicantManager * smgr;
gulong smgr_avail_id;
NMDBusManager * dbus_mgr;
char * dev;
gboolean is_wireless;
gboolean has_credreq; /* Whether querying 802.1x credentials is supported */
ApSupport ap_support; /* Lightweight AP mode support */
gboolean fast_supported;
guint32 max_scan_ssids;
guint32 ready_count;
char * object_path;
guint32 state;
int disconnect_reason;
NMCallStore * assoc_pcalls;
NMCallStore * other_pcalls;
gboolean scanning;
DBusGProxy * wpas_proxy;
DBusGProxy * introspect_proxy;
DBusGProxy * iface_proxy;
DBusGProxy * props_proxy;
char * net_path;
guint32 blobs_left;
GHashTable * bss_proxies;
gint32 last_scan; /* timestamp as returned by nm_utils_get_monotonic_timestamp_s() */
NMSupplicantConfig * cfg;
gboolean disposed;
} NMSupplicantInterfacePrivate;
static void
emit_error_helper (NMSupplicantInterface *self,
GError *err)
{
const char *name = NULL;
if (err->domain == DBUS_GERROR && err->code == DBUS_GERROR_REMOTE_EXCEPTION)
name = dbus_g_error_get_name (err);
g_signal_emit (self, signals[CONNECTION_ERROR], 0, name, err->message);
}
static void
signal_new_bss (NMSupplicantInterface *self,
const char *object_path,
GHashTable *props)
{
g_signal_emit (self, signals[NEW_BSS], 0, object_path, props);
}
static void
bssid_properties_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *error = NULL;
GHashTable *props = NULL;
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if (dbus_g_proxy_end_call (proxy, call_id, &error,
DBUS_TYPE_G_MAP_OF_VARIANT, &props,
G_TYPE_INVALID)) {
signal_new_bss (self, dbus_g_proxy_get_path (proxy), props);
g_hash_table_destroy (props);
} else {
if (!strstr (error->message, "The BSSID requested was invalid")) {
nm_log_warn (LOGD_SUPPLICANT, "Couldn't retrieve BSSID properties: %s.",
error->message);
}
g_error_free (error);
}
}
static void
bss_properties_changed (DBusGProxy *proxy,
const char *interface,
GHashTable *props,
const char **unused,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
if (priv->scanning)
priv->last_scan = nm_utils_get_monotonic_timestamp_s ();
if (g_strcmp0 (interface, WPAS_DBUS_IFACE_BSS) == 0)
g_signal_emit (self, signals[BSS_UPDATED], 0, dbus_g_proxy_get_path (proxy), props);
}
static void
handle_new_bss (NMSupplicantInterface *self,
const char *object_path,
GHashTable *props)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxy *bss_proxy;
DBusGProxyCall *call;
g_return_if_fail (object_path != NULL);
if (g_hash_table_lookup (priv->bss_proxies, object_path))
return;
bss_proxy = dbus_g_proxy_new_for_name (nm_dbus_manager_get_connection (priv->dbus_mgr),
WPAS_DBUS_SERVICE,
object_path,
DBUS_INTERFACE_PROPERTIES);
g_hash_table_insert (priv->bss_proxies,
(gpointer) dbus_g_proxy_get_path (bss_proxy),
bss_proxy);
/* Standard D-Bus PropertiesChanged signal */
dbus_g_object_register_marshaller (g_cclosure_marshal_generic,
G_TYPE_NONE,
G_TYPE_STRING, DBUS_TYPE_G_MAP_OF_VARIANT, G_TYPE_STRV,
G_TYPE_INVALID);
dbus_g_proxy_add_signal (bss_proxy, "PropertiesChanged",
G_TYPE_STRING, DBUS_TYPE_G_MAP_OF_VARIANT, G_TYPE_STRV,
G_TYPE_INVALID);
dbus_g_proxy_connect_signal (bss_proxy, "PropertiesChanged",
G_CALLBACK (bss_properties_changed),
self, NULL);
if (props) {
signal_new_bss (self, object_path, props);
} else {
call = dbus_g_proxy_begin_call (bss_proxy, "GetAll",
bssid_properties_cb,
self,
NULL,
G_TYPE_STRING, WPAS_DBUS_IFACE_BSS,
G_TYPE_INVALID);
nm_call_store_add (priv->other_pcalls, bss_proxy, call);
}
}
static void
wpas_iface_bss_added (DBusGProxy *proxy,
const char *object_path,
GHashTable *props,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
if (priv->scanning)
priv->last_scan = nm_utils_get_monotonic_timestamp_s ();
handle_new_bss (self, object_path, props);
}
static void
wpas_iface_bss_removed (DBusGProxy *proxy,
const char *object_path,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
g_signal_emit (self, signals[BSS_REMOVED], 0, object_path);
g_hash_table_remove (priv->bss_proxies, object_path);
}
static int
wpas_state_string_to_enum (const char *str_state)
{
if (!strcmp (str_state, "interface_disabled"))
return NM_SUPPLICANT_INTERFACE_STATE_DISABLED;
else if (!strcmp (str_state, "disconnected"))
return NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED;
else if (!strcmp (str_state, "inactive"))
return NM_SUPPLICANT_INTERFACE_STATE_INACTIVE;
else if (!strcmp (str_state, "scanning"))
return NM_SUPPLICANT_INTERFACE_STATE_SCANNING;
else if (!strcmp (str_state, "authenticating"))
return NM_SUPPLICANT_INTERFACE_STATE_AUTHENTICATING;
else if (!strcmp (str_state, "associating"))
return NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATING;
else if (!strcmp (str_state, "associated"))
return NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATED;
else if (!strcmp (str_state, "4way_handshake"))
return NM_SUPPLICANT_INTERFACE_STATE_4WAY_HANDSHAKE;
else if (!strcmp (str_state, "group_handshake"))
return NM_SUPPLICANT_INTERFACE_STATE_GROUP_HANDSHAKE;
else if (!strcmp (str_state, "completed"))
return NM_SUPPLICANT_INTERFACE_STATE_COMPLETED;
nm_log_warn (LOGD_SUPPLICANT, "Unknown supplicant state '%s'", str_state);
return -1;
}
static void
set_state (NMSupplicantInterface *self, guint32 new_state)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
guint32 old_state = priv->state;
g_return_if_fail (new_state < NM_SUPPLICANT_INTERFACE_STATE_LAST);
if (new_state == priv->state)
return;
/* DOWN is a terminal state */
g_return_if_fail (priv->state != NM_SUPPLICANT_INTERFACE_STATE_DOWN);
/* Cannot regress to READY, STARTING, or INIT from higher states */
if (priv->state >= NM_SUPPLICANT_INTERFACE_STATE_READY)
g_return_if_fail (new_state > NM_SUPPLICANT_INTERFACE_STATE_READY);
if (new_state == NM_SUPPLICANT_INTERFACE_STATE_READY) {
/* Get properties again to update to the actual wpa_supplicant
* interface state.
*/
wpas_iface_get_props (self);
} else if (new_state == NM_SUPPLICANT_INTERFACE_STATE_DOWN) {
/* Cancel all pending calls when going down */
nm_call_store_clear (priv->other_pcalls);
nm_call_store_clear (priv->assoc_pcalls);
/* Disconnect supplicant manager state listeners since we're done */
if (priv->smgr_avail_id) {
g_signal_handler_disconnect (priv->smgr, priv->smgr_avail_id);
priv->smgr_avail_id = 0;
}
if (priv->iface_proxy) {
dbus_g_proxy_disconnect_signal (priv->iface_proxy,
"PropertiesChanged",
G_CALLBACK (wpas_iface_properties_changed),
self);
dbus_g_proxy_disconnect_signal (priv->iface_proxy,
"ScanDone",
G_CALLBACK (wpas_iface_scan_done),
self);
dbus_g_proxy_disconnect_signal (priv->iface_proxy,
"BSSAdded",
G_CALLBACK (wpas_iface_bss_added),
self);
dbus_g_proxy_disconnect_signal (priv->iface_proxy,
"BSSRemoved",
G_CALLBACK (wpas_iface_bss_removed),
self);
}
}
priv->state = new_state;
if ( priv->state == NM_SUPPLICANT_INTERFACE_STATE_SCANNING
|| old_state == NM_SUPPLICANT_INTERFACE_STATE_SCANNING)
priv->last_scan = nm_utils_get_monotonic_timestamp_s ();
/* Disconnect reason is no longer relevant when not in the DISCONNECTED state */
if (priv->state != NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED)
priv->disconnect_reason = 0;
g_signal_emit (self, signals[STATE], 0,
priv->state,
old_state,
priv->disconnect_reason);
}
static void
set_state_from_string (NMSupplicantInterface *self, const char *new_state)
{
int state;
state = wpas_state_string_to_enum (new_state);
g_warn_if_fail (state > 0);
if (state > 0)
set_state (self, (guint32) state);
}
static void
set_scanning (NMSupplicantInterface *self, gboolean new_scanning)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
if (priv->scanning != new_scanning) {
priv->scanning = new_scanning;
/* Cache time of last scan completion */
if (priv->scanning == FALSE)
priv->last_scan = nm_utils_get_monotonic_timestamp_s ();
g_object_notify (G_OBJECT (self), "scanning");
}
}
gboolean
nm_supplicant_interface_get_scanning (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv;
g_return_val_if_fail (self != NULL, FALSE);
priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
if (priv->scanning)
return TRUE;
if (priv->state == NM_SUPPLICANT_INTERFACE_STATE_SCANNING)
return TRUE;
return FALSE;
}
gint32
nm_supplicant_interface_get_last_scan_time (NMSupplicantInterface *self)
{
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->last_scan;
}
static void
wpas_iface_scan_done (DBusGProxy *proxy,
gboolean success,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
/* Cache last scan completed time */
priv->last_scan = nm_utils_get_monotonic_timestamp_s ();
g_signal_emit (self, signals[SCAN_DONE], 0, success);
}
static void
parse_capabilities (NMSupplicantInterface *self, GHashTable *props)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GValue *value;
gboolean have_active = FALSE, have_ssid = FALSE;
g_return_if_fail (props != NULL);
value = g_hash_table_lookup (props, "Scan");
if (value && G_VALUE_HOLDS (value, G_TYPE_STRV)) {
const char **vals = g_value_get_boxed (value);
const char **iter = vals;
while (iter && *iter && (!have_active || !have_ssid)) {
if (g_strcmp0 (*iter, "active") == 0)
have_active = TRUE;
else if (g_strcmp0 (*iter, "ssid") == 0)
have_ssid = TRUE;
iter++;
}
}
value = g_hash_table_lookup (props, "MaxScanSSID");
if (value && G_VALUE_HOLDS (value, G_TYPE_INT)) {
/* We need active scan and SSID probe capabilities to care about MaxScanSSIDs */
if (have_active && have_ssid) {
/* wpa_supplicant's WPAS_MAX_SCAN_SSIDS value is 16, but for speed
* and to ensure we don't disclose too many SSIDs from the hidden
* list, we'll limit to 5.
*/
priv->max_scan_ssids = CLAMP (g_value_get_int (value), 0, 5);
nm_log_info (LOGD_SUPPLICANT, "(%s) supports %d scan SSIDs",
priv->dev, priv->max_scan_ssids);
}
}
}
static void
wpas_iface_properties_changed (DBusGProxy *proxy,
GHashTable *props,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GValue *value;
value = g_hash_table_lookup (props, "Scanning");
if (value && G_VALUE_HOLDS_BOOLEAN (value))
set_scanning (self, g_value_get_boolean (value));
value = g_hash_table_lookup (props, "State");
if (value && G_VALUE_HOLDS_STRING (value)) {
if (priv->state >= NM_SUPPLICANT_INTERFACE_STATE_READY) {
/* Only transition to actual wpa_supplicant interface states (ie,
* anything > READY) after the NMSupplicantInterface has had a
* chance to initialize, which is signalled by entering the READY
* state.
*/
set_state_from_string (self, g_value_get_string (value));
}
}
value = g_hash_table_lookup (props, "BSSs");
if (value && G_VALUE_HOLDS (value, DBUS_TYPE_G_ARRAY_OF_OBJECT_PATH)) {
GPtrArray *paths = g_value_get_boxed (value);
int i;
for (i = 0; paths && (i < paths->len); i++)
handle_new_bss (self, g_ptr_array_index (paths, i), NULL);
}
value = g_hash_table_lookup (props, "Capabilities");
if (value && G_VALUE_HOLDS (value, DBUS_TYPE_G_MAP_OF_VARIANT))
parse_capabilities (self, g_value_get_boxed (value));
/* Disconnect reason is currently only given for deauthentication events,
* not disassociation; currently they are IEEE 802.11 "reason codes",
* defined by (IEEE 802.11-2007, 7.3.1.7, Table 7-22). Any locally caused
* deauthentication will be negative, while authentications caused by the
* AP will be positive.
*/
value = g_hash_table_lookup (props, "DisconnectReason");
if (value && G_VALUE_HOLDS (value, G_TYPE_INT)) {
priv->disconnect_reason = g_value_get_int (value);
if (priv->disconnect_reason != 0) {
nm_log_warn (LOGD_SUPPLICANT, "Connection disconnected (reason %d)",
priv->disconnect_reason);
}
}
}
static void
iface_check_ready (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
if (priv->ready_count && priv->state < NM_SUPPLICANT_INTERFACE_STATE_READY) {
priv->ready_count--;
if (priv->ready_count == 0)
set_state (self, NM_SUPPLICANT_INTERFACE_STATE_READY);
}
}
static void
iface_get_props_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GHashTable *props = NULL;
GError *error = NULL;
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if (dbus_g_proxy_end_call (proxy, call_id, &error,
DBUS_TYPE_G_MAP_OF_VARIANT, &props,
G_TYPE_INVALID)) {
wpas_iface_properties_changed (NULL, props, self);
g_hash_table_destroy (props);
} else {
nm_log_warn (LOGD_SUPPLICANT, "could not get interface properties: %s.",
error && error->message ? error->message : "(unknown)");
g_clear_error (&error);
}
iface_check_ready (self);
}
static void
wpas_iface_get_props (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxyCall *call;
call = dbus_g_proxy_begin_call (priv->props_proxy, "GetAll",
iface_get_props_cb,
self,
NULL,
G_TYPE_STRING, WPAS_DBUS_IFACE_INTERFACE,
G_TYPE_INVALID);
nm_call_store_add (priv->other_pcalls, priv->props_proxy, call);
}
gboolean
nm_supplicant_interface_credentials_reply (NMSupplicantInterface *self,
const char *field,
const char *value,
GError **error)
{
NMSupplicantInterfacePrivate *priv;
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), FALSE);
g_return_val_if_fail (field != NULL, FALSE);
g_return_val_if_fail (value != NULL, FALSE);
priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
g_return_val_if_fail (priv->has_credreq == TRUE, FALSE);
/* Need a network block object path */
g_return_val_if_fail (priv->net_path, FALSE);
return dbus_g_proxy_call_with_timeout (priv->iface_proxy, "NetworkReply",
5000,
error,
DBUS_TYPE_G_OBJECT_PATH, priv->net_path,
G_TYPE_STRING, field,
G_TYPE_STRING, value,
G_TYPE_INVALID);
}
static void
wpas_iface_network_request (DBusGProxy *proxy,
const char *object_path,
const char *field,
const char *message,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
g_return_if_fail (priv->has_credreq == TRUE);
g_return_if_fail (priv->net_path != NULL);
g_return_if_fail (g_strcmp0 (object_path, priv->net_path) == 0);
g_signal_emit (self, signals[CREDENTIALS_REQUEST], 0, field, message);
}
static void
iface_check_netreply_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *error = NULL;
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if ( dbus_g_proxy_end_call (proxy, call_id, &error, G_TYPE_INVALID)
|| dbus_g_error_has_name (error, "fi.w1.wpa_supplicant1.InvalidArgs")) {
/* We know NetworkReply is supported if the NetworkReply method returned
* successfully (which is unexpected since we sent a bogus network
* object path) or if we got an "InvalidArgs" (which indicates NetworkReply
* is supported). We know it's not supported if we get an
* "UnknownMethod" error.
*/
priv->has_credreq = TRUE;
nm_log_dbg (LOGD_SUPPLICANT, "Supplicant %s network credentials requests",
priv->has_credreq ? "supports" : "does not support");
}
g_clear_error (&error);
iface_check_ready (self);
}
static void
wpas_iface_check_network_reply (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxyCall *call;
priv->ready_count++;
call = dbus_g_proxy_begin_call (priv->iface_proxy, "NetworkReply",
iface_check_netreply_cb,
self,
NULL,
DBUS_TYPE_G_OBJECT_PATH, "/foobaraasdfasdf",
G_TYPE_STRING, "foobar",
G_TYPE_STRING, "foobar",
G_TYPE_INVALID);
nm_call_store_add (priv->other_pcalls, priv->iface_proxy, call);
}
ApSupport
nm_supplicant_interface_get_ap_support (NMSupplicantInterface *self)
{
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->ap_support;
}
void
nm_supplicant_interface_set_ap_support (NMSupplicantInterface *self,
ApSupport ap_support)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
/* Use the best indicator of support between the supplicant global
* Capabilities property and the interface's introspection data.
*/
if (ap_support > priv->ap_support)
priv->ap_support = ap_support;
}
static void
iface_check_ap_mode_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
char *data;
/* The ProbeRequest method only exists if AP mode has been enabled */
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if (dbus_g_proxy_end_call (proxy, call_id, NULL,
G_TYPE_STRING,
&data,
G_TYPE_INVALID)) {
if (data && strstr (data, "ProbeRequest"))
priv->ap_support = AP_SUPPORT_YES;
g_free (data);
}
iface_check_ready (self);
}
static void
wpas_iface_check_ap_mode (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxyCall *call;
priv->ready_count++;
/* If the global supplicant capabilities property is not present, we can
* fall back to checking whether the ProbeRequest method is supported. If
* neither of these works we have no way of determining if AP mode is
* supported or not. hostap 1.0 and earlier don't support either of these.
*/
call = dbus_g_proxy_begin_call (priv->introspect_proxy, "Introspect",
iface_check_ap_mode_cb,
self,
NULL,
G_TYPE_INVALID);
nm_call_store_add (priv->other_pcalls, priv->introspect_proxy, call);
}
static void
interface_add_done (NMSupplicantInterface *self, char *path)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
nm_log_dbg (LOGD_SUPPLICANT, "(%s): interface added to supplicant", priv->dev);
priv->object_path = path;
priv->iface_proxy = dbus_g_proxy_new_for_name (nm_dbus_manager_get_connection (priv->dbus_mgr),
WPAS_DBUS_SERVICE,
path,
WPAS_DBUS_IFACE_INTERFACE);
dbus_g_object_register_marshaller (g_cclosure_marshal_VOID__BOXED,
G_TYPE_NONE,
DBUS_TYPE_G_MAP_OF_VARIANT,
G_TYPE_INVALID);
dbus_g_proxy_add_signal (priv->iface_proxy, "PropertiesChanged",
DBUS_TYPE_G_MAP_OF_VARIANT, G_TYPE_INVALID);
dbus_g_proxy_connect_signal (priv->iface_proxy, "PropertiesChanged",
G_CALLBACK (wpas_iface_properties_changed),
self, NULL);
dbus_g_proxy_add_signal (priv->iface_proxy, "ScanDone",
G_TYPE_BOOLEAN, G_TYPE_INVALID);
dbus_g_proxy_connect_signal (priv->iface_proxy, "ScanDone",
G_CALLBACK (wpas_iface_scan_done),
self,
NULL);
dbus_g_object_register_marshaller (g_cclosure_marshal_generic,
G_TYPE_NONE,
DBUS_TYPE_G_OBJECT_PATH, DBUS_TYPE_G_MAP_OF_VARIANT,
G_TYPE_INVALID);
dbus_g_proxy_add_signal (priv->iface_proxy, "BSSAdded",
DBUS_TYPE_G_OBJECT_PATH, DBUS_TYPE_G_MAP_OF_VARIANT,
G_TYPE_INVALID);
dbus_g_proxy_connect_signal (priv->iface_proxy, "BSSAdded",
G_CALLBACK (wpas_iface_bss_added),
self,
NULL);
dbus_g_object_register_marshaller (g_cclosure_marshal_VOID__BOXED,
G_TYPE_NONE,
DBUS_TYPE_G_OBJECT_PATH,
G_TYPE_INVALID);
dbus_g_proxy_add_signal (priv->iface_proxy, "BSSRemoved",
DBUS_TYPE_G_OBJECT_PATH,
G_TYPE_INVALID);
dbus_g_proxy_connect_signal (priv->iface_proxy, "BSSRemoved",
G_CALLBACK (wpas_iface_bss_removed),
self,
NULL);
dbus_g_object_register_marshaller (g_cclosure_marshal_generic,
G_TYPE_NONE,
DBUS_TYPE_G_OBJECT_PATH, G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_INVALID);
dbus_g_proxy_add_signal (priv->iface_proxy, "NetworkRequest",
DBUS_TYPE_G_OBJECT_PATH, G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_INVALID);
dbus_g_proxy_connect_signal (priv->iface_proxy, "NetworkRequest",
G_CALLBACK (wpas_iface_network_request),
self,
NULL);
priv->introspect_proxy = dbus_g_proxy_new_for_name (nm_dbus_manager_get_connection (priv->dbus_mgr),
WPAS_DBUS_SERVICE,
priv->object_path,
DBUS_INTERFACE_INTROSPECTABLE);
priv->props_proxy = dbus_g_proxy_new_for_name (nm_dbus_manager_get_connection (priv->dbus_mgr),
WPAS_DBUS_SERVICE,
path,
DBUS_INTERFACE_PROPERTIES);
/* Get initial properties and check whether NetworkReply is supported */
priv->ready_count = 1;
wpas_iface_get_props (self);
/* These two increment ready_count themselves */
wpas_iface_check_network_reply (self);
if (priv->ap_support == AP_SUPPORT_UNKNOWN)
wpas_iface_check_ap_mode (self);
}
static void
interface_get_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *error = NULL;
char *path = NULL;
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if (dbus_g_proxy_end_call (proxy, call_id, &error,
DBUS_TYPE_G_OBJECT_PATH, &path,
G_TYPE_INVALID)) {
interface_add_done (self, path);
} else {
nm_log_err (LOGD_SUPPLICANT, "(%s): error getting interface: %s",
priv->dev, error->message);
g_clear_error (&error);
set_state (self, NM_SUPPLICANT_INTERFACE_STATE_DOWN);
}
}
static void
interface_get (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxyCall *call;
call = dbus_g_proxy_begin_call (priv->wpas_proxy, "GetInterface",
interface_get_cb,
self,
NULL,
G_TYPE_STRING, priv->dev,
G_TYPE_INVALID);
nm_call_store_add (priv->other_pcalls, priv->wpas_proxy, call);
}
static void
interface_add_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *error = NULL;
char *path = NULL;
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if (dbus_g_proxy_end_call (proxy, call_id, &error,
DBUS_TYPE_G_OBJECT_PATH, &path,
G_TYPE_INVALID)) {
interface_add_done (self, path);
} else {
if (dbus_g_error_has_name (error, WPAS_ERROR_EXISTS_ERROR)) {
/* Interface already added, just get its object path */
interface_get (self);
} else if ( g_error_matches (error, DBUS_GERROR, DBUS_GERROR_SERVICE_UNKNOWN)
|| g_error_matches (error, DBUS_GERROR, DBUS_GERROR_SPAWN_EXEC_FAILED)
|| g_error_matches (error, DBUS_GERROR, DBUS_GERROR_SPAWN_FORK_FAILED)
|| g_error_matches (error, DBUS_GERROR, DBUS_GERROR_SPAWN_FAILED)
|| g_error_matches (error, DBUS_GERROR, DBUS_GERROR_TIMEOUT)
|| g_error_matches (error, DBUS_GERROR, DBUS_GERROR_NO_REPLY)
|| g_error_matches (error, DBUS_GERROR, DBUS_GERROR_TIMED_OUT)
|| dbus_g_error_has_name (error, DBUS_ERROR_SPAWN_SERVICE_NOT_FOUND)) {
/* Supplicant wasn't running and could not be launched via service
* activation. Wait for it to start by moving back to the INIT
* state.
*/
nm_log_dbg (LOGD_SUPPLICANT, "(%s): failed to activate supplicant: %s",
priv->dev, error->message);
set_state (self, NM_SUPPLICANT_INTERFACE_STATE_INIT);
} else {
nm_log_err (LOGD_SUPPLICANT, "(%s): error adding interface: %s",
priv->dev, error->message);
set_state (self, NM_SUPPLICANT_INTERFACE_STATE_DOWN);
}
g_clear_error (&error);
}
}
#if HAVE_WEXT
#define DEFAULT_WIFI_DRIVER "nl80211,wext"
#else
#define DEFAULT_WIFI_DRIVER "nl80211"
#endif
static void
interface_add (NMSupplicantInterface *self, gboolean is_wireless)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxyCall *call;
GHashTable *hash;
GValue driver = G_VALUE_INIT;
GValue ifname = G_VALUE_INIT;
/* Can only start the interface from INIT state */
g_return_if_fail (priv->state == NM_SUPPLICANT_INTERFACE_STATE_INIT);
nm_log_dbg (LOGD_SUPPLICANT, "(%s): adding interface to supplicant", priv->dev);
/* Move to starting to prevent double-calls of interface_add() */
set_state (self, NM_SUPPLICANT_INTERFACE_STATE_STARTING);
/* Try to add the interface to the supplicant. If the supplicant isn't
* running, this will start it via D-Bus activation and return the response
* when the supplicant has started.
*/
hash = g_hash_table_new (g_str_hash, g_str_equal);
g_value_init (&driver, G_TYPE_STRING);
g_value_set_string (&driver, is_wireless ? DEFAULT_WIFI_DRIVER : "wired");
g_hash_table_insert (hash, "Driver", &driver);
g_value_init (&ifname, G_TYPE_STRING);
g_value_set_string (&ifname, priv->dev);
g_hash_table_insert (hash, "Ifname", &ifname);
call = dbus_g_proxy_begin_call (priv->wpas_proxy, "CreateInterface",
interface_add_cb,
self,
NULL,
DBUS_TYPE_G_MAP_OF_VARIANT, hash,
G_TYPE_INVALID);
nm_call_store_add (priv->other_pcalls, priv->wpas_proxy, call);
g_hash_table_destroy (hash);
g_value_unset (&driver);
g_value_unset (&ifname);
}
static void
smgr_avail_cb (NMSupplicantManager *smgr,
GParamSpec *pspec,
gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (user_data);
if (nm_supplicant_manager_available (smgr)) {
/* This can happen if the supplicant couldn't be activated but
* for some reason was started after the activation failure.
*/
if (priv->state == NM_SUPPLICANT_INTERFACE_STATE_INIT)
interface_add (self, priv->is_wireless);
} else {
/* The supplicant stopped; so we must tear down the interface */
set_state (self, NM_SUPPLICANT_INTERFACE_STATE_DOWN);
}
}
static void
remove_network_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
GError *error = NULL;
if (!dbus_g_proxy_end_call (proxy, call_id, &error, G_TYPE_INVALID)) {
nm_log_dbg (LOGD_SUPPLICANT, "Couldn't remove network from supplicant interface: %s.",
error && error->message ? error->message : "(unknown)");
g_clear_error (&error);
}
}
static void
disconnect_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
GError *error = NULL;
if (!dbus_g_proxy_end_call (proxy, call_id, &error, G_TYPE_INVALID)) {
nm_log_warn (LOGD_SUPPLICANT, "Couldn't disconnect supplicant interface: %s.",
error && error->message ? error->message : "(unknown)");
g_clear_error (&error);
}
}
void
nm_supplicant_interface_disconnect (NMSupplicantInterface * self)
{
NMSupplicantInterfacePrivate *priv;
g_return_if_fail (NM_IS_SUPPLICANT_INTERFACE (self));
priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
/* Clear and cancel all pending calls related to a prior
* connection attempt.
*/
nm_call_store_clear (priv->assoc_pcalls);
/* Don't do anything if there is no connection to the supplicant yet. */
if (!priv->iface_proxy)
return;
/* Disconnect from the current AP */
if ( (priv->state >= NM_SUPPLICANT_INTERFACE_STATE_SCANNING)
&& (priv->state <= NM_SUPPLICANT_INTERFACE_STATE_COMPLETED)) {
dbus_g_proxy_begin_call (priv->iface_proxy, "Disconnect",
disconnect_cb,
NULL, NULL,
G_TYPE_INVALID);
}
/* Remove any network that was added by NetworkManager */
if (priv->net_path) {
dbus_g_proxy_begin_call (priv->iface_proxy, "RemoveNetwork",
remove_network_cb,
NULL, NULL,
DBUS_TYPE_G_OBJECT_PATH, priv->net_path,
G_TYPE_INVALID);
g_free (priv->net_path);
priv->net_path = NULL;
}
}
static void
select_network_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *err = NULL;
nm_call_store_remove (priv->assoc_pcalls, proxy, call_id);
if (!dbus_g_proxy_end_call (proxy, call_id, &err, G_TYPE_INVALID)) {
nm_log_warn (LOGD_SUPPLICANT, "Couldn't select network config: %s.", err->message);
emit_error_helper (self, err);
g_error_free (err);
}
}
static void
call_select_network (NMSupplicantInterface *self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGProxyCall *call;
/* We only select the network after all blobs (if any) have been set */
if (priv->blobs_left == 0) {
call = dbus_g_proxy_begin_call (priv->iface_proxy, "SelectNetwork",
select_network_cb,
self,
NULL,
DBUS_TYPE_G_OBJECT_PATH, priv->net_path,
G_TYPE_INVALID);
nm_call_store_add (priv->assoc_pcalls, priv->iface_proxy, call);
}
}
static void
add_blob_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *err = NULL;
guint tmp;
priv->blobs_left--;
nm_call_store_remove (priv->assoc_pcalls, proxy, call_id);
if (!dbus_g_proxy_end_call (proxy, call_id, &err, G_TYPE_UINT, &tmp, G_TYPE_INVALID)) {
nm_log_warn (LOGD_SUPPLICANT, "Couldn't set network certificates: %s.", err->message);
emit_error_helper (self, err);
g_error_free (err);
} else
call_select_network (self);
}
static void
add_network_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *err = NULL;
GHashTable *blobs;
GHashTableIter iter;
gpointer name, data;
DBusGProxyCall *call;
g_free (priv->net_path);
priv->net_path = NULL;
nm_call_store_remove (priv->assoc_pcalls, proxy, call_id);
if (!dbus_g_proxy_end_call (proxy, call_id, &err,
DBUS_TYPE_G_OBJECT_PATH, &priv->net_path,
G_TYPE_INVALID)) {
nm_log_warn (LOGD_SUPPLICANT, "Couldn't add a network to the supplicant interface: %s.",
err->message);
emit_error_helper (self, err);
g_error_free (err);
return;
}
/* Send blobs first; otherwise jump to sending the config settings */
blobs = nm_supplicant_config_get_blobs (priv->cfg);
priv->blobs_left = g_hash_table_size (blobs);
g_hash_table_iter_init (&iter, blobs);
while (g_hash_table_iter_next (&iter, &name, &data)) {
call = dbus_g_proxy_begin_call (priv->iface_proxy, "AddBlob",
add_blob_cb,
self,
NULL,
DBUS_TYPE_STRING, name,
DBUS_TYPE_G_UCHAR_ARRAY, blobs,
G_TYPE_INVALID);
nm_call_store_add (priv->assoc_pcalls, priv->iface_proxy, call);
}
call_select_network (self);
}
static void
set_ap_scan_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *err = NULL;
DBusGProxyCall *call;
GHashTable *config_hash;
nm_call_store_remove (priv->assoc_pcalls, proxy, call_id);
if (!dbus_g_proxy_end_call (proxy, call_id, &err, G_TYPE_INVALID)) {
nm_log_warn (LOGD_SUPPLICANT, "Couldn't send AP scan mode to the supplicant interface: %s.",
err->message);
emit_error_helper (self, err);
g_error_free (err);
return;
}
nm_log_info (LOGD_SUPPLICANT, "Config: set interface ap_scan to %d",
nm_supplicant_config_get_ap_scan (priv->cfg));
config_hash = nm_supplicant_config_get_hash (priv->cfg);
call = dbus_g_proxy_begin_call (priv->iface_proxy, "AddNetwork",
add_network_cb,
self,
NULL,
DBUS_TYPE_G_MAP_OF_VARIANT, config_hash,
G_TYPE_INVALID);
g_hash_table_destroy (config_hash);
nm_call_store_add (priv->assoc_pcalls, priv->iface_proxy, call);
}
gboolean
nm_supplicant_interface_set_config (NMSupplicantInterface *self,
NMSupplicantConfig *cfg)
{
NMSupplicantInterfacePrivate *priv;
DBusGProxyCall *call;
GValue value = G_VALUE_INIT;
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), FALSE);
priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
nm_supplicant_interface_disconnect (self);
/* Make sure the supplicant supports EAP-FAST before trying to send
* it an EAP-FAST configuration.
*/
if (nm_supplicant_config_fast_required (cfg) && !priv->fast_supported) {
nm_log_warn (LOGD_SUPPLICANT, "EAP-FAST is not supported by the supplicant");
return FALSE;
}
if (priv->cfg)
g_object_unref (priv->cfg);
priv->cfg = cfg;
if (cfg == NULL)
return TRUE;
g_object_ref (priv->cfg);
g_value_init (&value, G_TYPE_UINT);
g_value_set_uint (&value, nm_supplicant_config_get_ap_scan (priv->cfg));
call = dbus_g_proxy_begin_call (priv->props_proxy, "Set",
set_ap_scan_cb,
self,
NULL,
G_TYPE_STRING, WPAS_DBUS_IFACE_INTERFACE,
G_TYPE_STRING, "ApScan",
G_TYPE_VALUE, &value,
G_TYPE_INVALID);
nm_call_store_add (priv->assoc_pcalls, priv->props_proxy, call);
g_value_unset (&value);
return call != NULL;
}
static void
scan_request_cb (DBusGProxy *proxy, DBusGProxyCall *call_id, gpointer user_data)
{
NMSupplicantInterface *self = NM_SUPPLICANT_INTERFACE (user_data);
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
GError *err = NULL;
nm_call_store_remove (priv->other_pcalls, proxy, call_id);
if (!dbus_g_proxy_end_call (proxy, call_id, &err, G_TYPE_INVALID))
nm_log_warn (LOGD_SUPPLICANT, "Could not get scan request result: %s", err->message);
g_signal_emit (self, signals[SCAN_DONE], 0, err ? FALSE : TRUE);
g_clear_error (&err);
}
static void
destroy_gvalue (gpointer data)
{
GValue *value = (GValue *) data;
g_value_unset (value);
g_slice_free (GValue, value);
}
static GValue *
string_to_gvalue (const char *str)
{
GValue *val = g_slice_new0 (GValue);
g_value_init (val, G_TYPE_STRING);
g_value_set_string (val, str);
return val;
}
static GValue *
byte_array_array_to_gvalue (const GPtrArray *array)
{
GValue *val = g_slice_new0 (GValue);
g_value_init (val, DBUS_TYPE_G_ARRAY_OF_ARRAY_OF_UCHAR);
g_value_set_boxed (val, array);
return val;
}
gboolean
nm_supplicant_interface_request_scan (NMSupplicantInterface *self, const GPtrArray *ssids)
{
NMSupplicantInterfacePrivate *priv;
DBusGProxyCall *call;
GHashTable *hash;
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), FALSE);
priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
/* Scan parameters */
hash = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, destroy_gvalue);
g_hash_table_insert (hash, "Type", string_to_gvalue ("active"));
if (ssids)
g_hash_table_insert (hash, "SSIDs", byte_array_array_to_gvalue (ssids));
call = dbus_g_proxy_begin_call (priv->iface_proxy, "Scan",
scan_request_cb,
self,
NULL,
DBUS_TYPE_G_MAP_OF_VARIANT, hash,
G_TYPE_INVALID);
g_hash_table_destroy (hash);
nm_call_store_add (priv->other_pcalls, priv->iface_proxy, call);
return call != NULL;
}
guint32
nm_supplicant_interface_get_state (NMSupplicantInterface * self)
{
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), NM_SUPPLICANT_INTERFACE_STATE_DOWN);
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->state;
}
const char *
nm_supplicant_interface_state_to_string (guint32 state)
{
switch (state) {
case NM_SUPPLICANT_INTERFACE_STATE_INIT:
return "init";
case NM_SUPPLICANT_INTERFACE_STATE_STARTING:
return "starting";
case NM_SUPPLICANT_INTERFACE_STATE_READY:
return "ready";
case NM_SUPPLICANT_INTERFACE_STATE_DISABLED:
return "disabled";
case NM_SUPPLICANT_INTERFACE_STATE_DISCONNECTED:
return "disconnected";
case NM_SUPPLICANT_INTERFACE_STATE_INACTIVE:
return "inactive";
case NM_SUPPLICANT_INTERFACE_STATE_SCANNING:
return "scanning";
case NM_SUPPLICANT_INTERFACE_STATE_AUTHENTICATING:
return "authenticating";
case NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATING:
return "associating";
case NM_SUPPLICANT_INTERFACE_STATE_ASSOCIATED:
return "associated";
case NM_SUPPLICANT_INTERFACE_STATE_4WAY_HANDSHAKE:
return "4-way handshake";
case NM_SUPPLICANT_INTERFACE_STATE_GROUP_HANDSHAKE:
return "group handshake";
case NM_SUPPLICANT_INTERFACE_STATE_COMPLETED:
return "completed";
case NM_SUPPLICANT_INTERFACE_STATE_DOWN:
return "down";
default:
break;
}
return "unknown";
}
const char *
nm_supplicant_interface_get_device (NMSupplicantInterface * self)
{
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), NULL);
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->dev;
}
const char *
nm_supplicant_interface_get_object_path (NMSupplicantInterface *self)
{
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), NULL);
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->object_path;
}
const char *
nm_supplicant_interface_get_ifname (NMSupplicantInterface *self)
{
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), NULL);
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->dev;
}
guint
nm_supplicant_interface_get_max_scan_ssids (NMSupplicantInterface *self)
{
g_return_val_if_fail (NM_IS_SUPPLICANT_INTERFACE (self), 0);
return NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self)->max_scan_ssids;
}
/*******************************************************************/
NMSupplicantInterface *
nm_supplicant_interface_new (NMSupplicantManager *smgr,
const char *ifname,
gboolean is_wireless,
gboolean fast_supported,
ApSupport ap_support,
gboolean start_now)
{
NMSupplicantInterface *self;
NMSupplicantInterfacePrivate *priv;
guint id;
g_return_val_if_fail (NM_IS_SUPPLICANT_MANAGER (smgr), NULL);
g_return_val_if_fail (ifname != NULL, NULL);
self = g_object_new (NM_TYPE_SUPPLICANT_INTERFACE, NULL);
priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
priv->smgr = g_object_ref (smgr);
id = g_signal_connect (priv->smgr,
"notify::" NM_SUPPLICANT_MANAGER_AVAILABLE,
G_CALLBACK (smgr_avail_cb),
self);
priv->smgr_avail_id = id;
priv->dev = g_strdup (ifname);
priv->is_wireless = is_wireless;
priv->fast_supported = fast_supported;
priv->ap_support = ap_support;
if (start_now)
interface_add (self, priv->is_wireless);
return self;
}
static void
nm_supplicant_interface_init (NMSupplicantInterface * self)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (self);
DBusGConnection *bus;
priv->state = NM_SUPPLICANT_INTERFACE_STATE_INIT;
priv->assoc_pcalls = nm_call_store_new ();
priv->other_pcalls = nm_call_store_new ();
priv->dbus_mgr = nm_dbus_manager_get ();
bus = nm_dbus_manager_get_connection (priv->dbus_mgr);
priv->wpas_proxy = dbus_g_proxy_new_for_name (bus,
WPAS_DBUS_SERVICE,
WPAS_DBUS_PATH,
WPAS_DBUS_INTERFACE);
priv->bss_proxies = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, g_object_unref);
}
static void
set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
switch (prop_id) {
case PROP_SCANNING:
g_value_set_boolean (value, NM_SUPPLICANT_INTERFACE_GET_PRIVATE (object)->scanning);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
dispose (GObject *object)
{
NMSupplicantInterfacePrivate *priv = NM_SUPPLICANT_INTERFACE_GET_PRIVATE (object);
if (priv->disposed) {
G_OBJECT_CLASS (nm_supplicant_interface_parent_class)->dispose (object);
return;
}
priv->disposed = TRUE;
/* Cancel pending calls before unrefing the dbus manager */
nm_call_store_clear (priv->other_pcalls);
nm_call_store_destroy (priv->other_pcalls);
nm_call_store_clear (priv->assoc_pcalls);
nm_call_store_destroy (priv->assoc_pcalls);
if (priv->props_proxy)
g_object_unref (priv->props_proxy);
if (priv->iface_proxy)
g_object_unref (priv->iface_proxy);
g_free (priv->net_path);
if (priv->introspect_proxy)
g_object_unref (priv->introspect_proxy);
if (priv->wpas_proxy)
g_object_unref (priv->wpas_proxy);
g_hash_table_destroy (priv->bss_proxies);
if (priv->smgr) {
if (priv->smgr_avail_id)
g_signal_handler_disconnect (priv->smgr, priv->smgr_avail_id);
g_object_unref (priv->smgr);
}
g_free (priv->dev);
priv->dbus_mgr = NULL;
if (priv->cfg)
g_object_unref (priv->cfg);
g_free (priv->object_path);
/* Chain up to the parent class */
G_OBJECT_CLASS (nm_supplicant_interface_parent_class)->dispose (object);
}
static void
nm_supplicant_interface_class_init (NMSupplicantInterfaceClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (object_class, sizeof (NMSupplicantInterfacePrivate));
object_class->dispose = dispose;
object_class->set_property = set_property;
object_class->get_property = get_property;
/* Properties */
g_object_class_install_property (object_class, PROP_SCANNING,
g_param_spec_boolean ("scanning",
"Scanning",
"Scanning",
FALSE,
G_PARAM_READABLE));
/* Signals */
signals[STATE] =
g_signal_new (NM_SUPPLICANT_INTERFACE_STATE,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, state),
NULL, NULL, NULL,
G_TYPE_NONE, 3, G_TYPE_UINT, G_TYPE_UINT, G_TYPE_INT);
signals[REMOVED] =
g_signal_new (NM_SUPPLICANT_INTERFACE_REMOVED,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, removed),
NULL, NULL, NULL,
G_TYPE_NONE, 0);
signals[NEW_BSS] =
g_signal_new (NM_SUPPLICANT_INTERFACE_NEW_BSS,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, new_bss),
NULL, NULL, NULL,
G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_POINTER);
signals[BSS_UPDATED] =
g_signal_new (NM_SUPPLICANT_INTERFACE_BSS_UPDATED,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, bss_updated),
NULL, NULL, NULL,
G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_POINTER);
signals[BSS_REMOVED] =
g_signal_new (NM_SUPPLICANT_INTERFACE_BSS_REMOVED,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, bss_removed),
NULL, NULL, NULL,
G_TYPE_NONE, 1, G_TYPE_STRING);
signals[SCAN_DONE] =
g_signal_new (NM_SUPPLICANT_INTERFACE_SCAN_DONE,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, scan_done),
NULL, NULL, NULL,
G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
signals[CONNECTION_ERROR] =
g_signal_new (NM_SUPPLICANT_INTERFACE_CONNECTION_ERROR,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, connection_error),
NULL, NULL, NULL,
G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_STRING);
signals[CREDENTIALS_REQUEST] =
g_signal_new (NM_SUPPLICANT_INTERFACE_CREDENTIALS_REQUEST,
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NMSupplicantInterfaceClass, credentials_request),
NULL, NULL, NULL,
G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_STRING);
}
| heftig/NetworkManager | src/supplicant-manager/nm-supplicant-interface.c | C | gpl-2.0 | 54,091 |
/**
* (C) 2011-2012 Alibaba Group Holding Limited.
* <p>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*/
package com.taobao.profile.config;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import com.taobao.profile.utils.VariableNotFoundException;
/**
* 读取并保存配置
*
* @author xiaodu
* @since 2010-6-22
*/
public class ProfConfig {
/**
* 配置文件名
*/
private static final String CONFIG_FILE_NAME = "profile.properties";
/**
* 默认的配置文件路径,~/.tprofiler/profile.properties
*/
private File DEFAULT_PROFILE_PATH = new File(System.getProperty("user.home"),
"/.tprofiler/" + CONFIG_FILE_NAME);
/**
* 开始profile时间
*/
private String startProfTime;
/**
* 结束profile时间
*/
private String endProfTime;
/**
* log文件路径
*/
private String logFilePath;
/**
* method文件路径
*/
private String methodFilePath;
/**
* sampler文件路径
*/
private String samplerFilePath;
/**
* 不包括的ClassLoader
*/
private String excludeClassLoader;
/**
* 包括的包名
*/
private String includePackageStartsWith;
/**
* 不包括的包名
*/
private String excludePackageStartsWith;
/**
* 每次profile用时
*/
private int eachProfUseTime = -1;
/**
* 两次profile间隔时间
*/
private int eachProfIntervalTime = -1;
/**
* 两次sampler间隔时间
*/
private int samplerIntervalTime = -1;
/**
* 是否用纳秒采集
*/
private boolean needNanoTime;
/**
* 是否忽略get/set方法
*/
private boolean ignoreGetSetMethod;
/**
* 是否进入调试模式
*/
private boolean debugMode;
/**
* Socket端口号配置
*/
private int port;
/**
* 构造方法
*/
public ProfConfig() {
//此时配置文件中的debug参数还未读取,因此使用-Dtprofiler.debug=true来读取,用于开发时调试
boolean debug = "true".equalsIgnoreCase(System.getProperty("tprofiler.debug"));
/*
* 查找顺序:
* 1. 系统参数-Dprofile.properties=/path/profile.properties
* 2. 当前文件夹下的profile.properties
* 3. 用户文件夹~/.tprofiler/profile.properties,如:/home/manlge/.tprofiler/profile
* .properties
* 4. 默认jar包中的profile.properties
*/
String specifiedConfigFileName = System.getProperty(CONFIG_FILE_NAME);
File configFiles[] = {
specifiedConfigFileName == null ? null : new File(
specifiedConfigFileName),
new File(CONFIG_FILE_NAME),
DEFAULT_PROFILE_PATH
};
for (File file : configFiles) {
if (file != null && file.exists() && file.isFile()) {
if (debug) {
System.out.println(String.format("load configuration from \"%s\".",
file.getAbsolutePath()));
}
parseProperty(file);
return;
}
}
//加载默认配置
if (debug) {
System.out.println(String.format("load configuration from \"%s\".",
DEFAULT_PROFILE_PATH.getAbsolutePath()));
}
try {
extractDefaultProfile();
parseProperty(DEFAULT_PROFILE_PATH);
} catch (IOException e) {
throw new RuntimeException("error load config file " + DEFAULT_PROFILE_PATH,
e);
}
}
/**
* 解压默认的配置文件到~/.tprofiler/profile.properties,作为模板,以便用户编辑
* @throws IOException
*/
private void extractDefaultProfile() throws IOException {
/*
* 这里采用stream进行复制,而不是采用properties.load和save,主要原因为以下2点:
* 1. 性能,stream直接复制快,没有properties解析过程(不过文件较小,解析开销可以忽略)
* 2. properties会造成注释丢失,该文件作为模板提供给用户,包含注释信息
*/
InputStream in = new BufferedInputStream(
getClass().getClassLoader().getResourceAsStream(CONFIG_FILE_NAME));
OutputStream out = null;
try {
File profileDirectory = DEFAULT_PROFILE_PATH.getParentFile();
if (!profileDirectory.exists()) {
profileDirectory.mkdirs();
}
out = new BufferedOutputStream(new FileOutputStream(DEFAULT_PROFILE_PATH));
byte[] buffer = new byte[1024];
for (int len = -1; (len = in.read(buffer)) != -1; ) {
out.write(buffer, 0, len);
}
} finally {
in.close();
out.close();
}
}
/**
* 解析用户自定义配置文件
* @param path
*/
private void parseProperty(File path) {
Properties properties = new Properties();
try {
properties.load(new FileReader(path)); //配置文件原始内容,未进行变量替换
//变量查找上下文,采用System.properties和配置文件集合
Properties context = new Properties();
context.putAll(System.getProperties());
context.putAll(properties);
//加载配置
loadConfig(new ConfigureProperties(properties, context));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加载配置
* @param properties
*/
private void loadConfig(Properties properties) throws VariableNotFoundException {
String startProfTime = properties.getProperty("startProfTime");
String endProfTime = properties.getProperty("endProfTime");
String logFilePath = properties.getProperty("logFilePath");
String methodFilePath = properties.getProperty("methodFilePath");
String samplerFilePath = properties.getProperty("samplerFilePath");
String includePackageStartsWith = properties.getProperty(
"includePackageStartsWith");
String eachProfUseTime = properties.getProperty("eachProfUseTime");
String eachProfIntervalTime = properties.getProperty("eachProfIntervalTime");
String samplerIntervalTime = properties.getProperty("samplerIntervalTime");
String excludePackageStartsWith = properties.getProperty(
"excludePackageStartsWith");
String needNanoTime = properties.getProperty("needNanoTime");
String ignoreGetSetMethod = properties.getProperty("ignoreGetSetMethod");
String excludeClassLoader = properties.getProperty("excludeClassLoader");
String debugMode = properties.getProperty("debugMode");
String port = properties.getProperty("port");
setPort(port == null ? 50000 : Integer.valueOf(port));
setDebugMode(
"true".equalsIgnoreCase(debugMode == null ? null : debugMode.trim()));
setExcludeClassLoader(excludeClassLoader);
setExcludePackageStartsWith(excludePackageStartsWith);
setEndProfTime(endProfTime);
setIncludePackageStartsWith(includePackageStartsWith);
setLogFilePath(logFilePath);
setMethodFilePath(methodFilePath);
setSamplerFilePath(samplerFilePath);
setStartProfTime(startProfTime);
setNeedNanoTime("true".equals(needNanoTime));
setIgnoreGetSetMethod("true".equals(ignoreGetSetMethod));
if (eachProfUseTime == null) {
setEachProfUseTime(5);
} else {
setEachProfUseTime(Integer.valueOf(eachProfUseTime.trim()));
}
if (eachProfIntervalTime == null) {
setEachProfIntervalTime(50);
} else {
setEachProfIntervalTime(Integer.valueOf(eachProfIntervalTime.trim()));
}
if (samplerIntervalTime == null) {
setSamplerIntervalTime(10);
} else {
setSamplerIntervalTime(Integer.valueOf(samplerIntervalTime.trim()));
}
}
/**
* @return
*/
public String getStartProfTime() {
return startProfTime;
}
/**
* @param startProfTime
*/
public void setStartProfTime(String startProfTime) {
this.startProfTime = startProfTime;
}
/**
* @return
*/
public String getEndProfTime() {
return endProfTime;
}
/**
* @param endProfTime
*/
public void setEndProfTime(String endProfTime) {
this.endProfTime = endProfTime;
}
/**
* @return
*/
public String getLogFilePath() {
return logFilePath;
}
/**
* @param logFilePath
*/
public void setLogFilePath(String logFilePath) {
this.logFilePath = logFilePath;
}
/**
* @return the methodFilePath
*/
public String getMethodFilePath() {
return methodFilePath;
}
/**
* @param methodFilePath
* the methodFilePath to set
*/
public void setMethodFilePath(String methodFilePath) {
this.methodFilePath = methodFilePath;
}
/**
* @return
*/
public String getIncludePackageStartsWith() {
return includePackageStartsWith;
}
/**
* @param includePackageStartsWith
*/
public void setIncludePackageStartsWith(String includePackageStartsWith) {
this.includePackageStartsWith = includePackageStartsWith;
}
/**
* @return
*/
public int getEachProfUseTime() {
return eachProfUseTime;
}
/**
* @param eachProfUseTime
*/
public void setEachProfUseTime(int eachProfUseTime) {
this.eachProfUseTime = eachProfUseTime;
}
/**
* @return
*/
public int getEachProfIntervalTime() {
return eachProfIntervalTime;
}
/**
* @param eachProfIntervalTime
*/
public void setEachProfIntervalTime(int eachProfIntervalTime) {
this.eachProfIntervalTime = eachProfIntervalTime;
}
/**
* @return
*/
public String getExcludePackageStartsWith() {
return excludePackageStartsWith;
}
/**
* @param excludePackageStartsWith
*/
public void setExcludePackageStartsWith(String excludePackageStartsWith) {
this.excludePackageStartsWith = excludePackageStartsWith;
}
/**
* @return
*/
public boolean isNeedNanoTime() {
return needNanoTime;
}
/**
* @param needNanoTime
*/
public void setNeedNanoTime(boolean needNanoTime) {
this.needNanoTime = needNanoTime;
}
/**
* @return
*/
public boolean isIgnoreGetSetMethod() {
return ignoreGetSetMethod;
}
/**
* @param ignoreGetSetMethod
*/
public void setIgnoreGetSetMethod(boolean ignoreGetSetMethod) {
this.ignoreGetSetMethod = ignoreGetSetMethod;
}
/**
* @return the samplerFilePath
*/
public String getSamplerFilePath() {
return samplerFilePath;
}
/**
* @param samplerFilePath
* the samplerFilePath to set
*/
public void setSamplerFilePath(String samplerFilePath) {
this.samplerFilePath = samplerFilePath;
}
/**
* @return the samplerIntervalTime
*/
public int getSamplerIntervalTime() {
return samplerIntervalTime;
}
/**
* @param samplerIntervalTime
* the samplerIntervalTime to set
*/
public void setSamplerIntervalTime(int samplerIntervalTime) {
this.samplerIntervalTime = samplerIntervalTime;
}
/**
* @return the excludeClassLoader
*/
public String getExcludeClassLoader() {
return excludeClassLoader;
}
/**
* @param excludeClassLoader the excludeClassLoader to set
*/
public void setExcludeClassLoader(String excludeClassLoader) {
this.excludeClassLoader = excludeClassLoader;
}
/**
* @return the debugMode
*/
public boolean isDebugMode() {
return debugMode;
}
/**
* @param debugMode the debugMode to set
*/
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
| zhoulifu/TProfiler | src/main/java/com/taobao/profile/config/ProfConfig.java | Java | gpl-2.0 | 12,957 |
/** arch/arm/mach-msm/smd_rpcrouter.h
*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2007-2008 QUALCOMM Incorporated.
* Author: San Mehat <san@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef _ARCH_ARM_MACH_MSM_SMD_RPCROUTER_H
#define _ARCH_ARM_MACH_MSM_SMD_RPCROUTER_H
#include <linux/types.h>
#include <linux/list.h>
#include <linux/cdev.h>
#include <linux/platform_device.h>
#include <linux/wakelock.h>
#include <mach/msm_smd.h>
#include <mach/msm_rpcrouter.h>
/* definitions for the R2R wire protcol */
#define RPCROUTER_VERSION 1
#define RPCROUTER_PROCESSORS_MAX 4
#if defined(CONFIG_RPC_SIZE_1024)
#define RPCROUTER_MSGSIZE_MAX 1024
#else
#define RPCROUTER_MSGSIZE_MAX 512
#endif
#if defined(CONFIG_ARCH_MSM7X30)
#define RPCROUTER_PEND_REPLIES_MAX 32
#endif
#define RPCROUTER_CLIENT_BCAST_ID 0xffffffff
#define RPCROUTER_ROUTER_ADDRESS 0xfffffffe
#define RPCROUTER_PID_LOCAL 1
#define RPCROUTER_PID_REMOTE 0
#define RPCROUTER_CTRL_CMD_DATA 1
#define RPCROUTER_CTRL_CMD_HELLO 2
#define RPCROUTER_CTRL_CMD_BYE 3
#define RPCROUTER_CTRL_CMD_NEW_SERVER 4
#define RPCROUTER_CTRL_CMD_REMOVE_SERVER 5
#define RPCROUTER_CTRL_CMD_REMOVE_CLIENT 6
#define RPCROUTER_CTRL_CMD_RESUME_TX 7
#define RPCROUTER_CTRL_CMD_EXIT 8
#define RPCROUTER_DEFAULT_RX_QUOTA 5
union rr_control_msg {
uint32_t cmd;
struct {
uint32_t cmd;
uint32_t prog;
uint32_t vers;
uint32_t pid;
uint32_t cid;
} srv;
struct {
uint32_t cmd;
uint32_t pid;
uint32_t cid;
} cli;
};
struct rr_header {
uint32_t version;
uint32_t type;
uint32_t src_pid;
uint32_t src_cid;
uint32_t confirm_rx;
uint32_t size;
uint32_t dst_pid;
uint32_t dst_cid;
};
/* internals */
#define RPCROUTER_MAX_REMOTE_SERVERS 100
struct rr_fragment {
unsigned char data[RPCROUTER_MSGSIZE_MAX];
uint32_t length;
struct rr_fragment *next;
};
struct rr_packet {
struct list_head list;
struct rr_fragment *first;
struct rr_fragment *last;
struct rr_header hdr;
uint32_t mid;
uint32_t length;
};
#define PACMARK_LAST(n) ((n) & 0x80000000)
#define PACMARK_MID(n) (((n) >> 16) & 0xFF)
#define PACMARK_LEN(n) ((n) & 0xFFFF)
static inline uint32_t PACMARK(uint32_t len, uint32_t mid, uint32_t first,
uint32_t last)
{
return (len & 0xFFFF) |
((mid & 0xFF) << 16) |
((!!first) << 30) |
((!!last) << 31);
}
struct rr_server {
struct list_head list;
uint32_t pid;
uint32_t cid;
uint32_t prog;
uint32_t vers;
dev_t device_number;
struct cdev cdev;
struct device *device;
struct rpcsvr_platform_device p_device;
char pdev_name[32];
};
struct rr_remote_endpoint {
uint32_t pid;
uint32_t cid;
int tx_quota_cntr;
#if defined(CONFIG_ARCH_MSM7X30)
int quota_restart_state;
#endif
spinlock_t quota_lock;
wait_queue_head_t quota_wait;
struct list_head list;
};
#if defined(CONFIG_ARCH_MSM7X30)
struct msm_rpc_reply {
struct list_head list;
uint32_t pid;
uint32_t cid;
uint32_t prog; /* be32 */
uint32_t vers; /* be32 */
uint32_t xid; /* be32 */
};
#endif
struct msm_rpc_endpoint {
struct list_head list;
/* incomplete packets waiting for assembly */
struct list_head incomplete;
/* complete packets waiting to be read */
struct list_head read_q;
spinlock_t read_q_lock;
struct wake_lock read_q_wake_lock;
wait_queue_head_t wait_q;
unsigned flags;
#if defined(CONFIG_ARCH_MSM7X30)
/* restart handling */
int restart_state;
spinlock_t restart_lock;
wait_queue_head_t restart_wait;
#endif
/* endpoint address */
uint32_t pid;
uint32_t cid;
/* bound remote address
* if not connected (dst_pid == 0xffffffff) RPC_CALL writes fail
* RPC_CALLs must be to the prog/vers below or they will fail
*/
uint32_t dst_pid;
uint32_t dst_cid;
uint32_t dst_prog; /* be32 */
uint32_t dst_vers; /* be32 */
/* reply remote address
* if reply_pid == 0xffffffff, none available
* RPC_REPLY writes may only go to the pid/cid/xid of the
* last RPC_CALL we received.
*/
uint32_t reply_pid;
uint32_t reply_cid;
uint32_t reply_xid; /* be32 */
uint32_t next_pm; /* Pacmark sequence */
#if defined(CONFIG_ARCH_MSM7X30)
/* reply queue for inbound messages */
struct list_head reply_pend_q;
struct list_head reply_avail_q;
spinlock_t reply_q_lock;
uint32_t reply_cnt;
struct wake_lock reply_q_wake_lock;
#endif
/* device node if this endpoint is accessed via userspace */
dev_t dev;
};
struct msm_rpc_reply_buff {
uint32_t pid;
uint32_t cid;
uint32_t xid;
};
/* shared between smd_rpcrouter*.c */
int __msm_rpc_read(struct msm_rpc_endpoint *ept,
struct rr_fragment **frag,
unsigned len, long timeout);
int msm_rpcrouter_close(void);
struct msm_rpc_endpoint *msm_rpcrouter_create_local_endpoint(dev_t dev);
int msm_rpcrouter_destroy_local_endpoint(struct msm_rpc_endpoint *ept);
int msm_rpcrouter_create_server_cdev(struct rr_server *server);
int msm_rpcrouter_create_server_pdev(struct rr_server *server);
int msm_rpcrouter_init_devices(void);
void msm_rpcrouter_exit_devices(void);
#if defined(CONFIG_ARCH_MSM7X30)
void get_requesting_client(struct msm_rpc_endpoint *ept, uint32_t xid,
struct msm_rpc_client_info *clnt_info);
#endif
extern dev_t msm_rpcrouter_devno;
extern struct class *msm_rpcrouter_class;
void xdr_init(struct msm_rpc_xdr *xdr);
void xdr_init_input(struct msm_rpc_xdr *xdr, void *buf, uint32_t size);
void xdr_init_output(struct msm_rpc_xdr *xdr, void *buf, uint32_t size);
void xdr_clean_input(struct msm_rpc_xdr *xdr);
void xdr_clean_output(struct msm_rpc_xdr *xdr);
uint32_t xdr_read_avail(struct msm_rpc_xdr *xdr);
#endif
| Daniil2017/HTC-desire-A8181-kernel | arch/arm/mach-msm/smd_rpcrouter.h | C | gpl-2.0 | 5,989 |
# GRECO
Application Odoo pour groupements associatifs d'achats
Initialement créé avec et pour répondre aux besoins d'associations de consommateurs de produits écologiques, cette application comprendra dans sa première version les fonctionnalités suivantes :
- Gestion de l'association
- Gestion des commandes groupées, alertes par email et SMS
- Passage de commande des membres par le biais du site web
- Espace membres (intranet)
- Gestion des commandes fournisseurs
- Comptabilité
- Catalogues
Toute aide, au niveau de la définition des besoins ou de la programmation, est bienvenue !
| LLPIE/GRECO | README.md | Markdown | gpl-2.0 | 611 |
#
# linux/arch/arm/vfp/Makefile
#
# Copyright (C) 2001 ARM Limited
#
# ccflags-y := -DDEBUG
# asflags-y := -DDEBUG
KBUILD_AFLAGS :=$(KBUILD_AFLAGS:-msoft-float=-Wa,-mfpu=vfpv3-d16)
LDFLAGS +=--no-warn-mismatch
obj-y += vfp.o
vfp-$(CONFIG_VFP) += vfpmodule.o entry.o vfphw.o vfpsingle.o vfpdouble.o
| motley-git/TF201-Kernel | arch/arm/vfp/Makefile | Makefile | gpl-2.0 | 306 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth import views
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'lite_note.views.home', name='home'),
url(r'^test','lite_note.views.new_home',name='new_home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/', views.login, name='login'),
url(r'^logout/', views.logout, {'next_page': 'home'}, name='logout'),
url(r'^register/', 'regsiter.views.registration', name='registration_register'),
url(r'^create/', 'lite_note.views.create_note', name='create_note'),
url(r'^unknown/', 'lite_note.views.enter_anonymous_user', name='enter_anonymous'),
url(r'^note/(?P<id>[0-9]+)/', 'lite_note.views.note', name='note'),
url(r'^delete/(?P<id>[0-9]+)','lite_note.tools.delet_note'),
url(r'^private/(?P<id>[0-9]+)','lite_note.tools.make_private_note'),
url(r'^public/(?P<id>[0-9]+)','lite_note.tools.make_public_note'),
url(r'^favorite/(?P<id>[0-9]+)','lite_note.tools.make_favorite_note'),
url(r'^unfavorite/(?P<id>[0-9]+)','lite_note.tools.make_usual_note'),
url(r'^get_login','regsiter.views.request_login'),
url(r'^test','lite_note.views.new_home',name='new_home'),
url(r'^get_notes','lite_note.views.new_note',name='new_note')
)
| Shiwin/LiteNote | noties/urls.py | Python | gpl-2.0 | 1,648 |
static unsigned char dot_intensity[] = {
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x78,0x99,0xa6,0x99,0x71,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x99,0x9d,0x7c,0x6e,0x55,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0xa6,0x7c,0x6e,0x66,0x4c,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x99,0x6e,0x66,0x52,0x55,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x71,0x55,0x4c,0x55,0x68,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,0x6e,
};
static unsigned char dot_alpha[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x66,0xd4,0xff,0xd4,0x66,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x66,0xff,0xff,0xff,0xff,0xff,0x66,0x00,0x00,0x00,
0x00,0x00,0x00,0xd4,0xff,0xff,0xff,0xff,0xff,0xd4,0x00,0x00,0x00,
0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,
0x00,0x00,0x00,0xd4,0xff,0xff,0xff,0xff,0xff,0xd4,0x00,0x00,0x00,
0x00,0x00,0x00,0x66,0xff,0xff,0xff,0xff,0xff,0x66,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x66,0xd4,0xff,0xd4,0x66,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
static unsigned char circle_alpha[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x23,0x62,0x92,0xb3,0xb2,0x95,0x2b,0x00,0x00,0x00,
0x00,0x00,0x3e,0xab,0xc9,0xeb,0xf9,0xf5,0xfd,0xff,0x57,0x00,0x00,
0x00,0x1f,0xb5,0xd8,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0x2b,0x00,
0x00,0x67,0xb9,0xf2,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x9c,0x00,
0x00,0x9a,0xe2,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe5,0x00,
0x00,0xba,0xeb,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xc0,0xfa,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe5,0x00,
0x00,0x9b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x9c,0x00,
0x00,0x2b,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x2b,0x00,
0x00,0x00,0x57,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x57,0x00,0x00,
0x00,0x00,0x00,0x2b,0x9c,0xe5,0xff,0xe5,0x9c,0x2b,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
static unsigned char outline_alpha[] = {
0x00,0x00,0x00,0x4a,0xac,0xe9,0xff,0xe9,0xac,0x4a,0x00,0x00,0x00,
0x00,0x00,0x98,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x98,0x00,0x00,
0x00,0x98,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x98,0x00,
0x4a,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x4a,
0xac,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xac,
0xe9,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe9,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xe9,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe9,
0xac,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xac,
0x4a,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x4a,
0x00,0x98,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x98,0x00,
0x00,0x00,0x98,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x98,0x00,0x00,
0x00,0x00,0x00,0x4a,0xac,0xe9,0xff,0xe9,0xac,0x4a,0x00,0x00,0x00,
};
static unsigned char inconsistent_alpha[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,
0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,
0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xf8,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
static unsigned char check_base_alpha[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0xca,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
static unsigned char check_alpha[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x7c,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x2c,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0x00,0x00,0x00,
0x00,0x00,0x00,0x74,0x74,0x00,0x69,0xff,0xff,0x00,0x00,0x00,0x00,
0x00,0x00,0x74,0xff,0xff,0x74,0xff,0xff,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x74,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
static unsigned char check_inconsistent_alpha[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,
0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,
0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
| gestiweb/eneboo | src/plugins/styles/bluecurve/bits.h | C | gpl-2.0 | 7,646 |
/*
* arch/sh/kernel/vsyscall.c
*
* Copyright (C) 2006 Paul Mundt
*
* vDSO randomization
* Copyright(C) 2005-2006, Red Hat, Inc., Ingo Molnar
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/gfp.h>
#include <linux/module.h>
#include <linux/elf.h>
/*
* Should the kernel map a VDSO page into processes and pass its
* address down to glibc upon exec()?
*/
unsigned int __read_mostly vdso_enabled = 1;
EXPORT_SYMBOL_GPL(vdso_enabled);
static int __init vdso_setup(char *s)
{
vdso_enabled = simple_strtoul(s, NULL, 0);
return 1;
}
__setup("vdso=", vdso_setup);
/*
* These symbols are defined by vsyscall.o to mark the bounds
* of the ELF DSO images included therein.
*/
extern const char vsyscall_trapa_start, vsyscall_trapa_end;
static void *syscall_page;
int __init vsyscall_init(void)
{
syscall_page = (void *)get_zeroed_page(GFP_ATOMIC);
/*
* XXX: Map this page to a fixmap entry if we get around
* to adding the page to ELF core dumps
*/
memcpy(syscall_page,
&vsyscall_trapa_start,
&vsyscall_trapa_end - &vsyscall_trapa_start);
return 0;
}
static struct page *syscall_vma_nopage(struct vm_area_struct *vma,
unsigned long address, int *type)
{
unsigned long offset = address - vma->vm_start;
struct page *page;
if (address < vma->vm_start || address > vma->vm_end)
return NOPAGE_SIGBUS;
page = virt_to_page(syscall_page + offset);
get_page(page);
return page;
}
/* Prevent VMA merging */
static void syscall_vma_close(struct vm_area_struct *vma)
{
}
static struct vm_operations_struct syscall_vm_ops = {
.nopage = syscall_vma_nopage,
.close = syscall_vma_close,
};
/* Setup a VMA at program startup for the vsyscall page */
int arch_setup_additional_pages(struct linux_binprm *bprm,
int executable_stack)
{
struct vm_area_struct *vma;
struct mm_struct *mm = current->mm;
unsigned long addr;
int ret;
down_write(&mm->mmap_sem);
addr = get_unmapped_area(NULL, 0, PAGE_SIZE, 0, 0);
if (IS_ERR_VALUE(addr)) {
ret = addr;
goto up_fail;
}
vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (!vma) {
ret = -ENOMEM;
goto up_fail;
}
vma->vm_start = addr;
vma->vm_end = addr + PAGE_SIZE;
/* MAYWRITE to allow gdb to COW and set breakpoints */
vma->vm_flags = VM_READ|VM_EXEC|VM_MAYREAD|VM_MAYEXEC|VM_MAYWRITE;
vma->vm_flags |= mm->def_flags;
vma->vm_page_prot = protection_map[vma->vm_flags & 7];
vma->vm_ops = &syscall_vm_ops;
vma->vm_mm = mm;
ret = insert_vm_struct(mm, vma);
if (unlikely(ret)) {
kmem_cache_free(vm_area_cachep, vma);
goto up_fail;
}
current->mm->context.vdso = (void *)addr;
mm->total_vm++;
up_fail:
up_write(&mm->mmap_sem);
return ret;
}
const char *arch_vma_name(struct vm_area_struct *vma)
{
if (vma->vm_mm && vma->vm_start == (long)vma->vm_mm->context.vdso)
return "[vdso]";
return NULL;
}
struct vm_area_struct *get_gate_vma(struct task_struct *task)
{
return NULL;
}
int in_gate_area(struct task_struct *task, unsigned long address)
{
return 0;
}
int in_gate_area_no_task(unsigned long address)
{
return 0;
}
| xiandaicxsj/copyKvm | arch/sh/kernel/vsyscall/vsyscall.c | C | gpl-2.0 | 3,309 |
// This file has been generated by Py++.
// (C) Christopher Woods, GPL >= 2 License
#include "boost/python.hpp"
#include "AtomNameMatcher.pypp.hpp"
namespace bp = boost::python;
#include "SireError/errors.h"
#include "SireMaths/vector.h"
#include "SireStream/datastream.h"
#include "SireUnits/units.h"
#include "atom.h"
#include "atomidentifier.h"
#include "atomidx.h"
#include "atommatcher.h"
#include "atommatchers.h"
#include "atomname.h"
#include "atomselection.h"
#include "evaluator.h"
#include "moleculeinfodata.h"
#include "moleculeview.h"
#include "mover.h"
#include "selector.hpp"
#include "tostring.h"
#include "atommatchers.h"
SireMol::AtomNameMatcher __copy__(const SireMol::AtomNameMatcher &other){ return SireMol::AtomNameMatcher(other); }
#include "Qt/qdatastream.hpp"
#include "Helpers/str.hpp"
void register_AtomNameMatcher_class(){
{ //::SireMol::AtomNameMatcher
typedef bp::class_< SireMol::AtomNameMatcher, bp::bases< SireMol::AtomMatcher, SireBase::Property > > AtomNameMatcher_exposer_t;
AtomNameMatcher_exposer_t AtomNameMatcher_exposer = AtomNameMatcher_exposer_t( "AtomNameMatcher", "This is a simple atom matcher that matches the atoms based\non their names, so the atom called CA1 in molinfo0 will\nbe matched to the atom called CA1 in molinfo1\n\nAuthor: Christopher Woods\n", bp::init< >("Constructor") );
bp::scope AtomNameMatcher_scope( AtomNameMatcher_exposer );
AtomNameMatcher_exposer.def( bp::init< SireMol::AtomNameMatcher const & >(( bp::arg("arg0") ), "Copy constructor") );
AtomNameMatcher_exposer.def( bp::self != bp::self );
{ //::SireMol::AtomNameMatcher::operator=
typedef ::SireMol::AtomNameMatcher & ( ::SireMol::AtomNameMatcher::*assign_function_type)( ::SireMol::AtomNameMatcher const & ) ;
assign_function_type assign_function_value( &::SireMol::AtomNameMatcher::operator= );
AtomNameMatcher_exposer.def(
"assign"
, assign_function_value
, ( bp::arg("other") )
, bp::return_self< >()
, "" );
}
AtomNameMatcher_exposer.def( bp::self == bp::self );
{ //::SireMol::AtomNameMatcher::toString
typedef ::QString ( ::SireMol::AtomNameMatcher::*toString_function_type)( ) const;
toString_function_type toString_function_value( &::SireMol::AtomNameMatcher::toString );
AtomNameMatcher_exposer.def(
"toString"
, toString_function_value
, "" );
}
{ //::SireMol::AtomNameMatcher::typeName
typedef char const * ( *typeName_function_type )( );
typeName_function_type typeName_function_value( &::SireMol::AtomNameMatcher::typeName );
AtomNameMatcher_exposer.def(
"typeName"
, typeName_function_value
, "" );
}
{ //::SireMol::AtomNameMatcher::what
typedef char const * ( ::SireMol::AtomNameMatcher::*what_function_type)( ) const;
what_function_type what_function_value( &::SireMol::AtomNameMatcher::what );
AtomNameMatcher_exposer.def(
"what"
, what_function_value
, "" );
}
AtomNameMatcher_exposer.staticmethod( "typeName" );
AtomNameMatcher_exposer.def( "__copy__", &__copy__);
AtomNameMatcher_exposer.def( "__deepcopy__", &__copy__);
AtomNameMatcher_exposer.def( "clone", &__copy__);
AtomNameMatcher_exposer.def( "__rlshift__", &__rlshift__QDataStream< ::SireMol::AtomNameMatcher >,
bp::return_internal_reference<1, bp::with_custodian_and_ward<1,2> >() );
AtomNameMatcher_exposer.def( "__rrshift__", &__rrshift__QDataStream< ::SireMol::AtomNameMatcher >,
bp::return_internal_reference<1, bp::with_custodian_and_ward<1,2> >() );
AtomNameMatcher_exposer.def_pickle(sire_pickle_suite< ::SireMol::AtomNameMatcher >());
AtomNameMatcher_exposer.def( "__str__", &__str__< ::SireMol::AtomNameMatcher > );
AtomNameMatcher_exposer.def( "__repr__", &__str__< ::SireMol::AtomNameMatcher > );
}
}
| michellab/Sire | wrapper/Mol/AtomNameMatcher.pypp.cpp | C++ | gpl-2.0 | 4,394 |
/**
* @file clocks.c
* @author Pavel Komarov <pkomarov@gatech.edu> 941-545-7573
* @brief A library that provides easy ways to set system clocks
* @ingroup Digital
* @version 1
*
* http://solarracing.gatech.edu/wiki/Main_Page
*/
#include "F2806x_Device.h"
#include "clocks.h"
/*
* divsel and div make setting these with an FCLKS as trivial as single operations
*
* see Table 1-24 in the Technical reference manual for why these values are as they are.
*/
Uint16 divsel[36] = {1, 2, 1, 3, 1, 2,//2.5-15
1, 3, 1, 2, 1, 3,//17.5-30
1, 2, 1, 3, 1, 2,//32.5-45
3, 2, 3, 2, 3, 2,//50-75
3, 2, 3, 3, 3, 3,//80-120
3, 3, 3, 3, 3, 3};//130-180
Uint16 div[36] = {1, 1, 3, 1, 5, 3,//2.5-15
7, 2, 9, 5, 11,3,//17.5-30
13,7, 15,4, 17,9,//32.5-45
5, 11,6, 13,7, 15,//50-75
8, 17,9, 10,11,12,//80-120
13,14,15,16,17,18};//130-180
//possible clock frequencies in MHz
float32 xfclks[36]= {2.5, 5, 7.5, 10, 12.5, 15,
17.5, 20, 22.5, 25, 27.5, 30,
32.5, 35, 37.5, 40, 42.5, 45,
50, 55, 60, 65, 70, 75,
80, 85, 90, 100, 110, 120,
130, 140, 150, 160, 170, 180};
float32 xfclk;//for saving the the current clock frequency (in MHz)
float32 xftmr;//for saving current timer frequency (in kHz)
/*
* SysClkInit sets the system clock in MHz. The system clock can only take
* on a few values, multiples of fosc (the frequency of the oscillator used).
* So, an enum called FCLKS has been defined to aid the user in choosing a
* frequency. Note the default oscillator has a frequency of 10MHz; if a
* different oscillator is used, then this function will set fclk to
* (new fosc)/10MHz*(number of MHz specified with FLCKS enum).
*
* @param fclk An enum of type FCLKS describing the desired clock frequency in MHz
*/
void SysClkInit(FCLKS fclk) {
xfclk = xfclks[fclk];
//following lines are from page 82,83,84,85 of Tech ref man
if (SysCtrlRegs.PLLSTS.bit.MCLKSTS != 0) {//1. if not in normal operation mode, exit
return;
}
SysCtrlRegs.PLLSTS.bit.DIVSEL = 0;//2. set DIVSEL to 0
SysCtrlRegs.PLLSTS.bit.MCLKOFF = 1;//3. turn off failed osc detection
SysCtrlRegs.PLLCR.bit.DIV = div[fclk];//4. set DIV to be some new value
while (SysCtrlRegs.PLLSTS.bit.PLLLOCKS != 1){//5. wait for PLLLOCKS to be 1
continue;
}
SysCtrlRegs.PLLSTS.bit.MCLKOFF = 0;//6. reenable failed osc detection
SysCtrlRegs.PLLSTS.bit.DIVSEL = divsel[fclk];//7. set DIVSEL
}
/**
* TimerInit sets the system timer, which controls the rate of SPI among
* other systems. Note this function relies upon knowing the clock frequency,
* which is only stored when fclk is set by the user. So, this function
* should be called after SysClkInit(FCLKS fclk).
*
* @param ftmr A float describing the desired timer frequency in kHz
*/
void TimerInit(float32 ftmr) {
xftmr = ftmr;
//use current fclk to calculate proper divisor so ftmr is as desired
Uint32 prd = xfclk*1000/ftmr -1;//multiply by 1000 to put xfclk in kHz
CpuTimer0Regs.TCR.bit.TSS = 1;//stop the timer
CpuTimer0Regs.TCR.bit.TIE = 1;//enable timer-triggered interrupts
CpuTimer0Regs.PRD.all = prd;//should set to appropriate value
CpuTimer0Regs.TPR.all = 0;//the other divisor
CpuTimer0Regs.TCR.bit.TSS = 0;//start the timer
}
/**
* @return The current system clock frequency in MHz.
*/
float32 getfclk() {
return xfclk;
}
/**
* Services the watchdog
*/
void serviceWatchog(){
EALLOW;
SysCtrlRegs.WDKEY = 0x55;
SysCtrlRegs.WDKEY = 0xAA;
EDIS;
}
| gtsolarracing/TI-C2000-dev-suite | C2000-Workspace/C2000 Libraries/Clock Library/clocks.c | C | gpl-2.0 | 3,506 |
package net.demilich.metastone.game.events;
import net.demilich.metastone.game.Attribute;
import net.demilich.metastone.game.GameContext;
import net.demilich.metastone.game.entities.Entity;
public class AttributeGainedEvent extends GameEvent {
private final Entity target;
private final Attribute attribute;
public AttributeGainedEvent(GameContext context, Entity target, Attribute attribute) {
super(context, target.getOwner(), -1);
this.target = target;
this.attribute = attribute;
}
@Override
public Entity getEventTarget() {
return target;
}
public Attribute getEventAttribute() {
return attribute;
}
@Override
public GameEventType getEventType() {
return GameEventType.ATTRIBUTE_GAINED;
}
}
| doombubbles/metastonething | game/src/main/java/net/demilich/metastone/game/events/AttributeGainedEvent.java | Java | gpl-2.0 | 730 |
<?php
/**
* Used to set up and fix common variables and include
* the Multisite procedural and class library.
*
* Allows for some configuration in wp-config.php (see ms-default-constants.php)
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Include Multisite initialization functions */
require( ABSPATH . WPINC . '/ms-load.php' );
require( ABSPATH . WPINC . '/ms-default-constants.php' );
if ( defined( 'SUNRISE' ) )
include_once( WP_CONTENT_DIR . '/sunrise.php' );
/** Check for and define SUBDOMAIN_INSTALL and the deprecated VHOST constant. */
ms_subdomain_constants();
if ( !isset( $current_site ) || !isset( $current_blog ) ) {
$domain = addslashes( $_SERVER['HTTP_HOST'] );
if ( false !== strpos( $domain, ':' ) ) {
if ( substr( $domain, -3 ) == ':80' ) {
$domain = substr( $domain, 0, -3 );
$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -3 );
} elseif ( substr( $domain, -4 ) == ':443' ) {
$domain = substr( $domain, 0, -4 );
$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -4 );
} else {
wp_load_translations_early();
wp_die( __( 'Multisite only works without the port number in the URL.' ) );
}
}
$domain = rtrim( $domain, '.' );
$cookie_domain = $domain;
if ( substr( $cookie_domain, 0, 4 ) == 'www.' )
$cookie_domain = substr( $cookie_domain, 4 );
$path = preg_replace( '|([a-z0-9-]+.php.*)|', '', $_SERVER['REQUEST_URI'] );
$path = str_replace ( '/wp-admin/', '/', $path );
$path = preg_replace( '|(/[a-z0-9-]+?/).*|', '$1', $path );
$current_site = wpmu_current_site();
if ( ! isset( $current_site->blog_id ) )
$current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) );
if ( is_subdomain_install() ) {
$current_blog = wp_cache_get( 'current_blog_' . $domain, 'site-options' );
if ( !$current_blog ) {
$current_blog = get_blog_details( array( 'domain' => $domain ), false );
if ( $current_blog )
wp_cache_set( 'current_blog_' . $domain, $current_blog, 'site-options' );
}
if ( $current_blog && $current_blog->site_id != $current_site->id ) {
$current_site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE id = %d", $current_blog->site_id ) );
if ( ! isset( $current_site->blog_id ) )
$current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) );
} else
$blogname = substr( $domain, 0, strpos( $domain, '.' ) );
} else {
$blogname = htmlspecialchars( substr( $_SERVER[ 'REQUEST_URI' ], strlen( $path ) ) );
if ( false !== strpos( $blogname, '/' ) )
$blogname = substr( $blogname, 0, strpos( $blogname, '/' ) );
if ( false !== strpos( $blogname, '?' ) )
$blogname = substr( $blogname, 0, strpos( $blogname, '?' ) );
$reserved_blognames = array( 'page', 'comments', 'blog', 'wp-admin', 'wp-includes', 'wp-content', 'files', 'feed' );
if ( $blogname != '' && ! in_array( $blogname, $reserved_blognames ) && ! is_file( $blogname ) )
$path .= $blogname . '/';
$current_blog = wp_cache_get( 'current_blog_' . $domain . $path, 'site-options' );
if ( ! $current_blog ) {
$current_blog = get_blog_details( array( 'domain' => $domain, 'path' => $path ), false );
if ( $current_blog )
wp_cache_set( 'current_blog_' . $domain . $path, $current_blog, 'site-options' );
}
unset($reserved_blognames);
}
if ( ! defined( 'WP_INSTALLING' ) && is_subdomain_install() && ! is_object( $current_blog ) ) {
if ( defined( 'NOBLOGREDIRECT' ) ) {
$destination = NOBLOGREDIRECT;
if ( '%siteurl%' == $destination )
$destination = "http://" . $current_site->domain . $current_site->path;
} else {
$destination = 'http://' . $current_site->domain . $current_site->path . 'wp-signup.php?new=' . str_replace( '.' . $current_site->domain, '', $domain );
}
header( 'Location: ' . $destination );
die();
}
if ( ! defined( 'WP_INSTALLING' ) ) {
if ( $current_site && ! $current_blog ) {
if ( $current_site->domain != $_SERVER[ 'HTTP_HOST' ] ) {
header( 'Location: http://' . $current_site->domain . $current_site->path );
exit;
}
$current_blog = get_blog_details( array( 'domain' => $current_site->domain, 'path' => $current_site->path ), false );
}
if ( ! $current_blog || ! $current_site )
ms_not_installed();
}
$blog_id = $current_blog->blog_id;
$public = $current_blog->public;
if ( empty( $current_blog->site_id ) )
$current_blog->site_id = 1;
$site_id = $current_blog->site_id;
$current_site = get_current_site_name( $current_site );
if ( ! $blog_id ) {
if ( defined( 'WP_INSTALLING' ) ) {
$current_blog->blog_id = $blog_id = 1;
} else {
wp_load_translations_early();
$msg = ! $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->site'" ) ? ' ' . __( 'Database tables are missing.' ) : '';
wp_die( __( 'No site by that name on this system.' ) . $msg );
}
}
}
$wpdb->set_prefix( $table_prefix, false ); // $table_prefix can be set in sunrise.php
$wpdb->set_blog_id( $current_blog->blog_id, $current_blog->site_id );
$table_prefix = $wpdb->get_blog_prefix();
// need to init cache again after blog_id is set
wp_start_object_cache();
// Define upload directory constants
ms_upload_constants(); | batruji/metareading | wp-includes/ms-settings.php | PHP | gpl-2.0 | 5,368 |
package com;
/***************************************************************************
* (c) Copyright 2003 NPTest, Inc. *
* This computer program includes Confidential, Proprietary Information *
* and is a trade secret of NPTest. All use, disclosure, and/or *
* reproduction is prohibited unless authorized in writing by an officer *
* of NPTest. All Rights Reserved. *
***************************************************************************/
/**
* @file BinResultConsumer.java
* Contains all classes related binning data (soft, hard) handling management.
*/
import java.util.Iterator;
import java.util.Vector;
import managers.CapAreaManager;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.CORBA.ORB;
import Sapphire.CAP.CapArea;
import Sapphire.CAP.CommonAccessPort;
import Sapphire.CAP.ResultManager;
import SapphireTsp.CoreTsp;
import SapphireTsp.TspRuntimeException;
/**
* @class BinResultConsumer
* This class also provide basic methods to get bin results.
* Acitivate anad deactivate methods are dedicated to the registration and
* unregistration to flow:device information of the result consumer.
* This class extends the CORBA POA server dedicated to result consumers.
*/
public class BinResultConsumer extends Sapphire.CAP.ResultConsumerPOA
{
/**
* @name Private Members
*/
//@{
/// Internal class storage of the received sites.
protected boolean _receivedSites[] = null;
/// Handle to the CORBA activated object
protected byte[] _id = null;
/// Internal class storage of the hard bin information
public String _hardBinId[] = null;
/// Internal class storage of the soft bin information
public String _softBinId[] = null;
/// Internal class storage of the hard bin name information
public String _hardBinName[] = null;
/// Internal class storage of the soft bin name information
public String _softBinName[] = null;
public String _softBinDesc[] = null;
public String _hardBinDesc[] = null;
/// Internal class storage of the unit id information
public String _unitId[] = null;
protected static Vector simSiteVector = new Vector();
/// Internal class storage of the PASS/FAIL result information
protected int _binResult[] = null;
// 14225 ResultHelper used to expand compactData into the normal ResultElement
ResultHelper _resultHelper = null;
protected boolean simulationMode;
protected int simulationSiteCnt;
protected boolean debugFlag = false;
String[] TSPAction={null,null};
ResultManager rmMgr = null;
POA portableObjectAdapter = null;
CapArea tpMgr = null;
//@}
//---------------------------------------------------------------------------
/**
* Initialize the result consumer.
* - Clean hard and soft bin storage
* - Executed Site Mask is stored.
* - Received Site Mask is cleared.
*
* @exception TspRuntimeException thrown when Runtime or Corba error
*/
//---------------------------------------------------------------------------
public BinResultConsumer(boolean simMode,int simSiteNum) throws TspRuntimeException
{
try {
// Allocate the binning arrays
int nSites;
simulationMode = simMode;
if (!simMode)
{
CapAreaManager capAreaManager = CapAreaManager.instance();
tpMgr = capAreaManager.testProgram();
CapArea loadedSiteMask = tpMgr.getObject("LoadedSiteMask");
nSites = loadedSiteMask.getL("Size");
loadedSiteMask.cleanUp();
}
else {
nSites = simSiteNum;
simulationSiteCnt = simSiteNum;
}
_hardBinId = new String[nSites];
_softBinId = new String[nSites];
_hardBinName = new String[nSites];
_softBinName = new String[nSites];
_softBinDesc= new String[nSites];
_hardBinDesc= new String[nSites];
_unitId = new String[nSites];
_binResult = new int[nSites];
_resultHelper = new ResultHelper();
// Store received Site boolean marker
_receivedSites = new boolean[nSites];
if (!simMode)
activate();
}
catch (Sapphire.lib.error.Fatal f) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(f.msg);
System.err.println(f.where);
System.err.println(f.getMessage());
f.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
}
/*
* Needs to be run prior to recieveing new data.
*/
public void clean() throws TspRuntimeException
{
try {
int nSites;
if (simulationMode) {
nSites = simulationSiteCnt;
}
else {
CapArea loadedSiteMask = tpMgr.getObject("LoadedSiteMask");
nSites = loadedSiteMask.getL("Size");
loadedSiteMask.cleanUp();
}
_hardBinId = new String[nSites];
_softBinId = new String[nSites];
_hardBinName = new String[nSites];
_softBinName = new String[nSites];
_softBinDesc= new String[nSites];
_hardBinDesc= new String[nSites];
_unitId = new String[nSites];
_binResult = new int[nSites];
_resultHelper = new ResultHelper();
// Store received Site boolean marker
_receivedSites = new boolean[nSites];
}
catch (Sapphire.lib.error.Fatal f) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(f.msg);
System.err.println(f.where);
System.err.println(f.getMessage());
f.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
}
//---------------------------------------------------------------------------
/**
* Activate (register) the result consumer.
*
* @exception TspRuntimeException thrown when Runtime or Corba error
*/
//---------------------------------------------------------------------------
public void activate() throws TspRuntimeException
{
try {
// Activate the Result Consumer
CapAreaManager capAreaManager = CapAreaManager.instance();
CommonAccessPort cap = (CommonAccessPort) capAreaManager.capInterface();;
ORB orb = org.omg.CORBA.ORB.init(new String[0], null);
org.omg.CORBA.Object obj = orb.resolve_initial_references("RootPOA");
// create POA <equivalent to narrow() but typecast is used here>
portableObjectAdapter = (POA) obj;
_id = portableObjectAdapter.activate_object(this);
org.omg.PortableServer.POAManager poaMgr = portableObjectAdapter.the_POAManager();
poaMgr.activate();
// Subscribe Result Consumer to flow.Device information
rmMgr = cap.getResultManager();
//*NL* get the handle of resultManager from runtime instance
// *NL* pass the servant_locator of servant BinResultConsumer
rmMgr.subscribe("FlowResult:NODE:DEVICE:flow.Device", _this(), "*", "*", true);
rmMgr.subscribe("TestResult:Test", _this(), "ReadFuncFuse", "*", true);
}
catch (AdapterInactive e)
{
System.err.println("POA is inactive. This is a CORBA communication related issue.");
throw new TspRuntimeException("Internal DataPackage Setup Error.");
}
catch (org.omg.PortableServer.POAPackage.ServantAlreadyActive e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (org.omg.PortableServer.POAPackage.WrongPolicy e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Fatal e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (InvalidName e){
CoreTsp.out("A CORBA exception occurred induced by the TSP.");
throw new TspRuntimeException(e);
}
}
//---------------------------------------------------------------------------
/**
* Deactivate (unregister) the result consumer.
*
* @exception TspRuntimeException thrown when Runtime or Corba error
*/
//---------------------------------------------------------------------------
public void deactivate() throws TspRuntimeException
{
try {
//rMgr.unsubscribe("*:flow.Device", _this(), "*", "*"); //1415
rmMgr.unsubscribe("FlowResult:NODE:DEVICE:flow.Device", _this(), "*", "*");
rmMgr.unsubscribe("TestResult:Test", _this(), "ReadFuncFuse", "*");
// Deactivate the Result Consumer
portableObjectAdapter.deactivate_object(_id);
}
catch (org.omg.PortableServer.POAPackage.ObjectNotActive e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (org.omg.PortableServer.POAPackage.WrongPolicy e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Fatal e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
}
//---------------------------------------------------------------------------
/**
* Get the Hard Bin Id
*/
//---------------------------------------------------------------------------
public String[] hardBinId()
{
return _hardBinId;
}
//---------------------------------------------------------------------------
/**
* Get the Hard Bin Name
*/
//---------------------------------------------------------------------------
public String[] hardBinName()
{
return _hardBinName;
}
//---------------------------------------------------------------------------
/**
* Get the Hard BinDesc
*/
//---------------------------------------------------------------------------
public String[] hardBinDesc()
{
return _hardBinDesc;
}
//---------------------------------------------------------------------------
/**
* Get the Soft Bin Id
*/
//---------------------------------------------------------------------------
public String[] softBinId()
{
return _softBinId;
}
//---------------------------------------------------------------------------
/**
* Get the Soft Bin Name
*/
//---------------------------------------------------------------------------
public String[] softBinName()
{
return _softBinName;
}
//---------------------------------------------------------------------------
/**
* Get the Soft Bin Desc
*/
//---------------------------------------------------------------------------
public String[] softBinDesc()
{
return _softBinDesc;
}
//---------------------------------------------------------------------------
/**
* Get the Unit Id
*/
//---------------------------------------------------------------------------
public String[] unitId()
{
return _unitId;
}
//---------------------------------------------------------------------------
/**
* Get the PASS/FAIL result
*/
//---------------------------------------------------------------------------
public int[] binResult()
{
return _binResult;
}
public static void markSimulatedExecutedSite(int site)
{
if(simSiteVector != null)
{
simSiteVector.add(new Integer(site));
} else {
CoreTsp.out("Nothing Executed");
}
}
//---------------------------------------------------------------------------
/**
* Get the Done flag (true if all sites received)
*/
//---------------------------------------------------------------------------
public boolean isDone()
{
boolean areIdentical = true;
boolean executedSites[];
// Get executed Site array marker
if (simulationMode)
{
executedSites = new boolean[simulationSiteCnt];
for (int i = 0; i<simulationSiteCnt;i++)
executedSites[i] = false;
Iterator itr = simSiteVector.iterator();
while(itr.hasNext())
executedSites[((Integer)itr.next()).intValue()] = true;
}
else {
try {
Sapphire.CAP.CapArea loadedSiteMask = tpMgr.getObject("LoadedSiteMask");
int nSites = loadedSiteMask.getL("Size");
loadedSiteMask.cleanUp();
executedSites = new boolean[nSites];
Sapphire.CAP.CapArea siteMask = tpMgr.getObject("ExecutedSiteMask");
Sapphire.CAP.CapArea siteMaskItr = null;
siteMaskItr = siteMask.getArea("Iterator");
while (siteMaskItr.hasNext()) {
int site = siteMaskItr.getL("Next");
executedSites[site] = true;
}
siteMaskItr.cleanUp();
siteMask.cleanUp();
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
return false;
}
catch (Sapphire.lib.error.Fatal e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
return false;
}
}
// Compare executed sites and received sites
for (int i = 0; i < _receivedSites.length; i++) {
if (executedSites[i] != _receivedSites[i]) {
areIdentical = false;
}
}
return areIdentical;
}
//---------------------------------------------------------------------------
/**
* Implement the handleResult() to be called by updateResult()
*/
//---------------------------------------------------------------------------
public void handleResult(Sapphire.CAP.ResultData resultData)
{
for (int idx = 0; idx < resultData.site.length; ++idx) {
int iSite = resultData.site[idx];
if (resultData.element.elements == null) {
continue;
}
Sapphire.CAP.ResultElement elmts[] = resultData.element.elements;
for (int i = 0; i < elmts.length; i++) {
Sapphire.CAP.ResultElement elmt = elmts[i];
// Hard Bin Id stored into 'HardBinId' tag
if (elmt.name.equals("HardBinId"))
_hardBinId[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("HardBinName"))
_hardBinName[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("SoftBinId"))
_softBinId[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("SoftBinName"))
_softBinName[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("SoftBinDesc"))
_softBinDesc[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("HardBinDesc"))
_hardBinDesc[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("DeviceDescription"))
_unitId[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("TestDecision"))
if (elmt.value.extract_string().equals("Pass"))
_binResult[iSite] = 1;
else
_binResult[iSite] = 0;
}
// Mark the received site
_receivedSites[iSite] = true;
}
}
/* //added function to get unit ID using PUSH method
public void retrieveUnitId (Sapphire.CAP.ResultData resultData){
//System.out.print("resultData object" + resultData);
//CoreTsp.out("resultData object" + resultData);
if(_IsSerialNumberObject(resultData) == true){
for (int idx = 0; idx < resultData.site.length; ++idx){
if (resultData.element.elements == null){
continue;
}
int iSite = resultData.site[idx];
if(_receivedSites[iSite] == false){
Sapphire.CAP.ResultElement elmts[] = resultData.element.elements;
for (int i = 0; i < elmts.length; i++){
Sapphire.CAP.ResultElement elmt = elmts[i];
String FieldName = elmt.name;
if(_isSerialNumberField(FieldName) == true){
//added to retrieve unit id
//System.out.println("Element Val" + elmt.value.extract_string());
//CoreTsp.out("Element Val" + elmt.value.extract_string());
_unitId[iSite] = elmt.value.extract_string();
//Mark the received site
_receivedSites[iSite] = true;
break;
}
}
}
}
}
}
*/
private boolean _IsSerialNumberObject(Sapphire.CAP.ResultData resultData){
if (resultData.element != null){
String Name = resultData.element.name;
if(Name.equals("FuseRecord"))
return true;
else if(Name.equals("JTAG_FUNCFUSE"))
return true;
else if(Name.equals("JTAG_FUNCFUSE_SH_F"))
return true;
else if(Name.equals("JTAG_FUNCFUSE_SH_E"))
return true;
else if(Name.equals("JTAG_FUNCFUSE_JH_E"))
return true;
}
return false;
}
public boolean _isSerialNumberField (String FieldName){
String [] SerialNumberFieldNames = {
"FuseBitValues",
"DieFuseBitValues",
"SerialNum",
"FuseBits",
"funcfuse",
"redundfuse",
"RedundFuse",
"RedundFuseCore1",
"RedundFuseCore1_ProgFuseBits",
"ReadRedundFuseCore0",
"ProgramRRDFuseCore0",
"RedundFuse_VerifyBits",
"RedundFuseCore1_VerifyBits",
"FuncFuse",
"FuncFuse_VerifyBits",
"funcfuse_VerifyBits",
"fusereg_ProgFuseBits",
"funcfuse_ProgFuseBits",
"redundfuse_ProgFuseBits",
"RMW_ProgFuseBits",
"RMW_VerifyBits"
};
boolean RetValue = false;
for (int idx = 0; idx < SerialNumberFieldNames.length; ++idx){
if(SerialNumberFieldNames[idx].equals(FieldName)){
RetValue = true;
break;
}
}
return RetValue;
}
/* Implement the pure virtual updateResult() call back method
*/
//---------------------------------------------------------------------------
public void updateResult(Sapphire.CAP.ResultData result)
{
// Extract element: Only interested in POP_ELEMENT
// Skip PUSH ELEMENT
// Skip POP_TO_ELEMENT
// Skip ADD_ELEMENT
if (result.elementContext == Sapphire.CAP.ResultContext.POP_ELEMENT
||
result.elementContext == Sapphire.CAP.ResultContext.POP_TO_ELEMENT
) {
if (result.compactData != null && result.compactData.length() > 0) {
Sapphire.CAP.ResultData resultData = new Sapphire.CAP.ResultData();
resultData.type = result.type;
resultData.elementContext = result.elementContext;
resultData.flowContext = result.flowContext;
resultData.site = result.site;
resultData.element = new Sapphire.CAP.ResultElement();
try {
_resultHelper.reset();
while (_resultHelper.expandElement(result.compactData,resultData.element)) {
handleResult(resultData);
}
} catch (TspRuntimeException e) {
CoreTsp.out("BinResultConsumer::" + e.getMessage());
e.printStackTrace();
}
} else {
handleResult(result);
}
}
/* //added to retrive Unit Id
if (result.elementContext == Sapphire.CAP.ResultContext.ADD_ELEMENT){
if (result.compactData != null && result.compactData.length() > 0) {
Sapphire.CAP.ResultData resultData = new Sapphire.CAP.ResultData();
resultData.type = result.type;
resultData.elementContext = result.elementContext;
resultData.flowContext = result.flowContext;
resultData.site = result.site;
resultData.element = new Sapphire.CAP.ResultElement();
try {
_resultHelper.reset();
while (_resultHelper.expandElement(result.compactData,resultData.element)) {
retrieveUnitId(resultData);
}
} catch (TspRuntimeException e) {
CoreTsp.out("BinResultConsumer::" + e.getMessage());
e.printStackTrace();
}
} else{
retrieveUnitId(result);
}
}*/
}
//---------------------------------------------------------------------------
/**
* Implement the pure virtual quit() call back method
*/
//---------------------------------------------------------------------------
public void quit (boolean shutdown)
{
}
/**
* Emulates the functionality of the loadsitemask, which we cannot use
* in simulation mode. Therefore, this method should only be called
* while in simulation mode.
*/
public static void setSiteExecuted(int site){
simSiteVector.add(new Integer(site));
}
} | guanghaofan/MyTSP | 2.1.1.2/CPGTSP/src/com/BinResultConsumer.java | Java | gpl-2.0 | 22,629 |
/*
* excel2xoonips - A data convertor from Excel data to XooNIps import file
*
* Copyright (C) 2007 RIKEN Japan, All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include "libsl4.h"
#include "cexcel.h"
#include "excel2xoonips.h"
static inifile_t *_inifile_new( const char *inifile_path );
static inifile_column_t *_inifile_column_new( sl4_string_t *fields,
sl4_string_t *type,
sl4_string_t *optional,
const char *file, int line,
sl4_string_t *errmes );
static int _inifile_column_delete( inifile_column_t * col );
inifile_t *inifile_load( const char *inidir, const char *itemtype,
sl4_string_t *errmes )
{
int line;
sl4_string_t *inifile_path;
sl4_file_t *inifile;
strarray_t *matches;
inifile_t *ini;
char buf[INIFILE_MAX_LINE];
inifile_path = sl4_string_new( inidir );
if ( inifile_path == NULL ) {
ERROR_OUTMEM( );
}
if ( sl4_string_append( inifile_path, "/" ) != 0 ) {
ERROR_OUTMEM( );
}
if ( sl4_string_append( inifile_path, itemtype ) != 0 ) {
ERROR_OUTMEM( );
}
if ( sl4_string_append( inifile_path, ".ini" ) != 0 ) {
ERROR_OUTMEM( );
}
inifile = sl4_file_new( sl4_string_get( inifile_path ) );
if ( sl4_file_open( inifile, "r" ) != 0 ) {
/* failed to open file */
sl4_string_sprintf( errmes,
"Failed to Open INI File for XooNIps Item Type %s.",
itemtype );
return NULL;
}
line = 0;
ini = _inifile_new( sl4_string_get( inifile_path ) );
matches = strarray_new( );
if ( matches == NULL ) {
ERROR_OUTMEM( );
}
while ( !sl4_file_eof( inifile ) ) {
line++;
if ( sl4_file_gets( inifile, buf, INIFILE_MAX_LINE ) == 0 ) {
sl4_string_t *tmp;
tmp = sl4_string_new( buf );
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
sl4_string_trim( tmp );
if ( myonig_match( "/^[#;].*$/", sl4_string_get( tmp ), NULL ) ) {
/* comment line */
sl4_string_delete( tmp );
continue;
}
if ( myonig_match
( "/^\\s*([^=]+)\\s*=\\s*([^:]+)\\s*:\\s*([^#]+)(#.*)?\\s*$/",
sl4_string_get( tmp ), matches ) ) {
sl4_string_t *m[5];
m[0] = strarray_get( matches, 0 ); /* all */
m[1] = strarray_get( matches, 1 ); /* fields */
m[2] = strarray_get( matches, 2 ); /* type */
m[3] = strarray_get( matches, 3 ); /* optional */
m[4] = strarray_get( matches, 4 ); /* comment */
ini->col[ini->ncol] =
_inifile_column_new( m[1], m[2], m[3],
sl4_string_get( inifile_path ), line, errmes );
if ( ini->col[ini->ncol] == NULL ) {
sl4_string_delete( tmp );
sl4_file_close( inifile );
strarray_delete( matches );
sl4_string_delete( inifile_path );
inifile_delete( ini );
return NULL;
}
ini->ncol++;
} else {
/* invalid format */
sl4_string_delete( tmp );
sl4_file_close( inifile );
strarray_delete( matches );
sl4_string_delete( inifile_path );
inifile_delete( ini );
sl4_string_sprintf( errmes,
"Invalid format line found in item type %s line %d.",
itemtype, line );
return NULL;
}
strarray_clear( matches );
sl4_string_delete( tmp );
}
}
sl4_file_close( inifile );
strarray_delete( matches );
sl4_string_delete( inifile_path );
return ini;
}
int inifile_delete( inifile_t * ini )
{
int i;
sl4_string_delete( ini->inifile_path );
for ( i = 0; i < ini->ncol; i++ ) {
_inifile_column_delete( ini->col[i] );
}
free( ini );
return 0;
}
static inifile_t *_inifile_new( const char *inifile_path )
{
inifile_t *ini;
ini = ( inifile_t * ) malloc( sizeof( inifile_t ) );
if ( ini == NULL ) {
ERROR_OUTMEM( );
}
ini->inifile_path = sl4_string_new( inifile_path );
if ( ini->inifile_path == NULL ) {
ERROR_OUTMEM( );
}
ini->ncol = 0;
return ini;
}
static inifile_column_t *_inifile_column_new( sl4_string_t *fields,
sl4_string_t *type,
sl4_string_t *optional,
const char *itemtype,
int line, sl4_string_t *errmes )
{
inifile_column_t *col;
sl4_string_t *tmp;
size_t pos;
/* trim arguments */
sl4_string_trim( fields );
sl4_string_trim( type );
sl4_string_trim( optional );
/* allocate memory */
col = ( inifile_column_t * ) malloc( sizeof( inifile_column_t ) );
if ( col == NULL ) {
ERROR_OUTMEM( );
}
col->field = strarray_new( );
if ( col->field == NULL ) {
ERROR_OUTMEM( );
}
col->type = INIFILE_TYPE_UNDEF;
col->options = NULL;
/* fields */
pos = 0;
tmp = sl4_string_tokenize( fields, ",", &pos );
if ( tmp == NULL ) {
ERROR_UNEXPECTED( );
}
while ( tmp ) {
sl4_string_trim( tmp );
if ( sl4_string_empty( tmp ) ) {
sl4_string_delete( tmp );
_inifile_column_delete( col );
sl4_string_sprintf( errmes, "Empty field found in %s.ini line %d.",
itemtype, line );
return NULL;
}
strarray_add( col->field, tmp );
tmp = sl4_string_tokenize( fields, ",", &pos );
}
/* type */
if ( sl4_string_compare( type, "string" ) == 0 ) {
col->type = INIFILE_TYPE_STRING;
} else if ( sl4_string_compare( type, "int" ) == 0 ) {
col->type = INIFILE_TYPE_STRING;
} else if ( sl4_string_compare( type, "datetime" ) == 0 ) {
col->type = INIFILE_TYPE_DATETIME;
} else if ( sl4_string_compare( type, "indexes" ) == 0 ) {
col->type = INIFILE_TYPE_INDEXES;
} else if ( sl4_string_compare( type, "lang" ) == 0 ) {
int i;
const char *lang[] = {
"eng", "jpn", "fra", "deu", "esl", "ita", "dut",
"sve", "nor", "dan", "fin", "por", "chi", "kor",
NULL
};
col->type = INIFILE_TYPE_SELECT;
col->options = strarray_new( );
if ( col->options == NULL ) {
ERROR_OUTMEM( );
}
for ( i = 0; lang[i] != NULL; i++ ) {
tmp = sl4_string_new( lang[i] );
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
strarray_add( col->options, tmp );
}
} else if ( sl4_string_compare( type, "bool" ) == 0 ) {
col->type = INIFILE_TYPE_BOOL;
} else if ( sl4_string_compare( type, "rights" ) == 0 ) {
col->type = INIFILE_TYPE_RIGHTS;
} else {
strarray_t *matches = strarray_new( );
if ( myonig_match
( "/select\\(\\s*(.+)\\s*\\)/", sl4_string_get( type ), matches ) ) {
sl4_string_t *m = strarray_get( matches, 1 );
if ( m == NULL ) {
ERROR_UNEXPECTED( );
}
sl4_string_trim( m );
col->type = INIFILE_TYPE_SELECT;
col->options = strarray_new( );
if ( col->options == NULL ) {
ERROR_OUTMEM( );
}
pos = 0;
tmp = sl4_string_tokenize( m, ",", &pos );
while ( tmp ) {
sl4_string_trim( tmp );
strarray_add( col->options, tmp );
tmp = sl4_string_tokenize( m, ",", &pos );
}
} else
if ( myonig_match
( "/array\\(\\s*([^,]+)\\s*(,\\s*'(.+)')?\\s*\\)/",
sl4_string_get( type ), matches ) ) {
sl4_string_t *tag, *sep;
tag = strarray_get( matches, 1 );
if ( tag == NULL ) {
ERROR_UNEXPECTED( );
}
sep = strarray_get( matches, 3 );
col->type = INIFILE_TYPE_ARRAY;
col->options = strarray_new( );
if ( col->options == NULL ) {
ERROR_OUTMEM( );
}
sl4_string_trim( tag );
tmp = sl4_string_new( sl4_string_get( tag ) );
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
strarray_add( col->options, tmp );
if ( sep == NULL ) {
tmp = sl4_string_new( "\\n" );
} else {
tmp = sl4_string_new( sl4_string_get( sep ) );
}
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
sl4_string_convert_format( tmp );
strarray_add( col->options, tmp );
} else
if ( myonig_match
( "/dataset\\(\\s*([^,]+)\\s*(,\\s*'(.+)')?\\s*\\)/",
sl4_string_get( type ), matches ) ) {
sl4_string_t *tag, *sep;
tag = strarray_get( matches, 1 );
if ( tag == NULL ) {
ERROR_UNEXPECTED( );
}
sep = strarray_get( matches, 3 );
col->type = INIFILE_TYPE_DATASET;
col->options = strarray_new( );
if ( col->options == NULL ) {
ERROR_OUTMEM( );
}
sl4_string_trim( tag );
tmp = sl4_string_new( sl4_string_get( tag ) );
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
strarray_add( col->options, tmp );
if ( sep == NULL ) {
tmp = sl4_string_new( "\\n" );
} else {
tmp = sl4_string_new( sl4_string_get( sep ) );
}
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
sl4_string_convert_format( tmp );
strarray_add( col->options, tmp );
} else
if ( myonig_match
( "/file\\(\\s*(.+)\\s*\\)/", sl4_string_get( type ), matches ) ) {
sl4_string_t *m = strarray_get( matches, 1 );
if ( m == NULL ) {
ERROR_UNEXPECTED( );
}
sl4_string_trim( m );
col->type = INIFILE_TYPE_FILE;
col->options = strarray_new( );
if ( col->options == NULL ) {
ERROR_OUTMEM( );
}
tmp = sl4_string_new( sl4_string_get( m ) );
if ( tmp == NULL ) {
ERROR_OUTMEM( );
}
strarray_add( col->options, tmp );
} else {
strarray_delete( matches );
_inifile_column_delete( col );
sl4_string_sprintf( errmes,
"Invalid data type found in %s.ini line %d.",
itemtype, line );
return NULL;
}
strarray_delete( matches );
}
/* is_required */
sl4_string_trim( optional );
if ( sl4_string_compare( optional, "required" ) == 0 ) {
col->is_required = 1;
} else if ( sl4_string_compare( optional, "optional" ) == 0 ) {
col->is_required = 0;
} else {
_inifile_column_delete( col );
sl4_string_sprintf( errmes,
"Unknown requirement option found in %s.ini line %d.",
itemtype, line );
return NULL;
}
return col;
}
static int _inifile_column_delete( inifile_column_t * col )
{
strarray_delete( col->field );
if ( col->options != NULL ) {
strarray_delete( col->options );
}
free( col );
return 0;
}
| neuroinformatics/excel2xoonips | excel2xoonips/inifile.c | C | gpl-2.0 | 11,579 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('usermodule', '0002_auto_20151108_2019'),
]
operations = [
migrations.CreateModel(
name='Period',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=10)),
('start_date', models.DateField()),
('end_date', models.DateField()),
('professor', models.ForeignKey(to='usermodule.Professor')),
],
),
]
| Sezzh/tifis_platform | tifis_platform/groupmodule/migrations/0001_initial.py | Python | gpl-2.0 | 711 |
//******************************************************************************
//
// File Name : module.cpp
// Author : Skytrack ltd - Copyright (C) 2015
//
// This code is property of Skytrack company
//
//******************************************************************************
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <queue>
#include "module.h"
#include "thread.h"
#include "retranslator.h"
#include "../../core/spinlock.h"
#include "api.h"
static const MODULE_FAMILY family = MODULE_FAMILY_RETRANSLATOR;
static const char *name = "egts tatarstan";
static const unsigned int protocol_id = 2;
RETRANSLATOR *create_retranslator(const char *device_id, const char *host, unsigned short port, const char *login, const char *password)
{
RETRANSLATOR *pRetranslator = new RETRANSLATOR;
pRetranslator->device_id = device_id;
pRetranslator->host = host;
pRetranslator->port = port;
pRetranslator->login = login;
pRetranslator->password = password;
pRetranslator->oid = strtoul(device_id, NULL, 10);
spinlock_init(&pRetranslator->spinlock);
api_log_printf("[EGTS-TATARSTAN] Create retranslator for '%s'\r\n", device_id);
retranslators_add_item(pRetranslator);
return pRetranslator;
}
void destroy_retranslator(RETRANSLATOR *pRetranslator)
{
api_log_printf("[EGTS-TATARSTAN] Destroy retranslator for '%s' with socket #%d\r\n", pRetranslator->device_id.c_str(), pRetranslator->sock);
retranslators_remove_item(pRetranslator);
delete pRetranslator;
}
void add_record_to_retranslator(RETRANSLATOR *pRetranslator, RETRANSLATOR_RECORD *pRecord)
{
spinlock_lock(&pRetranslator->spinlock);
pRetranslator->records_queue.push(*pRecord);
spinlock_unlock(&pRetranslator->spinlock);
}
int get_var(int var_type, void **p)
{
switch (var_type) {
case MODULE_VAR_FAMILY:
*p = (void *)family;
break;
case MODULE_VAR_NAME:
*p = (void *)name;
break;
case MODULE_VAR_PROTOCOL_ID:
*p = (void *)&protocol_id;
break;
case MODULE_VAR_FUNC_CREATE_RETRANSLATOR:
*p = (void *)create_retranslator;
break;
case MODULE_VAR_FUNC_DESTROY_RETRANSLATOR:
*p = (void *)destroy_retranslator;
break;
case MODULE_VAR_FUNC_ADD_RECORD_TO_RETRANSLATOR:
*p = (void *)add_record_to_retranslator;
break;
default:
*p = NULL;
return -1;
}
return 0;
}
int set_var(int var_type, void *p)
{
CONFIG_OPTION *op = (CONFIG_OPTION *)p;
switch(var_type) {
case MODULE_VAR_FUNC_LOG:
api_log_printf = (LOG_PRINTF)p;
break;
}
return 0;
}
int start()
{
retranslators_init();
thread_start();
api_log_printf("[EGTS-TATARSTAN] Started\r\n");
return 0;
}
int stop()
{
thread_stop();
retranslators_destroy();
api_log_printf("[EGTS-TATARSTAN] Stopped\r\n");
return 0;
}
// End
| skytrack/tps5 | src/retranslators/egts-tatarstan/module.cpp | C++ | gpl-2.0 | 2,938 |
/*
* Copyright (C) 2005-2016 by Rafael Santiago
*
* This is a free software. You can redistribute it and/or modify under
* the terms of the GNU General Public License version 2.
*
*/
#include <dsl/compiler/verifiers/vibrato.h>
#include <dsl/compiler/verifiers/sepexpander.h>
#include <dsl/compiler/compiler.h>
#include <dsl/utils.h>
int vibrato_sep_verifier(const char *buf, char *error_message, tulip_single_note_ctx **song, const char **next) {
if (buf == NULL || song == NULL || next == NULL) {
return 0;
}
if (get_cmd_code_from_cmd_tag(buf) != kTlpVibrato) {
tlperr_s(error_message, "The vibrato separator was expected.");
return 0;
}
add_sep_to_tulip_single_note_ctx(kTlpVibrato, song);
(*next) = buf + 1;
return 1;
}
| rafael-santiago/tulip | src/dsl/compiler/verifiers/vibrato.c | C | gpl-2.0 | 812 |
/**
* \brief Linux emulation code
* \author Josef Soentgen
* \date 2014-07-28
*/
/*
* Copyright (C) 2014 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
/* Genode */
#include <base/printf.h>
#include <util/string.h>
/**************
** stdlib.h **
**************/
static char getenv_NLDBG[] = "1";
static char getenv_HZ[] = "100";
static char getenv_TICKS_PER_USEC[] = "10000";
extern "C" char *getenv(const char *name)
{
if (Genode::strcmp(name, "NLDBG") == 0) return getenv_NLDBG;
if (Genode::strcmp(name, "HZ") == 0) return getenv_HZ;
if (Genode::strcmp(name, "TICKS_PER_USEC") == 0) return getenv_TICKS_PER_USEC;
return nullptr;
}
#if 0
#include <base/env.h>
#include <base/printf.h>
#include <base/snprintf.h>
#include <dataspace/client.h>
#include <timer_session/connection.h>
#include <rom_session/connection.h>
#include <util/string.h>
#include <lx_emul.h>
extern "C" {
/*************
** errno.h **
*************/
int errno;
/*************
** stdio.h **
*************/
FILE *stdout;
FILE *stderr;
void *malloc(size_t size)
{
/* align on pointer size */
size = size + ((sizeof(Genode::addr_t)-1) & ~(sizeof(Genode::addr_t)-1));
size_t rsize = size + sizeof (Genode::addr_t);
void *addr = 0;
if (!Genode::env()->heap()->alloc(size, &addr))
return 0;
*(Genode::addr_t*)addr = rsize;
return ((Genode::addr_t*)addr) + 1;
}
void *calloc(size_t nmemb, size_t size)
{
#define MUL_NO_OVERFLOW (1UL << (sizeof(size_t) * 4))
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
nmemb > 0 && SIZE_MAX / nmemb < size) {
return NULL;
}
size *= nmemb;
void *addr = malloc(size);
Genode::memset(addr, 0, size);
return addr;
}
void free(void *ptr)
{
if (!ptr)
return;
Genode::addr_t *addr = ((Genode::addr_t*)ptr) - 1;
Genode::env()->heap()->free(addr, *addr);
}
void *realloc(void *ptr, Genode::size_t size)
{
if (!size)
free(ptr);
void *n = malloc(size);
size_t s = *((size_t *)ptr - 1);
Genode::memcpy(n, ptr, Genode::min(s, size));
free(ptr);
return n;
}
/**************
** stdlib.h **
**************/
static char getenv_HZ[] = "100";
static char getenv_TICKS_PER_USEC[] = "10000";
char *getenv(const char *name)
{
/* these values must match the ones of lx_emul wifi */
if (Genode::strcmp(name, "HZ") == 0) return getenv_HZ;
if (Genode::strcmp(name, "TICKS_PER_USEC") == 0) return getenv_TICKS_PER_USEC;
return nullptr;
}
long int strtol(const char *nptr, char **endptr, int base)
{
long res = 0;
if (base != 0 && base != 10) {
PERR("strtol: base of %d is not supported", base);
return 0;
}
Genode::ascii_to(nptr, res);
return res;
}
double strtod(const char *nptr, char **endptr)
{
double res = 0;
Genode::ascii_to(nptr, res);
return res;
}
/********************
** linux/string.h **
********************/
size_t strcspn(const char *s, const char *reject)
{
for (char const *p = s; *p; p++) {
char c = *p;
for (char const *r = reject; *r; r++) {
char d = *r;
if (c == d)
return (p - 1 - s);
}
}
return 0;
}
char *strdup(const char *s)
{
size_t len = strlen(s);
char *p = (char *) malloc(len + 1);
return strncpy(p, s, len + 1);
}
size_t strlen(const char *s)
{
return Genode::strlen(s);
}
int strcasecmp(const char* s1, const char *s2)
{
return Genode::strcmp(s1, s2);
}
int strcmp(const char* s1, const char *s2)
{
return Genode::strcmp(s1, s2);
}
int strncmp(const char *s1, const char *s2, size_t len)
{
return Genode::strcmp(s1, s2, len);
}
char *strchr(const char *p, int ch)
{
char c;
c = ch;
for (;; ++p) {
if (*p == c)
return ((char *)p);
if (*p == '\0')
break;
}
return 0;
}
void *memchr(const void *s, int c, size_t n)
{
const unsigned char *p = reinterpret_cast<const unsigned char*>(s);
while (n-- != 0) {
if ((unsigned char)c == *p++) {
return (void *)(p - 1);
}
}
return NULL;
}
char *strnchr(const char *p, size_t count, int ch)
{
char c;
c = ch;
for (; count; ++p, count--) {
if (*p == c)
return ((char *)p);
if (*p == '\0')
break;
}
return 0;
}
char *strncat(char *dst, const char *src, size_t n)
{
char *p = dst;
while (*p++) ;
while ((*p = *src) && (n-- > 0)) {
++src;
++p;
}
return dst;
}
char *strcpy(char *dst, const char *src)
{
char *p = dst;
while ((*dst = *src)) {
++src;
++dst;
}
return p;
}
char *strncpy(char *dst, const char* src, size_t n)
{
return Genode::strncpy(dst, src, n);
}
int snprintf(char *str, size_t size, const char *format, ...)
{
va_list list;
va_start(list, format);
Genode::String_console sc(str, size);
sc.vprintf(format, list);
va_end(list);
return sc.len();
}
int vsnprintf(char *str, size_t size, const char *format, va_list args)
{
Genode::String_console sc(str, size);
sc.vprintf(format, args);
return sc.len();
}
int asprintf(char **strp, const char *fmt, ...)
{
/* XXX for now, let's hope strings are not getting longer than 256 bytes */
enum { MAX_STRING_LENGTH = 256 };
char *p = (char*)malloc(MAX_STRING_LENGTH);
if (!p)
return -1;
va_list args;
va_start(args, fmt);
Genode::String_console sc(p, MAX_STRING_LENGTH);
sc.vprintf(fmt, args);
va_end(args);
return strlen(p);;
}
/**************
** unistd.h **
**************/
int getpagesize(void) {
return 4096; }
pid_t getpid(void) {
return 42; }
/************
** time.h **
************/
extern unsigned long jiffies;
time_t time(time_t *t)
{
return jiffies;
}
} /* extern "C" */
#endif
| dieface/genode | repos/dde_linux/src/lib/libnl/lxcc_emul.cc | C++ | gpl-2.0 | 5,659 |
// **********************************************************************
//
// Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#ifndef TEST_I_H
#define TEST_I_H
#include <Test.h>
class ThrowerI : public Test::Thrower
{
public:
ThrowerI();
virtual void shutdown(const Ice::Current&);
virtual bool supportsUndeclaredExceptions(const Ice::Current&);
virtual bool supportsAssertException(const Ice::Current&);
virtual void throwAasA(Ice::Int, const Ice::Current&);
virtual void throwAorDasAorD(Ice::Int, const Ice::Current&);
virtual void throwBasA(Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwCasA(Ice::Int, Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwBasB(Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwCasB(Ice::Int, Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwCasC(Ice::Int, Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwModA(Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwUndeclaredA(Ice::Int, const Ice::Current&);
virtual void throwUndeclaredB(Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwUndeclaredC(Ice::Int, Ice::Int, Ice::Int, const Ice::Current&);
virtual void throwLocalException(const Ice::Current&);
virtual void throwNonIceException(const Ice::Current&);
virtual void throwAssertException(const Ice::Current&);
virtual void throwAfterResponse(const Ice::Current&);
virtual void throwAfterException(const Ice::Current&);
};
#endif
| joshmoore/zeroc-ice | cpp/test/Ice/exceptions/TestI.h | C | gpl-2.0 | 1,751 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Migration_Alter_todo extends Migration{
public function up(){
$this->dbforge->add_column('todo', array(
'status' => array(
'type' => 'VARCHAR',
'constraint' => 255,
'default' => NULL
)
));
}
public function down(){
$this->dbforge->drop_column('todo', 'status');
}
} | brkrishna/freelance | dms/application/modules/todo/migrations/003_Alter_todo.php | PHP | gpl-2.0 | 504 |
#
# calculator.py : A calculator module for the deskbar applet.
#
# Copyright (C) 2008 by Johannes Buchner
# Copyright (C) 2007 by Michael Hofmann
# Copyright (C) 2006 by Callum McKenzie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors:
# Callum McKenzie <callum@spooky-possum.org> - Original author
# Michael Hofmann <mh21@piware.de> - compatibility changes for deskbar 2.20
# Johannes Buchner <buchner.johannes@gmx.at> - Made externally usable
#
# This version of calculator can be used with converter
# read how at http://twoday.tuwien.ac.at/jo/search?q=calculator+converter+deskbar
#
from __future__ import division
from deskbar.handlers.actions.CopyToClipboardAction import CopyToClipboardAction
from deskbar.defs import VERSION
from gettext import gettext as _
import deskbar.core.Utils
import deskbar.interfaces.Match
import deskbar.interfaces.Module
import logging
import math
import re
LOGGER = logging.getLogger(__name__)
HANDLERS = ["CalculatorModule"]
def bin (n):
"""A local binary equivalent of the hex and oct builtins."""
if (n == 0):
return "0b0"
s = ""
if (n < 0):
while n != -1:
s = str (n & 1) + s
n >>= 1
return "0b" + "...111" + s
else:
while n != 0:
s = str (n & 1) + s
n >>= 1
return "0b" + s
# These next three make sure {hex, oct, bin} can handle floating point,
# by rounding. This makes sure things like hex(255/2) behave as a
# programmer would expect while allowing 255/2 to equal 127.5 for normal
# people. Abstracting out the body of these into a single function which
# takes hex, oct or bin as an argument seems to run into problems with
# those functions not being defined correctly in the resticted eval (?).
def lenient_hex (c):
try:
return hex (c)
except TypeError:
return hex (int (c))
def lenient_oct (c):
try:
return oct (c)
except TypeError:
return oct (int (c))
def lenient_bin (c):
try:
return bin (c)
except TypeError:
return bin (int (c))
class CalculatorAction (CopyToClipboardAction):
def __init__ (self, text, answer):
CopyToClipboardAction.__init__ (self, answer, answer)
self.text = text
def get_verb(self):
return _("Copy <b>%(origtext)s = %(name)s</b> to clipboard")
def get_name(self, text = None):
"""Because the text variable for history entries contains the text
typed for the history search (and not the text of the orginal action),
we store the original text seperately."""
result = CopyToClipboardAction.get_name (self, text)
result["origtext"] = self.text
return result
def get_tooltip(self, text=None):
return self._name
class CalculatorMatch (deskbar.interfaces.Match):
def __init__ (self, text, answer, **kwargs):
deskbar.interfaces.Match.__init__ (self, name = text,
icon = "gtk-add", category = "calculator", **kwargs)
self.answer = str (answer)
self.add_action (CalculatorAction (text, self.answer))
def get_hash (self):
return self.answer
class CalculatorModule (deskbar.interfaces.Module):
INFOS = {"icon": deskbar.core.Utils.load_icon ("gtk-add"),
"name": _("Calculator"),
"description": _("Calculate simple equations"),
"version" : VERSION,
"categories" : { "calculator" : { "name" : _("Calculator") }}}
def __init__ (self):
deskbar.interfaces.Module.__init__ (self)
self.hexre = re.compile ("0[Xx][0-9a-fA-F_]*[0-9a-fA-F]")
self.binre = re.compile ("0[bB][01_]*[01]")
def _number_parser (self, match, base):
"""A generic number parser, regardless of base. It also ignores the
'_' character so it can be used as a separator. Note how we skip
the first two characters since we assume it is something like '0x'
or '0b' and identifies the base."""
table = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4,
'5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9,
'a' : 10, 'b' : 11, 'c' : 12, 'd' : 13,
'e' : 14, 'f' : 15 }
d = 0
for c in match.group()[2:]:
if c != "_":
d = d * base + table[c]
return str (d)
def _binsub (self, match):
"""Because python doesn't handle binary literals, we parse it
ourselves and replace it with a decimal representation."""
return self._number_parser (match, 2)
def _hexsub (self, match):
"""Parse the hex literal ourselves. We could let python do it, but
since we have a generic parser we use that instead."""
return self._number_parser (match, 16)
def run_query (self, query):
"""We evaluate the equation by first replacing hex and binary literals
with their decimal representation. (We need to check hex, so we can
distinguish 0x10b1 as a hex number, not 0x1 followed by 0b1.) We
severely restrict the eval environment. Any errors are ignored."""
restricted_dictionary = { "__builtins__" : None, "abs" : abs,
"acos" : math.acos, "asin" : math.asin,
"atan" : math.atan, "atan2" : math.atan2,
"bin" : lenient_bin,"ceil" : math.ceil,
"cos" : math.cos, "cosh" : math.cosh,
"degrees" : math.degrees,
"exp" : math.exp, "floor" : math.floor,
"hex" : lenient_hex, "int" : int,
"log" : math.log, "pow" : math.pow,
"log10" : math.log10, "oct" : lenient_oct,
"pi" : math.pi, "radians" : math.radians,
"round": round, "sin" : math.sin,
"sinh" : math.sinh, "sqrt" : math.sqrt,
"tan" : math.tan, "tanh" : math.tanh}
try:
scrubbedquery = query.lower()
scrubbedquery = self.hexre.sub (self._hexsub, scrubbedquery)
scrubbedquery = self.binre.sub (self._binsub, scrubbedquery)
for (c1, c2) in (("[", "("), ("{", "("), ("]", ")"), ("}", ")")):
scrubbedquery = scrubbedquery.replace (c1, c2)
answer = eval (scrubbedquery, restricted_dictionary)
# Try and avoid echoing back simple numbers. Note that this
# doesn't work well for floating point, e.g. '3.' behaves badly.
if str (answer) == query:
return None
# We need this check because the eval can return function objects
# when we are halfway through typing the expression.
if isinstance (answer, (float, int, long, str)):
return answer
else:
return None
except Exception, e:
LOGGER.debug (str(e))
return None
def query (self, query):
answer = self.run_query(query)
if answer != None:
result = [CalculatorMatch (query, answer)]
self._emit_query_ready (query, result)
return answer
else:
return []
| benpicco/mate-deskbar-applet | deskbar/handlers/calculator.py | Python | gpl-2.0 | 8,080 |
/**
* Copyright (c) 2006-2014 LxDE Developers, see the file AUTHORS for details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <glib/gi18n.h>
#include <stdlib.h>
#include <glib/gstdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <locale.h>
#include <string.h>
#include <gdk/gdkx.h>
#include <libfm/fm-gtk.h>
#define __LXPANEL_INTERNALS__
#include "private.h"
#include "misc.h"
#include "lxpanelctl.h"
#include "dbg.h"
static gchar *cfgfile = NULL;
static gchar version[] = VERSION;
static int config = 0;
static gboolean is_restarting = FALSE;
Command commands[] = {
//{ "configure", N_("Preferences"), configure },
{ "run", N_("Run"), gtk_run },
{ "restart", N_("Restart"), restart },
{ "logout", N_("Logout"), logout },
{ NULL, NULL },
};
void restart(void)
{
ENTER;
is_restarting = TRUE;
gtk_main_quit();
RET();
}
static void process_client_msg ( XClientMessageEvent* ev )
{
int cmd = ev->data.b[0];
switch( cmd )
{
#ifndef DISABLE_MENU
case LXPANEL_CMD_SYS_MENU:
{
GSList* l;
for( l = all_panels; l; l = l->next )
{
LXPanel* p = (LXPanel*)l->data;
GList *plugins, *pl;
if (p->priv->box == NULL)
continue;
plugins = gtk_container_get_children(GTK_CONTAINER(p->priv->box));
for (pl = plugins; pl; pl = pl->next)
{
const LXPanelPluginInit *init = PLUGIN_CLASS(pl->data);
if (init->show_system_menu)
/* queue to show system menu */
init->show_system_menu(pl->data);
}
g_list_free(plugins);
}
break;
}
#endif
case LXPANEL_CMD_RUN:
gtk_run();
break;
case LXPANEL_CMD_CONFIG:
{
LXPanel * p = ((all_panels != NULL) ? all_panels->data : NULL);
if (p != NULL)
panel_configure(p, 0);
}
break;
case LXPANEL_CMD_RESTART:
restart();
break;
case LXPANEL_CMD_EXIT:
gtk_main_quit();
break;
}
}
static GdkFilterReturn
panel_event_filter(GdkXEvent *xevent, GdkEvent *event, gpointer not_used)
{
Atom at;
Window win;
XEvent *ev = (XEvent *) xevent;
ENTER;
DBG("win = 0x%x\n", ev->xproperty.window);
if (ev->type != PropertyNotify )
{
/* private client message from lxpanelctl */
if( ev->type == ClientMessage && ev->xproperty.atom == a_LXPANEL_CMD )
{
process_client_msg( (XClientMessageEvent*)ev );
}
else if( ev->type == DestroyNotify )
{
fb_ev_emit_destroy( fbev, ((XDestroyWindowEvent*)ev)->window );
}
RET(GDK_FILTER_CONTINUE);
}
at = ev->xproperty.atom;
win = ev->xproperty.window;
if (win == GDK_ROOT_WINDOW())
{
if (at == a_NET_CLIENT_LIST)
{
fb_ev_emit(fbev, EV_CLIENT_LIST);
}
else if (at == a_NET_CURRENT_DESKTOP)
{
GSList* l;
for( l = all_panels; l; l = l->next )
((LXPanel*)l->data)->priv->curdesk = get_net_current_desktop();
fb_ev_emit(fbev, EV_CURRENT_DESKTOP);
}
else if (at == a_NET_NUMBER_OF_DESKTOPS)
{
GSList* l;
for( l = all_panels; l; l = l->next )
((LXPanel*)l->data)->priv->desknum = get_net_number_of_desktops();
fb_ev_emit(fbev, EV_NUMBER_OF_DESKTOPS);
}
else if (at == a_NET_DESKTOP_NAMES)
{
fb_ev_emit(fbev, EV_DESKTOP_NAMES);
}
else if (at == a_NET_ACTIVE_WINDOW)
{
fb_ev_emit(fbev, EV_ACTIVE_WINDOW );
}
else if (at == a_NET_CLIENT_LIST_STACKING)
{
fb_ev_emit(fbev, EV_CLIENT_LIST_STACKING);
}
else if (at == a_XROOTPMAP_ID)
{
GSList* l;
for( l = all_panels; l; l = l->next )
_panel_queue_update_background((LXPanel*)l->data);
}
else
return GDK_FILTER_CONTINUE;
return GDK_FILTER_REMOVE;
}
return GDK_FILTER_CONTINUE;
}
/* The same for new plugins type - they will be not unloaded by FmModule */
#define REGISTER_STATIC_MODULE(pc) do { \
extern LXPanelPluginInit lxpanel_static_plugin_##pc; \
lxpanel_register_plugin_type(#pc, &lxpanel_static_plugin_##pc); } while (0)
/* Initialize the static plugins. */
static void init_static_plugins(void)
{
#ifdef STATIC_SEPARATOR
REGISTER_STATIC_MODULE(separator);
#endif
#ifdef STATIC_LAUNCHTASKBAR
REGISTER_STATIC_MODULE(launchtaskbar);
#endif
#ifdef STATIC_DCLOCK
REGISTER_STATIC_MODULE(dclock);
#endif
#ifdef STATIC_WINCMD
REGISTER_STATIC_MODULE(wincmd);
#endif
#ifdef STATIC_DIRMENU
REGISTER_STATIC_MODULE(dirmenu);
#endif
#ifdef STATIC_PAGER
REGISTER_STATIC_MODULE(pager);
#endif
#ifdef STATIC_TRAY
REGISTER_STATIC_MODULE(tray);
#endif
#ifndef DISABLE_MENU
#ifdef STATIC_MENU
REGISTER_STATIC_MODULE(menu);
#endif
#endif
#ifdef STATIC_SPACE
REGISTER_STATIC_MODULE(space);
#endif
}
static void
usage()
{
g_print(_("lxpanel %s - lightweight GTK2+ panel for UNIX desktops\n"), version);
g_print(_("Command line options:\n"));
g_print(_(" --help -- print this help and exit\n"));
g_print(_(" --version -- print version and exit\n"));
// g_print(_(" --log <number> -- set log level 0-5. 0 - none 5 - chatty\n"));
// g_print(_(" --configure -- launch configuration utility\n"));
g_print(_(" --profile name -- use specified profile\n"));
g_print("\n");
g_print(_(" -h -- same as --help\n"));
g_print(_(" -p -- same as --profile\n"));
g_print(_(" -v -- same as --version\n"));
// g_print(_(" -C -- same as --configure\n"));
g_print(_("\nVisit http://lxde.org/ for detail.\n\n"));
}
/* Lightweight lock related functions - X clipboard hacks */
#define CLIPBOARD_NAME "LXPANEL_SELECTION"
/*
* clipboard_get_func - dummy get_func for gtk_clipboard_set_with_data ()
*/
static void
clipboard_get_func(
GtkClipboard *clipboard G_GNUC_UNUSED,
GtkSelectionData *selection_data G_GNUC_UNUSED,
guint info G_GNUC_UNUSED,
gpointer user_data_or_owner G_GNUC_UNUSED)
{
}
/*
* clipboard_clear_func - dummy clear_func for gtk_clipboard_set_with_data ()
*/
static void clipboard_clear_func(
GtkClipboard *clipboard G_GNUC_UNUSED,
gpointer user_data_or_owner G_GNUC_UNUSED)
{
}
/*
* Lightweight version for checking single instance.
* Try and get the CLIPBOARD_NAME clipboard instead of using file manipulation.
*
* Returns TRUE if successfully retrieved and FALSE otherwise.
*/
static gboolean check_main_lock()
{
static const GtkTargetEntry targets[] = { { CLIPBOARD_NAME, 0, 0 } };
gboolean retval = FALSE;
GtkClipboard *clipboard;
Atom atom;
Display *xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
atom = gdk_x11_get_xatom_by_name(CLIPBOARD_NAME);
XGrabServer(xdisplay);
if (XGetSelectionOwner(xdisplay, atom) != None)
goto out;
clipboard = gtk_clipboard_get(gdk_atom_intern(CLIPBOARD_NAME, FALSE));
if (gtk_clipboard_set_with_data(clipboard, targets,
G_N_ELEMENTS (targets),
clipboard_get_func,
clipboard_clear_func, NULL))
retval = TRUE;
out:
XUngrabServer (xdisplay);
gdk_flush ();
return retval;
}
#undef CLIPBOARD_NAME
static void _start_panels_from_dir(const char *panel_dir)
{
GDir* dir = g_dir_open( panel_dir, 0, NULL );
const gchar* name;
if( ! dir )
{
return;
}
while((name = g_dir_read_name(dir)) != NULL)
{
char* panel_config = g_build_filename( panel_dir, name, NULL );
if (strchr(panel_config, '~') == NULL) /* Skip editor backup files in case user has hand edited in this directory */
{
LXPanel* panel = panel_new( panel_config, name );
if( panel )
all_panels = g_slist_prepend( all_panels, panel );
}
g_free( panel_config );
}
g_dir_close( dir );
}
static gboolean start_all_panels( )
{
char *panel_dir;
const gchar * const * dir;
/* try user panels */
panel_dir = _user_config_file_name("panels", NULL);
_start_panels_from_dir(panel_dir);
g_free(panel_dir);
if (all_panels != NULL)
return TRUE;
/* else try XDG fallbacks */
dir = g_get_system_config_dirs();
if (dir) while (dir[0])
{
panel_dir = _system_config_file_name(dir[0], "panels");
_start_panels_from_dir(panel_dir);
g_free(panel_dir);
if (all_panels != NULL)
return TRUE;
dir++;
}
/* last try at old fallback for compatibility reasons */
panel_dir = _old_system_config_file_name("panels");
_start_panels_from_dir(panel_dir);
g_free(panel_dir);
return all_panels != NULL;
}
void load_global_config();
void free_global_config();
static void _ensure_user_config_dirs(void)
{
char *dir = g_build_filename(g_get_user_config_dir(), "lxpanel", cprofile,
"panels", NULL);
/* make sure the private profile and panels dir exists */
g_mkdir_with_parents(dir, 0700);
g_free(dir);
}
int main(int argc, char *argv[], char *env[])
{
int i;
const char* desktop_name;
char *file;
setlocale(LC_CTYPE, "");
#if !GLIB_CHECK_VERSION(2, 32, 0)
g_thread_init(NULL);
#endif
/* gdk_threads_init();
gdk_threads_enter(); */
gtk_init(&argc, &argv);
#ifdef ENABLE_NLS
bindtextdomain ( GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR );
bind_textdomain_codeset ( GETTEXT_PACKAGE, "UTF-8" );
textdomain ( GETTEXT_PACKAGE );
#endif
XSetLocaleModifiers("");
XSetErrorHandler((XErrorHandler) panel_handle_x_error);
resolve_atoms();
desktop_name = g_getenv("XDG_CURRENT_DESKTOP");
is_in_lxde = desktop_name && (0 == strcmp(desktop_name, "LXDE"));
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
usage();
exit(0);
} else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) {
printf("lxpanel %s\n", version);
exit(0);
} else if (!strcmp(argv[i], "--log")) {
i++;
if (i == argc) {
g_critical( "lxpanel: missing log level");
usage();
exit(1);
} else {
/* deprecated */
}
} else if (!strcmp(argv[i], "--configure") || !strcmp(argv[i], "-C")) {
config = 1;
} else if (!strcmp(argv[i], "--profile") || !strcmp(argv[i], "-p")) {
i++;
if (i == argc) {
g_critical( "lxpanel: missing profile name");
usage();
exit(1);
} else {
cprofile = g_strdup(argv[i]);
}
} else {
printf("lxpanel: unknown option - %s\n", argv[i]);
usage();
exit(1);
}
}
/* Add a gtkrc file to be parsed too. */
file = _user_config_file_name("gtkrc", NULL);
gtk_rc_parse(file);
g_free(file);
/* Check for duplicated lxpanel instances */
if (!check_main_lock() && !config) {
printf("There is already an instance of LXPanel. Now to exit\n");
exit(1);
}
_ensure_user_config_dirs();
/* Add our own icons to the search path of icon theme */
gtk_icon_theme_append_search_path( gtk_icon_theme_get_default(), PACKAGE_DATA_DIR "/images" );
fbev = fb_ev_new();
is_restarting = FALSE;
/* init LibFM */
fm_gtk_init(NULL);
/* prepare modules data */
lxpanel_prepare_modules();
init_static_plugins();
load_global_config();
/* NOTE: StructureNotifyMask is required by XRandR
* See init_randr_support() in gdkscreen-x11.c of gtk+ for detail.
*/
gdk_window_set_events(gdk_get_default_root_window(), GDK_STRUCTURE_MASK |
GDK_SUBSTRUCTURE_MASK | GDK_PROPERTY_CHANGE_MASK);
gdk_window_add_filter(gdk_get_default_root_window (), (GdkFilterFunc)panel_event_filter, NULL);
if( G_UNLIKELY( ! start_all_panels() ) )
g_warning( "Config files are not found.\n" );
/*
* FIXME: configure??
if (config)
configure();
*/
gtk_main();
XSelectInput (GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), GDK_ROOT_WINDOW(), NoEventMask);
gdk_window_remove_filter(gdk_get_default_root_window (), (GdkFilterFunc)panel_event_filter, NULL);
/* destroy all panels */
g_slist_foreach( all_panels, (GFunc) gtk_widget_destroy, NULL );
g_slist_free( all_panels );
all_panels = NULL;
g_free( cfgfile );
free_global_config();
lxpanel_unload_modules();
fm_gtk_finalize();
/* gdk_threads_leave(); */
g_object_unref(fbev);
if (!is_restarting)
return 0;
if (strchr(argv[0], G_DIR_SEPARATOR))
execve(argv[0], argv, env);
else
execve(g_find_program_in_path(argv[0]), argv, env);
return 1;
}
| linuxmintpl/lxpanel | src/main.c | C | gpl-2.0 | 14,172 |
<?php
/**
* @version $Id: default.php 20196 2011-01-09 02:40:25Z ian $
* @package Joomla.Site
* @subpackage com_content
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.DS.'helpers');
// If the page class is defined, add to class as suffix.
// It will be a separate class if the user starts it with a space
?>
<div class="blog-featured<?php echo $this->pageclass_sfx;?>">
<?php if ( $this->params->get('show_page_heading')!=0) : ?>
<h1 class="componentheading">
<?php echo $this->escape($this->params->get('page_heading')); ?>
</h1>
<?php endif; ?>
<?php $leadingcount=0 ; ?>
<?php if (!empty($this->lead_items)) : ?>
<div class="items-leading">
<?php foreach ($this->lead_items as &$item) : ?>
<div class="leading-<?php echo $leadingcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<?php
$leadingcount++;
?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php
$introcount=(count($this->intro_items));
$counter=0;
?>
<?php if (!empty($this->intro_items)) : ?>
<?php foreach ($this->intro_items as $key => &$item) : ?>
<?php
$key= ($key-$leadingcount)+1;
$rowcount=( ((int)$key-1) % (int) $this->columns) +1;
$row = $counter / $this->columns ;
if ($rowcount==1) : ?>
<div class="items-row cols-<?php echo (int) $this->columns;?> <?php echo 'row-'.$row ; ?>">
<?php endif; ?>
<div class="item column-<?php echo $rowcount;?><?php echo $item->state == 0 ? ' system-unpublished"' : null; ?>">
<div class="item-column">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
</div>
<?php $counter++; ?>
<?php if (($rowcount == $this->columns) or ($counter ==$introcount)): ?>
<span class="row-separator"></span>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php if (!empty($this->link_items)) : ?>
<div class="items-more">
<?php echo $this->loadTemplate('links'); ?>
</div>
<?php endif; ?>
<?php if ($this->params->def('show_pagination', 2) == 1 || ($this->params->get('show_pagination') == 2 && $this->pagination->get('pages.total') > 1)) : ?>
<div class="pagination">
<?php if ($this->params->def('show_pagination_results', 1)) : ?>
<p class="counter">
<?php echo $this->pagination->getPagesCounter(); ?>
</p>
<?php endif; ?>
<?php echo $this->pagination->getPagesLinks(); ?>
</div>
<?php endif; ?>
</div>
| gizzyatik/lideravtocom | templates/zt_opis25/html/com_content/featured/default.php | PHP | gpl-2.0 | 2,665 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'openPathTool.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(457, 95)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.formLayout = QtGui.QFormLayout(self.centralwidget)
self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
self.formLayout.setObjectName(_fromUtf8("formLayout"))
self.pathInLineEdit = QtGui.QLineEdit(self.centralwidget)
self.pathInLineEdit.setObjectName(_fromUtf8("pathInLineEdit"))
self.formLayout.setWidget(0, QtGui.QFormLayout.SpanningRole, self.pathInLineEdit)
self.pathOutLineEdit = QtGui.QLineEdit(self.centralwidget)
self.pathOutLineEdit.setReadOnly(True)
self.pathOutLineEdit.setObjectName(_fromUtf8("pathOutLineEdit"))
self.formLayout.setWidget(1, QtGui.QFormLayout.SpanningRole, self.pathOutLineEdit)
self.buttonLayout = QtGui.QHBoxLayout()
self.buttonLayout.setObjectName(_fromUtf8("buttonLayout"))
self.explorerButton = QtGui.QPushButton(self.centralwidget)
self.explorerButton.setObjectName(_fromUtf8("explorerButton"))
self.buttonLayout.addWidget(self.explorerButton)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.buttonLayout.addItem(spacerItem)
self.convertButton = QtGui.QPushButton(self.centralwidget)
self.convertButton.setObjectName(_fromUtf8("convertButton"))
self.buttonLayout.addWidget(self.convertButton)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.buttonLayout.addItem(spacerItem1)
self.closeButton = QtGui.QPushButton(self.centralwidget)
self.closeButton.setObjectName(_fromUtf8("closeButton"))
self.buttonLayout.addWidget(self.closeButton)
self.formLayout.setLayout(2, QtGui.QFormLayout.SpanningRole, self.buttonLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pathInLineEdit.setPlaceholderText(_translate("MainWindow", "Input Path", None))
self.pathOutLineEdit.setPlaceholderText(_translate("MainWindow", "Output Path", None))
self.explorerButton.setText(_translate("MainWindow", "Open In Explorer", None))
self.convertButton.setText(_translate("MainWindow", "Convert", None))
self.closeButton.setText(_translate("MainWindow", "Close", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| david2777/DavidsTools | Standalone/openPathTool/UI_openPathTool.py | Python | gpl-2.0 | 3,656 |
var Coords =[
new google.maps.LatLng(43.764497050251, 4.067245831926),
new google.maps.LatLng(43.767710540551, 4.0838447211269),
new google.maps.LatLng(43.763799242547, 4.0910940285128),
new google.maps.LatLng(43.751534987638, 4.0955537969329),
new google.maps.LatLng(43.749596196669, 4.0992272874881),
new google.maps.LatLng(43.748614101906, 4.1037735820058),
new google.maps.LatLng(43.740176897197, 4.1116967004996),
new google.maps.LatLng(43.737672967392, 4.1141608349415),
new google.maps.LatLng(43.737122105436, 4.1225139666038),
new google.maps.LatLng(43.740618383453, 4.1334746212138),
new google.maps.LatLng(43.73549175631, 4.1438531591789),
new google.maps.LatLng(43.732442056606, 4.1450336205531),
new google.maps.LatLng(43.717749022565, 4.1515839261668),
new google.maps.LatLng(43.715013286084, 4.1538768326902),
new google.maps.LatLng(43.70775944283, 4.1623216217659),
new google.maps.LatLng(43.69599663352, 4.1646093108827),
new google.maps.LatLng(43.692836878272, 4.164309790761),
new google.maps.LatLng(43.690142310761, 4.1636163228877),
new google.maps.LatLng(43.651750366126, 4.1938133092423),
new google.maps.LatLng(43.641876308886, 4.1928978389754),
new google.maps.LatLng(43.610808005954, 4.1700493321096),
new google.maps.LatLng(43.596111677254, 4.1496125262289),
new google.maps.LatLng(43.589087710743, 4.1503049224716),
new google.maps.LatLng(43.585565233082, 4.1502054865695),
new google.maps.LatLng(43.588357562326, 4.1228737302345),
new google.maps.LatLng(43.585273648539, 4.0998851223704),
new google.maps.LatLng(43.590937681987, 4.0882478576292),
new google.maps.LatLng(43.59030671958, 4.0794468991731),
new google.maps.LatLng(43.5889919794, 4.0751150449374),
new google.maps.LatLng(43.588594582094, 4.0746700716691),
new google.maps.LatLng(43.588353533806, 4.0834935156176),
new google.maps.LatLng(43.571377713527, 4.1063310679927),
new google.maps.LatLng(43.568435156867, 4.1087003638825),
new google.maps.LatLng(43.554374556735, 4.101033501705),
new google.maps.LatLng(43.556833163387, 4.0425173468859),
new google.maps.LatLng(43.556334613985, 4.0376446095051),
new google.maps.LatLng(43.550959182088, 4.0047437269044),
new google.maps.LatLng(43.541199151517, 3.9740100828706),
new google.maps.LatLng(43.540235526673, 3.9693732342211),
new google.maps.LatLng(43.518493270178, 3.912277253111),
new google.maps.LatLng(43.517199046766, 3.9079430828702),
new google.maps.LatLng(43.515263457389, 3.9038138774444),
new google.maps.LatLng(43.487461339826, 3.8527691888595),
new google.maps.LatLng(43.466501007342, 3.8262118759024),
new google.maps.LatLng(43.463562593536, 3.8235439882633),
new google.maps.LatLng(43.440040430863, 3.7945256440712),
new google.maps.LatLng(43.415801075627, 3.724911602778),
new google.maps.LatLng(43.412275889717, 3.7250604677071),
new google.maps.LatLng(43.40168543759, 3.7252723840087),
new google.maps.LatLng(43.392086513447, 3.6892124897449),
new google.maps.LatLng(43.392912486882, 3.6654331167972),
new google.maps.LatLng(43.388000704254, 3.6526137399832),
new google.maps.LatLng(43.367541706339, 3.6193510157753),
new google.maps.LatLng(43.326167903476, 3.5666749169165),
new google.maps.LatLng(43.323497321641, 3.5636511199473),
new google.maps.LatLng(43.302018302127, 3.5398007661227),
new google.maps.LatLng(43.275986759651, 3.5160101953829),
new google.maps.LatLng(43.27243694938, 3.507795812983),
new google.maps.LatLng(43.282183706868, 3.4436021012641),
new google.maps.LatLng(43.289466092167, 3.433618025397),
new google.maps.LatLng(43.290223414137, 3.4289577322512),
new google.maps.LatLng(43.290092412522, 3.4241451779723),
new google.maps.LatLng(43.287291792597, 3.400449018804),
new google.maps.LatLng(43.27737600946, 3.364782418103),
new google.maps.LatLng(43.275888464821, 3.3605742162691),
new google.maps.LatLng(43.270315972843, 3.3435411788445),
new google.maps.LatLng(43.267704564177, 3.3402736130879),
new google.maps.LatLng(43.254488903636, 3.3116188481241),
new google.maps.LatLng(43.252327124149, 3.3082137270658),
new google.maps.LatLng(43.233406140974, 3.2713326376239),
new google.maps.LatLng(43.231326326839, 3.2676612698119),
new google.maps.LatLng(43.212813466414, 3.2405555984303),
new google.maps.LatLng(43.219164104542, 3.2289833318724),
new google.maps.LatLng(43.24777428734, 3.2015235025104),
new google.maps.LatLng(43.250410690322, 3.1932162125318),
new google.maps.LatLng(43.250133185926, 3.1840046686603),
new google.maps.LatLng(43.243847449793, 3.1731200265047),
new google.maps.LatLng(43.24322705354, 3.1591848207257),
new google.maps.LatLng(43.247393750711, 3.1465096207935),
new google.maps.LatLng(43.254165245609, 3.1470107106721),
new google.maps.LatLng(43.259516359039, 3.1416149329225),
new google.maps.LatLng(43.260744300448, 3.1188861735501),
new google.maps.LatLng(43.254754449597, 3.1146616552818),
new google.maps.LatLng(43.256170311974, 3.1014154861434),
new google.maps.LatLng(43.257932720391, 3.0974432327844),
new google.maps.LatLng(43.259882544534, 3.0936330383983),
new google.maps.LatLng(43.263834423362, 3.0861969952925),
new google.maps.LatLng(43.262936768459, 3.0769759559943),
new google.maps.LatLng(43.280046316685, 3.0543445664211),
new google.maps.LatLng(43.281918942077, 3.036053972047),
new google.maps.LatLng(43.277621116516, 3.0111093680315),
new google.maps.LatLng(43.280939696638, 3.0120953583958),
new google.maps.LatLng(43.286245195319, 3.0057246144955),
new google.maps.LatLng(43.296782360259, 3.0048139017547),
new google.maps.LatLng(43.300142997304, 3.0062801771976),
new google.maps.LatLng(43.319717247656, 3.004416118444),
new google.maps.LatLng(43.319557883167, 2.9952697760087),
new google.maps.LatLng(43.319226203204, 2.9907122186526),
new google.maps.LatLng(43.313053766357, 2.9617841350901),
new google.maps.LatLng(43.31248527536, 2.9575323939526),
new google.maps.LatLng(43.311966634759, 2.9460700568401),
new google.maps.LatLng(43.313669610899, 2.942063999969),
new google.maps.LatLng(43.326095507672, 2.9212453430981),
new google.maps.LatLng(43.323523103733, 2.9183636410232),
new google.maps.LatLng(43.320058135741, 2.9109809574883),
new google.maps.LatLng(43.326271056758, 2.894918499876),
new google.maps.LatLng(43.327945382316, 2.8908727412029),
new google.maps.LatLng(43.333258686917, 2.8851135431243),
new google.maps.LatLng(43.34181850223, 2.8911667014333),
new google.maps.LatLng(43.351774895076, 2.8894896066632),
new google.maps.LatLng(43.354631167261, 2.8880023774612),
new google.maps.LatLng(43.35735328512, 2.8899004774047),
new google.maps.LatLng(43.360538965293, 2.8890197830529),
new google.maps.LatLng(43.36660247913, 2.8877108945586),
new google.maps.LatLng(43.372943781124, 2.8722746830842),
new google.maps.LatLng(43.38102210816, 2.8705636020831),
new google.maps.LatLng(43.383644063628, 2.8691710678577),
new google.maps.LatLng(43.376299709391, 2.8567710601744),
new google.maps.LatLng(43.373492477522, 2.8556245979945),
new google.maps.LatLng(43.356458197807, 2.8695716108069),
new google.maps.LatLng(43.339642234973, 2.8737369559741),
new google.maps.LatLng(43.330070869443, 2.8685266478631),
new google.maps.LatLng(43.325632856635, 2.8459730177875),
new google.maps.LatLng(43.323692982579, 2.8419187191978),
new google.maps.LatLng(43.323972511949, 2.8181539005732),
new google.maps.LatLng(43.319218171384, 2.8061021909638),
new google.maps.LatLng(43.308658383918, 2.8165981982052),
new google.maps.LatLng(43.304384773049, 2.8096722332936),
new google.maps.LatLng(43.302371254646, 2.8057185014417),
new google.maps.LatLng(43.300321439946, 2.8018139670651),
new google.maps.LatLng(43.287704527134, 2.7872219216814),
new google.maps.LatLng(43.277777110439, 2.7867997710852),
new google.maps.LatLng(43.274451763746, 2.7869582017553),
new google.maps.LatLng(43.274046909884, 2.7870780064563),
new google.maps.LatLng(43.266641083672, 2.7831713677293),
new google.maps.LatLng(43.265252489543, 2.7799883092305),
new google.maps.LatLng(43.261245392772, 2.7732813524163),
new google.maps.LatLng(43.258040806996, 2.7724824971388),
new google.maps.LatLng(43.257257123375, 2.7685056209493),
new google.maps.LatLng(43.254606456392, 2.752516658963),
new google.maps.LatLng(43.257401385285, 2.7500657839666),
new google.maps.LatLng(43.26458915665, 2.7407605946728),
new google.maps.LatLng(43.26725956, 2.7379020844305),
new google.maps.LatLng(43.275563590421, 2.7177301300182),
new google.maps.LatLng(43.273662523157, 2.7089126013864),
new google.maps.LatLng(43.274484060323, 2.7051794599365),
new google.maps.LatLng(43.276827893796, 2.7029562316351),
new google.maps.LatLng(43.282830333666, 2.700288609921),
new google.maps.LatLng(43.292274523921, 2.7055026122394),
new google.maps.LatLng(43.308344678077, 2.699145705393),
new google.maps.LatLng(43.311214819342, 2.7007265948906),
new google.maps.LatLng(43.323011355784, 2.6877672062537),
new google.maps.LatLng(43.316584642206, 2.685549684911),
new google.maps.LatLng(43.313619004238, 2.6772128758754),
new google.maps.LatLng(43.303715072161, 2.6748533990011),
new google.maps.LatLng(43.296348189032, 2.6597398522658),
new google.maps.LatLng(43.292980043257, 2.6592411715176),
new google.maps.LatLng(43.294199839325, 2.6477827840608),
new google.maps.LatLng(43.2945164635, 2.6439094262335),
new google.maps.LatLng(43.295561609799, 2.639744620708),
new google.maps.LatLng(43.29594476602, 2.6311843702299),
new google.maps.LatLng(43.287623826824, 2.6246102925863),
new google.maps.LatLng(43.284454138064, 2.6169440497314),
new google.maps.LatLng(43.287695631486, 2.6178331668848),
new google.maps.LatLng(43.298269018161, 2.6011656296314),
new google.maps.LatLng(43.301432589453, 2.6009218087246),
new google.maps.LatLng(43.313844940455, 2.5996990297167),
new google.maps.LatLng(43.31456274639, 2.5964288952093),
new google.maps.LatLng(43.317996923894, 2.5920016476026),
new google.maps.LatLng(43.321413960379, 2.5909829864245),
new google.maps.LatLng(43.333921712898, 2.5835290753887),
new google.maps.LatLng(43.337477685351, 2.5555245468346),
new google.maps.LatLng(43.335850335536, 2.5514927789278),
new google.maps.LatLng(43.345244858549, 2.5400771213401),
new google.maps.LatLng(43.354462442623, 2.5458975980357),
new google.maps.LatLng(43.366377586276, 2.5552281180032),
new google.maps.LatLng(43.376438915614, 2.5523836551378),
new google.maps.LatLng(43.389792167222, 2.5570546157474),
new google.maps.LatLng(43.397582100942, 2.5663027693091),
new google.maps.LatLng(43.400254245021, 2.5690248346599),
new google.maps.LatLng(43.399498714508, 2.5734708531489),
new google.maps.LatLng(43.399657202667, 2.5868803940185),
new google.maps.LatLng(43.405135281358, 2.5922905184457),
new google.maps.LatLng(43.411720619706, 2.5930471264166),
new google.maps.LatLng(43.412676728056, 2.5838183607221),
new google.maps.LatLng(43.421245171725, 2.569787871923),
new google.maps.LatLng(43.422970197904, 2.5657755060732),
new google.maps.LatLng(43.423309211223, 2.5792652548044),
new google.maps.LatLng(43.432719548507, 2.5979871913018),
new google.maps.LatLng(43.431343333441, 2.6021858553915),
new google.maps.LatLng(43.432006976889, 2.6063692423199),
new google.maps.LatLng(43.438037807129, 2.6060769379219),
new google.maps.LatLng(43.440421368499, 2.6088384166858),
new google.maps.LatLng(43.438538561989, 2.6176473878596),
new google.maps.LatLng(43.455595113375, 2.6410467522132),
new google.maps.LatLng(43.457930738128, 2.6445628335792),
new google.maps.LatLng(43.461273756026, 2.6446054565924),
new google.maps.LatLng(43.467069948695, 2.6415765366252),
new google.maps.LatLng(43.464183600798, 2.6636220293469),
new google.maps.LatLng(43.470056793486, 2.667986703452),
new google.maps.LatLng(43.472689847091, 2.6650896516086),
new google.maps.LatLng(43.480971393081, 2.6576208798072),
new google.maps.LatLng(43.494199142323, 2.6550284874719),
new google.maps.LatLng(43.503468507719, 2.6598952161139),
new google.maps.LatLng(43.516934617292, 2.6588473697839),
new google.maps.LatLng(43.513705649723, 2.6715116017393),
new google.maps.LatLng(43.513466923493, 2.6760175626237),
new google.maps.LatLng(43.516270810225, 2.6731937804288),
new google.maps.LatLng(43.548289121276, 2.631431888153),
new google.maps.LatLng(43.565386887977, 2.6166383423958),
new google.maps.LatLng(43.568726838576, 2.6179772822462),
new google.maps.LatLng(43.583252410712, 2.6309937461155),
new google.maps.LatLng(43.593203141017, 2.6272237888046),
new google.maps.LatLng(43.59246962559, 2.6225333627594),
new google.maps.LatLng(43.595433128828, 2.6200624775246),
new google.maps.LatLng(43.600531867019, 2.6155982491134),
new google.maps.LatLng(43.611114627643, 2.6277724435695),
new google.maps.LatLng(43.660680341037, 2.6454817228743),
new google.maps.LatLng(43.659454615325, 2.6497711337781),
new google.maps.LatLng(43.650005859011, 2.6535690824976),
new google.maps.LatLng(43.649452580576, 2.6672812128777),
new google.maps.LatLng(43.653820346744, 2.6846870062571),
new google.maps.LatLng(43.65093564865, 2.6873060999388),
new google.maps.LatLng(43.642500459434, 2.7229120951681),
new google.maps.LatLng(43.627271641781, 2.7409241318536),
new google.maps.LatLng(43.617866939561, 2.7465361802148),
new google.maps.LatLng(43.614151341425, 2.7545134228371),
new google.maps.LatLng(43.614897649884, 2.7590713748764),
new google.maps.LatLng(43.625880495443, 2.7816843259866),
new google.maps.LatLng(43.624646995985, 2.7951242380276),
new google.maps.LatLng(43.629544991817, 2.8015856982342),
new google.maps.LatLng(43.632165183812, 2.8046883131259),
new google.maps.LatLng(43.639491856918, 2.814698860384),
new google.maps.LatLng(43.637444036994, 2.8284189389341),
new google.maps.LatLng(43.644765452404, 2.8448820928324),
new google.maps.LatLng(43.644974394949, 2.8687602104603),
new google.maps.LatLng(43.657139264955, 2.8842868672717),
new google.maps.LatLng(43.654661487371, 2.9029316595363),
new google.maps.LatLng(43.654761850142, 2.9077854999055),
new google.maps.LatLng(43.662012667059, 2.9184687728366),
new google.maps.LatLng(43.686590522624, 2.9195863204309),
new google.maps.LatLng(43.694722489306, 2.9349566621739),
new google.maps.LatLng(43.691787770386, 2.9422223071178),
new google.maps.LatLng(43.696542782535, 2.9549713055804),
new google.maps.LatLng(43.699458154579, 2.9575922894355),
new google.maps.LatLng(43.704028418731, 2.9693510139828),
new google.maps.LatLng(43.704630679732, 2.9739546093266),
new google.maps.LatLng(43.708034325938, 2.9820841819559),
new google.maps.LatLng(43.706503424894, 2.9959944006669),
new google.maps.LatLng(43.701452800048, 3.0133191729311),
new google.maps.LatLng(43.696008060918, 3.0186561355853),
new google.maps.LatLng(43.694373855237, 3.0226504658572),
new google.maps.LatLng(43.692439638249, 3.031373174402),
new google.maps.LatLng(43.696959580507, 3.048227734022),
new google.maps.LatLng(43.692814182549, 3.0606757037474),
new google.maps.LatLng(43.696015241164, 3.0618684792685),
new google.maps.LatLng(43.702412070124, 3.0623586553531),
new google.maps.LatLng(43.706851849597, 3.0691559502941),
new google.maps.LatLng(43.715980768143, 3.0549590115441),
new google.maps.LatLng(43.72575200619, 3.0576478905281),
new google.maps.LatLng(43.732008869579, 3.0535121138241),
new google.maps.LatLng(43.738448204152, 3.0571141120726),
new google.maps.LatLng(43.744784855174, 3.053151949452),
new google.maps.LatLng(43.751566947329, 3.0552337274355),
new google.maps.LatLng(43.754958032058, 3.0562686019721),
new google.maps.LatLng(43.755715077854, 3.065405917086),
new google.maps.LatLng(43.767598283868, 3.0734966915114),
new google.maps.LatLng(43.779688997592, 3.0587893448412),
new google.maps.LatLng(43.782810955159, 3.0570421915607),
new google.maps.LatLng(43.786110232658, 3.0583743816932),
new google.maps.LatLng(43.801502128045, 3.0485654596642),
new google.maps.LatLng(43.804629053386, 3.0501560983569),
new google.maps.LatLng(43.81263813234, 3.0638127826534),
new google.maps.LatLng(43.818021394989, 3.0586546216152),
new google.maps.LatLng(43.827981493392, 3.0587312397999),
new google.maps.LatLng(43.835275493627, 3.0663125180764),
new google.maps.LatLng(43.83482928498, 3.0711626695373),
new google.maps.LatLng(43.835566076912, 3.0857027320166),
new google.maps.LatLng(43.827079985415, 3.1125618217326),
new google.maps.LatLng(43.817671678323, 3.1269721165949),
new google.maps.LatLng(43.813774641763, 3.150704446994),
new google.maps.LatLng(43.814802769068, 3.1514640348897),
new google.maps.LatLng(43.817077585965, 3.1549977151193),
new google.maps.LatLng(43.812840449347, 3.1823727961769),
new google.maps.LatLng(43.812965112624, 3.2053042908887),
new google.maps.LatLng(43.817787106301, 3.2226852222246),
new google.maps.LatLng(43.826073053974, 3.231791985611),
new google.maps.LatLng(43.827447161244, 3.23630882038),
new google.maps.LatLng(43.828815631227, 3.2447126452908),
new google.maps.LatLng(43.829588519884, 3.2490341072424),
new google.maps.LatLng(43.842955323279, 3.2502669090853),
new google.maps.LatLng(43.852747300616, 3.2371311723815),
new google.maps.LatLng(43.862696152916, 3.2353502467722),
new google.maps.LatLng(43.874948820418, 3.2430504110919),
new google.maps.LatLng(43.878317388521, 3.2562290077787),
new google.maps.LatLng(43.887610246167, 3.2618986007005),
new google.maps.LatLng(43.891011625337, 3.2626003861536),
new google.maps.LatLng(43.898527673087, 3.2741365958612),
new google.maps.LatLng(43.896781972883, 3.2774398578363),
new google.maps.LatLng(43.893310733501, 3.2858239253238),
new google.maps.LatLng(43.89499126559, 3.2951267145453),
new google.maps.LatLng(43.891149170611, 3.3186575516449),
new google.maps.LatLng(43.894203151013, 3.3425683201462),
new google.maps.LatLng(43.903712308652, 3.3419034376836),
new google.maps.LatLng(43.912517408301, 3.3550802349951),
new google.maps.LatLng(43.914533695681, 3.3586609129918),
new google.maps.LatLng(43.91153737767, 3.3598755570552),
new google.maps.LatLng(43.916530368788, 3.3700024875379),
new google.maps.LatLng(43.912394683674, 3.381294367721),
new google.maps.LatLng(43.910784467131, 3.3944099249313),
new google.maps.LatLng(43.914731968134, 3.4017218099446),
new google.maps.LatLng(43.911320641053, 3.4239191408841),
new google.maps.LatLng(43.900376679957, 3.4357709307027),
new google.maps.LatLng(43.886788101232, 3.4370249038852),
new google.maps.LatLng(43.873668693154, 3.4310044005068),
new google.maps.LatLng(43.872324530577, 3.4215954391113),
new google.maps.LatLng(43.864428499676, 3.4308018055531),
new google.maps.LatLng(43.862963916446, 3.435172414109),
new google.maps.LatLng(43.868875151211, 3.4471172854528),
new google.maps.LatLng(43.871395187163, 3.4608494969953),
new google.maps.LatLng(43.890458538981, 3.4820748627487),
new google.maps.LatLng(43.891302040199, 3.4915776491392),
new google.maps.LatLng(43.890776951764, 3.4961420107577),
new google.maps.LatLng(43.896385880324, 3.5071729007075),
new google.maps.LatLng(43.888426735064, 3.520671475872),
new google.maps.LatLng(43.885797283892, 3.5235256101578),
new google.maps.LatLng(43.864950499177, 3.5216367718623),
new google.maps.LatLng(43.859047652796, 3.5270306482096),
new google.maps.LatLng(43.85169620698, 3.548730140662),
new google.maps.LatLng(43.855336869534, 3.5616049715187),
new google.maps.LatLng(43.844916021787, 3.5743619494384),
new google.maps.LatLng(43.843569534149, 3.5789039669546),
new google.maps.LatLng(43.846188682295, 3.5817934974029),
new google.maps.LatLng(43.84964381202, 3.5994730361895),
new google.maps.LatLng(43.852974738999, 3.5998699928172),
new google.maps.LatLng(43.864451036219, 3.5768746481182),
new google.maps.LatLng(43.871189956839, 3.5788112243981),
new google.maps.LatLng(43.877435988535, 3.5829623464993),
new google.maps.LatLng(43.888930536817, 3.6005071530527),
new google.maps.LatLng(43.895393251159, 3.6022049882509),
new google.maps.LatLng(43.914143178022, 3.6210673424323),
new google.maps.LatLng(43.916981621984, 3.6235818111296),
new google.maps.LatLng(43.914927133575, 3.6375650839334),
new google.maps.LatLng(43.898953952047, 3.6379829406426),
new google.maps.LatLng(43.902417913782, 3.6452745634724),
new google.maps.LatLng(43.912664480132, 3.6448015493723),
new google.maps.LatLng(43.91127302046, 3.6624425296301),
new google.maps.LatLng(43.910570271097, 3.6669780416002),
new google.maps.LatLng(43.913269537642, 3.6734216577505),
new google.maps.LatLng(43.926098604097, 3.6786498226925),
new google.maps.LatLng(43.932409141351, 3.6765718045011),
new google.maps.LatLng(43.940638779668, 3.6836471729513),
new google.maps.LatLng(43.939498787614, 3.6863949964684),
new google.maps.LatLng(43.939945865751, 3.6894915790867),
new google.maps.LatLng(43.951660927496, 3.6844810735006),
new google.maps.LatLng(43.958236282201, 3.6994370904496),
new google.maps.LatLng(43.960987788741, 3.7172664964086),
new google.maps.LatLng(43.970683961405, 3.73112280709),
new google.maps.LatLng(43.966874323088, 3.7873258572737),
new google.maps.LatLng(43.963606421636, 3.7869436022047),
new google.maps.LatLng(43.95383961072, 3.7870800528868),
new google.maps.LatLng(43.942280572745, 3.7955083003835),
new google.maps.LatLng(43.942412902242, 3.8203006885095),
new google.maps.LatLng(43.939791611999, 3.8232809450009),
new google.maps.LatLng(43.924059754806, 3.8282808984296),
new google.maps.LatLng(43.918058153268, 3.8239936255809),
new google.maps.LatLng(43.911932942503, 3.8208482989948),
new google.maps.LatLng(43.890822245537, 3.7995341311598),
new google.maps.LatLng(43.878595108746, 3.8054596015989),
new google.maps.LatLng(43.8740857406, 3.8223464706225),
new google.maps.LatLng(43.86895635712, 3.827917049394),
new google.maps.LatLng(43.866426235967, 3.8307960804587),
new google.maps.LatLng(43.868659759257, 3.8344465065243),
new google.maps.LatLng(43.868629728148, 3.847656918052),
new google.maps.LatLng(43.87670296679, 3.8612461388793),
new google.maps.LatLng(43.878519033566, 3.8992451641929),
new google.maps.LatLng(43.887156027946, 3.913829613015),
new google.maps.LatLng(43.881974619437, 3.9195535058983),
new google.maps.LatLng(43.878667193571, 3.9182183737984),
new google.maps.LatLng(43.868334252413, 3.9177197550677),
new google.maps.LatLng(43.858787744224, 3.9231083899002),
new google.maps.LatLng(43.854253499492, 3.9337174488978),
new google.maps.LatLng(43.853580542707, 3.9378982848966),
new google.maps.LatLng(43.853383403992, 3.9421173047425),
new google.maps.LatLng(43.853510503837, 3.9589819749038),
new google.maps.LatLng(43.850436008362, 3.9577388119625),
new google.maps.LatLng(43.844136174577, 3.9581307895495),
new google.maps.LatLng(43.842681862082, 3.9795189482769),
new google.maps.LatLng(43.837122650706, 3.9737313860037),
new google.maps.LatLng(43.827216238239, 3.9741916092653),
new google.maps.LatLng(43.816410830524, 3.9620844065809),
new google.maps.LatLng(43.806046528717, 3.9601124944292),
new google.maps.LatLng(43.804510670711, 3.9636068631978),
new google.maps.LatLng(43.80148100489, 3.9743452731043),
new google.maps.LatLng(43.802879184168, 3.9788049798058),
new google.maps.LatLng(43.809897775503, 3.9955950285446),
new google.maps.LatLng(43.813055733212, 4.0013366064945),
new google.maps.LatLng(43.801556210281, 4.0286466763621),
new google.maps.LatLng(43.798931027045, 4.0315106937324),
new google.maps.LatLng(43.787576165384, 4.0497647101563),
new google.maps.LatLng(43.785050642722, 4.053114085562),
new google.maps.LatLng(43.778001428408, 4.0519833804752),
new google.maps.LatLng(43.774273825191, 4.0517470462304),
new google.maps.LatLng(43.772320564129, 4.0598278220158),
new google.maps.LatLng(43.767321313785, 4.0649246985509),
new google.maps.LatLng(43.764497050251, 4.067245831926)
];
| lescaph/wikini-ocim-museums | tools/bazar/presentation/herault.js | JavaScript | gpl-2.0 | 23,888 |
/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.ejb.session;
import com.caucho.config.inject.InjectManager;
import com.caucho.config.xml.XmlConfigContext;
import java.lang.annotation.*;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.InjectionTarget;
/**
* Component for session beans
*/
public class StatefulComponent<X> implements InjectionTarget<X> {
private final StatefulProvider _provider;
private final Class _beanClass;
public StatefulComponent(StatefulProvider provider,
Class beanClass)
{
_provider = provider;
_beanClass = beanClass;
}
/**
* Creates a new instance of the component
*/
public X produce(CreationalContext<X> env)
{
return (X) _provider.__caucho_createNew(this, env);
}
/**
* Inject the bean.
*/
public void inject(X instance, CreationalContext<X> ctx)
{
}
/**
* PostConstruct initialization
*/
public void postConstruct(X instance)
{
}
/**
* Call pre-destroy
*/
public void dispose(X instance)
{
}
/**
* Call destroy
*/
public void preDestroy(X instance)
{
}
/**
* Returns the injection points.
*/
public Set<InjectionPoint> getInjectionPoints()
{
return null;
}
}
| dlitz/resin | modules/resin/src/com/caucho/ejb/session/StatefulComponent.java | Java | gpl-2.0 | 2,418 |
# Configurable Product Functional Tests
The Functional Test Module for **Magento Configurable Product** module.
| kunj1988/Magento2 | app/code/Magento/ConfigurableProduct/Test/Mftf/README.md | Markdown | gpl-2.0 | 113 |
<?php
/* @CoreHome/_warningInvalidHost.twig */
class __TwigTemplate_e31e2465a2349738de07727308938a9e27425253c2b450531e729912f0f58e9f extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 2
if (((array_key_exists("isValidHost", $context) && array_key_exists("invalidHostMessage", $context)) && ($this->getContext($context, "isValidHost") == false))) {
// line 3
echo " ";
ob_start();
// line 4
echo " <a style=\"float:right;\" href=\"http://piwik.org/faq/troubleshooting/#faq_171\" target=\"_blank\"><img src=\"plugins/Zeitgeist/images/help.png\"/></a>
<strong>";
// line 5
echo twig_escape_filter($this->env, call_user_func_array($this->env->getFilter('translate')->getCallable(), array("General_Warning")), "html", null, true);
echo ": </strong>";
echo $this->getContext($context, "invalidHostMessage");
echo "
<br>
<br>
<small>";
// line 10
echo $this->getContext($context, "invalidHostMessageHowToFix");
echo "
<br/><br/><a style=\"float:right;\" href=\"http://piwik.org/faq/troubleshooting/#faq_171\" target=\"_blank\">";
// line 11
echo twig_escape_filter($this->env, call_user_func_array($this->env->getFilter('translate')->getCallable(), array("General_Help")), "html", null, true);
echo "
<img style=\"vertical-align: bottom;\" src=\"plugins/Zeitgeist/images/help.png\"/></a><br/>
</small>
";
$context["invalidHostText"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset());
// line 15
echo "
<div style=\"clear:both;width:800px;\">
";
// line 17
echo call_user_func_array($this->env->getFilter('notification')->getCallable(), array($this->getContext($context, "invalidHostText"), array("noclear" => true, "raw" => true, "context" => "warning")));
echo "
</div>
";
}
// line 21
echo "
";
}
public function getTemplateName()
{
return "@CoreHome/_warningInvalidHost.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 59 => 21, 52 => 17, 48 => 15, 41 => 11, 27 => 5, 24 => 4, 21 => 3, 361 => 164, 355 => 161, 352 => 160, 346 => 157, 343 => 156, 341 => 155, 334 => 153, 329 => 151, 322 => 149, 314 => 144, 308 => 141, 297 => 133, 290 => 129, 283 => 125, 279 => 124, 268 => 116, 264 => 115, 258 => 114, 250 => 109, 246 => 108, 240 => 105, 233 => 101, 229 => 100, 226 => 99, 220 => 97, 218 => 96, 215 => 95, 207 => 92, 204 => 91, 202 => 90, 199 => 89, 195 => 87, 184 => 85, 180 => 84, 177 => 83, 175 => 82, 172 => 81, 169 => 80, 166 => 79, 163 => 78, 157 => 73, 148 => 69, 144 => 67, 142 => 66, 139 => 65, 136 => 64, 130 => 62, 127 => 61, 125 => 60, 122 => 59, 118 => 58, 111 => 57, 102 => 54, 99 => 53, 93 => 51, 91 => 50, 84 => 45, 82 => 44, 77 => 41, 73 => 39, 71 => 38, 45 => 15, 42 => 14, 37 => 10, 28 => 8, 19 => 2,);
}
}
| agiza/vs-port | analytics/tmp/templates_c/e3/1e/2465a2349738de07727308938a9e27425253c2b450531e729912f0f58e9f.php | PHP | gpl-2.0 | 3,494 |
And /^the assignment "(\S+)" allows me to suggest topics$/ do |assignment|
When "I open the assignment #{assignment}"
And 'I click on the link to Suggest a topic'
end
When /^I open the assignment (\S+)$/ do |assignment|
click_link assignment
end
And 'I click on the link to Suggest a topic' do
click_link 'Suggest a topic'
end
And /^I provide the Title & the Description on the following page$/ do
fill_in 'suggestion_title', :with => "test suggestion title"
fill_in 'suggestion_description', :with => "test suggestion description"
end
And /^I click "Submit"$/ do
click_button 'Submit'
end
Then /^the following page should emit the text "Thank you for your suggestion!"$/ do
should have_content 'Thank you for your suggestion!'
end | sgurinder/E720 | features/step_definitions/suggesting_topics.rb | Ruby | gpl-2.0 | 753 |
ul.flippy {
margin: auto;
padding: 0px 20px;
text-align: center;
}
ul.flippy li {
margin: 0;
padding: 10px;
display: inline;
width: auto;
list-style-type: none;
list-style-image: none;
background: none;
white-space: nowrap;
} | nicl/Flippy-D6 | flippy.css | CSS | gpl-2.0 | 248 |
{% include 'base.html' %}
{% block head_additional %}
{% include 'components/vis-resources.html' %}
{% include 'components/general-resources.html' %}
<style>
body {
background-color: #2980BA;
}
.menu li.active {
background-color: #2980BA;
}
.menu a:hover {
color: white;
}
.visualization-panel h4 {
color: #2980BA;
}
</style>
{% endblock %}
{% block content %}
<div class="row ">
{# sidebar #}
<div id="dashboard-menu" class="col-md-1 col-sm-2 col-xs-2"
style="background-color: #2C3E50; padding:0"
align="center">
<img src="/static/assets/img/logo-original.svg" width="80%"
align="center"
style="padding-left: 10px; padding-top: 10px">
<ul class="menu">
<a href="/dashboard/"><li><span class="fa fa-bar-chart"></span></li></a>
<li class="active"><span class="fa fa-database"></span></li>
<a href="/dashboard/researcher/"><li><span class="fa fa-user"></span></li></a>
<a href="/dashboard/crossrefs/"><li><span class="fa fa-cubes"></span></li></a>
<a href="/dashboard/event/"><li><span class="fa fa-calendar"></span></li></a>
<br/>
<a href="https://project-thor.readme.io/docs/dashboard" target="_new" alt="Learn more about the THOR dashboard">
<li><i class="fa fa-info-circle" aria-hidden="true"></i></li>
</a>
</ul>
</div>
{# main content #}
<div id="dashboard-content">
<div class="row col-md-12 col-sm-12 col-xs-12"
style="padding-top: 1em; padding-bottom: 1em">
<div class="col-md-12">
<h2 class="color-white uppercase bold-text">Research Object
Identifier Metrics (DataCite) <a class="pull-right mui-btn mui-btn-default" target="_new" href="/api/data?type=doi">View RAW Data</a></h2>
</div>
</div>
<div class="row visualization-container">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="visualization-panel col-md-12"
style="height: 350px;">
<h4>Overview</h4>
<div id="monthly-chart" class="chart">
</div>
</div>
</div>
</div>
<div class="row visualization-container">
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<div class="visualization-panel col-md-12"
style="height: 920px;">
<h4>DOIs by Allocator</h4>
<div id="institution-chart" class="chart">
</div>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<div class="visualization-panel col-md-12"
style="height: 470px;">
<h4>DOI Object Type</h4>
<div id="object-type" class="chart">
</div>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<div class="visualization-panel col-md-12" style="height: 470px;">
<h4>DOIs With ORCID iDs</h4>
<div id="orcid-chart" class="chart">
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
<div id="table-button" class="toggle-hidden">
<span class="button-container"
onclick="dashboard.toggle_detail_view()">
<i class="glyphicon glyphicon-list"></i> <span id="button-txt">View Detailed List</span>
</span>
</div>
<div id="table-view" class="toggle-hidden">
<div class="row-fluid visualization-container">
<div class="col-md-12 col-sm-10 col-xs-8">
<div class="visualization-panel col-md-12"
style="height: 300px; overflow-y: scroll">
<h4>Detailed Research Object Metrics</h4>
<table class="table dc-data-table">
<thead>
<tr class="header">
<th></th>
<th>Data Centre</th>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
{% block end_additional %}
<script src="/static/assets/js/thor-dash-lib.js"
type="text/javascript"></script>
<script>
$(document).ready(function () {
dashboard.render_doi_metrics("/api/data?type=doi");
});
dashboard.register_resize_listener("doi", "/api/data?type=doi");
</script>
{% endblock %}
| thor-project/dashboard | thor/modules/dashboard/templates/data-dashboard.html | HTML | gpl-2.0 | 5,037 |
CREATE TABLE `part_options` (
`part_options_id` INTEGER PRIMARY KEY,
`def_part_id` INTEGER NOT NULL,
`def_scheme_id` INTEGER NOT NULL,
`poption` varchar(31) NOT NULL,
`cuser` INTEGER NOT NULL DEFAULT 0,
`muser` INTEGER NOT NULL DEFAULT 0,
`ctime` timestamp NOT NULL DEFAULT 0,
`mtime` timestamp NOT NULL DEFAULT 0,
FOREIGN KEY(`def_part_id`)
REFERENCES `default_part`(`def_part_id`)
ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY(`def_scheme_id`)
REFERENCES `seed_schemes`(`def_scheme_id`)
ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TRIGGER insert_part_options AFTER INSERT ON part_options
BEGIN
UPDATE part_options SET ctime = CURRENT_TIMESTAMP, mtime = CURRENT_TIMESTAMP WHERE part_options_id = new.part_options_id;
END;
CREATE TRIGGER update_part_options AFTER UPDATE on part_options
BEGIN
UPDATE part_options SET mtime = CURRENT_TIMESTAMP WHERE part_options_id = new.part_options_id;
END;
| shihad1972/cmdb | sql/sqlite/part_options.sql | SQL | gpl-2.0 | 951 |
/* Some misc dialog boxes for the program.
Copyright (C) 1994, 1995 the Free Software Foundation
Authors: 1994, 1995 Miguel de Icaza
1995 Jakub Jelinek
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
#include <config.h>
#include <ctype.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "global.h"
#include "tty.h"
#include "win.h" /* Our window tools */
#include "color.h" /* Color definitions */
#include "dialog.h" /* The nice dialog manager */
#include "widget.h" /* The widgets for the nice dialog manager */
#include "wtools.h"
#include "setup.h" /* For profile_name */
#include "profile.h" /* Load/save user formats */
#include "key.h" /* XCTRL and ALT macros */
#include "command.h" /* For cmdline */
#include "dir.h"
#include "panel.h"
#include "boxes.h"
#include "main.h" /* For the confirm_* variables */
#include "tree.h"
#include "layout.h" /* for get_nth_panel_name proto */
#include "background.h" /* task_list */
#ifdef HAVE_CHARSET
#include "charsets.h"
#include "selcodepage.h"
#endif
#ifdef USE_NETCODE
# include "../vfs/ftpfs.h"
#endif
#ifdef USE_VFS
#include "../vfs/gc.h"
#endif
static int DISPLAY_X = 45, DISPLAY_Y = 14;
static Dlg_head *dd;
static WRadio *my_radio;
static WInput *user;
static WInput *status;
static WCheck *check_status;
static int current_mode;
static char **displays_status;
/* Controls whether the array strings have been translated */
static const char *displays [LIST_TYPES] = {
N_("&Full file list"),
N_("&Brief file list"),
N_("&Long file list"),
N_("&User defined:")
};
/* Index in displays[] for "user defined" */
#define USER_TYPE 3
static int user_hotkey = 'u';
static cb_ret_t
display_callback (struct Dlg_head *h, dlg_msg_t msg, int parm)
{
switch (msg) {
case DLG_UNFOCUS:
if (dlg_widget_active (my_radio)) {
assign_text (status, displays_status[my_radio->sel]);
input_set_point (status, 0);
}
return MSG_HANDLED;
case DLG_KEY:
if (parm == '\n') {
if (dlg_widget_active (my_radio)) {
assign_text (status, displays_status[my_radio->sel]);
dlg_stop (h);
return MSG_HANDLED;
}
if (dlg_widget_active (user)) {
h->ret_value = B_USER + 6;
dlg_stop (h);
return MSG_HANDLED;
}
if (dlg_widget_active (status)) {
h->ret_value = B_USER + 7;
dlg_stop (h);
return MSG_HANDLED;
}
}
if (tolower (parm) == user_hotkey && dlg_widget_active (user)
&& dlg_widget_active (status)) {
my_radio->sel = 3;
dlg_select_widget (my_radio); /* force redraw */
dlg_select_widget (user);
return MSG_HANDLED;
}
return MSG_NOT_HANDLED;
default:
return default_dlg_callback (h, msg, parm);
}
}
static void
display_init (int radio_sel, char *init_text, int _check_status,
char **_status)
{
static const char *display_title = N_("Listing mode");
static int i18n_displays_flag;
const char *user_mini_status = _("user &Mini status");
const char *ok_button = _("&OK");
const char *cancel_button = _("&Cancel");
static int button_start = 30;
displays_status = _status;
if (!i18n_displays_flag) {
int i, l, maxlen = 0;
const char *cp;
display_title = _(display_title);
for (i = 0; i < LIST_TYPES; i++) {
displays[i] = _(displays[i]);
if ((l = strlen (displays[i])) > maxlen)
maxlen = l;
}
i = strlen (ok_button) + 5;
l = strlen (cancel_button) + 3;
l = max (i, l);
i = maxlen + l + 16;
if (i > DISPLAY_X)
DISPLAY_X = i;
i = strlen (user_mini_status) + 13;
if (i > DISPLAY_X)
DISPLAY_X = i;
i = strlen (display_title) + 10;
if (i > DISPLAY_X)
DISPLAY_X = i;
button_start = DISPLAY_X - l - 5;
/* get hotkey of user-defined format string */
cp = strchr (displays[USER_TYPE], '&');
if (cp != NULL && *++cp != '\0')
user_hotkey = tolower ((unsigned char) *cp);
i18n_displays_flag = 1;
}
dd = create_dlg (0, 0, DISPLAY_Y, DISPLAY_X, dialog_colors,
display_callback, "[Listing Mode...]", display_title,
DLG_CENTER | DLG_REVERSE);
add_widget (dd,
button_new (4, button_start, B_CANCEL, NORMAL_BUTTON,
cancel_button, 0));
add_widget (dd,
button_new (3, button_start, B_ENTER, DEFPUSH_BUTTON,
ok_button, 0));
status =
input_new (10, 9, INPUT_COLOR, DISPLAY_X - 14, _status[radio_sel],
"mini-input");
add_widget (dd, status);
input_set_point (status, 0);
check_status =
check_new (9, 5, _check_status, user_mini_status);
add_widget (dd, check_status);
user =
input_new (7, 9, INPUT_COLOR, DISPLAY_X - 14, init_text,
"user-fmt-input");
add_widget (dd, user);
input_set_point (user, 0);
my_radio = radio_new (3, 5, LIST_TYPES, displays);
my_radio->sel = my_radio->pos = current_mode;
add_widget (dd, my_radio);
}
int
display_box (WPanel *panel, char **userp, char **minip, int *use_msformat, int num)
{
int result, i;
char *section = NULL;
const char *p;
if (!panel) {
p = get_nth_panel_name (num);
panel = g_new (WPanel, 1);
panel->list_type = list_full;
panel->user_format = g_strdup (DEFAULT_USER_FORMAT);
panel->user_mini_status = 0;
for (i = 0; i < LIST_TYPES; i++)
panel->user_status_format[i] = g_strdup (DEFAULT_USER_FORMAT);
section = g_strconcat ("Temporal:", p, (char *) NULL);
if (!profile_has_section (section, profile_name)) {
g_free (section);
section = g_strdup (p);
}
panel_load_setup (panel, section);
g_free (section);
}
current_mode = panel->list_type;
display_init (current_mode, panel->user_format,
panel->user_mini_status, panel->user_status_format);
run_dlg (dd);
result = -1;
if (section) {
g_free (panel->user_format);
for (i = 0; i < LIST_TYPES; i++)
g_free (panel->user_status_format [i]);
g_free (panel);
}
if (dd->ret_value != B_CANCEL){
result = my_radio->sel;
*userp = g_strdup (user->buffer);
*minip = g_strdup (status->buffer);
*use_msformat = check_status->state & C_BOOL;
}
destroy_dlg (dd);
return result;
}
static int SORT_X = 40, SORT_Y = 14;
static const char *sort_orders_names [SORT_TYPES];
sortfn *
sort_box (sortfn *sort_fn, int *reverse, int *case_sensitive)
{
int i, r, l;
sortfn *result;
WCheck *c, *case_sense;
const char *ok_button = _("&OK");
const char *cancel_button = _("&Cancel");
const char *reverse_label = _("&Reverse");
const char *case_label = _("case sensi&tive");
const char *sort_title = _("Sort order");
static int i18n_sort_flag = 0, check_pos = 0, button_pos = 0;
if (!i18n_sort_flag) {
int maxlen = 0;
for (i = SORT_TYPES - 1; i >= 0; i--) {
sort_orders_names[i] = _(sort_orders[i].sort_name);
r = strlen (sort_orders_names[i]);
if (r > maxlen)
maxlen = r;
}
check_pos = maxlen + 9;
r = strlen (reverse_label) + 4;
i = strlen (case_label) + 4;
if (i > r)
r = i;
l = strlen (ok_button) + 6;
i = strlen (cancel_button) + 4;
if (i > l)
l = i;
i = check_pos + max (r, l) + 2;
if (i > SORT_X)
SORT_X = i;
i = strlen (sort_title) + 6;
if (i > SORT_X)
SORT_X = i;
button_pos = SORT_X - l - 2;
i18n_sort_flag = 1;
}
result = 0;
for (i = 0; i < SORT_TYPES; i++)
if ((sortfn *) (sort_orders[i].sort_fn) == sort_fn) {
current_mode = i;
break;
}
dd = create_dlg (0, 0, SORT_Y, SORT_X, dialog_colors, NULL,
"[Sort Order...]", sort_title, DLG_CENTER | DLG_REVERSE);
add_widget (dd,
button_new (10, button_pos, B_CANCEL, NORMAL_BUTTON,
cancel_button, 0));
add_widget (dd,
button_new (9, button_pos, B_ENTER, DEFPUSH_BUTTON,
ok_button, 0));
case_sense = check_new (4, check_pos, *case_sensitive, case_label);
add_widget (dd, case_sense);
c = check_new (3, check_pos, *reverse, reverse_label);
add_widget (dd, c);
my_radio = radio_new (3, 3, SORT_TYPES, sort_orders_names);
my_radio->sel = my_radio->pos = current_mode;
add_widget (dd, my_radio);
run_dlg (dd);
r = dd->ret_value;
if (r != B_CANCEL) {
result = (sortfn *) sort_orders[my_radio->sel].sort_fn;
*reverse = c->state & C_BOOL;
*case_sensitive = case_sense->state & C_BOOL;
} else
result = sort_fn;
destroy_dlg (dd);
return result;
}
#define CONFY 11
#define CONFX 46
static int my_delete;
static int my_directory_hotlist_delete;
static int my_overwrite;
static int my_execute;
static int my_exit;
static QuickWidget conf_widgets [] = {
{ quick_button, 4, 6, 4, CONFY, N_("&Cancel"),
0, B_CANCEL, 0, 0, NULL },
{ quick_button, 4, 6, 3, CONFY, N_("&OK"),
0, B_ENTER, 0, 0, NULL },
{ quick_checkbox, 1, 13, 7, CONFY, N_(" confirm di&Rectory hotlist delete "),
11, 0, &my_directory_hotlist_delete, NULL, NULL },
{ quick_checkbox, 1, 13, 6, CONFY, N_(" confirm &Exit "),
9, 0, &my_exit, 0, NULL },
{ quick_checkbox, 1, 13, 5, CONFY, N_(" confirm e&Xecute "),
10, 0, &my_execute, 0, NULL },
{ quick_checkbox, 1, 13, 4, CONFY, N_(" confirm o&Verwrite "),
10, 0, &my_overwrite, 0, NULL },
{ quick_checkbox, 1, 13, 3, CONFY, N_(" confirm &Delete "),
9, 0, &my_delete, 0, NULL },
NULL_QuickWidget
};
static QuickDialog confirmation =
{ CONFX, CONFY, -1, -1, N_(" Confirmation "), "[Confirmation]",
conf_widgets, 0
};
void
confirm_box (void)
{
#ifdef ENABLE_NLS
static int i18n_flag = 0;
if (!i18n_flag)
{
register int i = sizeof(conf_widgets)/sizeof(QuickWidget) - 1;
int l1, maxlen = 0;
while (i--)
{
conf_widgets [i].text = _(conf_widgets [i].text);
l1 = strlen (conf_widgets [i].text) + 3;
if (l1 > maxlen)
maxlen = l1;
}
/*
* If buttons start on 4/6, checkboxes (with some add'l space)
* must take not more than it.
*/
confirmation.xlen = (maxlen + 5) * 6 / 4;
/*
* And this for the case when buttons with some space to the right
* do not fit within 2/6
*/
l1 = strlen (conf_widgets [0].text) + 3;
i = strlen (conf_widgets [1].text) + 5;
if (i > l1)
l1 = i;
i = (l1 + 3) * 6 / 2;
if (i > confirmation.xlen)
confirmation.xlen = i;
confirmation.title = _(confirmation.title);
i18n_flag = confirmation.i18n = 1;
}
#endif /* ENABLE_NLS */
my_delete = confirm_delete;
my_overwrite = confirm_overwrite;
my_execute = confirm_execute;
my_exit = confirm_exit;
my_directory_hotlist_delete = confirm_directory_hotlist_delete;
if (quick_dialog (&confirmation) != B_CANCEL){
confirm_delete = my_delete;
confirm_overwrite = my_overwrite;
confirm_execute = my_execute;
confirm_exit = my_exit;
confirm_directory_hotlist_delete = my_directory_hotlist_delete;
}
}
#define DISPY 11
#define DISPX 46
#ifndef HAVE_CHARSET
static int new_mode;
static int new_meta;
static const char *display_bits_str [] =
{ N_("Full 8 bits output"), N_("ISO 8859-1"), N_("7 bits") };
static QuickWidget display_widgets [] = {
{ quick_button, 4, 6, 4, DISPY, N_("&Cancel"),
0, B_CANCEL, 0, 0, NULL },
{ quick_button, 4, 6, 3, DISPY, N_("&OK"),
0, B_ENTER, 0, 0, NULL },
{ quick_checkbox, 4, DISPX, 7, DISPY, N_("F&ull 8 bits input"),
0, 0, &new_meta, 0, NULL },
{ quick_radio, 4, DISPX, 3, DISPY, "", 3, 0,
&new_mode, const_cast(char **, display_bits_str), NULL },
NULL_QuickWidget
};
static QuickDialog display_bits =
{ DISPX, DISPY, -1, -1, N_(" Display bits "), "[Display bits]",
display_widgets, 0 };
void
display_bits_box (void)
{
int current_mode;
#ifdef ENABLE_NLS
static int i18n_flag = 0;
if (!i18n_flag)
{
register int i;
int l1, maxlen = 0;
for (i = 0; i < 3; i++)
{
display_widgets [i].text = _(display_widgets[i].text);
display_bits_str [i] = _(display_bits_str [i]);
l1 = strlen (display_bits_str [i]);
if (l1 > maxlen)
maxlen = l1;
}
l1 = strlen (display_widgets [2].text);
if (l1 > maxlen)
maxlen = l1;
display_bits.xlen = (maxlen + 5) * 6 / 4;
/* See above confirm_box */
l1 = strlen (display_widgets [0].text) + 3;
i = strlen (display_widgets [1].text) + 5;
if (i > l1)
l1 = i;
i = (l1 + 3) * 6 / 2;
if (i > display_bits.xlen)
display_bits.xlen = i;
display_bits.title = _(display_bits.title);
i18n_flag = display_bits.i18n = 1;
}
#endif /* ENABLE_NLS */
if (full_eight_bits)
current_mode = 0;
else if (eight_bit_clean)
current_mode = 1;
else
current_mode = 2;
display_widgets [3].value = current_mode;
new_meta = !use_8th_bit_as_meta;
if (quick_dialog (&display_bits) != B_ENTER)
return;
eight_bit_clean = new_mode < 2;
full_eight_bits = new_mode == 0;
#ifndef HAVE_SLANG
meta (stdscr, eight_bit_clean);
#else
SLsmg_Display_Eight_Bit = full_eight_bits ? 128 : 160;
#endif
use_8th_bit_as_meta = !new_meta;
}
#else /* HAVE_CHARSET */
static int new_display_codepage;
static WLabel *cplabel;
static WCheck *inpcheck;
static int
sel_charset_button (int action)
{
const char *cpname;
char buf[64];
new_display_codepage = select_charset (new_display_codepage, 1);
cpname = (new_display_codepage < 0)
? _("Other 8 bit")
: codepages[new_display_codepage].name;
/* avoid strange bug with label repainting */
g_snprintf (buf, sizeof (buf), "%-27s", cpname);
label_set_text (cplabel, buf);
return 0;
}
static Dlg_head *
init_disp_bits_box (void)
{
const char *cpname;
Dlg_head *dbits_dlg;
do_refresh ();
dbits_dlg =
create_dlg (0, 0, DISPY, DISPX, dialog_colors, NULL,
"[Display bits]", _(" Display bits "), DLG_CENTER | DLG_REVERSE);
add_widget (dbits_dlg,
label_new (3, 4, _("Input / display codepage:")));
cpname = (new_display_codepage < 0)
? _("Other 8 bit")
: codepages[new_display_codepage].name;
cplabel = label_new (4, 4, cpname);
add_widget (dbits_dlg, cplabel);
add_widget (dbits_dlg,
button_new (DISPY - 3, DISPX / 2 + 3, B_CANCEL,
NORMAL_BUTTON, _("&Cancel"), 0));
add_widget (dbits_dlg,
button_new (DISPY - 3, 7, B_ENTER, NORMAL_BUTTON, _("&OK"),
0));
inpcheck =
check_new (6, 4, !use_8th_bit_as_meta, _("F&ull 8 bits input"));
add_widget (dbits_dlg, inpcheck);
cpname = _("&Select");
add_widget (dbits_dlg,
button_new (4, DISPX - 8 - strlen (cpname), B_USER,
NORMAL_BUTTON, cpname, sel_charset_button));
return dbits_dlg;
}
void
display_bits_box (void)
{
Dlg_head *dbits_dlg;
new_display_codepage = display_codepage;
application_keypad_mode ();
dbits_dlg = init_disp_bits_box ();
run_dlg (dbits_dlg);
if (dbits_dlg->ret_value == B_ENTER) {
const char *errmsg;
display_codepage = new_display_codepage;
errmsg =
init_translation_table (source_codepage, display_codepage);
if (errmsg)
message (1, MSG_ERROR, "%s", errmsg);
#ifndef HAVE_SLANG
meta (stdscr, display_codepage != 0);
#else
SLsmg_Display_Eight_Bit = (display_codepage != 0
&& display_codepage != 1) ? 128 : 160;
#endif
use_8th_bit_as_meta = !(inpcheck->state & C_BOOL);
}
destroy_dlg (dbits_dlg);
repaint_screen ();
}
#endif /* HAVE_CHARSET */
#define TREE_Y 20
#define TREE_X 60
static cb_ret_t
tree_callback (struct Dlg_head *h, dlg_msg_t msg, int parm)
{
switch (msg) {
case DLG_POST_KEY:
/* The enter key will be processed by the tree widget */
if (parm == '\n') {
h->ret_value = B_ENTER;
dlg_stop (h);
}
return MSG_HANDLED;
default:
return default_dlg_callback (h, msg, parm);
}
}
/* Show tree in a box, not on a panel */
char *
tree_box (const char *current_dir)
{
WTree *mytree;
Dlg_head *dlg;
char *val;
WButtonBar *bar;
/* Create the components */
dlg = create_dlg (0, 0, TREE_Y, TREE_X, dialog_colors,
tree_callback, "[Directory Tree]", NULL, DLG_CENTER | DLG_REVERSE);
mytree = tree_new (0, 2, 2, TREE_Y - 6, TREE_X - 5);
add_widget (dlg, mytree);
bar = buttonbar_new(1);
add_widget (dlg, bar);
((Widget *) bar)->x = 0;
((Widget *) bar)->y = LINES - 1;
run_dlg (dlg);
if (dlg->ret_value == B_ENTER)
val = g_strdup (tree_selected_name (mytree));
else
val = 0;
destroy_dlg (dlg);
return val;
}
#ifdef USE_VFS
#if defined(USE_NETCODE)
#define VFSY 17
#define VFS_WIDGETBASE 10
#else
#define VFSY 8
#define VFS_WIDGETBASE 0
#endif
#define VFSX 56
static char *ret_timeout;
#if defined(USE_NETCODE)
static char *ret_passwd;
static char *ret_directory_timeout;
static char *ret_ftp_proxy;
static int ret_use_netrc;
static int ret_ftpfs_use_passive_connections;
static int ret_ftpfs_use_passive_connections_over_proxy;
#endif
static QuickWidget confvfs_widgets [] = {
{ quick_button, 30, VFSX, VFSY - 3, VFSY, N_("&Cancel"),
0, B_CANCEL, 0, 0, NULL },
{ quick_button, 12, VFSX, VFSY - 3, VFSY, N_("&OK"),
0, B_ENTER, 0, 0, NULL },
#if defined(USE_NETCODE)
{ quick_checkbox, 4, VFSX, 12, VFSY, N_("Use passive mode over pro&xy"), 0, 0,
&ret_ftpfs_use_passive_connections_over_proxy, 0, NULL },
{ quick_checkbox, 4, VFSX, 11, VFSY, N_("Use &passive mode"), 0, 0,
&ret_ftpfs_use_passive_connections, 0, NULL },
{ quick_checkbox, 4, VFSX, 10, VFSY, N_("&Use ~/.netrc"), 0, 0,
&ret_use_netrc, 0, NULL },
{ quick_input, 4, VFSX, 9, VFSY, "", 48, 0, 0, &ret_ftp_proxy,
"input-ftp-proxy" },
{ quick_checkbox, 4, VFSX, 8, VFSY, N_("&Always use ftp proxy"), 0, 0,
&ftpfs_always_use_proxy, 0, NULL },
{ quick_label, 49, VFSX, 7, VFSY, N_("sec"),
0, 0, 0, 0, NULL },
{ quick_input, 38, VFSX, 7, VFSY, "", 10, 0, 0, &ret_directory_timeout,
"input-timeout" },
{ quick_label, 4, VFSX, 7, VFSY, N_("ftpfs directory cache timeout:"),
0, 0, 0, 0, NULL },
{ quick_input, 4, VFSX, 6, VFSY, "", 48, 0, 0, &ret_passwd,
"input-passwd" },
{ quick_label, 4, VFSX, 5, VFSY, N_("ftp anonymous password:"),
0, 0, 0, 0, NULL },
#endif
{ quick_label, 49, VFSX, 3, VFSY, "sec",
0, 0, 0, 0, NULL },
{ quick_input, 38, VFSX, 3, VFSY, "", 10, 0, 0, &ret_timeout,
"input-timo-vfs" },
{ quick_label, 4, VFSX, 3, VFSY, N_("Timeout for freeing VFSs:"),
0, 0, 0, 0, NULL },
NULL_QuickWidget
};
static QuickDialog confvfs_dlg =
{ VFSX, VFSY, -1, -1, N_(" Virtual File System Setting "),
"[Virtual FS]", confvfs_widgets, 0 };
void
configure_vfs (void)
{
char buffer2[BUF_TINY];
#if defined(USE_NETCODE)
char buffer3[BUF_TINY];
ret_use_netrc = use_netrc;
ret_ftpfs_use_passive_connections = ftpfs_use_passive_connections;
ret_ftpfs_use_passive_connections_over_proxy = ftpfs_use_passive_connections_over_proxy;
g_snprintf(buffer3, sizeof (buffer3), "%i", ftpfs_directory_timeout);
confvfs_widgets[8].text = buffer3;
confvfs_widgets[10].text = ftpfs_anonymous_passwd;
confvfs_widgets[5].text = ftpfs_proxy_host;
#endif
g_snprintf (buffer2, sizeof (buffer2), "%i", vfs_timeout);
confvfs_widgets [3 + VFS_WIDGETBASE].text = buffer2;
if (quick_dialog (&confvfs_dlg) != B_CANCEL) {
vfs_timeout = atoi (ret_timeout);
g_free (ret_timeout);
if (vfs_timeout < 0 || vfs_timeout > 10000)
vfs_timeout = 10;
#if defined(USE_NETCODE)
g_free (ftpfs_anonymous_passwd);
ftpfs_anonymous_passwd = ret_passwd;
g_free (ftpfs_proxy_host);
ftpfs_proxy_host = ret_ftp_proxy;
ftpfs_directory_timeout = atoi(ret_directory_timeout);
use_netrc = ret_use_netrc;
ftpfs_use_passive_connections = ret_ftpfs_use_passive_connections;
ftpfs_use_passive_connections_over_proxy = ret_ftpfs_use_passive_connections_over_proxy;
g_free (ret_directory_timeout);
#endif
}
}
#endif /* USE_VFS */
char *
cd_dialog (void)
{
QuickDialog Quick_input;
QuickWidget quick_widgets [] = {
{ quick_input, 6, 57, 2, 0, "", 50, 0, 0, 0, "input" },
{ quick_label, 3, 57, 2, 0, "", 0, 0, 0, 0, NULL },
NULL_QuickWidget
};
char *my_str;
int len;
Quick_input.xlen = 57;
Quick_input.title = _("Quick cd");
Quick_input.help = "[Quick cd]";
quick_widgets [0].value = 2; /* want cd like completion */
quick_widgets [1].text = _("cd");
quick_widgets [1].y_divisions =
quick_widgets [0].y_divisions = Quick_input.ylen = 5;
len = strlen (quick_widgets [1].text);
quick_widgets [0].relative_x =
quick_widgets [1].relative_x + len + 1;
Quick_input.xlen = len + quick_widgets [0].hotkey_pos + 7;
quick_widgets [0].x_divisions =
quick_widgets [1].x_divisions = Quick_input.xlen;
Quick_input.i18n = 1;
Quick_input.xpos = 2;
Quick_input.ypos = LINES - 2 - Quick_input.ylen;
quick_widgets [0].str_result = &my_str;
Quick_input.widgets = quick_widgets;
if (quick_dialog (&Quick_input) != B_CANCEL){
return my_str;
} else
return 0;
}
void
symlink_dialog (const char *existing, const char *new, char **ret_existing,
char **ret_new)
{
QuickDialog Quick_input;
QuickWidget quick_widgets[] = {
{quick_button, 50, 80, 6, 8, N_("&Cancel"), 0, B_CANCEL, 0, 0,
NULL},
{quick_button, 16, 80, 6, 8, N_("&OK"), 0, B_ENTER, 0, 0, NULL},
{quick_input, 4, 80, 5, 8, "", 58, 0, 0, 0, "input-1"},
{quick_label, 4, 80, 4, 8, N_("Symbolic link filename:"), 0, 0, 0,
0, NULL},
{quick_input, 4, 80, 3, 8, "", 58, 0, 0, 0, "input-2"},
{quick_label, 4, 80, 2, 8,
N_("Existing filename (filename symlink will point to):"), 0, 0,
0, 0, NULL},
NULL_QuickWidget
};
Quick_input.xlen = 64;
Quick_input.ylen = 12;
Quick_input.title = N_("Symbolic link");
Quick_input.help = "[File Menu]";
Quick_input.i18n = 0;
quick_widgets[2].text = new;
quick_widgets[4].text = existing;
Quick_input.xpos = -1;
quick_widgets[2].str_result = ret_new;
quick_widgets[4].str_result = ret_existing;
Quick_input.widgets = quick_widgets;
if (quick_dialog (&Quick_input) == B_CANCEL) {
*ret_new = NULL;
*ret_existing = NULL;
}
}
#ifdef WITH_BACKGROUND
#define B_STOP (B_USER+1)
#define B_RESUME (B_USER+2)
#define B_KILL (B_USER+3)
static int JOBS_X = 60;
#define JOBS_Y 15
static WListbox *bg_list;
static Dlg_head *jobs_dlg;
static void
jobs_fill_listbox (void)
{
static const char *state_str [2];
TaskList *tl = task_list;
if (!state_str [0]){
state_str [0] = _("Running ");
state_str [1] = _("Stopped");
}
while (tl){
char *s;
s = g_strconcat (state_str [tl->state], " ", tl->info, (char *) NULL);
listbox_add_item (bg_list, LISTBOX_APPEND_AT_END, 0, s, (void *) tl);
g_free (s);
tl = tl->next;
}
}
static int
task_cb (int action)
{
TaskList *tl;
int sig = 0;
if (!bg_list->list)
return 0;
/* Get this instance information */
tl = (TaskList *) bg_list->current->data;
# ifdef SIGTSTP
if (action == B_STOP){
sig = SIGSTOP;
tl->state = Task_Stopped;
} else if (action == B_RESUME){
sig = SIGCONT;
tl->state = Task_Running;
} else
# endif
if (action == B_KILL){
sig = SIGKILL;
}
if (sig == SIGINT)
unregister_task_running (tl->pid, tl->fd);
kill (tl->pid, sig);
listbox_remove_list (bg_list);
jobs_fill_listbox ();
/* This can be optimized to just redraw this widget :-) */
dlg_redraw (jobs_dlg);
return 0;
}
static struct
{
const char* name;
int xpos;
int value;
int (*callback)(int);
}
job_buttons [] =
{
{N_("&Stop"), 3, B_STOP, task_cb},
{N_("&Resume"), 12, B_RESUME, task_cb},
{N_("&Kill"), 23, B_KILL, task_cb},
{N_("&OK"), 35, B_CANCEL, NULL }
};
void
jobs_cmd (void)
{
register int i;
int n_buttons = sizeof (job_buttons) / sizeof (job_buttons[0]);
#ifdef ENABLE_NLS
static int i18n_flag = 0;
if (!i18n_flag)
{
int startx = job_buttons [0].xpos;
int len;
for (i = 0; i < n_buttons; i++)
{
job_buttons [i].name = _(job_buttons [i].name);
len = strlen (job_buttons [i].name) + 4;
JOBS_X = max (JOBS_X, startx + len + 3);
job_buttons [i].xpos = startx;
startx += len;
}
/* Last button - Ok a.k.a. Cancel :) */
job_buttons [n_buttons - 1].xpos =
JOBS_X - strlen (job_buttons [n_buttons - 1].name) - 7;
i18n_flag = 1;
}
#endif /* ENABLE_NLS */
jobs_dlg = create_dlg (0, 0, JOBS_Y, JOBS_X, dialog_colors, NULL,
"[Background jobs]", _("Background Jobs"),
DLG_CENTER | DLG_REVERSE);
bg_list = listbox_new (2, 3, JOBS_X-7, JOBS_Y-9, 0);
add_widget (jobs_dlg, bg_list);
i = n_buttons;
while (i--)
{
add_widget (jobs_dlg, button_new (JOBS_Y-4,
job_buttons [i].xpos, job_buttons [i].value,
NORMAL_BUTTON, job_buttons [i].name,
job_buttons [i].callback));
}
/* Insert all of task information in the list */
jobs_fill_listbox ();
run_dlg (jobs_dlg);
destroy_dlg (jobs_dlg);
}
#endif /* WITH_BACKGROUND */
#ifdef WITH_SMBFS
struct smb_authinfo *
vfs_smb_get_authinfo (const char *host, const char *share, const char *domain,
const char *user)
{
static int dialog_x = 44;
enum { b0 = 3, dialog_y = 12};
struct smb_authinfo *return_value;
static const char* labs[] = {N_("Domain:"), N_("Username:"), N_("Password:")};
static const char* buts[] = {N_("&OK"), N_("&Cancel")};
static int ilen = 30, istart = 14;
static int b2 = 30;
char *title;
WInput *in_password;
WInput *in_user;
WInput *in_domain;
Dlg_head *auth_dlg;
#ifdef ENABLE_NLS
static int i18n_flag = 0;
if (!i18n_flag)
{
register int i = sizeof(labs)/sizeof(labs[0]);
int l1, maxlen = 0;
while (i--)
{
l1 = strlen (labs [i] = _(labs [i]));
if (l1 > maxlen)
maxlen = l1;
}
i = maxlen + ilen + 7;
if (i > dialog_x)
dialog_x = i;
for (i = sizeof(buts)/sizeof(buts[0]), l1 = 0; i--; )
{
l1 += strlen (buts [i] = _(buts [i]));
}
l1 += 15;
if (l1 > dialog_x)
dialog_x = l1;
ilen = dialog_x - 7 - maxlen; /* for the case of very long buttons :) */
istart = dialog_x - 3 - ilen;
b2 = dialog_x - (strlen(buts[1]) + 6);
i18n_flag = 1;
}
#endif /* ENABLE_NLS */
if (!domain)
domain = "";
if (!user)
user = "";
title = g_strdup_printf (_("Password for \\\\%s\\%s"), host, share);
auth_dlg = create_dlg (0, 0, dialog_y, dialog_x, dialog_colors, NULL,
"[Smb Authinfo]", title, DLG_CENTER | DLG_REVERSE);
g_free (title);
in_user = input_new (5, istart, INPUT_COLOR, ilen, user, "auth_name");
add_widget (auth_dlg, in_user);
in_domain = input_new (3, istart, INPUT_COLOR, ilen, domain, "auth_domain");
add_widget (auth_dlg, in_domain);
add_widget (auth_dlg, button_new (9, b2, B_CANCEL, NORMAL_BUTTON,
buts[1], 0));
add_widget (auth_dlg, button_new (9, b0, B_ENTER, DEFPUSH_BUTTON,
buts[0], 0));
in_password = input_new (7, istart, INPUT_COLOR, ilen, "", "auth_password");
in_password->completion_flags = 0;
in_password->is_password = 1;
add_widget (auth_dlg, in_password);
add_widget (auth_dlg, label_new (7, 3, labs[2]));
add_widget (auth_dlg, label_new (5, 3, labs[1]));
add_widget (auth_dlg, label_new (3, 3, labs[0]));
run_dlg (auth_dlg);
switch (auth_dlg->ret_value) {
case B_CANCEL:
return_value = 0;
break;
default:
return_value = g_new (struct smb_authinfo, 1);
if (return_value) {
return_value->host = g_strdup (host);
return_value->share = g_strdup (share);
return_value->domain = g_strdup (in_domain->buffer);
return_value->user = g_strdup (in_user->buffer);
return_value->password = g_strdup (in_password->buffer);
}
}
destroy_dlg (auth_dlg);
return return_value;
}
#endif /* WITH_SMBFS */
| dborca/mc | src/boxes.c | C | gpl-2.0 | 28,814 |
#include<pkg/common/PeriodicEngines.hpp>
#include<core/PartialEngine.hpp>
#include<pkg/common/Sphere.hpp>
#ifdef YADE_OPENGL
#include<pkg/common/OpenGLRenderer.hpp>
#endif
namespace yade { // Cannot have #include directive inside.
class DomainLimiter: public PeriodicEngine{
public:
virtual void action();
// clang-format off
YADE_CLASS_BASE_DOC_ATTRS(DomainLimiter,PeriodicEngine,"Delete particles that are out of axis-aligned box given by *lo* and *hi*.",
((Vector3r,lo,Vector3r(0,0,0),,"Lower corner of the domain."))
((Vector3r,hi,Vector3r(0,0,0),,"Upper corner of the domain."))
((long,nDeleted,0,Attr::readonly,"Cummulative number of particles deleted."))
((Real,mDeleted,0,,"Mass of deleted particles."))
((Real,vDeleted,0,,"Volume of deleted spheres (clumps not counted, in that case check :yref:`mDeleted<DomainLimiter.mDeleted>`)"))
((int,mask,-1,,"If mask is defined, only particles with corresponding groupMask will be deleted."))
);
// clang-format on
};
REGISTER_SERIALIZABLE(DomainLimiter);
class LawTester: public PartialEngine{
Body::id_t id1,id2; // shorthands for local use
public:
void init();
virtual void action();
void postLoad(LawTester&);
void warnDeprec(const string& s1, const string& s2){ if(!warnedDeprecPtRot){ warnedDeprecPtRot=true; LOG_WARN("LawTester."<<s1<<" is deprecated, use LawTester."<<s2<<" instead.");} }
Vector3r get_ptOurs(){ warnDeprec("ptOurs","uTest.head()"); return uTest.head<3>(); } Vector3r get_ptGeom(){ warnDeprec("ptGeom","uGeom.head()"); return uGeom.head<3>(); }
Vector3r get_rotOurs(){ warnDeprec("rotOurs","uTest.tail()"); return uTest.tail<3>(); } Vector3r get_rotGeom(){ warnDeprec("rotGeom","uGeom.tail()"); return uGeom.tail<3>(); }
DECLARE_LOGGER;
// clang-format off
YADE_CLASS_BASE_DOC_ATTRS_INIT_CTOR_PY(LawTester,PartialEngine,"Prescribe and apply deformations of an interaction in terms of local normal and shear displacements and rotations (using either :yref:`disPpath<LawTester.disPath>` and :yref:`rotPath<LawTester.rotPath>` [or :yref:`path<LawTester.path>` in the future]). Supported :yref:`IGeom` types are :yref:`ScGeom`, :yref:`L3Geom` and :yref:`L6Geom`. \n\nSee :ysrc:`scripts/test/law-test.py` for an example.",
((vector<Vector3r>,disPath,,Attr::triggerPostLoad,"Loading path, where each Vector3 contains desired normal displacement and two components of the shear displacement (in local coordinate system, which is being tracked automatically. If shorter than :yref:`rotPath<LawTester.rotPath>`, the last value is repeated."))
((vector<Vector3r>,rotPath,,Attr::triggerPostLoad,"Rotational components of the loading path, where each item contains torsion and two bending rotations in local coordinates. If shorter than :yref:`path<LawTester.path>`, the last value is repeated."))
((vector<string>,hooks,,,"Python commands to be run when the corresponding point in path is reached, before doing other things in that particular step. See also :yref:`doneHook<LawTester.doneHook>`. "))
((Vector6r,uGeom,Vector6r::Zero(),,"Current generalized displacements (3 displacements, 3 rotations), as stored in the interation itself. They should corredpond to :yref:`uTest<LawTester.uTest>`, otherwise a bug is indicated."))
((Vector6r,uTest,Vector6r::Zero(),,"Current generalized displacements (3 displacements, 3 rotations), as they should be according to this :yref:`LawTester`. Should correspond to :yref:`uGeom<LawTester.uGeom>`."))
((Vector6r,uTestNext,Vector6r::Zero(),Attr::hidden,"The value of uTest in the next step; since uTest is computed before uGeom is updated (in the next time step), uTest and uGeom would be always shifted by one timestep."))
((bool,warnedDeprecPtRot,false,Attr::hidden,"Flag to say that the user was already warned about using deprecated ptOurg/ptGeom/rotOurs/rotGeom."))
((Vector3r,shearTot,Vector3r::Zero(),Attr::hidden,"Current displacement in global coordinates; only used internally with ScGeom."))
((bool,displIsRel,true,,"Whether displacement values in *disPath* are normalized by reference contact length (r1+r2 for 2 spheres)."))
//((Vector3i,forceControl,Vector3i::Zero(),,"Select which components of path (non-zero value) have force (stress) rather than displacement (strain) meaning."))
((vector<int>,pathSteps,((void)"(constant step)",vector<int>(1,1)),Attr::triggerPostLoad,"Step number for corresponding values in :yref:`path<LawTester.path>`; if shorter than path, distance between last 2 values is used for the rest."))
((vector<int>,_pathT,,(Attr::readonly|Attr::noSave),"Time value corresponding to points on path, computed from *pathSteps*. Length is always the same as path."))
((vector<Vector6r>,_path,,(Attr::readonly|Attr::noSave),"Generalized displacement path values, computed from *disPath* and *rotPath* by appending zero initial value, and possibly repeating the last value to make lengths of *disPath* and *rotPath* match."))
((shared_ptr<Interaction>,I,,(Attr::hidden),"Interaction object being tracked."))
// axX, axY, axZ could be replaced by references to rows in trsf; perhaps do that in the future (in such a case, trsf would not be noSave)
((Vector3r,axX,,Attr::hidden,"Local x-axis in global coordinates (normal of the contact) |yupdate|"))
((Vector3r,axY,,Attr::hidden,"Local y-axis in global coordinates; perpendicular to axX; initialized arbitrarily, but tracked to be consistent. |yupdate|"))
((Vector3r,axZ,,(Attr::hidden|Attr::noSave),"Local z-axis in global coordinates; computed from axX and axY. |yupdate|"))
((Matrix3r,trsf,,(Attr::noSave|Attr::readonly),"Transformation matrix for the local coordinate system. |yupdate|"))
((size_t,_interpPos,0,(Attr::readonly|Attr::hidden),"State cookie for the interpolation routine."))
((Vector6r,uuPrev,Vector6r::Zero(),(Attr::readonly),"Generalized displacement values reached in the previous step, for knowing which increment to apply in the current step."))
((int,step,1,,"Step number in which this engine is active; determines position in path, using pathSteps."))
((string,doneHook,,,"Python command (as string) to run when end of the path is achieved. If empty, the engine will be set :yref:`dead<Engine.dead>`."))
((Real,renderLength,0,,"Characteristic length for the purposes of rendering, set equal to the smaller radius."))
((Real,refLength,0,(Attr::readonly),"Reference contact length, for rendering only."))
((Vector3r,contPt,Vector3r::Zero(),Attr::hidden,"Contact point (for rendering only)"))
((Real,idWeight,1,,"Float, usually ∈〈0,1〉, determining on how are displacements distributed between particles (0 for id1, 1 for id2); intermediate values will apply respective part to each of them. This parameter is ignored with 6-DoFs :yref:`IGeom`."))
((Real,rotWeight,1,,"Float ∈〈0,1〉 determining whether shear displacement is applied as rotation or displacement on arc (0 is displacement-only, 1 is rotation-only). Not effective when mutual rotation is specified."))
// reset force components along individual axes, instead of blocking DOFs which have no specific direction (for the force control)
, /* init */
, /* ctor */
, /* py */ .add_property("ptOurs",&LawTester::get_ptOurs,"first 3 components of uTest |ydeprecated|") .add_property("ptGeom",&LawTester::get_ptGeom,"first 3 components of uGeom |ydeprecated|") .add_property("rotOurs",&LawTester::get_rotOurs,"last 3 components of uTest |ydeprecated|") .add_property("rotGeom",&LawTester::get_rotGeom,"last 3 components of uGeom |ydeprecated|")
);
// clang-format on
};
REGISTER_SERIALIZABLE(LawTester);
#ifdef YADE_OPENGL
class GlExtra_LawTester: public GlExtraDrawer{
public:
DECLARE_LOGGER;
virtual void render();
// clang-format off
YADE_CLASS_BASE_DOC_ATTRS(GlExtra_LawTester,GlExtraDrawer,"Find an instance of :yref:`LawTester` and show visually its data.",
((shared_ptr<LawTester>,tester,,,"Associated :yref:`LawTester` object."))
);
// clang-format on
};
REGISTER_SERIALIZABLE(GlExtra_LawTester);
class GlExtra_OctreeCubes: public GlExtraDrawer{
public:
struct OctreeBox{ Vector3r center, extents; int fill; int level; };
std::vector<OctreeBox> boxes;
void postLoad(GlExtra_OctreeCubes&);
virtual void render();
// clang-format off
YADE_CLASS_BASE_DOC_ATTRS(GlExtra_OctreeCubes,GlExtraDrawer,"Render boxed read from file",
((string,boxesFile,,Attr::triggerPostLoad,"File to read boxes from; ascii files with ``x0 y0 z0 x1 y1 z1 c`` records, where ``c`` is an integer specifying fill (0 for wire, 1 for filled)."))
((Vector2i,fillRangeFill,Vector2i(2,2),,"Range of fill indices that will be filled."))
((Vector2i,fillRangeDraw,Vector2i(-2,2),,"Range of fill indices that will be rendered."))
((Vector2i,levelRangeDraw,Vector2i(-2,2),,"Range of levels that will be rendered."))
((bool,noFillZero,true,,"Do not fill 0-fill boxed (those that are further subdivided)"))
);
// clang-format on
};
REGISTER_SERIALIZABLE(GlExtra_OctreeCubes);
#endif
} // namespace yade
| cosurgi/trunk | pkg/dem/DomainLimiter.hpp | C++ | gpl-2.0 | 8,978 |
/* ----------------------------------------------------------------------
* Project: CMSIS DSP Library
* Title: arm_mat_scale_q31.c
* Description: Multiplies a Q31 matrix by a scalar
*
* $Date: 18. March 2019
* $Revision: V1.6.0
*
* Target Processor: Cortex-M cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2010-2019 ARM Limited or its affiliates. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "arm_math.h"
/**
@ingroup groupMatrix
*/
/**
@addtogroup MatrixScale
@{
*/
/**
@brief Q31 matrix scaling.
@param[in] pSrc points to input matrix
@param[in] scaleFract fractional portion of the scale factor
@param[in] shift number of bits to shift the result by
@param[out] pDst points to output matrix structure
@return execution status
- \ref ARM_MATH_SUCCESS : Operation successful
- \ref ARM_MATH_SIZE_MISMATCH : Matrix size check failed
@par Scaling and Overflow Behavior
The input data <code>*pSrc</code> and <code>scaleFract</code> are in 1.31 format.
These are multiplied to yield a 2.62 intermediate result which is shifted with saturation to 1.31 format.
*/
arm_status arm_mat_scale_q31(
const arm_matrix_instance_q31 * pSrc,
q31_t scaleFract,
int32_t shift,
arm_matrix_instance_q31 * pDst)
{
q31_t *pIn = pSrc->pData; /* Input data matrix pointer */
q31_t *pOut = pDst->pData; /* Output data matrix pointer */
uint32_t numSamples; /* Total number of elements in the matrix */
uint32_t blkCnt; /* Loop counter */
arm_status status; /* Status of matrix scaling */
int32_t kShift = shift + 1; /* Shift to apply after scaling */
q31_t in, out; /* Temporary variabels */
#ifdef ARM_MATH_MATRIX_CHECK
/* Check for matrix mismatch condition */
if ((pSrc->numRows != pDst->numRows) ||
(pSrc->numCols != pDst->numCols) )
{
/* Set status as ARM_MATH_SIZE_MISMATCH */
status = ARM_MATH_SIZE_MISMATCH;
}
else
#endif /* #ifdef ARM_MATH_MATRIX_CHECK */
{
/* Total number of samples in input matrix */
numSamples = (uint32_t) pSrc->numRows * pSrc->numCols;
#if defined (ARM_MATH_LOOPUNROLL)
/* Loop unrolling: Compute 4 outputs at a time */
blkCnt = numSamples >> 2U;
while (blkCnt > 0U)
{
/* C(m,n) = A(m,n) * k */
/* Scale, saturate and store result in destination buffer. */
in = *pIn++; /* read four inputs from source */
in = ((q63_t) in * scaleFract) >> 32; /* multiply input with scaler value */
out = in << kShift; /* apply shifting */
if (in != (out >> kShift)) /* saturate the results. */
out = 0x7FFFFFFF ^ (in >> 31);
*pOut++ = out; /* Store result destination */
in = *pIn++;
in = ((q63_t) in * scaleFract) >> 32;
out = in << kShift;
if (in != (out >> kShift))
out = 0x7FFFFFFF ^ (in >> 31);
*pOut++ = out;
in = *pIn++;
in = ((q63_t) in * scaleFract) >> 32;
out = in << kShift;
if (in != (out >> kShift))
out = 0x7FFFFFFF ^ (in >> 31);
*pOut++ = out;
in = *pIn++;
in = ((q63_t) in * scaleFract) >> 32;
out = in << kShift;
if (in != (out >> kShift))
out = 0x7FFFFFFF ^ (in >> 31);
*pOut++ = out;
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining outputs */
blkCnt = numSamples % 0x4U;
#else
/* Initialize blkCnt with number of samples */
blkCnt = numSamples;
#endif /* #if defined (ARM_MATH_LOOPUNROLL) */
while (blkCnt > 0U)
{
/* C(m,n) = A(m,n) * k */
/* Scale, saturate and store result in destination buffer. */
in = *pIn++;
in = ((q63_t) in * scaleFract) >> 32;
out = in << kShift;
if (in != (out >> kShift))
out = 0x7FFFFFFF ^ (in >> 31);
*pOut++ = out;
/* Decrement loop counter */
blkCnt--;
}
/* Set status as ARM_MATH_SUCCESS */
status = ARM_MATH_SUCCESS;
}
/* Return to application */
return (status);
}
/**
@} end of MatrixScale group
*/
| pingdynasty/OwlProgram | Libraries/CMSIS/DSP/Source/MatrixFunctions/arm_mat_scale_q31.c | C | gpl-2.0 | 5,299 |
/* This file is part of the project "Hilbert II" - http://www.qedeq.org
*
* Copyright 2000-2014, Michael Meyling <mime@qedeq.org>.
*
* "Hilbert II" is free software; you can redistribute
* it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.qedeq.kernel.bo.service.basis;
import org.qedeq.kernel.bo.module.InternalModuleServiceCall;
import org.qedeq.kernel.se.visitor.InterruptException;
/**
* Represents a service execution.
*
* @author Michael Meyling
*/
public interface ModuleServiceExecutor {
/**
* Execute service.
*
* @param call Parameters for service call and current execution status.
* @throws InterruptException User canceled call.
*/
public void executeService(InternalModuleServiceCall call) throws InterruptException;
}
| m-31/qedeq | QedeqKernelBo/src/org/qedeq/kernel/bo/service/basis/ModuleServiceExecutor.java | Java | gpl-2.0 | 1,198 |
# Copyright 2009-2010 by Peter Cock. All rights reserved.
# Based on code contributed and copyright 2009 by Jose Blanca (COMAV-UPV).
#
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Bio.SeqIO support for the binary Standard Flowgram Format (SFF) file format.
SFF was designed by 454 Life Sciences (Roche), the Whitehead Institute for
Biomedical Research and the Wellcome Trust Sanger Institute. You are expected
to use this module via the Bio.SeqIO functions under the format name "sff" (or
"sff-trim" as described below).
For example, to iterate over the records in an SFF file,
>>> from Bio import SeqIO
>>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff"):
... print record.id, len(record), record.seq[:20]+"..."
E3MFGYR02JWQ7T 265 tcagGGTCTACATGTTGGTT...
E3MFGYR02JA6IL 271 tcagTTTTTTTTGGAAAGGA...
E3MFGYR02JHD4H 310 tcagAAAGACAAGTGGTATC...
E3MFGYR02GFKUC 299 tcagCGGCCGGGCCTCTCAT...
E3MFGYR02FTGED 281 tcagTGGTAATGGGGGGAAA...
E3MFGYR02FR9G7 261 tcagCTCCGTAAGAAGGTGC...
E3MFGYR02GAZMS 278 tcagAAAGAAGTAAGGTAAA...
E3MFGYR02HHZ8O 221 tcagACTTTCTTCTTTACCG...
E3MFGYR02GPGB1 269 tcagAAGCAGTGGTATCAAC...
E3MFGYR02F7Z7G 219 tcagAATCATCCACTTTTTA...
Each SeqRecord object will contain all the annotation from the SFF file,
including the PHRED quality scores.
>>> print record.id, len(record)
E3MFGYR02F7Z7G 219
>>> print record.seq[:10], "..."
tcagAATCAT ...
>>> print record.letter_annotations["phred_quality"][:10], "..."
[22, 21, 23, 28, 26, 15, 12, 21, 28, 21] ...
Notice that the sequence is given in mixed case, the central upper case region
corresponds to the trimmed sequence. This matches the output of the Roche
tools (and the 3rd party tool sff_extract) for SFF to FASTA.
>>> print record.annotations["clip_qual_left"]
4
>>> print record.annotations["clip_qual_right"]
134
>>> print record.seq[:4]
tcag
>>> print record.seq[4:20], "...", record.seq[120:134]
AATCATCCACTTTTTA ... CAAAACACAAACAG
>>> print record.seq[134:]
atcttatcaacaaaactcaaagttcctaactgagacacgcaacaggggataagacaaggcacacaggggataggnnnnnnnnnnn
The annotations dictionary also contains any adapter clip positions
(usually zero), and information about the flows. e.g.
>>> print record.annotations["flow_key"]
TCAG
>>> print record.annotations["flow_values"][:10], "..."
(83, 1, 128, 7, 4, 84, 6, 106, 3, 172) ...
>>> print len(record.annotations["flow_values"])
400
>>> print record.annotations["flow_index"][:10], "..."
(1, 2, 3, 2, 2, 0, 3, 2, 3, 3) ...
>>> print len(record.annotations["flow_index"])
219
As a convenience method, you can read the file with SeqIO format name "sff-trim"
instead of "sff" to get just the trimmed sequences (without any annotation
except for the PHRED quality scores):
>>> from Bio import SeqIO
>>> for record in SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff-trim"):
... print record.id, len(record), record.seq[:20]+"..."
E3MFGYR02JWQ7T 260 GGTCTACATGTTGGTTAACC...
E3MFGYR02JA6IL 265 TTTTTTTTGGAAAGGAAAAC...
E3MFGYR02JHD4H 292 AAAGACAAGTGGTATCAACG...
E3MFGYR02GFKUC 295 CGGCCGGGCCTCTCATCGGT...
E3MFGYR02FTGED 277 TGGTAATGGGGGGAAATTTA...
E3MFGYR02FR9G7 256 CTCCGTAAGAAGGTGCTGCC...
E3MFGYR02GAZMS 271 AAAGAAGTAAGGTAAATAAC...
E3MFGYR02HHZ8O 150 ACTTTCTTCTTTACCGTAAC...
E3MFGYR02GPGB1 221 AAGCAGTGGTATCAACGCAG...
E3MFGYR02F7Z7G 130 AATCATCCACTTTTTAACGT...
Looking at the final record in more detail, note how this differs to the
example above:
>>> print record.id, len(record)
E3MFGYR02F7Z7G 130
>>> print record.seq[:10], "..."
AATCATCCAC ...
>>> print record.letter_annotations["phred_quality"][:10], "..."
[26, 15, 12, 21, 28, 21, 36, 28, 27, 27] ...
>>> print record.annotations
{}
You might use the Bio.SeqIO.convert() function to convert the (trimmed) SFF
reads into a FASTQ file (or a FASTA file and a QUAL file), e.g.
>>> from Bio import SeqIO
>>> from StringIO import StringIO
>>> out_handle = StringIO()
>>> count = SeqIO.convert("Roche/E3MFGYR02_random_10_reads.sff", "sff",
... out_handle, "fastq")
>>> print "Converted %i records" % count
Converted 10 records
The output FASTQ file would start like this:
>>> print "%s..." % out_handle.getvalue()[:50]
@E3MFGYR02JWQ7T
tcagGGTCTACATGTTGGTTAACCCGTACTGATT...
Bio.SeqIO.index() provides memory efficient random access to the reads in an
SFF file by name. SFF files can include an index within the file, which can
be read in making this very fast. If the index is missing (or in a format not
yet supported in Biopython) the file is indexed by scanning all the reads -
which is a little slower. For example,
>>> from Bio import SeqIO
>>> reads = SeqIO.index("Roche/E3MFGYR02_random_10_reads.sff", "sff")
>>> record = reads["E3MFGYR02JHD4H"]
>>> print record.id, len(record), record.seq[:20]+"..."
E3MFGYR02JHD4H 310 tcagAAAGACAAGTGGTATC...
Or, using the trimmed reads:
>>> from Bio import SeqIO
>>> reads = SeqIO.index("Roche/E3MFGYR02_random_10_reads.sff", "sff-trim")
>>> record = reads["E3MFGYR02JHD4H"]
>>> print record.id, len(record), record.seq[:20]+"..."
E3MFGYR02JHD4H 292 AAAGACAAGTGGTATCAACG...
You can also use the Bio.SeqIO.write() function with the "sff" format. Note
that this requires all the flow information etc, and thus is probably only
useful for SeqRecord objects originally from reading another SFF file (and
not the trimmed SeqRecord objects from parsing an SFF file as "sff-trim").
As an example, let's pretend this example SFF file represents some DNA which
was pre-amplified with a PCR primers AAAGANNNNN. The following script would
produce a sub-file containing all those reads whose post-quality clipping
region (i.e. the sequence after trimming) starts with AAAGA exactly (the non-
degenerate bit of this pretend primer):
>>> from Bio import SeqIO
>>> records = (record for record in
... SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff","sff")
... if record.seq[record.annotations["clip_qual_left"]:].startswith("AAAGA"))
>>> count = SeqIO.write(records, "temp_filtered.sff", "sff")
>>> print "Selected %i records" % count
Selected 2 records
Of course, for an assembly you would probably want to remove these primers.
If you want FASTA or FASTQ output, you could just slice the SeqRecord. However,
if you want SFF output we have to preserve all the flow information - the trick
is just to adjust the left clip position!
>>> from Bio import SeqIO
>>> def filter_and_trim(records, primer):
... for record in records:
... if record.seq[record.annotations["clip_qual_left"]:].startswith(primer):
... record.annotations["clip_qual_left"] += len(primer)
... yield record
>>> records = SeqIO.parse("Roche/E3MFGYR02_random_10_reads.sff", "sff")
>>> count = SeqIO.write(filter_and_trim(records,"AAAGA"),
... "temp_filtered.sff", "sff")
>>> print "Selected %i records" % count
Selected 2 records
We can check the results, note the lower case clipped region now includes the "AAAGA"
sequence:
>>> for record in SeqIO.parse("temp_filtered.sff", "sff"):
... print record.id, len(record), record.seq[:20]+"..."
E3MFGYR02JHD4H 310 tcagaaagaCAAGTGGTATC...
E3MFGYR02GAZMS 278 tcagaaagaAGTAAGGTAAA...
>>> for record in SeqIO.parse("temp_filtered.sff", "sff-trim"):
... print record.id, len(record), record.seq[:20]+"..."
E3MFGYR02JHD4H 287 CAAGTGGTATCAACGCAGAG...
E3MFGYR02GAZMS 266 AGTAAGGTAAATAACAAACG...
>>> import os
>>> os.remove("temp_filtered.sff")
For a description of the file format, please see the Roche manuals and:
http://www.ncbi.nlm.nih.gov/Traces/trace.cgi?cmd=show&f=formats&m=doc&s=formats
"""
from Bio.SeqIO.Interfaces import SequenceWriter
from Bio import Alphabet
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import struct
import sys
from Bio._py3k import _bytes_to_string, _as_bytes
_null = _as_bytes("\0")
_sff = _as_bytes(".sff")
_hsh = _as_bytes(".hsh")
_srt = _as_bytes(".srt")
_mft = _as_bytes(".mft")
#This is a hack because char 255 is special in unicode:
try:
#This works on Python 2.6+ or Python 3.0
_flag = eval(r'b"\xff"')
except SyntaxError:
#Must be on Python 2.4 or 2.5
_flag = "\xff" #Char 255
def _sff_file_header(handle):
"""Read in an SFF file header (PRIVATE).
Assumes the handle is at the start of the file, will read forwards
though the header and leave the handle pointing at the first record.
Returns a tuple of values from the header (header_length, index_offset,
index_length, number_of_reads, flows_per_read, flow_chars, key_sequence)
>>> handle = open("Roche/greek.sff", "rb")
>>> values = _sff_file_header(handle)
>>> print values[0]
840
>>> print values[1]
65040
>>> print values[2]
256
>>> print values[3]
24
>>> print values[4]
800
>>> values[-1]
'TCAG'
"""
if hasattr(handle,"mode") and "U" in handle.mode.upper():
raise ValueError("SFF files must NOT be opened in universal new "
"lines mode. Binary mode is recommended (although "
"on Unix the default mode is also fine).")
elif hasattr(handle,"mode") and "B" not in handle.mode.upper() \
and sys.platform == "win32":
raise ValueError("SFF files must be opened in binary mode on Windows")
#file header (part one)
#use big endiean encdoing >
#magic_number I
#version 4B
#index_offset Q
#index_length I
#number_of_reads I
#header_length H
#key_length H
#number_of_flows_per_read H
#flowgram_format_code B
#[rest of file header depends on the number of flows and how many keys]
fmt = '>4s4BQIIHHHB'
assert 31 == struct.calcsize(fmt)
data = handle.read(31)
if not data:
raise ValueError("Empty file.")
elif len(data) < 13:
raise ValueError("File too small to hold a valid SFF header.")
magic_number, ver0, ver1, ver2, ver3, index_offset, index_length, \
number_of_reads, header_length, key_length, number_of_flows_per_read, \
flowgram_format = struct.unpack(fmt, data)
if magic_number in [_hsh, _srt, _mft]:
#Probably user error, calling Bio.SeqIO.parse() twice!
raise ValueError("Handle seems to be at SFF index block, not start")
if magic_number != _sff: # 779314790
raise ValueError("SFF file did not start '.sff', but %s" \
% repr(magic_number))
if (ver0, ver1, ver2, ver3) != (0, 0, 0, 1):
raise ValueError("Unsupported SFF version in header, %i.%i.%i.%i" \
% (ver0, ver1, ver2, ver3))
if flowgram_format != 1:
raise ValueError("Flowgram format code %i not supported" \
% flowgram_format)
if (index_offset!=0) ^ (index_length!=0):
raise ValueError("Index offset %i but index length %i" \
% (index_offset, index_length))
flow_chars = _bytes_to_string(handle.read(number_of_flows_per_read))
key_sequence = _bytes_to_string(handle.read(key_length))
#According to the spec, the header_length field should be the total number
#of bytes required by this set of header fields, and should be equal to
#"31 + number_of_flows_per_read + key_length" rounded up to the next value
#divisible by 8.
assert header_length % 8 == 0
padding = header_length - number_of_flows_per_read - key_length - 31
assert 0 <= padding < 8, padding
if handle.read(padding).count(_null) != padding:
raise ValueError("Post header %i byte padding region contained data" \
% padding)
return header_length, index_offset, index_length, \
number_of_reads, number_of_flows_per_read, \
flow_chars, key_sequence
#This is a generator function!
def _sff_do_slow_index(handle):
"""Generates an index by scanning though all the reads in an SFF file (PRIVATE).
This is a slow but generic approach if we can't parse the provided index
(if present).
Will use the handle seek/tell functions.
"""
handle.seek(0)
header_length, index_offset, index_length, number_of_reads, \
number_of_flows_per_read, flow_chars, key_sequence \
= _sff_file_header(handle)
#Now on to the reads...
read_header_fmt = '>2HI4H'
read_header_size = struct.calcsize(read_header_fmt)
#NOTE - assuming flowgram_format==1, which means struct type H
read_flow_fmt = ">%iH" % number_of_flows_per_read
read_flow_size = struct.calcsize(read_flow_fmt)
assert 1 == struct.calcsize(">B")
assert 1 == struct.calcsize(">s")
assert 1 == struct.calcsize(">c")
assert read_header_size % 8 == 0 #Important for padding calc later!
for read in range(number_of_reads):
record_offset = handle.tell()
if record_offset == index_offset:
#Found index block within reads, ignore it:
offset = index_offset + index_length
if offset % 8:
offset += 8 - (offset % 8)
assert offset % 8 == 0
handle.seek(offset)
record_offset = offset
#assert record_offset%8 == 0 #Worth checking, but slow
#First the fixed header
data = handle.read(read_header_size)
read_header_length, name_length, seq_len, clip_qual_left, \
clip_qual_right, clip_adapter_left, clip_adapter_right \
= struct.unpack(read_header_fmt, data)
if read_header_length < 10 or read_header_length % 8 != 0:
raise ValueError("Malformed read header, says length is %i:\n%s" \
% (read_header_length, repr(data)))
#now the name and any padding (remainder of header)
name = _bytes_to_string(handle.read(name_length))
padding = read_header_length - read_header_size - name_length
if handle.read(padding).count(_null) != padding:
raise ValueError("Post name %i byte padding region contained data" \
% padding)
assert record_offset + read_header_length == handle.tell()
#now the flowgram values, flowgram index, bases and qualities
size = read_flow_size + 3*seq_len
handle.seek(size, 1)
#now any padding...
padding = size % 8
if padding:
padding = 8 - padding
if handle.read(padding).count(_null) != padding:
raise ValueError("Post quality %i byte padding region contained data" \
% padding)
#print read, name, record_offset
yield name, record_offset
if handle.tell() % 8 != 0:
raise ValueError("After scanning reads, did not end on a multiple of 8")
def _sff_find_roche_index(handle):
"""Locate any existing Roche style XML meta data and read index (PRIVATE).
Makes a number of hard coded assumptions based on reverse engineered SFF
files from Roche 454 machines.
Returns a tuple of read count, SFF "index" offset and size, XML offset
and size, and the actual read index offset and size.
Raises a ValueError for unsupported or non-Roche index blocks.
"""
handle.seek(0)
header_length, index_offset, index_length, number_of_reads, \
number_of_flows_per_read, flow_chars, key_sequence \
= _sff_file_header(handle)
assert handle.tell() == header_length
if not index_offset or not index_offset:
raise ValueError("No index present in this SFF file")
#Now jump to the header...
handle.seek(index_offset)
fmt = ">4s4B"
fmt_size = struct.calcsize(fmt)
data = handle.read(fmt_size)
if not data:
raise ValueError("Premature end of file? Expected index of size %i at offest %i, found nothing" \
% (index_length, index_offset))
if len(data) < fmt_size:
raise ValueError("Premature end of file? Expected index of size %i at offest %i, found %s" \
% (index_length, index_offset, repr(data)))
magic_number, ver0, ver1, ver2, ver3 = struct.unpack(fmt, data)
if magic_number == _mft: # 778921588
#Roche 454 manifest index
#This is typical from raw Roche 454 SFF files (2009), and includes
#both an XML manifest and the sorted index.
if (ver0, ver1, ver2, ver3) != (49, 46, 48, 48):
#This is "1.00" as a string
raise ValueError("Unsupported version in .mft index header, %i.%i.%i.%i" \
% (ver0, ver1, ver2, ver3))
fmt2 = ">LL"
fmt2_size = struct.calcsize(fmt2)
xml_size, data_size = struct.unpack(fmt2, handle.read(fmt2_size))
if index_length != fmt_size + fmt2_size + xml_size + data_size:
raise ValueError("Problem understanding .mft index header, %i != %i + %i + %i + %i" \
% (index_length, fmt_size, fmt2_size, xml_size, data_size))
return number_of_reads, header_length, \
index_offset, index_length, \
index_offset + fmt_size + fmt2_size, xml_size, \
index_offset + fmt_size + fmt2_size + xml_size, data_size
elif magic_number == _srt: #779317876
#Roche 454 sorted index
#I've had this from Roche tool sfffile when the read identifiers
#had nonstandard lengths and there was no XML manifest.
if (ver0, ver1, ver2, ver3) != (49, 46, 48, 48):
#This is "1.00" as a string
raise ValueError("Unsupported version in .srt index header, %i.%i.%i.%i" \
% (ver0, ver1, ver2, ver3))
data = handle.read(4)
if data != _null*4:
raise ValueError("Did not find expected null four bytes in .srt index")
return number_of_reads, header_length, \
index_offset, index_length, \
0, 0, \
index_offset + fmt_size + 4, index_length - fmt_size - 4
elif magic_number == _hsh:
raise ValueError("Hash table style indexes (.hsh) in SFF files are "
"not (yet) supported")
else:
raise ValueError("Unknown magic number %s in SFF index header:\n%s" \
% (repr(magic_number), repr(data)))
def _sff_read_roche_index_xml(handle):
"""Reads any existing Roche style XML manifest data in the SFF "index" (PRIVATE, DEPRECATED).
Will use the handle seek/tell functions. Returns a string.
This has been replaced by ReadRocheXmlManifest. We would normally just
delete an old private function without warning, but I believe some people
are using this so we'll handle this with a deprecation warning.
"""
import warnings
warnings.warn("Private function _sff_read_roche_index_xml is deprecated. "
"Use new public function ReadRocheXmlManifest instead",
DeprecationWarning)
return ReadRocheXmlManifest(handle)
def ReadRocheXmlManifest(handle):
"""Reads any Roche style XML manifest data in the SFF "index".
The SFF file format allows for multiple different index blocks, and Roche
took advantage of this to define their own index block wich also embeds
an XML manifest string. This is not a publically documented extension to
the SFF file format, this was reverse engineered.
The handle should be to an SFF file opened in binary mode. This function
will use the handle seek/tell functions and leave the handle in an
arbitrary location.
Any XML manifest found is returned as a Python string, which you can then
parse as appropriate, or reuse when writing out SFF files with the
SffWriter class.
Returns a string, or raises a ValueError if an Roche manifest could not be
found.
"""
number_of_reads, header_length, index_offset, index_length, xml_offset, \
xml_size, read_index_offset, read_index_size = _sff_find_roche_index(handle)
if not xml_offset or not xml_size:
raise ValueError("No XML manifest found")
handle.seek(xml_offset)
return _bytes_to_string(handle.read(xml_size))
#This is a generator function!
def _sff_read_roche_index(handle):
"""Reads any existing Roche style read index provided in the SFF file (PRIVATE).
Will use the handle seek/tell functions.
This works on ".srt1.00" and ".mft1.00" style Roche SFF index blocks.
Roche SFF indices use base 255 not 256, meaning we see bytes in range the
range 0 to 254 only. This appears to be so that byte 0xFF (character 255)
can be used as a marker character to separate entries (required if the
read name lengths vary).
Note that since only four bytes are used for the read offset, this is
limited to 255^4 bytes (nearly 4GB). If you try to use the Roche sfffile
tool to combine SFF files beyound this limit, they issue a warning and
omit the index (and manifest).
"""
number_of_reads, header_length, index_offset, index_length, xml_offset, \
xml_size, read_index_offset, read_index_size = _sff_find_roche_index(handle)
#Now parse the read index...
handle.seek(read_index_offset)
fmt = ">5B"
for read in range(number_of_reads):
#TODO - Be more aware of when the index should end?
data = handle.read(6)
while True:
more = handle.read(1)
if not more:
raise ValueError("Premature end of file!")
data += more
if more == _flag: break
assert data[-1:] == _flag, data[-1:]
name = _bytes_to_string(data[:-6])
off4, off3, off2, off1, off0 = struct.unpack(fmt, data[-6:-1])
offset = off0 + 255*off1 + 65025*off2 + 16581375*off3
if off4:
#Could in theory be used as a fifth piece of offset information,
#i.e. offset =+ 4228250625L*off4, but testing the Roche tools this
#is not the case. They simple don't support such large indexes.
raise ValueError("Expected a null terminator to the read name.")
yield name, offset
if handle.tell() != read_index_offset + read_index_size:
raise ValueError("Problem with index length? %i vs %i" \
% (handle.tell(), read_index_offset + read_index_size))
def _sff_read_seq_record(handle, number_of_flows_per_read, flow_chars,
key_sequence, alphabet, trim=False):
"""Parse the next read in the file, return data as a SeqRecord (PRIVATE)."""
#Now on to the reads...
#the read header format (fixed part):
#read_header_length H
#name_length H
#seq_len I
#clip_qual_left H
#clip_qual_right H
#clip_adapter_left H
#clip_adapter_right H
#[rest of read header depends on the name length etc]
read_header_fmt = '>2HI4H'
read_header_size = struct.calcsize(read_header_fmt)
read_flow_fmt = ">%iH" % number_of_flows_per_read
read_flow_size = struct.calcsize(read_flow_fmt)
read_header_length, name_length, seq_len, clip_qual_left, \
clip_qual_right, clip_adapter_left, clip_adapter_right \
= struct.unpack(read_header_fmt, handle.read(read_header_size))
if clip_qual_left:
clip_qual_left -= 1 #python counting
if clip_adapter_left:
clip_adapter_left -= 1 #python counting
if read_header_length < 10 or read_header_length % 8 != 0:
raise ValueError("Malformed read header, says length is %i" \
% read_header_length)
#now the name and any padding (remainder of header)
name = _bytes_to_string(handle.read(name_length))
padding = read_header_length - read_header_size - name_length
if handle.read(padding).count(_null) != padding:
raise ValueError("Post name %i byte padding region contained data" \
% padding)
#now the flowgram values, flowgram index, bases and qualities
#NOTE - assuming flowgram_format==1, which means struct type H
flow_values = handle.read(read_flow_size) #unpack later if needed
temp_fmt = ">%iB" % seq_len # used for flow index and quals
flow_index = handle.read(seq_len) #unpack later if needed
seq = _bytes_to_string(handle.read(seq_len)) #TODO - Use bytes in Seq?
quals = list(struct.unpack(temp_fmt, handle.read(seq_len)))
#now any padding...
padding = (read_flow_size + seq_len*3)%8
if padding:
padding = 8 - padding
if handle.read(padding).count(_null) != padding:
raise ValueError("Post quality %i byte padding region contained data" \
% padding)
#Now build a SeqRecord
if trim:
seq = seq[clip_qual_left:clip_qual_right].upper()
quals = quals[clip_qual_left:clip_qual_right]
#Don't record the clipping values, flow etc, they make no sense now:
annotations = {}
else:
#This use of mixed case mimics the Roche SFF tool's FASTA output
seq = seq[:clip_qual_left].lower() + \
seq[clip_qual_left:clip_qual_right].upper() + \
seq[clip_qual_right:].lower()
annotations = {"flow_values":struct.unpack(read_flow_fmt, flow_values),
"flow_index":struct.unpack(temp_fmt, flow_index),
"flow_chars":flow_chars,
"flow_key":key_sequence,
"clip_qual_left":clip_qual_left,
"clip_qual_right":clip_qual_right,
"clip_adapter_left":clip_adapter_left,
"clip_adapter_right":clip_adapter_right}
record = SeqRecord(Seq(seq, alphabet),
id=name,
name=name,
description="",
annotations=annotations)
#Dirty trick to speed up this line:
#record.letter_annotations["phred_quality"] = quals
dict.__setitem__(record._per_letter_annotations,
"phred_quality", quals)
#TODO - adaptor clipping
#Return the record and then continue...
return record
#This is a generator function!
def SffIterator(handle, alphabet=Alphabet.generic_dna, trim=False):
"""Iterate over Standard Flowgram Format (SFF) reads (as SeqRecord objects).
handle - input file, an SFF file, e.g. from Roche 454 sequencing.
This must NOT be opened in universal read lines mode!
alphabet - optional alphabet, defaults to generic DNA.
trim - should the sequences be trimmed?
The resulting SeqRecord objects should match those from a paired FASTA
and QUAL file converted from the SFF file using the Roche 454 tool
ssfinfo. i.e. The sequence will be mixed case, with the trim regions
shown in lower case.
This function is used internally via the Bio.SeqIO functions:
>>> from Bio import SeqIO
>>> handle = open("Roche/E3MFGYR02_random_10_reads.sff", "rb")
>>> for record in SeqIO.parse(handle, "sff"):
... print record.id, len(record)
E3MFGYR02JWQ7T 265
E3MFGYR02JA6IL 271
E3MFGYR02JHD4H 310
E3MFGYR02GFKUC 299
E3MFGYR02FTGED 281
E3MFGYR02FR9G7 261
E3MFGYR02GAZMS 278
E3MFGYR02HHZ8O 221
E3MFGYR02GPGB1 269
E3MFGYR02F7Z7G 219
>>> handle.close()
You can also call it directly:
>>> handle = open("Roche/E3MFGYR02_random_10_reads.sff", "rb")
>>> for record in SffIterator(handle):
... print record.id, len(record)
E3MFGYR02JWQ7T 265
E3MFGYR02JA6IL 271
E3MFGYR02JHD4H 310
E3MFGYR02GFKUC 299
E3MFGYR02FTGED 281
E3MFGYR02FR9G7 261
E3MFGYR02GAZMS 278
E3MFGYR02HHZ8O 221
E3MFGYR02GPGB1 269
E3MFGYR02F7Z7G 219
>>> handle.close()
Or, with the trim option:
>>> handle = open("Roche/E3MFGYR02_random_10_reads.sff", "rb")
>>> for record in SffIterator(handle, trim=True):
... print record.id, len(record)
E3MFGYR02JWQ7T 260
E3MFGYR02JA6IL 265
E3MFGYR02JHD4H 292
E3MFGYR02GFKUC 295
E3MFGYR02FTGED 277
E3MFGYR02FR9G7 256
E3MFGYR02GAZMS 271
E3MFGYR02HHZ8O 150
E3MFGYR02GPGB1 221
E3MFGYR02F7Z7G 130
>>> handle.close()
"""
if isinstance(Alphabet._get_base_alphabet(alphabet),
Alphabet.ProteinAlphabet):
raise ValueError("Invalid alphabet, SFF files do not hold proteins.")
if isinstance(Alphabet._get_base_alphabet(alphabet),
Alphabet.RNAAlphabet):
raise ValueError("Invalid alphabet, SFF files do not hold RNA.")
header_length, index_offset, index_length, number_of_reads, \
number_of_flows_per_read, flow_chars, key_sequence \
= _sff_file_header(handle)
#Now on to the reads...
#the read header format (fixed part):
#read_header_length H
#name_length H
#seq_len I
#clip_qual_left H
#clip_qual_right H
#clip_adapter_left H
#clip_adapter_right H
#[rest of read header depends on the name length etc]
read_header_fmt = '>2HI4H'
read_header_size = struct.calcsize(read_header_fmt)
read_flow_fmt = ">%iH" % number_of_flows_per_read
read_flow_size = struct.calcsize(read_flow_fmt)
assert 1 == struct.calcsize(">B")
assert 1 == struct.calcsize(">s")
assert 1 == struct.calcsize(">c")
assert read_header_size % 8 == 0 #Important for padding calc later!
#The spec allows for the index block to be before or even in the middle
#of the reads. We can check that if we keep track of our position
#in the file...
for read in range(number_of_reads):
if index_offset and handle.tell() == index_offset:
offset = index_offset + index_length
if offset % 8:
offset += 8 - (offset % 8)
assert offset % 8 == 0
handle.seek(offset)
#Now that we've done this, we don't need to do it again. Clear
#the index_offset so we can skip extra handle.tell() calls:
index_offset = 0
yield _sff_read_seq_record(handle,
number_of_flows_per_read,
flow_chars,
key_sequence,
alphabet,
trim)
#The following is not essential, but avoids confusing error messages
#for the user if they try and re-parse the same handle.
if index_offset and handle.tell() == index_offset:
offset = index_offset + index_length
if offset % 8:
offset += 8 - (offset % 8)
assert offset % 8 == 0
handle.seek(offset)
#Should now be at the end of the file...
if handle.read(1):
raise ValueError("Additional data at end of SFF file")
#This is a generator function!
def _SffTrimIterator(handle, alphabet=Alphabet.generic_dna):
"""Iterate over SFF reads (as SeqRecord objects) with trimming (PRIVATE)."""
return SffIterator(handle, alphabet, trim=True)
class SffWriter(SequenceWriter):
"""SFF file writer."""
def __init__(self, handle, index=True, xml=None):
"""Creates the writer object.
handle - Output handle, ideally in binary write mode.
index - Boolean argument, should we try and write an index?
xml - Optional string argument, xml manifest to be recorded in the index
block (see function ReadRocheXmlManifest for reading this data).
"""
if hasattr(handle,"mode") and "U" in handle.mode.upper():
raise ValueError("SFF files must NOT be opened in universal new "
"lines mode. Binary mode is required")
elif hasattr(handle,"mode") and "B" not in handle.mode.upper():
raise ValueError("SFF files must be opened in binary mode")
self.handle = handle
self._xml = xml
if index:
self._index = []
else:
self._index = None
def write_file(self, records):
"""Use this to write an entire file containing the given records."""
try:
self._number_of_reads = len(records)
except TypeError:
self._number_of_reads = 0 #dummy value
if not hasattr(self.handle, "seek") \
or not hasattr(self.handle, "tell"):
raise ValueError("A handle with a seek/tell methods is "
"required in order to record the total "
"record count in the file header (once it "
"is known at the end).")
if self._index is not None and \
not (hasattr(self.handle, "seek") and hasattr(self.handle, "tell")):
import warnings
warnings.warn("A handle with a seek/tell methods is required in "
"order to record an SFF index.")
self._index = None
self._index_start = 0
self._index_length = 0
if not hasattr(records, "next"):
records = iter(records)
#Get the first record in order to find the flow information
#we will need for the header.
try:
record = records.next()
except StopIteration:
record = None
if record is None:
#No records -> empty SFF file (or an error)?
#We can't write a header without the flow information.
#return 0
raise ValueError("Need at least one record for SFF output")
try:
self._key_sequence = _as_bytes(record.annotations["flow_key"])
self._flow_chars = _as_bytes(record.annotations["flow_chars"])
self._number_of_flows_per_read = len(self._flow_chars)
except KeyError:
raise ValueError("Missing SFF flow information")
self.write_header()
self.write_record(record)
count = 1
for record in records:
self.write_record(record)
count += 1
if self._number_of_reads == 0:
#Must go back and record the record count...
offset = self.handle.tell()
self.handle.seek(0)
self._number_of_reads = count
self.write_header()
self.handle.seek(offset) #not essential?
else:
assert count == self._number_of_reads
if self._index is not None:
self._write_index()
return count
def _write_index(self):
assert len(self._index)==self._number_of_reads
handle = self.handle
self._index.sort()
self._index_start = handle.tell() #need for header
#XML...
if self._xml is not None:
xml = _as_bytes(self._xml)
else:
from Bio import __version__
xml = "<!-- This file was output with Biopython %s -->\n" % __version__
xml += "<!-- This XML and index block attempts to mimic Roche SFF files -->\n"
xml += "<!-- This file may be a combination of multiple SFF files etc -->\n"
xml = _as_bytes(xml)
xml_len = len(xml)
#Write to the file...
fmt = ">I4BLL"
fmt_size = struct.calcsize(fmt)
handle.write(_null*fmt_size + xml) #will come back later to fill this
fmt2 = ">6B"
assert 6 == struct.calcsize(fmt2)
self._index.sort()
index_len = 0 #don't know yet!
for name, offset in self._index:
#Roche files record the offsets using base 255 not 256.
#See comments for parsing the index block. There may be a faster
#way to code this, but we can't easily use shifts due to odd base
off3 = offset
off0 = off3 % 255
off3 -= off0
off1 = off3 % 65025
off3 -= off1
off2 = off3 % 16581375
off3 -= off2
assert offset == off0 + off1 + off2 + off3, \
"%i -> %i %i %i %i" % (offset, off0, off1, off2, off3)
off3, off2, off1, off0 = off3//16581375, off2//65025, \
off1//255, off0
assert off0 < 255 and off1 < 255 and off2 < 255 and off3 < 255, \
"%i -> %i %i %i %i" % (offset, off0, off1, off2, off3)
handle.write(name + struct.pack(fmt2, 0, \
off3, off2, off1, off0, 255))
index_len += len(name) + 6
#Note any padding in not included:
self._index_length = fmt_size + xml_len + index_len #need for header
#Pad out to an 8 byte boundary (although I have noticed some
#real Roche SFF files neglect to do this depsite their manual
#suggesting this padding should be there):
if self._index_length % 8:
padding = 8 - (self._index_length%8)
handle.write(_null*padding)
else:
padding = 0
offset = handle.tell()
assert offset == self._index_start + self._index_length + padding, \
"%i vs %i + %i + %i" % (offset, self._index_start, \
self._index_length, padding)
#Must now go back and update the index header with index size...
handle.seek(self._index_start)
handle.write(struct.pack(fmt, 778921588, #magic number
49,46,48,48, #Roche index version, "1.00"
xml_len, index_len) + xml)
#Must now go back and update the header...
handle.seek(0)
self.write_header()
handle.seek(offset) #not essential?
def write_header(self):
#Do header...
key_length = len(self._key_sequence)
#file header (part one)
#use big endiean encdoing >
#magic_number I
#version 4B
#index_offset Q
#index_length I
#number_of_reads I
#header_length H
#key_length H
#number_of_flows_per_read H
#flowgram_format_code B
#[rest of file header depends on the number of flows and how many keys]
fmt = '>I4BQIIHHHB%is%is' % (self._number_of_flows_per_read, key_length)
#According to the spec, the header_length field should be the total
#number of bytes required by this set of header fields, and should be
#equal to "31 + number_of_flows_per_read + key_length" rounded up to
#the next value divisible by 8.
if struct.calcsize(fmt) % 8 == 0:
padding = 0
else:
padding = 8 - (struct.calcsize(fmt) % 8)
header_length = struct.calcsize(fmt) + padding
assert header_length % 8 == 0
header = struct.pack(fmt, 779314790, #magic number 0x2E736666
0, 0, 0, 1, #version
self._index_start, self._index_length,
self._number_of_reads,
header_length, key_length,
self._number_of_flows_per_read,
1, #the only flowgram format code we support
self._flow_chars, self._key_sequence)
self.handle.write(header + _null*padding)
def write_record(self, record):
"""Write a single additional record to the output file.
This assumes the header has been done.
"""
#Basics
name = _as_bytes(record.id)
name_len = len(name)
seq = _as_bytes(str(record.seq).upper())
seq_len = len(seq)
#Qualities
try:
quals = record.letter_annotations["phred_quality"]
except KeyError:
raise ValueError("Missing PHRED qualities information")
#Flow
try:
flow_values = record.annotations["flow_values"]
flow_index = record.annotations["flow_index"]
if self._key_sequence != _as_bytes(record.annotations["flow_key"]) \
or self._flow_chars != _as_bytes(record.annotations["flow_chars"]):
raise ValueError("Records have inconsistent SFF flow data")
except KeyError:
raise ValueError("Missing SFF flow information")
except AttributeError:
raise ValueError("Header not written yet?")
#Clipping
try:
clip_qual_left = record.annotations["clip_qual_left"]
if clip_qual_left:
clip_qual_left += 1
clip_qual_right = record.annotations["clip_qual_right"]
clip_adapter_left = record.annotations["clip_adapter_left"]
if clip_adapter_left:
clip_adapter_left += 1
clip_adapter_right = record.annotations["clip_adapter_right"]
except KeyError:
raise ValueError("Missing SFF clipping information")
#Capture information for index
if self._index is not None:
offset = self.handle.tell()
#Check the position of the final record (before sort by name)
#See comments earlier about how base 255 seems to be used.
#This means the limit is 255**4 + 255**3 +255**2 + 255**1
if offset > 4244897280:
import warnings
warnings.warn("Read %s has file offset %i, which is too large "
"to store in the Roche SFF index structure. No "
"index block will be recorded." % (name, offset))
#No point recoring the offsets now
self._index = None
else:
self._index.append((name, self.handle.tell()))
#the read header format (fixed part):
#read_header_length H
#name_length H
#seq_len I
#clip_qual_left H
#clip_qual_right H
#clip_adapter_left H
#clip_adapter_right H
#[rest of read header depends on the name length etc]
#name
#flow values
#flow index
#sequence
#padding
read_header_fmt = '>2HI4H%is' % name_len
if struct.calcsize(read_header_fmt) % 8 == 0:
padding = 0
else:
padding = 8 - (struct.calcsize(read_header_fmt) % 8)
read_header_length = struct.calcsize(read_header_fmt) + padding
assert read_header_length % 8 == 0
data = struct.pack(read_header_fmt,
read_header_length,
name_len, seq_len,
clip_qual_left, clip_qual_right,
clip_adapter_left, clip_adapter_right,
name) + _null*padding
assert len(data) == read_header_length
#now the flowgram values, flowgram index, bases and qualities
#NOTE - assuming flowgram_format==1, which means struct type H
read_flow_fmt = ">%iH" % self._number_of_flows_per_read
read_flow_size = struct.calcsize(read_flow_fmt)
temp_fmt = ">%iB" % seq_len # used for flow index and quals
data += struct.pack(read_flow_fmt, *flow_values) \
+ struct.pack(temp_fmt, *flow_index) \
+ seq \
+ struct.pack(temp_fmt, *quals)
#now any final padding...
padding = (read_flow_size + seq_len*3)%8
if padding:
padding = 8 - padding
self.handle.write(data + _null*padding)
if __name__ == "__main__":
print "Running quick self test"
filename = "../../Tests/Roche/E3MFGYR02_random_10_reads.sff"
metadata = ReadRocheXmlManifest(open(filename, "rb"))
index1 = sorted(_sff_read_roche_index(open(filename, "rb")))
index2 = sorted(_sff_do_slow_index(open(filename, "rb")))
assert index1 == index2
assert len(index1) == len(list(SffIterator(open(filename, "rb"))))
from StringIO import StringIO
try:
#This is in Python 2.6+, and is essential on Python 3
from io import BytesIO
except ImportError:
BytesIO = StringIO
assert len(index1) == len(list(SffIterator(BytesIO(open(filename,"rb").read()))))
if sys.platform != "win32":
assert len(index1) == len(list(SffIterator(open(filename, "r"))))
index2 = sorted(_sff_read_roche_index(open(filename)))
assert index1 == index2
index2 = sorted(_sff_do_slow_index(open(filename)))
assert index1 == index2
assert len(index1) == len(list(SffIterator(open(filename))))
assert len(index1) == len(list(SffIterator(BytesIO(open(filename,"r").read()))))
assert len(index1) == len(list(SffIterator(BytesIO(open(filename).read()))))
sff = list(SffIterator(open(filename, "rb")))
sff2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb")))
assert len(sff) == len(sff2)
for old, new in zip(sff, sff2):
assert old.id == new.id
assert str(old.seq) == str(new.seq)
sff2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_alt_index_at_start.sff", "rb")))
assert len(sff) == len(sff2)
for old, new in zip(sff, sff2):
assert old.id == new.id
assert str(old.seq) == str(new.seq)
sff2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_alt_index_in_middle.sff", "rb")))
assert len(sff) == len(sff2)
for old, new in zip(sff, sff2):
assert old.id == new.id
assert str(old.seq) == str(new.seq)
sff2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_index_at_start.sff", "rb")))
assert len(sff) == len(sff2)
for old, new in zip(sff, sff2):
assert old.id == new.id
assert str(old.seq) == str(new.seq)
sff2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_index_in_middle.sff", "rb")))
assert len(sff) == len(sff2)
for old, new in zip(sff, sff2):
assert old.id == new.id
assert str(old.seq) == str(new.seq)
sff_trim = list(SffIterator(open(filename, "rb"), trim=True))
print ReadRocheXmlManifest(open(filename, "rb"))
from Bio import SeqIO
filename = "../../Tests/Roche/E3MFGYR02_random_10_reads_no_trim.fasta"
fasta_no_trim = list(SeqIO.parse(open(filename,"rU"), "fasta"))
filename = "../../Tests/Roche/E3MFGYR02_random_10_reads_no_trim.qual"
qual_no_trim = list(SeqIO.parse(open(filename,"rU"), "qual"))
filename = "../../Tests/Roche/E3MFGYR02_random_10_reads.fasta"
fasta_trim = list(SeqIO.parse(open(filename,"rU"), "fasta"))
filename = "../../Tests/Roche/E3MFGYR02_random_10_reads.qual"
qual_trim = list(SeqIO.parse(open(filename,"rU"), "qual"))
for s, sT, f, q, fT, qT in zip(sff, sff_trim, fasta_no_trim,
qual_no_trim, fasta_trim, qual_trim):
#print
print s.id
#print s.seq
#print s.letter_annotations["phred_quality"]
assert s.id == f.id == q.id
assert str(s.seq) == str(f.seq)
assert s.letter_annotations["phred_quality"] == q.letter_annotations["phred_quality"]
assert s.id == sT.id == fT.id == qT.id
assert str(sT.seq) == str(fT.seq)
assert sT.letter_annotations["phred_quality"] == qT.letter_annotations["phred_quality"]
print "Writing with a list of SeqRecords..."
handle = StringIO()
w = SffWriter(handle, xml=metadata)
w.write_file(sff) #list
data = handle.getvalue()
print "And again with an iterator..."
handle = StringIO()
w = SffWriter(handle, xml=metadata)
w.write_file(iter(sff))
assert data == handle.getvalue()
#Check 100% identical to the original:
filename = "../../Tests/Roche/E3MFGYR02_random_10_reads.sff"
original = open(filename,"rb").read()
assert len(data) == len(original)
assert data == original
del data
handle.close()
print "-"*50
filename = "../../Tests/Roche/greek.sff"
for record in SffIterator(open(filename,"rb")):
print record.id
index1 = sorted(_sff_read_roche_index(open(filename, "rb")))
index2 = sorted(_sff_do_slow_index(open(filename, "rb")))
assert index1 == index2
try:
print ReadRocheXmlManifest(open(filename, "rb"))
assert False, "Should fail!"
except ValueError:
pass
handle = open(filename, "rb")
for record in SffIterator(handle):
pass
try:
for record in SffIterator(handle):
print record.id
assert False, "Should have failed"
except ValueError, err:
print "Checking what happens on re-reading a handle:"
print err
"""
#Ugly code to make test files...
index = ".diy1.00This is a fake index block (DIY = Do It Yourself), which is allowed under the SFF standard.\0"
padding = len(index)%8
if padding:
padding = 8 - padding
index += chr(0)*padding
assert len(index)%8 == 0
#Ugly bit of code to make a fake index at start
records = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_random_10_reads.sff", "rb")))
out_handle = open("../../Tests/Roche/E3MFGYR02_alt_index_at_start.sff", "w")
index = ".diy1.00This is a fake index block (DIY = Do It Yourself), which is allowed under the SFF standard.\0"
padding = len(index)%8
if padding:
padding = 8 - padding
index += chr(0)*padding
w = SffWriter(out_handle, index=False, xml=None)
#Fake the header...
w._number_of_reads = len(records)
w._index_start = 0
w._index_length = 0
w._key_sequence = records[0].annotations["flow_key"]
w._flow_chars = records[0].annotations["flow_chars"]
w._number_of_flows_per_read = len(w._flow_chars)
w.write_header()
w._index_start = out_handle.tell()
w._index_length = len(index)
out_handle.seek(0)
w.write_header() #this time with index info
w.handle.write(index)
for record in records:
w.write_record(record)
out_handle.close()
records2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_alt_index_at_start.sff", "rb")))
for old, new in zip(records, records2):
assert str(old.seq)==str(new.seq)
i = list(_sff_do_slow_index(open("../../Tests/Roche/E3MFGYR02_alt_index_at_start.sff", "rb")))
#Ugly bit of code to make a fake index in middle
records = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_random_10_reads.sff", "rb")))
out_handle = open("../../Tests/Roche/E3MFGYR02_alt_index_in_middle.sff", "w")
index = ".diy1.00This is a fake index block (DIY = Do It Yourself), which is allowed under the SFF standard.\0"
padding = len(index)%8
if padding:
padding = 8 - padding
index += chr(0)*padding
w = SffWriter(out_handle, index=False, xml=None)
#Fake the header...
w._number_of_reads = len(records)
w._index_start = 0
w._index_length = 0
w._key_sequence = records[0].annotations["flow_key"]
w._flow_chars = records[0].annotations["flow_chars"]
w._number_of_flows_per_read = len(w._flow_chars)
w.write_header()
for record in records[:5]:
w.write_record(record)
w._index_start = out_handle.tell()
w._index_length = len(index)
w.handle.write(index)
for record in records[5:]:
w.write_record(record)
out_handle.seek(0)
w.write_header() #this time with index info
out_handle.close()
records2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_alt_index_in_middle.sff", "rb")))
for old, new in zip(records, records2):
assert str(old.seq)==str(new.seq)
j = list(_sff_do_slow_index(open("../../Tests/Roche/E3MFGYR02_alt_index_in_middle.sff", "rb")))
#Ugly bit of code to make a fake index at end
records = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_random_10_reads.sff", "rb")))
out_handle = open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "w")
w = SffWriter(out_handle, index=False, xml=None)
#Fake the header...
w._number_of_reads = len(records)
w._index_start = 0
w._index_length = 0
w._key_sequence = records[0].annotations["flow_key"]
w._flow_chars = records[0].annotations["flow_chars"]
w._number_of_flows_per_read = len(w._flow_chars)
w.write_header()
for record in records:
w.write_record(record)
w._index_start = out_handle.tell()
w._index_length = len(index)
out_handle.write(index)
out_handle.seek(0)
w.write_header() #this time with index info
out_handle.close()
records2 = list(SffIterator(open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb")))
for old, new in zip(records, records2):
assert str(old.seq)==str(new.seq)
try:
print ReadRocheXmlManifest(open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb"))
assert False, "Should fail!"
except ValueError:
pass
k = list(_sff_do_slow_index(open("../../Tests/Roche/E3MFGYR02_alt_index_at_end.sff", "rb")))
"""
print "Done"
| BlogomaticProject/Blogomatic | opt/blog-o-matic/usr/lib/python/Bio/SeqIO/SffIO.py | Python | gpl-2.0 | 53,635 |
package sady.utilframe.bdControl;
import java.util.List;
import java.util.Set;
import sady.utilframe.bdControl.configuration.ColumnConfiguration;
import sady.utilframe.bdControl.configuration.FKConfiguration;
import sady.utilframe.bdControl.configuration.TableConfiguration;
public abstract class FullDBObject extends DBObject {
@Override
public List<String> getColumnNames() {
return super.getColumnNames();
}
@Override
public ColumnConfiguration getConfiguration(String columnName) {
return super.getConfiguration(columnName);
}
@Override
public List<List<FKConfiguration>> getFKs() {
return super.getFKs();
}
@Override
public List<List<FKConfiguration>> getReverseFKs() {
return super.getReverseFKs();
}
@Override
public TableConfiguration getTableConfiguration() {
return super.getTableConfiguration();
}
@Override
public Set<String> getUpdatedValues() {
return super.getUpdatedValues();
}
@Override
public boolean hasChanged() {
return super.hasChanged();
}
@Override
public FKConfiguration getFKConfiguration(String columnName) {
return super.getFKConfiguration(columnName);
}
@Override
public boolean isFK(String columnName) {
return super.isFK(columnName);
}
@Override
public List<String> getPKs() {
return super.getPKs();
}
}
| sadybr/UtilFrame | UtilFrame/src/sady/utilframe/bdControl/FullDBObject.java | Java | gpl-2.0 | 1,296 |
<?php
/**
* The admin-specific functionality of the plugin.
*
* @link https://wzymedia.com
* @since 1.0.0
*
* @package wzy_Records
* @subpackage wzy_Records/admin
*/
/**
* The admin-specific functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the admin-specific stylesheet and JavaScript.
*
* @package wzy_Records
* @subpackage wzy_Records/admin
* @author wzyMedia <wzy@outlook.com>
*/
class wzy_Records_Admin {
/**
* The ID of this plugin.
*
* @since 1.0.0
* @access private
* @var string $plugin_name The ID of this plugin.
*/
private $plugin_name;
/**
* The version of this plugin.
*
* @since 1.0.0
* @access private
* @var string $version The current version of this plugin.
*/
private $version;
/**
* Instance of the admin description class handling all general information related functions.
*
* @since 1.0.0
* @access public
* @var object $description
*/
public $description;
/**
* Instance of the admin general info class handling all general information related functions.
*
* @since 1.0.0
* @access public
* @var object $general_info
*/
public $general_info;
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
* @param string $plugin_name The name of this plugin.
* @param string $version The version of this plugin.
*/
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
require_once __DIR__ . '/class-wzy-records-admin-description.php';
$this->description = new wzy_Records_Admin_Description( $this->version );
require_once __DIR__ . '/class-wzy-records-admin-general-info.php';
$this->general_info = new wzy_Records_Admin_General_Info( $this->version );
}
/**
* Register the stylesheets for the admin area.
*
* @since 1.0.0
*/
public function enqueue_styles() {
/**
* This function is provided for demonstration purposes only.
*
* An instance of this class should be passed to the run() function
* defined in wzy_Records_Loader as all of the hooks are defined
* in that particular class.
*
* The wzy_Records_Loader will then create the relationship
* between the defined hooks and the functions defined in this
* class.
*/
wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/wzy-records-admin.css', array(), $this->version, 'all' );
}
/**
* Register the JavaScript for the admin area.
*
* @since 1.0.0
*/
public function enqueue_scripts() {
/**
* This function is provided for demonstration purposes only.
*
* An instance of this class should be passed to the run() function
* defined in wzy_Records_Loader as all of the hooks are defined
* in that particular class.
*
* The wzy_Records_Loader will then create the relationship
* between the defined hooks and the functions defined in this
* class.
*/
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/wzy-records-admin.js', array( 'jquery' ), $this->version, false );
}
/**
* Creates the book review custom post type.
*
* @since 1.0.0
* @access public
* @uses register_post_type()
* @return void
*/
public function rcno_review_posttype() {
$cap_type = 'post';
$plural = 'Records';
$single = 'Record';
$cpt_name = 'wzy_record';
$cpt_slug = 'record'; // @TODO: Create an option to select recipe slug.
$opts['can_export'] = true;
$opts['capability_type'] = $cap_type;
$opts['description'] = '';
$opts['exclude_from_search'] = false;
$opts['has_archive'] = 'records';
$opts['hierarchical'] = false;
$opts['map_meta_cap'] = true;
$opts['menu_icon'] = 'dashicons-portfolio';
$opts['menu_position'] = 5;
$opts['public'] = true;
$opts['publicly_querable'] = true;
$opts['query_var'] = true;
$opts['register_meta_box_cb'] = '';
$opts['rewrite'] = false;
$opts['show_in_admin_bar'] = true;
$opts['show_in_menu'] = true;
$opts['show_in_nav_menu'] = true;
$opts['show_ui'] = true;
$opts['supports'] = array( 'title', 'thumbnail', 'featured' );
$opts['taxonomies'] = array( 'category', 'post_tag' );
$opts['capabilities']['delete_others_posts'] = "delete_others_{$cap_type}s";
$opts['capabilities']['delete_post'] = "delete_{$cap_type}";
$opts['capabilities']['delete_posts'] = "delete_{$cap_type}s";
$opts['capabilities']['delete_private_posts'] = "delete_private_{$cap_type}s";
$opts['capabilities']['delete_published_posts'] = "delete_published_{$cap_type}s";
$opts['capabilities']['edit_others_posts'] = "edit_others_{$cap_type}s";
$opts['capabilities']['edit_post'] = "edit_{$cap_type}";
$opts['capabilities']['edit_posts'] = "edit_{$cap_type}s";
$opts['capabilities']['edit_private_posts'] = "edit_private_{$cap_type}s";
$opts['capabilities']['edit_published_posts'] = "edit_published_{$cap_type}s";
$opts['capabilities']['publish_posts'] = "publish_{$cap_type}s";
$opts['capabilities']['read_post'] = "read_{$cap_type}";
$opts['capabilities']['read_private_posts'] = "read_private_{$cap_type}s";
$opts['labels']['add_new'] = esc_html__( "New {$single}", 'wzy-records' );
$opts['labels']['add_new_item'] = esc_html__( "Add New {$single}", 'wzy-records' );
$opts['labels']['all_items'] = esc_html__( $plural, 'wzy-records' );
$opts['labels']['edit_item'] = esc_html__( "Edit {$single}", 'wzy-records' );
$opts['labels']['menu_name'] = esc_html__( $plural, 'wzy-records' );
$opts['labels']['name'] = esc_html__( $plural, 'wzy-records' );
$opts['labels']['name_admin_bar'] = esc_html__( $single, 'wzy-records' );
$opts['labels']['new_item'] = esc_html__( "New {$single}", 'wzy-records' );
$opts['labels']['not_found'] = esc_html__( "No {$plural} Found", 'wzy-records' );
$opts['labels']['not_found_in_trash'] = esc_html__( "No {$plural} Found in Trash", 'wzy-records' );
$opts['labels']['parent_item_colon'] = esc_html__( "Parent {$plural} :", 'wzy-records' );
$opts['labels']['search_items'] = esc_html__( "Search {$plural}", 'wzy-records' );
$opts['labels']['singular_name'] = esc_html__( $single, 'wzy-records' );
$opts['labels']['view_item'] = esc_html__( "View {$single}", 'wzy-records' );
$opts['rewrite']['ep_mask'] = EP_PERMALINK;
$opts['rewrite']['feeds'] = false;
$opts['rewrite']['pages'] = true;
$opts['rewrite']['slug'] = __( $cpt_slug, 'wzy-records' );
$opts['rewrite']['with_front'] = false;
$opts = apply_filters( 'rcno_review_cpt_options', $opts );
register_post_type( strtolower( $cpt_name ), $opts );
}
/**
* Register the administration menu for this plugin into the WordPress Dashboard menu.
*
* @since 1.0.0
*/
public function add_plugin_admin_menu() {
add_menu_page(
__( 'wzy Records', $this->plugin_name ),
__( 'Records', $this->plugin_name ),
'manage_options',
$this->plugin_name,
array( $this, 'display_plugin_admin_page' )
);
add_submenu_page(
'edit.php?post_type=wzy_record',
__( 'wzy Records', $this->plugin_name ),
__( 'Settings', $this->plugin_name ),
'manage_options',
$this->plugin_name,
array( $this, 'display_plugin_admin_page' )
);
remove_menu_page( $this->plugin_name );
}
/**
* Add settings action link to the plugins page.
*
* @since 1.0.0
* @return array Action links
*/
public function add_action_links( $links ) {
return array_merge(
array(
'settings' => '<a href="' . admin_url( 'admin.php?page=' . $this->plugin_name ) . '">' . __( 'Settings', $this->plugin_name ) . '</a>'
),
$links
);
}
/**
* Render the settings page for this plugin.
*
* @since 1.0.0
*/
public function display_plugin_admin_page() {
$tabs = wzy_Records_Settings_Definition::get_tabs();
$default_tab = wzy_Records_Settings_Definition::get_default_tab_slug();
$active_tab = isset( $_GET[ 'tab' ] ) && array_key_exists( $_GET['tab'], $tabs ) ? $_GET[ 'tab' ] : $default_tab;
include_once( 'partials/' . $this->plugin_name . '-admin-display.php' );
}
/**
* Saves all the data from review meta boxes
*
* @param int $record_id post ID of record being saved.
* @param mixed $record the record post object.
* @see https://developer.wordpress.org/reference/functions/wp_update_post/#user-contributed-notes
*
* @since 1.0.0
* @return int|bool
*/
public function wzy_save_record( $record_id, $record = null ) {
if ( ! wp_is_post_revision( $record_id ) ) { // 'save_post' is fired twice, once for revisions, then to save post.
remove_action( 'save_post', array( $this, 'wzy_save_record' ) );
$data = $_POST;
if ( null !== $record && $record->post_type === 'wzy_record' ) {
$errors = false;
// Verify if this is an auto save routine. If it is our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $record_id;
}
// Check user permissions.
if ( ! current_user_can( 'edit_post', $record_id ) ) {
$errors = 'There was an error saving the record. Insufficient administrator rights.';
}
// If we have an error update the error_option and return.
if ( $errors ) {
update_option( 'rcno_admin_errors', $errors );
return $record_id;
}
$this->description->wzy_save_record_description_metadata( $record_id, $data );
$this->general_info->wzy_save_record_general_info_metadata( $record_id, $data );
wp_update_post( $record );
add_action( 'save_post', array( $this, 'wzy_save_record' ) );
}
}
return true;
}
/**
* Book review update messages.
* See /wp-admin/edit-form-advanced.php
* @param array $messages Existing post update messages.
* @return array Amended post update messages with new review update messages.
*/
function wzy_updated_record_messages( $messages ) {
$post = get_post();
$post_type = get_post_type( $post );
$post_type_object = get_post_type_object( $post_type );
$messages['wzy_record'] = array(
0 => '', // Unused. Messages start at index 1.
1 => __( 'Record updated.', 'wzy-records' ),
2 => __( 'Custom field updated.', 'wzy-records' ),
3 => __( 'Custom field deleted.', 'wzy-records' ),
4 => __( 'Record updated.', 'wzy-records' ),
/* translators: %s: date and time of the revision */
5 => isset( $_GET['revision'] ) ? sprintf( __( 'Record restored to revision from %s', 'wzy-records' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => __( 'Record published.', 'wzy-records' ),
7 => __( 'Record saved.', 'wzy-records' ),
8 => __( 'Record submitted.', 'wzy-records' ),
9 => sprintf(
__( 'Record scheduled for: <strong>%1$s</strong>.', 'wzy-records' ),
// translators: Publish box date format, see http://php.net/date
date_i18n( __( 'M j, Y @ G:i', 'wzy-records' ), strtotime( $post->post_date ) )
),
10 => __( 'Record draft updated.', 'wzy-records' )
);
if ( $post_type_object->publicly_queryable && 'wzy_record' === $post_type ) {
$permalink = get_permalink( $post->ID );
$view_link = sprintf( ' <a href="%s">%s</a>', esc_url( $permalink ), __( 'View review', 'wzy-records' ) );
$messages[ $post_type ][1] .= $view_link;
$messages[ $post_type ][6] .= $view_link;
$messages[ $post_type ][9] .= $view_link;
$preview_permalink = add_query_arg( 'preview', 'true', $permalink );
$preview_link = sprintf( ' <a target="_blank" href="%s">%s</a>', esc_url( $preview_permalink ), __( 'Preview review', 'wzy-records' ) );
$messages[ $post_type ][8] .= $preview_link;
$messages[ $post_type ][10] .= $preview_link;
}
return $messages;
}
}
| w33zy/wzy-records | admin/class-wzy-records-admin.php | PHP | gpl-2.0 | 12,217 |
package com.example;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Greeting2 {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting2")
public MyGret greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new MyGret(counter.incrementAndGet(),
String.format(template, name));
}
} | soniyj/basement | src/Java/maven/demo/src/main/java/com/example/Greeting2.java | Java | gpl-2.0 | 660 |
package com.harrcharr.pulse;
class JNIUtil {
public static native void deleteGlobalRef(long ref);
}
| hchapman/libpulse-android | src/main/java/com/harrcharr/pulse/JNIUtil.java | Java | gpl-2.0 | 102 |
/*
* AG-HPX500 board header
*/
#ifndef _DEFS_XXXX_H
#define _DEFS_XXXX_H
#define SPD_P2PF_ARCH "K250"
enum SPD_GENERIC_ENUM {
/* for Power Mode */
SPD_PM_HIGH = 0x4d, /* R:600mA, W:600mA */
SPD_PM_LOW = 0x34, /* R:400mA, W:400mA */
SPD_PM_NORMAL = 0x00, /* R:400mA, W:600mA */
};
enum SPD_K250_ENUM {
SPD_N_DEV = 4,
SPD_N_CACHE = 2,
SPD_PM_LEVEL = SPD_PM_NORMAL,
SPD_CACHE_N_BUFFER = 8, /* 4MB */
};
#endif /* _DEFS_XXXX_H */
| kierank/p2card | arch/defs-K250.h | C | gpl-2.0 | 487 |
package net.demilich.metastone.game.actions;
public enum ActionType {
SYSTEM, END_TURN, PHYSICAL_ATTACK, SPELL, SUMMON, HERO_POWER, BATTLECRY, EQUIP_WEAPON,
}
| rafaelkalan/metastone | src/main/java/net/demilich/metastone/game/actions/ActionType.java | Java | gpl-2.0 | 161 |
A = require('./using_module_exports_a');
module.exports = {
b: function() {
return A.a()
}
};
| rasberries/dashboard | node_modules/stitchw/test/fixtures/default/circular/using_module_exports_b.js | JavaScript | gpl-2.0 | 110 |
package org.openthinclient.web.ui;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_LOGIN;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_PASSWORD;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_REMEMBERME;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_USERNAME;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_WELCOME;
import ch.qos.cal10n.IMessageConveyor;
import ch.qos.cal10n.MessageConveyor;
import com.vaadin.annotations.Theme;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;
import org.openthinclient.i18n.LocaleUtil;
import org.openthinclient.web.i18n.ConsoleWebMessages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.CommunicationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.vaadin.spring.security.shared.VaadinSharedSecurity;
/**
* LoginUI
*/
@SpringUI(path = "/login")
@Theme("openthinclient")
public class LoginUI extends UI {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginUI.class);
@Autowired
VaadinSharedSecurity vaadinSecurity;
private IMessageConveyor mc;
private CheckBox rememberMe;
@Override
protected void init(VaadinRequest request) {
setLocale(LocaleUtil.getLocaleForMessages(ConsoleWebMessages.class, UI.getCurrent().getLocale()));
mc = new MessageConveyor(UI.getCurrent().getLocale());
Component loginForm = buildLoginForm();
VerticalLayout rootLayout = new VerticalLayout(loginForm);
rootLayout.setSizeFull();
rootLayout.setComponentAlignment(loginForm, Alignment.MIDDLE_CENTER);
setContent(rootLayout);
setSizeFull();
}
private Component buildLoginForm() {
final VerticalLayout loginPanel = new VerticalLayout();
loginPanel.setSizeUndefined();
Responsive.makeResponsive(loginPanel);
loginPanel.addStyleName("login-panel");
loginPanel.addComponent(buildLabels());
Label loginFailed = new Label();
loginFailed.setStyleName("login-failed");
loginFailed.setVisible(false);
loginPanel.addComponents(loginFailed);
HorizontalLayout fields = new HorizontalLayout();
fields.setSpacing(true);
fields.addStyleName("fields");
final TextField username = new TextField(mc.getMessage(UI_LOGIN_USERNAME));
username.setIcon(FontAwesome.USER);
username.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
final PasswordField password = new PasswordField(mc.getMessage(UI_LOGIN_PASSWORD));
password.setIcon(FontAwesome.LOCK);
password.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
final Button signin = new Button(mc.getMessage(UI_LOGIN_LOGIN));
signin.addStyleName(ValoTheme.BUTTON_PRIMARY);
signin.setClickShortcut(KeyCode.ENTER);
signin.focus();
signin.addClickListener(event -> {
final IMessageConveyor mc = new MessageConveyor(UI.getCurrent().getLocale());
try {
final Authentication authentication = vaadinSecurity.login(username.getValue(), password.getValue(), rememberMe.getValue());
LOGGER.debug("Received UserLoginRequestedEvent for ", authentication.getPrincipal());
} catch (AuthenticationException | AccessDeniedException ex) {
loginFailed.getParent().addStyleName("failed");
if (ex.getCause() instanceof CommunicationException) {
loginFailed.setValue(mc.getMessage(ConsoleWebMessages.UI_DASHBOARDUI_LOGIN_COMMUNICATION_EXCEPTION));
} else {
loginFailed.setValue(mc.getMessage(ConsoleWebMessages.UI_DASHBOARDUI_LOGIN_FAILED));
}
loginFailed.setVisible(true);
} catch (Exception ex) {
loginFailed.getParent().getParent().addStyleName("error");
loginFailed.setValue(mc.getMessage(ConsoleWebMessages.UI_DASHBOARDUI_LOGIN_UNEXPECTED_ERROR));
loginFailed.setVisible(true);
LOGGER.error("Unexpected error while logging in", ex);
}
});
fields.addComponents(username, password, signin);
fields.setComponentAlignment(signin, Alignment.BOTTOM_LEFT);
loginPanel.addComponent(fields);
loginPanel.addComponent(rememberMe = new CheckBox(mc.getMessage(UI_LOGIN_REMEMBERME), false));
return loginPanel;
}
private Component buildLabels() {
CssLayout labels = new CssLayout();
labels.addStyleName("labels");
Label welcome = new Label(mc.getMessage(UI_LOGIN_WELCOME));
welcome.setSizeUndefined();
welcome.addStyleName(ValoTheme.LABEL_H4);
welcome.addStyleName(ValoTheme.LABEL_COLORED);
labels.addComponent(welcome);
Label title = new Label("openthinclient.org");
title.setSizeUndefined();
title.addStyleName(ValoTheme.LABEL_H3);
title.addStyleName(ValoTheme.LABEL_LIGHT);
labels.addComponent(title);
return labels;
}
}
| openthinclient/openthinclient-manager | console-web/webapp/src/main/java/org/openthinclient/web/ui/LoginUI.java | Java | gpl-2.0 | 5,939 |
/*
* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h"
#include "Box2D/Common/b2BlockAllocator.h"
#include "Box2D/Dynamics/b2Fixture.h"
#include <new>
using namespace std;
b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
{
void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact));
return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB);
}
void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
{
((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact();
allocator->Free(contact, sizeof(b2EdgeAndPolygonContact));
}
b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
: b2Contact(fixtureA, 0, fixtureB, 0)
{
b2Assert(m_fixtureA->GetType() == b2Shape::e_edge);
b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
}
void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
{
b2CollideEdgeAndPolygon( manifold,
(b2EdgeShape*)m_fixtureA->GetShape(), xfA,
(b2PolygonShape*)m_fixtureB->GetShape(), xfB);
}
| ricardobaumann/android | libs/android_application_2d_adventure_game-master/AndEnginePhysicsBox2DExtension-GLES2/jni/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp | C++ | gpl-2.0 | 2,057 |
<?php
/**
* @file
* BNF Essentiels - theme implementation to navigate books.
*
* Presented under nodes that are a part of book outlines.
*
* Available variables:
* - $tree: The immediate children of the current node rendered as an unordered
* list.
* - $current_depth: Depth of the current node within the book outline. Provided
* for context.
* - $prev_url: URL to the previous node.
* - $prev_title: Title of the previous node.
* - $parent_url: URL to the parent node.
* - $parent_title: Title of the parent node. Not printed by default. Provided
* as an option.
* - $next_url: URL to the next node.
* - $next_title: Title of the next node.
* - $has_links: Flags TRUE whenever the previous, parent or next data has a
* value.
* - $book_id: The book ID of the current outline being viewed. Same as the node
* ID containing the entire outline. Provided for context.
* - $book_url: The book/node URL of the current outline being viewed. Provided
* as an option. Not used by default.
* - $book_title: The book/node title of the current outline being viewed.
* Provided as an option. Not used by default.
*
* @see template_preprocess_book_navigation()
* @ingroup themeable
*/
if ($tree || $has_links)
{
?>
<?php print $tree; ?>
<ul class="pager">
<?php if ($prev_url): ?>
<li class="pager__previous">
<a href="<?php print $prev_url; ?>"><span class="accessibility"><?php print t('Go to previous page'); ?></span><i class="icon-arrow-left"></i></a>
</li>
<?php endif; ?>
<?php if ($next_url): ?>
<li class="pager__next">
<a href="<?php print $next_url; ?>">
<span class="accessibility"><?php print t('Go to next page'); ?></span><i class="icon-arrow-right"></i>
</a>
</li>
<?php endif; ?>
</ul>
<?php
}
| Paulmicha/drupal-7.godmothership | templates/book-navigation.tpl.php | PHP | gpl-2.0 | 1,813 |
/*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "ObjectMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "DatabaseEnv.h"
#include "AccountMgr.h"
#include "CellImpl.h"
#include "Chat.h"
#include "GridNotifiersImpl.h"
#include "Language.h"
#include "Log.h"
#include "Opcodes.h"
#include "Player.h"
#include "UpdateMask.h"
#include "SpellMgr.h"
#include "ScriptMgr.h"
#include "ChatLink.h"
bool ChatHandler::load_command_table = true;
// wrapper for old-style handlers
template<bool (ChatHandler::*F)(const char*)>
bool OldHandler(ChatHandler* chatHandler, const char* args)
{
return (chatHandler->*F)(args);
}
// get number of commands in table
static size_t getCommandTableSize(const ChatCommand* commands)
{
if (!commands)
return 0;
size_t count = 0;
while (commands[count].Name != NULL)
count++;
return count;
}
// append source command table to target, return number of appended commands
static size_t appendCommandTable(ChatCommand* target, const ChatCommand* source)
{
const size_t count = getCommandTableSize(source);
if (count)
memcpy(target, source, count * sizeof(ChatCommand));
return count;
}
ChatCommand * ChatHandler::getCommandTable()
{
static ChatCommand banCommandTable[] =
{
{ "account", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanAccountCommand>, "", NULL },
{ "character", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanCharacterCommand>, "", NULL },
{ "playeraccount", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanAccountByCharCommand>, "", NULL },
{ "ip", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanIPCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand baninfoCommandTable[] =
{
{ "account", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanInfoAccountCommand>, "", NULL },
{ "character", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanInfoCharacterCommand>, "", NULL },
{ "ip", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanInfoIPCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand banlistCommandTable[] =
{
{ "account", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanListAccountCommand>, "", NULL },
{ "character", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanListCharacterCommand>, "", NULL },
{ "ip", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleBanListIPCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand castCommandTable[] =
{
{ "back", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleCastBackCommand>, "", NULL },
{ "dist", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleCastDistCommand>, "", NULL },
{ "self", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleCastSelfCommand>, "", NULL },
{ "target", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleCastTargetCommand>, "", NULL },
{ "", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleCastCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand characterDeletedCommandTable[] =
{
{ "delete", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleCharacterDeletedDeleteCommand>, "", NULL },
{ "list", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleCharacterDeletedListCommand>, "", NULL },
{ "restore", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleCharacterDeletedRestoreCommand>, "", NULL },
{ "old", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleCharacterDeletedOldCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand characterCommandTable[] =
{
{ "customize", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleCharacterCustomizeCommand>, "", NULL },
{ "changefaction", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleCharacterChangeFactionCommand>, "", NULL },
{ "changerace", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleCharacterChangeRaceCommand>, "", NULL },
{ "deleted", SEC_GAMEMASTER, true, NULL, "", characterDeletedCommandTable},
{ "erase", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleCharacterEraseCommand>, "", NULL },
{ "level", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleCharacterLevelCommand>, "", NULL },
{ "rename", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleCharacterRenameCommand>, "", NULL },
{ "reputation", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleCharacterReputationCommand>, "", NULL },
{ "titles", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleCharacterTitlesCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand channelSetCommandTable[] =
{
{ "ownership", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleChannelSetOwnership>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand channelCommandTable[] =
{
{ "set", SEC_ADMINISTRATOR, true, NULL, "", channelSetCommandTable },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand groupCommandTable[] =
{
{ "leader", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleGroupLeaderCommand>, "", NULL },
{ "disband", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleGroupDisbandCommand>, "", NULL },
{ "remove", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleGroupRemoveCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand guildCommandTable[] =
{
{ "create", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleGuildCreateCommand>, "", NULL },
{ "delete", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleGuildDeleteCommand>, "", NULL },
{ "invite", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleGuildInviteCommand>, "", NULL },
{ "uninvite", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleGuildUninviteCommand>, "", NULL },
{ "rank", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleGuildRankCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand instanceCommandTable[] =
{
{ "listbinds", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleInstanceListBindsCommand>, "", NULL },
{ "unbind", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleInstanceUnbindCommand>, "", NULL },
{ "stats", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleInstanceStatsCommand>, "", NULL },
{ "savedata", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleInstanceSaveDataCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand listCommandTable[] =
{
{ "creature", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleListCreatureCommand>, "", NULL },
{ "item", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleListItemCommand>, "", NULL },
{ "object", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleListObjectCommand>, "", NULL },
{ "auras", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleListAurasCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand lookupPlayerCommandTable[] =
{
{ "ip", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleLookupPlayerIpCommand>, "", NULL },
{ "account", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleLookupPlayerAccountCommand>, "", NULL },
{ "email", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleLookupPlayerEmailCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand lookupCommandTable[] =
{
{ "area", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleLookupAreaCommand>, "", NULL },
{ "creature", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupCreatureCommand>, "", NULL },
{ "event", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleLookupEventCommand>, "", NULL },
{ "faction", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupFactionCommand>, "", NULL },
{ "item", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupItemCommand>, "", NULL },
{ "itemset", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupItemSetCommand>, "", NULL },
{ "object", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupObjectCommand>, "", NULL },
{ "quest", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupQuestCommand>, "", NULL },
{ "player", SEC_GAMEMASTER, true, NULL, "", lookupPlayerCommandTable },
{ "skill", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupSkillCommand>, "", NULL },
{ "spell", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupSpellCommand>, "", NULL },
{ "taxinode", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupTaxiNodeCommand>, "", NULL },
{ "tele", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleLookupTeleCommand>, "", NULL },
{ "title", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleLookupTitleCommand>, "", NULL },
{ "map", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleLookupMapCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand petCommandTable[] =
{
{ "create", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleCreatePetCommand>, "", NULL },
{ "learn", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandlePetLearnCommand>, "", NULL },
{ "unlearn", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandlePetUnlearnCommand>, "", NULL },
{ "tp", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandlePetTpCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand pdumpCommandTable[] =
{
{ "load", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandlePDumpLoadCommand>, "", NULL },
{ "write", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandlePDumpWriteCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand resetCommandTable[] =
{
{ "achievements", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetAchievementsCommand>, "", NULL },
{ "honor", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetHonorCommand>, "", NULL },
{ "level", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetLevelCommand>, "", NULL },
{ "spells", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetSpellsCommand>, "", NULL },
{ "stats", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetStatsCommand>, "", NULL },
{ "talents", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetTalentsCommand>, "", NULL },
{ "all", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleResetAllCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand sendCommandTable[] =
{
{ "items", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleSendItemsCommand>, "", NULL },
{ "mail", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleSendMailCommand>, "", NULL },
{ "message", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleSendMessageCommand>, "", NULL },
{ "money", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleSendMoneyCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand serverIdleRestartCommandTable[] =
{
{ "cancel", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerShutDownCancelCommand>, "", NULL },
{ "" , SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerIdleRestartCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand serverIdleShutdownCommandTable[] =
{
{ "cancel", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerShutDownCancelCommand>, "", NULL },
{ "" , SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerIdleShutDownCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand serverRestartCommandTable[] =
{
{ "cancel", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerShutDownCancelCommand>, "", NULL },
{ "" , SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerRestartCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand serverShutdownCommandTable[] =
{
{ "cancel", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerShutDownCancelCommand>, "", NULL },
{ "" , SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerShutDownCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand serverSetCommandTable[] =
{
{ "difftime", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleServerSetDiffTimeCommand>, "", NULL },
{ "loglevel", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleServerSetLogLevelCommand>, "", NULL },
{ "logfilelevel", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleServerSetLogFileLevelCommand>, "", NULL },
{ "motd", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerSetMotdCommand>, "", NULL },
{ "closed", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerSetClosedCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand serverCommandTable[] =
{
{ "corpses", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleServerCorpsesCommand>, "", NULL },
{ "exit", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleServerExitCommand>, "", NULL },
{ "idlerestart", SEC_ADMINISTRATOR, true, NULL, "", serverIdleRestartCommandTable },
{ "idleshutdown", SEC_ADMINISTRATOR, true, NULL, "", serverShutdownCommandTable },
{ "info", SEC_PLAYER, true, OldHandler<&ChatHandler::HandleServerInfoCommand>, "", NULL },
{ "motd", SEC_PLAYER, true, OldHandler<&ChatHandler::HandleServerMotdCommand>, "", NULL },
{ "plimit", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleServerPLimitCommand>, "", NULL },
{ "restart", SEC_ADMINISTRATOR, true, NULL, "", serverRestartCommandTable },
{ "shutdown", SEC_ADMINISTRATOR, true, NULL, "", serverShutdownCommandTable },
{ "set", SEC_ADMINISTRATOR, true, NULL, "", serverSetCommandTable },
{ "togglequerylog", SEC_CONSOLE, true, OldHandler<&ChatHandler::HandleServerToggleQueryLogging>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand unbanCommandTable[] =
{
{ "account", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleUnBanAccountCommand>, "", NULL },
{ "character", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleUnBanCharacterCommand>, "", NULL },
{ "playeraccount", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleUnBanAccountByCharCommand>, "", NULL },
{ "ip", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleUnBanIPCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand ticketResponseCommandTable[] =
{
{ "append", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketResponseAppendCommand>, "", NULL },
{ "appendln", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketResponseAppendLnCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand ticketCommandTable[] =
{
{ "list", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketListCommand>, "", NULL },
{ "onlinelist", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketListOnlineCommand>, "", NULL },
{ "viewname", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketGetByNameCommand>, "", NULL },
{ "viewid", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketGetByIdCommand>, "", NULL },
{ "close", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketCloseByIdCommand>, "", NULL },
{ "closedlist", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketListClosedCommand>, "", NULL },
{ "escalatedlist", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleGMTicketListEscalatedCommand>, "", NULL },
{ "delete", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleGMTicketDeleteByIdCommand>, "", NULL },
{ "assign", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleGMTicketAssignToCommand>, "", NULL },
{ "unassign", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleGMTicketUnAssignCommand>, "", NULL },
{ "comment", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketCommentCommand>, "", NULL },
{ "togglesystem", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleToggleGMTicketSystem>, "", NULL },
{ "escalate", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketEscalateCommand>, "", NULL },
{ "response", SEC_MODERATOR, false, NULL, "", ticketResponseCommandTable },
{ "complete", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGMTicketCompleteCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
static ChatCommand commandTable[] =
{
{ "character", SEC_GAMEMASTER, true, NULL, "", characterCommandTable},
{ "list", SEC_ADMINISTRATOR, true, NULL, "", listCommandTable },
{ "lookup", SEC_ADMINISTRATOR, true, NULL, "", lookupCommandTable },
{ "pdump", SEC_ADMINISTRATOR, true, NULL, "", pdumpCommandTable },
{ "guild", SEC_ADMINISTRATOR, true, NULL, "", guildCommandTable },
{ "cast", SEC_ADMINISTRATOR, false, NULL, "", castCommandTable },
{ "reset", SEC_ADMINISTRATOR, true, NULL, "", resetCommandTable },
{ "instance", SEC_ADMINISTRATOR, true, NULL, "", instanceCommandTable },
{ "server", SEC_ADMINISTRATOR, true, NULL, "", serverCommandTable },
{ "channel", SEC_ADMINISTRATOR, true, NULL, "", channelCommandTable },
{ "pet", SEC_GAMEMASTER, false, NULL, "", petCommandTable },
{ "ticket", SEC_MODERATOR, false, NULL, "", ticketCommandTable },
{ "aura", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleAuraCommand>, "", NULL },
{ "unaura", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleUnAuraCommand>, "", NULL },
{ "nameannounce", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleNameAnnounceCommand>, "", NULL },
{ "gmnameannounce", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleGMNameAnnounceCommand>, "", NULL },
{ "announce", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleAnnounceCommand>, "", NULL },
{ "gmannounce", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleGMAnnounceCommand>, "", NULL },
{ "notify", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleNotifyCommand>, "", NULL },
{ "gmnotify", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleGMNotifyCommand>, "", NULL },
{ "appear", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleAppearCommand>, "", NULL },
{ "summon", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleSummonCommand>, "", NULL },
{ "groupsummon", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGroupSummonCommand>, "", NULL },
{ "commands", SEC_PLAYER, true, OldHandler<&ChatHandler::HandleCommandsCommand>, "", NULL },
{ "demorph", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleDeMorphCommand>, "", NULL },
{ "die", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleDieCommand>, "", NULL },
{ "revive", SEC_ADMINISTRATOR, true, OldHandler<&ChatHandler::HandleReviveCommand>, "", NULL },
{ "dismount", SEC_PLAYER, false, OldHandler<&ChatHandler::HandleDismountCommand>, "", NULL },
{ "gps", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleGPSCommand>, "", NULL },
{ "guid", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleGUIDCommand>, "", NULL },
{ "help", SEC_PLAYER, true, OldHandler<&ChatHandler::HandleHelpCommand>, "", NULL },
{ "itemmove", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleItemMoveCommand>, "", NULL },
{ "cooldown", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleCooldownCommand>, "", NULL },
{ "unlearn", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleUnLearnCommand>, "", NULL },
{ "distance", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleGetDistanceCommand>, "", NULL },
{ "recall", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleRecallCommand>, "", NULL },
{ "save", SEC_PLAYER, false, OldHandler<&ChatHandler::HandleSaveCommand>, "", NULL },
{ "saveall", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleSaveAllCommand>, "", NULL },
{ "kick", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleKickPlayerCommand>, "", NULL },
{ "ban", SEC_ADMINISTRATOR, true, NULL, "", banCommandTable },
{ "unban", SEC_ADMINISTRATOR, true, NULL, "", unbanCommandTable },
{ "baninfo", SEC_ADMINISTRATOR, false, NULL, "", baninfoCommandTable },
{ "banlist", SEC_ADMINISTRATOR, true, NULL, "", banlistCommandTable },
{ "start", SEC_PLAYER, false, OldHandler<&ChatHandler::HandleStartCommand>, "", NULL },
{ "taxicheat", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleTaxiCheatCommand>, "", NULL },
{ "linkgrave", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleLinkGraveCommand>, "", NULL },
{ "neargrave", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleNearGraveCommand>, "", NULL },
{ "explorecheat", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleExploreCheatCommand>, "", NULL },
{ "hover", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleHoverCommand>, "", NULL },
{ "levelup", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleLevelUpCommand>, "", NULL },
{ "showarea", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleShowAreaCommand>, "", NULL },
{ "hidearea", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleHideAreaCommand>, "", NULL },
{ "additem", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleAddItemCommand>, "", NULL },
{ "additemset", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleAddItemSetCommand>, "", NULL },
{ "bank", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleBankCommand>, "", NULL },
{ "wchange", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleChangeWeather>, "", NULL },
{ "maxskill", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleMaxSkillCommand>, "", NULL },
{ "setskill", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleSetSkillCommand>, "", NULL },
{ "whispers", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleWhispersCommand>, "", NULL },
{ "pinfo", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandlePInfoCommand>, "", NULL },
{ "respawn", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleRespawnCommand>, "", NULL },
{ "send", SEC_MODERATOR, true, NULL, "", sendCommandTable },
{ "mute", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleMuteCommand>, "", NULL },
{ "unmute", SEC_MODERATOR, true, OldHandler<&ChatHandler::HandleUnmuteCommand>, "", NULL },
{ "movegens", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleMovegensCommand>, "", NULL },
{ "cometome", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleComeToMeCommand>, "", NULL },
{ "damage", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleDamageCommand>, "", NULL },
{ "combatstop", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleCombatStopCommand>, "", NULL },
{ "flusharenapoints", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleFlushArenaPointsCommand>, "", NULL },
{ "repairitems", SEC_GAMEMASTER, true, OldHandler<&ChatHandler::HandleRepairitemsCommand>, "", NULL },
{ "waterwalk", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandleWaterwalkCommand>, "", NULL },
{ "freeze", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleFreezeCommand>, "", NULL },
{ "unfreeze", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleUnFreezeCommand>, "", NULL },
{ "listfreeze", SEC_MODERATOR, false, OldHandler<&ChatHandler::HandleListFreezeCommand>, "", NULL },
{ "possess", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandlePossessCommand>, "", NULL },
{ "unpossess", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleUnPossessCommand>, "", NULL },
{ "bindsight", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleBindSightCommand>, "", NULL },
{ "unbindsight", SEC_ADMINISTRATOR, false, OldHandler<&ChatHandler::HandleUnbindSightCommand>, "", NULL },
{ "playall", SEC_GAMEMASTER, false, OldHandler<&ChatHandler::HandlePlayAllCommand>, "", NULL },
{ NULL, 0, false, NULL, "", NULL }
};
// cache for commands, needed because some commands are loaded dynamically through ScriptMgr
// cache is never freed and will show as a memory leak in diagnostic tools
// can't use vector as vector storage is implementation-dependent, eg, there can be alignment gaps between elements
static ChatCommand* commandTableCache = 0;
if (LoadCommandTable())
{
SetLoadCommandTable(false);
{
// count total number of top-level commands
size_t total = getCommandTableSize(commandTable);
std::vector<ChatCommand*> const& dynamic = sScriptMgr->GetChatCommands();
for (std::vector<ChatCommand*>::const_iterator it = dynamic.begin(); it != dynamic.end(); ++it)
total += getCommandTableSize(*it);
total += 1; // ending zero
// cache top-level commands
commandTableCache = (ChatCommand*)malloc(sizeof(ChatCommand) * total);
memset(commandTableCache, 0, sizeof(ChatCommand) * total);
ACE_ASSERT(commandTableCache);
size_t added = appendCommandTable(commandTableCache, commandTable);
for (std::vector<ChatCommand*>::const_iterator it = dynamic.begin(); it != dynamic.end(); ++it)
added += appendCommandTable(commandTableCache + added, *it);
}
QueryResult result = WorldDatabase.Query("SELECT name, security, help FROM command");
if (result)
{
do
{
Field *fields = result->Fetch();
std::string name = fields[0].GetString();
SetDataForCommandInTable(commandTableCache, name.c_str(), fields[1].GetUInt16(), fields[2].GetString(), name);
} while (result->NextRow());
}
}
return commandTableCache;
}
std::string ChatHandler::PGetParseString(int32 entry, ...) const
{
const char *format = GetTrinityString(entry);
char str[1024];
va_list ap;
va_start(ap, entry);
vsnprintf(str, 1024, format, ap);
va_end(ap);
return std::string(str);
}
const char *ChatHandler::GetTrinityString(int32 entry) const
{
return m_session->GetTrinityString(entry);
}
bool ChatHandler::isAvailable(ChatCommand const& cmd) const
{
// check security level only for simple command (without child commands)
return m_session->GetSecurity() >= AccountTypes(cmd.SecurityLevel);
}
bool ChatHandler::HasLowerSecurity(Player* target, uint64 guid, bool strong)
{
WorldSession* target_session = NULL;
uint32 target_account = 0;
if (target)
target_session = target->GetSession();
else if (guid)
target_account = sObjectMgr->GetPlayerAccountIdByGUID(guid);
if (!target_session && !target_account)
{
SendSysMessage(LANG_PLAYER_NOT_FOUND);
SetSentErrorMessage(true);
return true;
}
return HasLowerSecurityAccount(target_session, target_account, strong);
}
bool ChatHandler::HasLowerSecurityAccount(WorldSession* target, uint32 target_account, bool strong)
{
uint32 target_sec;
// allow everything from console and RA console
if (!m_session)
return false;
// ignore only for non-players for non strong checks (when allow apply command at least to same sec level)
if (m_session->GetSecurity() > SEC_PLAYER && !strong && !sWorld->getBoolConfig(CONFIG_GM_LOWER_SECURITY))
return false;
if (target)
target_sec = target->GetSecurity();
else if (target_account)
target_sec = sAccountMgr->GetSecurity(target_account, realmID);
else
return true; // caller must report error for (target == NULL && target_account == 0)
AccountTypes target_ac_sec = AccountTypes(target_sec);
if (m_session->GetSecurity() < target_ac_sec || (strong && m_session->GetSecurity() <= target_ac_sec))
{
SendSysMessage(LANG_YOURS_SECURITY_IS_LOW);
SetSentErrorMessage(true);
return true;
}
return false;
}
bool ChatHandler::hasStringAbbr(const char* name, const char* part)
{
// non "" command
if (*name)
{
// "" part from non-"" command
if (!*part)
return false;
for (;;)
{
if (!*part)
return true;
else if (!*name)
return false;
else if (tolower(*name) != tolower(*part))
return false;
++name; ++part;
}
}
// allow with any for ""
return true;
}
void ChatHandler::SendSysMessage(const char *str)
{
WorldPacket data;
// need copy to prevent corruption by strtok call in LineFromMessage original string
char* buf = strdup(str);
char* pos = buf;
while (char* line = LineFromMessage(pos))
{
FillSystemMessageData(&data, line);
m_session->SendPacket(&data);
}
free(buf);
}
void ChatHandler::SendGlobalSysMessage(const char *str)
{
// Chat output
WorldPacket data;
// need copy to prevent corruption by strtok call in LineFromMessage original string
char* buf = strdup(str);
char* pos = buf;
while (char* line = LineFromMessage(pos))
{
FillSystemMessageData(&data, line);
sWorld->SendGlobalMessage(&data);
}
free(buf);
}
void ChatHandler::SendGlobalGMSysMessage(const char *str)
{
// Chat output
WorldPacket data;
// need copy to prevent corruption by strtok call in LineFromMessage original string
char* buf = strdup(str);
char* pos = buf;
while (char* line = LineFromMessage(pos))
{
FillSystemMessageData(&data, line);
sWorld->SendGlobalGMMessage(&data);
}
free(buf);
}
void ChatHandler::SendSysMessage(int32 entry)
{
SendSysMessage(GetTrinityString(entry));
}
void ChatHandler::PSendSysMessage(int32 entry, ...)
{
const char *format = GetTrinityString(entry);
va_list ap;
char str [2048];
va_start(ap, entry);
vsnprintf(str, 2048, format, ap);
va_end(ap);
SendSysMessage(str);
}
void ChatHandler::PSendSysMessage(const char *format, ...)
{
va_list ap;
char str [2048];
va_start(ap, format);
vsnprintf(str, 2048, format, ap);
va_end(ap);
SendSysMessage(str);
}
bool ChatHandler::ExecuteCommandInTable(ChatCommand *table, const char* text, const std::string& fullcmd)
{
char const* oldtext = text;
std::string cmd = "";
while (*text != ' ' && *text != '\0')
{
cmd += *text;
++text;
}
while (*text == ' ') ++text;
for (uint32 i = 0; table[i].Name != NULL; ++i)
{
if (!hasStringAbbr(table[i].Name, cmd.c_str()))
continue;
bool match = false;
if (strlen(table[i].Name) > strlen(cmd.c_str()))
{
for (uint32 j = 0; table[j].Name != NULL; ++j)
{
if (!hasStringAbbr(table[j].Name, cmd.c_str()))
continue;
if (strcmp(table[j].Name, cmd.c_str()) != 0)
continue;
else
{
match = true;
break;
}
}
}
if (match)
continue;
// select subcommand from child commands list
if (table[i].ChildCommands != NULL)
{
if (!ExecuteCommandInTable(table[i].ChildCommands, text, fullcmd))
{
if (text && text[0] != '\0')
SendSysMessage(LANG_NO_SUBCMD);
else
SendSysMessage(LANG_CMD_SYNTAX);
ShowHelpForCommand(table[i].ChildCommands, text);
}
return true;
}
// must be available and have handler
if (!table[i].Handler || !isAvailable(table[i]))
continue;
SetSentErrorMessage(false);
// table[i].Name == "" is special case: send original command to handler
if ((table[i].Handler)(this, strlen(table[i].Name) != 0 ? text : oldtext))
{
if (table[i].SecurityLevel > SEC_PLAYER)
{
// chat case
if (m_session)
{
Player* p = m_session->GetPlayer();
uint64 sel_guid = p->GetSelection();
sLog->outCommand(m_session->GetAccountId(), "Command: %s [Player: %s (Account: %u) X: %f Y: %f Z: %f Map: %u Selected %s: %s (GUID: %u)]",
fullcmd.c_str(), p->GetName(), m_session->GetAccountId(), p->GetPositionX(), p->GetPositionY(), p->GetPositionZ(), p->GetMapId(),
GetLogNameForGuid(sel_guid), (p->GetSelectedUnit()) ? p->GetSelectedUnit()->GetName() : "", GUID_LOPART(sel_guid));
}
}
}
// some commands have custom error messages. Don't send the default one in these cases.
else if (!HasSentErrorMessage())
{
if (!table[i].Help.empty())
SendSysMessage(table[i].Help.c_str());
else
SendSysMessage(LANG_CMD_SYNTAX);
}
return true;
}
return false;
}
bool ChatHandler::SetDataForCommandInTable(ChatCommand *table, const char* text, uint32 security, std::string const& help, std::string const& fullcommand)
{
std::string cmd = "";
while (*text != ' ' && *text != '\0')
{
cmd += *text;
++text;
}
while (*text == ' ') ++text;
for (uint32 i = 0; table[i].Name != NULL; i++)
{
// for data fill use full explicit command names
if (table[i].Name != cmd)
continue;
// select subcommand from child commands list (including "")
if (table[i].ChildCommands != NULL)
{
if (SetDataForCommandInTable(table[i].ChildCommands, text, security, help, fullcommand))
return true;
else if (*text)
return false;
// fail with "" subcommands, then use normal level up command instead
}
// expected subcommand by full name DB content
else if (*text)
{
sLog->outErrorDb("Table `command` have unexpected subcommand '%s' in command '%s', skip.", text, fullcommand.c_str());
return false;
}
if (table[i].SecurityLevel != security)
sLog->outDetail("Table `command` overwrite for command '%s' default security (%u) by %u", fullcommand.c_str(), table[i].SecurityLevel, security);
table[i].SecurityLevel = security;
table[i].Help = help;
return true;
}
// in case "" command let process by caller
if (!cmd.empty())
{
if (table == getCommandTable())
sLog->outErrorDb("Table `command` have not existed command '%s', skip.", cmd.c_str());
else
sLog->outErrorDb("Table `command` have not existed subcommand '%s' in command '%s', skip.", cmd.c_str(), fullcommand.c_str());
}
return false;
}
int ChatHandler::ParseCommands(const char* text)
{
ASSERT(text);
ASSERT(*text);
std::string fullcmd = text;
if (m_session && m_session->GetSecurity() <= SEC_PLAYER && sWorld->getBoolConfig(CONFIG_ALLOW_PLAYER_COMMANDS) == 0)
return 0;
/// chat case (.command or !command format)
if (m_session)
{
if (text[0] != '!' && text[0] != '.')
return 0;
}
/// ignore single . and ! in line
if (strlen(text) < 2)
return 0;
// original `text` can't be used. It content destroyed in command code processing.
/// ignore messages staring from many dots.
if ((text[0] == '.' && text[1] == '.') || (text[0] == '!' && text[1] == '!'))
return 0;
/// skip first . or ! (in console allowed use command with . and ! and without its)
if (text[0] == '!' || text[0] == '.')
++text;
if (!ExecuteCommandInTable(getCommandTable(), text, fullcmd))
{
if (m_session && m_session->GetSecurity() == SEC_PLAYER)
return 0;
SendSysMessage(LANG_NO_CMD);
}
return 1;
}
bool ChatHandler::isValidChatMessage(const char* message)
{
/*
Valid examples:
|cffa335ee|Hitem:812:0:0:0:0:0:0:0:70|h[Glowing Brightwood Staff]|h|r
|cff808080|Hquest:2278:47|h[The Platinum Discs]|h|r
|cffffd000|Htrade:4037:1:150:1:6AAAAAAAAAAAAAAAAAAAAAAOAADAAAAAAAAAAAAAAAAIAAAAAAAAA|h[Engineering]|h|r
|cff4e96f7|Htalent:2232:-1|h[Taste for Blood]|h|r
|cff71d5ff|Hspell:21563|h[Command]|h|r
|cffffd000|Henchant:3919|h[Engineering: Rough Dynamite]|h|r
|cffffff00|Hachievement:546:0000000000000001:0:0:0:-1:0:0:0:0|h[Safe Deposit]|h|r
|cff66bbff|Hglyph:21:762|h[Glyph of Bladestorm]|h|r
| will be escaped to ||
*/
if (strlen(message) > 255)
return false;
// more simple checks
if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY) < 3)
{
const char validSequence[6] = "cHhhr";
const char* validSequenceIterator = validSequence;
const std::string validCommands = "cHhr|";
while (*message)
{
// find next pipe command
message = strchr(message, '|');
if (!message)
return true;
++message;
char commandChar = *message;
if (validCommands.find(commandChar) == std::string::npos)
return false;
++message;
// validate sequence
if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY) == 2)
{
if (commandChar == *validSequenceIterator)
{
if (validSequenceIterator == validSequence + 4)
validSequenceIterator = validSequence;
else
++validSequenceIterator;
}
else
return false;
}
}
return true;
}
return LinkExtractor(message).IsValidMessage();
}
bool ChatHandler::ShowHelpForSubCommands(ChatCommand *table, char const* cmd, char const* subcmd)
{
std::string list;
for (uint32 i = 0; table[i].Name != NULL; ++i)
{
// must be available (ignore handler existence for show command with possibe avalable subcomands
if (!isAvailable(table[i]))
continue;
/// for empty subcmd show all available
if (*subcmd && !hasStringAbbr(table[i].Name, subcmd))
continue;
if (m_session)
list += "\n ";
else
list += "\n\r ";
list += table[i].Name;
if (table[i].ChildCommands)
list += " ...";
}
if (list.empty())
return false;
if (table == getCommandTable())
{
SendSysMessage(LANG_AVIABLE_CMD);
PSendSysMessage("%s", list.c_str());
}
else
PSendSysMessage(LANG_SUBCMDS_LIST, cmd, list.c_str());
return true;
}
bool ChatHandler::ShowHelpForCommand(ChatCommand *table, const char* cmd)
{
if (*cmd)
{
for (uint32 i = 0; table[i].Name != NULL; ++i)
{
// must be available (ignore handler existence for show command with possibe avalable subcomands
if (!isAvailable(table[i]))
continue;
if (!hasStringAbbr(table[i].Name, cmd))
continue;
// have subcommand
char const* subcmd = (*cmd) ? strtok(NULL, " ") : "";
if (table[i].ChildCommands && subcmd && *subcmd)
{
if (ShowHelpForCommand(table[i].ChildCommands, subcmd))
return true;
}
if (!table[i].Help.empty())
SendSysMessage(table[i].Help.c_str());
if (table[i].ChildCommands)
if (ShowHelpForSubCommands(table[i].ChildCommands, table[i].Name, subcmd ? subcmd : ""))
return true;
return !table[i].Help.empty();
}
}
else
{
for (uint32 i = 0; table[i].Name != NULL; ++i)
{
// must be available (ignore handler existence for show command with possibe avalable subcomands
if (!isAvailable(table[i]))
continue;
if (strlen(table[i].Name))
continue;
if (!table[i].Help.empty())
SendSysMessage(table[i].Help.c_str());
if (table[i].ChildCommands)
if (ShowHelpForSubCommands(table[i].ChildCommands, "", ""))
return true;
return !table[i].Help.empty();
}
}
return ShowHelpForSubCommands(table, "", cmd);
}
//Note: target_guid used only in CHAT_MSG_WHISPER_INFORM mode (in this case channelName ignored)
void ChatHandler::FillMessageData(WorldPacket *data, WorldSession* session, uint8 type, uint32 language, const char *channelName, uint64 target_guid, const char *message, Unit *speaker)
{
uint32 messageLength = (message ? strlen(message) : 0) + 1;
data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
*data << uint8(type);
if ((type != CHAT_MSG_CHANNEL && type != CHAT_MSG_WHISPER) || language == LANG_ADDON)
*data << uint32(language);
else
*data << uint32(LANG_UNIVERSAL);
switch(type)
{
case CHAT_MSG_SAY:
case CHAT_MSG_PARTY:
case CHAT_MSG_PARTY_LEADER:
case CHAT_MSG_RAID:
case CHAT_MSG_GUILD:
case CHAT_MSG_OFFICER:
case CHAT_MSG_YELL:
case CHAT_MSG_WHISPER:
case CHAT_MSG_CHANNEL:
case CHAT_MSG_RAID_LEADER:
case CHAT_MSG_RAID_WARNING:
case CHAT_MSG_BG_SYSTEM_NEUTRAL:
case CHAT_MSG_BG_SYSTEM_ALLIANCE:
case CHAT_MSG_BG_SYSTEM_HORDE:
case CHAT_MSG_BATTLEGROUND:
case CHAT_MSG_BATTLEGROUND_LEADER:
target_guid = session ? session->GetPlayer()->GetGUID() : 0;
break;
case CHAT_MSG_MONSTER_SAY:
case CHAT_MSG_MONSTER_PARTY:
case CHAT_MSG_MONSTER_YELL:
case CHAT_MSG_MONSTER_WHISPER:
case CHAT_MSG_MONSTER_EMOTE:
case CHAT_MSG_RAID_BOSS_WHISPER:
case CHAT_MSG_RAID_BOSS_EMOTE:
case CHAT_MSG_BATTLENET:
{
*data << uint64(speaker->GetGUID());
*data << uint32(0); // 2.1.0
*data << uint32(strlen(speaker->GetName()) + 1);
*data << speaker->GetName();
uint64 listener_guid = 0;
*data << uint64(listener_guid);
if (listener_guid && !IS_PLAYER_GUID(listener_guid))
{
*data << uint32(1); // string listener_name_length
*data << uint8(0); // string listener_name
}
*data << uint32(messageLength);
*data << message;
*data << uint8(0);
return;
}
default:
if (type != CHAT_MSG_WHISPER_INFORM && type != CHAT_MSG_IGNORED && type != CHAT_MSG_DND && type != CHAT_MSG_AFK)
target_guid = 0; // only for CHAT_MSG_WHISPER_INFORM used original value target_guid
break;
}
*data << uint64(target_guid); // there 0 for BG messages
*data << uint32(0); // can be chat msg group or something
if (type == CHAT_MSG_CHANNEL)
{
ASSERT(channelName);
*data << channelName;
}
*data << uint64(target_guid);
*data << uint32(messageLength);
*data << message;
if (session != 0 && type != CHAT_MSG_WHISPER_INFORM && type != CHAT_MSG_DND && type != CHAT_MSG_AFK)
*data << uint8(session->GetPlayer()->chatTag());
else
*data << uint8(0);
}
Player* ChatHandler::getSelectedPlayer()
{
if (!m_session)
return NULL;
uint64 guid = m_session->GetPlayer()->GetSelection();
if (guid == 0)
return m_session->GetPlayer();
return sObjectMgr->GetPlayer(guid);
}
Unit* ChatHandler::getSelectedUnit()
{
if (!m_session)
return NULL;
uint64 guid = m_session->GetPlayer()->GetSelection();
if (guid == 0)
return m_session->GetPlayer();
return ObjectAccessor::GetUnit(*m_session->GetPlayer(), guid);
}
WorldObject *ChatHandler::getSelectedObject()
{
if (!m_session)
return NULL;
uint64 guid = m_session->GetPlayer()->GetSelection();
if (guid == 0)
return GetNearbyGameObject();
return ObjectAccessor::GetUnit(*m_session->GetPlayer(), guid);
}
Creature* ChatHandler::getSelectedCreature()
{
if (!m_session)
return NULL;
return ObjectAccessor::GetCreatureOrPetOrVehicle(*m_session->GetPlayer(), m_session->GetPlayer()->GetSelection());
}
char* ChatHandler::extractKeyFromLink(char* text, char const* linkType, char** something1)
{
// skip empty
if (!text)
return NULL;
// skip spaces
while (*text == ' '||*text == '\t'||*text == '\b')
++text;
if (!*text)
return NULL;
// return non link case
if (text[0] != '|')
return strtok(text, " ");
// [name] Shift-click form |color|linkType:key|h[name]|h|r
// or
// [name] Shift-click form |color|linkType:key:something1:...:somethingN|h[name]|h|r
char* check = strtok(text, "|"); // skip color
if (!check)
return NULL; // end of data
char* cLinkType = strtok(NULL, ":"); // linktype
if (!cLinkType)
return NULL; // end of data
if (strcmp(cLinkType, linkType) != 0)
{
strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after retturn from function
SendSysMessage(LANG_WRONG_LINK_TYPE);
return NULL;
}
char* cKeys = strtok(NULL, "|"); // extract keys and values
char* cKeysTail = strtok(NULL, "");
char* cKey = strtok(cKeys, ":|"); // extract key
if (something1)
*something1 = strtok(NULL, ":|"); // extract something
strtok(cKeysTail, "]"); // restart scan tail and skip name with possible spaces
strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after return from function
return cKey;
}
char* ChatHandler::extractKeyFromLink(char* text, char const* const* linkTypes, int* found_idx, char** something1)
{
// skip empty
if (!text)
return NULL;
// skip spaces
while (*text == ' '||*text == '\t'||*text == '\b')
++text;
if (!*text)
return NULL;
// return non link case
if (text[0] != '|')
return strtok(text, " ");
// [name] Shift-click form |color|linkType:key|h[name]|h|r
// or
// [name] Shift-click form |color|linkType:key:something1:...:somethingN|h[name]|h|r
// or
// [name] Shift-click form |linkType:key|h[name]|h|r
char* tail;
if (text[1] == 'c')
{
char* check = strtok(text, "|"); // skip color
if (!check)
return NULL; // end of data
tail = strtok(NULL, ""); // tail
}
else
tail = text+1; // skip first |
char* cLinkType = strtok(tail, ":"); // linktype
if (!cLinkType)
return NULL; // end of data
for (int i = 0; linkTypes[i]; ++i)
{
if (strcmp(cLinkType, linkTypes[i]) == 0)
{
char* cKeys = strtok(NULL, "|"); // extract keys and values
char* cKeysTail = strtok(NULL, "");
char* cKey = strtok(cKeys, ":|"); // extract key
if (something1)
*something1 = strtok(NULL, ":|"); // extract something
strtok(cKeysTail, "]"); // restart scan tail and skip name with possible spaces
strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after return from function
if (found_idx)
*found_idx = i;
return cKey;
}
}
strtok(NULL, " "); // skip link tail (to allow continue strtok(NULL, s) use after return from function
SendSysMessage(LANG_WRONG_LINK_TYPE);
return NULL;
}
GameObject* ChatHandler::GetNearbyGameObject()
{
if (!m_session)
return NULL;
Player* pl = m_session->GetPlayer();
GameObject* obj = NULL;
Trinity::NearestGameObjectCheck check(*pl);
Trinity::GameObjectLastSearcher<Trinity::NearestGameObjectCheck> searcher(pl, obj, check);
pl->VisitNearbyGridObject(999, searcher);
return obj;
}
GameObject* ChatHandler::GetObjectGlobalyWithGuidOrNearWithDbGuid(uint32 lowguid, uint32 entry)
{
if (!m_session)
return NULL;
Player* pl = m_session->GetPlayer();
GameObject* obj = pl->GetMap()->GetGameObject(MAKE_NEW_GUID(lowguid, entry, HIGHGUID_GAMEOBJECT));
if (!obj && sObjectMgr->GetGOData(lowguid)) // guid is DB guid of object
{
// search near player then
CellPair p(Trinity::ComputeCellPair(pl->GetPositionX(), pl->GetPositionY()));
Cell cell(p);
cell.data.Part.reserved = ALL_DISTRICT;
Trinity::GameObjectWithDbGUIDCheck go_check(*pl, lowguid);
Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck> checker(pl, obj, go_check);
TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
cell.Visit(p, object_checker, *pl->GetMap());
}
return obj;
}
enum SpellLinkType
{
SPELL_LINK_SPELL = 0,
SPELL_LINK_TALENT = 1,
SPELL_LINK_ENCHANT = 2,
SPELL_LINK_TRADE = 3,
SPELL_LINK_GLYPH = 4
};
static char const* const spellKeys[] =
{
"Hspell", // normal spell
"Htalent", // talent spell
"Henchant", // enchanting recipe spell
"Htrade", // profession/skill spell
"Hglyph", // glyph
0
};
uint32 ChatHandler::extractSpellIdFromLink(char* text)
{
// number or [name] Shift-click form |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r
// number or [name] Shift-click form |color|Hglyph:glyph_slot_id:glyph_prop_id|h[%s]|h|r
// number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r
// number or [name] Shift-click form |color|Htalent:talent_id, rank|h[name]|h|r
// number or [name] Shift-click form |color|Htrade:spell_id, skill_id, max_value, cur_value|h[name]|h|r
int type = 0;
char* param1_str = NULL;
char* idS = extractKeyFromLink(text, spellKeys, &type, ¶m1_str);
if (!idS)
return 0;
uint32 id = (uint32)atol(idS);
switch(type)
{
case SPELL_LINK_SPELL:
return id;
case SPELL_LINK_TALENT:
{
// talent
TalentEntry const* talentEntry = sTalentStore.LookupEntry(id);
if (!talentEntry)
return 0;
int32 rank = param1_str ? (uint32)atol(param1_str) : 0;
if (rank >= MAX_TALENT_RANK)
return 0;
if (rank < 0)
rank = 0;
return talentEntry->RankID[rank];
}
case SPELL_LINK_ENCHANT:
case SPELL_LINK_TRADE:
return id;
case SPELL_LINK_GLYPH:
{
uint32 glyph_prop_id = param1_str ? (uint32)atol(param1_str) : 0;
GlyphPropertiesEntry const* glyphPropEntry = sGlyphPropertiesStore.LookupEntry(glyph_prop_id);
if (!glyphPropEntry)
return 0;
return glyphPropEntry->SpellId;
}
}
// unknown type?
return 0;
}
GameTele const* ChatHandler::extractGameTeleFromLink(char* text)
{
// id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r
char* cId = extractKeyFromLink(text, "Htele");
if (!cId)
return false;
// id case (explicit or from shift link)
if (cId[0] >= '0' || cId[0] >= '9')
if (uint32 id = atoi(cId))
return sObjectMgr->GetGameTele(id);
return sObjectMgr->GetGameTele(cId);
}
enum GuidLinkType
{
SPELL_LINK_PLAYER = 0, // must be first for selection in not link case
SPELL_LINK_CREATURE = 1,
SPELL_LINK_GAMEOBJECT = 2
};
static char const* const guidKeys[] =
{
"Hplayer",
"Hcreature",
"Hgameobject",
0
};
uint64 ChatHandler::extractGuidFromLink(char* text)
{
int type = 0;
// |color|Hcreature:creature_guid|h[name]|h|r
// |color|Hgameobject:go_guid|h[name]|h|r
// |color|Hplayer:name|h[name]|h|r
char* idS = extractKeyFromLink(text, guidKeys, &type);
if (!idS)
return 0;
switch(type)
{
case SPELL_LINK_PLAYER:
{
std::string name = idS;
if (!normalizePlayerName(name))
return 0;
if (Player* player = sObjectMgr->GetPlayer(name.c_str()))
return player->GetGUID();
if (uint64 guid = sObjectMgr->GetPlayerGUIDByName(name))
return guid;
return 0;
}
case SPELL_LINK_CREATURE:
{
uint32 lowguid = (uint32)atol(idS);
if (CreatureData const* data = sObjectMgr->GetCreatureData(lowguid))
return MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_UNIT);
else
return 0;
}
case SPELL_LINK_GAMEOBJECT:
{
uint32 lowguid = (uint32)atol(idS);
if (GameObjectData const* data = sObjectMgr->GetGOData(lowguid))
return MAKE_NEW_GUID(lowguid, data->id, HIGHGUID_GAMEOBJECT);
else
return 0;
}
}
// unknown type?
return 0;
}
std::string ChatHandler::extractPlayerNameFromLink(char* text)
{
// |color|Hplayer:name|h[name]|h|r
char* name_str = extractKeyFromLink(text, "Hplayer");
if (!name_str)
return "";
std::string name = name_str;
if (!normalizePlayerName(name))
return "";
return name;
}
bool ChatHandler::extractPlayerTarget(char* args, Player** player, uint64* player_guid /*=NULL*/, std::string* player_name /*= NULL*/)
{
if (args && *args)
{
std::string name = extractPlayerNameFromLink(args);
if (name.empty())
{
SendSysMessage(LANG_PLAYER_NOT_FOUND);
SetSentErrorMessage(true);
return false;
}
Player* pl = sObjectMgr->GetPlayer(name.c_str());
// if allowed player pointer
if (player)
*player = pl;
// if need guid value from DB (in name case for check player existence)
uint64 guid = !pl && (player_guid || player_name) ? sObjectMgr->GetPlayerGUIDByName(name) : 0;
// if allowed player guid (if no then only online players allowed)
if (player_guid)
*player_guid = pl ? pl->GetGUID() : guid;
if (player_name)
*player_name = pl || guid ? name : "";
}
else
{
Player* pl = getSelectedPlayer();
// if allowed player pointer
if (player)
*player = pl;
// if allowed player guid (if no then only online players allowed)
if (player_guid)
*player_guid = pl ? pl->GetGUID() : 0;
if (player_name)
*player_name = pl ? pl->GetName() : "";
}
// some from req. data must be provided (note: name is empty if player not exist)
if ((!player || !*player) && (!player_guid || !*player_guid) && (!player_name || player_name->empty()))
{
SendSysMessage(LANG_PLAYER_NOT_FOUND);
SetSentErrorMessage(true);
return false;
}
return true;
}
void ChatHandler::extractOptFirstArg(char* args, char** arg1, char** arg2)
{
char* p1 = strtok(args, " ");
char* p2 = strtok(NULL, " ");
if (!p2)
{
p2 = p1;
p1 = NULL;
}
if (arg1)
*arg1 = p1;
if (arg2)
*arg2 = p2;
}
char* ChatHandler::extractQuotedArg(char* args)
{
if (!*args)
return NULL;
if (*args == '"')
return strtok(args+1, "\"");
else
{
char* space = strtok(args, "\"");
if (!space)
return false;
return strtok(NULL, "\"");
}
}
bool ChatHandler::needReportToTarget(Player* chr) const
{
Player* pl = m_session->GetPlayer();
return pl != chr && pl->IsVisibleGloballyFor(chr);
}
LocaleConstant ChatHandler::GetSessionDbcLocale() const
{
return m_session->GetSessionDbcLocale();
}
int ChatHandler::GetSessionDbLocaleIndex() const
{
return m_session->GetSessionDbLocaleIndex();
}
const char *CliHandler::GetTrinityString(int32 entry) const
{
return sObjectMgr->GetTrinityStringForDBCLocale(entry);
}
bool CliHandler::isAvailable(ChatCommand const& cmd) const
{
// skip non-console commands in console case
return cmd.AllowConsole;
}
void CliHandler::SendSysMessage(const char *str)
{
m_print(m_callbackArg, str);
m_print(m_callbackArg, "\r\n");
}
std::string CliHandler::GetNameLink() const
{
return GetTrinityString(LANG_CONSOLE_COMMAND);
}
bool CliHandler::needReportToTarget(Player* /*chr*/) const
{
return true;
}
bool ChatHandler::GetPlayerGroupAndGUIDByName(const char* cname, Player* &plr, Group* &group, uint64 &guid, bool offline)
{
plr = NULL;
guid = 0;
if (cname)
{
std::string name = cname;
if (!name.empty())
{
if (!normalizePlayerName(name))
{
PSendSysMessage(LANG_PLAYER_NOT_FOUND);
SetSentErrorMessage(true);
return false;
}
plr = sObjectMgr->GetPlayer(name.c_str());
if (offline)
guid = sObjectMgr->GetPlayerGUIDByName(name.c_str());
}
}
if (plr)
{
group = plr->GetGroup();
if (!guid || !offline)
guid = plr->GetGUID();
}
else
{
if (getSelectedPlayer())
plr = getSelectedPlayer();
else
plr = m_session->GetPlayer();
if (!guid || !offline)
guid = plr->GetGUID();
group = plr->GetGroup();
}
return true;
}
LocaleConstant CliHandler::GetSessionDbcLocale() const
{
return sWorld->GetDefaultDbcLocale();
}
int CliHandler::GetSessionDbLocaleIndex() const
{
return sObjectMgr->GetDBCLocaleIndex();
}
| Frimost/IceLands | src/server/game/Chat/Chat.cpp | C++ | gpl-2.0 | 68,462 |
/*
* equalcolumnheight
* https://github.com/mortennajbjerg/jquery.equalcolumnheight
*
* Copyright (c) 2013 Morten Najbjerg
* Licensed under the GPLv3 license.
*/
(function($) {
$.fn.equalcolumnheight = function() {
var $this = $(this),
heighest = 0;
// Calculate the heighest element and return integer
var getHeighestValue = function() {
var heights = getElementsHeight();
return Math.max.apply($this, heights );
};
// Return array of all element heights
var getElementsHeight = function() {
return $.map( $this , function(e){ return $(e).outerHeight(); });
};
// Set a height on all elements
var setElementsHeight = function(value) {
$this.css('height', value);
};
var init = function() {
setElementsHeight('auto');
heighest = getHeighestValue();
setElementsHeight(heighest);
};
// Set resize
$( window ).resize(function() {
init();
});
// Make sure that this works even
// if the columns has images inside them
$( window ).load(function() {
init();
});
init();
};
}(jQuery));
| mortennajbjerg/jquery.equalcolumnheight | src/equalcolumnheight.js | JavaScript | gpl-2.0 | 1,351 |
/* Copyright (C) 2004 - 2009 Versant Inc. http://www.db4o.com */
using Db4objects.Db4o.IO;
namespace Db4objects.Db4o.IO
{
/// <exclude></exclude>
public class DebugIoAdapter : VanillaIoAdapter
{
internal static int counter;
private static readonly int[] RangeOfInterest = new int[] { 0, 20 };
public DebugIoAdapter(IoAdapter delegateAdapter) : base(delegateAdapter)
{
}
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception>
protected DebugIoAdapter(IoAdapter delegateAdapter, string path, bool lockFile, long
initialLength, bool readOnly) : base(delegateAdapter.Open(path, lockFile, initialLength
, readOnly))
{
}
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception>
public override IoAdapter Open(string path, bool lockFile, long initialLength, bool
readOnly)
{
return new Db4objects.Db4o.IO.DebugIoAdapter(new RandomAccessFileAdapter(), path,
lockFile, initialLength, readOnly);
}
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception>
public override void Seek(long pos)
{
if (pos >= RangeOfInterest[0] && pos <= RangeOfInterest[1])
{
counter++;
Sharpen.Runtime.Out.WriteLine("seek: " + pos + " counter: " + counter);
}
base.Seek(pos);
}
}
}
| meebey/smuxi-head-mirror | lib/db4o-net/Db4objects.Db4o.Optional/Db4objects.Db4o/IO/DebugIoAdapter.cs | C# | gpl-2.0 | 1,325 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace MusicCollection.ToolBox.Web
{
internal class HttpWebResponseWrapped : IHttpWebResponse, IDisposable
{
private HttpWebResponse _Wrapped;
internal HttpWebResponseWrapped(HttpWebResponse iWrapped)
{
_Wrapped = iWrapped;
}
public HttpStatusCode StatusCode { get { return _Wrapped.StatusCode; } }
public Stream GetResponseStream()
{
return _Wrapped.GetResponseStream();
}
public string ContentEncoding { get { return _Wrapped.ContentEncoding; } }
public void Dispose()
{
IDisposable id = _Wrapped;
id.Dispose();
}
public void Close()
{
_Wrapped.Close();
}
}
}
| David-Desmaisons/MusicCollection | MusicCollection/ToolBox/Web/HttpWebResponseWrapped.cs | C# | gpl-2.0 | 887 |
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="http://ultimate.brainstormforce.com/wp-content/uploads/smile_fonts/Ultimate-set/A.Ultimate-set.css.pagespeed.cf.0xSe2I2K70.css">
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<div class="my-page">
<div class="my-page-item-style2">
<figure class="front-side-style2">
<div class="box-section">
<div class="box-icon">
<div class="icon-circle">
<i class="image-font"></i>
</div>
</div>
<h3 class="box-section-title-style2">Unlimited Possibilities</h3>
<div class="box-section-content-style2">
<p>Built with you in mind, it's super clean, sleek and simply pleasure to use.</p>
</div>
</div>
</figure>
<figure class="back-side-style2">
<div class="box-section">
<h3 class="box-section-title-style2">More info</h3>
<div class="box-section-content-style2">
<p>We give a lot of time and effort to ensure our users love to use our themes. It makes us smile.</p>
</div>
<div class="box-section-link-style2">
<a href="#">Get Information!</a>
</div>
</div>
</figure>
</div>
</div>
</body>
</html> | vova95/motoWidget | test/style6/index.html | HTML | gpl-2.0 | 1,322 |
define([
"jquery",
"fx-cat-br/widgets/Fx-widgets-commons",
'text!fx-cat-br/json/fx-catalog-collapsible-menu-config.json',
"lib/bootstrap"
], function ($, W_Commons, conf) {
var o = { },
defaultOptions = {
widget: {
lang: 'EN'
},
events: {
SELECT: 'fx.catalog.module.select'
}
};
var cache = {},
w_Commons, $collapse;
function Fx_Catalog_Collapsible_Menu() {
w_Commons = new W_Commons();
}
Fx_Catalog_Collapsible_Menu.prototype.init = function (options) {
//Merge options
$.extend(o, defaultOptions);
$.extend(o, options);
};
Fx_Catalog_Collapsible_Menu.prototype.render = function (options) {
$.extend(o, options);
cache.json = JSON.parse(conf);
this.initStructure();
this.renderMenu(cache.json);
};
Fx_Catalog_Collapsible_Menu.prototype.initStructure = function () {
o.collapseId = "fx-collapse-" + w_Commons.getFenixUniqueId();
$collapse = $('<div class="panel-group" id="accordion"></div>');
$collapse.attr("id", o.collapseId);
$(o.container).append($collapse);
};
Fx_Catalog_Collapsible_Menu.prototype.renderMenu = function (json) {
var self = this;
if (json.hasOwnProperty("panels")) {
var panels = json.panels;
for (var i = 0; i < panels.length; i++) {
$collapse.append(self.buildPanel(panels[i]))
}
$(o.container).append($collapse)
} else {
throw new Error("Fx_Catalog_Collapsible_Menu: no 'panels' attribute in config JSON.")
}
};
Fx_Catalog_Collapsible_Menu.prototype.buildPanel = function (panel) {
var self = this,
id = "fx-collapse-panel-" + w_Commons.getFenixUniqueId();
var $p = $(document.createElement("DIV"));
$p.addClass("panel");
$p.addClass("panel-default");
$p.append(self.buildPanelHeader(panel, id));
$p.append(self.buildPanelBody(panel, id));
return $p;
};
Fx_Catalog_Collapsible_Menu.prototype.buildPanelHeader = function (panel, id) {
//Init header
var $header = $('<div class="panel-heading"></div>'),
$title = $('<h4 class="panel-title fx-menu-category-title"></h4>'),
$a = $('<a data-toggle="collapse"></a>'),
$info = $('<div class="fx-catalog-modular-menu-category-info"></div>'),
$plus = $('<div class="fx-catalog-modular-menu-category-plus"></div>');
$a.attr("data-parent", "#" + o.collapseId);
$a.attr("href", "#" + id);
if (panel.hasOwnProperty("title")) {
$a.html(panel["title"][o.widget.lang]);
}
return $header.append($title.append($a.append($plus)).append($info));
};
Fx_Catalog_Collapsible_Menu.prototype.buildPanelBody = function (panel, id) {
//Init panel body
var $bodyContainer = $("<div class='panel-collapse collapse'></div>");
$bodyContainer.attr("id", id);
var $body = $('<div class="panel-body"></div>');
if (panel.hasOwnProperty("modules")) {
var modules = panel["modules"];
for (var j = 0; j < modules.length; j++) {
var $module = $("<div></div>"),
$btn = $('<button type="button" class="btn btn-default btn-block"></button>');
$btn.on('click', {module: modules[j] }, function (e) {
var $btn = $(this);
if ($btn.is(':disabled') === false) {
$btn.attr("disabled", "disabled");
w_Commons.raiseCustomEvent(o.container, o.events.SELECT, e.data.module)
}
});
if (modules[j].hasOwnProperty("id")) {
$btn.attr("id", modules[j].id);
}
if (modules[j].hasOwnProperty("module")) {
$btn.attr("data-module", modules[j].module);
}
//Keep it before the label to have the icon in its the left side
if (modules[j].hasOwnProperty("icon")) {
$btn.append($('<span class="' + modules[j].icon + '"></span>'));
}
if (modules[j].hasOwnProperty("label")) {
$btn.append(modules[j].label[o.widget.lang]);
}
if (modules[j].hasOwnProperty("popover")) {
/* console.log(modules[j]["popover"])
var keys = Object.keys(modules[j]["popover"]);
for (var k = 0; k < keys.length; k++ ){
$btn.attr(keys[k], modules[j]["popover"][keys[k]])
}*/
}
$module.append($btn);
$body.append($module)
}
}
return $bodyContainer.append($body);
};
Fx_Catalog_Collapsible_Menu.prototype.disable = function (module) {
$(o.container).find("[data-module='" + module + "']").attr("disabled", "disabled");
};
Fx_Catalog_Collapsible_Menu.prototype.activate = function (module) {
$(o.container).find("[data-module='" + module + "']").removeAttr("disabled");
};
return Fx_Catalog_Collapsible_Menu;
}); | FENIX-Platform/fenix-catalog | fenix-catalog-bridge/src/main/js/catalog/widgets/filter/Fx-catalog-collapsible-menu.js | JavaScript | gpl-2.0 | 5,443 |
\documentclass{report}
\usepackage{hyperref}
% WARNING: THIS SHOULD BE MODIFIED DEPENDING ON THE LETTER/A4 SIZE
\oddsidemargin 0cm
\evensidemargin 0cm
\marginparsep 0cm
\marginparwidth 0cm
\parindent 0cm
\setlength{\textwidth}{\paperwidth}
\addtolength{\textwidth}{-2in}
% Conditional define to determine if pdf output is used
\newif\ifpdf
\ifx\pdfoutput\undefined
\pdffalse
\else
\pdfoutput=1
\pdftrue
\fi
\ifpdf
\usepackage[pdftex]{graphicx}
\else
\usepackage[dvips]{graphicx}
\fi
% Write Document information for pdflatex/pdftex
\ifpdf
\pdfinfo{
/Author (Pasdoc)
/Title ()
}
\fi
\begin{document}
\label{toc}\tableofcontents
\newpage
% special variable used for calculating some widths.
\newlength{\tmplength}
\chapter{Long descriptive name of my introduction}
\label{ok_introduction}
\index{ok{\_}introduction}
\label{SecFirst}
\section{First section}
This file is supposed to contain some introductory material about whole code included in your documentation. You can note that all rules that apply to normal pasdoc descriptions apply also here, e.g. empty line means new paragraph:
New paragraph.
3rd paragraph. URLs are automatically recognized, like this: \href{http://pasdoc.sourceforge.net/}{http://pasdoc.sourceforge.net/}. You have to write the @ twice (like @@) to get one @ in the output. Also normal @{-}tags work: \begin{ttfamily}This is some code.\end{ttfamily}
\label{SecSecond}
\section{Second section}
Here you can see some hot snippet from implementation of this feature, just to test @longcode tag:
\texttt{\\\nopagebreak[3]
}\textbf{procedure}\texttt{~TPasDoc.HandleExtraFile(}\textbf{const}\texttt{~FileName:~}\textbf{string}\texttt{;\\\nopagebreak[3]
~~}\textbf{out}\texttt{~ExtraDescription:~TExtraDescription);\\\nopagebreak[3]
}\textbf{begin}\texttt{\\\nopagebreak[3]
~~ExtraDescription~:=~TExtraDescription.Create;\\\nopagebreak[3]
~~}\textbf{try}\texttt{\\\nopagebreak[3]
~~~~DoMessage(2,~mtInformation,~'Now~parsing~file~{\%}s...',~[FileName]);\\\nopagebreak[3]
\\\nopagebreak[3]
~~~~ExtraDescription.}\textbf{Name}\texttt{~:=~SCharsReplace(\\\nopagebreak[3]
~~~~~~ChangeFileExt(~ExtractFileName(FileName)~,~''),~['~'],~'{\_}');\\\nopagebreak[3]
\\\nopagebreak[3]
~~~~ExtraDescription.RawDescription~:=~FileToString(FileName);\\\nopagebreak[3]
~~}\textbf{except}\texttt{\\\nopagebreak[3]
~~~~FreeAndNil(ExtraDescription);\\\nopagebreak[3]
~~~~}\textbf{raise}\texttt{;\\\nopagebreak[3]
~~}\textbf{end}\texttt{;\\\nopagebreak[3]
}\textbf{end}\texttt{;\\
}
\label{ThirdSecond}
\section{Third section}
Normal links work : \begin{ttfamily}MyConstant\end{ttfamily}(\ref{ok_introduction_conclusion-MyConstant}).
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
\label{SomeAnchor}
Here is a paragraph with an anchor. It looks like a normal paragraph, but you can link to it with @link(SomeAnchor).
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Sections with the same user{-}visible names are OK (example when this is useful is below):
\label{SecStrings}
\section{Routines dealing with strings}
\label{SecStringsOverview}
\ifpdf
\subsection*{\large{\textbf{Overview}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Overview}
\fi
\label{SecStringsExamples}
\ifpdf
\subsection*{\large{\textbf{Examples}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Examples}
\fi
\label{SecIntegers}
\section{Routines dealing with integers}
\label{SecIntegersOverview}
\ifpdf
\subsection*{\large{\textbf{Overview}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Overview}
\fi
\label{SecIntegersExamples}
\ifpdf
\subsection*{\large{\textbf{Examples}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Examples}
\fi
\section{Author}
\par
Kambi
\section{Created}
\par
On some rainy day
\chapter{Unit ok{\_}introduction{\_}conclusion}
\label{ok_introduction_conclusion}
\index{ok{\_}introduction{\_}conclusion}
\section{Constants}
\ifpdf
\subsection*{\large{\textbf{MyConstant}}\normalsize\hspace{1ex}\hrulefill}
\else
\subsection*{MyConstant}
\fi
\label{ok_introduction_conclusion-MyConstant}
\index{MyConstant}
\begin{list}{}{
\settowidth{\tmplength}{\textbf{Description}}
\setlength{\itemindent}{0cm}
\setlength{\listparindent}{0cm}
\setlength{\leftmargin}{\evensidemargin}
\addtolength{\leftmargin}{\tmplength}
\settowidth{\labelsep}{X}
\addtolength{\leftmargin}{\labelsep}
\setlength{\labelwidth}{\tmplength}
}
\item[\textbf{Declaration}\hfill]
\ifpdf
\begin{flushleft}
\fi
\begin{ttfamily}
MyConstant = 1;\end{ttfamily}
\ifpdf
\end{flushleft}
\fi
\par
\item[\textbf{Description}]
This is some constant, with a link to my introduction: \begin{ttfamily}ok{\_}introduction\end{ttfamily}(\ref{ok_introduction}) and \begin{ttfamily}My conclusion\end{ttfamily}(\ref{ok_conclusion}). Link to \begin{ttfamily}second section of introduction\end{ttfamily}(\ref{SecSecond}), link to \begin{ttfamily}some anchor in introduction\end{ttfamily}(\ref{SomeAnchor})
\end{list}
\chapter{Long descriptive name of the first additional file:}
\label{ok_additionalfile1}
\index{ok{\_}additionalfile1}
\label{SecFirst}
\section{First section}
This file is supposed to contain any additional information that you wish to include in your documentation. You can note that all rules that apply to normal pasdoc descriptions apply also here, e.g. empty line means new paragraph:
New paragraph.
3rd paragraph. URLs are automatically recognized, like this: \href{http://pasdoc.sourceforge.net/}{http://pasdoc.sourceforge.net/}. You have to write the @ twice (like @@) to get one @ in the output. Also normal @{-}tags work: \begin{ttfamily}This is some code.\end{ttfamily}
\label{SecSecond}
\section{Second section}
Here you can see some hot snippet from implementation of this feature, just to test @longcode tag:
\texttt{\\\nopagebreak[3]
}\textbf{procedure}\texttt{~TPasDoc.HandleExtraFile(}\textbf{const}\texttt{~FileName:~}\textbf{string}\texttt{;\\\nopagebreak[3]
~~}\textbf{out}\texttt{~ExtraDescription:~TExtraDescription);\\\nopagebreak[3]
}\textbf{begin}\texttt{\\\nopagebreak[3]
~~ExtraDescription~:=~TExtraDescription.Create;\\\nopagebreak[3]
~~}\textbf{try}\texttt{\\\nopagebreak[3]
~~~~DoMessage(2,~mtInformation,~'Now~parsing~file~{\%}s...',~[FileName]);\\\nopagebreak[3]
\\\nopagebreak[3]
~~~~ExtraDescription.}\textbf{Name}\texttt{~:=~SCharsReplace(\\\nopagebreak[3]
~~~~~~ChangeFileExt(~ExtractFileName(FileName)~,~''),~['~'],~'{\_}');\\\nopagebreak[3]
\\\nopagebreak[3]
~~~~ExtraDescription.RawDescription~:=~FileToString(FileName);\\\nopagebreak[3]
~~}\textbf{except}\texttt{\\\nopagebreak[3]
~~~~FreeAndNil(ExtraDescription);\\\nopagebreak[3]
~~~~}\textbf{raise}\texttt{;\\\nopagebreak[3]
~~}\textbf{end}\texttt{;\\\nopagebreak[3]
}\textbf{end}\texttt{;\\
}
\label{ThirdSecond}
\section{Third section}
Normal links work : \begin{ttfamily}MyConstant\end{ttfamily}(\ref{ok_introduction_conclusion-MyConstant}).
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
\label{SomeAnchor}
Here is a paragraph with an anchor. It looks like a normal paragraph, but you can link to it with @link(SomeAnchor).
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Sections with the same user{-}visible names are OK (example when this is useful is below):
\label{SecStrings}
\section{Routines dealing with strings}
\label{SecStringsOverview}
\ifpdf
\subsection*{\large{\textbf{Overview}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Overview}
\fi
\label{SecStringsExamples}
\ifpdf
\subsection*{\large{\textbf{Examples}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Examples}
\fi
\label{SecIntegers}
\section{Routines dealing with integers}
\label{SecIntegersOverview}
\ifpdf
\subsection*{\large{\textbf{Overview}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Overview}
\fi
\label{SecIntegersExamples}
\ifpdf
\subsection*{\large{\textbf{Examples}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Examples}
\fi
\section{Author}
\par
Kambi
\section{Created}
\par
On some rainy day
\chapter{Long descriptive name of the second additional file:}
\label{ok_additionalfile2}
\index{ok{\_}additionalfile2}
\label{SecFirst}
\section{First section}
This file is supposed to contain any additional information that you wish to include in your documentation. You can note that all rules that apply to normal pasdoc descriptions apply also here, e.g. empty line means new paragraph:
New paragraph.
3rd paragraph. URLs are automatically recognized, like this: \href{http://pasdoc.sourceforge.net/}{http://pasdoc.sourceforge.net/}. You have to write the @ twice (like @@) to get one @ in the output. Also normal @{-}tags work: \begin{ttfamily}This is some code.\end{ttfamily}
\label{SecSecond}
\section{Second section}
Here you can see some hot snippet from implementation of this feature, just to test @longcode tag:
\texttt{\\\nopagebreak[3]
}\textbf{procedure}\texttt{~TPasDoc.HandleExtraFile(}\textbf{const}\texttt{~FileName:~}\textbf{string}\texttt{;\\\nopagebreak[3]
~~}\textbf{out}\texttt{~ExtraDescription:~TExtraDescription);\\\nopagebreak[3]
}\textbf{begin}\texttt{\\\nopagebreak[3]
~~ExtraDescription~:=~TExtraDescription.Create;\\\nopagebreak[3]
~~}\textbf{try}\texttt{\\\nopagebreak[3]
~~~~DoMessage(2,~mtInformation,~'Now~parsing~file~{\%}s...',~[FileName]);\\\nopagebreak[3]
\\\nopagebreak[3]
~~~~ExtraDescription.}\textbf{Name}\texttt{~:=~SCharsReplace(\\\nopagebreak[3]
~~~~~~ChangeFileExt(~ExtractFileName(FileName)~,~''),~['~'],~'{\_}');\\\nopagebreak[3]
\\\nopagebreak[3]
~~~~ExtraDescription.RawDescription~:=~FileToString(FileName);\\\nopagebreak[3]
~~}\textbf{except}\texttt{\\\nopagebreak[3]
~~~~FreeAndNil(ExtraDescription);\\\nopagebreak[3]
~~~~}\textbf{raise}\texttt{;\\\nopagebreak[3]
~~}\textbf{end}\texttt{;\\\nopagebreak[3]
}\textbf{end}\texttt{;\\
}
\label{ThirdSecond}
\section{Third section}
Normal links work : \begin{ttfamily}MyConstant\end{ttfamily}(\ref{ok_introduction_conclusion-MyConstant}).
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
\label{SomeAnchor}
Here is a paragraph with an anchor. It looks like a normal paragraph, but you can link to it with @link(SomeAnchor).
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Blah.
Sections with the same user{-}visible names are OK (example when this is useful is below):
\label{SecStrings}
\section{Routines dealing with strings}
\label{SecStringsOverview}
\ifpdf
\subsection*{\large{\textbf{Overview}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Overview}
\fi
\label{SecStringsExamples}
\ifpdf
\subsection*{\large{\textbf{Examples}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Examples}
\fi
\label{SecIntegers}
\section{Routines dealing with integers}
\label{SecIntegersOverview}
\ifpdf
\subsection*{\large{\textbf{Overview}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Overview}
\fi
\label{SecIntegersExamples}
\ifpdf
\subsection*{\large{\textbf{Examples}}\normalsize\hspace{1ex}\hrulefill}\else
\subsection*{Examples}
\fi
\section{Author}
\par
Kambi
\section{Created}
\par
On some rainy day
\chapter{Conclusion}
\label{ok_conclusion}
\index{ok{\_}conclusion}
Some conclusion text.\end{document}
| michaliskambi/pasdoc | tests/testcases_output/latex/ok_introduction_conclusion_additional/docs.tex | TeX | gpl-2.0 | 11,159 |
/**
* Calculon - A Java chess-engine.
*
* Copyright (C) 2008-2009 Barry Smith
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package barrysw19.calculon.analyzer;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.util.Arrays;
public class KingSafetyScorerTest extends AbstractAnalyserTest {
public KingSafetyScorerTest() {
super(new KingSafetyScorer());
}
@Test
public void testStart() {
assertScore(0, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1");
}
@Test
public void testCastled() {
assertScore(250, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQ1RK1 w - - 0 1");
}
@Test
public void testPawnGone() {
System.out.println(Arrays.toString(ImageIO.getReaderMIMETypes()));
assertScore(-70, "rnbq1rk1/1ppppppp/8/8/8/8/PPPPPP1P/RNBQ1RK1 w - - 0 1");
}
@Test
public void testFiancettoed() {
assertScore(-30, "rnbq1rk1/pppppppp/8/8/8/8/PPPPPPBP/RNBQ1RK1 w - - 0 1");
}
@Test
public void testFiancettoedNoBishop() {
assertScore(210, "6k1/1q6/8/8/8/Q7/5PPP/6K1 w - - 0 1");
assertScore(180, "6k1/1q6/8/8/8/Q5P1/5PBP/6K1 w - - 0 1");
assertScore(140, "6k1/1q6/8/8/8/Q5P1/5P1P/6K1 w - - 0 1");
}
}
| BarrySW19/CalculonX | src/test/java/barrysw19/calculon/analyzer/KingSafetyScorerTest.java | Java | gpl-2.0 | 1,728 |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
namespace Creek.UI.HTMLRenderer.Entities
{
/// <summary>
/// Raised when an error occured during html rendering.
/// </summary>
public sealed class HtmlRenderErrorEventArgs : EventArgs
{
/// <summary>
/// the exception that occured (can be null)
/// </summary>
private readonly Exception _exception;
/// <summary>
/// the error message
/// </summary>
private readonly string _message;
/// <summary>
/// error type that is reported
/// </summary>
private readonly HtmlRenderErrorType _type;
/// <summary>
/// Init.
/// </summary>
/// <param name="type">the type of error to report</param>
/// <param name="message">the error message</param>
/// <param name="exception">optional: the exception that occured</param>
public HtmlRenderErrorEventArgs(HtmlRenderErrorType type, string message, Exception exception = null)
{
_type = type;
_message = message;
_exception = exception;
}
/// <summary>
/// error type that is reported
/// </summary>
public HtmlRenderErrorType Type
{
get { return _type; }
}
/// <summary>
/// the error message
/// </summary>
public string Message
{
get { return _message; }
}
/// <summary>
/// the exception that occured (can be null)
/// </summary>
public Exception Exception
{
get { return _exception; }
}
public override string ToString()
{
return string.Format("Type: {0}", _type);
}
}
} | furesoft/Creek | Creek.UI/HTMLRenderer/Entities/HtmlRenderErrorEventArgs.cs | C# | gpl-2.0 | 2,073 |
package io.github.funkynoodles.projectcirkt;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
/**
* Created by Louis on 9/14/2015.
* contains contents for "Find" tab
*/
public class FindFragment extends Fragment {
//public ArrayList<String> listViewArray = new ArrayList<String>();
NearByClasses nbc = new NearByClasses();
public static FindFragment newInstance(){
FindFragment fragment = new FindFragment();
return fragment;
}
private HandleXML obj;
Button findBtn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_find, container, false);
Spinner spinner = (Spinner) myFragmentView.findViewById(R.id.timeSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.timeArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
findBtn = (Button)myFragmentView.findViewById(R.id.findButton);
findBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
obj = new HandleXML("http://courses.illinois.edu/cisapp/explorer/schedule/2015/fall/CS/225/35917.xml");
obj.fetchXML();
Intent intent = new Intent(v.getContext(),NearByClasses.class);
startActivity(intent);
getActivity().overridePendingTransition(R.animator.page_enter_animation, R.animator.page_exit_animation);
while(obj.parsingComplete);
NearByClasses.listViewArrayList.clear();
NearByClasses.listViewArrayList.add(obj.getCourseName() + ", " + obj.getSubjectName());
NearByClasses.listViewArrayList.add(obj.getSubjectID() + " " + obj.getCourseID());
NearByClasses.listViewArrayList.add(obj.getDescription());
NearByClasses.listViewArrayList.add(obj.getSectionNumber());
NearByClasses.listViewArrayList.add(obj.getSectionNotes());
NearByClasses.listViewArrayList.add(obj.getStatusCode());
NearByClasses.listViewArrayList.add(obj.getStartDate());
NearByClasses.listViewArrayList.add(obj.getEndDate());
NearByClasses.listViewArrayList.add(obj.getMeetingType());
NearByClasses.listViewArrayList.add(obj.getMeetingStart());
NearByClasses.listViewArrayList.add(obj.getMeetingEnd());
NearByClasses.listViewArrayList.add(obj.getDaysOfTheWeek());
NearByClasses.listViewArrayList.add(obj.getBuildingName() + " " + obj.getRoomNumber());
for(int loop1=0;loop1<obj.getInstructors().size();loop1++){
NearByClasses.listViewArrayList.add(obj.getInstructors().get(loop1));
}
//getActivity().finish();
//getActivity().overridePendingTransition(R.animator.page_exit_animation, R.animator.page_enter_animation);
}
});
return myFragmentView;
}
/**
* Called when Find button is pressed
*/
public void findClasses(View view){
}
} | FunkyNoodles/ProjectCirkt | app/src/main/java/io/github/funkynoodles/projectcirkt/FindFragment.java | Java | gpl-2.0 | 3,641 |
/***************************************************************************
SimpleMail - Copyright (C) 2000 Hynek Schlawack and Sebastian Bauer
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***************************************************************************/
/**
* @file string_lists.h
*/
#ifndef SM__STRING_LISTS_H
#define SM__STRING_LISTS_H
#ifndef SM__LISTS_H
#include "lists.h"
#endif
#include <string.h>
struct string_node
{
struct node node; /* embedded node struct */
char *string;
};
static inline int string_node_len(struct string_node *s)
{
return strlen(s->string);
}
struct string_list
{
struct list l;
};
/**
* Initialize the string list.
*
* @param list to be initialized
*/
void string_list_init(struct string_list *list);
/**
* Return the first string node of the given string list.
*
* @param list of which the first element should be returned
* @return the first element or NULL if the list is empty
*/
struct string_node *string_list_first(const struct string_list *list);
/**
* Return the last string node of the given string list.
*
* @param list of which the first element should be returned
* @return the first element or NULL if the list is empty
*/
struct string_node *string_list_last(const struct string_list *list);
/**
* @return the node following the given node.
*/
struct string_node *string_node_next(const struct string_node *node);
/**
* Insert the given string node at the tail of the given list.
*
* @param list the list at which the node should be inserted
* @param node the node to be inserted
*/
void string_list_insert_tail_node(struct string_list *list, struct string_node *node);
/**
* Insert the given node after the other given node.
*/
void string_list_insert_after(struct string_list *list, struct string_node *newnode, struct string_node *prednode);
/**
* Inserts a string into the end of a string list. The string will
* be duplicated. Nothing will be inserted if the string's length was 0.
*
* @param list the list to which to add the string.
* @param string the string to be added. The string will be duplicated.
* @return the newly created node that has just been inserted or NULL on memory
* failure or if length of string was 0.
*/
struct string_node *string_list_insert_tail(struct string_list *list, const char *string);
/**
* Inserts a string into the end of a string list. The string will
* be duplicated.
*
* @param list the list to which to add the string.
* @param string the string to be added. The string will be duplicated.
* @return the newly created node that has just been inserted or NULL on memory
* failure.
*/
struct string_node *string_list_insert_tail_always(struct string_list *list, const char *string);
/**
* Inserts a string into the end of a string list. The string will
* be duplicated but not more than len bytes.
*
* @param list the list to which to add the string.
* @param string the string to be added. The string will be duplicated.
* @param len the number of bytes to be copied.
* @return the newly created node that has just been inserted or NULL on memory
* failure or if length of string was 0.
*/
struct string_node *string_list_insert_tail_always_len(struct string_list *list, const char *string, int len);
/**
* Remove the head from the given string list.
*
* @param list the list from which the node should be removed.
* @return the head that has just been removed or NULL if the list was empty.
*/
struct string_node *string_list_remove_head(struct string_list *list);
/**
* Remove the tail of the given string list.
*
* @param list the list from which the node should be removed.
* @return the tail that has just been removed or NULL if the list was empty.
*/
struct string_node *string_list_remove_tail(struct string_list *list);
/**
* Clears the complete list by freeing all memory (including strings) but does
* not free the memory of the list itself.
*
* @param list the list whose element should be freed.
*/
void string_list_clear(struct string_list *list);
/**
* Exchange the contents of the two given string lists.
*
* @param a the first string list
* @param b the second string list
*/
void string_list_exchange(struct string_list *a, struct string_list *b);
/**
* Shortcut for calling string_list_clear() and free().
*
* @param list the list that should be cleared and freed.
*/
void string_list_free(struct string_list *list);
/**
* Looks for a given string node in the list and returns it.
* Search is case insensitive
*
* @param list
* @param str
* @return
*/
struct string_node *string_list_find(struct string_list *list, const char *str);
/**
* Locate the string_node of the given index.
*
* @return the string_node or NULL if it the list is not large enough.
*/
struct string_node *string_list_find_by_index(struct string_list *list, int index);
/**
* Determine the length of the given string list.
*
* @param l the list of which to determine the length.
* @return the length (number of nodes).
*/
int string_list_length(const struct string_list *l);
#endif
| sba1/simplemail | string_lists.h | C | gpl-2.0 | 5,742 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Sun Jan 11 16:07:12 EST 2015 -->
<title>net.minecraftforge.common.network Class Hierarchy (Forge API)</title>
<meta name="date" content="2015-01-11">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="net.minecraftforge.common.network Class Hierarchy (Forge API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/minecraftforge/common/config/package-tree.html">Prev</a></li>
<li><a href="../../../../net/minecraftforge/common/util/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/minecraftforge/common/network/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package net.minecraftforge.common.network</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">io.netty.channel.ChannelHandlerAdapter (implements io.netty.channel.ChannelHandler)
<ul>
<li type="circle">io.netty.channel.ChannelInboundHandlerAdapter (implements io.netty.channel.ChannelInboundHandler)
<ul>
<li type="circle">io.netty.channel.ChannelDuplexHandler (implements io.netty.channel.ChannelOutboundHandler)
<ul>
<li type="circle">io.netty.handler.codec.MessageToMessageCodec<INBOUND_IN,OUTBOUND_IN>
<ul>
<li type="circle">cpw.mods.fml.common.network.<a href="../../../../cpw/mods/fml/common/network/FMLIndexedMessageToMessageCodec.html" title="class in cpw.mods.fml.common.network"><span class="strong">FMLIndexedMessageToMessageCodec</span></a><A>
<ul>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/ForgeRuntimeCodec.html" title="class in net.minecraftforge.common.network"><span class="strong">ForgeRuntimeCodec</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/ServerToClientConnectionEstablishedHandler.html" title="class in net.minecraftforge.common.network"><span class="strong">ServerToClientConnectionEstablishedHandler</span></a></li>
<li type="circle">io.netty.channel.SimpleChannelInboundHandler<I>
<ul>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/DimensionMessageHandler.html" title="class in net.minecraftforge.common.network"><span class="strong">DimensionMessageHandler</span></a></li>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/FluidIdRegistryMessageHandler.html" title="class in net.minecraftforge.common.network"><span class="strong">FluidIdRegistryMessageHandler</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/ForgeMessage.html" title="class in net.minecraftforge.common.network"><span class="strong">ForgeMessage</span></a>
<ul>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/ForgeMessage.DimensionRegisterMessage.html" title="class in net.minecraftforge.common.network"><span class="strong">ForgeMessage.DimensionRegisterMessage</span></a></li>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/ForgeMessage.FluidIdMapMessage.html" title="class in net.minecraftforge.common.network"><span class="strong">ForgeMessage.FluidIdMapMessage</span></a></li>
</ul>
</li>
<li type="circle">net.minecraftforge.common.network.<a href="../../../../net/minecraftforge/common/network/ForgeNetworkHandler.html" title="class in net.minecraftforge.common.network"><span class="strong">ForgeNetworkHandler</span></a></li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/minecraftforge/common/config/package-tree.html">Prev</a></li>
<li><a href="../../../../net/minecraftforge/common/util/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/minecraftforge/common/network/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Gullanshire/Minecraft_Mod-The_Exorcist | 1.7.10_Forge_Documents/net/minecraftforge/common/network/package-tree.html | HTML | gpl-2.0 | 7,134 |
/*
Theme Name: Pho
Theme URI: http://demo.thematosoup.com/pho
Author: ThematoSoup
Author URI: http://thematosoup.com
Description: Lean, fast WordPress theme
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: pho
Domain Path: /languages/
Tags: one-column, two-columns, white, responsive-layout, custom-background, custom-colors, editor-style, featured-images, post-formats, sticky-post, theme-options, threaded-comments, translation-ready
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
Pho is based on Underscores http://underscores.me/, (C) 2012-2014 Automattic, Inc.
Resetting and rebuilding styles have been helped along thanks to the fine work of
Eric Meyer http://meyerweb.com/eric/tools/css/reset/index.html
along with Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/
and Blueprint http://www.blueprintcss.org/
*/
/*--------------------------------------------------------------
>>> TABLE OF CONTENTS:
----------------------------------------------------------------
1.0 - Reset
2.0 - Typography
3.0 - Layout
4.0 - Elements
5.0 - Forms
6.0 - Navigation
6.1 - Links
6.2 - Menus
7.0 - Accessibility
8.0 - Alignments
9.0 - Clearings
10.0 - Widgets
11.0 - Content
11.1 - Posts and pages
11.2 - Post Formats
11.3 - Comments
12.0 - Footer
12.1 - Infinite Scroll
13.0 - Media
13.1 - Captions
13.2 - Galleries
14.0 - Featured Content
15.0 - Media Queries
--------------------------------------------------------------*/
/*--------------------------------------------------------------
1.0 - Reset
--------------------------------------------------------------*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
border: 0;
font-family: inherit;
font-size: 100%;
font-style: inherit;
font-weight: inherit;
margin: 0;
outline: 0;
padding: 0;
vertical-align: baseline;
}
html {
font-size: 62.5%; /* Corrects text resizing oddly in IE6/7 when body font-size is set using em units http://clagnut.com/blog/348/#c790 */
overflow-y: scroll; /* Keeps page centered in all browsers regardless of content height */
-webkit-text-size-adjust: 100%; /* Prevents iOS text size adjust after orientation change, without disabling user zoom */
-ms-text-size-adjust: 100%; /* www.456bereastreet.com/archive/201012/controlling_text_size_in_safari_for_ios_without_disabling_user_zoom/ */
}
*,
*:before,
*:after { /* apply a natural box layout model to all elements; see http://www.paulirish.com/2012/box-sizing-border-box-ftw/ */
-webkit-box-sizing: border-box; /* Not needed for modern webkit but still used by Blackberry Browser 7.0; see http://caniuse.com/#search=box-sizing */
-moz-box-sizing: border-box; /* Still needed for Firefox 28; see http://caniuse.com/#search=box-sizing */
box-sizing: border-box;
}
body {
background: #fff;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
main,
nav,
section {
display: block;
}
ol, ul {
list-style: none;
}
table { /* tables still need 'cellspacing="0"' in the markup */
border-collapse: separate;
border-spacing: 0;
}
caption, th, td {
font-weight: normal;
text-align: left;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: "";
}
blockquote, q {
quotes: "" "";
}
a:focus {
outline: thin dotted;
}
a:hover,
a:active {
outline: 0;
}
a img {
border: 0;
}
/*--------------------------------------------------------------
2.0 Typography
--------------------------------------------------------------*/
body,
button,
input,
select,
textarea {
color: #404040;
font-family: Helvetica, sans-serif;
font-size: 18px;
font-size: 1.8rem;
line-height: 1.5;
}
h1, h2, h3, h4, h5, h6 {
font-family: Helvetica, sans-serif;
clear: both;
font-weight: normal;
margin: 1.5em 0 0.75em;
line-height: 1;
color: #1d1d1d;
}
h1 {
font-size: 36px;
font-size: 3.6rem;
}
h2 {
font-size: 30px;
font-size: 3rem;
}
h3 {
font-size: 24px;
font-size: 2.4rem;
}
h4 {
font-size: 21px;
font-size: 2.1rem;
}
h5 {
font-size: 18px;
font-size: 1.8rem;
}
h6 {
font-size: 15px;
font-size: 1.5rem;
}
p {
margin-bottom: 1.5em;
}
b, strong, dt {
font-weight: bold;
color: #1d1d1d;
}
dfn, cite, em, i {
font-style: italic;
}
blockquote {
margin: 2em 1.5em;
}
address {
margin: 0 0 1.5em;
}
pre {
background-color: rgba(0,0,0,0.025);
border: 1px solid rgba(0,0,0,0.05);
padding: 1.5em;
font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
font-size: 14px;
font-size: 1.4rem;
line-height: 1.6;
margin-bottom: 2em;
max-width: 100%;
overflow: auto;
}
code, kbd, tt, var {
font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
}
abbr, acronym {
border-bottom: 1px dotted #666;
cursor: help;
}
mark, ins {
background: #fff9c0;
text-decoration: none;
}
sup,
sub {
font-size: 75%;
height: 0;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
bottom: 1ex;
}
sub {
top: .5ex;
}
small {
font-size: 75%;
}
big {
font-size: 125%;
}
/*--------------------------------------------------------------
3.0 - Layout
--------------------------------------------------------------*/
.inner {
max-width: 1230px;
margin: 0 auto;
padding: 0 30px;
}
/* Content - Sidebar */
.content-area {
float: left;
margin: 0 -31.62393% 0 0;
width: 100%;
}
.site-main {
margin: 0 31.62393% 0 0;
padding-right: 30px;
}
.site-content .widget-area {
float: right;
width: 31.62393%;
}
/* Full width */
.no-sidebar #primary {
float: none;
}
.no-sidebar.single #primary .entry-title,
.no-sidebar.page #primary .entry-title {
padding-top: 30px;
}
.no-sidebar.layout-standard.blog #primary,
.no-sidebar.layout-standard.archive #primary,
.no-sidebar.single #primary .entry-header :not(.wp-post-image),
.no-sidebar.single #primary .entry-content,
.no-sidebar.single #primary .entry-footer,
.no-sidebar.single #primary .post-navigation,
.no-sidebar.page #primary .entry-header :not(.wp-post-image),
.no-sidebar.page #primary .entry-content,
.no-sidebar.page #primary .entry-footer,
.no-sidebar.page #primary .post-navigation {
float: none;
max-width: 800px;
margin-left: auto;
margin-right: auto;
}
.no-sidebar .site-main {
margin: 0;
padding-right: 0;
}
.error404 #primary {
max-width: 800px;
}
@media screen and (max-width: 800px) {
.content-area,
.site-main,
.site-content .widget-area {
float: none;
margin-left: 0;
margin-right: 0;
width: 100%;
}
.site-main {
padding-right: 0;
}
.site-main {
position: relative;
margin-bottom: 45px;
padding-bottom: 45px;
border-bottom: double 3px #f3f3f3;
}
.site-main:after {
content: '\f436';
position: absolute;
display: block;
width: 24px;
height: 24px;
font-size: 24px;
line-height: 24px;
font-family: Genericons;
-webkit-font-smoothing: antialiased;
color: #e5e5e5;
bottom: -14px;
left: 50%;
margin-left: -12px;
background: #fff;
}
}
#masthead,
#content {
margin-bottom: 45px;
}
.site-branding {
text-align: center;
padding: 60px 0;
}
.site-title {
margin: 0 0 0.2em;
font-size: 48px;
font-size: 4.8rem;
}
.site-title a,
.site-title a:visited {
color: #1d1d1d;
text-decoration: none;
}
.error404 .page-title {
margin-bottom: 0.5em;
}
.error404 .page-content {
padding: 40px 0;
}
.site-description {
font-size: 16px;
font-size: 1.6rem;
margin: 0;
font-weight: normal;
}
.site-footer {
clear: both;
width: 100%;
}
.custom-background-color #page,
.custom-background-image #page {
max-width: 1230px;
background: #fff;
margin: 0 auto;
}
/*--------------------------------------------------------------
4.0 Elements
--------------------------------------------------------------*/
hr {
background-color: #ccc;
border: 0;
height: 1px;
margin-bottom: 1.5em;
}
ul, ol {
margin: 0 0 2em 1.5em;
}
ul {
list-style: disc;
}
ol {
list-style: decimal;
}
li > ul,
li > ol {
margin-bottom: 0;
margin-left: 1.5em;
}
li ul {
list-style: square;
}
li ol {
list-style: lower-roman;
}
li li ul {
list-style: circle;
}
li li ol {
list-style: lower-alpha;
}
dt {
font-weight: bold;
}
dd {
margin: 0 1.5em 1.5em;
}
img {
height: auto; /* Make sure images are scaled correctly. */
max-width: 100%; /* Adhere to container width. */
}
figure {
margin: 0;
}
table {
margin: 0 0 1.5em;
width: 100%;
}
th {
font-weight: bold;
}
/*--------------------------------------------------------------
5.0 Forms
--------------------------------------------------------------*/
button,
input,
select,
textarea {
font-size: 100%; /* Corrects font size not being inherited in all browsers */
margin: 0; /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */
vertical-align: baseline; /* Improves appearance and consistency in all browsers */
}
button,
input[type="button"],
input[type="reset"],
input[type="submit"] {
border: none;
background: #e14546;
color: #fff;
cursor: pointer; /* Improves usability and consistency of cursor style between image-type 'input' and others */
-webkit-appearance: button; /* Corrects inability to style clickable 'input' types in iOS */
font-size: 14px;
font-size: 1.4rem;
line-height: 1;
padding: 1em 1.5em;
text-transform: uppercase;
}
button:hover,
input[type="button"]:hover,
input[type="reset"]:hover,
input[type="submit"]:hover,
#infinite-handle span:hover {
background: #555;
}
button:focus,
input[type="button"]:focus,
input[type="reset"]:focus,
input[type="submit"]:focus,
button:active,
input[type="button"]:active,
input[type="reset"]:active,
input[type="submit"]:active,
#infinite-handle span:focus,
#infinite-handle span:active {
background: #181818;
outline: none;
}
input[type="checkbox"],
input[type="radio"] {
padding: 0; /* Addresses excess padding in IE8/9 */
}
input[type="search"] {
-webkit-appearance: textfield; /* Addresses appearance set to searchfield in S5, Chrome */
-webkit-box-sizing: content-box; /* Addresses box sizing set to border-box in S5, Chrome (include -moz to future-proof) */
-moz-box-sizing: content-box;
box-sizing: content-box;
}
input[type="search"]::-webkit-search-decoration { /* Corrects inner padding displayed oddly in S5, Chrome on OSX */
-webkit-appearance: none;
}
button::-moz-focus-inner,
input::-moz-focus-inner { /* Corrects inner padding and border displayed oddly in FF3/4 www.sitepen.com/blog/2008/05/14/the-devils-in-the-details-fixing-dojos-toolbar-buttons/ */
border: 0;
padding: 0;
}
input[type="text"],
input[type="email"],
input[type="url"],
input[type="password"],
input[type="search"],
textarea {
color: #666;
border: 1px solid rgba(0,0,0,0.1);
border-radius: 0;
font-size: 14px;
font-size: 1.4rem;
padding: 0.5em;
transition: all 0.1s ease;
}
input[type="text"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="password"]:focus,
input[type="search"]:focus,
textarea:focus {
color: #111;
outline: none;
border-color: rgba(0,0,0,0.25);
background: rgba(0,0,0,0.075);
}
textarea {
overflow: auto; /* Removes default vertical scrollbar in IE6/7/8/9 */
vertical-align: top; /* Improves readability and alignment in all browsers */
width: 98%;
}
/*--------------------------------------------------------------
6.0 Navigation
--------------------------------------------------------------*/
/*--------------------------------------------------------------
6.1 Links
--------------------------------------------------------------*/
a {
color: #e14546;
}
a:visited {
color: #748c8e;
}
a:hover,
a:focus,
a:active {
color: #222;
}
/*--------------------------------------------------------------
6.2 Menus
--------------------------------------------------------------*/
.main-navigation {
clear: both;
display: block;
text-align: center;
border-top: 1px solid rgba(0,0,0,0.1);
border-bottom: 1px solid rgba(0,0,0,0.1);
}
.main-navigation ul {
list-style: none;
margin: 0;
padding-left: 0;
}
.main-navigation li {
position: relative;
display: inline-block;
text-transform: uppercase;
font-size: 14px;
font-size: 1.4rem;
}
.main-navigation a {
display: block;
text-decoration: none;
color: #333;
line-height: 1;
padding: 15px 20px;
}
/* Submenus when full menu is shown */
@media screen and (min-width: 601px) {
.main-navigation ul ul {
background: #1d1d1d;
border-top: 1px solid #e14546;
border-bottom: 1px solid #e14546;
float: left;
position: absolute;
top: 44px;
margin-left: 20px;
left: -999em;
z-index: 99999;
}
.main-navigation ul ul ul {
left: -999em;
top: -1px;
margin-left: 0;
}
.main-navigation ul ul a {
width: 220px;
color: #fff;
padding-left: 10px;
padding-right: 10px;
}
.main-navigation ul ul li {
font-size: 12px;
font-size: 1.2rem;
text-align: left;
border-bottom: 1px solid #333;
}
.main-navigation ul ul li:last-child {
border-bottom: none;
}
.main-navigation ul ul a:hover {
background: rgba(255,255,255,0.1);
}
.main-navigation ul li:hover > ul {
left: auto;
}
.main-navigation ul ul li:hover > ul {
left: 100%;
}
.main-navigation > ul.nav-menu > .current_page_item > a,
.main-navigation > ul.nav-menu > .current-menu-item > a,
.main-navigation > ul.nav-menu > li > a:hover,
.main-navigation > .nav-menu > ul > .current_page_item > a,
.main-navigation > .nav-menu > ul > .current-menu-item > a,
.main-navigation > .nav-menu > ul > li > a:hover {
color: #e14546;
}
.main-navigation .menu-item-has-children > a,
.main-navigation .page_item_has_children > a {
padding-right: 25px;
}
.main-navigation .menu-item-has-children > a:after,
.main-navigation .page_item_has_children > a:after {
-webkit-font-smoothing: antialiased;
content: "\f502";
display: inline-block;
font-family: Genericons;
font-size: 8px;
line-height: 8px;
position: absolute;
right: 12px;
top: 20px;
vertical-align: text-bottom;
}
.main-navigation .menu-item-has-children li.menu-item-has-children > a:after,
.main-navigation .menu-item-has-children li.page_item_has_children > a:after,
.main-navigation .page_item_has_children li.menu-item-has-children > a:after,
.main-navigation .page_item_has_children li.page_item_has_children > a:after {
content: "\f501";
right: 8px;
top: 18px;
}
/* Disable sub-menu indicator for last level menu items ($depth => 4) */
.main-navigation li li li li.menu-item-has-children > a:after,
.main-navigation li li li li.page_item_has_children > a:after,
.main-navigation li li li li.menu-item-has-children > a:after,
.main-navigation li li li li.page_item_has_children > a:after {
display: none;
}
}
/* Small menu */
.menu-toggle {
display: none;
}
@media screen and (max-width: 600px) {
.menu-toggle,
.main-navigation.toggled .nav-menu {
display: block;
width: 100%;
}
.main-navigation ul {
display: none;
}
.main-navigation li {
display: block;
font-size: 18px;
font-size: 1.8rem;
margin-bottom: 10px;
}
.main-navigation li a {
padding: 10px 0;
}
.main-navigation li ul {
display: block;
position: static;
}
.main-navigation li li {
font-size: 12px;
font-size: 1.2rem;
margin-bottom: 0;
}
.main-navigation li li a {
padding: 8px 0;
}
}
.site-main .comment-navigation,
.site-main .paging-navigation,
.site-main .post-navigation {
margin: 0 0 1.5em;
overflow: hidden;
font-size: 16px;
font-size: 1.6rem;
}
.comment-navigation .nav-previous,
.paging-navigation .nav-previous,
.post-navigation .nav-previous {
float: left;
width: 50%;
}
.comment-navigation .nav-next,
.paging-navigation .nav-next,
.post-navigation .nav-next {
float: right;
text-align: right;
width: 50%;
}
.comment-navigation a,
.post-navigation a {
color: #404040;
text-decoration: none;
display: block;
}
.post-navigation .wp-post-image {
width: 60px;
height: auto;
display: block;
float: left;
}
.post-navigation .nav-previous .wp-post-image + div {
margin-left: 75px;
}
.post-navigation .nav-next .wp-post-image {
float: right;
}
.post-navigation .nav-next .wp-post-image + div {
margin-right: 75px;
}
.post-navigation span.label,
.post-navigation span.link {
display: block;
}
.post-navigation span.label {
font-weight: bold;
}
.post-navigation span.link {
font-size: 14px;
font-size: 1.4rem;
}
.paging-navigation {
text-align: center;
}
.paging-navigation a,
.paging-navigation span {
display: inline-block;
min-width: 1.5em;
text-align: center;
}
.paging-navigation a {
color: #404040;
text-decoration: none;
}
.paging-navigation span {
background: #e14546;
color: #fff;
}
/* Social Menu */
#social-menu {
list-style: none;
margin: 0;
background: #1d1d1d;
text-align: center;
}
#social-menu li {
display: inline-block;
margin: 0 0.25em;
}
#social-menu a {
text-decoration: none;
color: #fff;
}
#social-menu a[href*="facebook.com"],
#social-menu a[href*="github.com"],
#social-menu a[href*="flickr.com"],
#social-menu a[href*="plus.google.com"],
#social-menu a[href*="instagram.com"],
#social-menu a[href*="linkedin.org"],
#social-menu a[href*="pinterest.com"],
#social-menu a[href*="skype"],
#social-menu a[href*="tumblr.com"],
#social-menu a[href*="twitter.com"],
#social-menu a[href*="vimeo.com"],
#social-menu a[href*="youtube.com"] {
font-size: 16px;
width: 16px;
height: 16px;
display: inline-block;
overflow: hidden;
}
#social-menu a[href*="facebook.com"]:before,
#social-menu a[href*="github.com"]:before,
#social-menu a[href*="flickr.com"]:before,
#social-menu a[href*="plus.google.com"]:before,
#social-menu a[href*="instagram.com"]:before,
#social-menu a[href*="linkedin.org"]:before,
#social-menu a[href*="pinterest.com"]:before,
#social-menu a[href*="skype"]:before,
#social-menu a[href*="tumblr.com"]:before,
#social-menu a[href*="twitter.com"]:before,
#social-menu a[href*="vimeo.com"]:before,
#social-menu a[href*="youtube.com"]:before {
display: inline-block;
width: 16px;
height: 16px;
-webkit-font-smoothing: antialiased;
font-size: 16px;
line-height: 1;
font-family: 'Genericons';
text-decoration: inherit;
font-weight: normal;
font-style: normal;
vertical-align: top;
}
#social-menu a[href*="facebook.com"]:before { content: '\f203'; }
#social-menu a[href*="github.com"]:before { content: '\f200'; }
#social-menu a[href*="flickr.com"]:before { content: '\f211'; }
#social-menu a[href*="plus.google.com"]:before { content: '\f206'; }
#social-menu a[href*="instagram.com"]:before { content: '\f215'; }
#social-menu a[href*="linkedin.com"]:before { content: '\f207'; }
#social-menu a[href*="pinterest.com"]:before { content: '\f209'; }
#social-menu a[href*="skype"]:before { content: '\f220'; }
#social-menu a[href*="tumblr.com"]:before { content: '\f214'; }
#social-menu a[href*="twitter.com"]:before { content: '\f202'; }
#social-menu a[href*="vimeo.com"]:before { content: '\f212'; }
#social-menu a[href*="youtube.com"]:before { content: '\f213'; }
/*--------------------------------------------------------------
7.0 Accessibility
--------------------------------------------------------------*/
/* Text meant only for screen readers */
.screen-reader-text {
clip: rect(1px, 1px, 1px, 1px);
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
}
.screen-reader-text:hover,
.screen-reader-text:active,
.screen-reader-text:focus {
background-color: #f1f1f1;
border-radius: 3px;
box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.6);
clip: auto !important;
color: #21759b;
display: block;
font-size: 14px;
font-weight: bold;
height: auto;
left: 5px;
line-height: normal;
padding: 15px 23px 14px;
text-decoration: none;
top: 5px;
width: auto;
z-index: 100000; /* Above WP toolbar */
}
/*--------------------------------------------------------------
8.0 Alignments
--------------------------------------------------------------*/
.alignleft {
display: inline;
float: left;
margin-right: 1.5em;
}
.alignright {
display: inline;
float: right;
margin-left: 1.5em;
}
.aligncenter {
clear: both;
display: block;
margin: 0 auto;
}
/*--------------------------------------------------------------
9.0 Clearings
--------------------------------------------------------------*/
.clear:before,
.clear:after,
.entry-content:before,
.entry-content:after,
.comment-content:before,
.comment-content:after,
.site-header:before,
.site-header:after,
.site-content:before,
.site-content:after,
.site-footer:before,
.site-footer:after,
.inner:before,
.inner:after,
.widget:before,
.widget:after {
content: '';
display: table;
}
.clear:after,
.entry-content:after,
.comment-content:after,
.site-header:after,
.site-content:after,
.site-footer:after,
.inner:after,
.widget:after {
clear: both;
}
/*--------------------------------------------------------------
10.0 Widgets
--------------------------------------------------------------*/
.widget {
margin: 0 0 30px;
font-size: 15px;
font-size: 1.5rem;
}
#secondary .widget:not(.widget_search) {
background-color: rgba(0,0,0,0.025);
border: 1px solid rgba(0,0,0,0.05);
padding: 30px;
}
.widget-title {
text-transform: uppercase;
font-size: 18px;
font-size: 1.8rem;
margin: 0 0 0.75em;
}
.widget a {
color: #e14546;
text-decoration: none;
}
.widget ul {
list-style: none;
margin: 0;
}
.widget li ul,
.widget li ol {
margin-left: 15px;
margin-top: 5px;
}
.widget li {
padding: 10px 0;
}
#secondary .widget li {
border-bottom: 1px dotted rgba(0,0,0,0.075);
padding: 10px 5px;
}
.widget li li {
padding: 5px 0;
border-bottom: none;
}
.widget li:last-child {
border-bottom: none;
padding-bottom: 0;
}
/* Make sure select elements fit in widgets */
.widget select {
max-width: 100%;
}
/* Search widget */
.search-submit {
display: none;
}
.search-form .search-field {
font-size: 15px;
font-size: 1.5rem;
border: 1px solid #e5e5e5;
padding: 10px;
border-radius: 0;
box-shadow: none;
display: block;
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
}
/* Calendar widget */
#wp-calendar {
border-collapse: collapse;
}
#wp-calendar caption {
text-transform: uppercase;
margin-bottom: 0.5em;
}
#wp-calendar td,
#wp-calendar th {
background: #fff;
text-align: center;
border: 1px solid #e5e5e5;
font-size: 14px;
font-size: 1.4rem;
padding: 3px;
}
/* Footer widgets */
/* Two per row */
.per-row-2 .widget {
width: 50%;
float: left;
}
.per-row-2 .widget:nth-child(2n+1) {
clear: left;
padding-left: 0;
}
.per-row-2 .widget:nth-child(2n) {
padding-right: 0;
}
/* Three per row */
.per-row-3 .widget {
width: 33.33333%;
float: left;
}
.per-row-3 .widget:nth-child(3n+1) {
clear: left;
padding-left: 0;
}
.per-row-3 .widget:nth-child(3n) {
padding-right: 0;
}
/* Four per row */
.per-row-4 .widget {
width: 25%;
float: left;
}
.per-row-4 .widget:nth-child(4n+1) {
clear: left;
padding-left: 0;
}
.per-row-4 .widget:nth-child(4n) {
padding-right: 0;
}
#footer-widgets {
padding: 30px 15px 0;
}
#footer-widgets .widget {
padding-left: 15px;
padding-right: 15px;
}
@media screen and (max-width: 800px) {
#footer-widgets .widget {
width: 50%;
}
}
@media screen and (max-width: 480px) {
#footer-widgets .widget {
width: 100%;
float: none;
}
}
/*--------------------------------------------------------------
11.0 Content
--------------------------------------------------------------*/
/*--------------------------------------------------------------
11.1 Posts and pages
--------------------------------------------------------------*/
.page-header {
margin-bottom: 45px;
padding-bottom: 45px;
border-bottom: double 3px #f3f3f3;
}
.page-title {
margin-top: 0;
margin-bottom: 0;
}
.taxonomy-description {
margin-top: 1.5em;
}
.taxonomy-description > :last-child {
margin-bottom: 0;
}
#posts-wrapper .hentry {
margin-bottom: 45px;
padding-bottom: 45px;
border-bottom: solid 1px #f3f3f3;
}
.layout-standard #posts-wrapper .sticky,
.layout-masonry #posts-wrapper .sticky .masonry-inner {
background-color: rgba(0,0,0,0.025);
border: 1px solid rgba(0,0,0,0.05);
padding: 30px;
}
.layout-masonry #posts-wrapper {
margin-left: -15px;
margin-right: -15px;
}
.no-sidebar #posts-wrapper .hentry.masonry-brick {
width: 33.33333%;
}
@media screen and (max-width: 770px) {
#posts-wrapper .hentry.masonry-brick,
.no-sidebar #posts-wrapper .hentry.masonry-brick {
width: 50%;
}
}
@media screen and (max-width: 570px) {
#posts-wrapper .hentry.masonry-brick,
.no-sidebar #posts-wrapper .hentry.masonry-brick {
width: 100%;
}
}
#posts-wrapper .entry-summary {
font-size: 16px;
font-size: 1.6rem;
}
.sticky {
}
.hentry {
margin: 0 0 3em;
}
.single .hentry .entry-footer {
padding-bottom: 45px;
margin-bottom: 0;
border-bottom: double 3px #f3f3f3;
}
.single .hentry .entry-footer,
.page .hentry .entry-footer {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
position: relative;
width: 100%;
}
.more-link,
#infinite-handle span {
display: inline-block;
background: #e14546;
color: #fff;
font-size: 14px;
font-size: 1.4rem;
line-height: 1;
padding: 1em 1.5em;
margin: 0.5em 0;
text-transform: uppercase;
text-decoration: none;
}
.more-link:hover,
.more-link:visited {
color: #fff;
}
.byline,
.updated:not(.published) {
display: none;
}
.single .byline,
.group-blog .byline {
display: inline;
}
.page-content,
.entry-content,
.entry-summary {
margin: 0 0 1.5em;
}
.page-links {
clear: both;
margin: 0 0 1.5em;
}
.entry-header {
margin-bottom: 30px;
}
.entry-header .wp-post-image {
margin-bottom: 30px;
}
.layout-masonry #posts-wrapper .entry-header,
.layout-masonry #posts-wrapper .wp-post-image {
margin-bottom: 20px;
}
.entry-title {
margin: 0 0 10px;
word-wrap: break-word;
}
.layout-masonry #posts-wrapper .entry-title {
font-size: 30px;
font-size: 3rem;
}
.entry-title a {
color: #1d1d1d;
text-decoration: none;
}
.entry-meta,
.entry-footer {
font-size: 14px;
font-size: 1.4rem;
color: #808080;
}
.entry-footer {
margin: 0 0 10px;
}
.entry-footer > span {
display: block;
margin-bottom: 0.3em;
}
.entry-content > :first-child,
.comment-content > :first-child {
margin-top: 0;
}
.entry-content > :last-child,
.comment-content > :last-child {
margin-bottom: 0;
}
.entry-content table,
.comment-content table {
border-collapse: collapse;
}
.entry-content td,
.entry-content th,
.comment-content td,
.comment-content th {
border: 1px solid #e5e5e5;
padding: 0.5em;
font-size: 16px;
font-size: 1.6rem;
}
.entry-content th,
.comment-content th {
background: #e14546;
color: #fff;
border-color: #fff;
}
.entry-content th a,
.comment-content th a {
color: #fff;
}
.entry-content blockquote,
.comment-content blockquote,
.entry-summary blockquote {
font-style: italic;
padding: 5px 0 5px 20px;
margin-left: 60px;
border-left: 3px solid #e14546;
position: relative;
}
.entry-summary blockquote {
margin-left: 40px;
padding-left: 15px;
}
.entry-content blockquote > :last-child,
.comment-content blockquote > :last-child,
.entry-summary blockquote > :last-child {
margin-bottom: 0;
}
.entry-content blockquote:before,
.comment-content blockquote:before,
.entry-summary blockquote:before {
color: #e14546;
content: '\f106';
font-size: 32px;
line-height: 32px;
height: 32px;
display: block;
font-family: Genericons;
-webkit-font-smoothing: antialiased;
position: absolute;
top: 5px;
left: -60px;
}
.entry-summary blockquote:before {
font-size: 24px;
line-height: 24px;
height: 24px;
left: -40px;
}
.entry-content blockquote cite,
.comment-content blockquote cite,
.entry-summary blockquote cite {
color: #808080;
display: block;
margin-top: 1em;
font-size: 14px;
font-size: 1.4rem;
text-align: right;
}
.post-password-form label {
display: block;
margin-bottom: 15px;
}
.post-password-form input[type="password"] {
display: block;
width: 300px;
}
/*--------------------------------------------------------------
11.2 Post Formats
--------------------------------------------------------------*/
#posts-wrapper .format-image .entry-header {
margin-bottom: 0;
}
#posts-wrapper .format-image .entry-title {
font-size: 20px;
font-size: 2rem;
}
.site-content .format-link .entry-title,
.site-content .format-aside .entry-title,
.site-content .format-quote .entry-title,
.site-content .format-status .entry-title,
.site-content .format-link .entry-footer,
.site-content .format-aside .entry-footer,
.site-content .format-quote .entry-footer,
.site-content .format-status .entry-footer,
.site-content .format-image .entry-footer {
display: none;
}
#posts-wrapper .entry-content {
margin-bottom: 0;
}
#posts-wrapper .entry-content + .entry-footer {
margin-top: 30px;
}
#posts-wrapper .hentry.masonry-brick {
width: 50%;
padding-left: 15px;
padding-right: 15px;
border-bottom: none;
padding-bottom: 0;
margin-bottom: 30px;
}
#posts-wrapper .format-status .entry-summary,
#posts-wrapper .format-status .entry-content {
font-size: 24px;
font-size: 2.4rem;
}
#posts-wrapper .hentry.masonry-brick .entry-summary,
#posts-wrapper .hentry.masonry-brick .entry-summary > :last-child {
margin-bottom: 0;
}
#posts-wrapper .hentry.masonry-brick .masonry-inner {
padding-bottom: 30px;
border-bottom: solid 1px #f3f3f3;
}
/*--------------------------------------------------------------
11.3 Comments
--------------------------------------------------------------*/
/* Form */
.required {
color: #e14546;
}
.comment-form label {
font-size: 14px;
font-size: 1.4rem;
display: block;
margin-bottom: 0.4em;
}
.comment-form-email,
.comment-form-author,
.comment-form-url {
float: left;
width: 30%;
box-sizing: content-box;
-moz-box-sizing: content-box;
}
.comment-form-email,
.comment-form-author {
padding-right: 5%;
}
.comment-form-email input,
.comment-form-author input,
.comment-form-url input,
.comment-form textarea {
width: 100%;
}
.form-allowed-tags {
font-size: 14px;
font-style: 1.4rem;
}
.comment-form-comment {
clear: left;
}
/* Comments */
.comment-list {
list-style: none;
margin: 30px 0;
}
.comment-list .children {
list-style: none;
margin: 30px 0 0 60px;
border-top: 1px solid #f3f3f3;
padding-top: 30px;
}
.comment-list .children .children .children {
margin-left: 0;
}
.comment-list > .comment {
border-bottom: double 3px #f3f3f3;
padding-bottom: 30px;
margin-bottom: 30px;
}
.comment {
margin-bottom: 20px;
padding-bottom: 20px;
border-bottom: 1px solid #f3f3f3;
}
.comment:last-child {
border-bottom: none;
padding-bottom: 0;
margin-bottom: 0;
}
.comment-content a {
word-wrap: break-word;
}
.comment-body {
padding-left: 60px;
padding-bottom: 50px;
position: relative;
}
.comment #respond {
padding-left: 60px;
}
.comment .avatar {
position: absolute;
top: 0;
left: 0;
}
.comment-author {
line-height: 1;
margin-bottom: 0.5em;
font-size: 20px;
font-size: 2rem;
}
.comment-author .url {
text-decoration: none;
color: #1d1d1d;
font-weight: normal;
}
.comment .says {
display: none;
}
.comment-metadata {
position: absolute;
bottom: 0;
left: 60px;
font-size: 14px;
font-size: 1.4rem;
line-height: 30px;
}
.comment-metadata a {
text-decoration: none;
}
.reply {
position: absolute;
bottom: 0;
right: 0;
font-size: 14px;
font-size: 1.4rem;
}
.reply a {
display: inline-block;
background: #e14546;
color: #fff;
text-decoration: none;
font-size: 14px;
font-size: 1.4rem;
line-height: 1;
padding: 8px 10px;
}
.comment-content {
color: #7e8080;
font-size: 16px;
font-size: 1.6rem;
}
.comment-content p {
margin-bottom: 1em;
}
.bypostauthor .comment-meta .fn:before {
content: '\f411';
font-family: Genericons;
-webkit-font-smoothing: antialiased;
font-size: 16px;
font-size: 1.6rem;
line-height: 1;
display: inline-block;
position: relative;
top: 2px;
margin-right: 4px;
font-weight: normal;
}
.form-allowed-tags {
display: none;
}
.logged-in-as {
font-size: 14px;
font-size: 1.4rem;
}
/*--------------------------------------------------------------
12.0 Footer
--------------------------------------------------------------*/
#colophon {
background-color: rgba(0,0,0,0.025);
border-top: 1px solid rgba(0,0,0,0.05);
}
#footer-bottom {
background: rgba(0,0,0,0.075);
font-size: 14px;
font-size: 1.4rem;
padding: 15px 0;
}
#footer-bottom a {
color: #e14546;
}
.site-info {
float: left;
width: 50%;
}
#footer-bottom ul.menu {
float: right;
width: 50%;
margin: 0;
list-style: none;
text-align: right;
}
#footer-bottom ul.menu li {
display: inline-block;
margin-left: 1em;
}
@media screen and (max-width: 900px) {
.site-info,
#footer-bottom ul.menu {
width: 100%;
float: none;
text-align: center;
}
#footer-bottom ul.menu + .site-info {
margin-top: 1em;
}
#footer-bottom ul.menu {
text-align: center;
}
#footer-bottom ul.menu li {
margin: 0 1em 0 0;
}
}
/*--------------------------------------------------------------
12.1 Infinite scroll
--------------------------------------------------------------*/
#infinite-footer {
background: rgba( 255, 255, 255, 0.8 );
border-top: 1px solid rgba(0,0,0,0.1);
}
#infinite-footer .container {
max-width: 1230px;
padding: 0 30px;
background: none;
border: none;
}
/* Globally hidden elements when Infinite Scroll is supported and in use. */
.infinite-scroll .paging-navigation, /* Older / Newer Posts Navigation (always hidden) */
.infinite-scroll.neverending .site-footer { /* Theme Footer (when set to scrolling) */
display: none;
}
/* When Infinite Scroll has reached its end we need to re-display elements that were hidden (via .neverending) before */
.infinity-end.neverending .site-footer {
display: block;
}
/* Fix Older Posts button placement in Masonry layout */
.infinite-scroll.layout-masonry #posts-wrapper {
position: relative;
padding-bottom: 60px;
}
.infinite-scroll.layout-masonry #posts-wrapper #infinite-handle {
position: absolute;
bottom: 0;
left: 0;
}
/*--------------------------------------------------------------
13.0 Media
--------------------------------------------------------------*/
.page-content img.wp-smiley,
.entry-content img.wp-smiley,
.comment-content img.wp-smiley {
border: none;
margin-bottom: 0;
margin-top: 0;
padding: 0;
}
/* Make sure embeds and iframes fit their containers */
embed,
iframe,
object {
max-width: 100%;
}
.wp-post-image {
display: block;
width: 100%;
height: auto;
}
.size-auto,
.size-full,
.size-large,
.size-medium,
.size-thumbnail {
max-width: 100%;
height: auto;
}
/*--------------------------------------------------------------
13.1 Captions
--------------------------------------------------------------*/
.wp-caption {
margin-bottom: 1.5em;
max-width: 100%;
}
.wp-caption img[class*="wp-image-"] {
display: block;
margin: 0 auto;
}
.wp-caption-text {
text-align: right;
font-size: 14px;
font-size: 1.4rem;
line-height: 1.2;
color: #808080;
}
.wp-caption .wp-caption-text {
margin: 0.5em 0;
}
/*--------------------------------------------------------------
13.2 Galleries
--------------------------------------------------------------*/
.gallery {
margin-bottom: 1.5em;
}
.gallery-item {
display: inline-block;
text-align: center;
vertical-align: top;
width: 100%;
padding: 10px;
}
.gallery-columns-2 .gallery-item {
max-width: 50%;
}
.gallery-columns-3 .gallery-item {
max-width: 33.33%;
}
.gallery-columns-4 .gallery-item {
max-width: 25%;
}
.gallery-columns-5 .gallery-item {
max-width: 20%;
}
.gallery-columns-6 .gallery-item {
max-width: 16.66%;
}
.gallery-columns-7 .gallery-item {
max-width: 14.28%;
}
.gallery-columns-8 .gallery-item {
max-width: 12.5%;
}
.gallery-columns-9 .gallery-item {
max-width: 11.11%;
}
.gallery-caption {
text-align: center;
font-size: 12px;
font-size: 1.2rem;
}
/*--------------------------------------------------------------
14.0 Featured Content
--------------------------------------------------------------*/
.featured-content {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
position: relative;
width: 100%;
margin-bottom: 45px;
padding-bottom: 45px;
border-bottom: double 3px #f3f3f3;
}
.featured-content:after {
content: '\f436';
position: absolute;
display: block;
width: 24px;
height: 24px;
font-size: 24px;
line-height: 24px;
font-family: Genericons;
-webkit-font-smoothing: antialiased;
color: #e5e5e5;
bottom: -14px;
left: 50%;
margin-left: -12px;
background: #fff;
}
.featured-content-inner {
overflow: hidden;
}
.featured-content .hentry {
margin: 0;
max-width: 100%;
width: 100%;
}
.featured-content .post-thumbnail,
.featured-content .post-thumbnail:hover {
background: transparent;
}
.featured-content .post-thumbnail {
display: block;
position: relative;
padding-top: 55.357142857%;
overflow: hidden;
}
.featured-content .post-thumbnail img {
left: 0;
position: absolute;
top: 0;
}
.featured-content .featured-text {
padding: 20px 5px;
}
.featured-content a {
color: #404040;
text-decoration: none;
}
.featured-content a img {
transition: opacity 0.25s ease;
}
.featured-content a:hover img {
opacity: 0.8;
}
.featured-content .entry-header {
margin-bottom: 10px;
}
.featured-content .entry-meta {
margin-top: 0;
}
.featured-content .cat-links {
display: none;
}
.featured-content .entry-title {
letter-spacing: 0.075em;
font-size: 28px;
font-size: 2.8rem;
}
.featured-content .entry-summary {
font-size: 14px;
font-size: 1.4rem;
}
.featured-content .entry-summary,
.featured-content .entry-summary > :last-child {
margin-bottom: 0;
}
/* Slider */
.featured-content .hentry {
-webkit-backface-visibility: hidden;
display: none;
position: relative;
}
.featured-content .post-thumbnail {
padding-top: 55.49132947%;
}
.slider-control-paging {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
float: left;
list-style: none;
margin: 0;
position: absolute;
z-index: 3;
bottom: 49px;
left: 0;
}
.slider-control-paging li {
float: left;
}
.slider-control-paging li:last-child {
margin-right: 0;
}
.slider-control-paging a {
cursor: pointer;
display: block;
height: 32px;
position: relative;
text-indent: -999em;
width: 32px;
}
.slider-control-paging a:before {
background-color: #808080;
content: "";
width: 12px;
height: 12px;
position: absolute;
left: 10px;
top: 10px;
}
.slider-control-paging .slider-active:before,
.slider-control-paging .slider-active:hover:before {
background: #e14546;
}
.slider-direction-nav {
clear: both;
list-style: none;
margin: 0 0 0 -74px;
position: absolute;
z-index: 3;
overflow: hidden;
bottom: 49px;
left: 600px;
}
.slider-direction-nav li {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
float: left;
text-align: center;
display: block;
}
.slider-direction-nav a {
display: block;
font-size: 0;
height: 32px;
color: #333;
}
.slider-direction-nav a:hover {
}
.slider-direction-nav a:before {
color: #333;
content: "\f430";
font-size: 32px;
line-height: 32px;
height: 32px;
display: inline-block;
font-family: Genericons;
-webkit-font-smoothing: antialiased;
}
.slider-direction-nav .slider-next:before {
content: "\f429";
}
.slider-direction-nav .slider-disabled {
display: none;
}
@media screen and (min-width: 801px) {
#featured-content .featured-text {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
position: absolute;
bottom: -1px;
left: 0;
width: 600px;
padding: 20px 20px 40px 10px;
background: #fff;
}
}
@media screen and (max-width: 800px) {
#featured-content .slider-direction-nav {
bottom: 30px;
left: auto;
right: 0;
margin-right: 0;
}
#featured-content .slider-control-paging {
bottom: 30px;
left: 0;
}
.slider-control-paging a {
height: 22px;
width: 22px;
}
.slider-control-paging a:before {
left: 5px;
top: 5px;
}
}
/*--------------------------------------------------------------
15.0 Media Queries
--------------------------------------------------------------*/ | ThematoSoup/Pho | style.css | CSS | gpl-2.0 | 40,297 |
<?php
/**
* Text_Diff
*
* General API for generating and formatting diffs - the differences between
* two sequences of strings.
*
* The PHP diff code used in this package was originally written by Geoffrey
* T. Dairiki and is used with his permission.
*
* $Horde: framework/Text_Diff/Diff.php,v 1.8 2004/10/13 09:30:20 jan Exp $
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_Diff {
/**
* Array of changes.
*
* @var array $_edits
*/
var $_edits;
/**
* Computes diffs between sequences of strings.
*
* @param array $from_lines An array of strings. Typically these are
* lines from a file.
* @param array $to_lines An array of strings.
*/
function Text_Diff($from_lines, $to_lines)
{
array_walk($from_lines, array($this, '_trimNewlines'));
array_walk($to_lines, array($this, '_trimNewlines'));
if (extension_loaded('xdiff')) {
$engine = &new Text_Diff_Engine_xdiff();
} else {
$engine = &new Text_Diff_Engine_native();
}
$this->_edits = $engine->diff($from_lines, $to_lines);
}
/**
* Returns the array of differences.
*/
function getDiff()
{
return $this->_edits;
}
/**
* Computes a reversed diff.
*
* Example:
* <code>
* $diff = &new Text_Diff($lines1, $lines2);
* $rev = $diff->reverse();
* </code>
*
* @return Text_Diff A Diff object representing the inverse of the
* original diff. Note that we purposely don't return a
* reference here, since this essentially is a clone()
* method.
*/
function reverse()
{
if (version_compare(zend_version(), '2', '>')) {
$rev = clone($obj);
} else {
$rev = $this;
}
$rev->_edits = array();
foreach ($this->_edits as $edit) {
$rev->_edits[] = $edit->reverse();
}
return $rev;
}
/**
* Checks for an empty diff.
*
* @return boolean True if two sequences were identical.
*/
function isEmpty()
{
foreach ($this->_edits as $edit) {
if (!is_a($edit, 'Text_Diff_Op_copy')) {
return false;
}
}
return true;
}
/**
* Computes the length of the Longest Common Subsequence (LCS).
*
* This is mostly for diagnostic purposed.
*
* @return int The length of the LCS.
*/
function lcs()
{
$lcs = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_copy')) {
$lcs += count($edit->orig);
}
}
return $lcs;
}
/**
* Gets the original set of lines.
*
* This reconstructs the $from_lines parameter passed to the constructor.
*
* @return array The original sequence of strings.
*/
function getOriginal()
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->orig) {
array_splice($lines, count($lines), 0, $edit->orig);
}
}
return $lines;
}
/**
* Gets the final set of lines.
*
* This reconstructs the $to_lines parameter passed to the constructor.
*
* @return array The sequence of strings.
*/
function getFinal()
{
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->final) {
array_splice($lines, count($lines), 0, $edit->final);
}
}
return $lines;
}
/**
* Removes trailing newlines from a line of text. This is meant to be used
* with array_walk().
*
* @param string $line The line to trim.
* @param integer $key The index of the line in the array. Not used.
*/
function _trimNewlines(&$line, $key)
{
$line = str_replace(array("\n", "\r", "\r\n"), '', $line);
}
/**
* Checks a diff for validity.
*
* This is here only for debugging purposes.
*/
function _check($from_lines, $to_lines)
{
if (serialize($from_lines) != serialize($this->getOriginal())) {
trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
}
if (serialize($to_lines) != serialize($this->getFinal())) {
trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
}
$rev = $this->reverse();
if (serialize($to_lines) != serialize($rev->getOriginal())) {
trigger_error("Reversed original doesn't match", E_USER_ERROR);
}
if (serialize($from_lines) != serialize($rev->getFinal())) {
trigger_error("Reversed final doesn't match", E_USER_ERROR);
}
$prevtype = null;
foreach ($this->_edits as $edit) {
if ($prevtype == get_class($edit)) {
trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
}
$prevtype = get_class($edit);
}
return true;
}
}
/**
* $Horde: framework/Text_Diff/Diff.php,v 1.8 2004/10/13 09:30:20 jan Exp $
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
*/
class Text_MappedDiff extends Text_Diff {
/**
* Computes a diff between sequences of strings.
*
* This can be used to compute things like case-insensitve diffs, or diffs
* which ignore changes in white-space.
*
* @param array $from_lines An array of strings.
* @param array $to_lines An array of strings.
* @param array $mapped_from_lines This array should have the same size
* number of elements as $from_lines. The
* elements in $mapped_from_lines and
* $mapped_to_lines are what is actually
* compared when computing the diff.
* @param array $mapped_to_lines This array should have the same number
* of elements as $to_lines.
*/
function Text_MappedDiff($from_lines, $to_lines,
$mapped_from_lines, $mapped_to_lines)
{
assert(count($from_lines) == count($mapped_from_lines));
assert(count($to_lines) == count($mapped_to_lines));
parent::Text_Diff($mapped_from_lines, $mapped_to_lines);
$xi = $yi = 0;
for ($i = 0; $i < count($this->edits); $i++) {
$orig = &$this->edits[$i]->orig;
if (is_array($orig)) {
$orig = array_slice($from_lines, $xi, count($orig));
$xi += count($orig);
}
$final = &$this->edits[$i]->final;
if (is_array($final)) {
$final = array_slice($to_lines, $yi, count($final));
$yi += count($final);
}
}
}
}
/**
* Class used internally by Diff to actually compute the diffs. This class
* uses the xdiff PECL package (http://pecl.php.net/package/xdiff) to compute
* the differences between the two input arrays.
*
* @author Jon Parise <jon@horde.org>
* @package Text_Diff
* @access private
*/
class Text_Diff_Engine_xdiff {
function diff($from_lines, $to_lines)
{
/* Convert the two input arrays into strings for xdiff processing. */
$from_string = implode("\n", $from_lines);
$to_string = implode("\n", $to_lines);
/* Diff the two strings and convert the result to an array. */
$diff = xdiff_string_diff($from_string, $to_string, count($to_lines));
$diff = explode("\n", $diff);
/* Walk through the diff one line at a time. We build the $edits
* array of diff operations by reading the first character of the
* xdiff output (which is in the "unified diff" format).
*
* Note that we don't have enough information to detect "changed"
* lines using this approach, so we can't add Text_Diff_Op_changed
* instances to the $edits array. The result is still perfectly
* valid, albeit a little less descriptive and efficient. */
$edits = array();
foreach ($diff as $line) {
switch ($line[0]) {
case ' ':
$edits[] = &new Text_Diff_Op_copy(array(substr($line, 1)));
break;
case '+':
$edits[] = &new Text_Diff_Op_add(array(substr($line, 1)));
break;
case '-':
$edits[] = &new Text_Diff_Op_delete(array(substr($line, 1)));
break;
}
}
return $edits;
}
}
/**
* Class used internally by Diff to actually compute the diffs. This class is
* implemented using native PHP code.
*
* The algorithm used here is mostly lifted from the perl module
* Algorithm::Diff (version 1.06) by Ned Konz, which is available at:
* http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip
*
* More ideas are taken from:
* http://www.ics.uci.edu/~eppstein/161/960229.html
*
* Some ideas (and a bit of code) are from from analyze.c, from GNU
* diffutils-2.7, which can be found at:
* ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz
*
* Some ideas (subdivision by NCHUNKS > 2, and some optimizations) are from
* Geoffrey T. Dairiki <dairiki@dairiki.org>. The original PHP version of this
* code was writting by him, and is used/adapted with his permission.
*
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @package Text_Diff
* @access private
*/
class Text_Diff_Engine_native {
function diff($from_lines, $to_lines)
{
$n_from = count($from_lines);
$n_to = count($to_lines);
$this->xchanged = $this->ychanged = array();
$this->xv = $this->yv = array();
$this->xind = $this->yind = array();
unset($this->seq);
unset($this->in_seq);
unset($this->lcs);
// Skip leading common lines.
for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
if ($from_lines[$skip] != $to_lines[$skip]) {
break;
}
$this->xchanged[$skip] = $this->ychanged[$skip] = false;
}
// Skip trailing common lines.
$xi = $n_from; $yi = $n_to;
for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
if ($from_lines[$xi] != $to_lines[$yi]) {
break;
}
$this->xchanged[$xi] = $this->ychanged[$yi] = false;
}
// Ignore lines which do not exist in both files.
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$xhash[$from_lines[$xi]] = 1;
}
for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
$line = $to_lines[$yi];
if (($this->ychanged[$yi] = empty($xhash[$line]))) {
continue;
}
$yhash[$line] = 1;
$this->yv[] = $line;
$this->yind[] = $yi;
}
for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
$line = $from_lines[$xi];
if (($this->xchanged[$xi] = empty($yhash[$line]))) {
continue;
}
$this->xv[] = $line;
$this->xind[] = $xi;
}
// Find the LCS.
$this->_compareseq(0, count($this->xv), 0, count($this->yv));
// Merge edits when possible.
$this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged);
$this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged);
// Compute the edit operations.
$edits = array();
$xi = $yi = 0;
while ($xi < $n_from || $yi < $n_to) {
assert($yi < $n_to || $this->xchanged[$xi]);
assert($xi < $n_from || $this->ychanged[$yi]);
// Skip matching "snake".
$copy = array();
while ($xi < $n_from && $yi < $n_to
&& !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
$copy[] = $from_lines[$xi++];
++$yi;
}
if ($copy) {
$edits[] = &new Text_Diff_Op_copy($copy);
}
// Find deletes & adds.
$delete = array();
while ($xi < $n_from && $this->xchanged[$xi]) {
$delete[] = $from_lines[$xi++];
}
$add = array();
while ($yi < $n_to && $this->ychanged[$yi]) {
$add[] = $to_lines[$yi++];
}
if ($delete && $add) {
$edits[] = &new Text_Diff_Op_change($delete, $add);
} elseif ($delete) {
$edits[] = &new Text_Diff_Op_delete($delete);
} elseif ($add) {
$edits[] = &new Text_Diff_Op_add($add);
}
}
return $edits;
}
/**
* Divides the Largest Common Subsequence (LCS) of the sequences (XOFF,
* XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized
* segments.
*
* Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of
* NCHUNKS+1 (X, Y) indexes giving the diving points between sub
* sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1),
* the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) ==
* (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM).
*
* This function assumes that the first lines of the specified portions of
* the two files do not match, and likewise that the last lines do not
* match. The caller must trim matching lines from the beginning and end
* of the portions it is going to specify.
*/
function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks)
{
// Bozz Added to no issue warning messages on assert failure
// on line 497
assert_options(ASSERT_WARNING, false);
$flip = false;
if ($xlim - $xoff > $ylim - $yoff) {
/* Things seems faster (I'm not sure I understand why) when the
* shortest sequence is in X. */
$flip = true;
list ($xoff, $xlim, $yoff, $ylim)
= array($yoff, $ylim, $xoff, $xlim);
}
if ($flip) {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->xv[$i]][] = $i;
}
} else {
for ($i = $ylim - 1; $i >= $yoff; $i--) {
$ymatches[$this->yv[$i]][] = $i;
}
}
$this->lcs = 0;
$this->seq[0]= $yoff - 1;
$this->in_seq = array();
$ymids[0] = array();
$numer = $xlim - $xoff + $nchunks - 1;
$x = $xoff;
for ($chunk = 0; $chunk < $nchunks; $chunk++) {
if ($chunk > 0) {
for ($i = 0; $i <= $this->lcs; $i++) {
$ymids[$i][$chunk-1] = $this->seq[$i];
}
}
$x1 = $xoff + (int)(($numer + ($xlim-$xoff)*$chunk) / $nchunks);
for (; $x < $x1; $x++) {
$line = $flip ? $this->yv[$x] : $this->xv[$x];
if (empty($ymatches[$line])) {
continue;
}
$matches = $ymatches[$line];
foreach ($matches as $y) {
if (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k-1];
break;
}
}
while (list($junk, $y) = each($matches)) {
if ($y > $this->seq[$k - 1]) {
assert($y < $this->seq[$k]);
/* Optimization: this is a common case: next match is
* just replacing previous match. */
$this->in_seq[$this->seq[$k]] = false;
$this->seq[$k] = $y;
$this->in_seq[$y] = 1;
} elseif (empty($this->in_seq[$y])) {
$k = $this->_lcsPos($y);
assert($k > 0);
$ymids[$k] = $ymids[$k-1];
}
}
}
}
$seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff);
$ymid = $ymids[$this->lcs];
for ($n = 0; $n < $nchunks - 1; $n++) {
$x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks);
$y1 = $ymid[$n] + 1;
$seps[] = $flip ? array($y1, $x1) : array($x1, $y1);
}
$seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim);
return array($this->lcs, $seps);
}
function _lcsPos($ypos)
{
$end = $this->lcs;
if ($end == 0 || $ypos > $this->seq[$end]) {
$this->seq[++$this->lcs] = $ypos;
$this->in_seq[$ypos] = 1;
return $this->lcs;
}
$beg = 1;
while ($beg < $end) {
$mid = (int)(($beg + $end) / 2);
if ($ypos > $this->seq[$mid]) {
$beg = $mid + 1;
} else {
$end = $mid;
}
}
assert($ypos != $this->seq[$end]);
$this->in_seq[$this->seq[$end]] = false;
$this->seq[$end] = $ypos;
$this->in_seq[$ypos] = 1;
return $end;
}
/**
* Finds LCS of two sequences.
*
* The results are recorded in the vectors $this->{x,y}changed[], by
* storing a 1 in the element for each line that is an insertion or
* deletion (ie. is not in the LCS).
*
* The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1.
*
* Note that XLIM, YLIM are exclusive bounds. All line numbers are
* origin-0 and discarded lines are not counted.
*/
function _compareseq ($xoff, $xlim, $yoff, $ylim)
{
/* Slide down the bottom initial diagonal. */
while ($xoff < $xlim && $yoff < $ylim
&& $this->xv[$xoff] == $this->yv[$yoff]) {
++$xoff;
++$yoff;
}
/* Slide up the top initial diagonal. */
while ($xlim > $xoff && $ylim > $yoff
&& $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) {
--$xlim;
--$ylim;
}
if ($xoff == $xlim || $yoff == $ylim) {
$lcs = 0;
} else {
/* This is ad hoc but seems to work well. $nchunks =
* sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks =
* max(2,min(8,(int)$nchunks)); */
$nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1;
list($lcs, $seps)
= $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks);
}
if ($lcs == 0) {
/* X and Y sequences have no common subsequence: mark all
* changed. */
while ($yoff < $ylim) {
$this->ychanged[$this->yind[$yoff++]] = 1;
}
while ($xoff < $xlim) {
$this->xchanged[$this->xind[$xoff++]] = 1;
}
} else {
/* Use the partitions to split this problem into subproblems. */
reset($seps);
$pt1 = $seps[0];
while ($pt2 = next($seps)) {
$this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]);
$pt1 = $pt2;
}
}
}
/**
* Adjusts inserts/deletes of identical lines to join changes as much as
* possible.
*
* We do something when a run of changed lines include a line at one end
* and has an excluded, identical line at the other. We are free to
* choose which identical line is included. `compareseq' usually chooses
* the one at the beginning, but usually it is cleaner to consider the
* following identical line to be the "change".
*
* This is extracted verbatim from analyze.c (GNU diffutils-2.7).
*/
function _shiftBoundaries($lines, &$changed, $other_changed)
{
$i = 0;
$j = 0;
assert('count($lines) == count($changed)');
$len = count($lines);
$other_len = count($other_changed);
while (1) {
/* Scan forward to find the beginning of another run of
* changes. Also keep track of the corresponding point in the
* other file.
*
* Throughout this code, $i and $j are adjusted together so that
* the first $i elements of $changed and the first $j elements of
* $other_changed both contain the same number of zeros (unchanged
* lines).
*
* Furthermore, $j is always kept so that $j == $other_len or
* $other_changed[$j] == false. */
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
while ($i < $len && ! $changed[$i]) {
assert('$j < $other_len && ! $other_changed[$j]');
$i++; $j++;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
if ($i == $len) {
break;
}
$start = $i;
/* Find the end of this run of changes. */
while (++$i < $len && $changed[$i]) {
continue;
}
do {
/* Record the length of this run of changes, so that we can
* later determine whether the run has grown. */
$runlength = $i - $start;
/* Move the changed region back, so long as the previous
* unchanged line matches the last changed one. This merges
* with previous changed regions. */
while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) {
$changed[--$start] = 1;
$changed[--$i] = false;
while ($start > 0 && $changed[$start - 1]) {
$start--;
}
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
/* Set CORRESPONDING to the end of the changed run, at the
* last point where it corresponds to a changed run in the
* other file. CORRESPONDING == LEN means no such point has
* been found. */
$corresponding = $j < $other_len ? $i : $len;
/* Move the changed region forward, so long as the first
* changed line matches the following unchanged one. This
* merges with following changed regions. Do this second, so
* that if there are no merges, the changed region is moved
* forward as far as possible. */
while ($i < $len && $lines[$start] == $lines[$i]) {
$changed[$start++] = false;
$changed[$i++] = 1;
while ($i < $len && $changed[$i]) {
$i++;
}
assert('$j < $other_len && ! $other_changed[$j]');
$j++;
if ($j < $other_len && $other_changed[$j]) {
$corresponding = $i;
while ($j < $other_len && $other_changed[$j]) {
$j++;
}
}
}
} while ($runlength != $i - $start);
/* If possible, move the fully-merged run of changes back to a
* corresponding run in the other file. */
while ($corresponding < $i) {
$changed[--$start] = 1;
$changed[--$i] = 0;
assert('$j > 0');
while ($other_changed[--$j]) {
continue;
}
assert('$j >= 0 && !$other_changed[$j]');
}
}
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @access private
*/
class Text_Diff_Op {
var $orig;
var $final;
function reverse()
{
trigger_error('Abstract method', E_USER_ERROR);
}
function norig()
{
return $this->orig ? count($this->orig) : 0;
}
function nfinal()
{
return $this->final ? count($this->final) : 0;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @access private
*/
class Text_Diff_Op_copy extends Text_Diff_Op {
function Text_Diff_Op_copy($orig, $final = false)
{
if (!is_array($final)) {
$final = $orig;
}
$this->orig = $orig;
$this->final = $final;
}
function &reverse()
{
return $reverse = &new Text_Diff_Op_copy($this->final, $this->orig);
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @access private
*/
class Text_Diff_Op_delete extends Text_Diff_Op {
function Text_Diff_Op_delete($lines)
{
$this->orig = $lines;
$this->final = false;
}
function &reverse()
{
return $reverse = &new Text_Diff_Op_add($this->orig);
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @access private
*/
class Text_Diff_Op_add extends Text_Diff_Op {
function Text_Diff_Op_add($lines)
{
$this->final = $lines;
$this->orig = false;
}
function &reverse()
{
return $reverse = &new Text_Diff_Op_delete($this->final);
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <dairiki@dairiki.org>
* @access private
*/
class Text_Diff_Op_change extends Text_Diff_Op {
function Text_Diff_Op_change($orig, $final)
{
$this->orig = $orig;
$this->final = $final;
}
function &reverse()
{
return $reverse = &new Text_Diff_Op_change($this->final, $this->orig);
}
}
| doxbox/doxbox-dms | lib/Text/Diff.php | PHP | gpl-2.0 | 26,525 |
#
# Copyright 2015 SmartBear Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
#
package WWW::SwaggerClient::VotesApi;
require 5.6.0;
use strict;
use warnings;
use utf8;
use Exporter;
use Carp qw( croak );
use Log::Any qw($log);
use WWW::SwaggerClient::ApiClient;
use WWW::SwaggerClient::Configuration;
sub new {
my $class = shift;
my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new;
my (%self) = (
'api_client' => $default_api_client,
@_
);
#my $self = {
# #api_client => $options->{api_client}
# api_client => $default_api_client
#};
bless \%self, $class;
}
#
# v1_votes_post
#
# Post or update vote
#
# @param string $cause Cause variable name (required)
# @param string $effect Effect variable name (required)
# @param number $correlation Correlation value (required)
# @param boolean $vote Vote: 0 (for implausible) or 1 (for plausible) (optional)
# @return CommonResponse
#
sub v1_votes_post {
my ($self, %args) = @_;
# verify the required parameter 'cause' is set
unless (exists $args{'cause'}) {
croak("Missing the required parameter 'cause' when calling v1_votes_post");
}
# verify the required parameter 'effect' is set
unless (exists $args{'effect'}) {
croak("Missing the required parameter 'effect' when calling v1_votes_post");
}
# verify the required parameter 'correlation' is set
unless (exists $args{'correlation'}) {
croak("Missing the required parameter 'correlation' when calling v1_votes_post");
}
# parse inputs
my $_resource_path = '/v1/votes';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = 'POST';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept('application/json');
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type();
# query params
if ( exists $args{'cause'}) {
$query_params->{'cause'} = $self->{api_client}->to_query_value($args{'cause'});
}# query params
if ( exists $args{'effect'}) {
$query_params->{'effect'} = $self->{api_client}->to_query_value($args{'effect'});
}# query params
if ( exists $args{'correlation'}) {
$query_params->{'correlation'} = $self->{api_client}->to_query_value($args{'correlation'});
}# query params
if ( exists $args{'vote'}) {
$query_params->{'vote'} = $self->{api_client}->to_query_value($args{'vote'});
}
my $_body_data;
# authentication setting, if any
my $auth_settings = ['oauth2'];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('CommonResponse', $response);
return $_response_object;
}
#
# v1_votes_delete_post
#
# Delete vote
#
# @param string $cause Cause variable name (required)
# @param string $effect Effect variable name (required)
# @return CommonResponse
#
sub v1_votes_delete_post {
my ($self, %args) = @_;
# verify the required parameter 'cause' is set
unless (exists $args{'cause'}) {
croak("Missing the required parameter 'cause' when calling v1_votes_delete_post");
}
# verify the required parameter 'effect' is set
unless (exists $args{'effect'}) {
croak("Missing the required parameter 'effect' when calling v1_votes_delete_post");
}
# parse inputs
my $_resource_path = '/v1/votes/delete';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = 'POST';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept('application/json');
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type();
# query params
if ( exists $args{'cause'}) {
$query_params->{'cause'} = $self->{api_client}->to_query_value($args{'cause'});
}# query params
if ( exists $args{'effect'}) {
$query_params->{'effect'} = $self->{api_client}->to_query_value($args{'effect'});
}
my $_body_data;
# authentication setting, if any
my $auth_settings = ['oauth2'];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('CommonResponse', $response);
return $_response_object;
}
1;
| QuantiModo/QuantiModo-SDK-Perl | lib/WWW/SwaggerClient/VotesApi.pm | Perl | gpl-2.0 | 5,986 |
'use strict';
/*
* jmlib-js - Portable JuggleMaster Library (JavaScript Version)
* Version 2.0
* (C) Per Johan Groland 2006-2016
*
* Based on JMLib 2.0, (C) Per Johan Groland and Gary Briggs
*
* Based on JuggleMaster Version 1.60
* Copyright (c) 1995-1996 Ken Matsuoka
*
* You may redistribute and/or modify JMLib_js under the terms of the
* Modified BSD License as published in various places online or in the
* COPYING.jmlib file in the package you downloaded.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Modified BSD License for more details.
*/
/* eslint-disable no-var, eqeqeq, no-constant-condition */
var Ball = require('./ball'),
Arm = require('./arm'),
Hand = require('./hand'),
validator = require('./validator');
// JMLib class
function JMLib(errorCallback) {
var i;
this.errorCallback = errorCallback;
// public variables
this.ap = new Arm();
this.rhand = new Ball();
this.lhand = new Ball();
this.handpoly = new Hand();
this.handpoly_ex = new Hand();
this.b = new Array(JMLib.BMAX);
for (i = 0; i < JMLib.BMAX; i++) {
this.b[i] = new Ball();
}
this.dpm = 0;
this.gx_max = 0;
this.gx_min = 0;
this.gy_max = 0;
this.gy_min = 0;
this.imageWidth = 0;
this.imageHeight = 0;
this.status = 0;
// protected variables
this.balln = 0;
this.bm1 = 0;
this.arm_x = 0;
this.arm_y = 0;
this.hand_x = 0;
this.hand_y = 0;
this.horCenter = 0;
this.verCenter = 0;
this.styledata = new Array(JMLib.STYLEMAX * 4);
this.style_len = 0;
this.ga = 0.0;
this.dwell_ratio = 0.0;
this.height_ratio = 0.0;
this.base = 0;
this.mirror = 0;
this.time_count = 0;
this.time_period = 0;
this.cSpeed = 0.0;
this.beep = 0;
this.syn = 0;
this.hand_on = 0;
this.fpu = true;
this.tw = 0;
this.aw = 0;
this.pmax = 0;
this.lastError = null;
//JML_INT32 patt[LMAX][MMAX];
this.patt = new Array(JMLib.LMAX);
for (i = 0; i < JMLib.LMAX; i++) {
this.patt[i] = new Array(JMLib.MMAX);
for (var j = 0; j < JMLib.MMAX; j++) {
this.patt[i][j] = 0;
}
}
this.patts = new Array(JMLib.LMAX);
this.pattw = 0;
this.r = new Array(JMLib.LMAX * 2);
this.smode = 0;
this.high0 = new Array(JMLib.BMAX + 1);
this.high = new Array(JMLib.BMAX + 1);
this.kw0 = 0; // XR/KW [m]
this.siteswap = ""; // The current siteswap
this.pattname = ""; // The name of the current pattern
this.steps = new Array(JMLib.LMAX); // used to print the site on screen
this.stylename = ""; // The name of the current style
// Scaling
this.scalingMethod = 0;
this.scaleImageWidth = 0;
this.scaleImageHeight = 0;
this.possible_styles = new Array();
this.possible_styles[0] = "Normal";
this.possible_styles[1] = "Reverse";
this.possible_styles[2] = "Shower";
this.possible_styles[3] = "Mills Mess";
this.possible_styles[4] = "Center";
this.possible_styles[5] = "Windmill";
//this.possible_styles[6] = "Random";
//this.self = this;
this.initialize();
}
// Misc. utility functions
JMLib.max = function (a, b) {
if (a > b) return a;
return b;
};
JMLib.min = function (a, b) {
if (a < b) return a;
return b;
};
JMLib.jijo = function (x) {
return x * x;
};
// Calculates |x|
JMLib.xabs = function (x) {
if (x < 0) return -x;
return x;
};
// Calculates x^y
JMLib.xpow = function (x, y) {
for (var i = 0; i < y - 1; i++) {
x *= y;
//document.write("i=" + i + " x=" + x + "<br>");
}
return x;
};
JMLib.random = function (x) {
return Math.floor(x * Math.random() % 1);
};
// For status
JMLib.ST_NONE = 0;
JMLib.ST_PAUSE = 1;
JMLib.ST_JUGGLE = 2;
// Misc. constants
JMLib.KW = 0.25;
JMLib.DW = 290; // max of dpm
/* low mem profile
JMLib.XR = 255; // Accuracy of x axis, set higher for large screens 255
JMLib.BMAX = 35; // max number of balls
JMLib.MMAX = 11; // Max multiplex, double+1
*/
// high mem profile
JMLib.XR = 1024; // Accuracy of x axis, set higher for large screens 255
JMLib.BMAX = 630; // max number of balls
JMLib.MMAX = 71; // Max multiplex, double+1
//
JMLib.LMAX = 76; // max column of a pattern
JMLib.OBJECT_HAND = 0x01;
JMLib.OBJECT_UNDER = 0x02;
JMLib.OBJECT_MOVE = 0x04;
JMLib.OBJECT_MOVE2 = 0x08;
JMLib.STYLEMAX = 3000; // maximum length of style data
JMLib.JML_MAX_SECTIONLEN = 40;
JMLib.JML_MAX_NAMELEN = 56;
JMLib.JML_MAX_SITELEN = 56;
JMLib.JML_MAX_STYLELEN = 56;
// high mem profile
//JMLib.JML_MAX_STYLELEN = 500;
JMLib.SPEED_MAX = 2.0;
JMLib.SPEED_MIN = 0.1;
JMLib.SPEED_DEF = 1.0;
JMLib.HR_MAX = 1.00;
JMLib.HR_MIN = 0.04;
JMLib.HR_DEF = 0.17;
JMLib.DR_MAX = 0.90;
JMLib.DR_MIN = 0.10;
JMLib.DR_DEF = 0.50;
JMLib.FS_MAX = 10;
JMLib.FS_MIN = 1;
JMLib.FS_DEF = 1;
// Scaling methods
JMLib.SCALING_METHOD_CLASSIC = 1;
JMLib.SCALING_METHOD_DYNAMIC = 2;
JMLib.prototype.getSiteposStart = function () {
if (this.syn && this.time_period % 2 == 1) {
return this.steps[this.time_period - 1];
}
return this.steps[this.time_period];
};
JMLib.prototype.getSiteposStop = function () {
if (this.syn && this.time_period % 2 == 0) {
return this.steps[this.time_period + 2];
}
return this.steps[this.time_period + 1];
};
JMLib.prototype.getSiteposLen = function () {
return this.getSiteposStop() - this.getSiteposStart();
};
JMLib.prototype.getiterations = function () {
return this.dpm;
};
JMLib.prototype.initialize = function () {
// Set default values
this.ga = 9.8;
this.dwell_ratio = 0.5;
this.height_ratio = 0.20;
this.mirror = 0;
this.cSpeed = JMLib.SPEED_DEF;
this.syn = 0;
this.hand_on = 1;
this.hand_x = 0;
this.hand_y = 0;
this.scalingMethod = JMLib.SCALING_METHOD_CLASSIC;
this.smode = 50.0;
this.status = JMLib.ST_NONE;
//fixme: add random number seed here
this.setWindowSize(480, 400);
this.setPatternDefault();
};
JMLib.prototype.shutdown = function () {};
JMLib.prototype.error = function (msg) {
this.lastError = msg;
if (this.errorCallback) {
this.errorCallback(msg);
}
};
JMLib.prototype.setWindowSizeDefault = function () {
this.setWindowSize(480, 400);
};
JMLib.prototype.setWindowSize = function (width, height) {
if (width <= 0 || height <= 0) return false;
if (this.scalingMethod == JMLib.SCALING_METHOD_DYNAMIC) {
this.scaleImageWidth = width;
this.scaleImageHeight = height;
return true;
}
// store current status and stop juggling
var oldStatus = this.status;
this.stopJuggle();
// set size
this.imageWidth = width;
this.imageHeight = height;
this.horCenter = parseInt(this.imageWidth / 2);
this.verCenter = parseInt(this.imageHeight / 2);
// recalculate pattern
if (oldStatus != JMLib.ST_NONE) this.startJuggle();
// restore state
this.status = oldStatus;
return true;
};
JMLib.prototype.setScalingMethod = function (scalingMethod) {
// no change
if (this.scalingMethod == scalingMethod) return;
if (scalingMethod == JMLib.SCALING_METHOD_DYNAMIC) {
this.scaleImageWidth = this.imageWidth;
this.scaleImageHeight = this.imageHeight;
this.setWindowSizeDefault();
this.scalingMethod = JMLib.SCALING_METHOD_DYNAMIC;
} else {
//SCALING_METHOD_CLASSIC
this.calingMethod = JMLib.SCALING_METHOD_CLASSIC;
this.setWindowSize(this.scaleImageWidth, this.scaleImageHeight);
}
};
JMLib.prototype.SCALING_METHOD_CLASSIC = JMLib.SCALING_METHOD_CLASSIC;
JMLib.prototype.SCALING_METHOD_DYNAMIC = JMLib.SCALING_METHOD_DYNAMIC;
JMLib.prototype.getImageWidth = function () {
if (this.scalingMethod == JMLib.SCALING_METHOD_CLASSIC) return this.imageWidth;else // SCALING_METHOD_DYNAMIC
return this.scaleImageWidth;
};
JMLib.prototype.getImageHeight = function () {
if (this.scalingMethod == JMLib.SCALING_METHOD_CLASSIC) return this.imageHeight;else // SCALING_METHOD_DYNAMIC
return this.scaleImageHeight;
};
JMLib.prototype.getBallRadius = function () {
var baseRadius = parseInt(11 * this.dpm / JMLib.DW);
if (this.scalingMethod == JMLib.SCALING_METHOD_CLASSIC) {
return baseRadius;
} else {
var zoomFactorY = this.scaleImageHeight / this.imageHeight;
zoomFactorY *= 0.9;
if (this.scaleImageWidth < this.scaleImageHeight) zoomFactorY *= this.scaleImageWidth / this.scaleImageHeight;
return parseInt(baseRadius * zoomFactorY); // convert return value to int
}
};
JMLib.prototype.doCoordTransform = function () {
var i;
var zoomFactorX = this.scaleImageWidth / this.imageWidth;
var zoomFactorY = this.scaleImageHeight / this.imageHeight;
// adjust for aspect ratio
if (this.scaleImageWidth < this.scaleImageHeight) zoomFactorY *= this.scaleImageWidth / this.scaleImageHeight;else zoomFactorX *= this.scaleImageHeight / this.scaleImageWidth;
zoomFactorX *= 1.1;
zoomFactorY *= 0.9;
// Adjust coordinates
// head
this.ap.hx -= parseInt(this.imageWidth / 2);
this.ap.hy -= parseInt(this.imageHeight / 2);
this.ap.hx = parseInt(this.ap.hx * zoomFactorX);
this.ap.hy = parseInt(this.ap.hy * zoomFactorY);
this.ap.hr = parseInt(this.ap.hr * zoomFactorY);
this.ap.hx += parseInt(this.scaleImageWidth / 2);
this.ap.hy += parseInt(this.scaleImageHeight / 2);
// juggler
for (i = 0; i < 6; i++) {
this.ap.rx[i] -= parseInt(this.imageWidth / 2);
this.ap.ry[i] -= parseInt(this.imageHeight / 2);
this.ap.rx[i] = parseInt(this.ap.rx[i] * zoomFactorX);
this.ap.ry[i] = parseInt(this.ap.ry[i] * zoomFactorY);
this.ap.rx[i] += parseInt(this.scaleImageWidth / 2);
this.ap.ry[i] += parseInt(this.scaleImageHeight / 2);
this.ap.lx[i] -= parseInt(this.imageWidth / 2);
this.ap.ly[i] -= parseInt(this.imageHeight / 2);
this.ap.lx[i] = parseInt(this.ap.lx[i] * zoomFactorX);
this.ap.ly[i] = parseInt(this.ap.ly[i] * zoomFactorY);
this.ap.lx[i] += parseInt(this.scaleImageWidth / 2);
this.ap.ly[i] += parseInt(this.scaleImageHeight / 2);
}
// hands
this.rhand.gx -= parseInt(this.imageWidth / 2);
this.rhand.gy -= parseInt(this.imageHeight / 2);
this.rhand.gx = parseInt(this.rhand.gx * zoomFactorX);
this.rhand.gy = parseInt(this.rhand.gy * zoomFactorY);
this.rhand.gx += parseInt(this.scaleImageWidth / 2);
this.rhand.gy += parseInt(this.scaleImageHeight / 2);
this.lhand.gx -= parseInt(this.imageWidth / 2);
this.lhand.gy -= parseInt(this.imageHeight / 2);
this.lhand.gx = parseInt(this.lhand.gx * zoomFactorX);
this.lhand.gy = parseInt(this.lhand.gy * zoomFactorY);
this.lhand.gx += parseInt(this.scaleImageWidth / 2);
this.lhand.gy += parseInt(this.scaleImageHeight / 2);
for (i = 0; i <= 9; i++) {
this.handpoly.rx[i] = parseInt(this.handpoly_ex.rx[i] * zoomFactorX);
this.handpoly.ry[i] = parseInt(this.handpoly_ex.ry[i] * zoomFactorY);
this.handpoly.lx[i] = parseInt(this.handpoly_ex.lx[i] * zoomFactorX);
this.handpoly.ly[i] = parseInt(this.handpoly_ex.ly[i] * zoomFactorY);
}
// balls
for (i = this.numBalls() - 1; i >= 0; i--) {
this.b[i].gx -= parseInt(this.imageWidth / 2);
this.b[i].gy -= parseInt(this.imageHeight / 2);
this.b[i].gx = parseInt(this.b[i].gx * zoomFactorX);
this.b[i].gy = parseInt(this.b[i].gy * zoomFactorY);
this.b[i].gx += parseInt(this.scaleImageWidth / 2);
this.b[i].gy += parseInt(this.scaleImageHeight / 2);
}
};
JMLib.prototype.setMirror = function (mir) {
// store current status and stop juggling
var oldStatus = this.status;
this.stopJuggle();
// set mirror
this.mirror = mir;
// recalculate pattern
if (oldStatus != JMLib.ST_NONE) JMLib.prototype.startJuggle();
// restore state
this.status = oldStatus;
};
JMLib.prototype.setPattern = function (name, site, hr, dr) {
if (site.length > JMLib.JML_MAX_SITELEN) {
this.error("Siteswap too long");
return false;
}
if (name.length > JMLib.JML_MAX_NAMELEN) {
this.error("Pattern name too long");
return false;
}
if (!validator.validateSite(site)) {
this.error("Invalid siteswap");
return false;
}
this.siteswap = site;
this.pattname = name;
this.height_ratio = hr;
this.dwell_ratio = dr;
// Turn off beep
this.beep = 0;
// Check ratios
if (this.height_ratio < JMLib.HR_MIN || this.height_ratio > JMLib.HR_MAX) this.height_ratio = JMLib.HR_DEF;
if (this.dwell_ratio < JMLib.DR_MIN || this.dwell_ratio > JMLib.DR_MAX) this.dwell_ratio = JMLib.DR_DEF;
// Set pattern
if ((this.jml_errno = this.set_patt(site)) == 0) {
this.doStepcalc();
return true;
} else {
switch (this.jml_errno) {
case 4:
this.error("Syntax error");
break;
case 5:
this.error("Invalid pattern");
break;
case 6:
this.error("Invalid character in pattern");
break;
case 7:
this.error("Synchronous number must be even");
break;
case 8:
this.error("Max 6 balls may be multiplexed");
break;
case 9:
this.error("Too many balls in pattern");
break;
case 10:
this.error("Pattern too long");
break;
case 13:
this.error("0 inside [] is invalid");
break;
default:
this.error("Unexpected error");
break;
}
return false;
}
};
JMLib.prototype.setStyle = function (name, length, data) {
if (data.length > JMLib.JML_MAX_STYLELEN) {
this.error("Style too large");
return false;
}
if (name.length > JMLib.JML_MAX_NAMELEN) {
this.error("Style name too long");
return false;
}
this.stylename = name;
this.styledata = data;
this.style_len = length;
return true;
};
//fixme: style data is passed as an array
// should perhaps add a style data class
JMLib.prototype.setStyleEx = function (name) {
var style;
if (name == "Normal") {
style = new Array(13, 0, 4, 0);
this.setStyle(name, 1, style);
} else if (name == "Reverse") {
style = new Array(4, 0, 13, 0);
this.setStyle(name, 1, style);
} else if (name == "Shower") {
style = new Array(5, 0, 10, 0, 10, 0, 5, 0);
this.setStyle(name, 2, style);
} else if (name == "Mills Mess") {
style = new Array(-1, 0, -12, 0, 0, 0, 12, 0, 1, 0, -12, 0);
this.setStyle(name, 3, style);
} else if (name == "Center") {
style = new Array(13, 0, 0, 0);
this.setStyle(name, 1, style);
} else if (name == "Windmill") {
style = new Array(10, 0, -8, 0, -8, 0, 10, 0);
this.setStyle(name, 2, style);
}
// placeholder for adding random style support here
else {
// anything else is interpreted as "Normal"
this.setStyleDefault();
}
return true;
};
JMLib.prototype.getStyles = function () {
return this.possible_styles;
};
JMLib.prototype.numStyles = function () {
return this.possible_styles.length;
};
JMLib.prototype.setPatternDefault = function () {
this.setPattern("3 Cascade", "3", JMLib.HR_DEF, JMLib.DR_DEF);
this.setStyleDefault();
};
JMLib.prototype.setStyleDefault = function () {
var defStyle = new Array(13, 0, 4, 0);
//this.setStyle("Normal", 1, defStyle);
this.stylename = "Normal";
this.styledata = defStyle;
this.style_len = 1;
};
JMLib.prototype.setHR = function (HR) {
if (HR > JMLib.HR_MAX) {
this.height_ratio = JMLib.HR_MAX;
} else if (HR < JMLib.HR_MIN) {
this.height_ratio = JMLib.HR_MIN;
} else {
this.height_ratio = HR;
}
};
JMLib.prototype.getHR = function () {
return this.height_ratio;
};
JMLib.prototype.setDR = function (DR) {
if (DR > JMLib.DR_MAX) {
this.dwell_ratio = JMLib.DR_MAX;
} else if (DR < JMLib.DR_MIN) {
this.dwell_ratio = JMLib.DR_MIN;
} else {
this.dwell_ratio = DR;
}
};
JMLib.prototype.getDR = function () {
return this.dwell_ratio;
};
JMLib.prototype.numBalls = function () {
return this.balln;
};
// Internal functions
JMLib.prototype.arm_line = function () {
var mx, my, sx, sy;
if (this.hand_on) {
// only bother calculating if hands are drawn
// Notes:
// * gx/gy may need to be replaced by gx0/gy0 if erasing old values
// the method used in the X11 version
// * JMWin uses 11*dpm/DW instead of 11, which causes incorrect
// hand placement for some reason.
this.ap.rx[0] = this.rhand.gx + 11 + this.arm_x;
this.ap.ry[0] = this.rhand.gy + 11 + this.arm_y;
this.ap.lx[0] = this.lhand.gx + 11 - this.arm_x;
this.ap.ly[0] = this.lhand.gy + 11 + this.arm_y;
sx = parseInt(this.dpm * JMLib.XR / this.kw0);
sy = this.base - parseInt(this.dpm / 3);
this.ap.rx[1] = parseInt((this.ap.rx[0] + (this.horCenter + sx) * 2) / 3 + this.dpm / 12);
this.ap.lx[1] = parseInt((this.ap.lx[0] + (this.horCenter - sx) * 2) / 3 - this.dpm / 12);
this.ap.ry[1] = parseInt((this.ap.ry[0] + sy) / 2 + this.dpm / 8);
this.ap.ly[1] = parseInt((this.ap.ly[0] + sy) / 2 + this.dpm / 8);
this.ap.rx[2] = parseInt((this.ap.rx[1] + (this.horCenter + sx) * 3) / 4);
this.ap.lx[2] = parseInt((this.ap.lx[1] + (this.horCenter - sx) * 3) / 4);
this.ap.ry[2] = parseInt((this.ap.ry[1] + sy * 2) / 3 - this.dpm / 25);
this.ap.ly[2] = parseInt((this.ap.ly[1] + sy * 2) / 3 - this.dpm / 25);
this.ap.rx[3] = parseInt((this.ap.rx[2] + (this.horCenter + sx) * 2) / 3 - this.dpm / 13);
this.ap.lx[3] = parseInt((this.ap.lx[2] + (this.horCenter - sx) * 2) / 3 + this.dpm / 13);
this.ap.ry[3] = parseInt((this.ap.ry[2] + sy * 2) / 3 - this.dpm / 40);
this.ap.ly[3] = parseInt((this.ap.ly[2] + sy * 2) / 3 - this.dpm / 40);
mx = (this.ap.rx[3] + this.ap.lx[3]) / 2;
my = (this.ap.ry[3] + this.ap.ly[3]) / 2;
this.ap.rx[4] = parseInt((mx * 2 + this.ap.rx[3]) / 3);
this.ap.lx[4] = parseInt((mx * 2 + this.ap.lx[3]) / 3);
this.ap.ry[4] = parseInt((my * 2 + this.ap.ry[3]) / 3);
this.ap.ly[4] = parseInt((my * 2 + this.ap.ly[3]) / 3);
this.ap.hx = parseInt(mx);
this.ap.hy = parseInt((my * 2 - this.dpm * 2 / 3 + this.base) / 3);
this.ap.hr = parseInt(this.dpm / 11);
this.ap.rx[5] = this.ap.hx + parseInt(this.dpm / 20);
this.ap.lx[5] = this.ap.hx - parseInt(this.dpm / 20);
this.ap.ry[5] = this.ap.hy + parseInt(this.dpm / 13);
this.ap.ly[5] = parseInt(this.ap.ry[5]);
}
};
JMLib.prototype.applyCorrections = function () {
// Correct ball coordinates
for (var i = this.balln - 1; i >= 0; i--) {
this.b[i].gx += this.bm1;
this.b[i].gy += this.bm1;
}
};
JMLib.prototype.hand_pos = function (c, h, x, z) {
//fixme: for testing only, remove
// x and z must be arrays with one element (pass-by-reference emulation)
//if (!(x instanceof Array)) document.write("hand_pos assert failure (x)<br>");
//if (!(z instanceof Array)) document.write("hand_pos assert failure (z)<br>");
var a;
if (this.mirror) {
if (!this.syn && h) c--;
if (c & 1) a = (--c + h) % this.style_len * 4 + 2;else a = (c + h) % this.style_len * 4;
} else {
if (!this.syn && !h) c--;
if (c & 1) a = (c - h) % this.style_len * 4 + 2;else a = (c + 1 - h) % this.style_len * 4;
}
if (h) x[0] = this.styledata[a];else x[0] = -this.styledata[a];
z[0] = this.styledata[a + 1];
};
JMLib.prototype.juggle = function ( /*Ball*/d) {
var tp;
var flag = 0;
var h, t;
var tpox = new Array(1);
tpox[0] = 0;
var rpox = new Array(1);
rpox[0] = 0;
var tpoz = new Array(1);
tpoz[0] = 0;
var rpoz = new Array(1);
rpoz[0] = 0;
var x = 0;
var y = 0;
// Save old values
d.gx1 = d.gx0;
d.gy1 = d.gy0;
d.gx0 = d.gx;
d.gy0 = d.gy;
if (d.c < 0) {
if (this.time_count >= -d.c * this.tw) d.c = -d.c;
}
while (true) {
tp = this.time_count - this.tw * JMLib.xabs(d.c);
if (tp < this.aw) break;
d.st &= ~JMLib.OBJECT_UNDER;
d.c0 = d.c;
if (d.st & JMLib.OBJECT_HAND) {
d.c += 2;
this.flag = 1;
} else {
t = d.c;
if (this.syn) {
if (this.mirror && !d.chand) t++;else if (!this.mirror && d.chand) t++;
}
t %= this.pattw;
d.bh = this.patt[t][this.r[t]];
d.c += JMLib.xabs(d.bh);
if (++this.r[t] >= this.patts[t]) this.r[t] = 0;
d.thand = d.chand;
if (d.bh & 1 || d.bh < 0) d.chand = 1 - d.chand;
flag = 1;
}
}
if (d.c >= 0 && tp >= 0 && !(d.st & JMLib.OBJECT_UNDER)) {
d.st |= JMLib.OBJECT_UNDER;
if (d.st & JMLib.OBJECT_HAND) {
if (d.st & JMLib.OBJECT_MOVE2) {
d.st |= JMLib.OBJECT_MOVE;
d.st &= ~JMLib.OBJECT_MOVE2;
} else {
d.st &= ~JMLib.OBJECT_MOVE;
}
} else {
t = d.c;
if (this.syn) {
if (this.mirror && !d.chand) t++;else if (!this.mirror && d.chand) t++;
}
t %= this.pattw;
if (d.bh == 1) d.st |= JMLib.OBJECT_MOVE;else d.st &= ~JMLib.OBJECT_MOVE;
for (var i = 0; i < this.patts[t]; i++) {
h = this.patt[t][i];
if (h == 1) {
if (d.chand) this.lhand.st |= JMLib.OBJECT_MOVE2;else this.rhand.st |= JMLib.OBJECT_MOVE2;
}
if (h != 2) {
if (d.chand) this.rhand.st |= JMLib.OBJECT_MOVE2;else this.lhand.st |= JMLib.OBJECT_MOVE2;
d.st |= JMLib.OBJECT_MOVE;
}
}
}
}
if (!(d.st & JMLib.OBJECT_MOVE)) {
if (d.c < 0) {
//opera.postError("BEFORE hand_pos(" + -d.c + ", " + d.chand + ", " + tpox[0] + ", " + tpoz[0] + ")");
this.hand_pos(-d.c, d.chand, tpox, tpoz);
//opera.postError("AFTER hand_pos(" + -d.c + ", " + d.chand + ", " + tpox[0] + ", " + tpoz[0] + ")");
rpox[0] = tpox[0];
rpoz[0] = tpoz[0];
} else {
if (d.st & JMLib.OBJECT_UNDER) {
//opera.postError("BEFORE hand_pos(" + d.c + ", " + d.chand + ", " + tpox[0] + ", " + tpoz[0] + ")");
this.hand_pos(d.c, d.chand, tpox, tpoz);
//opera.postError("AFTER hand_pos(" + d.c + ", " + d.chand + ", " + tpox[0] + ", " + tpoz[0] + ")");
//opera.postError("BEFORE hand_pos(" + (d.c + 2) + ", " + d.chand + ", " + rpox[0] + ", " + rpoz[0] + ")");
this.hand_pos(d.c + 2, d.chand, rpox, rpoz);
//opera.postError("AFTER hand_pos(" + (d.c + 2) + ", " + d.chand + ", " + rpox[0] + ", " + rpoz[0] + ")");
if (tpox[0] != rpox[0] || tpoz[0] != rpoz[0]) {
this.hand_pos(d.c + 1, d.chand, rpox, rpoz);
if (tpox[0] != rpox[0] || tpoz[0] != rpoz[0]) d.st |= JMLib.OBJECT_MOVE;
}
} else {
this.hand_pos(d.c - 2, d.chand, tpox, tpoz);
this.hand_pos(d.c, d.chand, rpox, rpoz);
if (tpox[0] != rpox[0] || tpoz[0] != rpoz[0]) {
this.hand_pos(d.c - 1, d.chand, tpox, tpoz);
if (tpox[0] != rpox[0] || tpoz[0] != rpoz[0]) d.st |= JMLib.OBJECT_MOVE;
}
}
}
}
if (d.st & JMLib.OBJECT_MOVE) {
if (d.bh == 1) {
this.hand_pos(d.c0 + 1, d.thand, tpox, tpoz);
this.hand_pos(d.c + 1, d.chand, rpox, rpoz);
} else if (d.st & JMLib.OBJECT_UNDER) {
this.hand_pos(d.c, d.chand, tpox, tpoz);
this.hand_pos(d.c + 1, d.chand, rpox, rpoz);
} else {
this.hand_pos(d.c0 + 1, d.thand, tpox, tpoz);
this.hand_pos(d.c, d.chand, rpox, rpoz);
}
}
if (this.fpu) {
var fx;
if (!(d.st & JMLib.OBJECT_HAND) && d.c < 0) {
if (tpox[0] == 0) {
fx = 0;
y = parseInt(tpoz[0] * this.dpm / 20 - tp * this.dpm / 12 / this.tw);
//opera.postError("x=" + x + ", y=" + y);
//opera.postError(y, tpoz[0], this.dpm, tp, this.dpm, this.tw);
} else {
if (tpox[0] > 0) fx = tpox[0] / 10 - tp / 6 / this.tw;else fx = tpox[0] / 10 + tp / 6 / this.tw;
y = parseInt(tpoz[0] * this.dpm / 20);
}
} else if (!(d.st & JMLib.OBJECT_MOVE)) {
fx = tpox[0] / 10;
y = tpoz[0] * this.dpm / 20;
} else {
if (d.bh == 1) {
fx = (tp - this.aw) / this.tw * 2 + 1;
y = parseInt(this.high[1] * (1 - JMLib.jijo(fx)));
} else if (d.st & JMLib.OBJECT_UNDER) {
fx = tp / this.aw * 2 - 1;
y = parseInt(this.high[0] * (1 - JMLib.jijo(fx)));
} else {
fx = tp / (this.tw * JMLib.xabs(d.bh) - this.aw) * 2 + 1;
y = parseInt(this.high[JMLib.xabs(d.bh)] * (1 - JMLib.jijo(fx)));
}
y += parseInt((fx * (rpoz[0] - tpoz[0]) + rpoz[0] + tpoz[0]) * this.dpm / 40);
d.t = fx; // spin
fx = (fx * (rpox[0] - tpox[0]) + rpox[0] + tpox[0]) / 20;
}
x = parseInt(fx * this.dpm * JMLib.KW);
} else {
if (!(d.st & JMLib.OBJECT_HAND) && d.c < 0) {
if (tpox[0] == 0) {
x = 0;
y = parseInt(tpoz[0] * this.dpm / 20 - tp * this.dpm / 12 / this.tw);
} else {
if (tpox[0] > 0) x = parseInt(JMLib.XR * tpox[0] / 10 - JMLib.XR * tp / 6 / this.tw);else x = parseInt(JMLib.XR * tpox[0] / 10 + JMLib.XR * tp / 6 / this.tw);
y = parseInt(tpoz[0] * this.dpm / 20);
}
} else if (!(d.st & JMLib.OBJECT_MOVE)) {
x = parseInt(JMLib.XR * tpox[0] / 10);
y = parseInt(tpoz[0] * this.dpm / 20);
} else {
if (d.bh == 1) {
x = parseInt(JMLib.XR * (tp - this.aw) * 2 / this.tw + JMLib.XR);
y = parseInt((JMLib.jijo(JMLib.XR) - JMLib.jijo(x)) / this.high0[1]);
} else if (d.st & JMLib.OBJECT_UNDER) {
x = parseInt(JMLib.XR * tp * 2 / this.aw - JMLib.XR);
y = parseInt((JMLib.jijo(JMLib.XR) - JMLib.jijo(x)) / this.high0[0]);
} else {
x = parseInt(JMLib.XR * tp * 2 / (this.tw * JMLib.xabs(d.bh) - this.aw) + JMLib.XR);
y = parseInt((JMLib.jijo(JMLib.XR) - JMLib.jijo(x)) / this.high0[JMLib.xabs(d.bh)]);
}
y += parseInt((x * (rpoz[0] - tpoz[0]) + JMLib.XR * (rpoz[0] + tpoz[0])) * this.dpm / JMLib.XR / 40);
x = parseInt((x * (rpox[0] - tpox[0]) + JMLib.XR * (rpox[0] + tpox[0])) / 20);
}
x = parseInt(x * this.dpm / this.kw0);
}
// NOTE:
// * The alternative calulations of d->gx and gy below are
// from JMWin. They cause the entire pattern to be skewed.
//opera.postError(d);
d.gx = this.horCenter + x - 11;
//d->gx=horCenter + x - 11 * dpm / DW;
//opera.postError(d);
//opera.postError("hand_x=" + this.hand_x + " hand_y=" + this.hand_y);
if (d.st & JMLib.OBJECT_HAND) {
if (d.chand) d.gx += this.hand_x;else d.gx -= this.hand_x;
y -= this.hand_y;
}
d.gy = this.base - y - 11;
//d->gy = base - y - 11 * dpm / DW;
return flag;
};
JMLib.prototype.set_ini = function (rr) {
var i, j;
var tw0;
var aw0;
this.balln = 0;
this.pmax = 0;
if (this.pattw > JMLib.LMAX) return 10;
if (this.pattw == 0) return 1;
for (i = 0; i < this.pattw; i++) {
for (j = 0; j < this.patts[i]; j++) {
this.balln += JMLib.xabs(this.patt[i][j]);
this.pmax = JMLib.max(this.pmax, JMLib.xabs(this.patt[i][j]));
}
}
if (this.balln % this.pattw) return 5;
this.balln = parseInt(this.balln / this.pattw);
if (this.balln == 0) return 9;
if (this.balln > JMLib.BMAX) return 9;
for (i = 0; i < JMLib.LMAX * 2; i++) {
this.r[i] = 0;
}for (i = 0; i <= this.balln; i++) {
j = 0;
while (this.r[j] == this.patts[j % this.pattw] && j < this.pattw + this.pmax) {
j++;
}if (i == this.balln) {
if (j == this.pattw + this.pmax) break;else return 5;
}
this.b[i].st = 0;
if (this.mirror) {
if ((j + this.syn) % 2) {
this.b[i].thand = 1;
this.b[i].chand = 1;
} else {
this.b[i].thand = 0;
this.b[i].chand = 0;
}
} else {
if ((j + this.syn) % 2) {
this.b[i].thand = 0;
this.b[i].chand = 0;
} else {
this.b[i].thand = 1;
this.b[i].chand = 1;
}
}
if (this.syn) this.b[i].c = -parseInt(j / 2) * 2;else this.b[i].c = -j;
while (j < this.pattw + this.pmax) {
if (this.r[j] == this.patts[j % this.pattw]) return 5;else this.r[j]++;
var k = this.patt[j % this.pattw][this.patts[j % this.pattw] - this.r[j]];
if (this.syn && k < 0) {
if (j % 2 == 0) j += -k + 1;else j += -k - 1;
} else {
j += k;
}
}
}
if (rr == 0) return 0;
if (this.pmax < 3) this.pmax = 3;
tw0 = Math.sqrt(2 / this.ga * this.pmax * this.height_ratio) * 2 / (this.pmax - this.dwell_ratio * 2) * this.smode / this.cSpeed;
this.tw = parseInt(this.fadd(tw0, 0, 0));
if (this.tw == 0) return 15;
aw0 = tw0 * this.dwell_ratio * 2;
this.aw = parseInt(this.fadd(aw0, 0, 0));
if (this.aw < 1) this.aw = 1;
if (this.aw > this.tw * 2 - 1) this.aw = this.tw * 2 - 1;
this.kw0 = parseInt(JMLib.XR / JMLib.KW);
if (this.fpu) {
this.high[0] = -0.2 * this.dpm;
this.high[1] = this.ga * JMLib.jijo(tw0 / this.smode * this.cSpeed) / 8 * this.dpm;
for (i = 2; i <= this.pmax; i++) {
this.high[i] = this.ga * JMLib.jijo((tw0 * i - aw0) / this.smode * this.cSpeed) / 8 * this.dpm;
}
} else {
this.high0[0] = parseInt(-JMLib.jijo(JMLib.XR) / 0.2 * this.dpm);
this.high0[1] = parseInt(JMLib.jijo(JMLib.XR) / (this.ga * JMLib.jijo(tw0 / this.smode * this.cSpeed) / 8 * this.dpm));
for (i = 2; i <= this.pmax; i++) {
this.high0[i] = parseInt(JMLib.jijo(JMLib.XR) / (this.ga * JMLib.jijo((tw0 * i - aw0) / this.smode * this.cSpeed) / 8 * this.dpm));
}
}
for (i = 0; i < this.balln; i++) {
this.b[i].bh = 0;
this.b[i].gx = this.horCenter;
this.b[i].gy = this.verCenter;
this.b[i].gx0 = this.horCenter;
this.b[i].gy0 = this.verCenter;
this.b[i].gx1 = this.horCenter;
this.b[i].gy1 = this.verCenter;
}
if (this.mirror) {
this.lhand.c = 0;
if (this.syn) this.rhand.c = 0;else this.rhand.c = -1;
} else {
this.rhand.c = 0;
if (this.syn) this.lhand.c = 0;else this.lhand.c = -1;
}
this.rhand.bh = 2;
this.rhand.st = JMLib.OBJECT_HAND;
this.rhand.thand = 1;
this.rhand.chand = 1;
this.rhand.gx = this.horCenter;
this.rhand.gy = this.verCenter;
this.rhand.gx0 = this.horCenter;
this.rhand.gy0 = this.verCenter;
this.rhand.gx1 = this.horCenter;
this.rhand.gy1 = this.verCenter;
this.lhand.bh = 2;
this.lhand.st = JMLib.OBJECT_HAND;
this.lhand.thand = 0;
this.lhand.chand = 0;
this.lhand.gx = this.horCenter;
this.lhand.gy = this.verCenter;
this.lhand.gx0 = this.horCenter;
this.lhand.gy0 = this.verCenter;
this.lhand.gx1 = this.horCenter;
this.lhand.gy1 = this.verCenter;
for (i = 0; i < this.pattw; i++) {
this.r[i] = 0;
}return 0;
};
JMLib.prototype.set_dpm = function () {
var cSpeed0;
cSpeed0 = this.cSpeed;
this.cSpeed = 2.0;
this.base = 0;
this.dpm = 400;
this.gy_max = 80 - 11;
this.gy_min = -200 - 11;
this.gx_max = -1000;
this.gx_min = 1000;
if (this.set_ini(1) == 0) {
for (this.time_count = 0; this.time_count < this.tw * (this.pattw + this.pmax + this.style_len); this.time_count++) {
for (var i = 0; i < this.balln; i++) {
this.juggle(this.b[i]);
this.gy_max = JMLib.max(this.gy_max, this.b[i].gy);
this.gy_min = JMLib.min(this.gy_min, this.b[i].gy);
this.gx_max = JMLib.max(this.gx_max, this.b[i].gx + 2 * 11 * this.dpm / this.DW); // changed from X11 version
this.gx_min = JMLib.min(this.gx_min, this.b[i].gx);
}
this.juggle(this.rhand);
this.juggle(this.lhand);
this.gy_max = JMLib.max(this.gy_max, this.rhand.gy);
this.gy_min = JMLib.min(this.gy_min, this.rhand.gy);
this.gy_max = JMLib.max(this.gy_max, this.lhand.gy);
this.gy_min = JMLib.min(this.gy_min, this.lhand.gy);
this.gx_max = JMLib.max(this.gx_max, this.rhand.gx);
this.gx_min = JMLib.min(this.gx_min, this.rhand.gx);
this.gx_max = JMLib.max(this.gx_max, this.lhand.gx);
this.gx_min = JMLib.min(this.gx_min, this.lhand.gx);
this.arm_x = parseInt((22 - 11) * this.dpm / JMLib.DW);
this.arm_y = parseInt((16 - 11) * this.dpm / JMLib.DW);
// from JMWin:
//ap.rx[0]=rhand.gx +11*dpm/DW+arm_x;
//ap.ry[0]=rhand.gy +11*dpm/DW+arm_y;
//ap.lx[0]=lhand.gx +11*dpm/DW-arm_x;
//ap.ly[0]=lhand.gy +11*dpm/DW+arm_y;
//
this.arm_line();
for (i = 0; i < 5; i++) {
this.gx_max = JMLib.max(this.gx_max, this.ap.rx[i]);
this.gx_max = JMLib.max(this.gx_max, this.ap.lx[i]);
this.gx_min = JMLib.min(this.gx_min, this.ap.rx[i]);
this.gx_min = JMLib.min(this.gx_min, this.ap.lx[i]);
}
}
}
if (this.gy_max - this.gy_min > 0) {
// special handling for smaller screens
if (this.imageWidth <= 320) {
if (this.imageWidth > 160) {
// 160-320 width
this.dpm = parseInt(this.imageHeight * 280 / (this.gy_max - this.gy_min));
this.base = parseInt(this.imageHeight - this.gy_max * this.dpm / this.imageHeight - 5);
} else {
// 0-160 width
this.dpm = parseInt(this.imageHeight * 280 / (this.gy_max - this.gy_min));
this.base = parseInt(this.imageHeight - this.imageHeight / 4);
}
} else {
this.dpm = parseInt(400.0 * (this.imageHeight - 30 * 2) / (this.gy_max - this.gy_min));
this.base = parseInt(this.imageHeight - 30 - this.gy_max * this.dpm / 400);
}
this.gx_min = parseInt(this.horCenter - (this.horCenter - this.gx_min) * this.dpm / 400);
this.gx_max = parseInt(this.horCenter - (this.horCenter - this.gx_max) * this.dpm / 400);
// original version
//dpm=(JML_INT32)(400.0*340/(gy_max-gy_min));
//if(dpm>DW) dpm=DW;
//base=370-(JML_INT32)( (JML_FLOAT)gy_max*dpm/400 );
}
this.cSpeed = cSpeed0;
};
JMLib.prototype.set_patt = function (s) {
var flag = 0;
var flag2 = 0;
var a = 0;
var pos = 0;
if (s.length > JMLib.LMAX) return 10;
this.pattw = 0;
this.balln = 0;
if (s.charAt(0) == '(') this.syn = 1;else this.syn = 0;
for (var i = 0; i < JMLib.LMAX; i++) {
if (i >= s.length) {
if (flag != 0 || flag2 != 0) return 4;
break;
}
if (s.charAt(pos) == '[') {
flag2 = 1;
this.patts[this.pattw] = 0;
pos++;
continue;
}
if (s.charAt(pos) == ']') {
if (flag2 == 0) return 4;
flag2 = 0;
this.pattw++;
pos++;
continue;
}
if (this.syn == 1) {
switch (s.charAt(pos)) {
case '(':
if (flag != 0) return 4;
flag = 1;
pos++;
continue;
case ')':
if (flag != 5) return 4;
flag = 0;
pos++;
continue;
case ',':
if (flag != 2) return 4;
flag = 4;
pos++;
continue;
case 'X':
case 'x':
if (flag != 2 && flag != 5) return 4;
if (flag2) this.patt[this.pattw][this.patts[this.pattw] - 1] = -a;else this.patt[this.pattw - 1][0] = -a;
pos++;
continue;
}
}
a = this.ctod(s.charAt(pos));
if (a == -1) return 6;
if (this.syn) {
if (a % 2) return 7;
if (flag2 == 0 && flag != 1 && flag != 4) return 4;
if (flag == 1) flag = 2;
if (flag == 4) flag = 5;
}
if (flag2) {
if (a == 0) return 13;
this.patt[this.pattw][this.patts[this.pattw]++] = a;
if (this.patts[this.pattw] > JMLib.MMAX) return 8;
} else {
this.patt[this.pattw][0] = a;
if (a == 0) this.patts[this.pattw++] = 0;else this.patts[this.pattw++] = 1;
}
pos++;
this.balln += a;
}
if (this.pattw == 0) return 9;
this.balln = parseInt(this.balln / this.pattw);
if (this.balln > JMLib.BMAX) return 9;
return 0;
};
// fixme: this function won't work
// use similar function from validator instead
/*
JMLib.prototype.ctod = function(c) {
if (c >= '0' && c <= '9') return c - '0';
else if (c >= 'a' && c <= 'z') return c - 'a' + 10;
else if (c >= 'A' && c <= 'Z') return c - 'A' + 10;
return -1;
}*/
JMLib.prototype.ctod = function (s) {
var str_0 = new String("0");
var str_a = new String("a");
var str_A = new String("A");
if (s >= '0' && s <= '9') return s.charCodeAt(0) - str_0.charCodeAt(0);else if (s >= 'a' && s <= 'z') return s.charCodeAt(0) - str_a.charCodeAt(0) + 10;else if (s >= 'A' && s <= 'Z') return s.charCodeAt(0) - str_A.charCodeAt(0) + 10;else return -1;
};
JMLib.prototype.startJuggle = function () {
this.set_dpm();
if (this.set_ini(1) != 0) return;
this.xbitset();
// apply corrections
this.bm1 = 11 - parseInt(11 * this.dpm / JMLib.DW);
this.time_count = 0;
this.time_period = 0;
this.status = JMLib.ST_JUGGLE;
};
JMLib.prototype.stopJuggle = function () {
this.status = JMLib.ST_NONE;
};
JMLib.prototype.togglePause = function () {
if (this.status == JMLib.ST_JUGGLE) this.status = JMLib.ST_PAUSE;else if (this.status == JMLib.ST_PAUSE) this.status = JMLib.ST_JUGGLE;
};
JMLib.prototype.setPause = function (pauseOn) {
if (this.status != JMLib.ST_NONE) {
if (pauseOn) this.status = JMLib.ST_PAUSE;else this.status = JMLib.ST_JUGGLE;
}
};
JMLib.prototype.getStatus = function () {
return this.status;
};
// fixme: xpos function seems to be wrong
JMLib.prototype.fadd = function (x, k, t) {
return ((x + t) * JMLib.xpow(10, k) + .5) / JMLib.xpow(10, k);
};
JMLib.prototype.speedUp = function () {
this.cSpeed = JMLib.SPEED_MAX;
this.set_ini(0);
};
JMLib.prototype.speedDown = function () {
this.cSpeed = JMLib.SPEED_MIN;
this.set_ini(0);
};
JMLib.prototype.speedReset = function () {
this.cSpeed = JMLib.SPEED_DEF;
this.set_ini(0);
};
JMLib.prototype.setSpeed = function (s) {
this.cSpeed = s;
this.set_ini(0);
};
JMLib.prototype.speed = function () {
return this.cSpeed;
};
JMLib.prototype.doJuggle = function () {
var i,
tone = 0;
if (this.status == JMLib.ST_PAUSE || this.status == JMLib.ST_NONE) {
return 0;
}
this.time_count++;
if (this.time_count < this.aw) this.time_count = this.aw;
this.time_period = parseInt((this.time_count - this.aw) / this.tw);
this.time_period %= this.pattw;
//this.time_period = time_count % pattw;
for (i = 0; i < this.balln; i++) {
if (this.juggle(this.b[i]) && this.beep) tone = JMLib.max(tone, JMLib.xabs(this.b[i].bh));
}if (this.juggle(this.rhand) + this.juggle(this.lhand) > 0) {
//if (back_on==1) patt_print(1);
}
this.arm_line();
this.applyCorrections();
if (this.scalingMethod == JMLib.SCALING_METHOD_DYNAMIC) this.doCoordTransform();
return tone;
};
JMLib.prototype.xbitset = function () {
var i,
j = 0;
// data is used to create the hand bitmaps
var data = [0, 18, 0, 23, 17, 23, 20, 22, 22, 20, 23, 17, 23, 12, 18, 12, 18, 16, 16, 18, 0, 18, 12, 15, 23, 17, 99, 99];
// initialize the data array.
for (i = 0; data[i] < 99; i++) {
data[i] = parseInt((data[i] - 11) * this.dpm / JMLib.DW);
} // apply hand placement offsets
this.hand_x = data[i - 4] + 2;
this.hand_y = data[i - 3] + 2;
this.arm_x = data[i - 2];
this.arm_y = data[i - 1];
// calculate hand polygons
for (i = 0; data[i + 6] < 99; i += 2) {
if (j > 9) break;
this.handpoly_ex.rx[j] = 11 + data[i];
this.handpoly_ex.ry[j] = 10 + data[i + 1];
this.handpoly_ex.lx[j] = 12 - data[i];
this.handpoly_ex.ly[j] = 10 + data[i + 1];
j++;
}
for (i = 0; i <= 9; i++) {
this.handpoly.rx[i] = this.handpoly_ex.rx[i];
this.handpoly.ry[i] = this.handpoly_ex.ry[i];
this.handpoly.lx[i] = this.handpoly_ex.lx[i];
this.handpoly.ly[i] = this.handpoly_ex.ly[i];
}
};
JMLib.prototype.doStepcalc = function () {
var i;
var stp = 0; // position in steps array
var pos = 0; // position in string
// reset
for (i = 0; i < JMLib.LMAX; i++) {
this.steps[i] = -1;
}
// Synchronous pattern
if (this.syn) {
while (pos <= this.siteswap.length) {
if (this.siteswap.charAt(pos) == '(') {
this.steps[stp] = pos;
stp += 2;
while (this.siteswap.charAt(pos) != ')') {
pos++;
}
pos++;
} else if (pos == this.siteswap.length) {
this.steps[stp] = pos;
break;
} else {
this.error("Internal error");
return;
}
}
} else {
while (pos <= this.siteswap.length) {
if (this.siteswap.charAt(pos) == '(') {
this.error("Internal error");
return;
}
// Multiplex
else if (this.siteswap.charAt(pos) == '[') {
this.steps[stp++] = pos;
while (this.siteswap.charAt(pos) != ']') {
pos++;
}
pos++;
}
// Normal throw
else {
this.steps[stp++] = pos++;
}
}
}
};
module.exports = JMLib; | perjg/jugglemaster | src/jmlib-js/dist/jmlib.js | JavaScript | gpl-2.0 | 38,548 |
#include "read_string.h"
char *read_string(pid_t child, unsigned long addr)
{
char *val = malloc(4096);
int allocated = 4096;
int read = 0;
unsigned long tmp;
while (1)
{
if (read + sizeof tmp > allocated)
{
allocated *= 2;
val = realloc(val, allocated);
}
tmp = ptrace(PTRACE_PEEKDATA, child, addr + read);
if(errno != 0)
{
val[read] = 0;
break;
}
memcpy(val + read, &tmp, sizeof tmp);
if (memchr(&tmp, 0, sizeof tmp) != NULL)
break;
read += sizeof tmp;
}
return val;
}
| anwarshahas/Multi-Variant-Execution-Monitor | monitor/src/read_string.c | C | gpl-2.0 | 649 |
<?php
if(isset($_GET['error'])){
require 'includes/error.php';
return;
}
$orders = $_GET['orders'];
for ($i = 0; $i < $orders->count(); $i++) {
?>
<div class="tr notselected" id="<?php echo $orders[$i]->getValue('id')?>">
<span class="td select" id="<?php echo $orders[$i]->getValue('id')?>" title="Select"></span>
<span class="td w150" style="text-align:center"><?php echo $orders[$i]->getValue('name')?></span>
<span class="td w120"><?php echo $orders[$i]->getValue('plan')?></span>
<span class="td w80" style="text-align:center"><?php echo number_format($orders[$i]->getValue('amount'), 2)?></span>
<span class="td w80" style="text-align:center"><?php echo (30 * $orders[$i]->getValue('tenure'))?> Days</span>
<span class="td w80" style="text-align:center"><?php echo Date::convertFromMySqlDate($orders[$i]->getValue('expires'))?></span>
<?php
if($orders[$i]->getValue('status') == 0){
?><span class="td w80">Pending</span><?php
}
else if($orders[$i]->getValue('status') == 1){
?><span class="td w80">Disputed</span><?php
}
else if($orders[$i]->getValue('status') == 2){
?><span class="td w80">Failed</span><?php
}
?>
<span class="td w100" style="text-align:center"><?php echo $orders[$i]->getValue('method')?></span>
<span class="td w120" style="text-align:center"><?php echo $orders[$i]->getValue('gateway_ref')?></span>
<span class="td w120" style="text-align:center"><?php echo Date::convertFromMySqlDate($orders[$i]->getValue('creation_date')) ?></span>
<span class="td w80" style="text-align:center"><a href="<?php echo CONTEXT_PATH?>/backend/prepaid/pending-orders?action=accept&id=<?php echo $orders[$i]->getValue('id')?>">Accept</a></span>
</div>
<?php
} | anytimestream/genesisville | views/backend/prepaid/pending-order-reload.php | PHP | gpl-2.0 | 1,818 |
Let's assume that you have growing file on your file system. For example, dumping a database with mysqldump. You want to watch its size with a duration. How can we do?
When you want to check file size at a moment, you execute something like this:
```
ls -lh db_dump.sql
```
and it prints out something like this:
```
-rw-r--r-- 1 root root 452M Oca 4 22:14 db_dump.sql
```
We will use **awk** to get file size from output. Why is AWK? Because it is an excellent filter and report writer. Many UNIX utilities generates rows and columns of information. AWK is an excellent tool for processing these rows and columns, and is easier to use.
When we pipe this output to **awk**,it splits the record delimited by whitespace character by default and stores it in the $n variables. If the line has 4 words, it will be stored in $1, $2, $3 and $4. $0 represents whole line.
Final version of our command will be this:
```
ls -lh db_dump.sql | awk '{print $5}'
```
When you execute, it will only print file size:
```
452M
```
Then we will pass this command as a parameter to **watch** command. It executes a program periodically and shows output fullscreen.
```
watch -n 5 "ls -lh db_dump.sql | awk '{print \$5}'"
```
Above command will show you file size every 5 seconds.
Happy hacking! | csonuryilmaz/notes | how_to/watch_growing_file_size_(en).md | Markdown | gpl-2.0 | 1,292 |
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width" />
<title>Big Crazy Title</title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php wp_head(); ?>
</head>
<body>
<div class="site-branding">
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
</div>
<div class="screen-reader-text skip-link"><a href="#content" title="<?php esc_attr_e( 'Skip to content', 'bjorn_sthlm' ); ?>"><?php _e( 'Skip to content', 'bjorn_sthlm' ); ?></a></div>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
<div id="main" class="site-main">
| murum/wordpress_bootstrap | wp-content/themes/starter/header.php | PHP | gpl-2.0 | 925 |
#ifdef WIN32
#include <sys_win.cpp>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GL/glfw3.h>
#elif __APPLE__
#include <sys_mac.cpp>
#include <OpenGL/gl3.h>
#include <GLFW/glfw3.h>
#endif
#include <cstdio>
#include <cstdint>
#include <ctime>
#include <gl.hpp>
#include <asset.hpp>
#include <math.hpp>
#include <nova.hpp>
#include <asset.cpp>
#include <math.cpp>
#include <nova.cpp>
void error_callback(int e, char const * desc) {
#ifdef WIN32
if(e == GLFW_VERSION_UNAVAILABLE) {
//TODO: Get OpenGL version
MessageBoxA(0, "Application requires OpenGL 3.3 or higher.", "Nova", MB_OK | MB_ICONERROR | MB_TOPMOST);
}
else
#endif
{
std::printf("ERROR: %d, %s\n", e, desc);
}
}
void key_callback(GLFWwindow * window, int key, int scan_code, int action, int mods) {
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
float get_current_time() {
return static_cast<float>(glfwGetTime());
}
math::Vec2 get_mouse_pos(GLFWwindow * window) {
double raw_mouse_x, raw_mouse_y;
glfwGetCursorPos(window, &raw_mouse_x, &raw_mouse_y);
return math::vec2((float)raw_mouse_x, (float)raw_mouse_y);
}
int main() {
glfwSetErrorCallback(error_callback);
if(!glfwInit()) {
return 0;
}
bool enable_full_screen = true;
bool enable_v_sync = false;
glfwWindowHint(GLFW_SAMPLES, 8);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWvidmode const * video_mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
uint32_t monitor_width = video_mode->width;
uint32_t monitor_height = video_mode->height;
uint32_t window_width = enable_full_screen ? monitor_width : 960;
uint32_t window_height = enable_full_screen ? monitor_height : 540;
GLFWwindow * window = glfwCreateWindow(window_width, window_height, "Nova", enable_full_screen ? glfwGetPrimaryMonitor() : 0, 0);
if(!window) {
glfwTerminate();
return 0;
}
// uint32_t window_frame_size_lft;
// uint32_t window_frame_size_top;
// uint32_t window_frame_size_rgt;
// uint32_t window_frame_size_bot;
// glfwGetWindowFrameSize(window, &window_frame_size_lft, &window_frame_size_top, &window_frame_size_rgt, &window_frame_size_bot);
// glfwSetWindowPos(window, window_frame_size_lft, window_frame_size_rgt);
glfwSetKeyCallback(window, key_callback);
glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, GL_TRUE);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
glfwMakeContextCurrent(window);
#ifdef WIN32
glewExperimental = true;
if(glewInit() != GLEW_OK) {
return 0;
}
#endif
if(enable_v_sync) {
glfwSwapInterval(1);
}
GLuint vertex_array_id;
glGenVertexArrays(1, &vertex_array_id);
glBindVertexArray(vertex_array_id);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
nova::GameState game_state = {};
game_state.back_buffer_width = window_width;
game_state.back_buffer_height = window_height;
game_state.key_space_pressed = false;
game_state.key_rgt_mouse_pressed = false;
game_state.key_lft_mouse_down = false;
game_state.key_rgt_mouse_down = false;
game_state.mouse_pos = get_mouse_pos(window);
float frame_time = get_current_time();
bool last_key_space = false;
bool last_key_rgt_mouse = false;
while(!glfwWindowShouldClose(window)) {
float last_frame_time = frame_time;
frame_time = get_current_time();
game_state.delta_time = frame_time - last_frame_time;
game_state.total_time += game_state.delta_time;
glfwPollEvents();
math::Vec2 mouse_pos = get_mouse_pos(window);
game_state.mouse_delta = mouse_pos - game_state.mouse_pos;
game_state.mouse_pos = mouse_pos;
bool key_space = glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS;
game_state.key_space_pressed = !last_key_space && key_space;
last_key_space = key_space;
game_state.key_lft_mouse_down = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
//TODO: Only use one key!!
bool key_rgt_mouse = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;
game_state.key_rgt_mouse_pressed = (!last_key_rgt_mouse && key_rgt_mouse) || game_state.key_space_pressed;
game_state.key_rgt_mouse_down = (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) || key_space;
last_key_rgt_mouse = key_rgt_mouse;
nova::tick(&game_state);
char txt_buffer[256] = {};
std::sprintf(txt_buffer, "Nova %.3fms", game_state.delta_time * 1000.0f);
glfwSetWindowTitle(window, txt_buffer);
glfwSwapBuffers(window);
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
} | PhilCK/nova | src/main.cpp | C++ | gpl-2.0 | 4,647 |
/*
* V(R) I/O Scheduler
*
* Copyright (C) 2007 Aaron Carroll <aaronc@gelato.unsw.edu.au>
*
*
* The algorithm:
*
* The next request is decided based on its distance from the last
* request, with a multiplicative penalty of `rev_penalty' applied
* for reversing the head direction. A rev_penalty of 1 means SSTF
* behaviour. As this variable is increased, the algorithm approaches
* pure SCAN. Setting rev_penalty to 0 forces SCAN.
*
* Async and synch requests are not treated seperately. Instead we
* rely on deadlines to ensure fairness.
*
*/
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/rbtree.h>
#include <linux/version.h>
#include <asm/div64.h>
enum vr_data_dir {
ASYNC,
SYNC,
};
enum vr_head_dir {
FORWARD,
BACKWARD,
};
static const int sync_expire = HZ / 2; /* max time before a sync is submitted. */
static const int async_expire = 5 * HZ; /* ditto for async, these limits are SOFT! */
static const int fifo_batch = 1;
static const int rev_penalty = 1; /* penalty for reversing head direction */
struct vr_data {
struct rb_root sort_list;
struct list_head fifo_list[2];
struct request *next_rq;
struct request *prev_rq;
unsigned int nbatched;
sector_t last_sector; /* head position */
int head_dir;
/* tunables */
int fifo_expire[2];
int fifo_batch;
int rev_penalty;
};
static void vr_move_request(struct vr_data *, struct request *);
static inline struct vr_data *
vr_get_data(struct request_queue *q)
{
return q->elevator->elevator_data;
}
static void
vr_add_rq_rb(struct vr_data *vd, struct request *rq)
{
elv_rb_add(&vd->sort_list, rq);
if (blk_rq_pos(rq) >= vd->last_sector) {
if (!vd->next_rq || blk_rq_pos(vd->next_rq) > blk_rq_pos(rq))
vd->next_rq = rq;
}
else {
if (!vd->prev_rq || blk_rq_pos(vd->prev_rq) < blk_rq_pos(rq))
vd->prev_rq = rq;
}
BUG_ON(vd->next_rq && vd->next_rq == vd->prev_rq);
BUG_ON(vd->next_rq && vd->prev_rq && blk_rq_pos(vd->next_rq) < blk_rq_pos(vd->prev_rq));
}
static void
vr_del_rq_rb(struct vr_data *vd, struct request *rq)
{
/*
* We might be deleting our cached next request.
* If so, find its sucessor.
*/
if (vd->next_rq == rq)
vd->next_rq = elv_rb_latter_request(NULL, rq);
else if (vd->prev_rq == rq)
vd->prev_rq = elv_rb_former_request(NULL, rq);
BUG_ON(vd->next_rq && vd->next_rq == vd->prev_rq);
BUG_ON(vd->next_rq && vd->prev_rq && blk_rq_pos(vd->next_rq) < blk_rq_pos(vd->prev_rq));
elv_rb_del(&vd->sort_list, rq);
}
/*
* add rq to rbtree and fifo
*/
static void
vr_add_request(struct request_queue *q, struct request *rq)
{
struct vr_data *vd = vr_get_data(q);
const int dir = rq_is_sync(rq);
vr_add_rq_rb(vd, rq);
if (vd->fifo_expire[dir]) {
rq_set_fifo_time(rq, jiffies + vd->fifo_expire[dir]);
list_add_tail(&rq->queuelist, &vd->fifo_list[dir]);
}
}
/*
* remove rq from rbtree and fifo.
*/
static void
vr_remove_request(struct request_queue *q, struct request *rq)
{
struct vr_data *vd = vr_get_data(q);
rq_fifo_clear(rq);
vr_del_rq_rb(vd, rq);
}
static int
vr_merge(struct request_queue *q, struct request **rqp, struct bio *bio)
{
sector_t sector = bio->bi_sector + bio_sectors(bio);
struct vr_data *vd = vr_get_data(q);
struct request *rq = elv_rb_find(&vd->sort_list, sector);
if (rq && elv_rq_merge_ok(rq, bio)) {
*rqp = rq;
return ELEVATOR_FRONT_MERGE;
}
return ELEVATOR_NO_MERGE;
}
static void
vr_merged_request(struct request_queue *q, struct request *req, int type)
{
struct vr_data *vd = vr_get_data(q);
/*
* if the merge was a front merge, we need to reposition request
*/
if (type == ELEVATOR_FRONT_MERGE) {
vr_del_rq_rb(vd, req);
vr_add_rq_rb(vd, req);
}
}
static void
vr_merged_requests(struct request_queue *q, struct request *rq,
struct request *next)
{
/*
* if next expires before rq, assign its expire time to rq
* and move into next position (next will be deleted) in fifo
*/
if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist)) {
if (time_before(rq_fifo_time(next), rq_fifo_time(rq))) {
list_move(&rq->queuelist, &next->queuelist);
rq_set_fifo_time(rq, rq_fifo_time(next));
}
}
vr_remove_request(q, next);
}
/*
* move an entry to dispatch queue
*/
static void
vr_move_request(struct vr_data *vd, struct request *rq)
{
struct request_queue *q = rq->q;
if (blk_rq_pos(rq) > vd->last_sector)
vd->head_dir = FORWARD;
else
vd->head_dir = BACKWARD;
vd->last_sector = blk_rq_pos(rq);
vd->next_rq = elv_rb_latter_request(NULL, rq);
vd->prev_rq = elv_rb_former_request(NULL, rq);
BUG_ON(vd->next_rq && vd->next_rq == vd->prev_rq);
vr_remove_request(q, rq);
elv_dispatch_add_tail(q, rq);
vd->nbatched++;
}
/*
* get the first expired request in direction ddir
*/
static struct request *
vr_expired_request(struct vr_data *vd, int ddir)
{
struct request *rq;
if (list_empty(&vd->fifo_list[ddir]))
return NULL;
rq = rq_entry_fifo(vd->fifo_list[ddir].next);
if (time_after(jiffies, rq_fifo_time(rq)))
return rq;
return NULL;
}
/*
* Returns the oldest expired request
*/
static struct request *
vr_check_fifo(struct vr_data *vd)
{
struct request *rq_sync = vr_expired_request(vd, SYNC);
struct request *rq_async = vr_expired_request(vd, ASYNC);
if (rq_async && rq_sync) {
if (time_after(rq_fifo_time(rq_async), rq_fifo_time(rq_sync)))
return rq_sync;
}
else if (rq_sync)
return rq_sync;
return rq_async;
}
/*
* Return the request with the lowest penalty
*/
static struct request *
vr_choose_request(struct vr_data *vd)
{
int penalty = (vd->rev_penalty) ? : INT_MAX;
struct request *next = vd->next_rq;
struct request *prev = vd->prev_rq;
sector_t next_pen, prev_pen;
BUG_ON(prev && prev == next);
if (!prev)
return next;
else if (!next)
return prev;
/* At this point both prev and next are defined and distinct */
next_pen = blk_rq_pos(next) - vd->last_sector;
prev_pen = vd->last_sector - blk_rq_pos(prev);
if (vd->head_dir == FORWARD)
next_pen = do_div(next_pen, penalty);
else
prev_pen = do_div(prev_pen, penalty);
if (next_pen <= prev_pen)
return next;
return prev;
}
static int
vr_dispatch_requests(struct request_queue *q, int force)
{
struct vr_data *vd = vr_get_data(q);
struct request *rq = NULL;
/* Check for and issue expired requests */
if (vd->nbatched > vd->fifo_batch) {
vd->nbatched = 0;
rq = vr_check_fifo(vd);
}
if (!rq) {
rq = vr_choose_request(vd);
if (!rq)
return 0;
}
vr_move_request(vd, rq);
return 1;
}
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,38)
static int
vr_queue_empty(struct request_queue *q)
{
struct vr_data *vd = vr_get_data(q);
return RB_EMPTY_ROOT(&vd->sort_list);
}
#endif
static void
vr_exit_queue(struct elevator_queue *e)
{
struct vr_data *vd = e->elevator_data;
BUG_ON(!RB_EMPTY_ROOT(&vd->sort_list));
kfree(vd);
}
/*
* initialize elevator private data (vr_data).
*/
static void *vr_init_queue(struct request_queue *q)
{
struct vr_data *vd;
vd = kmalloc_node(sizeof(*vd), GFP_KERNEL | __GFP_ZERO, q->node);
if (!vd)
return NULL;
INIT_LIST_HEAD(&vd->fifo_list[SYNC]);
INIT_LIST_HEAD(&vd->fifo_list[ASYNC]);
vd->sort_list = RB_ROOT;
vd->fifo_expire[SYNC] = sync_expire;
vd->fifo_expire[ASYNC] = async_expire;
vd->fifo_batch = fifo_batch;
vd->rev_penalty = rev_penalty;
return vd;
}
/*
* sysfs parts below
*/
static ssize_t
vr_var_show(int var, char *page)
{
return sprintf(page, "%d\n", var);
}
static ssize_t
vr_var_store(int *var, const char *page, size_t count)
{
*var = simple_strtol(page, NULL, 10);
return count;
}
#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
static ssize_t __FUNC(struct elevator_queue *e, char *page) \
{ \
struct vr_data *vd = e->elevator_data; \
int __data = __VAR; \
if (__CONV) \
__data = jiffies_to_msecs(__data); \
return vr_var_show(__data, (page)); \
}
SHOW_FUNCTION(vr_sync_expire_show, vd->fifo_expire[SYNC], 1);
SHOW_FUNCTION(vr_async_expire_show, vd->fifo_expire[ASYNC], 1);
SHOW_FUNCTION(vr_fifo_batch_show, vd->fifo_batch, 0);
SHOW_FUNCTION(vr_rev_penalty_show, vd->rev_penalty, 0);
#undef SHOW_FUNCTION
#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
{ \
struct vr_data *vd = e->elevator_data; \
int __data; \
int ret = vr_var_store(&__data, (page), count); \
if (__data < (MIN)) \
__data = (MIN); \
else if (__data > (MAX)) \
__data = (MAX); \
if (__CONV) \
*(__PTR) = msecs_to_jiffies(__data); \
else \
*(__PTR) = __data; \
return ret; \
}
STORE_FUNCTION(vr_sync_expire_store, &vd->fifo_expire[SYNC], 0, INT_MAX, 1);
STORE_FUNCTION(vr_async_expire_store, &vd->fifo_expire[ASYNC], 0, INT_MAX, 1);
STORE_FUNCTION(vr_fifo_batch_store, &vd->fifo_batch, 0, INT_MAX, 0);
STORE_FUNCTION(vr_rev_penalty_store, &vd->rev_penalty, 0, INT_MAX, 0);
#undef STORE_FUNCTION
#define DD_ATTR(name) \
__ATTR(name, S_IRUGO|S_IWUSR, vr_##name##_show, \
vr_##name##_store)
static struct elv_fs_entry vr_attrs[] = {
DD_ATTR(sync_expire),
DD_ATTR(async_expire),
DD_ATTR(fifo_batch),
DD_ATTR(rev_penalty),
__ATTR_NULL
};
static struct elevator_type iosched_vr = {
.ops = {
.elevator_merge_fn = vr_merge,
.elevator_merged_fn = vr_merged_request,
.elevator_merge_req_fn = vr_merged_requests,
.elevator_dispatch_fn = vr_dispatch_requests,
.elevator_add_req_fn = vr_add_request,
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,38)
.elevator_queue_empty_fn = vr_queue_empty,
#endif
.elevator_former_req_fn = elv_rb_former_request,
.elevator_latter_req_fn = elv_rb_latter_request,
.elevator_init_fn = vr_init_queue,
.elevator_exit_fn = vr_exit_queue,
},
.elevator_attrs = vr_attrs,
.elevator_name = "vr",
.elevator_owner = THIS_MODULE,
};
static int __init vr_init(void)
{
elv_register(&iosched_vr);
return 0;
}
static void __exit vr_exit(void)
{
elv_unregister(&iosched_vr);
}
module_init(vr_init);
module_exit(vr_exit);
MODULE_AUTHOR("Aaron Carroll");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("V(R) IO scheduler");
| AstroProfundis/android_kernel_samsung_sc03e | block/vr-iosched.c | C | gpl-2.0 | 9,966 |
#include <ctype.h>
static const char base64digits[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define BAD -1
static const char base64val[] = {
BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD,
BAD,BAD,BAD,BAD, BAD,BAD,BAD,BAD, BAD,BAD,BAD, 62, BAD,BAD,BAD, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,BAD,BAD, BAD,BAD,BAD,BAD,
BAD, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,BAD, BAD,BAD,BAD,BAD,
BAD, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,BAD, BAD,BAD,BAD,BAD
};
#define DECODE64(c) (isascii(c) ? base64val[c] : BAD)
void to64frombits(unsigned char *out, const unsigned char *in, int inlen)
/* raw bytes in quasi-big-endian order to base 64 string (NUL-terminated) */
{
for (; inlen >= 3; inlen -= 3) {
*out++ = base64digits[in[0] >> 2];
*out++ = base64digits[((in[0] << 4) & 0x30) | (in[1] >> 4)];
*out++ = base64digits[((in[1] << 2) & 0x3c) | (in[2] >> 6)];
*out++ = base64digits[in[2] & 0x3f];
in += 3;
}
if (inlen > 0) {
unsigned char fragment;
*out++ = base64digits[in[0] >> 2];
fragment = (in[0] << 4) & 0x30;
if (inlen > 1)
fragment |= in[1] >> 4;
*out++ = base64digits[fragment];
*out++ = (inlen < 2) ? '=' : base64digits[(in[1] << 2) & 0x3c];
*out++ = '=';
}
*out = '\0';
}
int from64tobits(char *out, const char *in)
/* base 64 to raw bytes in quasi-big-endian order, returning count of bytes */
{
int len = 0;
register unsigned char digit1, digit2, digit3, digit4;
if (in[0] == '+' && in[1] == ' ')
in += 2;
if (*in == '\r')
return(0);
do {
digit1 = in[0];
if (DECODE64(digit1) == BAD)
return(-1);
digit2 = in[1];
if (DECODE64(digit2) == BAD)
return(-1);
digit3 = in[2];
if (digit3 != '=' && DECODE64(digit3) == BAD)
return(-1);
digit4 = in[3];
if (digit4 != '=' && DECODE64(digit4) == BAD)
return(-1);
in += 4;
*out++ = (DECODE64(digit1) << 2) | (DECODE64(digit2) >> 4);
++len;
if (digit3 != '=') {
*out++ = ((DECODE64(digit2) << 4) & 0xf0) | (DECODE64(digit3) >> 2);
++len;
if (digit4 != '=') {
*out++ = ((DECODE64(digit3) << 6) & 0xc0) | DECODE64(digit4);
++len;
}
}
} while
(*in && *in != '\r' && digit4 != '=');
return (len);
}
/* base64.c ends here */
| fushengqian/kbs | libsystem/base64.c | C | gpl-2.0 | 2,866 |
function triggerEventAfterBootstrap(checkout) {
jQuery(document).trigger("wpshopify_bootstrap_after", [checkout]);
}
function triggerEventBeforeBootstrap() {
jQuery(document).trigger("wpshopify_bootstrap_before");
}
function triggerEventAfterAddToCart(product, checkout) {
jQuery(document).trigger("wpshopify_add_to_cart_after", [product, checkout]);
}
function triggerEventBeforeAddToCart(product) {
jQuery(document).trigger("wpshopify_add_to_cart_before", [product]);
}
export {
triggerEventAfterBootstrap,
triggerEventBeforeBootstrap,
triggerEventAfterAddToCart,
triggerEventBeforeAddToCart
}
| arobbins/wp-shopify | public/js/app/utils/utils-triggers.js | JavaScript | gpl-2.0 | 619 |
#!/usr/bin/env python
import subprocess
import os
class MakeException(Exception):
pass
def swapExt(path, current, replacement):
path, ext = os.path.splitext(path)
if ext == current:
path += replacement
return path
else:
raise MakeException(
"swapExt: expected file name ending in %s, got file name ending in %s" % \
(current, replacement))
headerFiles = [
'benc.h',
'bencode.h',
]
codeFiles = [
'benc_int.c',
'benc_bstr.c',
'benc_list.c',
'benc_dict.c',
'bencode.c',
'bcopy.c',
]
cflags = ['-g']
programFile = 'bcopy'
def gcc(*packedArgs):
args = []
for arg in packedArgs:
if isinstance(arg, list):
args += arg
elif isinstance(arg, tuple):
args += list(arg)
else:
args.append(arg)
subprocess.check_call(['gcc'] + args)
def compile(codeFile, cflags=[]):
objectFile = swapExt(codeFile, '.c', '.o')
gcc(cflags, '-c', ('-o', objectFile), codeFile)
return objectFile
def link(programFile, objectFiles, cflags=[]):
gcc(cflags, ('-o', programFile), objectFiles)
if __name__ == '__main__':
objectFiles = [compile(codeFile, cflags) for codeFile in codeFiles]
link(programFile, objectFiles, cflags)
| HarryR/ffff-dnsp2p | libbenc/make.py | Python | gpl-2.0 | 1,298 |
#ifndef SMBASE_EVENTQUEUE_H
#define SMBASE_EVENTQUEUE_H
#include <queue>
#include <QMutex>
#include <QWaitCondition>
#include "Event.h"
namespace __smbase{
class EventQueue{
private:
std::queue<Event *> myQueue;
const unsigned int MAX_EVENTS;
QMutex *mutex;
QWaitCondition *full;
QWaitCondition *empty;
public:
EventQueue();
~EventQueue();
void put(Event *);
Event* get();
};
}
#endif
| Pikecillo/genna | genna/smbase/smbaseCpp/__smbase/EventQueue.h | C | gpl-2.0 | 434 |
<html lang="en">
<head>
<title>SH-Addressing - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="SH-Syntax.html#SH-Syntax" title="SH Syntax">
<link rel="prev" href="SH_002dRegs.html#SH_002dRegs" title="SH-Regs">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="SH-Addressing"></a>
<a name="SH_002dAddressing"></a>
Previous: <a rel="previous" accesskey="p" href="SH_002dRegs.html#SH_002dRegs">SH-Regs</a>,
Up: <a rel="up" accesskey="u" href="SH-Syntax.html#SH-Syntax">SH Syntax</a>
<hr>
</div>
<h5 class="subsubsection">9.40.2.3 Addressing Modes</h5>
<p><a name="index-addressing-modes_002c-SH-1948"></a><a name="index-SH-addressing-modes-1949"></a><code>as</code> understands the following addressing modes for the SH.
<code>R</code><var>n</var> in the following refers to any of the numbered
registers, but <em>not</em> the control registers.
<dl>
<dt><code>R</code><var>n</var><dd>Register direct
<br><dt><code>@R</code><var>n</var><dd>Register indirect
<br><dt><code>@-R</code><var>n</var><dd>Register indirect with pre-decrement
<br><dt><code>@R</code><var>n</var><code>+</code><dd>Register indirect with post-increment
<br><dt><code>@(</code><var>disp</var><code>, R</code><var>n</var><code>)</code><dd>Register indirect with displacement
<br><dt><code>@(R0, R</code><var>n</var><code>)</code><dd>Register indexed
<br><dt><code>@(</code><var>disp</var><code>, GBR)</code><dd><code>GBR</code> offset
<br><dt><code>@(R0, GBR)</code><dd>GBR indexed
<br><dt><var>addr</var><dt><code>@(</code><var>disp</var><code>, PC)</code><dd>PC relative address (for branch or for addressing memory). The
<code>as</code> implementation allows you to use the simpler form
<var>addr</var> anywhere a PC relative address is called for; the alternate
form is supported for compatibility with other assemblers.
<br><dt><code>#</code><var>imm</var><dd>Immediate data
</dl>
</body></html>
| jocelynmass/nrf51 | toolchain/arm_cm0_deprecated/share/doc/gcc-arm-none-eabi/html/as.html/SH_002dAddressing.html | HTML | gpl-2.0 | 3,266 |
<html lang="en">
<head>
<title>Config Fragments - GNU Compiler Collection (GCC) Internals</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="GNU Compiler Collection (GCC) Internals">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Configuration.html#Configuration" title="Configuration">
<link rel="next" href="System-Config.html#System-Config" title="System Config">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
Copyright (C) 1988-2017 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being ``Funding Free Software'', the Front-Cover
Texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
``GNU Free Documentation License''.
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="Config-Fragments"></a>
Next: <a rel="next" accesskey="n" href="System-Config.html#System-Config">System Config</a>,
Up: <a rel="up" accesskey="u" href="Configuration.html#Configuration">Configuration</a>
<hr>
</div>
<h5 class="subsubsection">6.3.2.1 Scripts Used by <samp><span class="file">configure</span></samp></h5>
<p><samp><span class="file">configure</span></samp> uses some other scripts to help in its work:
<ul>
<li>The standard GNU <samp><span class="file">config.sub</span></samp> and <samp><span class="file">config.guess</span></samp>
files, kept in the top level directory, are used.
<li>The file <samp><span class="file">config.gcc</span></samp> is used to handle configuration
specific to the particular target machine. The file
<samp><span class="file">config.build</span></samp> is used to handle configuration specific to the
particular build machine. The file <samp><span class="file">config.host</span></samp> is used to handle
configuration specific to the particular host machine. (In general,
these should only be used for features that cannot reasonably be tested in
Autoconf feature tests.)
See <a href="System-Config.html#System-Config">The <samp><span class="file">config.build</span></samp>; <samp><span class="file">config.host</span></samp>; and <samp><span class="file">config.gcc</span></samp> Files</a>, for details of the contents of these files.
<li>Each language subdirectory has a file
<samp><var>language</var><span class="file">/config-lang.in</span></samp> that is used for
front-end-specific configuration. See <a href="Front-End-Config.html#Front-End-Config">The Front End <samp><span class="file">config-lang.in</span></samp> File</a>, for details of this file.
<li>A helper script <samp><span class="file">configure.frag</span></samp> is used as part of
creating the output of <samp><span class="file">configure</span></samp>.
</ul>
</body></html>
| jocelynmass/nrf51 | toolchain/arm_cm0/share/doc/gcc-arm-none-eabi/html/gccint/Config-Fragments.html | HTML | gpl-2.0 | 3,892 |
// BlogBridge -- RSS feed reader, manager, and web based service
// Copyright (C) 2002-2006 by R. Pito Salas
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 59 Temple Place,
// Suite 330, Boston, MA 02111-1307 USA
//
// Contact: R. Pito Salas
// mailto:pitosalas@users.sourceforge.net
// More information: about BlogBridge
// http://www.blogbridge.com
// http://sourceforge.net/projects/blogbridge
//
// $Id: LAFTheme.java,v 1.13 2008/02/28 15:59:52 spyromus Exp $
//
package com.salas.bb.views.themes;
import javax.swing.*;
import java.awt.*;
/**
* Theme which is completely based on current LAF.
*/
public class LAFTheme extends AbstractTheme
{
private static final String NAME = "LAF";
private static final String TITLE = "Look And Feel";
private static final JLabel LABEL = new JLabel();
private static final JList LIST = new JList();
/**
* Creates default LAF theme.
*/
public LAFTheme()
{
super(NAME, TITLE);
}
/**
* Returns color defined by the theme.
*
* @param key the key.
*
* @return color or <code>NULL</code> if color isn't defined by this theme.
*/
public Color getColor(ThemeKey.Color key)
{
Color color = null;
if ((ThemeKey.Color.ARTICLE_DATE_SEL_FG == key) ||
(ThemeKey.Color.ARTICLE_DATE_UNSEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TEXT_SEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TEXT_UNSEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TITLE_SEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TITLE_UNSEL_FG == key) ||
(ThemeKey.Color.ARTICLEGROUP_FG == key))
{
color = UIManager.getColor("Label.foreground");
} else if (ThemeKey.Color.ARTICLELIST_FEEDNAME_FG == key)
{
color = UIManager.getColor("SimpleInternalFrame.activeTitleForeground");
if (color == null) color = UIManager.getColor("InternalFrame.activeTitleForeground");
if (color == null) color = UIManager.getColor("Label.foreground");
} else if ((ThemeKey.Color.ARTICLE_SEL_BG == key) ||
(ThemeKey.Color.FEEDSLIST_SEL_BG == key))
{
color = LIST.getSelectionBackground();
} else if ((ThemeKey.Color.ARTICLE_UNSEL_BG == key) ||
(ThemeKey.Color.ARTICLEGROUP_BG == key) ||
(ThemeKey.Color.ARTICLELIST_BG == key) ||
(ThemeKey.Color.FEEDSLIST_BG == key) ||
(ThemeKey.Color.FEEDSLIST_ALT_BG == key))
{
color = LIST.getBackground();
} else if ((ThemeKey.Color.BLOGLINK_DISC_BG == key) ||
(ThemeKey.Color.BLOGLINK_UNDISC_BG == key))
{
// TODO change this to more appropriate value
color = LIST.getSelectionBackground();
} else if (ThemeKey.Color.FEEDSLIST_FG == key)
{
color = LIST.getForeground();
} else if (ThemeKey.Color.FEEDSLIST_SEL_FG == key)
{
color = LIST.getSelectionForeground();
}
return color;
}
/**
* Returns font defined by the theme.
*
* @param key the key.
*
* @return font or <code>NULL</code> if font isn't defined by this theme.
*/
public Font getFont(ThemeKey.Font key)
{
Font font = null;
if ((ThemeKey.Font.ARTICLE_TEXT == key) ||
(ThemeKey.Font.ARTICLE_TITLE == key) ||
(ThemeKey.Font.ARTICLE_DATE == key) ||
(ThemeKey.Font.ARTICLEGROUP == key) ||
(ThemeKey.Font.ARTICLELIST_FEEDNAME == key) ||
(ThemeKey.Font.MAIN == key))
{
font = LABEL.getFont();
}
return font;
}
/**
* Returns the delta to be applied to the size of the main font to get the font for the given
* key.
*
* @param key the key.
*
* @return the delta.
*/
public int getFontSizeDelta(ThemeKey.Font key)
{
return 0;
}
}
| pitosalas/blogbridge | src/com/salas/bb/views/themes/LAFTheme.java | Java | gpl-2.0 | 4,729 |
// This file is part of the uSTL library, an STL implementation.
//
// Copyright (c) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
#pragma once
#include "uvector.h"
#include "uctralgo.h"
namespace ustl {
/// \class list ulist.h ustl.h
/// \ingroup Sequences
///
/// \brief Linked list, defined as an alias to vector.
///
template <typename T>
class list : public vector<T> {
public:
typedef typename vector<T>::size_type size_type;
typedef typename vector<T>::iterator iterator;
typedef typename vector<T>::const_iterator const_iterator;
typedef typename vector<T>::reference reference;
typedef typename vector<T>::const_reference const_reference;
public:
inline list (void) : vector<T> () {}
inline explicit list (size_type n) : vector<T> (n) {}
inline list (size_type n, const T& v) : vector<T> (n, v) {}
inline list (const list<T>& v) : vector<T> (v) {}
inline list (const_iterator i1, const_iterator i2) : vector<T> (i1, i2) {}
inline size_type size (void) const { return vector<T>::size(); }
inline iterator begin (void) { return vector<T>::begin(); }
inline const_iterator begin (void) const { return vector<T>::begin(); }
inline iterator end (void) { return vector<T>::end(); }
inline const_iterator end (void) const { return vector<T>::end(); }
inline void push_front (const T& v) { this->insert (begin(), v); }
inline void pop_front (void) { this->erase (begin()); }
inline const_reference front (void) const { return *begin(); }
inline reference front (void) { return *begin(); }
inline void remove (const T& v) { ::ustl::remove (*this, v); }
template <typename Predicate>
inline void remove_if (Predicate p) { ::ustl::remove_if (*this, p); }
inline void reverse (void) { ::ustl::reverse (*this); }
inline void unique (void) { ::ustl::unique (*this); }
inline void sort (void) { ::ustl::sort (*this); }
void merge (list<T>& l);
void splice (iterator ip, list<T>& l, iterator first = nullptr, iterator last = nullptr);
#if HAVE_CPP11
inline list (list&& v) : vector<T> (move(v)) {}
inline list (std::initializer_list<T> v) : vector<T>(v) {}
inline list& operator= (list&& v) { vector<T>::operator= (move(v)); return *this; }
template <typename... Args>
inline void emplace_front (Args&&... args) { vector<T>::emplace (begin(), forward<Args>(args)...); }
inline void push_front (T&& v) { emplace_front (move(v)); }
#endif
};
/// Merges the contents with \p l. Assumes both lists are sorted.
template <typename T>
void list<T>::merge (list& l)
{
insert_space (begin(), l.size());
::ustl::merge (iat(l.size()), end(), l.begin(), l.end(), begin());
}
/// Moves the range [first, last) from \p l to this list at \p ip.
template <typename T>
void list<T>::splice (iterator ip, list<T>& l, iterator first, iterator last)
{
if (!first)
first = l.begin();
if (!last)
last = l.end();
insert (ip, first, last);
l.erase (first, last);
}
#define deque list ///< list has all the functionality provided by deque
} // namespace ustl
| SirBirne/PearOS | common/include/ustl/ulist.h | C | gpl-2.0 | 3,329 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CRAN - Package plotmo</title>
<link rel="stylesheet" type="text/css" href="../../CRAN_web.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
table td { vertical-align: top; }
</style>
</head>
<body>
<h2>plotmo: Plot a Model's Response and Residuals</h2>
<p>Plot model surfaces for a wide variety of models
using partial dependence plots and other techniques.
Also plot model residuals and other information on the model.</p>
<table summary="Package plotmo summary">
<tr>
<td>Version:</td>
<td>3.3.2</td>
</tr>
<tr>
<td>Depends:</td>
<td><a href="../plotrix/index.html">plotrix</a>, <a href="../TeachingDemos/index.html">TeachingDemos</a></td>
</tr>
<tr>
<td>Suggests:</td>
<td><a href="../C50/index.html">C50</a> (≥ 0.1.0-24), <a href="../earth/index.html">earth</a> (≥ 4.4.6), <a href="../gbm/index.html">gbm</a> (≥ 2.1.1), <a href="../glmnet/index.html">glmnet</a> (≥ 2.0.5), <a href="../MASS/index.html">MASS</a> (≥ 7.3-45), <a href="../neuralnet/index.html">neuralnet</a> (≥ 1.33), <a href="../rpart/index.html">rpart</a> (≥
4.1-10), <a href="../rpart.plot/index.html">rpart.plot</a> (≥ 2.0.1)</td>
</tr>
<tr>
<td>Published:</td>
<td>2016-12-02</td>
</tr>
<tr>
<td>Author:</td>
<td>Stephen Milborrow</td>
</tr>
<tr>
<td>Maintainer:</td>
<td>Stephen Milborrow <milbo at sonic.net></td>
</tr>
<tr>
<td>License:</td>
<td><a href="../../licenses/GPL-3">GPL-3</a></td>
</tr>
<tr>
<td>URL:</td>
<td><a href="http://www.milbo.users.sonic.net">http://www.milbo.users.sonic.net</a></td>
</tr>
<tr>
<td>NeedsCompilation:</td>
<td>no</td>
</tr>
<tr>
<td>Materials:</td>
<td><a href="NEWS">NEWS</a> </td>
</tr>
<tr>
<td>CRAN checks:</td>
<td><a href="../../checks/check_results_plotmo.html">plotmo results</a></td>
</tr>
</table>
<h4>Downloads:</h4>
<table summary="Package plotmo downloads">
<tr>
<td> Reference manual: </td>
<td> <a href="plotmo.pdf"> plotmo.pdf </a> </td>
</tr>
<tr>
<td> Package source: </td>
<td> <a href="../../../src/contrib/plotmo_3.3.2.tar.gz"> plotmo_3.3.2.tar.gz </a> </td>
</tr>
<tr>
<td> Windows binaries: </td>
<td> r-devel: <a href="../../../bin/windows/contrib/3.5/plotmo_3.3.2.zip">plotmo_3.3.2.zip</a>, r-release: <a href="../../../bin/windows/contrib/3.4/plotmo_3.3.2.zip">plotmo_3.3.2.zip</a>, r-oldrel: <a href="../../../bin/windows/contrib/3.3/plotmo_3.3.2.zip">plotmo_3.3.2.zip</a> </td>
</tr>
<tr>
<td> OS X El Capitan binaries: </td>
<td> r-release: <a href="../../../bin/macosx/el-capitan/contrib/3.4/plotmo_3.3.2.tgz">plotmo_3.3.2.tgz</a> </td>
</tr>
<tr>
<td> OS X Mavericks binaries: </td>
<td> r-oldrel: <a href="../../../bin/macosx/mavericks/contrib/3.3/plotmo_3.3.2.tgz">plotmo_3.3.2.tgz</a> </td>
</tr>
<tr>
<td> Old sources: </td>
<td> <a href="../../../src/contrib/Archive/plotmo"> plotmo archive </a> </td>
</tr>
</table>
<h4>Reverse dependencies:</h4>
<table summary="Package plotmo reverse dependencies">
<tr>
<td>Reverse depends:</td>
<td><a href="../earth/index.html">earth</a></td>
</tr>
</table>
<h4>Linking:</h4>
<p>Please use the canonical form
<a href="https://CRAN.R-project.org/package=plotmo"><samp>https://CRAN.R-project.org/package=plotmo</samp></a>
to link to this page.</p>
</body>
</html>
| esander91/NamespacePollution | Code/GetMetaDataFromCRAN/raw_html/plotmo.html | HTML | gpl-2.0 | 3,578 |
#!/usr/bin/python
##
## Copyright 2008, Various
## Adrian Likins <alikins@redhat.com>
##
## This software may be freely redistributed under the terms of the GNU
## general public license.
##
import os
import socket
import subprocess
import time
import unittest
import simplejson
import func.utils
from func import yaml
from func import jobthing
def structToYaml(data):
# takes a data structure, serializes it to
# yaml
buf = yaml.dump(data)
return buf
def structToJSON(data):
#Take data structure for the test
#and serializes it using json
serialized = simplejson.dumps(input)
return serialized
class BaseTest(object):
# assume we are talking to localhost
# th = socket.gethostname()
th = socket.getfqdn()
nforks=1
async=False
ft_cmd = "func-transmit"
# just so we can change it easy later
def _serialize(self, data):
raise NotImplementedError
def _deserialize(self, buf):
raise NotImplementedError
def _call_async(self, data):
data['async'] = True
data['nforks'] = 4
job_id = self._call(data)
no_answer = True
while (no_answer):
out = self._call({'clients': '*',
'method':'job_status',
'parameters': job_id})
if out[0] == jobthing.JOB_ID_FINISHED:
no_answer = False
else:
time.sleep(.25)
result = out[1]
return result
def _call(self, data):
f = self._serialize(data)
p = subprocess.Popen(self.ft_cmd, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = p.communicate(input=f)
return self._deserialize(output[0])
def call(self, data):
if self.async:
return self._call_async(data)
return self._call(data)
def __init__(self):
pass
# we do this all over the place...
def assert_on_fault(self, result):
assert func.utils.is_error(result[self.th]) == False
# assert type(result[self.th]) != xmlrpclib.Fault
class YamlBaseTest(BaseTest):
# i'd add the "yaml" attr here for nosetest to find, but it doesnt
# seem to find it unless the class is a test class directly
ft_cmd = "func-transmit --yaml"
def _serialize(self, data):
buf = yaml.dump(data)
return buf
def _deserialize(self, buf):
data = yaml.load(buf).next()
return data
class JSONBaseTest(BaseTest):
ft_cmd = "func-transmit --json"
def _serialize(self, data):
buf = simplejson.dumps(data)
return buf
def _deserialize(self, buf):
data = simplejson.loads(buf)
return data
class ListMinion(object):
def test_list_minions(self):
out = self.call({'clients': '*',
'method': 'list_minions'})
def test_list_minions_no_match(self):
out = self.call({'clients': 'somerandom-name-that-shouldnt-be-a_real_host_name',
'method': 'list_minions'})
assert out == []
def test_list_minions_group_name(self):
out = self.call({'clients': '@test',
'method': 'list_minions'})
def test_list_minions_no_clients(self):
out = self.call({'method': 'list_minions'})
class ListMinionAsync(ListMinion):
async = True
class TestListMinionYaml(YamlBaseTest, ListMinion):
yaml = True
def __init__(self):
super(TestListMinionYaml, self).__init__()
class TestListMinionJSON(JSONBaseTest, ListMinion):
json = True
def __init__(self):
super(TestListMinionJSON, self).__init__()
# list_minions is a convience call for func_transmit, and doesn't
# really make any sense to call async
#class TestListMinionYamlAsync(YamlBaseTest, ListMinionAsync):
# yaml = True
# async = True
# def __init__(self):
# super(TestListMinionYamlAsync, self).__init__()
#class TestListMinionJSONAsync(JSONBaseTest, ListMinionAsync):
# json = True
# async = True
# def __init__(self):
# super(TestListMinionJSONAsync, self).__init__()
class ClientGlob(object):
def _test_add(self, client):
result = self.call({'clients': client,
'method': 'add',
'module': 'test',
'parameters': [1,2]})
self.assert_on_fault(result)
return result
def test_single_client(self):
result = self._test_add(self.th)
def test_glob_client(self):
result = self._test_add("*")
def test_glob_list(self):
result = self._test_add([self.th, self.th])
def test_glob_string_list(self):
result = self._test_add("%s;*" % self.th)
# note, needs a /etc/func/group setup with the proper groups defined
# need to figure out a good way to test this... -akl
def test_group(self):
result = self._test_add("@test")
# def test_group_and_glob(self):
# result = self._test_add("@test;*")
# def test_list_of_groups(self):
# result = self._test_add(["@test", "@test2"])
# def test_string_list_of_groups(self):
# result = self._test_add("@test;@test2")
# run all the same tests, but run then
class ClientGlobAsync(ClientGlob):
async = True
class TestClientGlobYaml(YamlBaseTest, ClientGlob):
yaml = True
def __init__(self):
super(TestClientGlobYaml, self).__init__()
class TestClientGlobJSON(JSONBaseTest, ClientGlob):
json = True
def __init__(self):
super(TestClientGlobJSON, self).__init__()
class TestClientGlobYamlAsync(YamlBaseTest, ClientGlobAsync):
yaml = True
async = True
def __init__(self):
super(TestClientGlobYamlAsync, self).__init__()
class TestClientGlobJSONAsync(JSONBaseTest, ClientGlobAsync):
json = True
async = True
def __init__(self):
super(TestClientGlobJSONAsync, self).__init__()
# why the weird T_est name? because nosetests doesn't seem to reliably
# respect the __test__ attribute, and these modules aren't meant to be
# invoked as test classes themselves, only as bases for other tests
class T_estTest(object):
__test__ = False
def _echo_test(self, data):
result = self.call({'clients':'*',
'method': 'echo',
'module': 'test',
'parameters': [data]})
self.assert_on_fault(result)
assert result[self.th] == data
def test_add(self):
result = self.call({'clients':'*',
'method': 'add',
'module': 'test',
'parameters': [1,2]})
assert result[self.th] == 3
def test_echo_int(self):
self._echo_test(37)
def test_echo_array(self):
self._echo_test([1,2,"three", "fore", "V"])
def test_echo_hash(self):
self._echo_test({'one':1, 'two':2, 'three': 3, 'four':"IV"})
def test_echo_float(self):
self._echo_test(1.0)
# NOTE/FIXME: the big float tests fail for yaml and json
def test_echo_big_float(self):
self._echo_test(123121232.23)
def test_echo_bigger_float(self):
self._echo_test(234234234234234234234.234234234234234)
def test_echo_little_float(self):
self._echo_test(0.0000000000000000000000000000000000037)
# Note/FIXME: these test currently fail for YAML
def test_echo_boolean_true(self):
self._echo_test(True)
def test_echo_boolean_false(self):
self._echo_test(False)
class T_estTestAsync(T_estTest):
__test__ = False
async = True
class TestTestYaml(YamlBaseTest, T_estTest):
yaml = True
def __init__(self):
super(YamlBaseTest, self).__init__()
class TestTestJSON(JSONBaseTest, T_estTest):
json = True
def __init__(self):
super(JSONBaseTest,self).__init__()
class TestTestAsyncJSON(JSONBaseTest, T_estTestAsync):
json = True
async = True
def __init__(self):
super(JSONBaseTest,self).__init__()
class TestTestAsyncYaml(YamlBaseTest, T_estTestAsync):
yaml = True
async = True
def __init__(self):
super(YamlBaseTest,self).__init__()
| pombredanne/func | test/unittest/test_func_transmit.py | Python | gpl-2.0 | 8,415 |
/*
* Copyright 2006 BBC and Fluendo S.A.
*
* This library is licensed under 4 different licenses and you
* can choose to use it under the terms of any one of them. The
* four licenses are the MPL 1.1, the LGPL, the GPL and the MIT
* license.
*
* MPL:
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* LGPL:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* GPL:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* MIT:
*
* Unless otherwise indicated, Source Code is licensed under MIT license.
* See further explanation attached in License Statement (distributed in the file
* LICENSE).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include "tsmux.h"
#include "tsmuxstream.h"
#include "crc.h"
#define GST_CAT_DEFAULT mpegtsmux_debug
/* Maximum total data length for a PAT section is 1024 bytes, minus an
* 8 byte header, then the length of each program entry is 32 bits,
* then finally a 32 bit CRC. Thus the maximum number of programs in this mux
* is (1024 - 8 - 4) / 4 = 253 because it only supports single section PATs */
#define TSMUX_MAX_PROGRAMS 253
#define TSMUX_SECTION_HDR_SIZE 8
#define TSMUX_DEFAULT_NETWORK_ID 0x0001
#define TSMUX_DEFAULT_TS_ID 0x0001
/* HACK: We use a fixed buffering offset for the PCR at the moment -
* this is the amount 'in advance' of the stream that the PCR sits.
* 1/8 second atm */
#define TSMUX_PCR_OFFSET (TSMUX_CLOCK_FREQ / 8)
/* Times per second to write PCR */
#define TSMUX_DEFAULT_PCR_FREQ (25)
/* Base for all written PCR and DTS/PTS,
* so we have some slack to go backwards */
#define CLOCK_BASE (TSMUX_CLOCK_FREQ * 10 * 360)
static gboolean tsmux_write_pat (TsMux * mux);
static gboolean tsmux_write_pmt (TsMux * mux, TsMuxProgram * program);
/**
* tsmux_new:
*
* Create a new muxer session.
*
* Returns: A new #TsMux object.
*/
TsMux *
tsmux_new (void)
{
TsMux *mux;
mux = g_slice_new0 (TsMux);
mux->transport_id = TSMUX_DEFAULT_TS_ID;
mux->next_pgm_no = TSMUX_START_PROGRAM_ID;
mux->next_pmt_pid = TSMUX_START_PMT_PID;
mux->next_stream_pid = TSMUX_START_ES_PID;
mux->pat_changed = TRUE;
mux->last_pat_ts = -1;
mux->pat_interval = TSMUX_DEFAULT_PAT_INTERVAL;
return mux;
}
/**
* tsmux_set_write_func:
* @mux: a #TsMux
* @func: a user callback function
* @user_data: user data passed to @func
*
* Set the callback function and user data to be called when @mux has output to
* produce. @user_data will be passed as user data in @func.
*/
void
tsmux_set_write_func (TsMux * mux, TsMuxWriteFunc func, void *user_data)
{
g_return_if_fail (mux != NULL);
mux->write_func = func;
mux->write_func_data = user_data;
}
/**
* tsmux_set_alloc_func:
* @mux: a #TsMux
* @func: a user callback function
* @user_data: user data passed to @func
*
* Set the callback function and user data to be called when @mux needs
* a new buffer to write a packet into.
* @user_data will be passed as user data in @func.
*/
void
tsmux_set_alloc_func (TsMux * mux, TsMuxAllocFunc func, void *user_data)
{
g_return_if_fail (mux != NULL);
mux->alloc_func = func;
mux->alloc_func_data = user_data;
}
/**
* tsmux_set_pat_interval:
* @mux: a #TsMux
* @freq: a new PAT interval
*
* Set the interval (in cycles of the 90kHz clock) for writing out the PAT table.
*
* Many transport stream clients might have problems if the PAT table is not
* inserted in the stream at regular intervals, especially when initially trying
* to figure out the contents of the stream.
*/
void
tsmux_set_pat_interval (TsMux * mux, guint freq)
{
g_return_if_fail (mux != NULL);
mux->pat_interval = freq;
}
/**
* tsmux_get_pat_interval:
* @mux: a #TsMux
*
* Get the configured PAT interval. See also tsmux_set_pat_interval().
*
* Returns: the configured PAT interval
*/
guint
tsmux_get_pat_interval (TsMux * mux)
{
g_return_val_if_fail (mux != NULL, 0);
return mux->pat_interval;
}
/**
* tsmux_free:
* @mux: a #TsMux
*
* Free all resources associated with @mux. After calling this function @mux can
* not be used anymore.
*/
void
tsmux_free (TsMux * mux)
{
GList *cur;
g_return_if_fail (mux != NULL);
/* Free all programs */
for (cur = mux->programs; cur; cur = cur->next) {
TsMuxProgram *program = (TsMuxProgram *) cur->data;
tsmux_program_free (program);
}
g_list_free (mux->programs);
/* Free all streams */
for (cur = mux->streams; cur; cur = cur->next) {
TsMuxStream *stream = (TsMuxStream *) cur->data;
tsmux_stream_free (stream);
}
g_list_free (mux->streams);
g_slice_free (TsMux, mux);
}
/**
* tsmux_program_new:
* @mux: a #TsMux
*
* Create a new program in the mising session @mux.
*
* Returns: a new #TsMuxProgram or %NULL when the maximum number of programs has
* been reached.
*/
TsMuxProgram *
tsmux_program_new (TsMux * mux)
{
TsMuxProgram *program;
g_return_val_if_fail (mux != NULL, NULL);
/* Ensure we have room for another program */
if (mux->nb_programs == TSMUX_MAX_PROGRAMS)
return NULL;
program = g_slice_new0 (TsMuxProgram);
program->pmt_changed = TRUE;
program->last_pmt_ts = -1;
program->pmt_interval = TSMUX_DEFAULT_PMT_INTERVAL;
program->pgm_number = mux->next_pgm_no++;
program->pmt_pid = mux->next_pmt_pid++;
program->pcr_stream = NULL;
program->streams = g_array_sized_new (FALSE, TRUE, sizeof (TsMuxStream *), 1);
mux->programs = g_list_prepend (mux->programs, program);
mux->nb_programs++;
mux->pat_changed = TRUE;
return program;
}
/**
* tsmux_set_pmt_interval:
* @program: a #TsMuxProgram
* @freq: a new PMT interval
*
* Set the interval (in cycles of the 90kHz clock) for writing out the PMT table.
*
* Many transport stream clients might have problems if the PMT table is not
* inserted in the stream at regular intervals, especially when initially trying
* to figure out the contents of the stream.
*/
void
tsmux_set_pmt_interval (TsMuxProgram * program, guint freq)
{
g_return_if_fail (program != NULL);
program->pmt_interval = freq;
}
/**
* tsmux_get_pmt_interval:
* @program: a #TsMuxProgram
*
* Get the configured PMT interval. See also tsmux_set_pmt_interval().
*
* Returns: the configured PMT interval
*/
guint
tsmux_get_pmt_interval (TsMuxProgram * program)
{
g_return_val_if_fail (program != NULL, 0);
return program->pmt_interval;
}
/**
* tsmux_program_add_stream:
* @program: a #TsMuxProgram
* @stream: a #TsMuxStream
*
* Add @stream to @program.
*/
void
tsmux_program_add_stream (TsMuxProgram * program, TsMuxStream * stream)
{
g_return_if_fail (program != NULL);
g_return_if_fail (stream != NULL);
g_array_append_val (program->streams, stream);
program->pmt_changed = TRUE;
}
/**
* tsmux_program_set_pcr_stream:
* @program: a #TsMuxProgram
* @stream: a #TsMuxStream
*
* Set @stream as the PCR stream for @program, overwriting the previously
* configured PCR stream. When @stream is NULL, program will have no PCR stream
* configured.
*/
void
tsmux_program_set_pcr_stream (TsMuxProgram * program, TsMuxStream * stream)
{
g_return_if_fail (program != NULL);
if (program->pcr_stream == stream)
return;
if (program->pcr_stream != NULL)
tsmux_stream_pcr_unref (program->pcr_stream);
if (stream)
tsmux_stream_pcr_ref (stream);
program->pcr_stream = stream;
program->pmt_changed = TRUE;
}
/**
* tsmux_get_new_pid:
* @mux: a #TsMux
*
* Get a new free PID.
*
* Returns: a new free PID.
*/
guint16
tsmux_get_new_pid (TsMux * mux)
{
g_return_val_if_fail (mux != NULL, -1);
/* make sure this PID is free
* (and not taken by a specific earlier request) */
do {
mux->next_stream_pid++;
} while (tsmux_find_stream (mux, mux->next_stream_pid));
return mux->next_stream_pid;
}
/**
* tsmux_create_stream:
* @mux: a #TsMux
* @stream_type: a #TsMuxStreamType
* @pid: the PID of the new stream.
*
* Create a new stream of @stream_type in the muxer session @mux.
*
* When @pid is set to #TSMUX_PID_AUTO, a new free PID will automatically
* be allocated for the new stream.
*
* Returns: a new #TsMuxStream.
*/
TsMuxStream *
tsmux_create_stream (TsMux * mux, TsMuxStreamType stream_type, guint16 pid)
{
TsMuxStream *stream;
guint16 new_pid;
g_return_val_if_fail (mux != NULL, NULL);
if (pid == TSMUX_PID_AUTO) {
new_pid = tsmux_get_new_pid (mux);
} else {
new_pid = pid & 0x1FFF;
}
/* Ensure we're not creating a PID collision */
if (tsmux_find_stream (mux, new_pid))
return NULL;
stream = tsmux_stream_new (new_pid, stream_type);
mux->streams = g_list_prepend (mux->streams, stream);
mux->nb_streams++;
return stream;
}
/**
* tsmux_find_stream:
* @mux: a #TsMux
* @pid: the PID to find.
*
* Find the stream associated wih PID.
*
* Returns: a #TsMuxStream with @pid or NULL when the stream was not found.
*/
TsMuxStream *
tsmux_find_stream (TsMux * mux, guint16 pid)
{
TsMuxStream *found = NULL;
GList *cur;
g_return_val_if_fail (mux != NULL, NULL);
for (cur = mux->streams; cur; cur = cur->next) {
TsMuxStream *stream = (TsMuxStream *) cur->data;
if (tsmux_stream_get_pid (stream) == pid) {
found = stream;
break;
}
}
return found;
}
static gboolean
tsmux_get_buffer (TsMux * mux, GstBuffer ** buf)
{
g_return_val_if_fail (buf, FALSE);
if (G_UNLIKELY (!mux->alloc_func))
return FALSE;
mux->alloc_func (buf, mux->alloc_func_data);
if (!*buf)
return FALSE;
g_assert (GST_BUFFER_SIZE (*buf) == TSMUX_PACKET_LENGTH);
return TRUE;
}
static gboolean
tsmux_packet_out (TsMux * mux, GstBuffer * buf, gint64 pcr)
{
if (G_UNLIKELY (mux->write_func == NULL)) {
if (buf)
gst_buffer_unref (buf);
return TRUE;
}
return mux->write_func (buf, mux->write_func_data, pcr);
}
/*
* adaptation_field() {
* adaptation_field_length 8 uimsbf
* if(adaptation_field_length >0) {
* discontinuity_indicator 1 bslbf
* random_access_indicator 1 bslbf
* elementary_stream_priority_indicator 1 bslbf
* PCR_flag 1 bslbf
* OPCR_flag 1 bslbf
* splicing_point_flag 1 bslbf
* transport_private_data_flag 1 bslbf
* adaptation_field_extension_flag 1 bslbf
* if(PCR_flag == '1') {
* program_clock_reference_base 33 uimsbf
* reserved 6 bslbf
* program_clock_reference_extension 9 uimsbf
* }
* if(OPCR_flag == '1') {
* original_program_clock_reference_base 33 uimsbf
* reserved 6 bslbf
* original_program_clock_reference_extension 9 uimsbf
* }
* if (splicing_point_flag == '1') {
* splice_countdown 8 tcimsbf
* }
* if(transport_private_data_flag == '1') {
* transport_private_data_length 8 uimsbf
* for (i=0; i<transport_private_data_length;i++){
* private_data_byte 8 bslbf
* }
* }
* if (adaptation_field_extension_flag == '1' ) {
* adaptation_field_extension_length 8 uimsbf
* ltw_flag 1 bslbf
* piecewise_rate_flag 1 bslbf
* seamless_splice_flag 1 bslbf
* reserved 5 bslbf
* if (ltw_flag == '1') {
* ltw_valid_flag 1 bslbf
* ltw_offset 15 uimsbf
* }
* if (piecewise_rate_flag == '1') {
* reserved 2 bslbf
* piecewise_rate 22 uimsbf
* }
* if (seamless_splice_flag == '1'){
* splice_type 4 bslbf
* DTS_next_AU[32..30] 3 bslbf
* marker_bit 1 bslbf
* DTS_next_AU[29..15] 15 bslbf
* marker_bit 1 bslbf
* DTS_next_AU[14..0] 15 bslbf
* marker_bit 1 bslbf
* }
* for ( i=0;i<N;i++) {
* reserved 8 bslbf
* }
* }
* for (i=0;i<N;i++){
* stuffing_byte 8 bslbf
* }
* }
* }
*/
static gboolean
tsmux_write_adaptation_field (guint8 * buf,
TsMuxPacketInfo * pi, guint8 min_length, guint8 * written)
{
guint8 pos = 2;
guint8 flags = 0;
g_assert (min_length <= TSMUX_PAYLOAD_LENGTH);
/* Write out all the fields from the packet info only if the
* user set the flag to request the adaptation field - if the flag
* isn't set, we're just supposed to write stuffing bytes */
if (pi->flags & TSMUX_PACKET_FLAG_ADAPTATION) {
TS_DEBUG ("writing adaptation fields");
if (pi->flags & TSMUX_PACKET_FLAG_DISCONT)
flags |= 0x80;
if (pi->flags & TSMUX_PACKET_FLAG_RANDOM_ACCESS)
flags |= 0x40;
if (pi->flags & TSMUX_PACKET_FLAG_PRIORITY)
flags |= 0x20;
if (pi->flags & TSMUX_PACKET_FLAG_WRITE_PCR) {
guint64 pcr_base;
guint32 pcr_ext;
pcr_base = (pi->pcr / 300);
pcr_ext = (pi->pcr % 300);
flags |= 0x10;
TS_DEBUG ("Writing PCR %" G_GUINT64_FORMAT " + ext %u", pcr_base,
pcr_ext);
buf[pos++] = (pcr_base >> 25) & 0xff;
buf[pos++] = (pcr_base >> 17) & 0xff;
buf[pos++] = (pcr_base >> 9) & 0xff;
buf[pos++] = (pcr_base >> 1) & 0xff;
buf[pos++] = ((pcr_base << 7) & 0x80) | ((pcr_ext >> 8) & 0x01);
buf[pos++] = (pcr_ext) & 0xff;
}
if (pi->flags & TSMUX_PACKET_FLAG_WRITE_OPCR) {
guint64 opcr_base;
guint32 opcr_ext;
opcr_base = (pi->opcr / 300);
opcr_ext = (pi->opcr % 300);
flags |= 0x08;
TS_DEBUG ("Writing OPCR");
buf[pos++] = (opcr_base >> 25) & 0xff;
buf[pos++] = (opcr_base >> 17) & 0xff;
buf[pos++] = (opcr_base >> 9) & 0xff;
buf[pos++] = (opcr_base >> 1) & 0xff;
buf[pos++] = ((opcr_base << 7) & 0x80) | ((opcr_ext >> 8) & 0x01);
buf[pos++] = (opcr_ext) & 0xff;
}
if (pi->flags & TSMUX_PACKET_FLAG_WRITE_SPLICE) {
flags |= 0x04;
buf[pos++] = pi->splice_countdown;
}
if (pi->private_data_len > 0) {
flags |= 0x02;
/* Private data to write, ensure we have enough room */
if ((1 + pi->private_data_len) > (TSMUX_PAYLOAD_LENGTH - pos))
return FALSE;
buf[pos++] = pi->private_data_len;
memcpy (&(buf[pos]), pi->private_data, pi->private_data_len);
pos += pi->private_data_len;
TS_DEBUG ("%u bytes of private data", pi->private_data_len);
}
if (pi->flags & TSMUX_PACKET_FLAG_WRITE_ADAPT_EXT) {
flags |= 0x01;
TS_DEBUG ("FIXME: write Adaptation extension");
/* Write an empty extension for now */
buf[pos++] = 1;
buf[pos++] = 0;
}
}
/* Write the flags at the start */
buf[1] = flags;
/* Stuffing bytes if needed */
while (pos < min_length)
buf[pos++] = 0xff;
/* Write the adaptation field length, which doesn't include its own byte */
buf[0] = pos - 1;
if (written)
*written = pos;
return TRUE;
}
static gboolean
tsmux_write_ts_header (guint8 * buf, TsMuxPacketInfo * pi,
guint * payload_len_out, guint * payload_offset_out)
{
guint8 *tmp;
guint8 adaptation_flag;
guint8 adapt_min_length = 0;
guint8 adapt_len = 0;
guint payload_len;
gboolean write_adapt = FALSE;
/* Sync byte */
buf[0] = TSMUX_SYNC_BYTE;
TS_DEBUG ("PID 0x%04x, counter = 0x%01x, %u bytes avail", pi->pid,
pi->packet_count & 0x0f, pi->stream_avail);
/* 3 bits:
* transport_error_indicator
* payload_unit_start_indicator
* transport_priority: (00)
* 13 bits: PID
*/
tmp = buf + 1;
if (pi->packet_start_unit_indicator) {
tsmux_put16 (&tmp, 0x4000 | pi->pid);
} else
tsmux_put16 (&tmp, pi->pid);
/* 2 bits: scrambling_control (NOT SUPPORTED) (00)
* 2 bits: adaptation field control (1x has_adaptation_field | x1 has_payload)
* 4 bits: continuity counter (xxxx)
*/
adaptation_flag = pi->packet_count & 0x0f;
if (pi->flags & TSMUX_PACKET_FLAG_ADAPTATION) {
write_adapt = TRUE;
}
if (pi->stream_avail < TSMUX_PAYLOAD_LENGTH) {
/* Need an adaptation field regardless for stuffing */
adapt_min_length = TSMUX_PAYLOAD_LENGTH - pi->stream_avail;
write_adapt = TRUE;
}
if (write_adapt) {
gboolean res;
/* Flag the adaptation field presence */
adaptation_flag |= 0x20;
res = tsmux_write_adaptation_field (buf + TSMUX_HEADER_LENGTH,
pi, adapt_min_length, &adapt_len);
if (G_UNLIKELY (res == FALSE))
return FALSE;
/* Should have written at least the number of bytes we requested */
g_assert (adapt_len >= adapt_min_length);
}
/* The amount of packet data we wrote is the remaining space after
* the adaptation field */
*payload_len_out = payload_len = TSMUX_PAYLOAD_LENGTH - adapt_len;
*payload_offset_out = TSMUX_HEADER_LENGTH + adapt_len;
/* Now if we are going to write out some payload, flag that fact */
if (payload_len > 0 && pi->stream_avail > 0) {
/* Flag the presence of a payload */
adaptation_flag |= 0x10;
/* We must have enough data to fill the payload, or some calculation
* went wrong */
g_assert (payload_len <= pi->stream_avail);
/* Packet with payload, increment the continuity counter */
pi->packet_count++;
}
/* Write the byte of transport_scrambling_control, adaptation_field_control
* + continuity counter out */
buf[3] = adaptation_flag;
if (write_adapt) {
TS_DEBUG ("Adaptation field of size >= %d + %d bytes payload",
adapt_len, payload_len);
} else {
TS_DEBUG ("Payload of %d bytes only", payload_len);
}
return TRUE;
}
/**
* tsmux_write_stream_packet:
* @mux: a #TsMux
* @stream: a #TsMuxStream
*
* Write a packet of @stream.
*
* Returns: TRUE if the packet could be written.
*/
gboolean
tsmux_write_stream_packet (TsMux * mux, TsMuxStream * stream)
{
guint payload_len, payload_offs;
TsMuxPacketInfo *pi = &stream->pi;
gboolean res;
gint64 cur_pcr = -1;
GstBuffer *buf = NULL;
guint8 *data;
g_return_val_if_fail (mux != NULL, FALSE);
g_return_val_if_fail (stream != NULL, FALSE);
if (tsmux_stream_is_pcr (stream)) {
gint64 cur_pts = tsmux_stream_get_pts (stream);
gboolean write_pat;
GList *cur;
cur_pcr = 0;
if (cur_pts != -1) {
TS_DEBUG ("TS for PCR stream is %" G_GINT64_FORMAT, cur_pts);
}
/* FIXME: The current PCR needs more careful calculation than just
* writing a fixed offset */
if (cur_pts != -1 && (cur_pts >= TSMUX_PCR_OFFSET))
cur_pcr = (cur_pts - TSMUX_PCR_OFFSET) *
(TSMUX_SYS_CLOCK_FREQ / TSMUX_CLOCK_FREQ);
cur_pcr += CLOCK_BASE * (TSMUX_SYS_CLOCK_FREQ / TSMUX_CLOCK_FREQ);
/* Need to decide whether to write a new PCR in this packet */
if (stream->last_pcr == -1 ||
(cur_pcr - stream->last_pcr >
(TSMUX_SYS_CLOCK_FREQ / TSMUX_DEFAULT_PCR_FREQ))) {
stream->pi.flags |=
TSMUX_PACKET_FLAG_ADAPTATION | TSMUX_PACKET_FLAG_WRITE_PCR;
stream->pi.pcr = cur_pcr;
stream->last_pcr = cur_pcr;
} else {
cur_pcr = -1;
}
/* check if we need to rewrite pat */
if (mux->last_pat_ts == -1 || mux->pat_changed)
write_pat = TRUE;
else if (cur_pts >= mux->last_pat_ts + mux->pat_interval)
write_pat = TRUE;
else
write_pat = FALSE;
if (write_pat) {
mux->last_pat_ts = cur_pts;
if (!tsmux_write_pat (mux))
return FALSE;
}
/* check if we need to rewrite any of the current pmts */
for (cur = mux->programs; cur; cur = cur->next) {
TsMuxProgram *program = (TsMuxProgram *) cur->data;
gboolean write_pmt;
if (program->last_pmt_ts == -1 || program->pmt_changed)
write_pmt = TRUE;
else if (cur_pts >= program->last_pmt_ts + program->pmt_interval)
write_pmt = TRUE;
else
write_pmt = FALSE;
if (write_pmt) {
program->last_pmt_ts = cur_pts;
if (!tsmux_write_pmt (mux, program))
return FALSE;
}
}
}
pi->packet_start_unit_indicator = tsmux_stream_at_pes_start (stream);
if (pi->packet_start_unit_indicator) {
tsmux_stream_initialize_pes_packet (stream);
if (stream->dts != -1)
stream->dts += CLOCK_BASE;
if (stream->pts != -1)
stream->pts += CLOCK_BASE;
}
pi->stream_avail = tsmux_stream_bytes_avail (stream);
/* obtain buffer */
if (!tsmux_get_buffer (mux, &buf))
return FALSE;
data = GST_BUFFER_DATA (buf);
if (!tsmux_write_ts_header (data, pi, &payload_len, &payload_offs))
goto fail;
if (!tsmux_stream_get_data (stream, data + payload_offs, payload_len))
goto fail;
res = tsmux_packet_out (mux, buf, cur_pcr);
/* Reset all dynamic flags */
stream->pi.flags &= TSMUX_PACKET_FLAG_PES_FULL_HEADER;
return res;
/* ERRORS */
fail:
{
if (buf)
gst_buffer_unref (buf);
return FALSE;
}
}
/**
* tsmux_program_free:
* @program: a #TsMuxProgram
*
* Free the resources of @program. After this call @program can not be used
* anymore.
*/
void
tsmux_program_free (TsMuxProgram * program)
{
g_return_if_fail (program != NULL);
g_array_free (program->streams, TRUE);
g_slice_free (TsMuxProgram, program);
}
static gboolean
tsmux_write_section (TsMux * mux, TsMuxSection * section)
{
guint8 *cur_in;
guint payload_remain;
guint payload_len, payload_offs;
TsMuxPacketInfo *pi;
GstBuffer *buf = NULL;
pi = §ion->pi;
pi->packet_start_unit_indicator = TRUE;
cur_in = section->data;
payload_remain = pi->stream_avail;
while (payload_remain > 0) {
guint8 *data;
/* obtain buffer */
if (!tsmux_get_buffer (mux, &buf))
goto fail;
data = GST_BUFFER_DATA (buf);
if (pi->packet_start_unit_indicator) {
/* Need to write an extra single byte start pointer */
pi->stream_avail++;
if (!tsmux_write_ts_header (data, pi, &payload_len, &payload_offs)) {
pi->stream_avail--;
goto fail;
}
pi->stream_avail--;
/* Write the pointer byte */
data[payload_offs] = 0x00;
payload_offs++;
payload_len--;
pi->packet_start_unit_indicator = FALSE;
} else {
if (!tsmux_write_ts_header (data, pi, &payload_len, &payload_offs))
goto fail;
}
TS_DEBUG ("Outputting %d bytes to section. %d remaining after",
payload_len, payload_remain - payload_len);
memcpy (data + payload_offs, cur_in, payload_len);
cur_in += payload_len;
payload_remain -= payload_len;
/* we do not write PCR in section */
if (G_UNLIKELY (!tsmux_packet_out (mux, buf, -1))) {
/* buffer given away */
buf = NULL;
goto fail;
}
buf = NULL;
}
return TRUE;
/* ERRORS */
fail:
{
if (buf)
gst_buffer_unref (buf);
return FALSE;
}
}
static void
tsmux_write_section_hdr (guint8 * pos, guint8 table_id, guint16 len,
guint16 id, guint8 version, guint8 section_nr, guint8 last_section_nr)
{
/* The length passed is the total length of the section, but we're not
* supposed to include the first 3 bytes of the header in the count */
len -= 3;
/* 1 byte table identifier */
*pos++ = table_id;
/* section_syntax_indicator = '0' | '0' | '11' reserved bits | (len >> 8) */
tsmux_put16 (&pos, 0xB000 | len);
/* 2 bytes transport/program id */
tsmux_put16 (&pos, id);
/* '11' reserved | version 'xxxxxx' | 'x' current_next */
*pos++ = 0xC0 | ((version & 0x1F) << 1) | 0x01;
*pos++ = section_nr;
*pos++ = last_section_nr;
}
static gboolean
tsmux_write_pat (TsMux * mux)
{
GList *cur;
TsMuxSection *pat = &mux->pat;
if (mux->pat_changed) {
/* program_association_section ()
* table_id 8 uimsbf
* section_syntax_indicator 1 bslbf
* '0' 1 bslbf
* reserved 2 bslbf
* section_length 12 uimsbf
* transport_stream_id 16 uimsbf
* reserved 2 bslbf
* version_number 5 uimsbf
* current_next_indicator 1 bslbf
* section_number 8 uimsbf
* last_section_number 8 uimsbf
* for (i = 0; i < N; i++) {
* program_number 16 uimsbf
* reserved 3 bslbf
* network_PID_or_program_map_PID 13 uimbsf
* }
* CRC_32 32 rbchof
*/
guint8 *pos;
guint32 crc;
/* Prepare the section data after the section header */
pos = pat->data + TSMUX_SECTION_HDR_SIZE;
for (cur = mux->programs; cur; cur = cur->next) {
TsMuxProgram *program = (TsMuxProgram *) cur->data;
tsmux_put16 (&pos, program->pgm_number);
tsmux_put16 (&pos, 0xE000 | program->pmt_pid);
}
/* Measure the section length, include extra 4 bytes for CRC below */
pat->pi.stream_avail = pos - pat->data + 4;
/* Go back and write the header now that we know the final length.
* table_id = 0 for PAT */
tsmux_write_section_hdr (pat->data, 0x00, pat->pi.stream_avail,
mux->transport_id, mux->pat_version, 0, 0);
/* Calc and output CRC for data bytes, not including itself */
crc = calc_crc32 (pat->data, pat->pi.stream_avail - 4);
tsmux_put32 (&pos, crc);
TS_DEBUG ("PAT has %d programs, is %u bytes",
mux->nb_programs, pat->pi.stream_avail);
mux->pat_changed = FALSE;
mux->pat_version++;
}
return tsmux_write_section (mux, pat);
}
static gboolean
tsmux_write_pmt (TsMux * mux, TsMuxProgram * program)
{
TsMuxSection *pmt = &program->pmt;
if (program->pmt_changed) {
/* program_association_section ()
* table_id 8 uimsbf
* section_syntax_indicator 1 bslbf
* '0' 1 bslbf
* reserved 2 bslbf
* section_length 12 uimsbf
* program_id 16 uimsbf
* reserved 2 bslbf
* version_number 5 uimsbf
* current_next_indicator 1 bslbf
* section_number 8 uimsbf
* last_section_number 8 uimsbf
* reserved 3 bslbf
* PCR_PID 13 uimsbf
* reserved 4 bslbf
* program_info_length 12 uimsbf
* for (i = 0; i < N; i++)
* descriptor ()
*
* for (i = 0; i < N1; i++) {
* stream_type 8 uimsbf
* reserved 3 bslbf
* elementary_PID 13 uimbsf
* reserved 4 bslbf
* ES_info_length 12 uimbsf
* for (i = 0; i < N1; i++) {
* descriptor ();
* }
* }
* CRC_32 32 rbchof
*/
guint8 *pos;
guint32 crc;
guint i;
/* Prepare the section data after the basic section header */
pos = pmt->data + TSMUX_SECTION_HDR_SIZE;
if (program->pcr_stream == NULL)
tsmux_put16 (&pos, 0xFFFF);
else
tsmux_put16 (&pos, 0xE000 | tsmux_stream_get_pid (program->pcr_stream));
/* 4 bits reserved, 12 bits program_info_length, descriptor : HDMV */
tsmux_put16 (&pos, 0xF00C);
tsmux_put16 (&pos, 0x0504);
tsmux_put16 (&pos, 0x4844);
tsmux_put16 (&pos, 0x4D56);
tsmux_put16 (&pos, 0x8804);
tsmux_put16 (&pos, 0x0FFF);
tsmux_put16 (&pos, 0xFCFC);
/* Write out the entries */
for (i = 0; i < program->streams->len; i++) {
TsMuxStream *stream = g_array_index (program->streams, TsMuxStream *, i);
guint16 es_info_len;
/* FIXME: Use API to retrieve this from the stream */
*pos++ = stream->stream_type;
tsmux_put16 (&pos, 0xE000 | tsmux_stream_get_pid (stream));
/* Write any ES descriptors needed */
tsmux_stream_get_es_descrs (stream, mux->es_info_buf, &es_info_len);
tsmux_put16 (&pos, 0xF000 | es_info_len);
if (es_info_len > 0) {
TS_DEBUG ("Writing descriptor of len %d for PID 0x%04x",
es_info_len, tsmux_stream_get_pid (stream));
if (G_UNLIKELY (pos + es_info_len >=
pmt->data + TSMUX_MAX_SECTION_LENGTH))
return FALSE;
memcpy (pos, mux->es_info_buf, es_info_len);
pos += es_info_len;
}
}
/* Include the CRC in the byte count */
pmt->pi.stream_avail = pos - pmt->data + 4;
/* Go back and patch the pmt_header now that we know the length.
* table_id = 2 for PMT */
tsmux_write_section_hdr (pmt->data, 0x02, pmt->pi.stream_avail,
program->pgm_number, program->pmt_version, 0, 0);
/* Calc and output CRC for data bytes,
* but not counting the CRC bytes this time */
crc = calc_crc32 (pmt->data, pmt->pi.stream_avail - 4);
tsmux_put32 (&pos, crc);
TS_DEBUG ("PMT for program %d has %d streams, is %u bytes",
program->pgm_number, program->streams->len, pmt->pi.stream_avail);
pmt->pi.pid = program->pmt_pid;
program->pmt_changed = FALSE;
program->pmt_version++;
}
return tsmux_write_section (mux, pmt);
}
| drothlis/gst-plugins-bad | gst/mpegtsmux/tsmux/tsmux.c | C | gpl-2.0 | 33,268 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_74) on Mon Feb 29 22:41:17 PST 2016 -->
<title>Index</title>
<meta name="date" content="2016-02-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?index-all.html" target="_top">Frames</a></li>
<li><a href="index-all.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="#I:A">A</a> <a href="#I:C">C</a> <a href="#I:E">E</a> <a href="#I:F">F</a> <a href="#I:G">G</a> <a href="#I:H">H</a> <a href="#I:I">I</a> <a href="#I:L">L</a> <a href="#I:M">M</a> <a href="#I:P">P</a> <a href="#I:R">R</a> <a href="#I:S">S</a> <a href="#I:U">U</a> <a href="#I:W">W</a> <a name="I:A">
<!-- -->
</a>
<h2 class="title">A</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#addCreature-aquarium.creatures.Creature-">addCreature(Creature)</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Adds a Creature to the Aquarium.</div>
</dd>
<dt><a href="aquarium/package-summary.html">aquarium</a> - package aquarium</dt>
<dd>
<div class="block">Contains the <code>Aquarium</code> manager class and subpackages
for Aquarium resources, such as UI and the creatures
that go in the Aquarium.</div>
</dd>
<dt><a href="aquarium/Aquarium.html" title="class in aquarium"><span class="typeNameLink">Aquarium</span></a> - Class in <a href="aquarium/package-summary.html">aquarium</a></dt>
<dd>
<div class="block">The Aquarium holds the animation logic for creatures which may be
added using <code>fillWithCreatures</code>.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#Aquarium--">Aquarium()</a></span> - Constructor for class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Creates an empty Aquarium.</div>
</dd>
<dt><a href="aquarium/creatures/package-summary.html">aquarium.creatures</a> - package aquarium.creatures</dt>
<dd>
<div class="block">Contains the collection of classes implementing <a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures"><code>Creature</code></a>
which are then added to the <a href="aquarium/Aquarium.html" title="class in aquarium"><code>Aquarium</code></a>.</div>
</dd>
<dt><a href="aquarium/ui/package-summary.html">aquarium.ui</a> - package aquarium.ui</dt>
<dd>
<div class="block">UI classes used by AquariumMain and the <a href="aquarium/Aquarium.html" title="class in aquarium"><code>Aquarium</code></a> class.</div>
</dd>
<dt><a href="aquarium/ui/AquariumFrame.html" title="class in aquarium.ui"><span class="typeNameLink">AquariumFrame</span></a> - Class in <a href="aquarium/ui/package-summary.html">aquarium.ui</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/AquariumFrame.html#AquariumFrame-aquarium.Aquarium-int-int-">AquariumFrame(Aquarium, int, int)</a></span> - Constructor for class aquarium.ui.<a href="aquarium/ui/AquariumFrame.html" title="class in aquarium.ui">AquariumFrame</a></dt>
<dd> </dd>
<dt><a href="AquariumMain.html" title="class in <Unnamed>"><span class="typeNameLink">AquariumMain</span></a> - Class in <a href="package-summary.html"><Unnamed></a></dt>
<dd>
<div class="block">Class holding the main method for the AP Aquarium.</div>
</dd>
<dt><span class="memberNameLink"><a href="AquariumMain.html#AquariumMain--">AquariumMain()</a></span> - Constructor for class <a href="AquariumMain.html" title="class in <Unnamed>">AquariumMain</a></dt>
<dd> </dd>
<dt><a href="aquarium/ui/AquariumPanel.html" title="class in aquarium.ui"><span class="typeNameLink">AquariumPanel</span></a> - Class in <a href="aquarium/ui/package-summary.html">aquarium.ui</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/AquariumPanel.html#AquariumPanel-aquarium.Aquarium-">AquariumPanel(Aquarium)</a></span> - Constructor for class aquarium.ui.<a href="aquarium/ui/AquariumPanel.html" title="class in aquarium.ui">AquariumPanel</a></dt>
<dd> </dd>
</dl>
<a name="I:C">
<!-- -->
</a>
<h2 class="title">C</h2>
<dl>
<dt><a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures"><span class="typeNameLink">ChangingSwimmer</span></a> - Class in <a href="aquarium/creatures/package-summary.html">aquarium.creatures</a></dt>
<dd>
<div class="block">A ChangingSwimmer is a PaintedCreature which:
Moves at a given whole integer slope speed, in a straight line;
Can change X and Y speeds after being created;
Bounces off of the walls, the floor, and the surface of the water,
in order to stay underwater.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#ChangingSwimmer-java.lang.String-int-">ChangingSwimmer(String, int)</a></span> - Constructor for class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Creates a ChangingSwimmer.</div>
</dd>
<dt><a href="aquarium/ui/ControllerFrame.html" title="class in aquarium.ui"><span class="typeNameLink">ControllerFrame</span></a> - Class in <a href="aquarium/ui/package-summary.html">aquarium.ui</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/ControllerFrame.html#ControllerFrame-aquarium.Aquarium-">ControllerFrame(Aquarium)</a></span> - Constructor for class aquarium.ui.<a href="aquarium/ui/ControllerFrame.html" title="class in aquarium.ui">ControllerFrame</a></dt>
<dd> </dd>
<dt><a href="aquarium/ui/ControllerPanel.html" title="class in aquarium.ui"><span class="typeNameLink">ControllerPanel</span></a> - Class in <a href="aquarium/ui/package-summary.html">aquarium.ui</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/ControllerPanel.html#ControllerPanel-aquarium.Aquarium-">ControllerPanel(Aquarium)</a></span> - Constructor for class aquarium.ui.<a href="aquarium/ui/ControllerPanel.html" title="class in aquarium.ui">ControllerPanel</a></dt>
<dd> </dd>
<dt><a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures"><span class="typeNameLink">Creature</span></a> - Interface in <a href="aquarium/creatures/package-summary.html">aquarium.creatures</a></dt>
<dd>
<div class="block">A Creature inhabits an <a href="aquarium/Aquarium.html" title="class in aquarium"><code>Aquarium</code></a> and primarily has a name, location, and appearance.</div>
</dd>
</dl>
<a name="I:E">
<!-- -->
</a>
<h2 class="title">E</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#empty--">empty()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Empties the Aquarium by removing all creatures.</div>
</dd>
</dl>
<a name="I:F">
<!-- -->
</a>
<h2 class="title">F</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#fillWithCreatures--">fillWithCreatures()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Fills the Aquarium by creating and adding <a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures"><code>Creature</code></a>s.</div>
</dd>
</dl>
<a name="I:G">
<!-- -->
</a>
<h2 class="title">G</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#getAppearance--">getAppearance()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Gets the image that can be used to render this Creature's appearance.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#getAppearance--">getAppearance()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#getCreatures--">getCreatures()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Gets the creatures in the Aquarium.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#getLocation--">getLocation()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Gets the location of the center point of this Creature.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#getLocation--">getLocation()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#getName--">getName()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Gets the friendly name of this Creature.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#getName--">getName()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/AquariumPanel.html#getPreferredSize--">getPreferredSize()</a></span> - Method in class aquarium.ui.<a href="aquarium/ui/AquariumPanel.html" title="class in aquarium.ui">AquariumPanel</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#getSpeedX--">getSpeedX()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Gets the ChangingSwimmer's speed in the X direction</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#getSpeedY--">getSpeedY()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Gets the ChangingSwimmer's speed in the Y direction</div>
</dd>
</dl>
<a name="I:H">
<!-- -->
</a>
<h2 class="title">H</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#HEIGHT">HEIGHT</a></span> - Static variable in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">The height of the Aquarium's water area in pixels.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#height">height</a></span> - Variable in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#hitClouds--">hitClouds()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the Y axis when the top of the Aquarium is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#hitClouds--">hitClouds()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Event method called by the Aquarium to indicate that the Creature has touched or passed
the top of the sky area.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#hitClouds--">hitClouds()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the Y axis when the top of the Aquarium is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#hitClouds--">hitClouds()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#hitFloor--">hitFloor()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the Y axis when the floor is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#hitFloor--">hitFloor()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Event method called by the Aquarium to indicate that the Creature has touched or passed
the floor (bottom).</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#hitFloor--">hitFloor()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the Y axis when the floor is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#hitFloor--">hitFloor()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#hitLeftWall--">hitLeftWall()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the X axis when the left wall is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#hitLeftWall--">hitLeftWall()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Event method called by the Aquarium to indicate that the Creature has touched or passed
the left wall.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#hitLeftWall--">hitLeftWall()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the X axis when the left wall is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#hitLeftWall--">hitLeftWall()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#hitRightWall--">hitRightWall()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the X axis when the right wall is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#hitRightWall--">hitRightWall()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Event method called by the Aquarium to indicate that the Creature has touched or passed
the right wall.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#hitRightWall--">hitRightWall()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the X axis when the right wall is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#hitRightWall--">hitRightWall()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#hitSurface--">hitSurface()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the Y axis when the surface of the water is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#hitSurface--">hitSurface()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Event method called by the Aquarium to indicate that the Creature is touching the water's
surface.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#hitSurface--">hitSurface()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Reverses course along the Y axis when the surface of the water is hit.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#hitSurface--">hitSurface()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
</dl>
<a name="I:I">
<!-- -->
</a>
<h2 class="title">I</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#isRunning--">isRunning()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Returns true if the Aquarium simulation is running.</div>
</dd>
</dl>
<a name="I:L">
<!-- -->
</a>
<h2 class="title">L</h2>
<dl>
<dt><a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures"><span class="typeNameLink">LineSwimmer</span></a> - Class in <a href="aquarium/creatures/package-summary.html">aquarium.creatures</a></dt>
<dd>
<div class="block">A LineSwimmer is a PaintedCreature which:
Moves at a given whole integer slope speed, in a straight line;
Bounces off of the walls, the floor, and the surface of the water,
in order to stay underwater.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#LineSwimmer-java.lang.String-int-">LineSwimmer(String, int)</a></span> - Constructor for class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Creates a LineSwimmer.</div>
</dd>
</dl>
<a name="I:M">
<!-- -->
</a>
<h2 class="title">M</h2>
<dl>
<dt><span class="memberNameLink"><a href="AquariumMain.html#main-java.lang.String:A-">main(String[])</a></span> - Static method in class <a href="AquariumMain.html" title="class in <Unnamed>">AquariumMain</a></dt>
<dd>
<div class="block">The main method for the AP Aquarium.</div>
</dd>
</dl>
<a name="I:P">
<!-- -->
</a>
<h2 class="title">P</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#paint-java.awt.Graphics-">paint(Graphics)</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#paint-java.awt.Graphics-">paint(Graphics)</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#paint-java.awt.Graphics-">paint(Graphics)</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/AquariumPanel.html#paintComponent-java.awt.Graphics-">paintComponent(Graphics)</a></span> - Method in class aquarium.ui.<a href="aquarium/ui/AquariumPanel.html" title="class in aquarium.ui">AquariumPanel</a></dt>
<dd> </dd>
<dt><a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures"><span class="typeNameLink">PaintedCreature</span></a> - Class in <a href="aquarium/creatures/package-summary.html">aquarium.creatures</a></dt>
<dd>
<div class="block">A Creature which has an appearance it paints on its own.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#PaintedCreature-java.lang.String-int-int-">PaintedCreature(String, int, int)</a></span> - Constructor for class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd>
<div class="block">Creates an PaintedCreature.</div>
</dd>
</dl>
<a name="I:R">
<!-- -->
</a>
<h2 class="title">R</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#removeCreature-aquarium.creatures.Creature-">removeCreature(Creature)</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Removes a Creature from the Aquarium.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/ui/AquariumFrame.html#repaintCanvas--">repaintCanvas()</a></span> - Method in class aquarium.ui.<a href="aquarium/ui/AquariumFrame.html" title="class in aquarium.ui">AquariumFrame</a></dt>
<dd> </dd>
</dl>
<a name="I:S">
<!-- -->
</a>
<h2 class="title">S</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#setFrame-aquarium.ui.AquariumFrame-">setFrame(AquariumFrame)</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Sets the parent <a href="aquarium/ui/AquariumFrame.html" title="class in aquarium.ui"><code>AquariumFrame</code></a> for this Aquarium.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#setSpeedX-int-">setSpeedX(int)</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Sets the ChangingSwimmer's speed in the X direction
<em>Note</em>: Fish need to keep moving horizontally to survive, so an X speed of 0 is not allowed</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#setSpeedY-int-">setSpeedY(int)</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Sets the ChangingSwimmer's speed in the Y direction</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#SKY_HEIGHT">SKY_HEIGHT</a></span> - Static variable in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">The height of the Aquarium's sky area in pixels.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#start--">start()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Starts the Aquarium animation.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#stop--">stop()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Stops the Aquarium animation.</div>
</dd>
</dl>
<a name="I:U">
<!-- -->
</a>
<h2 class="title">U</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#updateCreatureLocations--">updateCreatureLocations()</a></span> - Method in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">Calls the <a href="aquarium/creatures/Creature.html#updateLocation--"><code>Creature.updateLocation()</code></a> method for each <a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures"><code>Creature</code></a> in the
Aquarium, and then calls event methods in order.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/ChangingSwimmer.html#updateLocation--">updateLocation()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/ChangingSwimmer.html" title="class in aquarium.creatures">ChangingSwimmer</a></dt>
<dd>
<div class="block">Moves the ChangingSwimmer in the amount of its given speed in both the X and Y directions.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/Creature.html#updateLocation--">updateLocation()</a></span> - Method in interface aquarium.creatures.<a href="aquarium/creatures/Creature.html" title="interface in aquarium.creatures">Creature</a></dt>
<dd>
<div class="block">Causes the Creature to move in some way.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/LineSwimmer.html#updateLocation--">updateLocation()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/LineSwimmer.html" title="class in aquarium.creatures">LineSwimmer</a></dt>
<dd>
<div class="block">Moves the LineSwimmer in the amount of its given speed in both the X and Y directions.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#updateLocation--">updateLocation()</a></span> - Method in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
</dl>
<a name="I:W">
<!-- -->
</a>
<h2 class="title">W</h2>
<dl>
<dt><span class="memberNameLink"><a href="aquarium/Aquarium.html#WIDTH">WIDTH</a></span> - Static variable in class aquarium.<a href="aquarium/Aquarium.html" title="class in aquarium">Aquarium</a></dt>
<dd>
<div class="block">The width of the Aquarium in pixels.</div>
</dd>
<dt><span class="memberNameLink"><a href="aquarium/creatures/PaintedCreature.html#width">width</a></span> - Variable in class aquarium.creatures.<a href="aquarium/creatures/PaintedCreature.html" title="class in aquarium.creatures">PaintedCreature</a></dt>
<dd> </dd>
</dl>
<a href="#I:A">A</a> <a href="#I:C">C</a> <a href="#I:E">E</a> <a href="#I:F">F</a> <a href="#I:G">G</a> <a href="#I:H">H</a> <a href="#I:I">I</a> <a href="#I:L">L</a> <a href="#I:M">M</a> <a href="#I:P">P</a> <a href="#I:R">R</a> <a href="#I:S">S</a> <a href="#I:U">U</a> <a href="#I:W">W</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?index-all.html" target="_top">Frames</a></li>
<li><a href="index-all.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| btrzcinski/apaquarium | doc/index-all.html | HTML | gpl-2.0 | 30,664 |
__author__ = 'ryanplyler'
def sayhi(config):
error = None
try:
server_output = "Executing action 'sayhi()'"
response = "HI THERE!"
except:
error = 1
return server_output, response, error
| grplyler/netcmd | netcmd_actions.py | Python | gpl-2.0 | 231 |
/*
* \brief Connection to Terminal service
* \author Norman Feske
* \date 2011-08-12
*/
/*
* Copyright (C) 2011-2013 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
#ifndef _INCLUDE__TERMINAL_SESSION__CONNECTION_H_
#define _INCLUDE__TERMINAL_SESSION__CONNECTION_H_
#include <terminal_session/client.h>
#include <base/connection.h>
namespace Terminal {
struct Connection : Genode::Connection<Session>, Session_client
{
/**
* Wait for connection-established signal
*/
static void wait_for_connection(Genode::Capability<Session> cap)
{
using namespace Genode;
/* create signal receiver, just for the single signal */
Signal_context sig_ctx;
Signal_receiver sig_rec;
Signal_context_capability sig_cap = sig_rec.manage(&sig_ctx);
/* register signal handler */
cap.call<Rpc_connected_sigh>(sig_cap);
/* wati for signal */
sig_rec.wait_for_signal();
sig_rec.dissolve(&sig_ctx);
}
Connection()
:
Genode::Connection<Session>(session("ram_quota=%zd", 2*4096)),
Session_client(cap())
{
wait_for_connection(cap());
}
};
}
#endif /* _INCLUDE__TERMINAL_SESSION__CONNECTION_H_ */
| m-stein/genode | os/include/terminal_session/connection.h | C | gpl-2.0 | 1,278 |
/*
* Copyright (C) 2008-2022 by the Widelands Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
*
*/
#ifndef WL_LOGIC_MAP_OBJECTS_TRIBES_REQUIREMENTS_H
#define WL_LOGIC_MAP_OBJECTS_TRIBES_REQUIREMENTS_H
#include <climits>
#include <map>
#include <memory>
#include <vector>
#include "logic/map_objects/tribes/training_attribute.h"
class FileRead;
class FileWrite;
namespace Widelands {
class MapObject;
class EditorGameBase;
class MapObjectLoader;
struct MapObjectSaver;
struct RequirementsStorage;
/**
* Requirements can be attached to Requests.
*
* Requirements are matched to a \ref MapObject 's \ref TrainingAttribute as
* returned by \ref MapObject::get_training_attribute .
*/
struct Requirements {
private:
struct BaseCapsule {
virtual ~BaseCapsule() {
}
virtual bool check(const MapObject&) const = 0;
virtual void write(FileWrite&, EditorGameBase&, MapObjectSaver&) const = 0;
virtual const RequirementsStorage& storage() const = 0;
};
template <typename T> struct Capsule : public BaseCapsule {
explicit Capsule(const T& init_m) : m(init_m) {
}
bool check(const MapObject& obj) const override {
return m.check(obj);
}
void write(FileWrite& fw, EditorGameBase& egbase, MapObjectSaver& mos) const override {
m.write(fw, egbase, mos);
}
const RequirementsStorage& storage() const override {
return T::storage;
}
T m;
};
public:
Requirements() {
}
template <typename T> Requirements(const T& req) : m(new Capsule<T>(req)) {
}
/**
* \return \c true if the object satisfies the requirements.
*/
bool check(const MapObject&) const;
// For Save/Load Games
void read(FileRead&, EditorGameBase&, MapObjectLoader&);
void write(FileWrite&, EditorGameBase&, MapObjectSaver&) const;
private:
std::shared_ptr<BaseCapsule> m;
};
/**
* On-disk IDs for certain requirements.
*
* Only add enums at the end, and make their value explicit.
*/
enum {
requirementIdOr = 1,
requirementIdAnd = 2,
requirementIdAttribute = 3,
};
/**
* Factory-like system for requirement loading from files.
*/
struct RequirementsStorage {
using Reader = Requirements (*)(FileRead&, EditorGameBase&, MapObjectLoader&);
RequirementsStorage(uint32_t id, Reader reader);
uint32_t id() const;
static Requirements read(FileRead&, EditorGameBase&, MapObjectLoader&);
private:
using StorageMap = std::map<uint32_t, RequirementsStorage*>;
uint32_t id_;
Reader reader_;
static StorageMap& storageMap();
};
/**
* Require that at least one of the sub-requirements added with \ref add()
* is met. Defaults to \c false if no sub-requirement is added.
*/
struct RequireOr {
void add(const Requirements&);
bool check(const MapObject&) const;
void write(FileWrite&, EditorGameBase& egbase, MapObjectSaver&) const;
static const RequirementsStorage storage;
private:
std::vector<Requirements> m;
};
/**
* Require that all sub-requirements added \ref add() are met.
* Defaults to \c true if no sub-requirement is added.
*/
struct RequireAnd {
void add(const Requirements&);
bool check(const MapObject&) const;
void write(FileWrite&, EditorGameBase& egbase, MapObjectSaver&) const;
static const RequirementsStorage storage;
private:
std::vector<Requirements> m;
};
/**
* Require that a \ref TrainingAttribute lies in the given, inclusive, range.
*/
struct RequireAttribute {
RequireAttribute(TrainingAttribute const init_at, int32_t const init_min, int32_t const init_max)
: at(init_at), min(init_min), max(init_max) {
}
RequireAttribute() : at(TrainingAttribute::kTotal), min(SHRT_MIN), max(SHRT_MAX) {
}
bool check(const MapObject&) const;
void write(FileWrite&, EditorGameBase& egbase, MapObjectSaver&) const;
static const RequirementsStorage storage;
int32_t get_min() const {
return min;
}
int32_t get_max() const {
return max;
}
private:
TrainingAttribute at;
int32_t min;
int32_t max;
};
} // namespace Widelands
#endif // end of include guard: WL_LOGIC_MAP_OBJECTS_TRIBES_REQUIREMENTS_H
| widelands/widelands | src/logic/map_objects/tribes/requirements.h | C | gpl-2.0 | 4,619 |
package org.iatoki.judgels.gabriel.blackbox.sandboxes;
import org.iatoki.judgels.gabriel.blackbox.Sandbox;
import org.iatoki.judgels.gabriel.blackbox.SandboxExecutionResult;
import org.iatoki.judgels.gabriel.blackbox.SandboxesInteractor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public final class FakeSandboxesInteractor implements SandboxesInteractor {
@Override
public SandboxExecutionResult[] executeInteraction(Sandbox sandbox1, List<String> command1, Sandbox sandbox2, List<String> command2) {
ProcessBuilder pb1 = sandbox1.getProcessBuilder(command1);
ProcessBuilder pb2 = sandbox2.getProcessBuilder(command2);
Process p1;
Process p2;
try {
p1 = pb1.start();
p2 = pb2.start();
} catch (IOException e) {
return new SandboxExecutionResult[]{
SandboxExecutionResult.internalError(e.getMessage()),
SandboxExecutionResult.internalError(e.getMessage())
};
}
InputStream p1InputStream = p1.getInputStream();
OutputStream p1OutputStream = p1.getOutputStream();
InputStream p2InputStream = p2.getInputStream();
OutputStream p2OutputStream = p2.getOutputStream();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new UnidirectionalPipe(p1InputStream, p2OutputStream));
executor.submit(new UnidirectionalPipe(p2InputStream, p1OutputStream));
int exitCode1 = 0;
int exitCode2 = 0;
try {
exitCode2 = p2.waitFor();
exitCode1 = p1.waitFor();
} catch (InterruptedException e) {
return new SandboxExecutionResult[]{
SandboxExecutionResult.internalError(e.getMessage()),
SandboxExecutionResult.internalError(e.getMessage())
};
}
return new SandboxExecutionResult[]{
sandbox1.getResult(exitCode1),
sandbox2.getResult(exitCode2)
};
}
}
class UnidirectionalPipe implements Runnable {
private final InputStream in;
private final OutputStream out;
public UnidirectionalPipe(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
try {
while (true) {
byte[] buffer = new byte[4096];
int len = in.read(buffer);
if (len == -1) {
break;
}
out.write(buffer, 0, len);
out.flush();
}
in.close();
out.close();
} catch (IOException e) {
}
}
} | ia-toki/judgels-gabriel-commons | src/main/java/org/iatoki/judgels/gabriel/blackbox/sandboxes/FakeSandboxesInteractor.java | Java | gpl-2.0 | 2,878 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.