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
/* Copyright (c) 2013-2014, The Linux Foundation. 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 version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/cpu.h> #include <linux/sysfs.h> #include <linux/cpufreq.h> #include <linux/jiffies.h> #include <linux/percpu.h> #include <linux/kobject.h> #include <linux/spinlock.h> #include <linux/notifier.h> #include <linux/bitops.h> #include <linux/stat.h> #include <asm/cputime.h> #include <linux/module.h> #define MAX_CPUATTR_NAME_LEN (16) #define MAX_CPU_STATS_LINE_LEN (64) static spinlock_t cpufreq_stats_lock; static unsigned int stats_collection_enabled = 1; static const char *time_in_state_attr_name = "time_in_state"; struct cpu_persistent_stats { /* CPU name, e.g. cpu0 */ char name[MAX_CPUATTR_NAME_LEN]; /* the number identifying this CPU */ unsigned int cpu_id; /* * the last time stats were * updated for this CPU */ unsigned long long last_time; /* * the number of frequencies available * to this CPU */ unsigned int max_state; /* * the index corresponding to * the frequency (from freq_table) that this CPU * last ran at */ unsigned int last_index; /* * the kobject corresponding to * this CPU */ struct kobject cpu_persistent_stat_kobj; /* * a table holding the cumulative time * (in jiffies) spent by this CPU at * frequency freq_table[i] */ cputime64_t *time_in_state; /* * a table holding the frequencies this CPU * can run at */ unsigned int *freq_table; }; struct cpufreq_persistent_stats { char name[MAX_CPUATTR_NAME_LEN]; struct kobject *persistent_stats_kobj; } persistent_stats = { .name = "stats", }; static DEFINE_PER_CPU(struct cpu_persistent_stats, pcpu_stats); static struct attribute cpu_time_in_state_attr[NR_CPUS]; static int cpufreq_stats_update(unsigned int cpu) { unsigned long long cur_time; struct cpu_persistent_stats *cpu_stats = &per_cpu(pcpu_stats, cpu); if (!stats_collection_enabled) return 0; if (cpu_stats->last_time) { cur_time = get_jiffies_64(); if (likely(cpu_stats->time_in_state)) cpu_stats->time_in_state[cpu_stats->last_index] = cpu_stats->time_in_state[cpu_stats->last_index] + (cur_time - cpu_stats->last_time); cpu_stats->last_time = cur_time; } return 0; } static void reset_stats(void) { unsigned int cpu; unsigned long irq_flags; struct cpu_persistent_stats *cpux_persistent_stats; spin_lock_irqsave(&cpufreq_stats_lock, irq_flags); for_each_possible_cpu(cpu) { cpux_persistent_stats = &per_cpu(pcpu_stats, cpu); if (cpux_persistent_stats->freq_table && cpux_persistent_stats->time_in_state) { int i; for (i = 0; i < cpux_persistent_stats->max_state; i++) cpux_persistent_stats->time_in_state[i] = 0ULL; } } spin_unlock_irqrestore(&cpufreq_stats_lock, irq_flags); } static int freq_table_get_index( struct cpu_persistent_stats *stats, unsigned int freq) { int index; if (stats->freq_table) { for (index = 0; index < stats->max_state; index++) if (stats->freq_table[index] == freq) return index; } return -ENOENT; } static void cpufreq_stats_free_table(unsigned int cpu) { unsigned long irq_flags; struct cpu_persistent_stats *cpu_stats = &per_cpu(pcpu_stats, cpu); spin_lock_irqsave(&cpufreq_stats_lock, irq_flags); kfree(cpu_stats->time_in_state); cpu_stats->time_in_state = NULL; cpu_stats->freq_table = NULL; spin_unlock_irqrestore(&cpufreq_stats_lock, irq_flags); } static int cpufreq_stats_create_table(unsigned int cpu, struct cpufreq_policy *policy) { unsigned int i, k, count = 0; unsigned int alloc_size; struct cpu_persistent_stats *cpu_stats = &per_cpu(pcpu_stats, cpu); unsigned long irq_flags; struct cpufreq_frequency_table *table = cpufreq_frequency_get_table(policy->cpu); void *temp_time_in_state; int next_freq_index; if (unlikely(!table)) return -EINVAL; if (likely(cpu_stats->time_in_state)) return -EBUSY; for (i = 0; table[i].frequency != CPUFREQ_TABLE_END; i++) { unsigned int freq = table[i].frequency; if (freq == CPUFREQ_ENTRY_INVALID) continue; count++; } alloc_size = count * sizeof(int) + count * sizeof(cputime64_t); temp_time_in_state = kzalloc(alloc_size, GFP_KERNEL); if (!temp_time_in_state) return -ENOMEM; spin_lock_irqsave(&cpufreq_stats_lock, irq_flags); if (!cpu_stats->time_in_state) { cpu_stats->time_in_state = temp_time_in_state; cpu_stats->max_state = count; cpu_stats->freq_table = (unsigned int *)(cpu_stats->time_in_state + count); k = 0; for (i = 0; table[i].frequency != CPUFREQ_TABLE_END; i++) { unsigned int freq = table[i].frequency; if (freq == CPUFREQ_ENTRY_INVALID) continue; cpu_stats->freq_table[k++] = freq; } } else kfree(temp_time_in_state); next_freq_index = freq_table_get_index( cpu_stats, policy->cur); if (next_freq_index != -ENOENT) { cpu_stats->last_time = get_jiffies_64(); cpu_stats->last_index = next_freq_index; } spin_unlock_irqrestore(&cpufreq_stats_lock, irq_flags); return 0; } static int cpufreq_stat_notifier_trans(struct notifier_block *nb, unsigned long val, void *data) { struct cpufreq_freqs *freq = data; struct cpufreq_policy *policy; static unsigned int table_created_count; struct cpu_persistent_stats *cpu_stats = &per_cpu(pcpu_stats, freq->cpu); unsigned long irq_flags; unsigned int cpu; int next_freq_index; if (val != CPUFREQ_POSTCHANGE) return 0; policy = cpufreq_cpu_get(freq->cpu); if (!policy) return 0; if (table_created_count < num_possible_cpus()) { for_each_cpu(cpu, policy->cpus) { if (cpufreq_stats_create_table(cpu, policy) == 0) table_created_count++; } } spin_lock_irqsave(&cpufreq_stats_lock, irq_flags); for_each_cpu(cpu, policy->cpus) { cpu_stats = &per_cpu(pcpu_stats, cpu); next_freq_index = freq_table_get_index(cpu_stats, freq->new); if (next_freq_index != -ENOENT) { if (cpu_online(cpu)) { cpufreq_stats_update(cpu); cpu_stats->last_time = get_jiffies_64(); } cpu_stats->last_index = next_freq_index; } } spin_unlock_irqrestore(&cpufreq_stats_lock, irq_flags); cpufreq_cpu_put(policy); return 0; } static int cpufreq_stat_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned int cpu = (unsigned long)hcpu; struct cpu_persistent_stats *cpu_stats = &per_cpu(pcpu_stats, cpu); unsigned long flags; spin_lock_irqsave(&cpufreq_stats_lock, flags); switch (action) { case CPU_ONLINE: case CPU_ONLINE_FROZEN: cpu_stats->last_time = get_jiffies_64(); break; case CPU_DEAD: case CPU_DEAD_FROZEN: cpufreq_stats_update(cpu); cpu_stats->last_time = 0; break; } spin_unlock_irqrestore(&cpufreq_stats_lock, flags); return NOTIFY_OK; } /************************** sysfs interface ************************/ static ssize_t show_cpu_time_in_state(struct kobject *kobj, struct attribute *attr, char *buf) { /* * The container of kobj is of type cpu_persistent_stats * so we can use it to get the cpu ID corresponding to this attribute. */ int len = 0, i; unsigned long irq_flags; struct cpu_persistent_stats *cpux_persistent_stats = container_of(kobj, struct cpu_persistent_stats, cpu_persistent_stat_kobj); spin_lock_irqsave(&cpufreq_stats_lock, irq_flags); cpufreq_stats_update(cpux_persistent_stats->cpu_id); if (cpux_persistent_stats->time_in_state) { for (i = 0; i < cpux_persistent_stats->max_state; i++) { cputime64_t time_in_state = cpux_persistent_stats->time_in_state[i]; s64 clocktime_in_state = cputime64_to_clock_t(time_in_state); len += snprintf(buf + len, MAX_CPU_STATS_LINE_LEN, "%u %lld\n", cpux_persistent_stats->freq_table[i], clocktime_in_state); } } spin_unlock_irqrestore(&cpufreq_stats_lock, irq_flags); return len; } static ssize_t store_reset(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret, input; ret = sscanf(buf, "%d", &input); if (ret < 0) return -EINVAL; if (input) reset_stats(); return count; } static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return snprintf(buf, 2, "%u\n", !!stats_collection_enabled); } static ssize_t store_enable(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret, input; unsigned int cpu; unsigned long irq_flags; ret = sscanf(buf, "%d", &input); if (ret < 0) return -EINVAL; if (!!input == stats_collection_enabled) return count; if (input && !stats_collection_enabled) { spin_lock_irqsave(&cpufreq_stats_lock, irq_flags); for_each_possible_cpu(cpu) { if (per_cpu(pcpu_stats, cpu).last_time) per_cpu(pcpu_stats, cpu).last_time = get_jiffies_64(); } spin_unlock_irqrestore(&cpufreq_stats_lock, irq_flags); } stats_collection_enabled = !!input; return count; } static const struct sysfs_ops cpu_time_in_state_ops = { .show = show_cpu_time_in_state, }; static struct kobj_attribute reset_attr = __ATTR(reset, 0220, NULL, store_reset); static struct kobj_attribute enable_attr = __ATTR(enable, S_IRUGO|S_IWUSR, show_enabled, store_enable); static int create_persistent_stats_groups(void) { unsigned int cpu_id; int ret; struct cpu_persistent_stats *cpu_stats; /* Create toplevel persistent stats kobject. */ ret = cpufreq_get_global_kobject(); if (ret) return ret; persistent_stats.persistent_stats_kobj = kobject_create_and_add(persistent_stats.name, cpufreq_global_kobject); if (!persistent_stats.persistent_stats_kobj) { pr_err("%s: Unable to create persistent_stats_kobj.\n", __func__); ret = -EINVAL; goto abort_stats_kobj_create_failed; } ret = sysfs_create_file( persistent_stats.persistent_stats_kobj, &enable_attr.attr); if (ret) { pr_err("%s: Unable to create enable_attr\n", __func__); goto abort_enable_attr_create_failed; } ret = sysfs_create_file( persistent_stats.persistent_stats_kobj, &reset_attr.attr); if (ret) { pr_err("%s: Unable to create reset_attr\n", __func__); goto abort_reset_attr_create_failed; } /* Create kobjects and add them to persistent_stats_kobj */ for_each_possible_cpu(cpu_id) { memset(&cpu_time_in_state_attr[cpu_id], 0, sizeof(struct attribute)); cpu_stats = &per_cpu(pcpu_stats, cpu_id); snprintf(cpu_stats->name, MAX_CPUATTR_NAME_LEN, "cpu%u", cpu_id); cpu_time_in_state_attr[cpu_id].name = time_in_state_attr_name; cpu_time_in_state_attr[cpu_id].mode = S_IRUGO; cpu_stats->cpu_id = cpu_id; cpu_stats->cpu_persistent_stat_kobj.ktype = kzalloc(sizeof(struct kobj_type), GFP_KERNEL); if (!cpu_stats->cpu_persistent_stat_kobj.ktype) { ret = -ENOMEM; goto abort_cpu_persistent_stats_create_failed; } ret = kobject_init_and_add( &cpu_stats->cpu_persistent_stat_kobj, cpu_stats->cpu_persistent_stat_kobj.ktype, persistent_stats.persistent_stats_kobj, cpu_stats->name); if (ret) { pr_err("%s: Failed to create persistent stats node for cpu%u\n", __func__, cpu_id); goto abort_cpu_persistent_stats_create_failed; } cpu_stats->cpu_persistent_stat_kobj.ktype->sysfs_ops = &cpu_time_in_state_ops; ret = sysfs_create_file( &cpu_stats->cpu_persistent_stat_kobj, &cpu_time_in_state_attr[cpu_id]); if (ret) { pr_err("%s: sys_create_file failed.\n", __func__); goto abort_cpu_persistent_stats_create_failed; } } return 0; abort_cpu_persistent_stats_create_failed: /* Remove all CPU entries and the root persistent_stats entry */ for_each_possible_cpu(cpu_id) { cpu_stats = &per_cpu(pcpu_stats, cpu_id); sysfs_remove_file( &cpu_stats->cpu_persistent_stat_kobj, &cpu_time_in_state_attr[cpu_id]); kfree(cpu_stats->cpu_persistent_stat_kobj.ktype); kobject_put(&cpu_stats->cpu_persistent_stat_kobj); } abort_reset_attr_create_failed: sysfs_remove_file(persistent_stats.persistent_stats_kobj, &enable_attr.attr); abort_enable_attr_create_failed: kobject_put(persistent_stats.persistent_stats_kobj); abort_stats_kobj_create_failed: cpufreq_put_global_kobject(); return ret; } /* * Remove the persistent stats groups created at this driver's init time. */ static void remove_persistent_stats_groups(void) { int cpu_id = 0; struct cpu_persistent_stats *cpu_stats; for (cpu_id = 0; cpu_id < num_possible_cpus(); cpu_id++) { cpu_stats = &per_cpu(pcpu_stats, cpu_id); sysfs_remove_file( &cpu_stats->cpu_persistent_stat_kobj, &cpu_time_in_state_attr[cpu_id]); kfree(cpu_stats->cpu_persistent_stat_kobj.ktype); kobject_put(&cpu_stats->cpu_persistent_stat_kobj); } /* Remove the root persistent stats kobject. */ kobject_put(persistent_stats.persistent_stats_kobj); cpufreq_put_global_kobject(); } static struct notifier_block cpufreq_stat_cpu_notifier __refdata = { .notifier_call = cpufreq_stat_cpu_callback, }; static struct notifier_block notifier_trans_block = { .notifier_call = cpufreq_stat_notifier_trans }; static int __init cpufreq_persistent_stats_init(void) { int ret = 0; spin_lock_init(&cpufreq_stats_lock); ret = cpufreq_register_notifier(&notifier_trans_block, CPUFREQ_TRANSITION_NOTIFIER); if (ret) return ret; ret = register_hotcpu_notifier(&cpufreq_stat_cpu_notifier); if (ret) goto abort_register_hotcpu_failed; ret = create_persistent_stats_groups(); if (ret) goto abort_create_stats_group_failed; return 0; abort_create_stats_group_failed: unregister_hotcpu_notifier(&cpufreq_stat_cpu_notifier); abort_register_hotcpu_failed: cpufreq_unregister_notifier(&notifier_trans_block, CPUFREQ_TRANSITION_NOTIFIER); return ret; } static void __exit cpufreq_persistent_stats_exit(void) { unsigned int cpu; cpufreq_unregister_notifier(&notifier_trans_block, CPUFREQ_TRANSITION_NOTIFIER); unregister_hotcpu_notifier(&cpufreq_stat_cpu_notifier); for_each_possible_cpu(cpu) cpufreq_stats_free_table(cpu); remove_persistent_stats_groups(); } MODULE_DESCRIPTION("Persists CPUFreq stats across CPU hotplugs."); MODULE_LICENSE("GPL"); module_init(cpufreq_persistent_stats_init); module_exit(cpufreq_persistent_stats_exit);
deadman96385/android_kernel_nextbit_msm8992
drivers/cpufreq/cpufreq_persistent_stats.c
C
gpl-2.0
14,594
#!/usr/bin/env python3 # encoding: utf-8 """ This parser uses the --preprocess option of wesnoth so a working wesnoth executable must be available at runtime if the WML to parse contains preprocessing directives. Pure WML can be parsed as is. For example: wml = "" [unit] id=elve name=Elve [abilities] [damage] id=Ensnare [/dama ge] [/abilities] [/unit] "" p = Parser() cfg = p.parse_text(wml) for unit in cfg.get_all(tag = "unit"): print(unit.get_text_val("id")) print(unit.get_text_val("name")) for abilities in unit.get_all(tag = "abilitities"): for ability in abilities.get_all(tag = ""): print(ability.get_name()) print(ability.get_text_val("id")) Because no preprocessing is required, we did not have to pass the location of the wesnoth executable to Parser. The get_all method always returns a list over matching tags or attributes. The get_name method can be used to get the name and the get_text_val method can be used to query the value of an attribute. """ import os, glob, sys, re, subprocess, argparse, tempfile, shutil import atexit tempdirs_to_clean = [] tmpfiles_to_clean = [] @atexit.register def cleaner(): for temp_dir in tempdirs_to_clean: shutil.rmtree(temp_dir, ignore_errors=True) for temp_file in tmpfiles_to_clean: os.remove(temp_file) class WMLError(Exception): """ Catch this exception to retrieve the first error message from the parser. """ def __init__(self, parser=None, message=None): if parser: self.line = parser.parser_line self.wml_line = parser.last_wml_line self.message = message self.preprocessed = parser.preprocessed def __str__(self): return """WMLError: %s %s %s %s """ % (str(self.line), self.preprocessed, self.wml_line, self.message) class StringNode: """ One part of an attribute's value. Because a single WML string can be made from multiple translatable strings we model it as a list of several StringNode each with its own text domain. """ def __init__(self, data: bytes): self.textdomain = None # non-translatable by default self.data = data def wml(self) -> bytes: if not self.data: return b"" return self.data def debug(self): if self.textdomain: return "_<%s>'%s'" % (self.textdomain, self.data.decode("utf8", "ignore")) else: return "'%s'" % self.data.decode("utf8", "ignore") def __str__(self): return "StringNode({})".format(self.debug()) def __repr__(self): return str(self) class AttributeNode: """ A WML attribute. For example the "id=Elfish Archer" in: [unit] id=Elfish Archer [/unit] """ def __init__(self, name, location=None): self.name = name self.location = location self.value = [] # List of StringNode def wml(self) -> bytes: s = self.name + b"=\"" for v in self.value: s += v.wml().replace(b"\"", b"\"\"") s += b"\"" return s def debug(self): return self.name.decode("utf8") + "=" + " .. ".join( [v.debug() for v in self.value]) def get_text(self, translation=None) -> str: """ Returns a text representation of the node's value. The translation callback, if provided, will be called on each partial string with the string and its corresponding textdomain and the returned translation will be used. """ r = "" for s in self.value: ustr = s.data.decode("utf8", "ignore") if translation: r += translation(ustr, s.textdomain) else: r += ustr return r def get_binary(self): """ Returns the unmodified binary representation of the value. """ r = b"" for s in self.value: r += s.data return r def get_name(self): return self.name.decode("utf8") def __str__(self): return "AttributeNode({})".format(self.debug()) def __repr__(self): return str(self) class TagNode: """ A WML tag. For example the "unit" in this example: [unit] id=Elfish Archer [/unit] """ def __init__(self, name, location=None): self.name = name self.location = location # List of child elements, which are either of type TagNode or # AttributeNode. self.data = [] self.speedy_tags = {} def wml(self) -> bytes: """ Returns a (binary) WML representation of the entire node. All attribute values are enclosed in quotes and quotes are escaped (as double quotes). Note that no other escaping is performed (see the BinaryWML specification for additional escaping you may require). """ s = b"[" + self.name + b"]\n" for sub in self.data: s += sub.wml() + b"\n" s += b"[/" + self.name.lstrip(b'+') + b"]\n" return s def debug(self): s = "[%s]\n" % self.name.decode("utf8") for sub in self.data: for subline in sub.debug().splitlines(): s += " %s\n" % subline s += "[/%s]\n" % self.name.decode("utf8").lstrip('+') return s def get_all(self, **kw): """ This gets all child tags or child attributes of the tag. For example: [unit] name=A name=B [attack] [/attack] [attack] [/attack] [/unit] unit.get_all(att = "name") will return two nodes for "name=A" and "name=B" unit.get_all(tag = "attack") will return two nodes for the two [attack] tags. unit.get_all() will return 4 nodes for all 4 sub-elements. unit.get_all(att = "") Will return the two attribute nodes. unit.get_all(tag = "") Will return the two tag nodes. If no elements are found an empty list is returned. """ if len(kw) == 1 and "tag" in kw and kw["tag"]: return self.speedy_tags.get(kw["tag"].encode("utf8"), []) r = [] for sub in self.data: ok = True for k, v in list(kw.items()): v = v.encode("utf8") if k == "tag": if not isinstance(sub, TagNode): ok = False elif v != b"" and sub.name != v: ok = False elif k == "att": if not isinstance(sub, AttributeNode): ok = False elif v != b"" and sub.name != v: ok = False if ok: r.append(sub) return r def get_text_val(self, name, default=None, translation=None, val=-1): """ Returns the value of the specified attribute. If the attribute is given multiple times, the value number val is returned (default behaviour being to return the last value). If the attribute is not found, the default parameter is returned. If a translation is specified, it should be a function which when passed a unicode string and text-domain returns a translation of the unicode string. The easiest way is to pass it to gettext.translation if you have the binary message catalogues loaded. """ x = self.get_all(att=name) if not x: return default return x[val].get_text(translation) def get_binary(self, name, default=None): """ Returns the unmodified binary data for the first attribute of the given name or the passed default value if it is not found. """ x = self.get_all(att=name) if not x: return default return x[0].get_binary() def append(self, node): """ Appends a child node (must be either a TagNode or AttributeNode). """ self.data.append(node) if isinstance(node, TagNode): if node.name not in self.speedy_tags: self.speedy_tags[node.name] = [] self.speedy_tags[node.name].append(node) def get_name(self): return self.name.decode("utf8") def __str__(self): return "TagNode({})".format(self.get_name()) def __repr__(self): return str(self) class RootNode(TagNode): """ The root node. There is exactly one such node. """ def __init__(self): TagNode.__init__(self, None) def debug(self): s = "" for sub in self.data: for subline in sub.debug().splitlines(): s += subline + "\n" return s def __str__(self): return "RootNode()" def __repr__(self): return str(self) class Parser: def __init__(self, wesnoth_exe=None, config_dir=None, data_dir=None): """ wesnoth_exe - Wesnoth executable to use. This should have been configured to use the desired data and config directories. config_dir - The Wesnoth configuration directory, can be None to use the wesnoth default. data_dir - The Wesnoth data directory, can be None to use the wesnoth default. After parsing is done the root node of the result will be in the root attribute. """ self.wesnoth_exe = wesnoth_exe self.config_dir = None if config_dir: self.config_dir = os.path.abspath(config_dir) self.data_dir = None if data_dir: self.data_dir = os.path.abspath(data_dir) self.keep_temp_dir = None self.temp_dir = None self.no_preprocess = (wesnoth_exe is None) self.preprocessed = None self.verbose = False self.last_wml_line = "?" self.parser_line = 0 self.line_in_file = 42424242 self.chunk_start = "?" def parse_file(self, path, defines="") -> RootNode: """ Parse the given file found under path. """ self.path = path if not self.no_preprocess: self.preprocess(defines) return self.parse() def parse_binary(self, binary: bytes, defines="") -> RootNode: """ Parse a chunk of binary WML. """ td, tmpfilePath = tempfile.mkstemp(prefix="wmlparser_", suffix=".cfg") with open(tmpfilePath, 'wb') as temp: temp.write(binary) os.close(td) self.path = tmpfilePath tmpfiles_to_clean.append(tmpfilePath) if not self.no_preprocess: self.preprocess(defines) return self.parse() def parse_text(self, text, defines="") -> RootNode: """ Parse a text string. """ return self.parse_binary(text.encode("utf8"), defines) def preprocess(self, defines): """ This is called by the parse functions to preprocess the input from a normal WML .cfg file into a preprocessed .plain file. """ if self.keep_temp_dir: output = self.keep_temp_dir else: output = tempfile.mkdtemp(prefix="wmlparser_") tempdirs_to_clean.append(output) self.temp_dir = output commandline = [self.wesnoth_exe] if self.data_dir: commandline += ["--data-dir", self.data_dir] if self.config_dir: commandline += ["--config-dir", self.config_dir] commandline += ["--preprocess", self.path, output] if defines: commandline += ["--preprocess-defines", defines] if self.verbose: print((" ".join(commandline))) p = subprocess.Popen(commandline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if self.verbose: print((out + err).decode("utf8")) self.preprocessed = output + "/" + os.path.basename(self.path) + \ ".plain" if not os.path.exists(self.preprocessed): first_line = open(self.path).readline().strip() raise WMLError(self, "Preprocessor error:\n" + " ".join(commandline) + "\n" + "First line: " + first_line + "\n" + out.decode("utf8") + err.decode("utf8")) def parse_line_without_commands_loop(self, line: str) -> str: """ Once the .plain commands are handled WML lines are passed to this. """ if not line: return if line.strip(): self.skip_newlines_after_plus = False if self.in_tag: self.handle_tag(line) return if self.in_arrows: arrows = line.find(b'>>') if arrows >= 0: self.in_arrows = False self.temp_string += line[:arrows] self.temp_string_node = StringNode(self.temp_string) self.temp_string = b"" self.temp_key_nodes[self.commas].value.append( self.temp_string_node) self.in_arrows = False return line[arrows + 2:] else: self.temp_string += line return quote = line.find(b'"') if not self.in_string: arrows = line.find(b'<<') if arrows >= 0 and (quote < 0 or quote > arrows): self.parse_line_without_commands(line[:arrows]) self.in_arrows = True return line[arrows + 2:] if quote >= 0: if self.in_string: # double quote if quote < len(line) - 1 and line[quote + 1] == b'"'[0]: self.temp_string += line[:quote + 1] return line[quote + 2:] self.temp_string += line[:quote] self.temp_string_node = StringNode(self.temp_string) if self.translatable: self.temp_string_node.textdomain = self.textdomain self.translatable = False self.temp_string = b"" if not self.temp_key_nodes: raise WMLError(self, "Unexpected string value.") self.temp_key_nodes[self.commas].value.append( self.temp_string_node) self.in_string = False return line[quote + 1:] else: self.parse_outside_strings(line[:quote]) self.in_string = True return line[quote + 1:] else: if self.in_string: self.temp_string += line else: self.parse_outside_strings(line) def parse_line_without_commands(self, line): while True: line = self.parse_line_without_commands_loop(line) if not line: break def parse_outside_strings(self, line): """ Parse a WML fragment outside of strings. """ if not line: return if line.lstrip(b" \t").startswith(b"#textdomain "): self.textdomain = line.lstrip(b" \t")[12:].strip().decode("utf8") return if not self.temp_key_nodes: line = line.lstrip() if not line: return # Is it a tag? if line.startswith(b"["): self.handle_tag(line) # No tag, must be an attribute. else: self.handle_attribute(line) else: for i, segment in enumerate(line.split(b"+")): segment = segment.lstrip(b" \t") if i > 0: # If the last segment is empty (there was a plus sign # at the end) we need to skip newlines. self.skip_newlines_after_plus = not segment.strip() if not segment: continue if segment.rstrip(b" ") == b"_": self.translatable = True segment = segment[1:].lstrip(b" ") if not segment: continue self.handle_value(segment) def handle_tag(self, line): end = line.find(b"]") if end < 0: if line.endswith(b"\n"): raise WMLError(self, "Expected closing bracket.") self.in_tag += line return tag = (self.in_tag + line[:end])[1:] self.in_tag = b"" if tag.startswith(b"/"): self.parent_node = self.parent_node[:-1] elif tag.startswith(b"+") and self.parent_node and self.parent_node[-1].get_all(tag=tag[1:].decode()): node_to_append_to = self.parent_node[-1].get_all(tag=tag[1:].decode())[-1] self.parent_node.append(node_to_append_to) else: node = TagNode(tag, location=(self.line_in_file, self.chunk_start)) if self.parent_node: self.parent_node[-1].append(node) self.parent_node.append(node) self.parse_outside_strings(line[end + 1:]) def handle_attribute(self, line): assign = line.find(b"=") remainder = None if assign >= 0: remainder = line[assign + 1:] line = line[:assign] self.commas = 0 self.temp_key_nodes = [] for att in line.split(b","): att = att.strip() node = AttributeNode(att, location=(self.line_in_file, self.chunk_start)) self.temp_key_nodes.append(node) if self.parent_node: self.parent_node[-1].append(node) if remainder: self.parse_outside_strings(remainder) def handle_value(self, segment): def add_text(segment): segment = segment.rstrip() if not segment: return n = len(self.temp_key_nodes) maxsplit = n - self.commas - 1 if maxsplit < 0: maxsplit = 0 for subsegment in segment.split(b",", maxsplit): self.temp_string += subsegment.strip() self.temp_string_node = StringNode(self.temp_string) self.temp_string = b"" self.temp_key_nodes[self.commas].value.append( self.temp_string_node) if self.commas < n - 1: self.commas += 1 # Finish assignment on newline, except if there is a # plus sign before the newline. add_text(segment) if segment.endswith(b"\n") and not self.skip_newlines_after_plus: self.temp_key_nodes = [] def parse(self) -> RootNode: """ Parse preprocessed WML into a tree of tags and attributes. """ # parsing state self.temp_string = b"" self.temp_string_node = None self.commas = 0 self.temp_key_nodes = [] self.in_string = False self.in_arrows = False self.textdomain = "wesnoth" self.translatable = False self.root = RootNode() self.parent_node = [self.root] self.skip_newlines_after_plus = False self.in_tag = b"" command_marker_byte = bytes([254]) input = self.preprocessed if not input: input = self.path for rawline in open(input, "rb"): compos = rawline.find(command_marker_byte) self.parser_line += 1 # Everything from chr(254) to newline is the command. if compos != 0: self.line_in_file += 1 if compos >= 0: self.parse_line_without_commands(rawline[:compos]) self.handle_command(rawline[compos + 1:-1]) else: self.parse_line_without_commands(rawline) if self.keep_temp_dir is None and self.temp_dir: if self.verbose: print(("removing " + self.temp_dir)) shutil.rmtree(self.temp_dir, ignore_errors=True) return self.root def handle_command(self, com): if com.startswith(b"line "): self.last_wml_line = com[5:] _ = self.last_wml_line.split(b" ") self.chunk_start = [(_[i + 1], int(_[i])) for i in range(0, len(_), 2)] self.line_in_file = self.chunk_start[0][1] elif com.startswith(b"textdomain "): self.textdomain = com[11:].decode("utf8") else: raise WMLError(self, "Unknown parser command: " + com) def get_all(self, **kw): return self.root.get_all(**kw) def get_text_val(self, name, default=None, translation=None): return self.root.get_text_val(name, default, translation) def jsonify(tree, verbose=False, depth=1): """ Convert a Parser tree into JSON If verbose, insert a linebreak after every brace and comma (put every item on its own line), otherwise, condense everything into a single line. """ import json def node_to_dict(n): d = {} tags = set(x.get_name() for x in n.get_all(tag="")) for tag in tags: d[tag] = [node_to_dict(x) for x in n.get_all(tag=tag)] for att in n.get_all(att=""): d[att.get_name()] = att.get_text() return d print(json.dumps(node_to_dict(tree), indent=depth if verbose else None)) def xmlify(tree, verbose=False, depth=0): import xml.etree.ElementTree as ET def node_to_et(n): et = ET.Element(n.get_name()) for att in n.get_all(att=""): attel = ET.Element(att.get_name()) attel.text = att.get_text() et.append(attel) for tag in n.get_all(tag=""): et.append(node_to_et(tag)) return et ET.ElementTree(node_to_et(tree.get_all()[0])).write( sys.stdout, encoding="unicode") if __name__ == "__main__": arg = argparse.ArgumentParser() arg.add_argument("-a", "--data-dir", help="directly passed on to wesnoth.exe") arg.add_argument("-c", "--config-dir", help="directly passed on to wesnoth.exe") arg.add_argument("-i", "--input", help="a WML file to parse") arg.add_argument("-k", "--keep-temp", help="specify directory where to keep temp files") arg.add_argument("-t", "--text", help="WML text to parse") arg.add_argument("-w", "--wesnoth", help="path to wesnoth.exe") arg.add_argument("-d", "--defines", help="comma separated list of WML defines") arg.add_argument("-T", "--test", action="store_true") arg.add_argument("-j", "--to-json", action="store_true") arg.add_argument("-v", "--verbose", action="store_true") arg.add_argument("-x", "--to-xml", action="store_true") args = arg.parse_args() if not args.input and not args.text and not args.test: sys.stderr.write("No input given. Use -h for help.\n") sys.exit(1) if (args.wesnoth and not os.path.exists(args.wesnoth)): sys.stderr.write("Wesnoth executable not found.\n") sys.exit(1) if not args.wesnoth: print("Warning: Without the -w option WML is not preprocessed!", file=sys.stderr) if args.test: print("Running tests") p = Parser(args.wesnoth, args.config_dir, args.data_dir) if args.keep_temp: p.keep_temp_dir = args.keep_temp if args.verbose: p.verbose = True only = None def test2(input, expected, note, function): if only and note != only: return input = input.strip() expected = expected.strip() p.parse_text(input) output = function(p).strip() if output != expected: print("__________") print(("FAILED " + note)) print("INPUT:") print(input) print("OUTPUT:") print(output) print("EXPECTED:") print(expected) print("__________") else: print(("PASSED " + note)) def test(input, expected, note): test2(input, expected, note, lambda p: p.root.debug()) def test_with_preprocessor(input, expected, note): if not args.wesnoth: print("SKIPPED WITHOUT PREPROCESSOR " + note) return test(input, expected, note) test( """ [test] a=1 [/test] """, """ [test] a='1' [/test] """, "simple") test( """ [+foo] a=1 [/foo] """, """ [+foo] a='1' [/foo] """, "+foo without foo in toplevel") test( """ [foo] [+bar] a=1 [/bar] [/foo] """, """ [foo] [+bar] a='1' [/bar] [/foo] """, "+foo without foo in child") test( """ [test] [foo] a=1 [/foo] [/test] """, """ [test] [foo] a='1' [/foo] [/test] """, "subtag, part 1") test( """ [test] [foo] a=1 [/foo] [/test] [+test] [+foo] [/foo] [/test] """, """ [test] [foo] a='1' [/foo] [/test] """, "subtag, part 2") test( """ [test] a, b, c = 1, 2, 3 [/test] """, """ [test] a='1' b='2' c='3' [/test] """, "multi assign") test( """ [test] a, b = 1, 2, 3 [/test] """, """ [test] a='1' b='2, 3' [/test] """, "multi assign 2") test( """ [test] a, b, c = 1, 2 [/test] """, """ [test] a='1' b='2' c= [/test] """, "multi assign 3") test_with_preprocessor( """ #textdomain A #define X _ "abc" #enddef #textdomain B [test] x = _ "abc" + {X} [/test] """, """ [test] x=_<B>'abc' .. _<A>'abc' [/test] """, "textdomain") test( """ [test] x,y = _1,_2 [/test] """, """ [test] x='_1' y='_2' [/test] """, "underscores") test( """ [test] a = "a ""quoted"" word" [/test] """, """ [test] a='a "quoted" word' [/test] """, "quoted") test( """ [test] code = << "quotes" here ""blah"" >> [/test] """, """ [test] code=' "quotes" here ""blah"" ' [/test] """, "quoted2") test( """ foo="bar"+ "baz" """, """ foo='bar' .. 'baz' """, "multi line string") test_with_preprocessor( """ #define baz "baz" #enddef foo="bar"+{baz} """, """ foo='bar' .. 'baz' """, "defined multi line string") test_with_preprocessor( """ foo="bar" + "baz" # blah """, """ foo='bar' .. 'baz' """, "comment after +") test_with_preprocessor( """ #define baz "baz" #enddef foo="bar" {baz} """, """ foo='bar' .. 'baz' """, "defined string concatenation") test_with_preprocessor( """ #define A BLOCK [{BLOCK}] [/{BLOCK}] #enddef {A blah} """, """ [blah] [/blah] """, "defined tag") test2( """ [test] a=1 b=2 a=3 b=4 [/test] """, "3, 4", "multiatt", lambda p: p.get_all(tag = "test")[0].get_text_val("a") + ", " + p.get_all(tag = "test")[0].get_text_val("b")) sys.exit(0) p = Parser(args.wesnoth, args.config_dir, args.data_dir) if args.keep_temp: p.keep_temp_dir = args.keep_temp if args.verbose: p.verbose = True if args.input: p.parse_file(args.input, args.defines) elif args.text: p.parse_text(args.text, args.defines) if args.to_json: jsonify(p.root, True) print() elif args.to_xml: print('<?xml version="1.0" encoding="UTF-8" ?>') print('<root>') xmlify(p.root, True, 1) print('</root>') else: print((p.root.debug()))
spixi/wesnoth
data/tools/wesnoth/wmlparser3.py
Python
gpl-2.0
27,879
<?php /* $Id: loginbox.php,v 1.2 2004/03/29 00:18:17 ccwjr Exp $ CRE Loaded, Open Source E-Commerce Solutions http://www.creloaded.com Copyright (c) 2007 CRE Loaded Copyright (c) 2003 osCommerce Released under the GNU General Public License */ define('BOX_HEADING_LOGIN_BOX_MY_ACCOUNT','My Account Info'); define('LOGIN_BOX_MY_ACCOUNT','My Account Overview'); define('LOGIN_BOX_ACCOUNT_EDIT','Edit My Account Information'); define('LOGIN_BOX_ADDRESS_BOOK','Edit Address Book'); define('LOGIN_BOX_ACCOUNT_HISTORY','View My Order History'); define('LOGIN_BOX_PRODUCT_NOTIFICATIONS','Product Notifications'); define('LOGIN_BOX_PASSWORD_FORGOTTEN','Password Forgotten?'); define('BOX_LOGINBOX_EMAIL','Your Email Address'); define('BOX_LOGINBOX_PASSWORD','Your Password'); define('LOGIN_BOX_LOGOFF','Logoff'); ?>
loadedcommerce/Loaded6CE
Loaded_Commerce_CE/includes/languages/english/loginbox.php
PHP
gpl-2.0
822
/* * * Copyright 2009-2016, LabN Consulting, L.L.C. * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; see the file COPYING; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _QUAGGA_RFAPI_VNC_IMPORT_BGP_H_ #define _QUAGGA_RFAPI_VNC_IMPORT_BGP_H_ #include "lib/zebra.h" #include "lib/prefix.h" #include "bgpd/bgpd.h" #include "bgpd/bgp_route.h" #define VALID_INTERIOR_TYPE(type) \ (((type) == ZEBRA_ROUTE_BGP) || ((type) == ZEBRA_ROUTE_BGP_DIRECT)) extern uint32_t calc_local_pref(struct attr *attr, struct peer *peer); extern int vnc_prefix_cmp(const void *pfx1, const void *pfx2); extern void vnc_import_bgp_add_route(struct bgp *bgp, const struct prefix *prefix, struct bgp_path_info *info); extern void vnc_import_bgp_del_route(struct bgp *bgp, const struct prefix *prefix, struct bgp_path_info *info); extern void vnc_import_bgp_redist_enable(struct bgp *bgp, afi_t afi); extern void vnc_import_bgp_redist_disable(struct bgp *bgp, afi_t afi); extern void vnc_import_bgp_exterior_redist_enable(struct bgp *bgp, afi_t afi); extern void vnc_import_bgp_exterior_redist_disable(struct bgp *bgp, afi_t afi); extern void vnc_import_bgp_exterior_add_route( struct bgp *bgp, /* exterior instance, we hope */ const struct prefix *prefix, /* unicast prefix */ struct bgp_path_info *info); /* unicast info */ extern void vnc_import_bgp_exterior_del_route( struct bgp *bgp, const struct prefix *prefix, /* unicast prefix */ struct bgp_path_info *info); /* unicast info */ extern void vnc_import_bgp_add_vnc_host_route_mode_resolve_nve( struct bgp *bgp, struct prefix_rd *prd, /* RD */ struct bgp_table *table_rd, /* per-rd VPN route table */ const struct prefix *prefix, /* VPN prefix */ struct bgp_path_info *bpi); /* new VPN host route */ extern void vnc_import_bgp_del_vnc_host_route_mode_resolve_nve( struct bgp *bgp, struct prefix_rd *prd, /* RD */ struct bgp_table *table_rd, /* per-rd VPN route table */ const struct prefix *prefix, /* VPN prefix */ struct bgp_path_info *bpi); /* old VPN host route */ #endif /* _QUAGGA_RFAPI_VNC_IMPORT_BGP_H_ */
freerangerouting/frr
bgpd/rfapi/vnc_import_bgp.h
C
gpl-2.0
2,809
#include "cm_local.h" #include "cm_patch.h" //#define CULL_BBOX /* This file does not reference any globals, and has these entry points: void CM_ClearLevelPatches( void ); struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, const vec3_t *points ); void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ); qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ); void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, flaot *points) ); Issues for collision against curved surfaces: Surface edges need to be handled differently than surface planes Plane expansion causes raw surfaces to expand past expanded bounding box Position test of a volume against a surface is tricky. Position test of a point against a surface is not well defined, because the surface has no volume. Tracing leading edge points instead of volumes? Position test by tracing corner to corner? (8*7 traces -- ouch) coplanar edges triangulated patches degenerate patches endcaps degenerate WARNING: this may misbehave with meshes that have rows or columns that only degenerate a few triangles. Completely degenerate rows and columns are handled properly. */ /* #define MAX_FACETS 1024 #define MAX_PATCH_PLANES 2048 typedef struct { float plane[4]; int signbits; // signx + (signy<<1) + (signz<<2), used as lookup during collision } patchPlane_t; typedef struct { int surfacePlane; int numBorders; // 3 or four + 6 axial bevels + 4 or 3 * 4 edge bevels int borderPlanes[4+6+16]; int borderInward[4+6+16]; qboolean borderNoAdjust[4+6+16]; } facet_t; typedef struct patchCollide_s { vec3_t bounds[2]; int numPlanes; // surface planes plus edge planes patchPlane_t *planes; int numFacets; facet_t *facets; } patchCollide_t; #define MAX_GRID_SIZE 129 typedef struct { int width; int height; qboolean wrapWidth; qboolean wrapHeight; vec3_t points[MAX_GRID_SIZE][MAX_GRID_SIZE]; // [width][height] } cGrid_t; #define SUBDIVIDE_DISTANCE 16 //4 // never more than this units away from curve #define PLANE_TRI_EPSILON 0.1 #define WRAP_POINT_EPSILON 0.1 */ #define ADDBEVELS int c_totalPatchBlocks; int c_totalPatchSurfaces; int c_totalPatchEdges; static const patchCollide_t *debugPatchCollide; static const facet_t *debugFacet; static qboolean debugBlock; static vec3_t debugBlockPoints[4]; /* ================= CM_ClearLevelPatches ================= */ void CM_ClearLevelPatches( void ) { debugPatchCollide = NULL; debugFacet = NULL; } /* ================= CM_SignbitsForNormal ================= */ static int CM_SignbitsForNormal( vec3_t normal ) { int bits, j; bits = 0; for (j=0 ; j<3 ; j++) { if ( normal[j] < 0 ) { bits |= 1<<j; } } return bits; } /* ===================== CM_PlaneFromPoints Returns false if the triangle is degenrate. The normal will point out of the clock for clockwise ordered points ===================== */ static qboolean CM_PlaneFromPoints( vec4_t plane, vec3_t a, vec3_t b, vec3_t c ) { vec3_t d1, d2; VectorSubtract( b, a, d1 ); VectorSubtract( c, a, d2 ); CrossProduct( d2, d1, plane ); if ( VectorNormalize( plane ) == 0 ) { return qfalse; } plane[3] = DotProduct( a, plane ); return qtrue; } /* ================================================================================ GRID SUBDIVISION ================================================================================ */ /* ================= CM_NeedsSubdivision Returns true if the given quadratic curve is not flat enough for our collision detection purposes ================= */ static qboolean CM_NeedsSubdivision( vec3_t a, vec3_t b, vec3_t c ) { vec3_t cmid; vec3_t lmid; vec3_t delta; float dist; int i; // calculate the linear midpoint for ( i = 0 ; i < 3 ; i++ ) { lmid[i] = 0.5*(a[i] + c[i]); } // calculate the exact curve midpoint for ( i = 0 ; i < 3 ; i++ ) { cmid[i] = 0.5 * ( 0.5*(a[i] + b[i]) + 0.5*(b[i] + c[i]) ); } // see if the curve is far enough away from the linear mid VectorSubtract( cmid, lmid, delta ); dist = VectorLengthSquared( delta ); return dist >= SUBDIVIDE_DISTANCE * SUBDIVIDE_DISTANCE; } /* =============== CM_Subdivide a, b, and c are control points. the subdivided sequence will be: a, out1, out2, out3, c =============== */ static void CM_Subdivide( vec3_t a, vec3_t b, vec3_t c, vec3_t out1, vec3_t out2, vec3_t out3 ) { int i; for ( i = 0 ; i < 3 ; i++ ) { out1[i] = 0.5 * (a[i] + b[i]); out3[i] = 0.5 * (b[i] + c[i]); out2[i] = 0.5 * (out1[i] + out3[i]); } } /* ================= CM_TransposeGrid Swaps the rows and columns in place ================= */ static void CM_TransposeGrid( cGrid_t *grid ) { int i, j, l; vec3_t temp; qboolean tempWrap; if ( grid->width > grid->height ) { for ( i = 0 ; i < grid->height ; i++ ) { for ( j = i + 1 ; j < grid->width ; j++ ) { if ( j < grid->height ) { // swap the value VectorCopy( grid->points[i][j], temp ); VectorCopy( grid->points[j][i], grid->points[i][j] ); VectorCopy( temp, grid->points[j][i] ); } else { // just copy VectorCopy( grid->points[j][i], grid->points[i][j] ); } } } } else { for ( i = 0 ; i < grid->width ; i++ ) { for ( j = i + 1 ; j < grid->height ; j++ ) { if ( j < grid->width ) { // swap the value VectorCopy( grid->points[j][i], temp ); VectorCopy( grid->points[i][j], grid->points[j][i] ); VectorCopy( temp, grid->points[i][j] ); } else { // just copy VectorCopy( grid->points[i][j], grid->points[j][i] ); } } } } l = grid->width; grid->width = grid->height; grid->height = l; tempWrap = grid->wrapWidth; grid->wrapWidth = grid->wrapHeight; grid->wrapHeight = tempWrap; } /* =================== CM_SetGridWrapWidth If the left and right columns are exactly equal, set grid->wrapWidth qtrue =================== */ static void CM_SetGridWrapWidth( cGrid_t *grid ) { int i, j; float d; for ( i = 0 ; i < grid->height ; i++ ) { for ( j = 0 ; j < 3 ; j++ ) { d = grid->points[0][i][j] - grid->points[grid->width-1][i][j]; if ( d < -WRAP_POINT_EPSILON || d > WRAP_POINT_EPSILON ) { break; } } if ( j != 3 ) { break; } } if ( i == grid->height ) { grid->wrapWidth = qtrue; } else { grid->wrapWidth = qfalse; } } /* ================= CM_SubdivideGridColumns Adds columns as necessary to the grid until all the aproximating points are within SUBDIVIDE_DISTANCE from the true curve ================= */ static void CM_SubdivideGridColumns( cGrid_t *grid ) { int i, j, k; for ( i = 0 ; i < grid->width - 2 ; ) { // grid->points[i][x] is an interpolating control point // grid->points[i+1][x] is an aproximating control point // grid->points[i+2][x] is an interpolating control point // // first see if we can collapse the aproximating collumn away // for ( j = 0 ; j < grid->height ; j++ ) { if ( CM_NeedsSubdivision( grid->points[i][j], grid->points[i+1][j], grid->points[i+2][j] ) ) { break; } } if ( j == grid->height ) { // all of the points were close enough to the linear midpoints // that we can collapse the entire column away for ( j = 0 ; j < grid->height ; j++ ) { // remove the column for ( k = i + 2 ; k < grid->width ; k++ ) { VectorCopy( grid->points[k][j], grid->points[k-1][j] ); } } grid->width--; // go to the next curve segment i++; continue; } // // we need to subdivide the curve // for ( j = 0 ; j < grid->height ; j++ ) { vec3_t prev, mid, next; // save the control points now VectorCopy( grid->points[i][j], prev ); VectorCopy( grid->points[i+1][j], mid ); VectorCopy( grid->points[i+2][j], next ); // make room for two additional columns in the grid // columns i+1 will be replaced, column i+2 will become i+4 // i+1, i+2, and i+3 will be generated for ( k = grid->width - 1 ; k > i + 1 ; k-- ) { VectorCopy( grid->points[k][j], grid->points[k+2][j] ); } // generate the subdivided points CM_Subdivide( prev, mid, next, grid->points[i+1][j], grid->points[i+2][j], grid->points[i+3][j] ); } grid->width += 2; // the new aproximating point at i+1 may need to be removed // or subdivided farther, so don't advance i } } #define POINT_EPSILON 0.1 /* ====================== CM_ComparePoints ====================== */ static qboolean CM_ComparePoints( float *a, float *b ) { float d; d = a[0] - b[0]; if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { return qfalse; } d = a[1] - b[1]; if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { return qfalse; } d = a[2] - b[2]; if ( d < -POINT_EPSILON || d > POINT_EPSILON ) { return qfalse; } return qtrue; } /* ================= CM_RemoveDegenerateColumns If there are any identical columns, remove them ================= */ static void CM_RemoveDegenerateColumns( cGrid_t *grid ) { int i, j, k; for ( i = 0 ; i < grid->width - 1 ; i++ ) { for ( j = 0 ; j < grid->height ; j++ ) { if ( !CM_ComparePoints( grid->points[i][j], grid->points[i+1][j] ) ) { break; } } if ( j != grid->height ) { continue; // not degenerate } for ( j = 0 ; j < grid->height ; j++ ) { // remove the column for ( k = i + 2 ; k < grid->width ; k++ ) { VectorCopy( grid->points[k][j], grid->points[k-1][j] ); } } grid->width--; // check against the next column i--; } } /* ================================================================================ PATCH COLLIDE GENERATION ================================================================================ */ static int numPlanes; #ifdef _XBOX static patchPlane_t *planes = NULL; void CM_TempPatchPlanesAlloc(void) { if(!planes) { planes = (patchPlane_t*)Z_Malloc(MAX_PATCH_PLANES*sizeof(patchPlane_t), TAG_TEMP_WORKSPACE, qfalse); } } void CM_TempPatchPlanesDealloc(void) { if(planes) { Z_Free(planes); planes = NULL; } } #else static patchPlane_t planes[MAX_PATCH_PLANES]; #endif //static int numFacets; // static facet_t facets[MAX_PATCH_PLANES]; //maybe MAX_FACETS ?? //static facet_t facets[MAX_FACETS]; // Switched to MAX_FACETS = VV_FIXME, allocate these only during use static facet_t *facets = NULL; #define NORMAL_EPSILON 0.0001 #define DIST_EPSILON 0.02 int CM_PlaneEqual(patchPlane_t *p, float plane[4], int *flipped) { float invplane[4]; if ( Q_fabs(p->plane[0] - plane[0]) < NORMAL_EPSILON && Q_fabs(p->plane[1] - plane[1]) < NORMAL_EPSILON && Q_fabs(p->plane[2] - plane[2]) < NORMAL_EPSILON && Q_fabs(p->plane[3] - plane[3]) < DIST_EPSILON ) { *flipped = qfalse; return qtrue; } VectorNegate(plane, invplane); invplane[3] = -plane[3]; if ( Q_fabs(p->plane[0] - invplane[0]) < NORMAL_EPSILON && Q_fabs(p->plane[1] - invplane[1]) < NORMAL_EPSILON && Q_fabs(p->plane[2] - invplane[2]) < NORMAL_EPSILON && Q_fabs(p->plane[3] - invplane[3]) < DIST_EPSILON ) { *flipped = qtrue; return qtrue; } return qfalse; } void CM_SnapVector(vec3_t normal) { int i; for (i=0 ; i<3 ; i++) { if ( Q_fabs(normal[i] - 1) < NORMAL_EPSILON ) { VectorClear (normal); normal[i] = 1; break; } if ( Q_fabs(normal[i] - -1) < NORMAL_EPSILON ) { VectorClear (normal); normal[i] = -1; break; } } } int CM_FindPlane2(float plane[4], int *flipped) { int i; // see if the points are close enough to an existing plane for ( i = 0 ; i < numPlanes ; i++ ) { if (CM_PlaneEqual(&planes[i], plane, flipped)) return i; } // add a new plane if ( numPlanes == MAX_PATCH_PLANES ) { Com_Error( ERR_DROP, "MAX_PATCH_PLANES reached (%d)", MAX_PATCH_PLANES ); } Vector4Copy( plane, planes[numPlanes].plane ); planes[numPlanes].signbits = CM_SignbitsForNormal( plane ); numPlanes++; *flipped = qfalse; return numPlanes-1; } /* ================== CM_FindPlane ================== */ static int CM_FindPlane( float *p1, float *p2, float *p3 ) { float plane[4]; int i; float d; if ( !CM_PlaneFromPoints( plane, p1, p2, p3 ) ) { return -1; } // see if the points are close enough to an existing plane for ( i = 0 ; i < numPlanes ; i++ ) { if ( DotProduct( plane, planes[i].plane ) < 0 ) { continue; // allow backwards planes? } d = DotProduct( p1, planes[i].plane ) - planes[i].plane[3]; if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { continue; } d = DotProduct( p2, planes[i].plane ) - planes[i].plane[3]; if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { continue; } d = DotProduct( p3, planes[i].plane ) - planes[i].plane[3]; if ( d < -PLANE_TRI_EPSILON || d > PLANE_TRI_EPSILON ) { continue; } // found it return i; } // add a new plane if ( numPlanes == MAX_PATCH_PLANES ) { Com_Error( ERR_DROP, "MAX_PATCH_PLANES" ); } Vector4Copy( plane, planes[numPlanes].plane ); planes[numPlanes].signbits = CM_SignbitsForNormal( plane ); numPlanes++; return numPlanes-1; } /* ================== CM_PointOnPlaneSide ================== */ static int CM_PointOnPlaneSide( float *p, int planeNum ) { float *plane; float d; if ( planeNum == -1 ) { return SIDE_ON; } plane = planes[ planeNum ].plane; d = DotProduct( p, plane ) - plane[3]; if ( d > PLANE_TRI_EPSILON ) { return SIDE_FRONT; } if ( d < -PLANE_TRI_EPSILON ) { return SIDE_BACK; } return SIDE_ON; } #ifdef _XBOX static int CM_GridPlane( int* gridPlanes, int i, int j, int tri ) { int p; p = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+tri]; if ( p != -1 ) { return p; } p = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+(!tri)]; if ( p != -1 ) { return p; } // should never happen Com_Printf( "WARNING: CM_GridPlane unresolvable\n" ); return -1; } #else // _XBOX static int CM_GridPlane( int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int tri ) { int p; p = gridPlanes[i][j][tri]; if ( p != -1 ) { return p; } p = gridPlanes[i][j][!tri]; if ( p != -1 ) { return p; } // should never happen Com_Printf( "WARNING: CM_GridPlane unresolvable\n" ); return -1; } #endif // _XBOX /* ================== CM_EdgePlaneNum ================== */ #ifdef _XBOX static int CM_EdgePlaneNum( cGrid_t *grid, int* gridPlanes/*[PATCH_MAX_GRID_SIZE][PATCH_MAX_GRID_SIZE][2]*/, int i, int j, int k ) { float *p1, *p2; vec3_t up; int p; switch ( k ) { case 0: // top border p1 = grid->points[i][j]; p2 = grid->points[i+1][j]; p = CM_GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); case 2: // bottom border p1 = grid->points[i][j+1]; p2 = grid->points[i+1][j+1]; p = CM_GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p2, p1, up ); case 3: // left border p1 = grid->points[i][j]; p2 = grid->points[i][j+1]; p = CM_GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p2, p1, up ); case 1: // right border p1 = grid->points[i+1][j]; p2 = grid->points[i+1][j+1]; p = CM_GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); case 4: // diagonal out of triangle 0 p1 = grid->points[i+1][j+1]; p2 = grid->points[i][j]; p = CM_GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); case 5: // diagonal out of triangle 1 p1 = grid->points[i][j]; p2 = grid->points[i+1][j+1]; p = CM_GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); } Com_Error( ERR_DROP, "CM_EdgePlaneNum: bad k" ); return -1; } #else static int CM_EdgePlaneNum( cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int k ) { float *p1, *p2; vec3_t up; int p; switch ( k ) { case 0: // top border p1 = grid->points[i][j]; p2 = grid->points[i+1][j]; p = CM_GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); case 2: // bottom border p1 = grid->points[i][j+1]; p2 = grid->points[i+1][j+1]; p = CM_GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p2, p1, up ); case 3: // left border p1 = grid->points[i][j]; p2 = grid->points[i][j+1]; p = CM_GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p2, p1, up ); case 1: // right border p1 = grid->points[i+1][j]; p2 = grid->points[i+1][j+1]; p = CM_GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); case 4: // diagonal out of triangle 0 p1 = grid->points[i+1][j+1]; p2 = grid->points[i][j]; p = CM_GridPlane( gridPlanes, i, j, 0 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); case 5: // diagonal out of triangle 1 p1 = grid->points[i][j]; p2 = grid->points[i+1][j+1]; p = CM_GridPlane( gridPlanes, i, j, 1 ); VectorMA( p1, 4, planes[ p ].plane, up ); return CM_FindPlane( p1, p2, up ); } Com_Error( ERR_DROP, "CM_EdgePlaneNum: bad k" ); return -1; } #endif /* =================== CM_SetBorderInward =================== */ #ifdef _XBOX static void CM_SetBorderInward( facetLoad_t *facet, cGrid_t *grid, int i, int j, int which ) { int k, l; float *points[4]; int numPoints; switch ( which ) { case -1: points[0] = grid->points[i][j]; points[1] = grid->points[i+1][j]; points[2] = grid->points[i+1][j+1]; points[3] = grid->points[i][j+1]; numPoints = 4; break; case 0: points[0] = grid->points[i][j]; points[1] = grid->points[i+1][j]; points[2] = grid->points[i+1][j+1]; numPoints = 3; break; case 1: points[0] = grid->points[i+1][j+1]; points[1] = grid->points[i][j+1]; points[2] = grid->points[i][j]; numPoints = 3; break; default: Com_Error( ERR_FATAL, "CM_SetBorderInward: bad parameter" ); numPoints = 0; break; } for ( k = 0 ; k < facet->numBorders ; k++ ) { int front, back; front = 0; back = 0; for ( l = 0 ; l < numPoints ; l++ ) { int side; side = CM_PointOnPlaneSide( points[l], facet->borderPlanes[k] ); if ( side == SIDE_FRONT ) { front++; } if ( side == SIDE_BACK ) { back++; } } if ( front && !back ) { facet->borderInward[k] = qtrue; } else if ( back && !front ) { facet->borderInward[k] = qfalse; } else if ( !front && !back ) { // flat side border facet->borderPlanes[k] = -1; } else { // bisecting side border Com_DPrintf( "WARNING: CM_SetBorderInward: mixed plane sides\n" ); facet->borderInward[k] = qfalse; if ( !debugBlock ) { debugBlock = qtrue; VectorCopy( grid->points[i][j], debugBlockPoints[0] ); VectorCopy( grid->points[i+1][j], debugBlockPoints[1] ); VectorCopy( grid->points[i+1][j+1], debugBlockPoints[2] ); VectorCopy( grid->points[i][j+1], debugBlockPoints[3] ); } } } } #else // _XBOX static void CM_SetBorderInward( facet_t *facet, cGrid_t *grid, int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2], int i, int j, int which ) { int k, l; float *points[4]; int numPoints; switch ( which ) { case -1: points[0] = grid->points[i][j]; points[1] = grid->points[i+1][j]; points[2] = grid->points[i+1][j+1]; points[3] = grid->points[i][j+1]; numPoints = 4; break; case 0: points[0] = grid->points[i][j]; points[1] = grid->points[i+1][j]; points[2] = grid->points[i+1][j+1]; numPoints = 3; break; case 1: points[0] = grid->points[i+1][j+1]; points[1] = grid->points[i][j+1]; points[2] = grid->points[i][j]; numPoints = 3; break; default: Com_Error( ERR_FATAL, "CM_SetBorderInward: bad parameter" ); numPoints = 0; break; } for ( k = 0 ; k < facet->numBorders ; k++ ) { int front, back; front = 0; back = 0; for ( l = 0 ; l < numPoints ; l++ ) { int side; side = CM_PointOnPlaneSide( points[l], facet->borderPlanes[k] ); if ( side == SIDE_FRONT ) { front++; } if ( side == SIDE_BACK ) { back++; } } if ( front && !back ) { facet->borderInward[k] = qtrue; } else if ( back && !front ) { facet->borderInward[k] = qfalse; } else if ( !front && !back ) { // flat side border facet->borderPlanes[k] = -1; } else { // bisecting side border Com_DPrintf( "WARNING: CM_SetBorderInward: mixed plane sides\n" ); facet->borderInward[k] = qfalse; if ( !debugBlock ) { debugBlock = qtrue; VectorCopy( grid->points[i][j], debugBlockPoints[0] ); VectorCopy( grid->points[i+1][j], debugBlockPoints[1] ); VectorCopy( grid->points[i+1][j+1], debugBlockPoints[2] ); VectorCopy( grid->points[i][j+1], debugBlockPoints[3] ); } } } } #endif /* ================== CM_ValidateFacet If the facet isn't bounded by its borders, we screwed up. ================== */ #ifdef _XBOX static qboolean CM_ValidateFacet( facetLoad_t *facet ) { float plane[4]; int j; winding_t *w; vec3_t bounds[2]; if ( facet->surfacePlane == -1 ) { return qfalse; } Vector4Copy( planes[ facet->surfacePlane ].plane, plane ); w = BaseWindingForPlane( plane, plane[3] ); for ( j = 0 ; j < facet->numBorders && w ; j++ ) { if ( facet->borderPlanes[j] == -1 ) { FreeWinding(w); return qfalse; } Vector4Copy( planes[ facet->borderPlanes[j] ].plane, plane ); if ( !facet->borderInward[j] ) { VectorSubtract( vec3_origin, plane, plane ); plane[3] = -plane[3]; } ChopWindingInPlace( &w, plane, plane[3], 0.1f ); } if ( !w ) { return qfalse; // winding was completely chopped away } // see if the facet is unreasonably large WindingBounds( w, bounds[0], bounds[1] ); FreeWinding( w ); for ( j = 0 ; j < 3 ; j++ ) { if ( bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS ) { return qfalse; // we must be missing a plane } if ( bounds[0][j] >= MAX_MAP_BOUNDS ) { return qfalse; } if ( bounds[1][j] <= -MAX_MAP_BOUNDS ) { return qfalse; } } return qtrue; // winding is fine } #else // _XBOX static qboolean CM_ValidateFacet( facet_t *facet ) { float plane[4]; int j; winding_t *w; vec3_t bounds[2]; if ( facet->surfacePlane == -1 ) { return qfalse; } Vector4Copy( planes[ facet->surfacePlane ].plane, plane ); w = BaseWindingForPlane( plane, plane[3] ); for ( j = 0 ; j < facet->numBorders && w ; j++ ) { if ( facet->borderPlanes[j] == -1 ) { FreeWinding(w); return qfalse; } Vector4Copy( planes[ facet->borderPlanes[j] ].plane, plane ); if ( !facet->borderInward[j] ) { VectorSubtract( vec3_origin, plane, plane ); plane[3] = -plane[3]; } ChopWindingInPlace( &w, plane, plane[3], 0.1f ); } if ( !w ) { return qfalse; // winding was completely chopped away } // see if the facet is unreasonably large WindingBounds( w, bounds[0], bounds[1] ); FreeWinding( w ); for ( j = 0 ; j < 3 ; j++ ) { if ( bounds[1][j] - bounds[0][j] > MAX_MAP_BOUNDS ) { return qfalse; // we must be missing a plane } if ( bounds[0][j] >= MAX_MAP_BOUNDS ) { return qfalse; } if ( bounds[1][j] <= -MAX_MAP_BOUNDS ) { return qfalse; } } return qtrue; // winding is fine } #endif // _XBOX /* ================== CM_AddFacetBevels ================== */ #ifdef _XBOX void CM_AddFacetBevels( facetLoad_t *facet ) { int i, j, k, l; int axis, dir, order, flipped; float plane[4], d, newplane[4]; winding_t *w, *w2; vec3_t mins, maxs, vec, vec2; #ifndef ADDBEVELS return; #endif Vector4Copy( planes[ facet->surfacePlane ].plane, plane ); w = BaseWindingForPlane( plane, plane[3] ); for ( j = 0 ; j < facet->numBorders && w ; j++ ) { if (facet->borderPlanes[j] == facet->surfacePlane) continue; Vector4Copy( planes[ facet->borderPlanes[j] ].plane, plane ); if ( !facet->borderInward[j] ) { VectorSubtract( vec3_origin, plane, plane ); plane[3] = -plane[3]; } ChopWindingInPlace( &w, plane, plane[3], 0.1f ); } if ( !w ) { return; } WindingBounds(w, mins, maxs); // add the axial planes order = 0; for ( axis = 0 ; axis < 3 ; axis++ ) { for ( dir = -1 ; dir <= 1 ; dir += 2, order++ ) { VectorClear(plane); plane[axis] = dir; if (dir == 1) { plane[3] = maxs[axis]; } else { plane[3] = -mins[axis]; } //if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present for ( i = 0 ; i < facet->numBorders ; i++ ) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) break; } if ( i == facet->numBorders ) { if (facet->numBorders > 4 + 6 + 16) Com_Printf(S_COLOR_RED"ERROR: too many bevels\n"); int num = CM_FindPlane2(plane, &flipped); assert(num > -32768 && num < 32768); facet->borderPlanes[facet->numBorders] = num; facet->borderNoAdjust[facet->numBorders] = 0; facet->borderInward[facet->numBorders] = flipped; facet->numBorders++; } } } // // add the edge bevels // // test the non-axial plane edges for ( j = 0 ; j < w->numpoints ; j++ ) { k = (j+1)%w->numpoints; VectorSubtract (w->p[j], w->p[k], vec); //if it's a degenerate edge if (VectorNormalize (vec) < 0.5) continue; CM_SnapVector(vec); for ( k = 0; k < 3 ; k++ ) if ( vec[k] == -1 || vec[k] == 1 ) break; // axial if ( k < 3 ) continue; // only test non-axial edges // try the six possible slanted axials from this edge for ( axis = 0 ; axis < 3 ; axis++ ) { for ( dir = -1 ; dir <= 1 ; dir += 2 ) { // construct a plane VectorClear (vec2); vec2[axis] = dir; CrossProduct (vec, vec2, plane); if (VectorNormalize (plane) < 0.5) continue; plane[3] = DotProduct (w->p[j], plane); // if all the points of the facet winding are // behind this plane, it is a proper edge bevel for ( l = 0 ; l < w->numpoints ; l++ ) { d = DotProduct (w->p[l], plane) - plane[3]; if (d > 0.1) break; // point in front } if ( l < w->numpoints ) continue; //if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present for ( i = 0 ; i < facet->numBorders ; i++ ) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) { break; } } if ( i == facet->numBorders ) { if (facet->numBorders > 4 + 6 + 16) Com_Printf(S_COLOR_RED"ERROR: too many bevels\n"); int num = CM_FindPlane2(plane, &flipped); assert(num > -32768 && num < 32768); facet->borderPlanes[facet->numBorders] = num; for ( k = 0 ; k < facet->numBorders ; k++ ) { if (facet->borderPlanes[facet->numBorders] == facet->borderPlanes[k]) Com_Printf("WARNING: bevel plane already used\n"); } facet->borderNoAdjust[facet->numBorders] = 0; facet->borderInward[facet->numBorders] = flipped; // w2 = CopyWinding(w); Vector4Copy(planes[facet->borderPlanes[facet->numBorders]].plane, newplane); if (!facet->borderInward[facet->numBorders]) { VectorNegate(newplane, newplane); newplane[3] = -newplane[3]; } //end if ChopWindingInPlace( &w2, newplane, newplane[3], 0.1f ); if (!w2) { Com_DPrintf("WARNING: CM_AddFacetBevels... invalid bevel\n"); continue; } else { FreeWinding(w2); } // facet->numBorders++; //already got a bevel // break; } } } } FreeWinding( w ); #ifndef BSPC //add opposite plane assert(facet->surfacePlane > -32768 && facet->surfacePlane < 32768); facet->borderPlanes[facet->numBorders] = facet->surfacePlane; facet->borderNoAdjust[facet->numBorders] = 0; facet->borderInward[facet->numBorders] = qtrue; facet->numBorders++; #endif //BSPC } #else // _XBOX void CM_AddFacetBevels( facet_t *facet ) { int i, j, k, l; int axis, dir, order, flipped; float plane[4], d, newplane[4]; winding_t *w, *w2; vec3_t mins, maxs, vec, vec2; #ifndef ADDBEVELS return; #endif Vector4Copy( planes[ facet->surfacePlane ].plane, plane ); w = BaseWindingForPlane( plane, plane[3] ); for ( j = 0 ; j < facet->numBorders && w ; j++ ) { if (facet->borderPlanes[j] == facet->surfacePlane) continue; Vector4Copy( planes[ facet->borderPlanes[j] ].plane, plane ); if ( !facet->borderInward[j] ) { VectorSubtract( vec3_origin, plane, plane ); plane[3] = -plane[3]; } ChopWindingInPlace( &w, plane, plane[3], 0.1f ); } if ( !w ) { return; } WindingBounds(w, mins, maxs); // add the axial planes order = 0; for ( axis = 0 ; axis < 3 ; axis++ ) { for ( dir = -1 ; dir <= 1 ; dir += 2, order++ ) { VectorClear(plane); plane[axis] = dir; if (dir == 1) { plane[3] = maxs[axis]; } else { plane[3] = -mins[axis]; } //if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present for ( i = 0 ; i < facet->numBorders ; i++ ) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) break; } if ( i == facet->numBorders ) { if (facet->numBorders > 4 + 6 + 16) Com_Printf(S_COLOR_RED"ERROR: too many bevels\n"); facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped); facet->borderNoAdjust[facet->numBorders] = 0; facet->borderInward[facet->numBorders] = flipped; facet->numBorders++; } } } // // add the edge bevels // // test the non-axial plane edges for ( j = 0 ; j < w->numpoints ; j++ ) { k = (j+1)%w->numpoints; VectorSubtract (w->p[j], w->p[k], vec); //if it's a degenerate edge if (VectorNormalize (vec) < 0.5) continue; CM_SnapVector(vec); for ( k = 0; k < 3 ; k++ ) if ( vec[k] == -1 || vec[k] == 1 ) break; // axial if ( k < 3 ) continue; // only test non-axial edges // try the six possible slanted axials from this edge for ( axis = 0 ; axis < 3 ; axis++ ) { for ( dir = -1 ; dir <= 1 ; dir += 2 ) { // construct a plane VectorClear (vec2); vec2[axis] = dir; CrossProduct (vec, vec2, plane); if (VectorNormalize (plane) < 0.5) continue; plane[3] = DotProduct (w->p[j], plane); // if all the points of the facet winding are // behind this plane, it is a proper edge bevel for ( l = 0 ; l < w->numpoints ; l++ ) { d = DotProduct (w->p[l], plane) - plane[3]; if (d > 0.1) break; // point in front } if ( l < w->numpoints ) continue; //if it's the surface plane if (CM_PlaneEqual(&planes[facet->surfacePlane], plane, &flipped)) { continue; } // see if the plane is allready present for ( i = 0 ; i < facet->numBorders ; i++ ) { if (CM_PlaneEqual(&planes[facet->borderPlanes[i]], plane, &flipped)) { break; } } if ( i == facet->numBorders ) { if (facet->numBorders > 4 + 6 + 16) Com_Printf(S_COLOR_RED"ERROR: too many bevels\n"); facet->borderPlanes[facet->numBorders] = CM_FindPlane2(plane, &flipped); for ( k = 0 ; k < facet->numBorders ; k++ ) { if (facet->borderPlanes[facet->numBorders] == facet->borderPlanes[k]) Com_Printf("WARNING: bevel plane already used\n"); } facet->borderNoAdjust[facet->numBorders] = 0; facet->borderInward[facet->numBorders] = flipped; // w2 = CopyWinding(w); Vector4Copy(planes[facet->borderPlanes[facet->numBorders]].plane, newplane); if (!facet->borderInward[facet->numBorders]) { VectorNegate(newplane, newplane); newplane[3] = -newplane[3]; } //end if ChopWindingInPlace( &w2, newplane, newplane[3], 0.1f ); if (!w2) { Com_DPrintf("WARNING: CM_AddFacetBevels... invalid bevel\n"); continue; } else { FreeWinding(w2); } // facet->numBorders++; //already got a bevel // break; } } } } FreeWinding( w ); #ifndef BSPC //add opposite plane facet->borderPlanes[facet->numBorders] = facet->surfacePlane; facet->borderNoAdjust[facet->numBorders] = 0; facet->borderInward[facet->numBorders] = qtrue; facet->numBorders++; #endif //BSPC } #endif // _XBOX typedef enum { EN_TOP, EN_RIGHT, EN_BOTTOM, EN_LEFT } edgeName_t; #ifdef _XBOX facetLoad_t* cm_facets = 0; int* cm_gridPlanes = 0; void CM_PatchCollideFromGridTempAlloc() { if (!cm_facets) { cm_facets = (facetLoad_t*)Z_Malloc(MAX_PATCH_PLANES*sizeof(facetLoad_t), TAG_TEMP_WORKSPACE, qfalse); } if (!cm_gridPlanes) { cm_gridPlanes = (int*)Z_Malloc(CM_MAX_GRID_SIZE*CM_MAX_GRID_SIZE*2*sizeof(int), TAG_TEMP_WORKSPACE, qfalse); } } void CM_PatchCollideFromGridTempDealloc() { Z_Free(cm_gridPlanes); Z_Free(cm_facets); cm_gridPlanes = 0; cm_facets = 0; } #endif /* ================== CM_PatchCollideFromGrid ================== */ #ifdef _XBOX int min1 = 0, max1 = 0, min2 = 0, max2 = 0; static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf, facetLoad_t *facetbuf, int *gridbuf ) { int i, j; float *p1, *p2, *p3; int *gridPlanes; facetLoad_t *facet; int borders[4]; int noAdjust[4]; facetLoad_t *facets; int numFacets; facets = cm_facets; if (facets == 0) { facets = facetbuf; } gridPlanes = cm_gridPlanes; if (gridPlanes == 0) { gridPlanes = gridbuf; } numPlanes = 0; numFacets = 0; // find the planes for each triangle of the grid for ( i = 0 ; i < grid->width - 1 ; i++ ) { for ( j = 0 ; j < grid->height - 1 ; j++ ) { p1 = grid->points[i][j]; p2 = grid->points[i+1][j]; p3 = grid->points[i+1][j+1]; gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] = CM_FindPlane( p1, p2, p3 ); p1 = grid->points[i+1][j+1]; p2 = grid->points[i][j+1]; p3 = grid->points[i][j]; gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1] = CM_FindPlane( p1, p2, p3 ); } } // create the borders for each facet for ( i = 0 ; i < grid->width - 1 ; i++ ) { for ( j = 0 ; j < grid->height - 1 ; j++ ) { borders[EN_TOP] = -1; if ( j > 0 ) { borders[EN_TOP] = gridPlanes[i*CM_MAX_GRID_SIZE*2+(j-1)*2+1]; } else if ( grid->wrapHeight ) { borders[EN_TOP] = gridPlanes[i*CM_MAX_GRID_SIZE*2+(grid->height-2)*2+1]; } noAdjust[EN_TOP] = ( borders[EN_TOP] == gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] ); if ( borders[EN_TOP] == -1 || noAdjust[EN_TOP] ) { borders[EN_TOP] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 0 ); } borders[EN_BOTTOM] = -1; if ( j < grid->height - 2 ) { borders[EN_BOTTOM] = gridPlanes[i*CM_MAX_GRID_SIZE*2+(j+1)*2+0]; } else if ( grid->wrapHeight ) { borders[EN_BOTTOM] = gridPlanes[i*CM_MAX_GRID_SIZE*2+0*2+0]; } noAdjust[EN_BOTTOM] = ( borders[EN_BOTTOM] == gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1] ); if ( borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM] ) { borders[EN_BOTTOM] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 2 ); } borders[EN_LEFT] = -1; if ( i > 0 ) { borders[EN_LEFT] = gridPlanes[(i-1)*CM_MAX_GRID_SIZE*2+j*2+0]; } else if ( grid->wrapWidth ) { borders[EN_LEFT] = gridPlanes[(grid->width-2)*CM_MAX_GRID_SIZE*2+j*2+0]; } noAdjust[EN_LEFT] = ( borders[EN_LEFT] == gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1] ); if ( borders[EN_LEFT] == -1 || noAdjust[EN_LEFT] ) { borders[EN_LEFT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 3 ); } borders[EN_RIGHT] = -1; if ( i < grid->width - 2 ) { borders[EN_RIGHT] = gridPlanes[(i+1)*CM_MAX_GRID_SIZE*2+j*2+1]; } else if ( grid->wrapWidth ) { borders[EN_RIGHT] = gridPlanes[0*CM_MAX_GRID_SIZE*2+j*2+1]; } noAdjust[EN_RIGHT] = ( borders[EN_RIGHT] == gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] ); if ( borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT] ) { borders[EN_RIGHT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 1 ); } if ( numFacets == MAX_FACETS ) { Com_Error( ERR_DROP, "MAX_FACETS" ); } facet = &facets[numFacets]; memset( facet, 0, sizeof( *facet ) ); if ( gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] == gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1] ) { if ( gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] == -1 ) { continue; // degenrate } facet->surfacePlane = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0]; facet->numBorders = 4; facet->borderPlanes[0] = borders[EN_TOP]; assert(borders[EN_TOP] > -32768 && borders[EN_TOP] < 32768); facet->borderNoAdjust[0] = noAdjust[EN_TOP]; assert(noAdjust[EN_TOP] >= 0 && noAdjust[EN_TOP] < 256); facet->borderPlanes[1] = borders[EN_RIGHT]; assert(borders[EN_RIGHT] > -32768 && borders[EN_RIGHT] < 32768); facet->borderNoAdjust[1] = noAdjust[EN_RIGHT]; assert(noAdjust[EN_RIGHT] >= 0 && noAdjust[EN_RIGHT] < 256); facet->borderPlanes[2] = borders[EN_BOTTOM]; assert(borders[EN_BOTTOM] > -32768 && borders[EN_BOTTOM] < 32768); facet->borderNoAdjust[2] = noAdjust[EN_BOTTOM]; assert(noAdjust[EN_BOTTOM] >= 0 && noAdjust[EN_BOTTOM] < 256); facet->borderPlanes[3] = borders[EN_LEFT]; assert(borders[EN_LEFT] > -32768 && borders[EN_LEFT] < 32768); facet->borderNoAdjust[3] = noAdjust[EN_LEFT]; assert(noAdjust[EN_LEFT] >= 0 && noAdjust[EN_LEFT] < 256); CM_SetBorderInward( facet, grid, i, j, -1 ); if ( CM_ValidateFacet( facet ) ) { CM_AddFacetBevels( facet ); numFacets++; } } else { // two seperate triangles facet->surfacePlane = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0]; facet->numBorders = 3; facet->borderPlanes[0] = borders[EN_TOP]; assert(borders[EN_TOP] > -32768 && borders[EN_TOP] < 32768); assert(noAdjust[EN_TOP] >= 0 && noAdjust[EN_TOP] < 256); facet->borderNoAdjust[0] = noAdjust[EN_TOP]; facet->borderPlanes[1] = borders[EN_RIGHT]; assert(borders[EN_RIGHT] > -32768 && borders[EN_RIGHT] < 32768); facet->borderNoAdjust[1] = noAdjust[EN_RIGHT]; assert(noAdjust[EN_RIGHT] >= 0 && noAdjust[EN_RIGHT] < 256); facet->borderPlanes[2] = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1]; assert(gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1] > -32768 && gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1] < 32768); if ( facet->borderPlanes[2] == -1 ) { facet->borderPlanes[2] = borders[EN_BOTTOM]; assert(borders[EN_BOTTOM] > -32768 && borders[EN_BOTTOM] < 32768); if ( facet->borderPlanes[2] == -1 ) { int num = CM_EdgePlaneNum( grid, gridPlanes, i, j, 4 ); assert(num > -32768 && num < 32768); facet->borderPlanes[2] = num; } } CM_SetBorderInward( facet, grid, i, j, 0 ); if ( CM_ValidateFacet( facet ) ) { CM_AddFacetBevels( facet ); numFacets++; } if ( numFacets == MAX_FACETS ) { Com_Error( ERR_DROP, "MAX_FACETS" ); } facet = &facets[numFacets]; memset( facet, 0, sizeof( *facet ) ); facet->surfacePlane = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+1]; facet->numBorders = 3; facet->borderPlanes[0] = borders[EN_BOTTOM]; assert(borders[EN_BOTTOM] > -32768 && borders[EN_BOTTOM] < 32768); facet->borderNoAdjust[0] = noAdjust[EN_BOTTOM]; assert(noAdjust[EN_BOTTOM] >= 0 && noAdjust[EN_BOTTOM] < 256); facet->borderPlanes[1] = borders[EN_LEFT]; assert(borders[EN_LEFT] > -32768 && borders[EN_LEFT] < 32768); facet->borderNoAdjust[1] = noAdjust[EN_LEFT]; assert(noAdjust[EN_LEFT] >= 0 && noAdjust[EN_LEFT] < 256); facet->borderPlanes[2] = gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0]; assert(gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] > -32768 && gridPlanes[i*CM_MAX_GRID_SIZE*2+j*2+0] < 32768); if ( facet->borderPlanes[2] == -1 ) { facet->borderPlanes[2] = borders[EN_TOP]; assert(borders[EN_TOP] > -32768 && borders[EN_TOP] < 32768); if ( facet->borderPlanes[2] == -1 ) { int num = CM_EdgePlaneNum( grid, gridPlanes, i, j, 5 ); assert(num > -32768 && num < 32768); facet->borderPlanes[2] = num; } } CM_SetBorderInward( facet, grid, i, j, 1 ); if ( CM_ValidateFacet( facet ) ) { CM_AddFacetBevels( facet ); numFacets++; } } } } // copy the results out pf->numPlanes = numPlanes; pf->numFacets = numFacets; if (numFacets) { pf->facets = (facet_t *) Z_Malloc( numFacets * sizeof( *pf->facets ), TAG_BSP, qfalse); for(i=0; i<numFacets; i++) { pf->facets[i].data = (char*)Z_Malloc(facets[i].numBorders * 4, TAG_BSP, qfalse); pf->facets[i].surfacePlane = facets[i].surfacePlane; pf->facets[i].numBorders = facets[i].numBorders; short *bp = pf->facets[i].GetBorderPlanes(); char *bi = pf->facets[i].GetBorderInward(); char *bna = pf->facets[i].GetBorderNoAdjust(); for(j=0; j<facets[i].numBorders; j++) { bp[j] = facets[i].borderPlanes[j]; bi[j] = facets[i].borderInward[j]; bna[j] = facets[i].borderNoAdjust[j]; } } } else { pf->facets = 0; } pf->planes = (patchPlane_t *) Z_Malloc( numPlanes * sizeof( *pf->planes ), TAG_BSP, qfalse); memcpy( pf->planes, planes, numPlanes * sizeof( *pf->planes ) ); } #else static void CM_PatchCollideFromGrid( cGrid_t *grid, patchCollide_t *pf ) { int i, j; float *p1, *p2, *p3; MAC_STATIC int gridPlanes[CM_MAX_GRID_SIZE][CM_MAX_GRID_SIZE][2]; facet_t *facet; int borders[4]; int noAdjust[4]; int numFacets; facets = (facet_t*) Z_Malloc(MAX_FACETS*sizeof(facet_t), TAG_TEMP_WORKSPACE, qfalse, 4); numPlanes = 0; numFacets = 0; // find the planes for each triangle of the grid for ( i = 0 ; i < grid->width - 1 ; i++ ) { for ( j = 0 ; j < grid->height - 1 ; j++ ) { p1 = grid->points[i][j]; p2 = grid->points[i+1][j]; p3 = grid->points[i+1][j+1]; gridPlanes[i][j][0] = CM_FindPlane( p1, p2, p3 ); p1 = grid->points[i+1][j+1]; p2 = grid->points[i][j+1]; p3 = grid->points[i][j]; gridPlanes[i][j][1] = CM_FindPlane( p1, p2, p3 ); } } // create the borders for each facet for ( i = 0 ; i < grid->width - 1 ; i++ ) { for ( j = 0 ; j < grid->height - 1 ; j++ ) { borders[EN_TOP] = -1; if ( j > 0 ) { borders[EN_TOP] = gridPlanes[i][j-1][1]; } else if ( grid->wrapHeight ) { borders[EN_TOP] = gridPlanes[i][grid->height-2][1]; } noAdjust[EN_TOP] = ( borders[EN_TOP] == gridPlanes[i][j][0] ); if ( borders[EN_TOP] == -1 || noAdjust[EN_TOP] ) { borders[EN_TOP] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 0 ); } borders[EN_BOTTOM] = -1; if ( j < grid->height - 2 ) { borders[EN_BOTTOM] = gridPlanes[i][j+1][0]; } else if ( grid->wrapHeight ) { borders[EN_BOTTOM] = gridPlanes[i][0][0]; } noAdjust[EN_BOTTOM] = ( borders[EN_BOTTOM] == gridPlanes[i][j][1] ); if ( borders[EN_BOTTOM] == -1 || noAdjust[EN_BOTTOM] ) { borders[EN_BOTTOM] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 2 ); } borders[EN_LEFT] = -1; if ( i > 0 ) { borders[EN_LEFT] = gridPlanes[i-1][j][0]; } else if ( grid->wrapWidth ) { borders[EN_LEFT] = gridPlanes[grid->width-2][j][0]; } noAdjust[EN_LEFT] = ( borders[EN_LEFT] == gridPlanes[i][j][1] ); if ( borders[EN_LEFT] == -1 || noAdjust[EN_LEFT] ) { borders[EN_LEFT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 3 ); } borders[EN_RIGHT] = -1; if ( i < grid->width - 2 ) { borders[EN_RIGHT] = gridPlanes[i+1][j][1]; } else if ( grid->wrapWidth ) { borders[EN_RIGHT] = gridPlanes[0][j][1]; } noAdjust[EN_RIGHT] = ( borders[EN_RIGHT] == gridPlanes[i][j][0] ); if ( borders[EN_RIGHT] == -1 || noAdjust[EN_RIGHT] ) { borders[EN_RIGHT] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 1 ); } if ( numFacets == MAX_FACETS ) { Com_Error( ERR_DROP, "MAX_FACETS" ); } facet = &facets[numFacets]; memset( facet, 0, sizeof( *facet ) ); if ( gridPlanes[i][j][0] == gridPlanes[i][j][1] ) { if ( gridPlanes[i][j][0] == -1 ) { continue; // degenrate } facet->surfacePlane = gridPlanes[i][j][0]; facet->numBorders = 4; facet->borderPlanes[0] = borders[EN_TOP]; facet->borderNoAdjust[0] = noAdjust[EN_TOP]; facet->borderPlanes[1] = borders[EN_RIGHT]; facet->borderNoAdjust[1] = noAdjust[EN_RIGHT]; facet->borderPlanes[2] = borders[EN_BOTTOM]; facet->borderNoAdjust[2] = noAdjust[EN_BOTTOM]; facet->borderPlanes[3] = borders[EN_LEFT]; facet->borderNoAdjust[3] = noAdjust[EN_LEFT]; CM_SetBorderInward( facet, grid, gridPlanes, i, j, -1 ); if ( CM_ValidateFacet( facet ) ) { CM_AddFacetBevels( facet ); numFacets++; } } else { // two seperate triangles facet->surfacePlane = gridPlanes[i][j][0]; facet->numBorders = 3; facet->borderPlanes[0] = borders[EN_TOP]; facet->borderNoAdjust[0] = noAdjust[EN_TOP]; facet->borderPlanes[1] = borders[EN_RIGHT]; facet->borderNoAdjust[1] = noAdjust[EN_RIGHT]; facet->borderPlanes[2] = gridPlanes[i][j][1]; if ( facet->borderPlanes[2] == -1 ) { facet->borderPlanes[2] = borders[EN_BOTTOM]; if ( facet->borderPlanes[2] == -1 ) { facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 4 ); } } CM_SetBorderInward( facet, grid, gridPlanes, i, j, 0 ); if ( CM_ValidateFacet( facet ) ) { CM_AddFacetBevels( facet ); numFacets++; } if ( numFacets == MAX_FACETS ) { Com_Error( ERR_DROP, "MAX_FACETS" ); } facet = &facets[numFacets]; memset( facet, 0, sizeof( *facet ) ); facet->surfacePlane = gridPlanes[i][j][1]; facet->numBorders = 3; facet->borderPlanes[0] = borders[EN_BOTTOM]; facet->borderNoAdjust[0] = noAdjust[EN_BOTTOM]; facet->borderPlanes[1] = borders[EN_LEFT]; facet->borderNoAdjust[1] = noAdjust[EN_LEFT]; facet->borderPlanes[2] = gridPlanes[i][j][0]; if ( facet->borderPlanes[2] == -1 ) { facet->borderPlanes[2] = borders[EN_TOP]; if ( facet->borderPlanes[2] == -1 ) { facet->borderPlanes[2] = CM_EdgePlaneNum( grid, gridPlanes, i, j, 5 ); } } CM_SetBorderInward( facet, grid, gridPlanes, i, j, 1 ); if ( CM_ValidateFacet( facet ) ) { CM_AddFacetBevels( facet ); numFacets++; } } } } // copy the results out pf->numPlanes = numPlanes; pf->numFacets = numFacets; if (numFacets) { pf->facets = (facet_t *) Z_Malloc( numFacets * sizeof( *pf->facets ), TAG_BSP, qfalse); memcpy( pf->facets, facets, numFacets * sizeof( *pf->facets ) ); } else { pf->facets = 0; } pf->planes = (patchPlane_t *) Z_Malloc( numPlanes * sizeof( *pf->planes ), TAG_BSP, qfalse); memcpy( pf->planes, planes, numPlanes * sizeof( *pf->planes ) ); Z_Free(facets); } #endif // _XBOX static patchCollide_t *pfScratch = 0; void CM_PreparePatchCollide(int num) { pfScratch = (patchCollide_t *) Z_Malloc( sizeof( *pfScratch ) * num, TAG_BSP, qfalse ); } cGrid_t *cm_grid = 0; void CM_GridAlloc() { if (cm_grid) return; cm_grid = (cGrid_t*)Z_Malloc(sizeof(cGrid_t), TAG_TEMP_WORKSPACE, qfalse); } void CM_GridDealloc() { Z_Free(cm_grid); cm_grid = 0; } /* =================== CM_GeneratePatchCollide Creates an internal structure that will be used to perform collision detection with a patch mesh. Points is packed as concatenated rows. =================== */ #ifdef _XBOX struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points, facetLoad_t *facetbuf, int *gridbuf ) { patchCollide_t *pf; // --AAA--AAA-- // cGrid_t *grid = new cGrid_t; cGrid_t *grid = cm_grid; // --AAA--AAA-- int i, j; memset(grid, 0, sizeof(cGrid_t)); if ( width <= 2 || height <= 2 || !points ) { Com_Error( ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", width, height, points ); } if ( !(width & 1) || !(height & 1) ) { Com_Error( ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes" ); } if ( width > CM_MAX_GRID_SIZE || height > CM_MAX_GRID_SIZE ) { Com_Error( ERR_DROP, "CM_GeneratePatchFacets: source is > CM_MAX_GRID_SIZE" ); } // build a grid grid->width = width; grid->height = height; grid->wrapWidth = qfalse; grid->wrapHeight = qfalse; for ( i = 0 ; i < width ; i++ ) { for ( j = 0 ; j < height ; j++ ) { VectorCopy( points[j*width + i], grid->points[i][j] ); } } // subdivide the grid CM_SetGridWrapWidth( grid ); CM_SubdivideGridColumns( grid ); CM_RemoveDegenerateColumns( grid ); CM_TransposeGrid( grid ); CM_SetGridWrapWidth( grid ); CM_SubdivideGridColumns( grid ); CM_RemoveDegenerateColumns( grid ); // we now have a grid of points exactly on the curve // the aproximate surface defined by these points will be // collided against // --AAA--AAA-- // pf = (patchCollide_t *) Z_Malloc( sizeof( *pf ), TAG_BSP, qfalse ); pf = pfScratch++; // --AAA--AAA-- ClearBounds( pf->bounds[0], pf->bounds[1] ); for ( i = 0 ; i < grid->width ; i++ ) { for ( j = 0 ; j < grid->height ; j++ ) { AddPointToBounds( grid->points[i][j], pf->bounds[0], pf->bounds[1] ); } } c_totalPatchBlocks += ( grid->width - 1 ) * ( grid->height - 1 ); // generate a bsp tree for the surface CM_PatchCollideFromGrid( grid, pf, facetbuf, gridbuf ); // expand by one unit for epsilon purposes pf->bounds[0][0] -= 1; pf->bounds[0][1] -= 1; pf->bounds[0][2] -= 1; pf->bounds[1][0] += 1; pf->bounds[1][1] += 1; pf->bounds[1][2] += 1; // --AAA--AAA-- // delete grid; // --AAA--AAA-- return pf; } #else struct patchCollide_s *CM_GeneratePatchCollide( int width, int height, vec3_t *points ) { patchCollide_t *pf; MAC_STATIC cGrid_t grid; int i, j; if ( width <= 2 || height <= 2 || !points ) { Com_Error( ERR_DROP, "CM_GeneratePatchFacets: bad parameters: (%i, %i, %p)", width, height, points ); } if ( !(width & 1) || !(height & 1) ) { Com_Error( ERR_DROP, "CM_GeneratePatchFacets: even sizes are invalid for quadratic meshes" ); } if ( width > CM_MAX_GRID_SIZE || height > CM_MAX_GRID_SIZE ) { Com_Error( ERR_DROP, "CM_GeneratePatchFacets: source is > CM_MAX_GRID_SIZE" ); } // build a grid grid.width = width; grid.height = height; grid.wrapWidth = qfalse; grid.wrapHeight = qfalse; for ( i = 0 ; i < width ; i++ ) { for ( j = 0 ; j < height ; j++ ) { VectorCopy( points[j*width + i], grid.points[i][j] ); } } // subdivide the grid CM_SetGridWrapWidth( &grid ); CM_SubdivideGridColumns( &grid ); CM_RemoveDegenerateColumns( &grid ); CM_TransposeGrid( &grid ); CM_SetGridWrapWidth( &grid ); CM_SubdivideGridColumns( &grid ); CM_RemoveDegenerateColumns( &grid ); // we now have a grid of points exactly on the curve // the aproximate surface defined by these points will be // collided against pf = (patchCollide_t *) Z_Malloc( sizeof( *pf ), TAG_BSP, qfalse ); ClearBounds( pf->bounds[0], pf->bounds[1] ); for ( i = 0 ; i < grid.width ; i++ ) { for ( j = 0 ; j < grid.height ; j++ ) { AddPointToBounds( grid.points[i][j], pf->bounds[0], pf->bounds[1] ); } } c_totalPatchBlocks += ( grid.width - 1 ) * ( grid.height - 1 ); // generate a bsp tree for the surface CM_PatchCollideFromGrid( &grid, pf ); // expand by one unit for epsilon purposes pf->bounds[0][0] -= 1; pf->bounds[0][1] -= 1; pf->bounds[0][2] -= 1; pf->bounds[1][0] += 1; pf->bounds[1][1] += 1; pf->bounds[1][2] += 1; return pf; } #endif // _XBOX /* ================================================================================ TRACE TESTING ================================================================================ */ /* ==================== CM_TraceThroughPatchCollide Modifies tr->tr if any of the facets effect the trace ==================== */ /* void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { int i, j, n; float d1, d2, offset, planedist, fraction; vec3_t v1, v2, normal, point; patchPlane_t *planes; facet_t *facet; // facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { planes = &pc->planes[ facet->surfacePlane ]; VectorCopy(planes->plane, normal); for (n = 0; n < 3; n++) { if (normal[n] > 0) v1[n] = tw->size[0][n]; else v1[n] = tw->size[1][n]; } //end for VectorNegate(normal, v2); offset = DotProduct(v1, v2); //offset = 0; // planedist = planes->plane[3] + offset; // d1 = DotProduct( tw->start, normal ) - planedist; d2 = DotProduct( tw->end, normal ) - planedist; // if completely in front of face, no intersection with the entire patch if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) { continue; } // if it doesn't cross the plane, the plane isn't relevent if (d1 <= 0 && d2 <= 0 ) { continue; } // crosses face if (d1 > d2) { // enter fraction = (d1-SURFACE_CLIP_EPSILON) / (d1-d2); if ( fraction < 0 ) { fraction = 0; } for (j = 0; j < 3; j++) point[j] = tw->start[j] + (tw->end[j] - tw->start[j]) * fraction; } else { continue; } // for (j = 0; j < facet->numBorders; j++) { planes = &pc->planes[ facet->borderPlanes[j] ]; if (!facet->borderInward[j]) { VectorNegate(planes->plane, normal); planedist = -planes->plane[3]; } //end if else { VectorCopy(planes->plane, normal); planedist = planes->plane[3]; } //end else for (n = 0; n < 3; n++) { if (normal[n] > 0) v1[n] = tw->size[0][n]; else v1[n] = tw->size[1][n]; } //end for VectorNegate(normal, v2); offset = DotProduct(v1, v2); //offset = 0; planedist -= offset; //the hit point should be in front of the (inward facing) border plane if (DotProduct(point, normal) - planedist < -ON_EPSILON) break; } //end for if (j < facet->numBorders) continue; // if (fraction < tw->trace.fraction) { debugPatchCollide = pc; debugFacet = facet; tw->trace.fraction = fraction; planes = &pc->planes[ facet->surfacePlane ]; VectorCopy( planes->plane, tw->trace.plane.normal ); tw->trace.plane.dist = planes->plane[3]; } //end if } //end for } //end of the function CM_TraceThroughPatchCollide*/ /* ==================== CM_TracePointThroughPatchCollide special case for point traces because the patch collide "brushes" have no volume ==================== */ #ifdef _XBOX void CM_TracePointThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { qboolean frontFacing[MAX_PATCH_PLANES]; float intersection[MAX_PATCH_PLANES]; float intersect; const patchPlane_t *planes; const facet_t *facet; int i, j, k; float offset; float d1, d2; #ifndef BSPC static cvar_t *cv; #endif //BSPC #ifndef BSPC if ( !cm_playerCurveClip->integer && !tw->isPoint ) { return; // FIXME: until I get player sized clipping working right } #endif if (!pc->numFacets) { //not gonna do anything anyhow? return; } // determine the trace's relationship to all planes planes = pc->planes; for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; if ( d1 <= 0 ) { frontFacing[i] = qfalse; } else { frontFacing[i] = qtrue; } if ( d1 == d2 ) { intersection[i] = WORLD_SIZE; } else { intersection[i] = d1 / ( d1 - d2 ); if ( intersection[i] <= 0 ) { intersection[i] = WORLD_SIZE; } } } // see if any of the surface planes are intersected facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { if ( !frontFacing[facet->surfacePlane] ) { continue; } intersect = intersection[facet->surfacePlane]; if ( intersect < 0 ) { continue; // surface is behind the starting point } if ( intersect > tw->trace.fraction ) { continue; // already hit something closer } for ( j = 0 ; j < facet->numBorders ; j++ ) { k = facet->GetBorderPlanes()[j]; if ( frontFacing[k] ^ facet->GetBorderInward()[j] ) { if ( intersection[k] > intersect ) { break; } } else { if ( intersection[k] < intersect ) { break; } } } if ( j == facet->numBorders ) { // we hit this facet #ifndef BSPC if (!cv) { cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); } if (cv->integer) { debugPatchCollide = pc; debugFacet = facet; } #endif //BSPC planes = &pc->planes[facet->surfacePlane]; // calculate intersection with a slight pushoff offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; tw->trace.fraction = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); if ( tw->trace.fraction < 0 ) { tw->trace.fraction = 0; } VectorCopy( planes->plane, tw->trace.plane.normal ); tw->trace.plane.dist = planes->plane[3]; } } } #else // _XBOX void CM_TracePointThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { qboolean frontFacing[MAX_PATCH_PLANES]; float intersection[MAX_PATCH_PLANES]; float intersect; const patchPlane_t *planes; const facet_t *facet; int i, j, k; float offset; float d1, d2; #ifndef BSPC static cvar_t *cv; #endif //BSPC #ifndef BSPC if ( !cm_playerCurveClip->integer && !tw->isPoint ) { return; // FIXME: until I get player sized clipping working right } #endif if (!pc->numFacets) { //not gonna do anything anyhow? return; } // determine the trace's relationship to all planes planes = pc->planes; for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; if ( d1 <= 0 ) { frontFacing[i] = qfalse; } else { frontFacing[i] = qtrue; } if ( d1 == d2 ) { intersection[i] = WORLD_SIZE; } else { intersection[i] = d1 / ( d1 - d2 ); if ( intersection[i] <= 0 ) { intersection[i] = WORLD_SIZE; } } } // see if any of the surface planes are intersected facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { if ( !frontFacing[facet->surfacePlane] ) { continue; } intersect = intersection[facet->surfacePlane]; if ( intersect < 0 ) { continue; // surface is behind the starting point } if ( intersect > tw->trace.fraction ) { continue; // already hit something closer } for ( j = 0 ; j < facet->numBorders ; j++ ) { k = facet->borderPlanes[j]; if ( frontFacing[k] ^ facet->borderInward[j] ) { if ( intersection[k] > intersect ) { break; } } else { if ( intersection[k] < intersect ) { break; } } } if ( j == facet->numBorders ) { // we hit this facet #ifndef BSPC if (!cv) { cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); } if (cv->integer) { debugPatchCollide = pc; debugFacet = facet; } #endif //BSPC planes = &pc->planes[facet->surfacePlane]; // calculate intersection with a slight pushoff offset = DotProduct( tw->offsets[ planes->signbits ], planes->plane ); d1 = DotProduct( tw->start, planes->plane ) - planes->plane[3] + offset; d2 = DotProduct( tw->end, planes->plane ) - planes->plane[3] + offset; tw->trace.fraction = ( d1 - SURFACE_CLIP_EPSILON ) / ( d1 - d2 ); if ( tw->trace.fraction < 0 ) { tw->trace.fraction = 0; } VectorCopy( planes->plane, tw->trace.plane.normal ); tw->trace.plane.dist = planes->plane[3]; } } } #endif /* ==================== CM_CheckFacetPlane ==================== */ int CM_CheckFacetPlane(float *plane, vec3_t start, vec3_t end, float *enterFrac, float *leaveFrac, int *hit) { float d1, d2, f; *hit = qfalse; d1 = DotProduct( start, plane ) - plane[3]; d2 = DotProduct( end, plane ) - plane[3]; // if completely in front of face, no intersection with the entire facet if (d1 > 0 && ( d2 >= SURFACE_CLIP_EPSILON || d2 >= d1 ) ) { return qfalse; } // if it doesn't cross the plane, the plane isn't relevent if (d1 <= 0 && d2 <= 0 ) { return qtrue; } // crosses face if (d1 > d2) { // enter f = (d1-SURFACE_CLIP_EPSILON) / (d1-d2); if ( f < 0 ) { f = 0; } //always favor previous plane hits and thus also the surface plane hit if (f > *enterFrac) { *enterFrac = f; *hit = qtrue; } } else { // leave f = (d1+SURFACE_CLIP_EPSILON) / (d1-d2); if ( f > 1 ) { f = 1; } if (f < *leaveFrac) { *leaveFrac = f; } } return qtrue; } /* ==================== CM_TraceThroughPatchCollide ==================== */ #ifdef _XBOX void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { int i, j, hit, hitnum; float offset, enterFrac, leaveFrac, t; patchPlane_t *planes; facet_t *facet; float plane[4], bestplane[4]; vec3_t startp, endp; #ifndef BSPC static cvar_t *cv; #endif //BSPC #ifndef CULL_BBOX // I'm not sure if test is strictly correct. Are all // bboxes axis aligned? Do I care? It seems to work // good enough... for ( i = 0 ; i < 3 ; i++ ) { if ( tw->bounds[0][i] > pc->bounds[1][i] || tw->bounds[1][i] < pc->bounds[0][i] ) { return; } } #endif if (tw->isPoint) { CM_TracePointThroughPatchCollide( tw, pc ); return; } #ifndef ADDBEVELS CM_TracePointThroughPatchCollide( tw, pc ); return; #endif // facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { enterFrac = -1.0; leaveFrac = 1.0; hitnum = -1; // planes = &pc->planes[ facet->surfacePlane ]; VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); VectorSubtract( tw->end, tw->sphere.offset, endp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); VectorAdd( tw->end, tw->sphere.offset, endp ); } } else { offset = DotProduct( tw->offsets[ planes->signbits ], plane); plane[3] -= offset; VectorCopy( tw->start, startp ); VectorCopy( tw->end, endp ); } if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) { continue; } if (hit) { Vector4Copy(plane, bestplane); } for ( j = 0 ; j < facet->numBorders ; j++ ) { planes = &pc->planes[ facet->GetBorderPlanes()[j] ]; if (facet->GetBorderInward()[j]) { VectorNegate(planes->plane, plane); plane[3] = -planes->plane[3]; } else { VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; } if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); VectorSubtract( tw->end, tw->sphere.offset, endp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); VectorAdd( tw->end, tw->sphere.offset, endp ); } } else { // NOTE: this works even though the plane might be flipped because the bbox is centered offset = DotProduct( tw->offsets[ planes->signbits ], plane); plane[3] += Q_fabs(offset); VectorCopy( tw->start, startp ); VectorCopy( tw->end, endp ); } if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) { break; } if (hit) { hitnum = j; Vector4Copy(plane, bestplane); } } if (j < facet->numBorders) continue; //never clip against the back side if (hitnum == facet->numBorders - 1) continue; if (enterFrac < leaveFrac && enterFrac >= 0) { if (enterFrac < tw->trace.fraction) { if (enterFrac < 0) { enterFrac = 0; } #ifndef BSPC if (!cv) { cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); } if (cv && cv->integer) { debugPatchCollide = pc; debugFacet = facet; } #endif // BSPC tw->trace.fraction = enterFrac; VectorCopy( bestplane, tw->trace.plane.normal ); tw->trace.plane.dist = bestplane[3]; } } } } #else // _XBOX void CM_TraceThroughPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { int i, j, hit, hitnum; float offset, enterFrac, leaveFrac, t; patchPlane_t *planes; facet_t *facet; float plane[4], bestplane[4]; vec3_t startp, endp; #ifndef BSPC static cvar_t *cv; #endif //BSPC if (tw->isPoint) { CM_TracePointThroughPatchCollide( tw, pc ); return; } #ifndef ADDBEVELS CM_TracePointThroughPatchCollide( tw, pc ); return; #endif // facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { enterFrac = -1.0; leaveFrac = 1.0; hitnum = -1; // planes = &pc->planes[ facet->surfacePlane ]; VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); VectorSubtract( tw->end, tw->sphere.offset, endp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); VectorAdd( tw->end, tw->sphere.offset, endp ); } } else { offset = DotProduct( tw->offsets[ planes->signbits ], plane); plane[3] -= offset; VectorCopy( tw->start, startp ); VectorCopy( tw->end, endp ); } if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) { continue; } if (hit) { Vector4Copy(plane, bestplane); } for ( j = 0 ; j < facet->numBorders ; j++ ) { planes = &pc->planes[ facet->borderPlanes[j] ]; if (facet->borderInward[j]) { VectorNegate(planes->plane, plane); plane[3] = -planes->plane[3]; } else { VectorCopy(planes->plane, plane); plane[3] = planes->plane[3]; } if ( tw->sphere.use ) { // adjust the plane distance apropriately for radius plane[3] += tw->sphere.radius; // find the closest point on the capsule to the plane t = DotProduct( plane, tw->sphere.offset ); if ( t > 0.0f ) { VectorSubtract( tw->start, tw->sphere.offset, startp ); VectorSubtract( tw->end, tw->sphere.offset, endp ); } else { VectorAdd( tw->start, tw->sphere.offset, startp ); VectorAdd( tw->end, tw->sphere.offset, endp ); } } else { // NOTE: this works even though the plane might be flipped because the bbox is centered offset = DotProduct( tw->offsets[ planes->signbits ], plane); plane[3] += fabs(offset); VectorCopy( tw->start, startp ); VectorCopy( tw->end, endp ); } if (!CM_CheckFacetPlane(plane, startp, endp, &enterFrac, &leaveFrac, &hit)) { break; } if (hit) { hitnum = j; Vector4Copy(plane, bestplane); } } if (j < facet->numBorders) continue; //never clip against the back side if (hitnum == facet->numBorders - 1) continue; if (enterFrac < leaveFrac && enterFrac >= 0) { if (enterFrac < tw->trace.fraction) { if (enterFrac < 0) { enterFrac = 0; } #ifndef BSPC if (!cv) { cv = Cvar_Get( "r_debugSurfaceUpdate", "1", 0 ); } if (cv && cv->integer) { debugPatchCollide = pc; debugFacet = facet; } #endif // BSPC tw->trace.fraction = enterFrac; VectorCopy( bestplane, tw->trace.plane.normal ); tw->trace.plane.dist = bestplane[3]; } } } } #endif // _XBOX /* ======================================================================= POSITION TEST ======================================================================= */ #define BOX_FRONT 0 #define BOX_BACK 1 #define BOX_CROSS 2 /* ==================== CM_PositionTestInPatchCollide Modifies tr->tr if any of the facets effect the trace ==================== */ #ifdef _XBOX qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { int cross[MAX_PATCH_PLANES]; const patchPlane_t *planes; const facet_t *facet; int i, j, k; float offset; float d; //return qfalse; #ifndef CULL_BBOX for ( i = 0 ; i < 3 ; i++ ) { if ( tw->bounds[0][i] > pc->bounds[1][i] || tw->bounds[1][i] < pc->bounds[0][i] ) { return qfalse; } } #endif // determine if the box is in front, behind, or crossing each plane planes = pc->planes; for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { d = DotProduct( tw->start, planes->plane ) - planes->plane[3]; offset = Q_fabs( DotProduct( tw->offsets[ planes->signbits ], planes->plane ) ); if ( d < -offset ) { cross[i] = BOX_FRONT; } else if ( d > offset ) { cross[i] = BOX_BACK; } else { cross[i] = BOX_CROSS; } } // see if any of the surface planes are intersected facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { // the facet plane must be in a cross state if ( cross[facet->surfacePlane] != BOX_CROSS ) { continue; } // all of the boundaries must be either cross or back for ( j = 0 ; j < facet->numBorders ; j++ ) { k = facet->GetBorderPlanes()[j]; if ( cross[ k ] == BOX_CROSS ) { continue; } if ( cross[k] ^ facet->GetBorderInward()[j] ) { break; } } // if we passed all borders, we are definately in this facet if ( j == facet->numBorders ) { return qtrue; } } return qfalse; } #else // _XBOX qboolean CM_PositionTestInPatchCollide( traceWork_t *tw, const struct patchCollide_s *pc ) { int cross[MAX_PATCH_PLANES]; const patchPlane_t *planes; const facet_t *facet; int i, j, k; float offset; float d; //return qfalse; #ifndef CULL_BBOX for ( i = 0 ; i < 3 ; i++ ) { if ( tw->bounds[0][i] > pc->bounds[1][i] || tw->bounds[1][i] < pc->bounds[0][i] ) { return qfalse; } } #endif // determine if the box is in front, behind, or crossing each plane planes = pc->planes; for ( i = 0 ; i < pc->numPlanes ; i++, planes++ ) { d = DotProduct( tw->start, planes->plane ) - planes->plane[3]; offset = fabs( DotProduct( tw->offsets[ planes->signbits ], planes->plane ) ); if ( d < -offset ) { cross[i] = BOX_FRONT; } else if ( d > offset ) { cross[i] = BOX_BACK; } else { cross[i] = BOX_CROSS; } } // see if any of the surface planes are intersected facet = pc->facets; for ( i = 0 ; i < pc->numFacets ; i++, facet++ ) { // the facet plane must be in a cross state if ( cross[facet->surfacePlane] != BOX_CROSS ) { continue; } // all of the boundaries must be either cross or back for ( j = 0 ; j < facet->numBorders ; j++ ) { k = facet->borderPlanes[j]; if ( cross[ k ] == BOX_CROSS ) { continue; } if ( cross[k] ^ facet->borderInward[j] ) { break; } } // if we passed all borders, we are definately in this facet if ( j == facet->numBorders ) { return qtrue; } } return qfalse; } #endif // _XBOX /* ======================================================================= DEBUGGING ======================================================================= */ /* ================== CM_DrawDebugSurface Called from the renderer ================== */ #ifndef BSPC void BotDrawDebugPolygons(void (*drawPoly)(int color, int numPoints, float *points), int value); #endif void CM_DrawDebugSurface( void (*drawPoly)(int color, int numPoints, float *points) ) { #ifndef _XBOX static cvar_t *cv; const patchCollide_t *pc; facet_t *facet; winding_t *w; int i, j, k, n; int curplanenum, planenum, curinward, inward; float plane[4]; vec3_t mins = {-15, -15, -28}, maxs = {15, 15, 28}; //vec3_t mins = {0, 0, 0}, maxs = {0, 0, 0}; vec3_t v1, v2; if ( !debugPatchCollide ) { return; } #ifndef BSPC if ( !cv ) { cv = Cvar_Get( "cm_debugSize", "2", 0 ); } #endif pc = debugPatchCollide; for ( i = 0, facet = pc->facets ; i < pc->numFacets ; i++, facet++ ) { for ( k = 0 ; k < facet->numBorders + 1; k++ ) { // if (k < facet->numBorders) { planenum = facet->borderPlanes[k]; inward = facet->borderInward[k]; } else { planenum = facet->surfacePlane; inward = qfalse; //continue; } Vector4Copy( pc->planes[ planenum ].plane, plane ); //planenum = facet->surfacePlane; if ( inward ) { VectorSubtract( vec3_origin, plane, plane ); plane[3] = -plane[3]; } plane[3] += cv->value; //* for (n = 0; n < 3; n++) { if (plane[n] > 0) v1[n] = maxs[n]; else v1[n] = mins[n]; } //end for VectorNegate(plane, v2); plane[3] += fabs(DotProduct(v1, v2)); //*/ w = BaseWindingForPlane( plane, plane[3] ); for ( j = 0 ; j < facet->numBorders + 1 && w; j++ ) { // if (j < facet->numBorders) { curplanenum = facet->borderPlanes[j]; curinward = facet->borderInward[j]; } else { curplanenum = facet->surfacePlane; curinward = qfalse; //continue; } // if (curplanenum == planenum) continue; Vector4Copy( pc->planes[ curplanenum ].plane, plane ); if ( !curinward ) { VectorSubtract( vec3_origin, plane, plane ); plane[3] = -plane[3]; } // if ( !facet->borderNoAdjust[j] ) { plane[3] -= cv->value; // } for (n = 0; n < 3; n++) { if (plane[n] > 0) v1[n] = maxs[n]; else v1[n] = mins[n]; } //end for VectorNegate(plane, v2); plane[3] -= fabs(DotProduct(v1, v2)); ChopWindingInPlace( &w, plane, plane[3], 0.1f ); } if ( w ) { if ( facet == debugFacet ) { drawPoly( 4, w->numpoints, w->p[0] ); //Com_Printf("blue facet has %d border planes\n", facet->numBorders); } else { drawPoly( 1, w->numpoints, w->p[0] ); } FreeWinding( w ); } else Com_Printf("winding chopped away by border planes\n"); } } // draw the debug block { vec3_t v[3]; VectorCopy( debugBlockPoints[0], v[0] ); VectorCopy( debugBlockPoints[1], v[1] ); VectorCopy( debugBlockPoints[2], v[2] ); drawPoly( 2, 3, v[0] ); VectorCopy( debugBlockPoints[2], v[0] ); VectorCopy( debugBlockPoints[3], v[1] ); VectorCopy( debugBlockPoints[0], v[2] ); drawPoly( 2, 3, v[0] ); } #if 0 vec3_t v[4]; v[0][0] = pc->bounds[1][0]; v[0][1] = pc->bounds[1][1]; v[0][2] = pc->bounds[1][2]; v[1][0] = pc->bounds[1][0]; v[1][1] = pc->bounds[0][1]; v[1][2] = pc->bounds[1][2]; v[2][0] = pc->bounds[0][0]; v[2][1] = pc->bounds[0][1]; v[2][2] = pc->bounds[1][2]; v[3][0] = pc->bounds[0][0]; v[3][1] = pc->bounds[1][1]; v[3][2] = pc->bounds[1][2]; drawPoly( 4, v[0] ); #endif #endif // _XBOX }
abergmeier/jedi_outcast
code/qcommon/cm_patch.cpp
C++
gpl-2.0
74,740
/* * Copyright (C) 2008-2019 TrinityCore <https://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/>. */ #ifdef _WIN32 #ifndef _WIN32_SERVICE_ #define _WIN32_SERVICE_ bool WinServiceInstall(); bool WinServiceUninstall(); bool WinServiceRun(); #endif // _WIN32_SERVICE_ #endif // _WIN32
123xlex/TrinityCore
src/common/Platform/ServiceWin32.h
C
gpl-2.0
1,071
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.nashorn.internal.runtime.linker; import static jdk.nashorn.internal.lookup.Lookup.MH; import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; import jdk.dynalink.CallSiteDescriptor; import jdk.dynalink.NamedOperation; import jdk.dynalink.Operation; import jdk.dynalink.beans.BeansLinker; import jdk.dynalink.beans.StaticClass; import jdk.dynalink.linker.GuardedInvocation; import jdk.dynalink.linker.GuardingDynamicLinker; import jdk.dynalink.linker.GuardingTypeConverterFactory; import jdk.dynalink.linker.LinkRequest; import jdk.dynalink.linker.LinkerServices; import jdk.dynalink.linker.support.Guards; import jdk.dynalink.linker.support.Lookup; import jdk.nashorn.internal.codegen.types.Type; import jdk.nashorn.internal.runtime.ECMAException; import jdk.nashorn.internal.runtime.JSType; import jdk.nashorn.internal.runtime.ScriptRuntime; import jdk.nashorn.internal.runtime.UnwarrantedOptimismException; /** * Nashorn bottom linker; used as a last-resort catch-all linker for all linking requests that fall through all other * linkers (see how {@link Bootstrap} class configures the dynamic linker in its static initializer). It will throw * appropriate ECMAScript errors for attempts to invoke operations on {@code null}, link no-op property getters and * setters for Java objects that couldn't be linked by any other linker, and throw appropriate ECMAScript errors for * attempts to invoke arbitrary Java objects as functions or constructors. */ final class NashornBottomLinker implements GuardingDynamicLinker, GuardingTypeConverterFactory { @Override public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception { final Object self = linkRequest.getReceiver(); if (self == null) { return linkNull(linkRequest); } // None of the objects that can be linked by NashornLinker should ever reach here. Basically, anything below // this point is a generic Java bean. Therefore, reaching here with a ScriptObject is a Nashorn bug. assert isExpectedObject(self) : "Couldn't link " + linkRequest.getCallSiteDescriptor() + " for " + self.getClass().getName(); return linkBean(linkRequest); } private static final MethodHandle EMPTY_PROP_GETTER = MH.dropArguments(MH.constant(Object.class, UNDEFINED), 0, Object.class); private static final MethodHandle EMPTY_ELEM_GETTER = MH.dropArguments(EMPTY_PROP_GETTER, 0, Object.class); private static final MethodHandle EMPTY_PROP_SETTER = MH.asType(EMPTY_ELEM_GETTER, EMPTY_ELEM_GETTER.type().changeReturnType(void.class)); private static final MethodHandle EMPTY_ELEM_SETTER = MH.dropArguments(EMPTY_PROP_SETTER, 0, Object.class); private static final MethodHandle THROW_STRICT_PROPERTY_SETTER; private static final MethodHandle THROW_STRICT_PROPERTY_REMOVER; private static final MethodHandle THROW_OPTIMISTIC_UNDEFINED; private static final MethodHandle MISSING_PROPERTY_REMOVER; static { final Lookup lookup = new Lookup(MethodHandles.lookup()); THROW_STRICT_PROPERTY_SETTER = lookup.findOwnStatic("throwStrictPropertySetter", void.class, Object.class, Object.class); THROW_STRICT_PROPERTY_REMOVER = lookup.findOwnStatic("throwStrictPropertyRemover", boolean.class, Object.class, Object.class); THROW_OPTIMISTIC_UNDEFINED = lookup.findOwnStatic("throwOptimisticUndefined", Object.class, int.class); MISSING_PROPERTY_REMOVER = lookup.findOwnStatic("missingPropertyRemover", boolean.class, Object.class, Object.class); } private static GuardedInvocation linkBean(final LinkRequest linkRequest) throws Exception { final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); final Object self = linkRequest.getReceiver(); switch (NashornCallSiteDescriptor.getStandardOperation(desc)) { case NEW: if(BeansLinker.isDynamicConstructor(self)) { throw typeError("no.constructor.matches.args", ScriptRuntime.safeToString(self)); } if(BeansLinker.isDynamicMethod(self)) { throw typeError("method.not.constructor", ScriptRuntime.safeToString(self)); } throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self)); case CALL: if(BeansLinker.isDynamicConstructor(self)) { throw typeError("constructor.requires.new", ScriptRuntime.safeToString(self)); } if(BeansLinker.isDynamicMethod(self)) { throw typeError("no.method.matches.args", ScriptRuntime.safeToString(self)); } throw typeError("not.a.function", NashornCallSiteDescriptor.getFunctionErrorMessage(desc, self)); default: // Everything else is supposed to have been already handled by Bootstrap.beansLinker // delegating to linkNoSuchBeanMember throw new AssertionError("unknown call type " + desc); } } static MethodHandle linkMissingBeanMember(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception { final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); final String operand = NashornCallSiteDescriptor.getOperand(desc); final boolean strict = NashornCallSiteDescriptor.isStrict(desc); switch (NashornCallSiteDescriptor.getStandardOperation(desc)) { case GET: if (NashornCallSiteDescriptor.isOptimistic(desc)) { return adaptThrower(MethodHandles.insertArguments(THROW_OPTIMISTIC_UNDEFINED, 0, NashornCallSiteDescriptor.getProgramPoint(desc)), desc); } else if (operand != null) { return getInvocation(EMPTY_PROP_GETTER, linkerServices, desc); } return getInvocation(EMPTY_ELEM_GETTER, linkerServices, desc); case SET: if (strict) { return adaptThrower(bindOperand(THROW_STRICT_PROPERTY_SETTER, operand), desc); } else if (operand != null) { return getInvocation(EMPTY_PROP_SETTER, linkerServices, desc); } return getInvocation(EMPTY_ELEM_SETTER, linkerServices, desc); case REMOVE: if (strict) { return adaptThrower(bindOperand(THROW_STRICT_PROPERTY_REMOVER, operand), desc); } return getInvocation(bindOperand(MISSING_PROPERTY_REMOVER, operand), linkerServices, desc); default: throw new AssertionError("unknown call type " + desc); } } private static MethodHandle bindOperand(final MethodHandle handle, final String operand) { return operand == null ? handle : MethodHandles.insertArguments(handle, 1, operand); } private static MethodHandle adaptThrower(final MethodHandle handle, final CallSiteDescriptor desc) { final MethodType targetType = desc.getMethodType(); final int paramCount = handle.type().parameterCount(); return MethodHandles .dropArguments(handle, paramCount, targetType.parameterList().subList(paramCount, targetType.parameterCount())) .asType(targetType); } @SuppressWarnings("unused") private static void throwStrictPropertySetter(final Object self, final Object name) { throw createTypeError(self, name, "cant.set.property"); } @SuppressWarnings("unused") private static boolean throwStrictPropertyRemover(final Object self, final Object name) { if (isNonConfigurableProperty(self, name)) { throw createTypeError(self, name, "cant.delete.property"); } return true; } @SuppressWarnings("unused") private static boolean missingPropertyRemover(final Object self, final Object name) { return !isNonConfigurableProperty(self, name); } // Corresponds to ECMAScript 5.1 8.12.7 [[Delete]] point 3 check for "isConfigurable" (but negated) private static boolean isNonConfigurableProperty(final Object self, final Object name) { if (self instanceof StaticClass) { final Class<?> clazz = ((StaticClass)self).getRepresentedClass(); return BeansLinker.getReadableStaticPropertyNames(clazz).contains(name) || BeansLinker.getWritableStaticPropertyNames(clazz).contains(name) || BeansLinker.getStaticMethodNames(clazz).contains(name); } final Class<?> clazz = self.getClass(); return BeansLinker.getReadableInstancePropertyNames(clazz).contains(name) || BeansLinker.getWritableInstancePropertyNames(clazz).contains(name) || BeansLinker.getInstanceMethodNames(clazz).contains(name); } private static ECMAException createTypeError(final Object self, final Object name, final String msg) { return typeError(msg, String.valueOf(name), ScriptRuntime.safeToString(self)); } @SuppressWarnings("unused") private static Object throwOptimisticUndefined(final int programPoint) { throw new UnwarrantedOptimismException(UNDEFINED, programPoint, Type.OBJECT); } @Override public GuardedInvocation convertToType(final Class<?> sourceType, final Class<?> targetType, final Supplier<MethodHandles.Lookup> lookupSupplier) throws Exception { final GuardedInvocation gi = convertToTypeNoCast(sourceType, targetType); return gi == null ? null : gi.asType(MH.type(targetType, sourceType)); } /** * Main part of the implementation of {@link GuardingTypeConverterFactory#convertToType} that doesn't * care about adapting the method signature; that's done by the invoking method. Returns conversion * from Object to String/number/boolean (JS primitive types). * @param sourceType the source type * @param targetType the target type * @return a guarded invocation that converts from the source type to the target type. * @throws Exception if something goes wrong */ private static GuardedInvocation convertToTypeNoCast(final Class<?> sourceType, final Class<?> targetType) throws Exception { final MethodHandle mh = CONVERTERS.get(targetType); if (mh != null) { return new GuardedInvocation(mh); } return null; } private static MethodHandle getInvocation(final MethodHandle handle, final LinkerServices linkerServices, final CallSiteDescriptor desc) { return linkerServices.asTypeLosslessReturn(handle, desc.getMethodType()); } // Used solely in an assertion to figure out if the object we get here is something we in fact expect. Objects // linked by NashornLinker should never reach here. private static boolean isExpectedObject(final Object obj) { return !(NashornLinker.canLinkTypeStatic(obj.getClass())); } private static GuardedInvocation linkNull(final LinkRequest linkRequest) { final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor(); switch (NashornCallSiteDescriptor.getStandardOperation(desc)) { case NEW: case CALL: throw typeError("not.a.function", "null"); case GET: throw typeError(NashornCallSiteDescriptor.isMethodFirstOperation(desc) ? "no.such.function" : "cant.get.property", getArgument(linkRequest), "null"); case SET: throw typeError("cant.set.property", getArgument(linkRequest), "null"); case REMOVE: throw typeError("cant.delete.property", getArgument(linkRequest), "null"); default: throw new AssertionError("unknown call type " + desc); } } private static final Map<Class<?>, MethodHandle> CONVERTERS = new HashMap<>(); static { CONVERTERS.put(boolean.class, JSType.TO_BOOLEAN.methodHandle()); CONVERTERS.put(double.class, JSType.TO_NUMBER.methodHandle()); CONVERTERS.put(int.class, JSType.TO_INTEGER.methodHandle()); CONVERTERS.put(long.class, JSType.TO_LONG.methodHandle()); CONVERTERS.put(String.class, JSType.TO_STRING.methodHandle()); } private static String getArgument(final LinkRequest linkRequest) { final Operation op = linkRequest.getCallSiteDescriptor().getOperation(); if (op instanceof NamedOperation) { return ((NamedOperation)op).getName().toString(); } return ScriptRuntime.safeToString(linkRequest.getArguments()[1]); } }
md-5/jdk10
src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornBottomLinker.java
Java
gpl-2.0
14,098
<!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta content="charset=utf-8"> <title>FlexSlider 2</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <!-- Syntax Highlighter --> <link href="css/shCore.css" rel="stylesheet" type="text/css" /> <link href="css/shThemeDefault.css" rel="stylesheet" type="text/css" /> <!-- Demo CSS --> <link rel="stylesheet" href="css/demo.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../flexslider.css" type="text/css" media="screen" /> <!-- Modernizr --> <script src="js/modernizr.js"></script> </head> <body class="loading"> <div id="container" class="cf"> <header role="navigation"> <a class="logo" href="http://www.woothemes.com" title="WooThemes"> <img src="images/logo.png" alt="WooThemes" /> </a> <h1>FlexSlider 2</h1> <h2>The best responsive slider. Period.</h2> <a class="button green" href="https://github.com/woothemes/FlexSlider/zipball/master">Download Flexslider</a> <h3 class="nav-header">Other Examples</h3> <nav> <ul> <li><a href="index.html">Basic Slider</a></li> <li><a href="basic-slider-with-custom-direction-nav.html">Basic Slider customDirectionNav</a></li> <li><a href="basic-slider-with-caption.html">Basic Slider with Simple Caption</a></li> <li><a href="thumbnail-controlnav.html">Slider w/thumbnail controlNav pattern</a></li> <li><a href="thumbnail-slider.html">Slider w/thumbnail slider</a></li> <li><a href="basic-carousel.html">Basic Carousel</a></li> <li><a href="carousel-min-max.html">Carousel with min and max ranges</a></li> <li><a href="dynamic-carousel-min-max.html">Carousel with dynamic min/max ranges</a></li> <li class="active"><a href="video.html">Video & the api (vimeo)</a></li> <li><a href="video-wistia.html">Video & the api (wistia)</a></li> <li><a href="basic-carousel-rtl.html">Basic Carousel - RTL</a></li> </ul> </nav> </header> <div id="main" role="main"> <section class="slider"> <div class="flexslider"> <ul class="slides"> <li> <iframe id="player_1" src="https://player.vimeo.com/video/39683393?api=1&amp;player_id=player_1" width="500" height="281" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> </li> <li> <img src="images/kitchen_adventurer_lemon.jpg" /> </li> <li> <img src="images/kitchen_adventurer_donut.jpg" /> </li> <li> <img src="images/kitchen_adventurer_caramel.jpg" /> </li> </ul> </div> </section> <aside> <div class="cf"> <h3>Video</h3> <ul class="toggle cf"> <li class="js"><a href="#view-js">JS</a></li> <li class="html"><a href="#view-html">HTML</a></li> </ul> </div> <div id="view-js" class="code"> <pre class="brush: js; toolbar: false; gutter: false;"> // Can also be used with $(document).ready() $(window).load(function() { // Vimeo API nonsense var player = document.getElementById('player_1'); $f(player).addEvent('ready', ready); function addEvent(element, eventName, callback) { if (element.addEventListener) { element.addEventListener(eventName, callback, false) } else { element.attachEvent(eventName, callback, false); } } function ready(player_id) { var froogaloop = $f(player_id); froogaloop.addEvent('play', function(data) { $('.flexslider').flexslider("pause"); }); froogaloop.addEvent('pause', function(data) { $('.flexslider').flexslider("play"); }); } // Call fitVid before FlexSlider initializes, so the proper initial height can be retrieved. $(".flexslider") .fitVids() .flexslider({ animation: "slide", useCSS: false, animationLoop: false, smoothHeight: true, before: function(slider){ $f(player).api('pause'); } }); }); </pre> </div> <div id="view-html" class="code"> <pre class="brush: xml; toolbar: false; gutter: false;"> &lt;!-- Place somewhere in the &lt;body&gt; of your page --> &lt;div class="flexslider"> &lt;ul class="slides"> &lt;li> &lt;iframe id="player_1" src="https://player.vimeo.com/video/39683393?api=1&amp;player_id=player_1" width="500" height="281" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen>&lt;/iframe> &lt;/li> &lt;li> &lt;img src="slide2.jpg" /> &lt;/li> &lt;li> &lt;img src="slide3.jpg" /> &lt;/li> &lt;li> &lt;img src="slide4.jpg" /> &lt;/li> &lt;/ul> &lt;/div> </pre> </div> </aside> </div> </div> <!-- jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.min.js">\x3C/script>')</script> <!-- FlexSlider --> <script defer src="../jquery.flexslider.js"></script> <script type="text/javascript"> $(function(){ SyntaxHighlighter.all(); }); $(window).load(function(){ // Vimeo API nonsense var player = document.getElementById('player_1'); $f(player).addEvent('ready', ready); function addEvent(element, eventName, callback) { (element.addEventListener) ? element.addEventListener(eventName, callback, false) : element.attachEvent(eventName, callback, false); } function ready(player_id) { var froogaloop = $f(player_id); froogaloop.addEvent('play', function(data) { $('.flexslider').flexslider("pause"); }); froogaloop.addEvent('pause', function(data) { $('.flexslider').flexslider("play"); }); } // Call fitVid before FlexSlider initializes, so the proper initial height can be retrieved. $(".flexslider") .fitVids() .flexslider({ animation: "slide", useCSS: false, animationLoop: false, smoothHeight: true, start: function(slider){ $('body').removeClass('loading'); }, before: function(slider){ $f(player).api('pause'); } }); }); </script> <!-- Syntax Highlighter --> <script type="text/javascript" src="js/shCore.js"></script> <script type="text/javascript" src="js/shBrushXml.js"></script> <script type="text/javascript" src="js/shBrushJScript.js"></script> <!-- Optional FlexSlider Additions --> <script src="js/froogaloop.js"></script> <script src="js/jquery.fitvid.js"></script> <script src="js/demo.js"></script> </body> </html>
sunlight25/d8
web/themes/contrib/zircon/assets/includes/flexslider/demo/video.html
HTML
gpl-2.0
7,522
<?php /* * Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /** * * Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides resizable compute capacity in the cloud. It is designed to make * web-scale computing easier for developers. * * Amazon EC2's simple web service interface allows you to obtain and configure capacity with minimal friction. It provides you with complete * control of your computing resources and lets you run on Amazon's proven computing environment. Amazon EC2 reduces the time required to * obtain and boot new server instances to minutes, allowing you to quickly scale capacity, both up and down, as your computing requirements * change. Amazon EC2 changes the economics of computing by allowing you to pay only for capacity that you actually use. Amazon EC2 provides * developers the tools to build failure resilient applications and isolate themselves from common failure scenarios. * * Visit <a href="http://aws.amazon.com/ec2/">http://aws.amazon.com/ec2/</a> for more information. * * @version Tue Aug 23 12:47:35 PDT 2011 * @license See the included NOTICE.md file for complete information. * @copyright See the included NOTICE.md file for complete information. * @link http://aws.amazon.com/ec2/Amazon Elastic Compute Cloud * @link http://aws.amazon.com/documentation/ec2/Amazon Elastic Compute Cloud documentation */ class AmazonEC2 extends CFRuntime { /*%******************************************************************************************%*/ // CLASS CONSTANTS /** * Specify the default queue URL. */ const DEFAULT_URL = 'ec2.amazonaws.com'; /** * Specify the queue URL for the US-East (Northern Virginia) Region. */ const REGION_US_E1 = 'us-east-1'; /** * Specify the queue URL for the US-West (Northern California) Region. */ const REGION_US_W1 = 'us-west-1'; /** * Specify the queue URL for the EU (Ireland) Region. */ const REGION_EU_W1 = 'eu-west-1'; /** * Specify the queue URL for the Asia Pacific (Singapore) Region. */ const REGION_APAC_SE1 = 'ap-southeast-1'; /** * Specify the queue URL for the Asia Pacific (Japan) Region. */ const REGION_APAC_NE1 = 'ap-northeast-1'; /** * The "pending" state code of an EC2 instance. Useful for conditionals. */ const STATE_PENDING = 0; /** * The "running" state code of an EC2 instance. Useful for conditionals. */ const STATE_RUNNING = 16; /** * The "shutting-down" state code of an EC2 instance. Useful for conditionals. */ const STATE_SHUTTING_DOWN = 32; /** * The "terminated" state code of an EC2 instance. Useful for conditionals. */ const STATE_TERMINATED = 48; /** * The "stopping" state code of an EC2 instance. Useful for conditionals. */ const STATE_STOPPING = 64; /** * The "stopped" state code of an EC2 instance. Useful for conditionals. */ const STATE_STOPPED = 80; /*%******************************************************************************************%*/ // SETTERS /** * This allows you to explicitly sets the region for the service to use. * * @param string $region (Required) The region to explicitly set. Available options are <REGION_US_E1>, <REGION_US_W1>, <REGION_EU_W1>, or <REGION_APAC_SE1>. * @return $this A reference to the current instance. */ public function set_region($region) { $this->set_hostname('http://ec2.'. $region .'.amazonaws.com'); return $this; } /*%******************************************************************************************%*/ // CONSTRUCTOR /** * Constructs a new instance of <AmazonEC2>. If the <code>AWS_DEFAULT_CACHE_CONFIG</code> configuration * option is set, requests will be authenticated using a session token. Otherwise, requests will use * the older authentication method. * * @param string $key (Optional) Your AWS key, or a session key. If blank, it will look for the <code>AWS_KEY</code> constant. * @param string $secret_key (Optional) Your AWS secret key, or a session secret key. If blank, it will look for the <code>AWS_SECRET_KEY</code> constant. * @param string $token (optional) An AWS session token. If blank, a request will be made to the AWS Secure Token Service to fetch a set of session credentials. * @return boolean A value of <code>false</code> if no valid values are set, otherwise <code>true</code>. */ public function __construct($key = null, $secret_key = null, $token = null) { $this->api_version = '2011-02-28'; $this->hostname = self::DEFAULT_URL; if (!$key && !defined('AWS_KEY')) { // @codeCoverageIgnoreStart throw new EC2_Exception('No account key was passed into the constructor, nor was it set in the AWS_KEY constant.'); // @codeCoverageIgnoreEnd } if (!$secret_key && !defined('AWS_SECRET_KEY')) { // @codeCoverageIgnoreStart throw new EC2_Exception('No account secret was passed into the constructor, nor was it set in the AWS_SECRET_KEY constant.'); // @codeCoverageIgnoreEnd } if (defined('AWS_DEFAULT_CACHE_CONFIG') && AWS_DEFAULT_CACHE_CONFIG) { return parent::session_based_auth($key, $secret_key, $token); } return parent::__construct($key, $secret_key); } /*%******************************************************************************************%*/ // SERVICE METHODS /** * * The RebootInstances operation requests a reboot of one or more instances. This operation is asynchronous; it only queues a request to * reboot the specified instance(s). The operation will succeed if the instances are valid and belong to the user. Requests to reboot * terminated instances are ignored. * * @param string|array $instance_id (Required) The list of instances to terminate. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function reboot_instances($instance_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($instance_id) ? $instance_id : array($instance_id)) ))); return $this->authenticate('RebootInstances', $opt, $this->hostname); } /** * * The DescribeReservedInstances operation describes Reserved Instances that were purchased for use with your account. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>ReservedInstancesId</code> - <code>string|array</code> - Optional - The optional list of Reserved Instance IDs to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for ReservedInstances. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_reserved_instances($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['ReservedInstancesId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ReservedInstancesId' => (is_array($opt['ReservedInstancesId']) ? $opt['ReservedInstancesId'] : array($opt['ReservedInstancesId'])) ))); unset($opt['ReservedInstancesId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeReservedInstances', $opt, $this->hostname); } /** * * The DescribeAvailabilityZones operation describes availability zones that are currently available to the account and their states. * * Availability zones are not the same across accounts. The availability zone <code>us-east-1a</code> for account A is not necessarily the * same as <code>us-east-1a</code> for account B. Zone assignments are mapped independently for each account. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>ZoneName</code> - <code>string|array</code> - Optional - A list of the availability zone names to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for AvailabilityZones. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_availability_zones($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['ZoneName'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ZoneName' => (is_array($opt['ZoneName']) ? $opt['ZoneName'] : array($opt['ZoneName'])) ))); unset($opt['ZoneName']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeAvailabilityZones', $opt, $this->hostname); } /** * * Detach a previously attached volume from a running instance. * * @param string $volume_id (Required) The ID of the volume to detach. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>InstanceId</code> - <code>string</code> - Optional - The ID of the instance from which to detach the the specified volume. </li> * <li><code>Device</code> - <code>string</code> - Optional - The device name to which the volume is attached on the specified instance. </li> * <li><code>Force</code> - <code>boolean</code> - Optional - Forces detachment if the previous detachment attempt did not occur cleanly (logging into an instance, unmounting the volume, and detaching normally). This option can lead to data loss or a corrupted file system. Use this option only as a last resort to detach a volume from a failed instance. The instance will not have an opportunity to flush file system caches nor file system meta data. If you use this option, you must perform file system check and repair procedures. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function detach_volume($volume_id, $opt = null) { if (!$opt) $opt = array(); $opt['VolumeId'] = $volume_id; return $this->authenticate('DetachVolume', $opt, $this->hostname); } /** * * The DeleteKeyPair operation deletes a key pair. * * @param string $key_name (Required) The name of the Amazon EC2 key pair to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_key_pair($key_name, $opt = null) { if (!$opt) $opt = array(); $opt['KeyName'] = $key_name; return $this->authenticate('DeleteKeyPair', $opt, $this->hostname); } /** * * Disables monitoring for a running instance. * * @param string|array $instance_id (Required) The list of Amazon EC2 instances on which to disable monitoring. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function unmonitor_instances($instance_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($instance_id) ? $instance_id : array($instance_id)) ))); return $this->authenticate('UnmonitorInstances', $opt, $this->hostname); } /** * * Attaches a VPN gateway to a VPC. This is the last step required to get your VPC fully connected to your data center before launching * instances in it. For more information, go to Process for Using Amazon VPC in the Amazon Virtual Private Cloud Developer Guide. * * @param string $vpn_gateway_id (Required) The ID of the VPN gateway to attach to the VPC. * @param string $vpc_id (Required) The ID of the VPC to attach to the VPN gateway. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function attach_vpn_gateway($vpn_gateway_id, $vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpnGatewayId'] = $vpn_gateway_id; $opt['VpcId'] = $vpc_id; return $this->authenticate('AttachVpnGateway', $opt, $this->hostname); } /** * * Creates an Amazon EBS-backed AMI from a "running" or "stopped" instance. AMIs that use an Amazon EBS root device boot faster than AMIs that * use instance stores. They can be up to 1 TiB in size, use storage that persists on instance failure, and can be stopped and started. * * @param string $instance_id (Required) The ID of the instance from which to create the new image. * @param string $name (Required) The name for the new AMI being created. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Description</code> - <code>string</code> - Optional - The description for the new AMI being created. </li> * <li><code>NoReboot</code> - <code>boolean</code> - Optional - By default this property is set to <code>false</code>, which means Amazon EC2 attempts to cleanly shut down the instance before image creation and reboots the instance afterwards. When set to true, Amazon EC2 will not shut down the instance before creating the image. When this option is used, file system integrity on the created image cannot be guaranteed. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_image($instance_id, $name, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; $opt['Name'] = $name; return $this->authenticate('CreateImage', $opt, $this->hostname); } /** * * The DeleteSecurityGroup operation deletes a security group. * * If you attempt to delete a security group that contains instances, a fault is returned. * * If you attempt to delete a security group that is referenced by another security group, a fault is returned. For example, if security group * B has a rule that allows access from security group A, security group A cannot be deleted until the allow rule is removed. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GroupName</code> - <code>string</code> - Optional - The name of the Amazon EC2 security group to delete. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - The ID of the Amazon EC2 security group to delete. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_security_group($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DeleteSecurityGroup', $opt, $this->hostname); } /** * * This action applies only to security groups in a VPC; it's not supported for EC2 security groups. For information about Amazon Virtual * Private Cloud and VPC security groups, go to the Amazon Virtual Private Cloud User Guide. * * The action adds one or more egress rules to a VPC security group. Specifically, this permits instances in a security group to send traffic * to either one or more destination CIDR IP address ranges, or to one or more destination security groups in the same VPC. * * Each rule consists of the protocol (e.g., TCP), plus either a CIDR range, or a source group. For the TCP and UDP protocols, you must also * specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use <code>-1</code> * as a wildcard for the ICMP type or code. * * Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. * * <b>Important: </b> For VPC security groups: You can have up to 50 rules total per group (covering both ingress and egress). * * @param string $group_id (Required) ID of the VPC security group to modify. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>IpPermissions</code> - <code>array</code> - Optional - List of IP permissions to authorize on the specified security group. Specifying permissions through IP permissions is the preferred way of authorizing permissions since it offers more flexibility and control. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>IpProtocol</code> - <code>string</code> - Optional - The IP protocol of this permission. Valid protocol values: <code>tcp</code>, <code>udp</code>, <code>icmp</code> </li> * <li><code>FromPort</code> - <code>integer</code> - Optional - Start of port range for the TCP and UDP protocols, or an ICMP type number. An ICMP type number of <code>-1</code> indicates a wildcard (i.e., any ICMP type number). </li> * <li><code>ToPort</code> - <code>integer</code> - Optional - End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of <code>-1</code> indicates a wildcard (i.e., any ICMP code). </li> * <li><code>Groups</code> - <code>array</code> - Optional - The list of AWS user IDs and groups included in this permission. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The AWS user ID of an account. </li> * <li><code>GroupName</code> - <code>string</code> - Optional - Name of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - ID of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * </ul></li> * </ul></li> * <li><code>IpRanges</code> - <code>string|array</code> - Optional - The list of CIDR IP ranges included in this permission. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function authorize_security_group_egress($group_id, $opt = null) { if (!$opt) $opt = array(); $opt['GroupId'] = $group_id; // Optional parameter if (isset($opt['IpPermissions'])) { $opt = array_merge($opt, CFComplexType::map(array( 'IpPermissions' => $opt['IpPermissions'] ))); unset($opt['IpPermissions']); } return $this->authenticate('AuthorizeSecurityGroupEgress', $opt, $this->hostname); } /** * Retrieves the encrypted administrator password for the instances running Windows. * * The Windows password is only generated the first time an AMI is launched. It is not generated for * rebundled AMIs or after the password is changed on an instance. The password is encrypted using the * key pair that you provided. * * @param string $instance_id (Required) The ID of the instance for which you want the Windows administrator password. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>DecryptPasswordWithKey</code> - <code>string</code> - Optional - Enables the decryption of the Administrator password for the given Microsoft Windows instance. Specifies the RSA private key that is associated with the keypair ID which was used to launch the Microsoft Windows instance.</li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This is useful for manually-managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function get_password_data($instance_id, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; // Unless DecryptPasswordWithKey is set, simply return the response. if (!isset($opt['DecryptPasswordWithKey'])) { return $this->authenticate('GetPasswordData', $opt, $this->hostname); } // Otherwise, decrypt the password. else { // Get a resource representing the private key. $private_key = openssl_pkey_get_private($opt['DecryptPasswordWithKey']); unset($opt['DecryptPasswordWithKey']); // Fetch the encrypted password. $response = $this->authenticate('GetPasswordData', $opt, $this->hostname); $data = trim((string) $response->body->passwordData); // If it's Base64-encoded... if ($this->util->is_base64($data)) { // Base64-decode it, and decrypt it with the private key. if (openssl_private_decrypt(base64_decode($data), $decrypted, $private_key)) { // Replace the previous password data with the decrypted value. $response->body->passwordData = $decrypted; } } return $response; } } /** * * Associates a set of DHCP options (that you've previously created) with the specified VPC. Or, associates the default DHCP options with the * VPC. The default set consists of the standard EC2 host name, no domain name, no DNS server, no NTP server, and no NetBIOS server or node * type. After you associate the options with the VPC, any existing instances and all new instances that you launch in that VPC use the * options. For more information about the supported DHCP options and using them with Amazon VPC, go to Using DHCP Options in the Amazon * Virtual Private Cloud Developer Guide. * * @param string $dhcp_options_id (Required) The ID of the DHCP options to associate with the VPC. Specify "default" to associate the default DHCP options with the VPC. * @param string $vpc_id (Required) The ID of the VPC to associate the DHCP options with. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function associate_dhcp_options($dhcp_options_id, $vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['DhcpOptionsId'] = $dhcp_options_id; $opt['VpcId'] = $vpc_id; return $this->authenticate('AssociateDhcpOptions', $opt, $this->hostname); } /** * * Stops an instance that uses an Amazon EBS volume as its root device. Instances that use Amazon EBS volumes as their root devices can be * quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for hourly instance * usage. However, your root partition Amazon EBS volume remains, continues to persist your data, and you are charged for Amazon EBS volume * usage. You can restart your instance at any time. * * Before stopping an instance, make sure it is in a state from which it can be restarted. Stopping an instance does not preserve data stored * in RAM. * * Performing this operation on an instance that uses an instance store as its root device returns an error. * * @param string|array $instance_id (Required) The list of Amazon EC2 instances to stop. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Force</code> - <code>boolean</code> - Optional - Forces the instance to stop. The instance will not have an opportunity to flush file system caches nor file system meta data. If you use this option, you must perform file system check and repair procedures. This option is not recommended for Windows instances. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function stop_instances($instance_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($instance_id) ? $instance_id : array($instance_id)) ))); return $this->authenticate('StopInstances', $opt, $this->hostname); } /** * Imports the public key from an RSA key pair created with a third-party tool. This operation differs * from CreateKeyPair as the private key is never transferred between the caller and AWS servers. * * RSA key pairs are easily created on Microsoft Windows and Linux OS systems using the <code>ssh-keygen</code> * command line tool provided with the standard OpenSSH installation. Standard library support for RSA * key pair creation is also available for Java, Ruby, Python, and many other programming languages. * * The following formats are supported: * * <ul> * <li>OpenSSH public key format.</li> * <li>Base64 encoded DER format.</li> * <li>SSH public key file format as specified in <a href="http://tools.ietf.org/html/rfc4716">RFC 4716</a>.</li> * </ul> * * @param string $key_name (Required) The unique name for the key pair. * @param string $public_key_material (Required) The public key portion of the key pair being imported. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This is useful for manually-managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function import_key_pair($key_name, $public_key_material, $opt = null) { if (!$opt) $opt = array(); $opt['KeyName'] = $key_name; $opt['PublicKeyMaterial'] = $this->util->is_base64($public_key_material) ? $public_key_material : base64_encode($public_key_material); return $this->authenticate('ImportKeyPair', $opt, $this->hostname); } /** * * The CreateSecurityGroup operation creates a new security group. * * Every instance is launched in a security group. If no security group is specified during launch, the instances are launched in the default * security group. Instances within the same security group have unrestricted network access to each other. Instances will reject network * access attempts from other instances in a different security group. As the owner of instances you can grant or revoke specific permissions * using the AuthorizeSecurityGroupIngress and RevokeSecurityGroupIngress operations. * * @param string $group_name (Required) Name of the security group. * @param string $group_description (Required) Description of the group. This is informational only. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>VpcId</code> - <code>string</code> - Optional - ID of the VPC. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_security_group($group_name, $group_description, $opt = null) { if (!$opt) $opt = array(); $opt['GroupName'] = $group_name; $opt['GroupDescription'] = $group_description; return $this->authenticate('CreateSecurityGroup', $opt, $this->hostname); } /** * * Describes the Spot Price history. * * Spot Instances are instances that Amazon EC2 starts on your behalf when the maximum price that you specify exceeds the current Spot Price. * Amazon EC2 periodically sets the Spot Price based on available Spot Instance capacity and current spot instance requests. * * For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud * User Guide. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>StartTime</code> - <code>string</code> - Optional - The start date and time of the Spot Instance price history data. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li> * <li><code>EndTime</code> - <code>string</code> - Optional - The end date and time of the Spot Instance price history data. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li> * <li><code>InstanceType</code> - <code>string|array</code> - Optional - Specifies the instance type to return. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>ProductDescription</code> - <code>string|array</code> - Optional - The description of the AMI. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for SpotPriceHistory. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>AvailabilityZone</code> - <code>string</code> - Optional - Filters the results by availability zone (ex: 'us-east-1a'). </li> * <li><code>MaxResults</code> - <code>integer</code> - Optional - Specifies the number of rows to return. </li> * <li><code>NextToken</code> - <code>string</code> - Optional - Specifies the next set of rows to return. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_spot_price_history($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['StartTime'])) { $opt['StartTime'] = $this->util->convert_date_to_iso8601($opt['StartTime']); } // Optional parameter if (isset($opt['EndTime'])) { $opt['EndTime'] = $this->util->convert_date_to_iso8601($opt['EndTime']); } // Optional parameter if (isset($opt['InstanceType'])) { $opt = array_merge($opt, CFComplexType::map(array( 'InstanceType' => (is_array($opt['InstanceType']) ? $opt['InstanceType'] : array($opt['InstanceType'])) ))); unset($opt['InstanceType']); } // Optional parameter if (isset($opt['ProductDescription'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ProductDescription' => (is_array($opt['ProductDescription']) ? $opt['ProductDescription'] : array($opt['ProductDescription'])) ))); unset($opt['ProductDescription']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeSpotPriceHistory', $opt, $this->hostname); } /** * * The DescribeRegions operation describes regions zones that are currently available to the account. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>RegionName</code> - <code>string|array</code> - Optional - The optional list of regions to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Regions. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_regions($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['RegionName'])) { $opt = array_merge($opt, CFComplexType::map(array( 'RegionName' => (is_array($opt['RegionName']) ? $opt['RegionName'] : array($opt['RegionName'])) ))); unset($opt['RegionName']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeRegions', $opt, $this->hostname); } /** * * Creates a set of DHCP options that you can then associate with one or more VPCs, causing all existing and new instances that you launch in * those VPCs to use the set of DHCP options. The following table lists the individual DHCP options you can specify. For more information about * the options, go to <a href="http://www.ietf.org/rfc/rfc2132.txt">http://www.ietf.org/rfc/rfc2132.txt</a> * * @param array $dhcp_configuration (Required) A set of one or more DHCP configurations. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Key</code> - <code>string</code> - Optional - Contains the name of a DHCP option. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains a set of values for a DHCP option. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_dhcp_options($dhcp_configuration, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'DhcpConfiguration' => (is_array($dhcp_configuration) ? $dhcp_configuration : array($dhcp_configuration)) ))); return $this->authenticate('CreateDhcpOptions', $opt, $this->hostname); } /** * * Resets permission settings for the specified snapshot. * * @param string $snapshot_id (Required) The ID of the snapshot whose attribute is being reset. * @param string $attribute (Required) The name of the attribute being reset. Available attribute names: <code>createVolumePermission</code> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function reset_snapshot_attribute($snapshot_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['SnapshotId'] = $snapshot_id; $opt['Attribute'] = $attribute; return $this->authenticate('ResetSnapshotAttribute', $opt, $this->hostname); } /** * * Deletes a route from a route table in a VPC. For more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * @param string $route_table_id (Required) The ID of the route table where the route will be deleted. * @param string $destination_cidr_block (Required) The CIDR range for the route you want to delete. The value you specify must exactly match the CIDR for the route you want to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_route($route_table_id, $destination_cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['RouteTableId'] = $route_table_id; $opt['DestinationCidrBlock'] = $destination_cidr_block; return $this->authenticate('DeleteRoute', $opt, $this->hostname); } /** * * Gives you information about your Internet gateways. You can filter the results to return information only about Internet gateways that * match criteria you specify. For example, you could get information only about gateways with particular tags. The Internet gateway must match * at least one of the specified values for it to be included in the results. * * You can specify multiple filters (e.g., the Internet gateway is attached to a particular VPC and is tagged with a particular value). The * result includes information for a particular Internet gateway only if the gateway matches all your filters. If there's no match, no special * message is returned; the response is simply empty. * * You can use wildcards with the filter values: an asterisk matches zero or more characters, and <code>?</code> matches exactly one * character. You can escape special characters using a backslash before the character. For example, a value of <code>\*amazon\?\\</code> * searches for the literal string <code>*amazon?\</code>. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>InternetGatewayId</code> - <code>string|array</code> - Optional - One or more Internet gateway IDs. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Internet Gateways. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_internet_gateways($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['InternetGatewayId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'InternetGatewayId' => (is_array($opt['InternetGatewayId']) ? $opt['InternetGatewayId'] : array($opt['InternetGatewayId'])) ))); unset($opt['InternetGatewayId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeInternetGateways', $opt, $this->hostname); } /** * * The DescribeSecurityGroups operation returns information about security groups that you own. * * If you specify security group names, information about those security group is returned. Otherwise, information for all security group is * returned. If you specify a group that does not exist, a fault is returned. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GroupName</code> - <code>string|array</code> - Optional - The optional list of Amazon EC2 security groups to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>GroupId</code> - <code>string|array</code> - Optional - Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for SecurityGroups. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_security_groups($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['GroupName'])) { $opt = array_merge($opt, CFComplexType::map(array( 'GroupName' => (is_array($opt['GroupName']) ? $opt['GroupName'] : array($opt['GroupName'])) ))); unset($opt['GroupName']); } // Optional parameter if (isset($opt['GroupId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'GroupId' => (is_array($opt['GroupId']) ? $opt['GroupId'] : array($opt['GroupId'])) ))); unset($opt['GroupId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeSecurityGroups', $opt, $this->hostname); } /** * * Detaches a VPN gateway from a VPC. You do this if you're planning to turn off the VPC and not use it anymore. You can confirm a VPN gateway * has been completely detached from a VPC by describing the VPN gateway (any attachments to the VPN gateway are also described). * * You must wait for the attachment's state to switch to detached before you can delete the VPC or attach a different VPC to the VPN gateway. * * @param string $vpn_gateway_id (Required) The ID of the VPN gateway to detach from the VPC. * @param string $vpc_id (Required) The ID of the VPC to detach the VPN gateway from. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function detach_vpn_gateway($vpn_gateway_id, $vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpnGatewayId'] = $vpn_gateway_id; $opt['VpcId'] = $vpc_id; return $this->authenticate('DetachVpnGateway', $opt, $this->hostname); } /** * * The DeregisterImage operation deregisters an AMI. Once deregistered, instances of the AMI can no longer be launched. * * @param string $image_id (Required) The ID of the AMI to deregister. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function deregister_image($image_id, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; return $this->authenticate('DeregisterImage', $opt, $this->hostname); } /** * * Describes the data feed for Spot Instances. * * For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud * User Guide. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_spot_datafeed_subscription($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DescribeSpotDatafeedSubscription', $opt, $this->hostname); } /** * * Deletes tags from the specified Amazon EC2 resources. * * @param string|array $resource_id (Required) A list of one or more resource IDs. This could be the ID of an AMI, an instance, an EBS volume, or snapshot, etc. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Tag</code> - <code>array</code> - Optional - The tags to delete from the specified resources. Each tag item consists of a key-value pair. If a tag is specified without a value, the tag and all of its values are deleted. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Key</code> - <code>string</code> - Optional - The tag's key. </li> * <li><code>Value</code> - <code>string</code> - Optional - The tag's value. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_tags($resource_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'ResourceId' => (is_array($resource_id) ? $resource_id : array($resource_id)) ))); // Optional parameter if (isset($opt['Tag'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Tag' => $opt['Tag'] ))); unset($opt['Tag']); } return $this->authenticate('DeleteTags', $opt, $this->hostname); } /** * * Deletes a subnet from a VPC. You must terminate all running instances in the subnet before deleting it, otherwise Amazon VPC returns an * error. * * @param string $subnet_id (Required) The ID of the subnet you want to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_subnet($subnet_id, $opt = null) { if (!$opt) $opt = array(); $opt['SubnetId'] = $subnet_id; return $this->authenticate('DeleteSubnet', $opt, $this->hostname); } /** * * Creates a new VPN gateway. A VPN gateway is the VPC-side endpoint for your VPN connection. You can create a VPN gateway before creating the * VPC itself. * * @param string $type (Required) The type of VPN connection this VPN gateway supports. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>AvailabilityZone</code> - <code>string</code> - Optional - The Availability Zone in which to create the VPN gateway. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_vpn_gateway($type, $opt = null) { if (!$opt) $opt = array(); $opt['Type'] = $type; return $this->authenticate('CreateVpnGateway', $opt, $this->hostname); } /** * * Deletes a VPN gateway. Use this when you want to delete a VPC and all its associated components because you no longer need them. We * recommend that before you delete a VPN gateway, you detach it from the VPC and delete the VPN connection. Note that you don't need to delete * the VPN gateway if you just want to delete and re-create the VPN connection between your VPC and data center. * * @param string $vpn_gateway_id (Required) The ID of the VPN gateway to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_vpn_gateway($vpn_gateway_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpnGatewayId'] = $vpn_gateway_id; return $this->authenticate('DeleteVpnGateway', $opt, $this->hostname); } /** * * Attach a previously created volume to a running instance. * * @param string $volume_id (Required) The ID of the Amazon EBS volume. The volume and instance must be within the same Availability Zone and the instance must be running. * @param string $instance_id (Required) The ID of the instance to which the volume attaches. The volume and instance must be within the same Availability Zone and the instance must be running. * @param string $device (Required) Specifies how the device is exposed to the instance (e.g., <code>/dev/sdh</code>). * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function attach_volume($volume_id, $instance_id, $device, $opt = null) { if (!$opt) $opt = array(); $opt['VolumeId'] = $volume_id; $opt['InstanceId'] = $instance_id; $opt['Device'] = $device; return $this->authenticate('AttachVolume', $opt, $this->hostname); } /** * * Provides details of a user's registered licenses. Zero or more IDs may be specified on the call. When one or more license IDs are * specified, only data for the specified IDs are returned. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>LicenseId</code> - <code>string|array</code> - Optional - Specifies the license registration for which details are to be returned. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Licenses. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_licenses($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['LicenseId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'LicenseId' => (is_array($opt['LicenseId']) ? $opt['LicenseId'] : array($opt['LicenseId'])) ))); unset($opt['LicenseId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeLicenses', $opt, $this->hostname); } /** * * Activates a specific number of licenses for a 90-day period. Activations can be done against a specific license ID. * * @param string $license_id (Required) Specifies the ID for the specific license to activate against. * @param integer $capacity (Required) Specifies the additional number of licenses to activate. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function activate_license($license_id, $capacity, $opt = null) { if (!$opt) $opt = array(); $opt['LicenseId'] = $license_id; $opt['Capacity'] = $capacity; return $this->authenticate('ActivateLicense', $opt, $this->hostname); } /** * * The ResetImageAttribute operation resets an attribute of an AMI to its default value. * * The productCodes attribute cannot be reset. * * @param string $image_id (Required) The ID of the AMI whose attribute is being reset. * @param string $attribute (Required) The name of the attribute being reset. Available attribute names: <code>launchPermission</code> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function reset_image_attribute($image_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; $opt['Attribute'] = $attribute; return $this->authenticate('ResetImageAttribute', $opt, $this->hostname); } /** * * Gives you information about your VPN connections. * * We strongly recommend you use HTTPS when calling this operation because the response contains sensitive cryptographic information for * configuring your customer gateway. * * You can filter the results to return information only about VPN connections that match criteria you specify. For example, you could ask to * get information about a particular VPN connection (or all) only if the VPN's state is pending or available. You can specify multiple filters * (e.g., the VPN connection is associated with a particular VPN gateway, and the gateway's state is pending or available). The result includes * information for a particular VPN connection only if the VPN connection matches all your filters. If there's no match, no special message is * returned; the response is simply empty. The following table shows the available filters. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>VpnConnectionId</code> - <code>string|array</code> - Optional - A VPN connection ID. More than one may be specified per request. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for VPN Connections. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_vpn_connections($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['VpnConnectionId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'VpnConnectionId' => (is_array($opt['VpnConnectionId']) ? $opt['VpnConnectionId'] : array($opt['VpnConnectionId'])) ))); unset($opt['VpnConnectionId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeVpnConnections', $opt, $this->hostname); } /** * * Create a snapshot of the volume identified by volume ID. A volume does not have to be detached at the time the snapshot is taken. * * Snapshot creation requires that the system is in a consistent state. For instance, this means that if taking a snapshot of a database, the * tables must be read-only locked to ensure that the snapshot will not contain a corrupted version of the database. Therefore, be careful when * using this API to ensure that the system remains in the consistent state until the create snapshot status has returned. * * @param string $volume_id (Required) The ID of the volume from which to create the snapshot. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Description</code> - <code>string</code> - Optional - The description for the new snapshot. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_snapshot($volume_id, $opt = null) { if (!$opt) $opt = array(); $opt['VolumeId'] = $volume_id; return $this->authenticate('CreateSnapshot', $opt, $this->hostname); } /** * * Deletes a previously created volume. Once successfully deleted, a new volume can be created with the same name. * * @param string $volume_id (Required) The ID of the EBS volume to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_volume($volume_id, $opt = null) { if (!$opt) $opt = array(); $opt['VolumeId'] = $volume_id; return $this->authenticate('DeleteVolume', $opt, $this->hostname); } /** * * Gives you information about your VPCs. You can filter the results to return information only about VPCs that match criteria you specify. * * For example, you could ask to get information about a particular VPC or VPCs (or all your VPCs) only if the VPC's state is available. You * can specify multiple filters (e.g., the VPC uses one of several sets of DHCP options, and the VPC's state is available). The result includes * information for a particular VPC only if the VPC matches all your filters. * * If there's no match, no special message is returned; the response is simply empty. The following table shows the available filters. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>VpcId</code> - <code>string|array</code> - Optional - The ID of a VPC you want information about. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for VPCs. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_vpcs($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['VpcId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'VpcId' => (is_array($opt['VpcId']) ? $opt['VpcId'] : array($opt['VpcId'])) ))); unset($opt['VpcId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeVpcs', $opt, $this->hostname); } /** * * Deactivates a specific number of licenses. Deactivations can be done against a specific license ID after they have persisted for at least a * 90-day period. * * @param string $license_id (Required) Specifies the ID for the specific license to deactivate against. * @param integer $capacity (Required) Specifies the amount of capacity to deactivate against the license. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function deactivate_license($license_id, $capacity, $opt = null) { if (!$opt) $opt = array(); $opt['LicenseId'] = $license_id; $opt['Capacity'] = $capacity; return $this->authenticate('DeactivateLicense', $opt, $this->hostname); } /** * * The AssociateAddress operation associates an elastic IP address with an instance. * * If the IP address is currently assigned to another instance, the IP address is assigned to the new instance. This is an idempotent * operation. If you enter it more than once, Amazon EC2 does not return an error. * * @param string $instance_id (Required) The instance to associate with the IP address. * @param string $public_ip (Required) IP address that you are assigning to the instance. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>AllocationId</code> - <code>string</code> - Optional - The allocation ID that AWS returned when you allocated the elastic IP address for use with Amazon VPC. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function associate_address($instance_id, $public_ip, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; $opt['PublicIp'] = $public_ip; return $this->authenticate('AssociateAddress', $opt, $this->hostname); } /** * * Deletes a customer gateway. You must delete the VPN connection before deleting the customer gateway. * * You can have a single active customer gateway per AWS account (active means that you've created a VPN connection with that customer * gateway). AWS might delete any customer gateway you leave inactive for an extended period of time. * * @param string $customer_gateway_id (Required) The ID of the customer gateway to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_customer_gateway($customer_gateway_id, $opt = null) { if (!$opt) $opt = array(); $opt['CustomerGatewayId'] = $customer_gateway_id; return $this->authenticate('DeleteCustomerGateway', $opt, $this->hostname); } /** * * Creates an entry (i.e., rule) in a network ACL with a rule number you specify. Each network ACL has a set of numbered ingress rules and a * separate set of numbered egress rules. When determining whether a packet should be allowed in or out of a subnet associated with the ACL, * Amazon VPC processes the entries in the ACL according to the rule numbers, in ascending order. * * <b>Important: </b> We recommend that you leave room between the rules (e.g., 100, 110, 120, etc.), and not number them sequentially (101, * 102, 103, etc.). This allows you to easily add a new rule between existing ones without having to renumber the rules. * * After you add an entry, you can't modify it; you must either replace it, or create a new entry and delete the old one. * * For more information about network ACLs, go to Network ACLs in the Amazon Virtual Private Cloud User Guide. * * @param string $network_acl_id (Required) ID of the ACL where the entry will be created. * @param integer $rule_number (Required) Rule number to assign to the entry (e.g., 100). ACL entries are processed in ascending order by rule number. * @param string $protocol (Required) IP protocol the rule applies to. Valid Values: <code>tcp</code>, <code>udp</code>, <code>icmp</code> or an IP protocol number. * @param string $rule_action (Required) Whether to allow or deny traffic that matches the rule. [Allowed values: <code>allow</code>, <code>deny</code>] * @param boolean $egress (Required) Whether this rule applies to egress traffic from the subnet (<code>true</code>) or ingress traffic to the subnet (<code>false</code>). * @param string $cidr_block (Required) The CIDR range to allow or deny, in CIDR notation (e.g., <code>172.16.0.0/24</code>). * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Icmp</code> - <code>array</code> - Optional - ICMP values. <ul> * <li><code>Type</code> - <code>integer</code> - Optional - For the ICMP protocol, the ICMP type. A value of <code>-1</code> is a wildcard meaning all types. Required if specifying <code>icmp</code> for the protocol. </li> * <li><code>Code</code> - <code>integer</code> - Optional - For the ICMP protocol, the ICMP code. A value of <code>-1</code> is a wildcard meaning all codes. Required if specifying <code>icmp</code> for the protocol. </li></ul></li> * <li><code>PortRange</code> - <code>array</code> - Optional - Port ranges. <ul> * <li><code>From</code> - <code>integer</code> - Optional - The first port in the range. Required if specifying <code>tcp</code> or <code>udp</code> for the protocol. </li> * <li><code>To</code> - <code>integer</code> - Optional - The last port in the range. Required if specifying <code>tcp</code> or <code>udp</code> for the protocol. </li></ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_network_acl_entry($network_acl_id, $rule_number, $protocol, $rule_action, $egress, $cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['NetworkAclId'] = $network_acl_id; $opt['RuleNumber'] = $rule_number; $opt['Protocol'] = $protocol; $opt['RuleAction'] = $rule_action; $opt['Egress'] = $egress; $opt['CidrBlock'] = $cidr_block; // Optional parameter if (isset($opt['Icmp'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Icmp' => $opt['Icmp'] ))); unset($opt['Icmp']); } // Optional parameter if (isset($opt['PortRange'])) { $opt = array_merge($opt, CFComplexType::map(array( 'PortRange' => $opt['PortRange'] ))); unset($opt['PortRange']); } return $this->authenticate('CreateNetworkAclEntry', $opt, $this->hostname); } /** * * Detaches an Internet gateway from a VPC, disabling connectivity between the Internet and the VPC. The VPC must not contain any running * instances with elastic IP addresses. For more information about your VPC and Internet gateway, go to Amazon Virtual Private Cloud User * Guide. * * For more information about Amazon Virtual Private Cloud and Internet gateways, go to the Amazon Virtual Private Cloud User Guide. * * @param string $internet_gateway_id (Required) The ID of the Internet gateway to detach. * @param string $vpc_id (Required) The ID of the VPC. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function detach_internet_gateway($internet_gateway_id, $vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['InternetGatewayId'] = $internet_gateway_id; $opt['VpcId'] = $vpc_id; return $this->authenticate('DetachInternetGateway', $opt, $this->hostname); } /** * * Creates a new route table within a VPC. After you create a new route table, you can add routes and associate the table with a subnet. For * more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * @param string $vpc_id (Required) The ID of the VPC where the route table will be created. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_route_table($vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpcId'] = $vpc_id; return $this->authenticate('CreateRouteTable', $opt, $this->hostname); } /** * * Describes the status of the indicated volume or, in lieu of any specified, all volumes belonging to the caller. Volumes that have been * deleted are not described. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>VolumeId</code> - <code>string|array</code> - Optional - The optional list of EBS volumes to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Volumes. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_volumes($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['VolumeId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'VolumeId' => (is_array($opt['VolumeId']) ? $opt['VolumeId'] : array($opt['VolumeId'])) ))); unset($opt['VolumeId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeVolumes', $opt, $this->hostname); } /** * * Gives you information about your route tables. You can filter the results to return information only about tables that match criteria you * specify. For example, you could get information only about a table associated with a particular subnet. You can specify multiple values for * the filter. The table must match at least one of the specified values for it to be included in the results. * * You can specify multiple filters (e.g., the table has a particular route, and is associated with a particular subnet). The result includes * information for a particular table only if it matches all your filters. If there's no match, no special message is returned; the response is * simply empty. * * You can use wildcards with the filter values: an asterisk matches zero or more characters, and <code>?</code> matches exactly one * character. You can escape special characters using a backslash before the character. For example, a value of <code>\*amazon\?\\</code> * searches for the literal string <code>*amazon?\</code>. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>RouteTableId</code> - <code>string|array</code> - Optional - One or more route table IDs. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Route Tables. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_route_tables($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['RouteTableId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'RouteTableId' => (is_array($opt['RouteTableId']) ? $opt['RouteTableId'] : array($opt['RouteTableId'])) ))); unset($opt['RouteTableId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeRouteTables', $opt, $this->hostname); } /** * * Enables monitoring for a running instance. * * @param string|array $instance_id (Required) The list of Amazon EC2 instances on which to enable monitoring. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function monitor_instances($instance_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($instance_id) ? $instance_id : array($instance_id)) ))); return $this->authenticate('MonitorInstances', $opt, $this->hostname); } /** * * Gives you information about one or more sets of DHCP options. You can specify one or more DHCP options set IDs, or no IDs (to describe all * your sets of DHCP options). The returned information consists of: * * <ul> <li> The DHCP options set ID </li> * * <li> The options </li> * * </ul> * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>DhcpOptionsId</code> - <code>string|array</code> - Optional - Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for DhcpOptions. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_dhcp_options($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['DhcpOptionsId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'DhcpOptionsId' => (is_array($opt['DhcpOptionsId']) ? $opt['DhcpOptionsId'] : array($opt['DhcpOptionsId'])) ))); unset($opt['DhcpOptionsId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeDhcpOptions', $opt, $this->hostname); } /** * * Gives you information about the network ACLs in your VPC. You can filter the results to return information only about ACLs that match * criteria you specify. For example, you could get information only the ACL associated with a particular subnet. The ACL must match at least * one of the specified values for it to be included in the results. * * You can specify multiple filters (e.g., the ACL is associated with a particular subnet and has an egress entry that denies traffic to a * particular port). The result includes information for a particular ACL only if it matches all your filters. If there's no match, no special * message is returned; the response is simply empty. * * You can use wildcards with the filter values: an asterisk matches zero or more characters, and <code>?</code> matches exactly one * character. You can escape special characters using a backslash before the character. For example, a value of <code>\*amazon\?\\</code> * searches for the literal string <code>*amazon?\</code>. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>NetworkAclId</code> - <code>string|array</code> - Optional - One or more network ACL IDs. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Network ACLs. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_network_acls($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['NetworkAclId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'NetworkAclId' => (is_array($opt['NetworkAclId']) ? $opt['NetworkAclId'] : array($opt['NetworkAclId'])) ))); unset($opt['NetworkAclId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeNetworkAcls', $opt, $this->hostname); } /** * * The DescribeBundleTasks operation describes in-progress and recent bundle tasks. Complete and failed tasks are removed from the list a * short time after completion. If no bundle ids are given, all bundle tasks are returned. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>BundleId</code> - <code>string|array</code> - Optional - The list of bundle task IDs to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for BundleTasks. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_bundle_tasks($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['BundleId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'BundleId' => (is_array($opt['BundleId']) ? $opt['BundleId'] : array($opt['BundleId'])) ))); unset($opt['BundleId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeBundleTasks', $opt, $this->hostname); } /** * * The RevokeSecurityGroupIngress operation revokes permissions from a security group. The permissions used to revoke must be specified using * the same values used to grant the permissions. * * Permissions are specified by IP protocol (TCP, UDP, or ICMP), the source of the request (by IP range or an Amazon EC2 user-group pair), the * source and destination port ranges (for TCP and UDP), and the ICMP codes and types (for ICMP). * * Permission changes are quickly propagated to instances within the security group. However, depending on the number of instances in the * group, a small delay might occur. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GroupName</code> - <code>string</code> - Optional - Name of the standard (EC2) security group to modify. The group must belong to your account. Can be used instead of GroupID for standard (EC2) security groups. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - ID of the standard (EC2) or VPC security group to modify. The group must belong to your account. Required for VPC security groups; can be used instead of GroupName for standard (EC2) security groups. </li> * <li><code>IpPermissions</code> - <code>array</code> - Optional - List of IP permissions to revoke on the specified security group. For an IP permission to be removed, it must exactly match one of the IP permissions you specify in this list. Specifying permissions through IP permissions is the preferred way of revoking permissions since it offers more flexibility and control. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>IpProtocol</code> - <code>string</code> - Optional - The IP protocol of this permission. Valid protocol values: <code>tcp</code>, <code>udp</code>, <code>icmp</code> </li> * <li><code>FromPort</code> - <code>integer</code> - Optional - Start of port range for the TCP and UDP protocols, or an ICMP type number. An ICMP type number of <code>-1</code> indicates a wildcard (i.e., any ICMP type number). </li> * <li><code>ToPort</code> - <code>integer</code> - Optional - End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of <code>-1</code> indicates a wildcard (i.e., any ICMP code). </li> * <li><code>Groups</code> - <code>array</code> - Optional - The list of AWS user IDs and groups included in this permission. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The AWS user ID of an account. </li> * <li><code>GroupName</code> - <code>string</code> - Optional - Name of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - ID of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * </ul></li> * </ul></li> * <li><code>IpRanges</code> - <code>string|array</code> - Optional - The list of CIDR IP ranges included in this permission. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function revoke_security_group_ingress($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['IpPermissions'])) { $opt = array_merge($opt, CFComplexType::map(array( 'IpPermissions' => $opt['IpPermissions'] ))); unset($opt['IpPermissions']); } return $this->authenticate('RevokeSecurityGroupIngress', $opt, $this->hostname); } /** * The GetConsoleOutput operation retrieves console output for the specified instance. * * Instance console output is buffered and posted shortly after instance boot, reboot, and * termination. Amazon EC2 preserves the most recent 64 KB output which will be available for at least * one hour after the most recent post. * * @param string $instance_id (Required) The ID of the instance for which you want console output. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This is useful for manually-managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. The value of <code>output</code> is automatically Base64-decoded. */ public function get_console_output($instance_id, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; $response = $this->authenticate('GetConsoleOutput', $opt, $this->hostname); // Automatically Base64-decode the <output> value. if ($this->util->is_base64((string) $response->body->output)) { $response->body->output = base64_decode($response->body->output); } return $response; } /** * * Creates a new Internet gateway in your AWS account. After creating the Internet gateway, you then attach it to a VPC using * <code>AttachInternetGateway</code>. For more information about your VPC and Internet gateway, go to Amazon Virtual Private Cloud User Guide. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_internet_gateway($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('CreateInternetGateway', $opt, $this->hostname); } /** * * The ModifyImageAttribute operation modifies an attribute of an AMI. * * @param string $image_id (Required) The ID of the AMI whose attribute you want to modify. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Attribute</code> - <code>string</code> - Optional - The name of the AMI attribute you want to modify. Available attributes: <code>launchPermission</code>, <code>productCodes</code> </li> * <li><code>OperationType</code> - <code>string</code> - Optional - The type of operation being requested. Available operation types: <code>add</code>, <code>remove</code> </li> * <li><code>UserId</code> - <code>string|array</code> - Optional - The AWS user ID being added to or removed from the list of users with launch permissions for this AMI. Only valid when the launchPermission attribute is being modified. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>UserGroup</code> - <code>string|array</code> - Optional - The user group being added to or removed from the list of user groups with launch permissions for this AMI. Only valid when the launchPermission attribute is being modified. Available user groups: <code>all</code> Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>ProductCode</code> - <code>string|array</code> - Optional - The list of product codes being added to or removed from the specified AMI. Only valid when the productCodes attribute is being modified. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Value</code> - <code>string</code> - Optional - The value of the attribute being modified. Only valid when the description attribute is being modified. </li> * <li><code>LaunchPermission</code> - <code>array</code> - Optional - <ul> * <li><code>Add</code> - <code>array</code> - Optional - <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The AWS user ID of the user involved in this launch permission. </li> * <li><code>Group</code> - <code>string</code> - Optional - The AWS group of the user involved in this launch permission. Available groups: <code>all</code> </li> * </ul></li> * </ul></li> * <li><code>Remove</code> - <code>array</code> - Optional - <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The AWS user ID of the user involved in this launch permission. </li> * <li><code>Group</code> - <code>string</code> - Optional - The AWS group of the user involved in this launch permission. Available groups: <code>all</code> </li> * </ul></li> * </ul></li></ul></li> * <li><code>Description</code> - <code>string</code> - Optional - String value </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function modify_image_attribute($image_id, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; // Optional parameter if (isset($opt['UserId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'UserId' => (is_array($opt['UserId']) ? $opt['UserId'] : array($opt['UserId'])) ))); unset($opt['UserId']); } // Optional parameter if (isset($opt['UserGroup'])) { $opt = array_merge($opt, CFComplexType::map(array( 'UserGroup' => (is_array($opt['UserGroup']) ? $opt['UserGroup'] : array($opt['UserGroup'])) ))); unset($opt['UserGroup']); } // Optional parameter if (isset($opt['ProductCode'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ProductCode' => (is_array($opt['ProductCode']) ? $opt['ProductCode'] : array($opt['ProductCode'])) ))); unset($opt['ProductCode']); } // Optional parameter if (isset($opt['LaunchPermission'])) { $opt = array_merge($opt, CFComplexType::map(array( 'LaunchPermission' => $opt['LaunchPermission'] ))); unset($opt['LaunchPermission']); } return $this->authenticate('ModifyImageAttribute', $opt, $this->hostname); } /** * * Provides information to AWS about your customer gateway device. The customer gateway is the appliance at your end of the VPN connection * (compared to the VPN gateway, which is the device at the AWS side of the VPN connection). You can have a single active customer gateway per * AWS account (active means that you've created a VPN connection to use with the customer gateway). AWS might delete any customer gateway that * you create with this operation if you leave it inactive for an extended period of time. * * You must provide the Internet-routable IP address of the customer gateway's external interface. The IP address must be static. * * You must also provide the device's Border Gateway Protocol (BGP) Autonomous System Number (ASN). You can use an existing ASN assigned to * your network. If you don't have an ASN already, you can use a private ASN (in the 64512 - 65534 range). For more information about ASNs, go * to <a * href="http://en.wikipedia.org/wiki/Autonomous_system_%28Internet%29">http://en.wikipedia.org/wiki/Autonomous_system_%28Internet%29</a>. * * @param string $type (Required) The type of VPN connection this customer gateway supports. * @param string $ip_address (Required) The Internet-routable IP address for the customer gateway's outside interface. The address must be static * @param integer $bgp_asn (Required) The customer gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN). * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_customer_gateway($type, $ip_address, $bgp_asn, $opt = null) { if (!$opt) $opt = array(); $opt['Type'] = $type; $opt['IpAddress'] = $ip_address; $opt['BgpAsn'] = $bgp_asn; return $this->authenticate('CreateCustomerGateway', $opt, $this->hostname); } /** * * Creates the data feed for Spot Instances, enabling you to view Spot Instance usage logs. You can create one data feed per account. * * For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud * User Guide. * * @param string $bucket (Required) The Amazon S3 bucket in which to store the Spot Instance datafeed. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Prefix</code> - <code>string</code> - Optional - The prefix that is prepended to datafeed files. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_spot_datafeed_subscription($bucket, $opt = null) { if (!$opt) $opt = array(); $opt['Bucket'] = $bucket; return $this->authenticate('CreateSpotDatafeedSubscription', $opt, $this->hostname); } /** * * Attaches an Internet gateway to a VPC, enabling connectivity between the Internet and the VPC. For more information about your VPC and * Internet gateway, go to the Amazon Virtual Private Cloud User Guide. * * @param string $internet_gateway_id (Required) The ID of the Internet gateway to attach. * @param string $vpc_id (Required) The ID of the VPC. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function attach_internet_gateway($internet_gateway_id, $vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['InternetGatewayId'] = $internet_gateway_id; $opt['VpcId'] = $vpc_id; return $this->authenticate('AttachInternetGateway', $opt, $this->hostname); } /** * * Deletes a VPN connection. Use this if you want to delete a VPC and all its associated components. Another reason to use this operation is * if you believe the tunnel credentials for your VPN connection have been compromised. In that situation, you can delete the VPN connection * and create a new one that has new keys, without needing to delete the VPC or VPN gateway. If you create a new VPN connection, you must * reconfigure the customer gateway using the new configuration information returned with the new VPN connection ID. * * If you're deleting the VPC and all its associated parts, we recommend you detach the VPN gateway from the VPC and delete the VPC before * deleting the VPN connection. * * @param string $vpn_connection_id (Required) The ID of the VPN connection to delete * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_vpn_connection($vpn_connection_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpnConnectionId'] = $vpn_connection_id; return $this->authenticate('DeleteVpnConnection', $opt, $this->hostname); } /** * * Creates a new VPN connection between an existing VPN gateway and customer gateway. The only supported connection type is ipsec.1. * * The response includes information that you need to configure your customer gateway, in XML format. We recommend you use the command line * version of this operation (<code>ec2-create-vpn-connection</code>), which takes an <code>-f</code> option (for format) and returns * configuration information formatted as expected by the vendor you specified, or in a generic, human readable format. For information about * the command, go to <code>ec2-create-vpn-connection</code> in the Amazon Virtual Private Cloud Command Line Reference. * * We strongly recommend you use HTTPS when calling this operation because the response contains sensitive cryptographic information for * configuring your customer gateway. * * If you decide to shut down your VPN connection for any reason and then create a new one, you must re-configure your customer gateway with * the new information returned from this call. * * @param string $type (Required) The type of VPN connection. * @param string $customer_gateway_id (Required) The ID of the customer gateway. * @param string $vpn_gateway_id (Required) The ID of the VPN gateway. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_vpn_connection($type, $customer_gateway_id, $vpn_gateway_id, $opt = null) { if (!$opt) $opt = array(); $opt['Type'] = $type; $opt['CustomerGatewayId'] = $customer_gateway_id; $opt['VpnGatewayId'] = $vpn_gateway_id; return $this->authenticate('CreateVpnConnection', $opt, $this->hostname); } /** * * Returns information about an attribute of an instance. Only one attribute can be specified per call. * * @param string $instance_id (Required) The ID of the instance whose instance attribute is being described. * @param string $attribute (Required) The name of the attribute to describe. Available attribute names: <code>instanceType</code>, <code>kernel</code>, <code>ramdisk</code>, <code>userData</code>, <code>disableApiTermination</code>, <code>instanceInitiatedShutdownBehavior</code>, <code>rootDeviceName</code>, <code>blockDeviceMapping</code> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_instance_attribute($instance_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; $opt['Attribute'] = $attribute; return $this->authenticate('DescribeInstanceAttribute', $opt, $this->hostname); } /** * * Gives you information about your subnets. You can filter the results to return information only about subnets that match criteria you * specify. * * For example, you could ask to get information about a particular subnet (or all) only if the subnet's state is available. You can specify * multiple filters (e.g., the subnet is in a particular VPC, and the subnet's state is available). * * The result includes information for a particular subnet only if the subnet matches all your filters. If there's no match, no special * message is returned; the response is simply empty. The following table shows the available filters. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>SubnetId</code> - <code>string|array</code> - Optional - A set of one or more subnet IDs. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Subnets. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_subnets($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['SubnetId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'SubnetId' => (is_array($opt['SubnetId']) ? $opt['SubnetId'] : array($opt['SubnetId'])) ))); unset($opt['SubnetId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeSubnets', $opt, $this->hostname); } /** * * The RunInstances operation launches a specified number of instances. * * If Amazon EC2 cannot launch the minimum number AMIs you request, no instances launch. If there is insufficient capacity to launch the * maximum number of AMIs you request, Amazon EC2 launches as many as possible to satisfy the requested maximum values. * * Every instance is launched in a security group. If you do not specify a security group at launch, the instances start in your default * security group. For more information on creating security groups, see CreateSecurityGroup. * * An optional instance type can be specified. For information about instance types, see Instance Types. * * You can provide an optional key pair ID for each image in the launch request (for more information, see CreateKeyPair). All instances that * are created from images that use this key pair will have access to the associated public key at boot. You can use this key to provide secure * access to an instance of an image on a per-instance basis. Amazon EC2 public images use this feature to provide secure access without * passwords. * * Launching public images without a key pair ID will leave them inaccessible. * * The public key material is made available to the instance at boot time by placing it in the <code>openssh_id.pub</code> file on a logical * device that is exposed to the instance as <code>/dev/sda2</code> (the ephemeral store). The format of this file is suitable for use as an * entry within <code>~/.ssh/authorized_keys</code> (the OpenSSH format). This can be done at boot (e.g., as part of <code>rc.local</code>) * allowing for secure access without passwords. * * Optional user data can be provided in the launch request. All instances that collectively comprise the launch request have access to this * data For more information, see Instance Metadata. * * * If any of the AMIs have a product code attached for which the user has not subscribed, the RunInstances call will fail. * * We strongly recommend using the 2.6.18 Xen stock kernel with the <code>c1.medium</code> and <code>c1.xlarge</code> instances. Although the * default Amazon EC2 kernels will work, the new kernels provide greater stability and performance for these instance types. For more * information about kernels, see Kernels, RAM Disks, and Block Device Mappings. * * @param string $image_id (Required) Unique ID of a machine image, returned by a call to DescribeImages. * @param integer $min_count (Required) Minimum number of instances to launch. If the value is more than Amazon EC2 can launch, no instances are launched at all. * @param integer $max_count (Required) Maximum number of instances to launch. If the value is more than Amazon EC2 can launch, the largest possible number above minCount will be launched instead. Between 1 and the maximum number allowed for your account (default: 20). * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>KeyName</code> - <code>string</code> - Optional - The name of the key pair. </li> * <li><code>SecurityGroup</code> - <code>string|array</code> - Optional - The names of the security groups into which the instances will be launched. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>SecurityGroupId</code> - <code>string|array</code> - Optional - Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>UserData</code> - <code>string</code> - Optional - Specifies additional information to make available to the instance(s). </li> * <li><code>InstanceType</code> - <code>string</code> - Optional - Specifies the instance type for the launched instances. [Allowed values: <code>t1.micro</code>, <code>m1.small</code>, <code>m1.large</code>, <code>m1.xlarge</code>, <code>m2.xlarge</code>, <code>m2.2xlarge</code>, <code>m2.4xlarge</code>, <code>c1.medium</code>, <code>c1.xlarge</code>, <code>cc1.4xlarge</code>, <code>cg1.4xlarge</code>]</li> * <li><code>Placement</code> - <code>array</code> - Optional - Specifies the placement constraints (Availability Zones) for launching the instances. <ul> * <li><code>AvailabilityZone</code> - <code>string</code> - Optional - The availability zone in which an Amazon EC2 instance runs. </li> * <li><code>GroupName</code> - <code>string</code> - Optional - The name of the PlacementGroup in which an Amazon EC2 instance runs. Placement groups are primarily used for launching High Performance Computing instances in the same group to ensure fast connection speeds. </li> * <li><code>Tenancy</code> - <code>string</code> - Optional - The allowed tenancy of instances launched into the VPC. A value of default means instances can be launched with any tenancy; a value of dedicated means instances must be launched with tenancy as dedicated. </li></ul></li> * <li><code>KernelId</code> - <code>string</code> - Optional - The ID of the kernel with which to launch the instance. </li> * <li><code>RamdiskId</code> - <code>string</code> - Optional - The ID of the RAM disk with which to launch the instance. Some kernels require additional drivers at launch. Check the kernel requirements for information on whether you need to specify a RAM disk. To find kernel requirements, go to the Resource Center and search for the kernel ID. </li> * <li><code>BlockDeviceMapping</code> - <code>array</code> - Optional - Specifies how block devices are exposed to the instance. Each mapping is made up of a virtualName and a deviceName. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>VirtualName</code> - <code>string</code> - Optional - Specifies the virtual device name. </li> * <li><code>DeviceName</code> - <code>string</code> - Optional - Specifies the device name (e.g., <code>/dev/sdh</code>). </li> * <li><code>Ebs</code> - <code>array</code> - Optional - Specifies parameters used to automatically setup Amazon EBS volumes when the instance is launched. Takes an associative array of parameters that can have the following keys: <ul> * <li><code>SnapshotId</code> - <code>string</code> - Optional - The ID of the snapshot from which the volume will be created. </li> * <li><code>VolumeSize</code> - <code>integer</code> - Optional - The size of the volume, in gigabytes. </li> * <li><code>DeleteOnTermination</code> - <code>boolean</code> - Optional - Specifies whether the Amazon EBS volume is deleted on instance termination. </li> * </ul></li> * <li><code>NoDevice</code> - <code>string</code> - Optional - Specifies the device name to suppress during instance launch. </li> * </ul></li> * </ul></li> * <li><code>Monitoring.Enabled</code> - <code>boolean</code> - Optional - Enables monitoring for the instance. </li> * <li><code>SubnetId</code> - <code>string</code> - Optional - Specifies the subnet ID within which to launch the instance(s) for Amazon Virtual Private Cloud. </li> * <li><code>DisableApiTermination</code> - <code>boolean</code> - Optional - Specifies whether the instance can be terminated using the APIs. You must modify this attribute before you can terminate any "locked" instances from the APIs. </li> * <li><code>InstanceInitiatedShutdownBehavior</code> - <code>string</code> - Optional - Specifies whether the instance's Amazon EBS volumes are stopped or terminated when the instance is shut down. </li> * <li><code>License</code> - <code>array</code> - Optional - Specifies active licenses in use and attached to an Amazon EC2 instance. <ul> * <li><code>Pool</code> - <code>string</code> - Optional - The license pool from which to take a license when starting Amazon EC2 instances in the associated <code>RunInstances</code> request. </li></ul></li> * <li><code>PrivateIpAddress</code> - <code>string</code> - Optional - If you're using Amazon Virtual Private Cloud, you can optionally use this parameter to assign the instance a specific available IP address from the subnet. </li> * <li><code>ClientToken</code> - <code>string</code> - Optional - Unique, case-sensitive identifier you provide to ensure idempotency of the request. For more information, go to How to Ensure Idempotency in the Amazon Elastic Compute Cloud User Guide. </li> * <li><code>AdditionalInfo</code> - <code>string</code> - Optional - </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function run_instances($image_id, $min_count, $max_count, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; $opt['MinCount'] = $min_count; $opt['MaxCount'] = $max_count; // Optional parameter if (isset($opt['SecurityGroup'])) { $opt = array_merge($opt, CFComplexType::map(array( 'SecurityGroup' => (is_array($opt['SecurityGroup']) ? $opt['SecurityGroup'] : array($opt['SecurityGroup'])) ))); unset($opt['SecurityGroup']); } // Optional parameter if (isset($opt['SecurityGroupId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'SecurityGroupId' => (is_array($opt['SecurityGroupId']) ? $opt['SecurityGroupId'] : array($opt['SecurityGroupId'])) ))); unset($opt['SecurityGroupId']); } // Optional parameter if (isset($opt['Placement'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Placement' => $opt['Placement'] ))); unset($opt['Placement']); } // Optional parameter if (isset($opt['BlockDeviceMapping'])) { $opt = array_merge($opt, CFComplexType::map(array( 'BlockDeviceMapping' => $opt['BlockDeviceMapping'] ))); unset($opt['BlockDeviceMapping']); } // Optional parameter if (isset($opt['License'])) { $opt = array_merge($opt, CFComplexType::map(array( 'License' => $opt['License'] ))); unset($opt['License']); } return $this->authenticate('RunInstances', $opt, $this->hostname); } /** * * Returns information about one or more PlacementGroup instances in a user's account. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GroupName</code> - <code>string|array</code> - Optional - The name of the <code>PlacementGroup</code>. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Placement Groups. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_placement_groups($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['GroupName'])) { $opt = array_merge($opt, CFComplexType::map(array( 'GroupName' => (is_array($opt['GroupName']) ? $opt['GroupName'] : array($opt['GroupName'])) ))); unset($opt['GroupName']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribePlacementGroups', $opt, $this->hostname); } /** * * Associates a subnet with a route table. The subnet and route table must be in the same VPC. This association causes traffic originating * from the subnet to be routed according to the routes in the route table. The action returns an association ID, which you need if you want to * disassociate the route table from the subnet later. A route table can be associated with multiple subnets. * * For more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * @param string $subnet_id (Required) The ID of the subnet. * @param string $route_table_id (Required) The ID of the route table. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function associate_route_table($subnet_id, $route_table_id, $opt = null) { if (!$opt) $opt = array(); $opt['SubnetId'] = $subnet_id; $opt['RouteTableId'] = $route_table_id; return $this->authenticate('AssociateRouteTable', $opt, $this->hostname); } /** * * The DescribeInstances operation returns information about instances that you own. * * If you specify one or more instance IDs, Amazon EC2 returns information for those instances. If you do not specify instance IDs, Amazon EC2 * returns information for all relevant instances. If you specify an invalid instance ID, a fault is returned. If you specify an instance that * you do not own, it will not be included in the returned results. * * Recently terminated instances might appear in the returned results. This interval is usually less than one hour. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>InstanceId</code> - <code>string|array</code> - Optional - An optional list of the instances to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Instances. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_instances($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['InstanceId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($opt['InstanceId']) ? $opt['InstanceId'] : array($opt['InstanceId'])) ))); unset($opt['InstanceId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeInstances', $opt, $this->hostname); } /** * * Deletes a network ACL from a VPC. The ACL must not have any subnets associated with it. You can't delete the default network ACL. For more * information about network ACLs, go to Network ACLs in the Amazon Virtual Private Cloud User Guide. * * @param string $network_acl_id (Required) The ID of the network ACL to be deleted. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_network_acl($network_acl_id, $opt = null) { if (!$opt) $opt = array(); $opt['NetworkAclId'] = $network_acl_id; return $this->authenticate('DeleteNetworkAcl', $opt, $this->hostname); } /** * * The DescribeImages operation returns information about AMIs, AKIs, and ARIs available to the user. Information returned includes image * type, product codes, architecture, and kernel and RAM disk IDs. Images available to the user include public images available for any user to * launch, private images owned by the user making the request, and private images owned by other users for which the user has explicit launch * permissions. * * Launch permissions fall into three categories: * * <ul> <li> <b>Public:</b> The owner of the AMI granted launch permissions for the AMI to the all group. All users have launch permissions * for these AMIs. </li> * * <li> <b>Explicit:</b> The owner of the AMI granted launch permissions to a specific user. </li> * * <li> <b>Implicit:</b> A user has implicit launch permissions for all AMIs he or she owns. </li> * * </ul> * * The list of AMIs returned can be modified by specifying AMI IDs, AMI owners, or users with launch permissions. If no options are specified, * Amazon EC2 returns all AMIs for which the user has launch permissions. * * If you specify one or more AMI IDs, only AMIs that have the specified IDs are returned. If you specify an invalid AMI ID, a fault is * returned. If you specify an AMI ID for which you do not have access, it will not be included in the returned results. * * If you specify one or more AMI owners, only AMIs from the specified owners and for which you have access are returned. The results can * include the account IDs of the specified owners, amazon for AMIs owned by Amazon or self for AMIs that you own. * * If you specify a list of executable users, only users that have launch permissions for the AMIs are returned. You can specify account IDs * (if you own the AMI(s)), self for AMIs for which you own or have explicit permissions, or all for public AMIs. * * Deregistered images are included in the returned results for an unspecified interval after deregistration. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>ImageId</code> - <code>string|array</code> - Optional - An optional list of the AMI IDs to describe. If not specified, all AMIs will be described. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Owner</code> - <code>string|array</code> - Optional - The optional list of owners for the described AMIs. The IDs amazon, self, and explicit can be used to include AMIs owned by Amazon, AMIs owned by the user, and AMIs for which the user has explicit launch permissions, respectively. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>ExecutableBy</code> - <code>string|array</code> - Optional - The optional list of users with explicit launch permissions for the described AMIs. The user ID can be a user's account ID, 'self' to return AMIs for which the sender of the request has explicit launch permissions, or 'all' to return AMIs with public launch permissions. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Images. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_images($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['ImageId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ImageId' => (is_array($opt['ImageId']) ? $opt['ImageId'] : array($opt['ImageId'])) ))); unset($opt['ImageId']); } // Optional parameter if (isset($opt['Owner'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Owner' => (is_array($opt['Owner']) ? $opt['Owner'] : array($opt['Owner'])) ))); unset($opt['Owner']); } // Optional parameter if (isset($opt['ExecutableBy'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ExecutableBy' => (is_array($opt['ExecutableBy']) ? $opt['ExecutableBy'] : array($opt['ExecutableBy'])) ))); unset($opt['ExecutableBy']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeImages', $opt, $this->hostname); } /** * * Starts an instance that uses an Amazon EBS volume as its root device. Instances that use Amazon EBS volumes as their root devices can be * quickly stopped and started. When an instance is stopped, the compute resources are released and you are not billed for hourly instance * usage. However, your root partition Amazon EBS volume remains, continues to persist your data, and you are charged for Amazon EBS volume * usage. You can restart your instance at any time. * * Performing this operation on an instance that uses an instance store as its root device returns an error. * * @param string|array $instance_id (Required) The list of Amazon EC2 instances to start. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function start_instances($instance_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($instance_id) ? $instance_id : array($instance_id)) ))); return $this->authenticate('StartInstances', $opt, $this->hostname); } /** * * Modifies an attribute of an instance. * * @param string $instance_id (Required) The ID of the instance whose attribute is being modified. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Attribute</code> - <code>string</code> - Optional - The name of the attribute being modified. Available attribute names: <code>instanceType</code>, <code>kernel</code>, <code>ramdisk</code>, <code>userData</code>, <code>disableApiTermination</code>, <code>instanceInitiatedShutdownBehavior</code>, <code>rootDevice</code>, <code>blockDeviceMapping</code> </li> * <li><code>Value</code> - <code>string</code> - Optional - The new value of the instance attribute being modified. Only valid when <code>kernel</code>, <code>ramdisk</code>, <code>userData</code>, <code>disableApiTermination</code> or <code>instanceInitiateShutdownBehavior</code> is specified as the attribute being modified. </li> * <li><code>BlockDeviceMapping</code> - <code>array</code> - Optional - The new block device mappings for the instance whose attributes are being modified. Only valid when blockDeviceMapping is specified as the attribute being modified. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>DeviceName</code> - <code>string</code> - Optional - The device name (e.g., <code>/dev/sdh</code>) at which the block device is exposed on the instance. </li> * <li><code>Ebs</code> - <code>array</code> - Optional - The EBS instance block device specification describing the EBS block device to map to the specified device name on a running instance. Takes an associative array of parameters that can have the following keys: <ul> * <li><code>VolumeId</code> - <code>string</code> - Optional - The ID of the EBS volume that should be mounted as a block device on an Amazon EC2 instance. </li> * <li><code>DeleteOnTermination</code> - <code>boolean</code> - Optional - Specifies whether the Amazon EBS volume is deleted on instance termination. </li> * </ul></li> * <li><code>VirtualName</code> - <code>string</code> - Optional - The virtual device name. </li> * <li><code>NoDevice</code> - <code>string</code> - Optional - When set to the empty string, specifies that the device name in this object should not be mapped to any real device. </li> * </ul></li> * </ul></li> * <li><code>SourceDestCheck</code> - <code>boolean</code> - Optional - Boolean value </li> * <li><code>DisableApiTermination</code> - <code>boolean</code> - Optional - Boolean value </li> * <li><code>InstanceType</code> - <code>string</code> - Optional - String value </li> * <li><code>Kernel</code> - <code>string</code> - Optional - String value </li> * <li><code>Ramdisk</code> - <code>string</code> - Optional - String value </li> * <li><code>UserData</code> - <code>string</code> - Optional - String value </li> * <li><code>InstanceInitiatedShutdownBehavior</code> - <code>string</code> - Optional - String value </li> * <li><code>GroupId</code> - <code>string|array</code> - Optional - Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function modify_instance_attribute($instance_id, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; // Optional parameter if (isset($opt['BlockDeviceMapping'])) { $opt = array_merge($opt, CFComplexType::map(array( 'BlockDeviceMapping' => $opt['BlockDeviceMapping'] ))); unset($opt['BlockDeviceMapping']); } // Optional parameter if (isset($opt['GroupId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'GroupId' => (is_array($opt['GroupId']) ? $opt['GroupId'] : array($opt['GroupId'])) ))); unset($opt['GroupId']); } return $this->authenticate('ModifyInstanceAttribute', $opt, $this->hostname); } /** * * Deletes a set of DHCP options that you specify. Amazon VPC returns an error if the set of options you specify is currently associated with * a VPC. You can disassociate the set of options by associating either a new set of options or the default options with the VPC. * * @param string $dhcp_options_id (Required) The ID of the DHCP options set to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_dhcp_options($dhcp_options_id, $opt = null) { if (!$opt) $opt = array(); $opt['DhcpOptionsId'] = $dhcp_options_id; return $this->authenticate('DeleteDhcpOptions', $opt, $this->hostname); } /** * * The AuthorizeSecurityGroupIngress operation adds permissions to a security group. * * Permissions are specified by the IP protocol (TCP, UDP or ICMP), the source of the request (by IP range or an Amazon EC2 user-group pair), * the source and destination port ranges (for TCP and UDP), and the ICMP codes and types (for ICMP). When authorizing ICMP, <code>-1</code> * can be used as a wildcard in the type and code fields. * * Permission changes are propagated to instances within the security group as quickly as possible. However, depending on the number of * instances, a small delay might occur. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GroupName</code> - <code>string</code> - Optional - Name of the standard (EC2) security group to modify. The group must belong to your account. Can be used instead of GroupID for standard (EC2) security groups. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - ID of the standard (EC2) or VPC security group to modify. The group must belong to your account. Required for VPC security groups; can be used instead of GroupName for standard (EC2) security groups. </li> * <li><code>IpPermissions</code> - <code>array</code> - Optional - List of IP permissions to authorize on the specified security group. Specifying permissions through IP permissions is the preferred way of authorizing permissions since it offers more flexibility and control. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>IpProtocol</code> - <code>string</code> - Optional - The IP protocol of this permission. Valid protocol values: <code>tcp</code>, <code>udp</code>, <code>icmp</code> </li> * <li><code>FromPort</code> - <code>integer</code> - Optional - Start of port range for the TCP and UDP protocols, or an ICMP type number. An ICMP type number of <code>-1</code> indicates a wildcard (i.e., any ICMP type number). </li> * <li><code>ToPort</code> - <code>integer</code> - Optional - End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of <code>-1</code> indicates a wildcard (i.e., any ICMP code). </li> * <li><code>Groups</code> - <code>array</code> - Optional - The list of AWS user IDs and groups included in this permission. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The AWS user ID of an account. </li> * <li><code>GroupName</code> - <code>string</code> - Optional - Name of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - ID of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * </ul></li> * </ul></li> * <li><code>IpRanges</code> - <code>string|array</code> - Optional - The list of CIDR IP ranges included in this permission. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function authorize_security_group_ingress($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['IpPermissions'])) { $opt = array_merge($opt, CFComplexType::map(array( 'IpPermissions' => $opt['IpPermissions'] ))); unset($opt['IpPermissions']); } return $this->authenticate('AuthorizeSecurityGroupIngress', $opt, $this->hostname); } /** * * Describes Spot Instance requests. Spot Instances are instances that Amazon EC2 starts on your behalf when the maximum price that you * specify exceeds the current Spot Price. Amazon EC2 periodically sets the Spot Price based on available Spot Instance capacity and current * spot instance requests. For conceptual information about Spot Instances, refer to the <a * href="http://docs.amazonwebservices.com/AWSEC2/2010-08-31/DeveloperGuide/">Amazon Elastic Compute Cloud Developer Guide</a> or <a * href="http://docs.amazonwebservices.com/AWSEC2/2010-08-31/UserGuide/">Amazon Elastic Compute Cloud User Guide</a>. * * You can filter the results to return information only about Spot Instance requests that match criteria you specify. For example, you could * get information about requests where the Spot Price you specified is a certain value (you can't use greater than or less than comparison, * but you can use <code>*</code> and <code>?</code> wildcards). You can specify multiple values for a filter. A Spot Instance request must * match at least one of the specified values for it to be included in the results. * * You can specify multiple filters (e.g., the Spot Price is equal to a particular value, and the instance type is <code>m1.small</code>). The * result includes information for a particular request only if it matches all your filters. If there's no match, no special message is * returned; the response is simply empty. * * You can use wildcards with the filter values: an asterisk matches zero or more characters, and <code>?</code> matches exactly one * character. You can escape special characters using a backslash before the character. For example, a value of <code>\*amazon\?\\</code> * searches for the literal string <code>*amazon?\</code>. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>SpotInstanceRequestId</code> - <code>string|array</code> - Optional - The ID of the request. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for SpotInstances. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_spot_instance_requests($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['SpotInstanceRequestId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'SpotInstanceRequestId' => (is_array($opt['SpotInstanceRequestId']) ? $opt['SpotInstanceRequestId'] : array($opt['SpotInstanceRequestId'])) ))); unset($opt['SpotInstanceRequestId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeSpotInstanceRequests', $opt, $this->hostname); } /** * * Creates a VPC with the CIDR block you specify. The smallest VPC you can create uses a <code>/28</code> netmask (16 IP addresses), and the * largest uses a <code>/18</code> netmask (16,384 IP addresses). To help you decide how big to make your VPC, go to the topic about creating * VPCs in the Amazon Virtual Private Cloud Developer Guide. * * By default, each instance you launch in the VPC has the default DHCP options (the standard EC2 host name, no domain name, no DNS server, no * NTP server, and no NetBIOS server or node type). * * @param string $cidr_block (Required) A valid CIDR block. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>InstanceTenancy</code> - <code>string</code> - Optional - The allowed tenancy of instances launched into the VPC. A value of default means instances can be launched with any tenancy; a value of dedicated means instances must be launched with tenancy as dedicated. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_vpc($cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['CidrBlock'] = $cidr_block; return $this->authenticate('CreateVpc', $opt, $this->hostname); } /** * * Gives you information about your customer gateways. You can filter the results to return information only about customer gateways that * match criteria you specify. For example, you could ask to get information about a particular customer gateway (or all) only if the gateway's * state is pending or available. You can specify multiple filters (e.g., the customer gateway has a particular IP address for the * Internet-routable external interface, and the gateway's state is pending or available). The result includes information for a particular * customer gateway only if the gateway matches all your filters. If there's no match, no special message is returned; the response is simply * empty. The following table shows the available filters. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>CustomerGatewayId</code> - <code>string|array</code> - Optional - A set of one or more customer gateway IDs. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Customer Gateways. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_customer_gateways($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['CustomerGatewayId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'CustomerGatewayId' => (is_array($opt['CustomerGatewayId']) ? $opt['CustomerGatewayId'] : array($opt['CustomerGatewayId'])) ))); unset($opt['CustomerGatewayId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeCustomerGateways', $opt, $this->hostname); } /** * * Creates a new route in a route table within a VPC. The route's target can be either a gateway attached to the VPC or a NAT instance in the * VPC. * * When determining how to route traffic, we use the route with the most specific match. For example, let's say the traffic is destined for * <code>192.0.2.3</code>, and the route table includes the following two routes: * * <ul> <li> <code>192.0.2.0/24</code> (goes to some target A) </li> * * <li> <code>192.0.2.0/28</code> (goes to some target B) </li> * * </ul> * * Both routes apply to the traffic destined for <code>192.0.2.3</code>. However, the second route in the list is more specific, so we use * that route to determine where to target the traffic. * * For more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * @param string $route_table_id (Required) The ID of the route table where the route will be added. * @param string $destination_cidr_block (Required) The CIDR address block used for the destination match. For example: <code>0.0.0.0/0</code>. Routing decisions are based on the most specific match. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GatewayId</code> - <code>string</code> - Optional - The ID of a VPN or Internet gateway attached to your VPC. You must provide either <code>GatewayId</code> or <code>InstanceId</code>, but not both. </li> * <li><code>InstanceId</code> - <code>string</code> - Optional - The ID of a NAT instance in your VPC. You must provide either <code>GatewayId</code> or <code>InstanceId</code>, but not both. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_route($route_table_id, $destination_cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['RouteTableId'] = $route_table_id; $opt['DestinationCidrBlock'] = $destination_cidr_block; return $this->authenticate('CreateRoute', $opt, $this->hostname); } /** * * Deletes a route table from a VPC. The route table must not be associated with a subnet. You can't delete the main route table. For more * information about route tables, go to <a href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route * Tables</a> in the Amazon Virtual Private Cloud User Guide. * * @param string $route_table_id (Required) The ID of the route table to be deleted. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_route_table($route_table_id, $opt = null) { if (!$opt) $opt = array(); $opt['RouteTableId'] = $route_table_id; return $this->authenticate('DeleteRouteTable', $opt, $this->hostname); } /** * * Creates a Spot Instance request. * * Spot Instances are instances that Amazon EC2 starts on your behalf when the maximum price that you specify exceeds the current Spot Price. * Amazon EC2 periodically sets the Spot Price based on available Spot Instance capacity and current spot instance requests. * * For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud * User Guide. * * @param string $spot_price (Required) Specifies the maximum hourly price for any Spot Instance launched to fulfill the request. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>InstanceCount</code> - <code>integer</code> - Optional - Specifies the maximum number of Spot Instances to launch. </li> * <li><code>Type</code> - <code>string</code> - Optional - Specifies the Spot Instance type. [Allowed values: <code>one-time</code>, <code>persistent</code>]</li> * <li><code>ValidFrom</code> - <code>string</code> - Optional - Defines the start date of the request. If this is a one-time request, the request becomes active at this date and time and remains active until all instances launch, the request expires, or the request is canceled. If the request is persistent, the request becomes active at this date and time and remains active until it expires or is canceled. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li> * <li><code>ValidUntil</code> - <code>string</code> - Optional - End date of the request. If this is a one-time request, the request remains active until all instances launch, the request is canceled, or this date is reached. If the request is persistent, it remains active until it is canceled or this date and time is reached. May be passed as a number of seconds since UNIX Epoch, or any string compatible with <php:strtotime()>.</li> * <li><code>LaunchGroup</code> - <code>string</code> - Optional - Specifies the instance launch group. Launch groups are Spot Instances that launch and terminate together. </li> * <li><code>AvailabilityZoneGroup</code> - <code>string</code> - Optional - Specifies the Availability Zone group. When specifying the same Availability Zone group for all Spot Instance requests, all Spot Instances are launched in the same Availability Zone. </li> * <li><code>LaunchSpecification</code> - <code>array</code> - Optional - Specifies additional launch instance information. <ul> * <li><code>ImageId</code> - <code>string</code> - Optional - The AMI ID. </li> * <li><code>KeyName</code> - <code>string</code> - Optional - The name of the key pair. </li> * <li><code>GroupSet</code> - <code>array</code> - Optional - Name of the security group. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>GroupName</code> - <code>string</code> - Optional - </li> * <li><code>GroupId</code> - <code>string</code> - Optional - </li> * </ul></li> * </ul></li> * <li><code>SecurityGroup</code> - <code>string|array</code> - Optional - Name of the security group. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>UserData</code> - <code>string</code> - Optional - Optional data, specific to a user's application, to provide in the launch request. All instances that collectively comprise the launch request have access to this data. User data is never returned through API responses. </li> * <li><code>InstanceType</code> - <code>string</code> - Optional - Specifies the instance type. [Allowed values: <code>t1.micro</code>, <code>m1.small</code>, <code>m1.large</code>, <code>m1.xlarge</code>, <code>m2.xlarge</code>, <code>m2.2xlarge</code>, <code>m2.4xlarge</code>, <code>c1.medium</code>, <code>c1.xlarge</code>, <code>cc1.4xlarge</code>, <code>cg1.4xlarge</code>]</li> * <li><code>Placement</code> - <code>array</code> - Optional - Defines a placement item. Takes an associative array of parameters that can have the following keys: <ul> * <li><code>AvailabilityZone</code> - <code>string</code> - Optional - The availability zone in which an Amazon EC2 instance runs. </li> * <li><code>GroupName</code> - <code>string</code> - Optional - The name of the PlacementGroup in which an Amazon EC2 instance runs. Placement groups are primarily used for launching High Performance Computing instances in the same group to ensure fast connection speeds. </li> * </ul></li> * <li><code>KernelId</code> - <code>string</code> - Optional - Specifies the ID of the kernel to select. </li> * <li><code>RamdiskId</code> - <code>string</code> - Optional - Specifies the ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the kernel requirements for information on whether or not you need to specify a RAM disk and search for the kernel ID. </li> * <li><code>BlockDeviceMapping</code> - <code>array</code> - Optional - Specifies how block devices are exposed to the instance. Each mapping is made up of a virtualName and a deviceName. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>VirtualName</code> - <code>string</code> - Optional - Specifies the virtual device name. </li> * <li><code>DeviceName</code> - <code>string</code> - Optional - Specifies the device name (e.g., <code>/dev/sdh</code>). </li> * <li><code>Ebs</code> - <code>array</code> - Optional - Specifies parameters used to automatically setup Amazon EBS volumes when the instance is launched. Takes an associative array of parameters that can have the following keys: <ul> * <li><code>SnapshotId</code> - <code>string</code> - Optional - The ID of the snapshot from which the volume will be created. </li> * <li><code>VolumeSize</code> - <code>integer</code> - Optional - The size of the volume, in gigabytes. </li> * <li><code>DeleteOnTermination</code> - <code>boolean</code> - Optional - Specifies whether the Amazon EBS volume is deleted on instance termination. </li> * </ul></li> * <li><code>NoDevice</code> - <code>string</code> - Optional - Specifies the device name to suppress during instance launch. </li> * </ul></li> * </ul></li> * <li><code>Monitoring.Enabled</code> - <code>boolean</code> - Optional - Enables monitoring for the instance. </li> * <li><code>SubnetId</code> - <code>string</code> - Optional - Specifies the Amazon VPC subnet ID within which to launch the instance(s) for Amazon Virtual Private Cloud. </li></ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function request_spot_instances($spot_price, $opt = null) { if (!$opt) $opt = array(); $opt['SpotPrice'] = $spot_price; // Optional parameter if (isset($opt['ValidFrom'])) { $opt['ValidFrom'] = $this->util->convert_date_to_iso8601($opt['ValidFrom']); } // Optional parameter if (isset($opt['ValidUntil'])) { $opt['ValidUntil'] = $this->util->convert_date_to_iso8601($opt['ValidUntil']); } // Optional parameter if (isset($opt['LaunchSpecification'])) { $opt = array_merge($opt, CFComplexType::map(array( 'LaunchSpecification' => $opt['LaunchSpecification'] ))); unset($opt['LaunchSpecification']); } return $this->authenticate('RequestSpotInstances', $opt, $this->hostname); } /** * * Adds or overwrites tags for the specified resources. Each resource can have a maximum of 10 tags. Each tag consists of a key-value pair. * Tag keys must be unique per resource. * * @param string|array $resource_id (Required) One or more IDs of resources to tag. This could be the ID of an AMI, an instance, an EBS volume, or snapshot, etc. Pass a string for a single value, or an indexed array for multiple values. * @param array $tag (Required) The tags to add or overwrite for the specified resources. Each tag item consists of a key-value pair. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Key</code> - <code>string</code> - Optional - The tag's key. </li> * <li><code>Value</code> - <code>string</code> - Optional - The tag's value. </li> * </ul></li> * </ul> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_tags($resource_id, $tag, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'ResourceId' => (is_array($resource_id) ? $resource_id : array($resource_id)) ))); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'Tag' => (is_array($tag) ? $tag : array($tag)) ))); return $this->authenticate('CreateTags', $opt, $this->hostname); } /** * * Replaces an existing route within a route table in a VPC. For more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * @param string $route_table_id (Required) The ID of the route table where the route will be replaced. * @param string $destination_cidr_block (Required) The CIDR address block used for the destination match. For example: <code>0.0.0.0/0</code>. The value you provide must match the CIDR of an existing route in the table. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>GatewayId</code> - <code>string</code> - Optional - The ID of a VPN or Internet gateway attached to your VPC. </li> * <li><code>InstanceId</code> - <code>string</code> - Optional - The ID of a NAT instance in your VPC. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function replace_route($route_table_id, $destination_cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['RouteTableId'] = $route_table_id; $opt['DestinationCidrBlock'] = $destination_cidr_block; return $this->authenticate('ReplaceRoute', $opt, $this->hostname); } /** * * Describes the tags for the specified resources. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for tags. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_tags($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeTags', $opt, $this->hostname); } /** * * CancelBundleTask operation cancels a pending or in-progress bundling task. This is an asynchronous call and it make take a while for the * task to be canceled. If a task is canceled while it is storing items, there may be parts of the incomplete AMI stored in S3. It is up to the * caller to clean up these parts from S3. * * @param string $bundle_id (Required) The ID of the bundle task to cancel. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function cancel_bundle_task($bundle_id, $opt = null) { if (!$opt) $opt = array(); $opt['BundleId'] = $bundle_id; return $this->authenticate('CancelBundleTask', $opt, $this->hostname); } /** * * Cancels one or more Spot Instance requests. * * Spot Instances are instances that Amazon EC2 starts on your behalf when the maximum price that you specify exceeds the current Spot Price. * Amazon EC2 periodically sets the Spot Price based on available Spot Instance capacity and current spot instance requests. * * For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud * User Guide. * * @param string|array $spot_instance_request_id (Required) Specifies the ID of the Spot Instance request. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function cancel_spot_instance_requests($spot_instance_request_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'SpotInstanceRequestId' => (is_array($spot_instance_request_id) ? $spot_instance_request_id : array($spot_instance_request_id)) ))); return $this->authenticate('CancelSpotInstanceRequests', $opt, $this->hostname); } /** * * The PurchaseReservedInstancesOffering operation purchases a Reserved Instance for use with your account. With Amazon EC2 Reserved * Instances, you purchase the right to launch Amazon EC2 instances for a period of time (without getting insufficient capacity errors) and pay * a lower usage rate for the actual time used. * * @param string $reserved_instances_offering_id (Required) The unique ID of the Reserved Instances offering being purchased. * @param integer $instance_count (Required) The number of Reserved Instances to purchase. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function purchase_reserved_instances_offering($reserved_instances_offering_id, $instance_count, $opt = null) { if (!$opt) $opt = array(); $opt['ReservedInstancesOfferingId'] = $reserved_instances_offering_id; $opt['InstanceCount'] = $instance_count; return $this->authenticate('PurchaseReservedInstancesOffering', $opt, $this->hostname); } /** * * Adds or remove permission settings for the specified snapshot. * * @param string $snapshot_id (Required) The ID of the EBS snapshot whose attributes are being modified. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Attribute</code> - <code>string</code> - Optional - The name of the attribute being modified. Available attribute names: <code>createVolumePermission</code> </li> * <li><code>OperationType</code> - <code>string</code> - Optional - The operation to perform on the attribute. Available operation names: <code>add</code>, <code>remove</code> </li> * <li><code>UserId</code> - <code>string|array</code> - Optional - The AWS user IDs to add to or remove from the list of users that have permission to create EBS volumes from the specified snapshot. Currently supports "all". Only valid when the <code>createVolumePermission</code> attribute is being modified. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>UserGroup</code> - <code>string|array</code> - Optional - The AWS group names to add to or remove from the list of groups that have permission to create EBS volumes from the specified snapshot. Currently supports "all". Only valid when the <code>createVolumePermission</code> attribute is being modified. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>CreateVolumePermission</code> - <code>array</code> - Optional - <ul> * <li><code>Add</code> - <code>array</code> - Optional - <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The user ID of the user that can create volumes from the snapshot. </li> * <li><code>Group</code> - <code>string</code> - Optional - The group that is allowed to create volumes from the snapshot (currently supports "all"). </li> * </ul></li> * </ul></li> * <li><code>Remove</code> - <code>array</code> - Optional - <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The user ID of the user that can create volumes from the snapshot. </li> * <li><code>Group</code> - <code>string</code> - Optional - The group that is allowed to create volumes from the snapshot (currently supports "all"). </li> * </ul></li> * </ul></li></ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function modify_snapshot_attribute($snapshot_id, $opt = null) { if (!$opt) $opt = array(); $opt['SnapshotId'] = $snapshot_id; // Optional parameter if (isset($opt['UserId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'UserId' => (is_array($opt['UserId']) ? $opt['UserId'] : array($opt['UserId'])) ))); unset($opt['UserId']); } // Optional parameter if (isset($opt['UserGroup'])) { $opt = array_merge($opt, CFComplexType::map(array( 'UserGroup' => (is_array($opt['UserGroup']) ? $opt['UserGroup'] : array($opt['UserGroup'])) ))); unset($opt['UserGroup']); } // Optional parameter if (isset($opt['CreateVolumePermission'])) { $opt = array_merge($opt, CFComplexType::map(array( 'CreateVolumePermission' => $opt['CreateVolumePermission'] ))); unset($opt['CreateVolumePermission']); } return $this->authenticate('ModifySnapshotAttribute', $opt, $this->hostname); } /** * * The TerminateInstances operation shuts down one or more instances. This operation is idempotent; if you terminate an instance more than * once, each call will succeed. * * Terminated instances will remain visible after termination (approximately one hour). * * @param string|array $instance_id (Required) The list of instances to terminate. Pass a string for a single value, or an indexed array for multiple values. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function terminate_instances($instance_id, $opt = null) { if (!$opt) $opt = array(); // Required parameter $opt = array_merge($opt, CFComplexType::map(array( 'InstanceId' => (is_array($instance_id) ? $instance_id : array($instance_id)) ))); return $this->authenticate('TerminateInstances', $opt, $this->hostname); } /** * * Deletes the data feed for Spot Instances. * * For conceptual information about Spot Instances, refer to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud * User Guide. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_spot_datafeed_subscription($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('DeleteSpotDatafeedSubscription', $opt, $this->hostname); } /** * * Deletes an Internet gateway from your AWS account. The gateway must not be attached to a VPC. For more information about your VPC and * Internet gateway, go to Amazon Virtual Private Cloud User Guide. * * @param string $internet_gateway_id (Required) The ID of the Internet gateway to be deleted. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_internet_gateway($internet_gateway_id, $opt = null) { if (!$opt) $opt = array(); $opt['InternetGatewayId'] = $internet_gateway_id; return $this->authenticate('DeleteInternetGateway', $opt, $this->hostname); } /** * * Changes the route table associated with a given subnet in a VPC. After you execute this action, the subnet uses the routes in the new route * table it's associated with. For more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * You can also use this to change which table is the main route table in the VPC. You just specify the main route table's association ID and * the route table that you want to be the new main route table. * * @param string $association_id (Required) The ID representing the current association between the original route table and the subnet. * @param string $route_table_id (Required) The ID of the new route table to associate with the subnet. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function replace_route_table_association($association_id, $route_table_id, $opt = null) { if (!$opt) $opt = array(); $opt['AssociationId'] = $association_id; $opt['RouteTableId'] = $route_table_id; return $this->authenticate('ReplaceRouteTableAssociation', $opt, $this->hostname); } /** * * Returns information about an attribute of a snapshot. Only one attribute can be specified per call. * * @param string $snapshot_id (Required) The ID of the EBS snapshot whose attribute is being described. * @param string $attribute (Required) The name of the EBS attribute to describe. Available attribute names: createVolumePermission * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_snapshot_attribute($snapshot_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['SnapshotId'] = $snapshot_id; $opt['Attribute'] = $attribute; return $this->authenticate('DescribeSnapshotAttribute', $opt, $this->hostname); } /** * * The DescribeAddresses operation lists elastic IP addresses assigned to your account. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>PublicIp</code> - <code>string|array</code> - Optional - The optional list of Elastic IP addresses to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Addresses. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>AllocationId</code> - <code>string|array</code> - Optional - Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_addresses($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['PublicIp'])) { $opt = array_merge($opt, CFComplexType::map(array( 'PublicIp' => (is_array($opt['PublicIp']) ? $opt['PublicIp'] : array($opt['PublicIp'])) ))); unset($opt['PublicIp']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } // Optional parameter if (isset($opt['AllocationId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'AllocationId' => (is_array($opt['AllocationId']) ? $opt['AllocationId'] : array($opt['AllocationId'])) ))); unset($opt['AllocationId']); } return $this->authenticate('DescribeAddresses', $opt, $this->hostname); } /** * * The DescribeKeyPairs operation returns information about key pairs available to you. If you specify key pairs, information about those key * pairs is returned. Otherwise, information for all registered key pairs is returned. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>KeyName</code> - <code>string|array</code> - Optional - The optional list of key pair names to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for KeyPairs. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_key_pairs($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['KeyName'])) { $opt = array_merge($opt, CFComplexType::map(array( 'KeyName' => (is_array($opt['KeyName']) ? $opt['KeyName'] : array($opt['KeyName'])) ))); unset($opt['KeyName']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeKeyPairs', $opt, $this->hostname); } /** * * The DescribeImageAttribute operation returns information about an attribute of an AMI. Only one attribute can be specified per call. * * @param string $image_id (Required) The ID of the AMI whose attribute is to be described. * @param string $attribute (Required) The name of the attribute to describe. Available attribute names: <code>productCodes</code>, <code>kernel</code>, <code>ramdisk</code>, <code>launchPermisson</code>, <code>blockDeviceMapping</code> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_image_attribute($image_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['ImageId'] = $image_id; $opt['Attribute'] = $attribute; return $this->authenticate('DescribeImageAttribute', $opt, $this->hostname); } /** * * Disassociates a subnet from a route table. * * After you perform this action, the subnet no longer uses the routes in the route table. Instead it uses the routes in the VPC's main route * table. For more information about route tables, go to <a * href="http://docs.amazonwebservices.com/AmazonVPC/latest/UserGuide/VPC_Route_Tables.html">Route Tables</a> in the Amazon Virtual Private * Cloud User Guide. * * @param string $association_id (Required) The association ID representing the current association between the route table and subnet. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function disassociate_route_table($association_id, $opt = null) { if (!$opt) $opt = array(); $opt['AssociationId'] = $association_id; return $this->authenticate('DisassociateRouteTable', $opt, $this->hostname); } /** * * The ConfirmProductInstance operation returns true if the specified product code is attached to the specified instance. The operation * returns false if the product code is not attached to the instance. * * The ConfirmProductInstance operation can only be executed by the owner of the AMI. This feature is useful when an AMI owner is providing * support and wants to verify whether a user's instance is eligible. * * @param string $product_code (Required) The product code to confirm. * @param string $instance_id (Required) The ID of the instance to confirm. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function confirm_product_instance($product_code, $instance_id, $opt = null) { if (!$opt) $opt = array(); $opt['ProductCode'] = $product_code; $opt['InstanceId'] = $instance_id; return $this->authenticate('ConfirmProductInstance', $opt, $this->hostname); } /** * * Deletes an ingress or egress entry (i.e., rule) from a network ACL. For more information about network ACLs, go to Network ACLs in the * Amazon Virtual Private Cloud User Guide. * * @param string $network_acl_id (Required) ID of the network ACL. * @param integer $rule_number (Required) Rule number for the entry to delete. * @param boolean $egress (Required) Whether the rule to delete is an egress rule (<code>true</code>) or ingress rule (<code>false</code>). * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_network_acl_entry($network_acl_id, $rule_number, $egress, $opt = null) { if (!$opt) $opt = array(); $opt['NetworkAclId'] = $network_acl_id; $opt['RuleNumber'] = $rule_number; $opt['Egress'] = $egress; return $this->authenticate('DeleteNetworkAclEntry', $opt, $this->hostname); } /** * * This action applies only to security groups in a VPC. It doesn't work with EC2 security groups. For information about Amazon Virtual * Private Cloud and VPC security groups, go to the Amazon Virtual Private Cloud User Guide. * * The action removes one or more egress rules from a VPC security group. The values that you specify in the revoke request (e.g., ports, * etc.) must match the existing rule's values in order for the rule to be revoked. * * Each rule consists of the protocol, and the CIDR range or destination security group. For the TCP and UDP protocols, you must also specify * the destination port or range of ports. For the ICMP protocol, you must also specify the ICMP type and code. * * Rule changes are propagated to instances within the security group as quickly as possible. However, a small delay might occur. * * @param string $group_id (Required) ID of the VPC security group to modify. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>IpPermissions</code> - <code>array</code> - Optional - List of IP permissions to authorize on the specified security group. Specifying permissions through IP permissions is the preferred way of authorizing permissions since it offers more flexibility and control. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>IpProtocol</code> - <code>string</code> - Optional - The IP protocol of this permission. Valid protocol values: <code>tcp</code>, <code>udp</code>, <code>icmp</code> </li> * <li><code>FromPort</code> - <code>integer</code> - Optional - Start of port range for the TCP and UDP protocols, or an ICMP type number. An ICMP type number of <code>-1</code> indicates a wildcard (i.e., any ICMP type number). </li> * <li><code>ToPort</code> - <code>integer</code> - Optional - End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of <code>-1</code> indicates a wildcard (i.e., any ICMP code). </li> * <li><code>Groups</code> - <code>array</code> - Optional - The list of AWS user IDs and groups included in this permission. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>UserId</code> - <code>string</code> - Optional - The AWS user ID of an account. </li> * <li><code>GroupName</code> - <code>string</code> - Optional - Name of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * <li><code>GroupId</code> - <code>string</code> - Optional - ID of the security group in the specified AWS account. Cannot be used when specifying a CIDR IP address range. </li> * </ul></li> * </ul></li> * <li><code>IpRanges</code> - <code>string|array</code> - Optional - The list of CIDR IP ranges included in this permission. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function revoke_security_group_egress($group_id, $opt = null) { if (!$opt) $opt = array(); $opt['GroupId'] = $group_id; // Optional parameter if (isset($opt['IpPermissions'])) { $opt = array_merge($opt, CFComplexType::map(array( 'IpPermissions' => $opt['IpPermissions'] ))); unset($opt['IpPermissions']); } return $this->authenticate('RevokeSecurityGroupEgress', $opt, $this->hostname); } /** * * Initializes an empty volume of a given size. * * @param string $availability_zone (Required) The Availability Zone in which to create the new volume. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Size</code> - <code>integer</code> - Optional - The size of the volume, in gigabytes. Required if you are not creating a volume from a snapshot. </li> * <li><code>SnapshotId</code> - <code>string</code> - Optional - The ID of the snapshot from which to create the new volume. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_volume($availability_zone, $opt = null) { if (!$opt) $opt = array(); $opt['AvailabilityZone'] = $availability_zone; return $this->authenticate('CreateVolume', $opt, $this->hostname); } /** * * Gives you information about your VPN gateways. You can filter the results to return information only about VPN gateways that match criteria * you specify. * * For example, you could ask to get information about a particular VPN gateway (or all) only if the gateway's state is pending or available. * You can specify multiple filters (e.g., the VPN gateway is in a particular Availability Zone and the gateway's state is pending or * available). * * The result includes information for a particular VPN gateway only if the gateway matches all your filters. If there's no match, no special * message is returned; the response is simply empty. The following table shows the available filters. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>VpnGatewayId</code> - <code>string|array</code> - Optional - A list of filters used to match properties for VPN Gateways. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for VPN Gateways. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_vpn_gateways($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['VpnGatewayId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'VpnGatewayId' => (is_array($opt['VpnGatewayId']) ? $opt['VpnGatewayId'] : array($opt['VpnGatewayId'])) ))); unset($opt['VpnGatewayId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeVpnGateways', $opt, $this->hostname); } /** * * Creates a subnet in an existing VPC. You can create up to 20 subnets in a VPC. If you add more than one subnet to a VPC, they're set up in * a star topology with a logical router in the middle. When you create each subnet, you provide the VPC ID and the CIDR block you want for the * subnet. Once you create a subnet, you can't change its CIDR block. The subnet's CIDR block can be the same as the VPC's CIDR block (assuming * you want only a single subnet in the VPC), or a subset of the VPC's CIDR block. If you create more than one subnet in a VPC, the subnets' * CIDR blocks must not overlap. The smallest subnet (and VPC) you can create uses a <code>/28</code> netmask (16 IP addresses), and the * largest uses a <code>/18</code> netmask (16,384 IP addresses). * * AWS reserves both the first four and the last IP address in each subnet's CIDR block. They're not available for use. * * @param string $vpc_id (Required) The ID of the VPC to create the subnet in. * @param string $cidr_block (Required) The CIDR block the subnet is to cover. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>AvailabilityZone</code> - <code>string</code> - Optional - The Availability Zone to create the subnet in. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_subnet($vpc_id, $cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['VpcId'] = $vpc_id; $opt['CidrBlock'] = $cidr_block; return $this->authenticate('CreateSubnet', $opt, $this->hostname); } /** * * The DescribeReservedInstancesOfferings operation describes Reserved Instance offerings that are available for purchase. With Amazon EC2 * Reserved Instances, you purchase the right to launch Amazon EC2 instances for a period of time (without getting insufficient capacity * errors) and pay a lower usage rate for the actual time used. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>ReservedInstancesOfferingId</code> - <code>string|array</code> - Optional - An optional list of the unique IDs of the Reserved Instance offerings to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>InstanceType</code> - <code>string</code> - Optional - The instance type on which the Reserved Instance can be used. [Allowed values: <code>t1.micro</code>, <code>m1.small</code>, <code>m1.large</code>, <code>m1.xlarge</code>, <code>m2.xlarge</code>, <code>m2.2xlarge</code>, <code>m2.4xlarge</code>, <code>c1.medium</code>, <code>c1.xlarge</code>, <code>cc1.4xlarge</code>, <code>cg1.4xlarge</code>]</li> * <li><code>AvailabilityZone</code> - <code>string</code> - Optional - The Availability Zone in which the Reserved Instance can be used. </li> * <li><code>ProductDescription</code> - <code>string</code> - Optional - The Reserved Instance product description. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for ReservedInstancesOfferings. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>InstanceTenancy</code> - <code>string</code> - Optional - The tenancy of the Reserved Instance offering. A Reserved Instance with tenancy of dedicated will run on single-tenant hardware and can only be launched within a VPC. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_reserved_instances_offerings($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['ReservedInstancesOfferingId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'ReservedInstancesOfferingId' => (is_array($opt['ReservedInstancesOfferingId']) ? $opt['ReservedInstancesOfferingId'] : array($opt['ReservedInstancesOfferingId'])) ))); unset($opt['ReservedInstancesOfferingId']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeReservedInstancesOfferings', $opt, $this->hostname); } /** * * Deletes the snapshot identified by <code>snapshotId</code>. * * @param string $snapshot_id (Required) The ID of the snapshot to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_snapshot($snapshot_id, $opt = null) { if (!$opt) $opt = array(); $opt['SnapshotId'] = $snapshot_id; return $this->authenticate('DeleteSnapshot', $opt, $this->hostname); } /** * * Changes which network ACL a subnet is associated with. By default when you create a subnet, it's automatically associated with the default * network ACL. For more information about network ACLs, go to Network ACLs in the Amazon Virtual Private Cloud User Guide. * * @param string $association_id (Required) The ID representing the current association between the original network ACL and the subnet. * @param string $network_acl_id (Required) The ID of the new ACL to associate with the subnet. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function replace_network_acl_association($association_id, $network_acl_id, $opt = null) { if (!$opt) $opt = array(); $opt['AssociationId'] = $association_id; $opt['NetworkAclId'] = $network_acl_id; return $this->authenticate('ReplaceNetworkAclAssociation', $opt, $this->hostname); } /** * * The DisassociateAddress operation disassociates the specified elastic IP address from the instance to which it is assigned. This is an * idempotent operation. If you enter it more than once, Amazon EC2 does not return an error. * * @param string $public_ip (Required) The elastic IP address that you are disassociating from the instance. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>AssociationId</code> - <code>string</code> - Optional - Association ID corresponding to the VPC elastic IP address you want to disassociate. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function disassociate_address($public_ip, $opt = null) { if (!$opt) $opt = array(); $opt['PublicIp'] = $public_ip; return $this->authenticate('DisassociateAddress', $opt, $this->hostname); } /** * * Creates a PlacementGroup into which multiple Amazon EC2 instances can be launched. Users must give the group a name unique within the scope * of the user account. * * @param string $group_name (Required) The name of the <code>PlacementGroup</code>. * @param string $strategy (Required) The <code>PlacementGroup</code> strategy. [Allowed values: <code>cluster</code>] * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_placement_group($group_name, $strategy, $opt = null) { if (!$opt) $opt = array(); $opt['GroupName'] = $group_name; $opt['Strategy'] = $strategy; return $this->authenticate('CreatePlacementGroup', $opt, $this->hostname); } /** * The BundleInstance operation request that an instance is bundled the next time it boots. The * bundling process creates a new image from a running instance and stores the AMI data in S3. Once * bundled, the image must be registered in the normal way using the RegisterImage API. * * @param string $instance_id (Required) The ID of the instance to bundle. * @param array $policy (Required) The details of S3 storage for bundling a Windows instance. Takes an associative array of parameters that can have the following keys: <ul> * <li><code>Bucket</code> - <code>string</code> - Optional - The bucket in which to store the AMI. You can specify a bucket that you already own or a new bucket that Amazon EC2 creates on your behalf. If you specify a bucket that belongs to someone else, Amazon EC2 returns an error.</li> * <li><code>Prefix</code> - <code>string</code> - Optional - The prefix to use when storing the AMI in S3.</li> * <li><code>AWSAccessKeyId</code> - <code>string</code> - Optional - The Access Key ID of the owner of the Amazon S3 bucket. Use the <CFPolicy::get_key()> method of a <CFPolicy> instance.</li> * <li><code>UploadPolicy</code> - <code>string</code> - Optional - A Base64-encoded Amazon S3 upload policy that gives Amazon EC2 permission to upload items into Amazon S3 on the user's behalf. Use the <CFPolicy::get_policy()> method of a <CFPolicy> instance.</li> * <li><code>UploadPolicySignature</code> - <code>string</code> - Optional - The signature of the Base64 encoded JSON document. Use the <CFPolicy::get_policy_signature()> method of a <CFPolicy> instance.</li></ul> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This is useful for manually-managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function bundle_instance($instance_id, $policy, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; $opt = array_merge($opt, CFComplexType::map(array( 'Storage.S3' => $policy ))); return $this->authenticate('BundleInstance', $opt, $this->hostname); } /** * * Deletes a PlacementGroup from a user's account. Terminate all Amazon EC2 instances in the placement group before deletion. * * @param string $group_name (Required) The name of the <code>PlacementGroup</code> to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_placement_group($group_name, $opt = null) { if (!$opt) $opt = array(); $opt['GroupName'] = $group_name; return $this->authenticate('DeletePlacementGroup', $opt, $this->hostname); } /** * * Deletes a VPC. You must detach or delete all gateways or other objects that are dependent on the VPC first. For example, you must terminate * all running instances, delete all VPC security groups (except the default), delete all the route tables (except the default), etc. * * @param string $vpc_id (Required) The ID of the VPC you want to delete. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function delete_vpc($vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpcId'] = $vpc_id; return $this->authenticate('DeleteVpc', $opt, $this->hostname); } /** * * The AllocateAddress operation acquires an elastic IP address for use with your account. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Domain</code> - <code>string</code> - Optional - Set to <code>vpc</code> to allocate the address to your VPC. By default, will allocate to EC2. [Allowed values: <code>vpc</code>, <code>standard</code>]</li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function allocate_address($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('AllocateAddress', $opt, $this->hostname); } /** * * The ReleaseAddress operation releases an elastic IP address associated with your account. * * Releasing an IP address automatically disassociates it from any instance with which it is associated. For more information, see * DisassociateAddress. * * After releasing an elastic IP address, it is released to the IP address pool and might no longer be available to your account. Make sure to * update your DNS records and any servers or devices that communicate with the address. * * If you run this operation on an elastic IP address that is already released, the address might be assigned to another account which will * cause Amazon EC2 to return an error. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>PublicIp</code> - <code>string</code> - Optional - The elastic IP address that you are releasing from your account. </li> * <li><code>AllocationId</code> - <code>string</code> - Optional - The allocation ID that AWS provided when you allocated the address for use with Amazon VPC. </li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function release_address($opt = null) { if (!$opt) $opt = array(); return $this->authenticate('ReleaseAddress', $opt, $this->hostname); } /** * * Resets an attribute of an instance to its default value. * * @param string $instance_id (Required) The ID of the Amazon EC2 instance whose attribute is being reset. * @param string $attribute (Required) The name of the attribute being reset. Available attribute names: <code>kernel</code>, <code>ramdisk</code> * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function reset_instance_attribute($instance_id, $attribute, $opt = null) { if (!$opt) $opt = array(); $opt['InstanceId'] = $instance_id; $opt['Attribute'] = $attribute; return $this->authenticate('ResetInstanceAttribute', $opt, $this->hostname); } /** * * The CreateKeyPair operation creates a new 2048 bit RSA key pair and returns a unique ID that can be used to reference this key pair when * launching new instances. For more information, see RunInstances. * * @param string $key_name (Required) The unique name for the new key pair. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_key_pair($key_name, $opt = null) { if (!$opt) $opt = array(); $opt['KeyName'] = $key_name; return $this->authenticate('CreateKeyPair', $opt, $this->hostname); } /** * * Replaces an entry (i.e., rule) in a network ACL. For more information about network ACLs, go to Network ACLs in the Amazon Virtual Private * Cloud User Guide. * * @param string $network_acl_id (Required) ID of the ACL where the entry will be replaced. * @param integer $rule_number (Required) Rule number of the entry to replace. * @param string $protocol (Required) IP protocol the rule applies to. Valid Values: <code>tcp</code>, <code>udp</code>, <code>icmp</code> or an IP protocol number. * @param string $rule_action (Required) Whether to allow or deny traffic that matches the rule. [Allowed values: <code>allow</code>, <code>deny</code>] * @param boolean $egress (Required) Whether this rule applies to egress traffic from the subnet (<code>true</code>) or ingress traffic (<code>false</code>). * @param string $cidr_block (Required) The CIDR range to allow or deny, in CIDR notation (e.g., <code>172.16.0.0/24</code>). * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>Icmp</code> - <code>array</code> - Optional - ICMP values. <ul> * <li><code>Type</code> - <code>integer</code> - Optional - For the ICMP protocol, the ICMP type. A value of <code>-1</code> is a wildcard meaning all types. Required if specifying <code>icmp</code> for the protocol. </li> * <li><code>Code</code> - <code>integer</code> - Optional - For the ICMP protocol, the ICMP code. A value of <code>-1</code> is a wildcard meaning all codes. Required if specifying <code>icmp</code> for the protocol. </li></ul></li> * <li><code>PortRange</code> - <code>array</code> - Optional - Port ranges. <ul> * <li><code>From</code> - <code>integer</code> - Optional - The first port in the range. Required if specifying <code>tcp</code> or <code>udp</code> for the protocol. </li> * <li><code>To</code> - <code>integer</code> - Optional - The last port in the range. Required if specifying <code>tcp</code> or <code>udp</code> for the protocol. </li></ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function replace_network_acl_entry($network_acl_id, $rule_number, $protocol, $rule_action, $egress, $cidr_block, $opt = null) { if (!$opt) $opt = array(); $opt['NetworkAclId'] = $network_acl_id; $opt['RuleNumber'] = $rule_number; $opt['Protocol'] = $protocol; $opt['RuleAction'] = $rule_action; $opt['Egress'] = $egress; $opt['CidrBlock'] = $cidr_block; // Optional parameter if (isset($opt['Icmp'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Icmp' => $opt['Icmp'] ))); unset($opt['Icmp']); } // Optional parameter if (isset($opt['PortRange'])) { $opt = array_merge($opt, CFComplexType::map(array( 'PortRange' => $opt['PortRange'] ))); unset($opt['PortRange']); } return $this->authenticate('ReplaceNetworkAclEntry', $opt, $this->hostname); } /** * * Returns information about the Amazon EBS snapshots available to you. Snapshots available to you include public snapshots available for any * AWS account to launch, private snapshots you own, and private snapshots owned by another AWS account but for which you've been given * explicit create volume permissions. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>SnapshotId</code> - <code>string|array</code> - Optional - The optional list of EBS snapshot IDs to describe. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Owner</code> - <code>string|array</code> - Optional - The optional list of EBS snapshot owners. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>RestorableBy</code> - <code>string|array</code> - Optional - The optional list of users who have permission to create volumes from the described EBS snapshots. Pass a string for a single value, or an indexed array for multiple values. </li> * <li><code>Filter</code> - <code>array</code> - Optional - A list of filters used to match properties for Snapshots. For a complete reference to the available filter keys for this operation, see the Amazon EC2 API reference. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>Name</code> - <code>string</code> - Optional - Specifies the name of the filter. </li> * <li><code>Value</code> - <code>string|array</code> - Optional - Contains one or more values for the filter. Pass a string for a single value, or an indexed array for multiple values. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function describe_snapshots($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['SnapshotId'])) { $opt = array_merge($opt, CFComplexType::map(array( 'SnapshotId' => (is_array($opt['SnapshotId']) ? $opt['SnapshotId'] : array($opt['SnapshotId'])) ))); unset($opt['SnapshotId']); } // Optional parameter if (isset($opt['Owner'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Owner' => (is_array($opt['Owner']) ? $opt['Owner'] : array($opt['Owner'])) ))); unset($opt['Owner']); } // Optional parameter if (isset($opt['RestorableBy'])) { $opt = array_merge($opt, CFComplexType::map(array( 'RestorableBy' => (is_array($opt['RestorableBy']) ? $opt['RestorableBy'] : array($opt['RestorableBy'])) ))); unset($opt['RestorableBy']); } // Optional parameter if (isset($opt['Filter'])) { $opt = array_merge($opt, CFComplexType::map(array( 'Filter' => $opt['Filter'] ))); unset($opt['Filter']); } return $this->authenticate('DescribeSnapshots', $opt, $this->hostname); } /** * * Creates a new network ACL in a VPC. Network ACLs provide an optional layer of security (on top of security groups) for the instances in * your VPC. For more information about network ACLs, go to Network ACLs in the Amazon Virtual Private Cloud User Guide. * * @param string $vpc_id (Required) The ID of the VPC where the network ACL will be created. * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function create_network_acl($vpc_id, $opt = null) { if (!$opt) $opt = array(); $opt['VpcId'] = $vpc_id; return $this->authenticate('CreateNetworkAcl', $opt, $this->hostname); } /** * * The RegisterImage operation registers an AMI with Amazon EC2. Images must be registered before they can be launched. For more information, * see RunInstances. * * Each AMI is associated with an unique ID which is provided by the Amazon EC2 service through the RegisterImage operation. During * registration, Amazon EC2 retrieves the specified image manifest from Amazon S3 and verifies that the image is owned by the user registering * the image. * * The image manifest is retrieved once and stored within the Amazon EC2. Any modifications to an image in Amazon S3 invalidates this * registration. If you make changes to an image, deregister the previous image and register the new image. For more information, see * DeregisterImage. * * @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul> * <li><code>ImageLocation</code> - <code>string</code> - Optional - The full path to your AMI manifest in Amazon S3 storage. </li> * <li><code>Name</code> - <code>string</code> - Optional - The name to give the new Amazon Machine Image. Constraints: 3-128 alphanumeric characters, parenthesis (<code>()</code>), commas (<code>,</code>), slashes (<code>/</code>), dashes (<code>-</code>), or underscores(<code>_</code>) </li> * <li><code>Description</code> - <code>string</code> - Optional - The description describing the new AMI. </li> * <li><code>Architecture</code> - <code>string</code> - Optional - The architecture of the image. Valid Values: <code>i386</code>, <code>x86_64</code> </li> * <li><code>KernelId</code> - <code>string</code> - Optional - The optional ID of a specific kernel to register with the new AMI. </li> * <li><code>RamdiskId</code> - <code>string</code> - Optional - The optional ID of a specific ramdisk to register with the new AMI. Some kernels require additional drivers at launch. Check the kernel requirements for information on whether you need to specify a RAM disk. </li> * <li><code>RootDeviceName</code> - <code>string</code> - Optional - The root device name (e.g., <code>/dev/sda1</code>). </li> * <li><code>BlockDeviceMapping</code> - <code>array</code> - Optional - The block device mappings for the new AMI, which specify how different block devices (ex: EBS volumes and ephemeral drives) will be exposed on instances launched from the new image. <ul> * <li><code>x</code> - <code>array</code> - This represents a simple array index. <ul> * <li><code>VirtualName</code> - <code>string</code> - Optional - Specifies the virtual device name. </li> * <li><code>DeviceName</code> - <code>string</code> - Optional - Specifies the device name (e.g., <code>/dev/sdh</code>). </li> * <li><code>Ebs</code> - <code>array</code> - Optional - Specifies parameters used to automatically setup Amazon EBS volumes when the instance is launched. Takes an associative array of parameters that can have the following keys: <ul> * <li><code>SnapshotId</code> - <code>string</code> - Optional - The ID of the snapshot from which the volume will be created. </li> * <li><code>VolumeSize</code> - <code>integer</code> - Optional - The size of the volume, in gigabytes. </li> * <li><code>DeleteOnTermination</code> - <code>boolean</code> - Optional - Specifies whether the Amazon EBS volume is deleted on instance termination. </li> * </ul></li> * <li><code>NoDevice</code> - <code>string</code> - Optional - Specifies the device name to suppress during instance launch. </li> * </ul></li> * </ul></li> * <li><code>curlopts</code> - <code>array</code> - Optional - A set of values to pass directly into <code>curl_setopt()</code>, where the key is a pre-defined <code>CURLOPT_*</code> constant.</li> * <li><code>returnCurlHandle</code> - <code>boolean</code> - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.</li></ul> * @return CFResponse A <CFResponse> object containing a parsed HTTP response. */ public function register_image($opt = null) { if (!$opt) $opt = array(); // Optional parameter if (isset($opt['BlockDeviceMapping'])) { $opt = array_merge($opt, CFComplexType::map(array( 'BlockDeviceMapping' => $opt['BlockDeviceMapping'] ))); unset($opt['BlockDeviceMapping']); } return $this->authenticate('RegisterImage', $opt, $this->hostname); } } /*%******************************************************************************************%*/ // EXCEPTIONS /** * Default EC2 Exception. */ class EC2_Exception extends Exception {}
wshearn/openshift-quickstart-modx
php/core/model/aws/services/ec2.class.php
PHP
gpl-2.0
256,814
/* $Id: exitcodes.h,v 1.7 2005/08/31 17:36:11 kloczek Exp $ */ /* * Exit codes used by shadow programs */ #define E_SUCCESS 0 /* success */ #define E_NOPERM 1 /* permission denied */ #define E_USAGE 2 /* invalid command syntax */ #define E_BAD_ARG 3 /* invalid argument to option */ #define E_PASSWD_NOTFOUND 14 /* not found password file */ #define E_SHADOW_NOTFOUND 15 /* not found shadow password file */ #define E_GROUP_NOTFOUND 16 /* not found group file */ #define E_GSHADOW_NOTFOUND 17 /* not found shadow group file */
rhuitl/uClinux
user/shadow/lib/exitcodes.h
C
gpl-2.0
561
/* $Id: bwtwofb.c,v 1.13 2000/02/14 02:50:25 davem Exp $ * bwtwofb.c: BWtwo frame buffer driver * * Copyright (C) 1998 Jakub Jelinek (jj@ultra.linux.cz) * Copyright (C) 1996 Miguel de Icaza (miguel@nuclecu.unam.mx) * Copyright (C) 1997 Eddie C. Dost (ecd@skynet.be) * Copyright (C) 1998 Pavel Machek (pavel@ucw.cz) */ #include <linux/config.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/malloc.h> #include <linux/vmalloc.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/selection.h> #include <video/sbusfb.h> #include <asm/io.h> #if !defined(__sparc_v9__) && !defined(__mc68000__) #include <asm/sun4paddr.h> #endif #include <video/fbcon-mfb.h> /* OBio addresses for the bwtwo registers */ #define BWTWO_REGISTER_OFFSET 0x400000 struct bw2_regs { struct bt_regs bt; volatile u8 control; volatile u8 status; volatile u8 cursor_start; volatile u8 cursor_end; volatile u8 h_blank_start; volatile u8 h_blank_end; volatile u8 h_sync_start; volatile u8 h_sync_end; volatile u8 comp_sync_end; volatile u8 v_blank_start_high; volatile u8 v_blank_start_low; volatile u8 v_blank_end; volatile u8 v_sync_start; volatile u8 v_sync_end; volatile u8 xfer_holdoff_start; volatile u8 xfer_holdoff_end; }; /* Status Register Constants */ #define BWTWO_SR_RES_MASK 0x70 #define BWTWO_SR_1600_1280 0x50 #define BWTWO_SR_1152_900_76_A 0x40 #define BWTWO_SR_1152_900_76_B 0x60 #define BWTWO_SR_ID_MASK 0x0f #define BWTWO_SR_ID_MONO 0x02 #define BWTWO_SR_ID_MONO_ECL 0x03 #define BWTWO_SR_ID_MSYNC 0x04 #define BWTWO_SR_ID_NOCONN 0x0a /* Control Register Constants */ #define BWTWO_CTL_ENABLE_INTS 0x80 #define BWTWO_CTL_ENABLE_VIDEO 0x40 #define BWTWO_CTL_ENABLE_TIMING 0x20 #define BWTWO_CTL_ENABLE_CURCMP 0x10 #define BWTWO_CTL_XTAL_MASK 0x0C #define BWTWO_CTL_DIVISOR_MASK 0x03 /* Status Register Constants */ #define BWTWO_STAT_PENDING_INT 0x80 #define BWTWO_STAT_MSENSE_MASK 0x70 #define BWTWO_STAT_ID_MASK 0x0f static struct sbus_mmap_map bw2_mmap_map[] = { { 0, 0, SBUS_MMAP_FBSIZE(1) }, { 0, 0, 0 } }; static void bw2_blank (struct fb_info_sbusfb *fb) { unsigned long flags; u8 tmp; spin_lock_irqsave(&fb->lock, flags); tmp = sbus_readb(&fb->s.bw2.regs->control); tmp &= ~BWTWO_CTL_ENABLE_VIDEO; sbus_writeb(tmp, &fb->s.bw2.regs->control); spin_unlock_irqrestore(&fb->lock, flags); } static void bw2_unblank (struct fb_info_sbusfb *fb) { unsigned long flags; u8 tmp; spin_lock_irqsave(&fb->lock, flags); tmp = sbus_readb(&fb->s.bw2.regs->control); tmp |= BWTWO_CTL_ENABLE_VIDEO; sbus_writeb(tmp, &fb->s.bw2.regs->control); spin_unlock_irqrestore(&fb->lock, flags); } static void bw2_margins (struct fb_info_sbusfb *fb, struct display *p, int x_margin, int y_margin) { p->screen_base += (y_margin - fb->y_margin) * p->line_length + ((x_margin - fb->x_margin) >> 3); } static u8 bw2regs_1600[] __initdata = { 0x14, 0x8b, 0x15, 0x28, 0x16, 0x03, 0x17, 0x13, 0x18, 0x7b, 0x19, 0x05, 0x1a, 0x34, 0x1b, 0x2e, 0x1c, 0x00, 0x1d, 0x0a, 0x1e, 0xff, 0x1f, 0x01, 0x10, 0x21, 0 }; static u8 bw2regs_ecl[] __initdata = { 0x14, 0x65, 0x15, 0x1e, 0x16, 0x04, 0x17, 0x0c, 0x18, 0x5e, 0x19, 0x03, 0x1a, 0xa7, 0x1b, 0x23, 0x1c, 0x00, 0x1d, 0x08, 0x1e, 0xff, 0x1f, 0x01, 0x10, 0x20, 0 }; static u8 bw2regs_analog[] __initdata = { 0x14, 0xbb, 0x15, 0x2b, 0x16, 0x03, 0x17, 0x13, 0x18, 0xb0, 0x19, 0x03, 0x1a, 0xa6, 0x1b, 0x22, 0x1c, 0x01, 0x1d, 0x05, 0x1e, 0xff, 0x1f, 0x01, 0x10, 0x20, 0 }; static u8 bw2regs_76hz[] __initdata = { 0x14, 0xb7, 0x15, 0x27, 0x16, 0x03, 0x17, 0x0f, 0x18, 0xae, 0x19, 0x03, 0x1a, 0xae, 0x1b, 0x2a, 0x1c, 0x01, 0x1d, 0x09, 0x1e, 0xff, 0x1f, 0x01, 0x10, 0x24, 0 }; static u8 bw2regs_66hz[] __initdata = { 0x14, 0xbb, 0x15, 0x2b, 0x16, 0x04, 0x17, 0x14, 0x18, 0xae, 0x19, 0x03, 0x1a, 0xa8, 0x1b, 0x24, 0x1c, 0x01, 0x1d, 0x05, 0x1e, 0xff, 0x1f, 0x01, 0x10, 0x20, 0 }; static char idstring[60] __initdata = { 0 }; char __init *bwtwofb_init(struct fb_info_sbusfb *fb) { struct fb_fix_screeninfo *fix = &fb->fix; struct display *disp = &fb->disp; struct fbtype *type = &fb->type; #ifdef CONFIG_SUN4 unsigned long phys = sun4_bwtwo_physaddr; struct resource res; #else unsigned long phys = fb->sbdp->reg_addrs[0].phys_addr; #endif struct resource *resp; unsigned int vaddr; #ifndef FBCON_HAS_MFB return NULL; #endif #ifdef CONFIG_SUN4 res.start = phys; res.end = res.start + BWTWO_REGISTER_OFFSET + sizeof(struct bw2_regs) - 1; res.flags = IORESOURCE_IO | (fb->iospace & 0xff); resp = &res; #else resp = &fb->sbdp->resource[0]; #endif if (!fb->s.bw2.regs) { fb->s.bw2.regs = (struct bw2_regs *) sbus_ioremap(resp, BWTWO_REGISTER_OFFSET, sizeof(struct bw2_regs), "bw2 regs"); if ((!ARCH_SUN4) && (!prom_getbool(fb->prom_node, "width"))) { /* Ugh, broken PROM didn't initialize us. * Let's deal with this ourselves. */ u8 status, mon; u8 *p; int sizechange = 0; status = sbus_readb(&fb->s.bw2.regs->status); mon = status & BWTWO_SR_RES_MASK; switch (status & BWTWO_SR_ID_MASK) { case BWTWO_SR_ID_MONO_ECL: if (mon == BWTWO_SR_1600_1280) { p = bw2regs_1600; fb->type.fb_width = 1600; fb->type.fb_height = 1280; sizechange = 1; } else p = bw2regs_ecl; break; case BWTWO_SR_ID_MONO: p = bw2regs_analog; break; case BWTWO_SR_ID_MSYNC: if (mon == BWTWO_SR_1152_900_76_A || mon == BWTWO_SR_1152_900_76_B) p = bw2regs_76hz; else p = bw2regs_66hz; break; case BWTWO_SR_ID_NOCONN: return NULL; default: #ifndef CONFIG_FB_SUN3 prom_printf("bw2: can't handle SR %02x\n", status); prom_halt(); #endif return NULL; /* fool gcc. */ } for ( ; *p; p += 2) { u8 *regp = &((u8 *)fb->s.bw2.regs)[p[0]]; sbus_writeb(p[1], regp); } } } strcpy(fb->info.modename, "BWtwo"); strcpy(fix->id, "BWtwo"); fix->line_length = fb->var.xres_virtual >> 3; fix->accel = FB_ACCEL_SUN_BWTWO; disp->scrollmode = SCROLL_YREDRAW; disp->inverse = 1; if (!disp->screen_base) { disp->screen_base = (char *) sbus_ioremap(resp, 0, type->fb_size, "bw2 ram"); } disp->screen_base += fix->line_length * fb->y_margin + (fb->x_margin >> 3); fb->dispsw = fbcon_mfb; fix->visual = FB_VISUAL_MONO01; #ifndef CONFIG_SUN4 fb->blank = bw2_blank; fb->unblank = bw2_unblank; prom_getproperty(fb->sbdp->prom_node, "address", (char *)&vaddr, sizeof(vaddr)); fb->physbase = __get_phys((unsigned long)vaddr); #endif fb->margins = bw2_margins; fb->mmap_map = bw2_mmap_map; #ifdef __sparc_v9__ sprintf(idstring, "bwtwo at %016lx", phys); #else sprintf(idstring, "bwtwo at %x.%08lx", fb->iospace, phys); #endif return idstring; }
QiuLihua83/linux-2.4.0
drivers/video/bwtwofb.c
C
gpl-2.0
6,975
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Health * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Exception */ #require_once 'Zend/Exception.php'; /** * @see Zend_Gdata_Query */ #require_once('Zend/Gdata/Query.php'); /** * Assists in constructing queries for Google Health * * @link http://code.google.com/apis/health * * @category Zend * @package Zend_Gdata * @subpackage Health * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Health_Query extends Zend_Gdata_Query { /** * URI of a user's profile feed. */ const HEALTH_PROFILE_FEED_URI = 'https://www.google.com/health/feeds/profile/default'; /** * URI of register (notices) feed. */ const HEALTH_REGISTER_FEED_URI = 'https://www.google.com/health/feeds/register/default'; /** * Namespace for an item category */ const ITEM_CATEGORY_NS = 'http://schemas.google.com/health/item'; /** * Create Gdata_Query object */ public function __construct($url = null) { throw new Zend_Exception( 'Google Health API has been discontinued by Google and was removed' . ' from Zend Framework in 1.12.0. For more information see: ' . 'http://googleblog.blogspot.ca/2011/06/update-on-google-health-and-google.html' ); } }
FPLD/project0
vendor/magento/zendframework1/library/Zend/Gdata/Health/Query.php
PHP
gpl-2.0
2,102
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SCUMM_IMUSE_INSTRUMENT_H #define SCUMM_IMUSE_INSTRUMENT_H #include "common/scummsys.h" class MidiChannel; namespace Scumm { class Serializer; class Instrument; class InstrumentInternal { public: virtual ~InstrumentInternal() {} virtual void saveOrLoad(Serializer *s) = 0; virtual void send(MidiChannel *mc) = 0; virtual void copy_to(Instrument *dest) = 0; virtual bool is_valid() = 0; }; class Instrument { private: byte _type; InstrumentInternal *_instrument; public: enum { itNone = 0, itProgram = 1, itAdLib = 2, itRoland = 3, itPcSpk = 4, itMacSfx = 5 }; Instrument() : _type(0), _instrument(0) { } ~Instrument() { delete _instrument; } static void nativeMT32(bool native); static const byte _gmRhythmMap[35]; void clear(); void copy_to(Instrument *dest) { if (_instrument) _instrument->copy_to(dest); else dest->clear(); } void program(byte program, bool mt32); void adlib(const byte *instrument); void roland(const byte *instrument); void pcspk(const byte *instrument); void macSfx(byte program); byte getType() { return _type; } bool isValid() { return (_instrument ? _instrument->is_valid() : false); } void saveOrLoad(Serializer *s); void send(MidiChannel *mc) { if (_instrument) _instrument->send(mc); } }; } // End of namespace Scumm #endif
MaddTheSane/scummvm
engines/scumm/imuse/instrument.h
C
gpl-2.0
2,273
#! /usr/bin/env bash set -e cd $(dirname $0)/.. doxygen chmod -R g+rx doc/
OursDesCavernes/springlobby
tools/update-docs.sh
Shell
gpl-2.0
78
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * 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/>. */ /* ScriptData SDName: boss_timmy_the_cruel SD%Complete: 100 SDComment: SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" enum Says { SAY_SPAWN = 0 }; enum Spells { SPELL_RAVENOUSCLAW = 17470 }; class boss_timmy_the_cruel : public CreatureScript { public: boss_timmy_the_cruel() : CreatureScript("boss_timmy_the_cruel") { } CreatureAI* GetAI(Creature* creature) const { return new boss_timmy_the_cruelAI (creature); } struct boss_timmy_the_cruelAI : public ScriptedAI { boss_timmy_the_cruelAI(Creature* creature) : ScriptedAI(creature) {} uint32 RavenousClaw_Timer; bool HasYelled; void Reset() { RavenousClaw_Timer = 10000; HasYelled = false; } void EnterCombat(Unit* /*who*/) { if (!HasYelled) { Talk(SAY_SPAWN); HasYelled = true; } } void UpdateAI(uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //RavenousClaw if (RavenousClaw_Timer <= diff) { //Cast DoCast(me->GetVictim(), SPELL_RAVENOUSCLAW); //15 seconds until we should cast this again RavenousClaw_Timer = 15000; } else RavenousClaw_Timer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_timmy_the_cruel() { new boss_timmy_the_cruel(); }
TrinityDeveloper/TrinityCore
src/server/scripts/EasternKingdoms/Stratholme/boss_timmy_the_cruel.cpp
C++
gpl-2.0
2,422
/*****************************************************************************/ // Copyright 2006-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in // accordance with the terms of the Adobe license agreement accompanying it. /*****************************************************************************/ /* $Id: //mondo/dng_sdk_1_3/dng_sdk/source/dng_mosaic_info.h#1 $ */ /* $DateTime: 2009/06/22 05:04:49 $ */ /* $Change: 578634 $ */ /* $Author: tknoll $ */ /** \file * Support for descriptive information about color filter array patterns. */ /*****************************************************************************/ #ifndef __dng_mosaic_info__ #define __dng_mosaic_info__ /*****************************************************************************/ #include "dng_classes.h" #include "dng_rect.h" #include "dng_sdk_limits.h" #include "dng_types.h" /*****************************************************************************/ /// \brief Support for describing color filter array patterns and manipulating mosaic sample data. /// /// See CFAPattern tag in \ref spec_tiff_ep "TIFF/EP specification" and CFAPlaneColor, CFALayout, and BayerGreenSplit /// tags in the \ref spec_dng "DNG 1.1.0 specification". class dng_mosaic_info { public: /// Size of fCFAPattern. dng_point fCFAPatternSize; /// CFA pattern from CFAPattern tag in the \ref spec_tiff_ep "TIFF/EP specification." uint8 fCFAPattern [kMaxCFAPattern] [kMaxCFAPattern]; /// Number of color planes in DNG input. uint32 fColorPlanes; uint8 fCFAPlaneColor [kMaxColorPlanes]; /// Value of CFALayout tag in the \ref spec_dng "DNG 1.3 specification." /// CFALayout describes the spatial layout of the CFA. The currently defined values are: /// - 1 = Rectangular (or square) layout. /// - 2 = Staggered layout A: even columns are offset down by 1/2 row. /// - 3 = Staggered layout B: even columns are offset up by 1/2 row. /// - 4 = Staggered layout C: even rows are offset right by 1/2 column. /// - 5 = Staggered layout D: even rows are offset left by 1/2 column. /// - 6 = Staggered layout E: even rows are offset up by 1/2 row, even columns are offset left by 1/2 column. /// - 7 = Staggered layout F: even rows are offset up by 1/2 row, even columns are offset right by 1/2 column. /// - 8 = Staggered layout G: even rows are offset down by 1/2 row, even columns are offset left by 1/2 column. /// - 9 = Staggered layout H: even rows are offset down by 1/2 row, even columns are offset right by 1/2 column. uint32 fCFALayout; /// Value of BayerGreeSplit tag in DNG file. /// BayerGreenSplit only applies to CFA images using a Bayer pattern filter array. This tag /// specifies, in arbitrary units, how closely the values of the green pixels in the blue/green rows /// track the values of the green pixels in the red/green rows. /// /// A value of zero means the two kinds of green pixels track closely, while a non-zero value /// means they sometimes diverge. The useful range for this tag is from 0 (no divergence) to about /// 5000 (large divergence). uint32 fBayerGreenSplit; protected: dng_point fSrcSize; dng_point fCroppedSize; real64 fAspectRatio; public: dng_mosaic_info (); virtual ~dng_mosaic_info (); virtual void Parse (dng_host &host, dng_stream &stream, dng_info &info); virtual void PostParse (dng_host &host, dng_negative &negative); /// Returns whether the RAW data in this DNG file from a color filter array (mosaiced) source. /// \retval true if this DNG file is from a color filter array (mosiaced) source. bool IsColorFilterArray () const { return fCFAPatternSize != dng_point (0, 0); } /// Enable generating four-plane output from three-plane Bayer input. /// Extra plane is a second version of the green channel. First green is produced /// using green mosaic samples from one set of rows/columns (even/odd) and the second /// green channel is produced using the other set of rows/columns. One can compare the /// two versions to judge whether BayerGreenSplit needs to be set for a given input source. virtual bool SetFourColorBayer (); /// Returns scaling factor relative to input size needed to capture output data. /// Staggered (or rotated) sensing arrays are produced to a larger output than the number of input samples. /// This method indicates how much larger. /// \retval a point with integer scaling factors for the horizotal and vertical dimensions. virtual dng_point FullScale () const; /// Returns integer factors by which mosaic data must be downsampled to produce an image which is as close /// to prefSize as possible in longer dimension, but no smaller than minSize. /// \param minSize Number of pixels as minium for longer dimension of downsampled image. /// \param prefSize Number of pixels as target for longer dimension of downsampled image. /// \param cropFactor Faction of the image to be used after cropping. /// \retval Point containing integer factors by which image must be downsampled. virtual dng_point DownScale (uint32 minSize, uint32 prefSize, real64 cropFactor) const; /// Return size of demosaiced image for passed in downscaling factor. /// \param downScale Integer downsampling factor obtained from DownScale method. /// \retval Size of resulting demosaiced image. virtual dng_point DstSize (const dng_point &downScale) const; /// Demosaic interpolation of a single plane for non-downsampled case. /// \param host dng_host to use for buffer allocation requests, user cancellation testing, and progress updates. /// \param negative DNG negative of mosaiced data. /// \param srcImage Source image for mosaiced data. /// \param dstImage Destination image for resulting interpolated data. /// \param srcPlane Which plane to interpolate. virtual void InterpolateGeneric (dng_host &host, dng_negative &negative, const dng_image &srcImage, dng_image &dstImage, uint32 srcPlane = 0) const; /// Demosaic interpolation of a single plane for downsampled case. /// \param host dng_host to use for buffer allocation requests, user cancellation testing, and progress updates. /// \param negative DNG negative of mosaiced data. /// \param srcImage Source image for mosaiced data. /// \param dstImage Destination image for resulting interpolated data. /// \param downScale Amount (in horizontal and vertical) by which to subsample image. /// \param srcPlane Which plane to interpolate. virtual void InterpolateFast (dng_host &host, dng_negative &negative, const dng_image &srcImage, dng_image &dstImage, const dng_point &downScale, uint32 srcPlane = 0) const; /// Demosaic interpolation of a single plane. Chooses between generic and fast interpolators based on parameters. /// \param host dng_host to use for buffer allocation requests, user cancellation testing, and progress updates. /// \param negative DNG negative of mosaiced data. /// \param srcImage Source image for mosaiced data. /// \param dstImage Destination image for resulting interpolated data. /// \param downScale Amount (in horizontal and vertical) by which to subsample image. /// \param srcPlane Which plane to interpolate. virtual void Interpolate (dng_host &host, dng_negative &negative, const dng_image &srcImage, dng_image &dstImage, const dng_point &downScale, uint32 srcPlane = 0) const; protected: virtual bool IsSafeDownScale (const dng_point &downScale) const; uint32 SizeForDownScale (const dng_point &downScale) const; virtual bool ValidSizeDownScale (const dng_point &downScale, uint32 minSize) const; }; /*****************************************************************************/ #endif /*****************************************************************************/
centic9/digikam-ppa
extra/kipi-plugins/dngconverter/dngwriter/extra/dng_sdk/dng_mosaic_info.h
C
gpl-2.0
8,235
/* * linux/arch/arm/mach-at91/board-csb337.c * * Copyright (C) 2005 SAN People * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/types.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/spi/spi.h> #include <linux/mtd/physmap.h> #include <asm/hardware.h> #include <asm/setup.h> #include <asm/mach-types.h> #include <asm/irq.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <asm/mach/irq.h> #include <asm/arch/board.h> #include <asm/arch/gpio.h> #include "generic.h" /* * Serial port configuration. * 0 .. 3 = USART0 .. USART3 * 4 = DBGU */ static struct at91_uart_config __initdata csb337_uart_config = { .console_tty = 0, /* ttyS0 */ .nr_tty = 2, .tty_map = { 4, 1, -1, -1, -1 } /* ttyS0, ..., ttyS4 */ }; static void __init csb337_map_io(void) { /* Initialize processor: 3.6864 MHz crystal */ at91rm9200_initialize(3686400, AT91RM9200_BGA); /* Setup the LEDs */ at91_init_leds(AT91_PIN_PB0, AT91_PIN_PB1); /* Setup the serial ports and console */ at91_init_serial(&csb337_uart_config); } static void __init csb337_init_irq(void) { at91rm9200_init_interrupts(NULL); } static struct at91_eth_data __initdata csb337_eth_data = { .phy_irq_pin = AT91_PIN_PC2, .is_rmii = 0, }; static struct at91_usbh_data __initdata csb337_usbh_data = { .ports = 2, }; static struct at91_udc_data __initdata csb337_udc_data = { // this has no VBUS sensing pin .pullup_pin = AT91_PIN_PA24, }; static struct i2c_board_info __initdata csb337_i2c_devices[] = { { I2C_BOARD_INFO("rtc-ds1307", 0x68), .type = "ds1307", }, }; static struct at91_cf_data __initdata csb337_cf_data = { /* * connector P4 on the CSB 337 mates to * connector P8 on the CSB 300CF */ /* CSB337 specific */ .det_pin = AT91_PIN_PC3, /* CSB300CF specific */ .irq_pin = AT91_PIN_PA19, .vcc_pin = AT91_PIN_PD0, .rst_pin = AT91_PIN_PD2, }; static struct at91_mmc_data __initdata csb337_mmc_data = { .det_pin = AT91_PIN_PD5, .slot_b = 0, .wire4 = 1, .wp_pin = AT91_PIN_PD6, }; static struct spi_board_info csb337_spi_devices[] = { { /* CAN controller */ .modalias = "sak82c900", .chip_select = 0, .max_speed_hz = 6 * 1000 * 1000, }, }; #define CSB_FLASH_BASE AT91_CHIPSELECT_0 #define CSB_FLASH_SIZE 0x800000 static struct mtd_partition csb_flash_partitions[] = { { .name = "uMON flash", .offset = 0, .size = MTDPART_SIZ_FULL, .mask_flags = MTD_WRITEABLE, /* read only */ } }; static struct physmap_flash_data csb_flash_data = { .width = 2, .parts = csb_flash_partitions, .nr_parts = ARRAY_SIZE(csb_flash_partitions), }; static struct resource csb_flash_resources[] = { { .start = CSB_FLASH_BASE, .end = CSB_FLASH_BASE + CSB_FLASH_SIZE - 1, .flags = IORESOURCE_MEM, } }; static struct platform_device csb_flash = { .name = "physmap-flash", .id = 0, .dev = { .platform_data = &csb_flash_data, }, .resource = csb_flash_resources, .num_resources = ARRAY_SIZE(csb_flash_resources), }; static void __init csb337_board_init(void) { /* Serial */ at91_add_device_serial(); /* Ethernet */ at91_add_device_eth(&csb337_eth_data); /* USB Host */ at91_add_device_usbh(&csb337_usbh_data); /* USB Device */ at91_add_device_udc(&csb337_udc_data); /* I2C */ at91_add_device_i2c(); i2c_register_board_info(0, csb337_i2c_devices, ARRAY_SIZE(csb337_i2c_devices)); /* Compact Flash */ at91_set_gpio_input(AT91_PIN_PB22, 1); /* IOIS16 */ at91_add_device_cf(&csb337_cf_data); /* SPI */ at91_add_device_spi(csb337_spi_devices, ARRAY_SIZE(csb337_spi_devices)); /* MMC */ at91_add_device_mmc(0, &csb337_mmc_data); /* NOR flash */ platform_device_register(&csb_flash); } MACHINE_START(CSB337, "Cogent CSB337") /* Maintainer: Bill Gatliff */ .phys_io = AT91_BASE_SYS, .io_pg_offst = (AT91_VA_BASE_SYS >> 18) & 0xfffc, .boot_params = AT91_SDRAM_BASE + 0x100, .timer = &at91rm9200_timer, .map_io = csb337_map_io, .init_irq = csb337_init_irq, .init_machine = csb337_board_init, MACHINE_END
kidmaple/CoolWall
linux-2.6.x/arch/arm/mach-at91/board-csb337.c
C
gpl-2.0
4,777
/* * Copyright (c) 2011 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #define CONFIG_SYS_NS16550_COM1 NV_ADDRESS_MAP_APB_UARTB_BASE
chpec/uboot-ac100
include/configs/chromeos/tegra2/wario/parts/uart.h
C
gpl-2.0
250
/* Assembler interface for targets using CGEN. -*- C -*- CGEN: Cpu tools GENerator THIS FILE IS MACHINE GENERATED WITH CGEN. - the resultant file is machine generated, cgen-asm.in isn't Copyright (C) 1996-2017 Free Software Foundation, Inc. This file is part of libopcodes. This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. It 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. */ /* ??? Eventually more and more of this stuff can go to cpu-independent files. Keep that in mind. */ #include "sysdep.h" #include <stdio.h> #include "ansidecl.h" #include "bfd.h" #include "symcat.h" #include "ip2k-desc.h" #include "ip2k-opc.h" #include "opintl.h" #include "xregex.h" #include "libiberty.h" #include "safe-ctype.h" #undef min #define min(a,b) ((a) < (b) ? (a) : (b)) #undef max #define max(a,b) ((a) > (b) ? (a) : (b)) static const char * parse_insn_normal (CGEN_CPU_DESC, const CGEN_INSN *, const char **, CGEN_FIELDS *); /* -- assembler routines inserted here. */ /* -- asm.c */ static const char * parse_fr (CGEN_CPU_DESC cd, const char **strp, int opindex, unsigned long *valuep) { const char *errmsg; const char *old_strp; char *afteroffset; enum cgen_parse_operand_result result_type; bfd_vma value; extern CGEN_KEYWORD ip2k_cgen_opval_register_names; bfd_vma tempvalue; old_strp = *strp; afteroffset = NULL; /* Check here to see if you're about to try parsing a w as the first arg and return an error if you are. */ if ((strncmp (*strp, "w", 1) == 0) || (strncmp (*strp, "W", 1) == 0)) { (*strp)++; if ((strncmp (*strp, ",", 1) == 0) || ISSPACE (**strp)) { /* We've been passed a w. Return with an error message so that cgen will try the next parsing option. */ errmsg = _("W keyword invalid in FR operand slot."); return errmsg; } *strp = old_strp; } /* Attempt parse as register keyword. */ errmsg = cgen_parse_keyword (cd, strp, & ip2k_cgen_opval_register_names, (long *) valuep); if (*strp != NULL && errmsg == NULL) return errmsg; /* Attempt to parse for "(IP)". */ afteroffset = strstr (*strp, "(IP)"); if (afteroffset == NULL) /* Make sure it's not in lower case. */ afteroffset = strstr (*strp, "(ip)"); if (afteroffset != NULL) { if (afteroffset != *strp) { /* Invalid offset present. */ errmsg = _("offset(IP) is not a valid form"); return errmsg; } else { *strp += 4; *valuep = 0; errmsg = NULL; return errmsg; } } /* Attempt to parse for DP. ex: mov w, offset(DP) mov offset(DP),w */ /* Try parsing it as an address and see what comes back. */ afteroffset = strstr (*strp, "(DP)"); if (afteroffset == NULL) /* Maybe it's in lower case. */ afteroffset = strstr (*strp, "(dp)"); if (afteroffset != NULL) { if (afteroffset == *strp) { /* No offset present. Use 0 by default. */ tempvalue = 0; errmsg = NULL; } else errmsg = cgen_parse_address (cd, strp, opindex, BFD_RELOC_IP2K_FR_OFFSET, & result_type, & tempvalue); if (errmsg == NULL) { if (tempvalue <= 127) { /* Value is ok. Fix up the first 2 bits and return. */ *valuep = 0x0100 | tempvalue; *strp += 4; /* Skip over the (DP) in *strp. */ return errmsg; } else { /* Found something there in front of (DP) but it's out of range. */ errmsg = _("(DP) offset out of range."); return errmsg; } } } /* Attempt to parse for SP. ex: mov w, offset(SP) mov offset(SP), w. */ afteroffset = strstr (*strp, "(SP)"); if (afteroffset == NULL) /* Maybe it's in lower case. */ afteroffset = strstr (*strp, "(sp)"); if (afteroffset != NULL) { if (afteroffset == *strp) { /* No offset present. Use 0 by default. */ tempvalue = 0; errmsg = NULL; } else errmsg = cgen_parse_address (cd, strp, opindex, BFD_RELOC_IP2K_FR_OFFSET, & result_type, & tempvalue); if (errmsg == NULL) { if (tempvalue <= 127) { /* Value is ok. Fix up the first 2 bits and return. */ *valuep = 0x0180 | tempvalue; *strp += 4; /* Skip over the (SP) in *strp. */ return errmsg; } else { /* Found something there in front of (SP) but it's out of range. */ errmsg = _("(SP) offset out of range."); return errmsg; } } } /* Attempt to parse as an address. */ *strp = old_strp; errmsg = cgen_parse_address (cd, strp, opindex, BFD_RELOC_IP2K_FR9, & result_type, & value); if (errmsg == NULL) { *valuep = value; /* If a parenthesis is found, warn about invalid form. */ if (**strp == '(') errmsg = _("illegal use of parentheses"); /* If a numeric value is specified, ensure that it is between 1 and 255. */ else if (result_type == CGEN_PARSE_OPERAND_RESULT_NUMBER) { if (value < 0x1 || value > 0xff) errmsg = _("operand out of range (not between 1 and 255)"); } } return errmsg; } static const char * parse_addr16 (CGEN_CPU_DESC cd, const char **strp, int opindex, unsigned long *valuep) { const char *errmsg; enum cgen_parse_operand_result result_type; bfd_reloc_code_real_type code = BFD_RELOC_NONE; bfd_vma value; if (opindex == (CGEN_OPERAND_TYPE) IP2K_OPERAND_ADDR16H) code = BFD_RELOC_IP2K_HI8DATA; else if (opindex == (CGEN_OPERAND_TYPE) IP2K_OPERAND_ADDR16L) code = BFD_RELOC_IP2K_LO8DATA; else { /* Something is very wrong. opindex has to be one of the above. */ errmsg = _("parse_addr16: invalid opindex."); return errmsg; } errmsg = cgen_parse_address (cd, strp, opindex, code, & result_type, & value); if (errmsg == NULL) { /* We either have a relocation or a number now. */ if (result_type == CGEN_PARSE_OPERAND_RESULT_NUMBER) { /* We got a number back. */ if (code == BFD_RELOC_IP2K_HI8DATA) value >>= 8; else /* code = BFD_RELOC_IP2K_LOW8DATA. */ value &= 0x00FF; } *valuep = value; } return errmsg; } static const char * parse_addr16_cjp (CGEN_CPU_DESC cd, const char **strp, int opindex, unsigned long *valuep) { const char *errmsg; enum cgen_parse_operand_result result_type; bfd_reloc_code_real_type code = BFD_RELOC_NONE; bfd_vma value; if (opindex == (CGEN_OPERAND_TYPE) IP2K_OPERAND_ADDR16CJP) code = BFD_RELOC_IP2K_ADDR16CJP; else if (opindex == (CGEN_OPERAND_TYPE) IP2K_OPERAND_ADDR16P) code = BFD_RELOC_IP2K_PAGE3; errmsg = cgen_parse_address (cd, strp, opindex, code, & result_type, & value); if (errmsg == NULL) { if (result_type == CGEN_PARSE_OPERAND_RESULT_NUMBER) { if ((value & 0x1) == 0) /* If the address is even .... */ { if (opindex == (CGEN_OPERAND_TYPE) IP2K_OPERAND_ADDR16CJP) *valuep = (value >> 1) & 0x1FFF; /* Should mask be 1FFF? */ else if (opindex == (CGEN_OPERAND_TYPE) IP2K_OPERAND_ADDR16P) *valuep = (value >> 14) & 0x7; } else errmsg = _("Byte address required. - must be even."); } else if (result_type == CGEN_PARSE_OPERAND_RESULT_QUEUED) { /* This will happen for things like (s2-s1) where s2 and s1 are labels. */ *valuep = value; } else errmsg = _("cgen_parse_address returned a symbol. Literal required."); } return errmsg; } static const char * parse_lit8 (CGEN_CPU_DESC cd, const char **strp, int opindex, long *valuep) { const char *errmsg; enum cgen_parse_operand_result result_type; bfd_reloc_code_real_type code = BFD_RELOC_NONE; bfd_vma value; /* Parse %OP relocating operators. */ if (strncmp (*strp, "%bank", 5) == 0) { *strp += 5; code = BFD_RELOC_IP2K_BANK; } else if (strncmp (*strp, "%lo8data", 8) == 0) { *strp += 8; code = BFD_RELOC_IP2K_LO8DATA; } else if (strncmp (*strp, "%hi8data", 8) == 0) { *strp += 8; code = BFD_RELOC_IP2K_HI8DATA; } else if (strncmp (*strp, "%ex8data", 8) == 0) { *strp += 8; code = BFD_RELOC_IP2K_EX8DATA; } else if (strncmp (*strp, "%lo8insn", 8) == 0) { *strp += 8; code = BFD_RELOC_IP2K_LO8INSN; } else if (strncmp (*strp, "%hi8insn", 8) == 0) { *strp += 8; code = BFD_RELOC_IP2K_HI8INSN; } /* Parse %op operand. */ if (code != BFD_RELOC_NONE) { errmsg = cgen_parse_address (cd, strp, opindex, code, & result_type, & value); if ((errmsg == NULL) && (result_type != CGEN_PARSE_OPERAND_RESULT_QUEUED)) errmsg = _("percent-operator operand is not a symbol"); *valuep = value; } /* Parse as a number. */ else { errmsg = cgen_parse_signed_integer (cd, strp, opindex, valuep); /* Truncate to eight bits to accept both signed and unsigned input. */ if (errmsg == NULL) *valuep &= 0xFF; } return errmsg; } static const char * parse_bit3 (CGEN_CPU_DESC cd, const char **strp, int opindex, unsigned long *valuep) { const char *errmsg; char mode = 0; long count = 0; unsigned long value; if (strncmp (*strp, "%bit", 4) == 0) { *strp += 4; mode = 1; } else if (strncmp (*strp, "%msbbit", 7) == 0) { *strp += 7; mode = 1; } else if (strncmp (*strp, "%lsbbit", 7) == 0) { *strp += 7; mode = 2; } errmsg = cgen_parse_unsigned_integer (cd, strp, opindex, valuep); if (errmsg) return errmsg; if (mode) { value = * valuep; if (value == 0) { errmsg = _("Attempt to find bit index of 0"); return errmsg; } if (mode == 1) { count = 31; while ((value & 0x80000000) == 0) { count--; value <<= 1; } } else if (mode == 2) { count = 0; while ((value & 0x00000001) == 0) { count++; value >>= 1; } } *valuep = count; } return errmsg; } /* -- dis.c */ const char * ip2k_cgen_parse_operand (CGEN_CPU_DESC, int, const char **, CGEN_FIELDS *); /* Main entry point for operand parsing. This function is basically just a big switch statement. Earlier versions used tables to look up the function to use, but - if the table contains both assembler and disassembler functions then the disassembler contains much of the assembler and vice-versa, - there's a lot of inlining possibilities as things grow, - using a switch statement avoids the function call overhead. This function could be moved into `parse_insn_normal', but keeping it separate makes clear the interface between `parse_insn_normal' and each of the handlers. */ const char * ip2k_cgen_parse_operand (CGEN_CPU_DESC cd, int opindex, const char ** strp, CGEN_FIELDS * fields) { const char * errmsg = NULL; /* Used by scalar operands that still need to be parsed. */ long junk ATTRIBUTE_UNUSED; switch (opindex) { case IP2K_OPERAND_ADDR16CJP : errmsg = parse_addr16_cjp (cd, strp, IP2K_OPERAND_ADDR16CJP, (unsigned long *) (& fields->f_addr16cjp)); break; case IP2K_OPERAND_ADDR16H : errmsg = parse_addr16 (cd, strp, IP2K_OPERAND_ADDR16H, (unsigned long *) (& fields->f_imm8)); break; case IP2K_OPERAND_ADDR16L : errmsg = parse_addr16 (cd, strp, IP2K_OPERAND_ADDR16L, (unsigned long *) (& fields->f_imm8)); break; case IP2K_OPERAND_ADDR16P : errmsg = parse_addr16_cjp (cd, strp, IP2K_OPERAND_ADDR16P, (unsigned long *) (& fields->f_page3)); break; case IP2K_OPERAND_BITNO : errmsg = parse_bit3 (cd, strp, IP2K_OPERAND_BITNO, (unsigned long *) (& fields->f_bitno)); break; case IP2K_OPERAND_CBIT : errmsg = cgen_parse_unsigned_integer (cd, strp, IP2K_OPERAND_CBIT, (unsigned long *) (& junk)); break; case IP2K_OPERAND_DCBIT : errmsg = cgen_parse_unsigned_integer (cd, strp, IP2K_OPERAND_DCBIT, (unsigned long *) (& junk)); break; case IP2K_OPERAND_FR : errmsg = parse_fr (cd, strp, IP2K_OPERAND_FR, (unsigned long *) (& fields->f_reg)); break; case IP2K_OPERAND_LIT8 : errmsg = parse_lit8 (cd, strp, IP2K_OPERAND_LIT8, (long *) (& fields->f_imm8)); break; case IP2K_OPERAND_PABITS : errmsg = cgen_parse_unsigned_integer (cd, strp, IP2K_OPERAND_PABITS, (unsigned long *) (& junk)); break; case IP2K_OPERAND_RETI3 : errmsg = cgen_parse_unsigned_integer (cd, strp, IP2K_OPERAND_RETI3, (unsigned long *) (& fields->f_reti3)); break; case IP2K_OPERAND_ZBIT : errmsg = cgen_parse_unsigned_integer (cd, strp, IP2K_OPERAND_ZBIT, (unsigned long *) (& junk)); break; default : /* xgettext:c-format */ fprintf (stderr, _("Unrecognized field %d while parsing.\n"), opindex); abort (); } return errmsg; } cgen_parse_fn * const ip2k_cgen_parse_handlers[] = { parse_insn_normal, }; void ip2k_cgen_init_asm (CGEN_CPU_DESC cd) { ip2k_cgen_init_opcode_table (cd); ip2k_cgen_init_ibld_table (cd); cd->parse_handlers = & ip2k_cgen_parse_handlers[0]; cd->parse_operand = ip2k_cgen_parse_operand; #ifdef CGEN_ASM_INIT_HOOK CGEN_ASM_INIT_HOOK #endif } /* Regex construction routine. This translates an opcode syntax string into a regex string, by replacing any non-character syntax element (such as an opcode) with the pattern '.*' It then compiles the regex and stores it in the opcode, for later use by ip2k_cgen_assemble_insn Returns NULL for success, an error message for failure. */ char * ip2k_cgen_build_insn_regex (CGEN_INSN *insn) { CGEN_OPCODE *opc = (CGEN_OPCODE *) CGEN_INSN_OPCODE (insn); const char *mnem = CGEN_INSN_MNEMONIC (insn); char rxbuf[CGEN_MAX_RX_ELEMENTS]; char *rx = rxbuf; const CGEN_SYNTAX_CHAR_TYPE *syn; int reg_err; syn = CGEN_SYNTAX_STRING (CGEN_OPCODE_SYNTAX (opc)); /* Mnemonics come first in the syntax string. */ if (! CGEN_SYNTAX_MNEMONIC_P (* syn)) return _("missing mnemonic in syntax string"); ++syn; /* Generate a case sensitive regular expression that emulates case insensitive matching in the "C" locale. We cannot generate a case insensitive regular expression because in Turkish locales, 'i' and 'I' are not equal modulo case conversion. */ /* Copy the literal mnemonic out of the insn. */ for (; *mnem; mnem++) { char c = *mnem; if (ISALPHA (c)) { *rx++ = '['; *rx++ = TOLOWER (c); *rx++ = TOUPPER (c); *rx++ = ']'; } else *rx++ = c; } /* Copy any remaining literals from the syntax string into the rx. */ for(; * syn != 0 && rx <= rxbuf + (CGEN_MAX_RX_ELEMENTS - 7 - 4); ++syn) { if (CGEN_SYNTAX_CHAR_P (* syn)) { char c = CGEN_SYNTAX_CHAR (* syn); switch (c) { /* Escape any regex metacharacters in the syntax. */ case '.': case '[': case '\\': case '*': case '^': case '$': #ifdef CGEN_ESCAPE_EXTENDED_REGEX case '?': case '{': case '}': case '(': case ')': case '*': case '|': case '+': case ']': #endif *rx++ = '\\'; *rx++ = c; break; default: if (ISALPHA (c)) { *rx++ = '['; *rx++ = TOLOWER (c); *rx++ = TOUPPER (c); *rx++ = ']'; } else *rx++ = c; break; } } else { /* Replace non-syntax fields with globs. */ *rx++ = '.'; *rx++ = '*'; } } /* Trailing whitespace ok. */ * rx++ = '['; * rx++ = ' '; * rx++ = '\t'; * rx++ = ']'; * rx++ = '*'; /* But anchor it after that. */ * rx++ = '$'; * rx = '\0'; CGEN_INSN_RX (insn) = xmalloc (sizeof (regex_t)); reg_err = regcomp ((regex_t *) CGEN_INSN_RX (insn), rxbuf, REG_NOSUB); if (reg_err == 0) return NULL; else { static char msg[80]; regerror (reg_err, (regex_t *) CGEN_INSN_RX (insn), msg, 80); regfree ((regex_t *) CGEN_INSN_RX (insn)); free (CGEN_INSN_RX (insn)); (CGEN_INSN_RX (insn)) = NULL; return msg; } } /* Default insn parser. The syntax string is scanned and operands are parsed and stored in FIELDS. Relocs are queued as we go via other callbacks. ??? Note that this is currently an all-or-nothing parser. If we fail to parse the instruction, we return 0 and the caller will start over from the beginning. Backtracking will be necessary in parsing subexpressions, but that can be handled there. Not handling backtracking here may get expensive in the case of the m68k. Deal with later. Returns NULL for success, an error message for failure. */ static const char * parse_insn_normal (CGEN_CPU_DESC cd, const CGEN_INSN *insn, const char **strp, CGEN_FIELDS *fields) { /* ??? Runtime added insns not handled yet. */ const CGEN_SYNTAX *syntax = CGEN_INSN_SYNTAX (insn); const char *str = *strp; const char *errmsg; const char *p; const CGEN_SYNTAX_CHAR_TYPE * syn; #ifdef CGEN_MNEMONIC_OPERANDS /* FIXME: wip */ int past_opcode_p; #endif /* For now we assume the mnemonic is first (there are no leading operands). We can parse it without needing to set up operand parsing. GAS's input scrubber will ensure mnemonics are lowercase, but we may not be called from GAS. */ p = CGEN_INSN_MNEMONIC (insn); while (*p && TOLOWER (*p) == TOLOWER (*str)) ++p, ++str; if (* p) return _("unrecognized instruction"); #ifndef CGEN_MNEMONIC_OPERANDS if (* str && ! ISSPACE (* str)) return _("unrecognized instruction"); #endif CGEN_INIT_PARSE (cd); cgen_init_parse_operand (cd); #ifdef CGEN_MNEMONIC_OPERANDS past_opcode_p = 0; #endif /* We don't check for (*str != '\0') here because we want to parse any trailing fake arguments in the syntax string. */ syn = CGEN_SYNTAX_STRING (syntax); /* Mnemonics come first for now, ensure valid string. */ if (! CGEN_SYNTAX_MNEMONIC_P (* syn)) abort (); ++syn; while (* syn != 0) { /* Non operand chars must match exactly. */ if (CGEN_SYNTAX_CHAR_P (* syn)) { /* FIXME: While we allow for non-GAS callers above, we assume the first char after the mnemonic part is a space. */ /* FIXME: We also take inappropriate advantage of the fact that GAS's input scrubber will remove extraneous blanks. */ if (TOLOWER (*str) == TOLOWER (CGEN_SYNTAX_CHAR (* syn))) { #ifdef CGEN_MNEMONIC_OPERANDS if (CGEN_SYNTAX_CHAR(* syn) == ' ') past_opcode_p = 1; #endif ++ syn; ++ str; } else if (*str) { /* Syntax char didn't match. Can't be this insn. */ static char msg [80]; /* xgettext:c-format */ sprintf (msg, _("syntax error (expected char `%c', found `%c')"), CGEN_SYNTAX_CHAR(*syn), *str); return msg; } else { /* Ran out of input. */ static char msg [80]; /* xgettext:c-format */ sprintf (msg, _("syntax error (expected char `%c', found end of instruction)"), CGEN_SYNTAX_CHAR(*syn)); return msg; } continue; } #ifdef CGEN_MNEMONIC_OPERANDS (void) past_opcode_p; #endif /* We have an operand of some sort. */ errmsg = cd->parse_operand (cd, CGEN_SYNTAX_FIELD (*syn), &str, fields); if (errmsg) return errmsg; /* Done with this operand, continue with next one. */ ++ syn; } /* If we're at the end of the syntax string, we're done. */ if (* syn == 0) { /* FIXME: For the moment we assume a valid `str' can only contain blanks now. IE: We needn't try again with a longer version of the insn and it is assumed that longer versions of insns appear before shorter ones (eg: lsr r2,r3,1 vs lsr r2,r3). */ while (ISSPACE (* str)) ++ str; if (* str != '\0') return _("junk at end of line"); /* FIXME: would like to include `str' */ return NULL; } /* We couldn't parse it. */ return _("unrecognized instruction"); } /* Main entry point. This routine is called for each instruction to be assembled. STR points to the insn to be assembled. We assume all necessary tables have been initialized. The assembled instruction, less any fixups, is stored in BUF. Remember that if CGEN_INT_INSN_P then BUF is an int and thus the value still needs to be converted to target byte order, otherwise BUF is an array of bytes in target byte order. The result is a pointer to the insn's entry in the opcode table, or NULL if an error occured (an error message will have already been printed). Note that when processing (non-alias) macro-insns, this function recurses. ??? It's possible to make this cpu-independent. One would have to deal with a few minor things. At this point in time doing so would be more of a curiosity than useful [for example this file isn't _that_ big], but keeping the possibility in mind helps keep the design clean. */ const CGEN_INSN * ip2k_cgen_assemble_insn (CGEN_CPU_DESC cd, const char *str, CGEN_FIELDS *fields, CGEN_INSN_BYTES_PTR buf, char **errmsg) { const char *start; CGEN_INSN_LIST *ilist; const char *parse_errmsg = NULL; const char *insert_errmsg = NULL; int recognized_mnemonic = 0; /* Skip leading white space. */ while (ISSPACE (* str)) ++ str; /* The instructions are stored in hashed lists. Get the first in the list. */ ilist = CGEN_ASM_LOOKUP_INSN (cd, str); /* Keep looking until we find a match. */ start = str; for ( ; ilist != NULL ; ilist = CGEN_ASM_NEXT_INSN (ilist)) { const CGEN_INSN *insn = ilist->insn; recognized_mnemonic = 1; #ifdef CGEN_VALIDATE_INSN_SUPPORTED /* Not usually needed as unsupported opcodes shouldn't be in the hash lists. */ /* Is this insn supported by the selected cpu? */ if (! ip2k_cgen_insn_supported (cd, insn)) continue; #endif /* If the RELAXED attribute is set, this is an insn that shouldn't be chosen immediately. Instead, it is used during assembler/linker relaxation if possible. */ if (CGEN_INSN_ATTR_VALUE (insn, CGEN_INSN_RELAXED) != 0) continue; str = start; /* Skip this insn if str doesn't look right lexically. */ if (CGEN_INSN_RX (insn) != NULL && regexec ((regex_t *) CGEN_INSN_RX (insn), str, 0, NULL, 0) == REG_NOMATCH) continue; /* Allow parse/insert handlers to obtain length of insn. */ CGEN_FIELDS_BITSIZE (fields) = CGEN_INSN_BITSIZE (insn); parse_errmsg = CGEN_PARSE_FN (cd, insn) (cd, insn, & str, fields); if (parse_errmsg != NULL) continue; /* ??? 0 is passed for `pc'. */ insert_errmsg = CGEN_INSERT_FN (cd, insn) (cd, insn, fields, buf, (bfd_vma) 0); if (insert_errmsg != NULL) continue; /* It is up to the caller to actually output the insn and any queued relocs. */ return insn; } { static char errbuf[150]; const char *tmp_errmsg; #ifdef CGEN_VERBOSE_ASSEMBLER_ERRORS #define be_verbose 1 #else #define be_verbose 0 #endif if (be_verbose) { /* If requesting verbose error messages, use insert_errmsg. Failing that, use parse_errmsg. */ tmp_errmsg = (insert_errmsg ? insert_errmsg : parse_errmsg ? parse_errmsg : recognized_mnemonic ? _("unrecognized form of instruction") : _("unrecognized instruction")); if (strlen (start) > 50) /* xgettext:c-format */ sprintf (errbuf, "%s `%.50s...'", tmp_errmsg, start); else /* xgettext:c-format */ sprintf (errbuf, "%s `%.50s'", tmp_errmsg, start); } else { if (strlen (start) > 50) /* xgettext:c-format */ sprintf (errbuf, _("bad instruction `%.50s...'"), start); else /* xgettext:c-format */ sprintf (errbuf, _("bad instruction `%.50s'"), start); } *errmsg = errbuf; return NULL; } }
totalspectrum/binutils-propeller
opcodes/ip2k-asm.c
C
gpl-2.0
24,746
<?php use Twig\Node\Expression\Binary\MatchesBinary; class_exists('Twig\Node\Expression\Binary\MatchesBinary'); @trigger_error('Using the "Twig_Node_Expression_Binary_Matches" class is deprecated since Twig version 2.7, use "Twig\Node\Expression\Binary\MatchesBinary" instead.', \E_USER_DEPRECATED); if (false) { /** @deprecated since Twig 2.7, use "Twig\Node\Expression\Binary\MatchesBinary" instead */ class Twig_Node_Expression_Binary_Matches extends MatchesBinary { } }
tobiasbuhrer/tobiasb
vendor/twig/twig/lib/Twig/Node/Expression/Binary/Matches.php
PHP
gpl-2.0
494
/* * f_mass_storage.c -- Mass Storage USB Composite Function * * Copyright (C) 2003-2008 Alan Stern * Copyright (C) 2009 Samsung Electronics * Author: Michal Nazarewicz <mina86@mina86.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") as published by the Free Software * Foundation, either version 2 of that License or (at your option) any * later version. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * The Mass Storage Function acts as a USB Mass Storage device, * appearing to the host as a disk drive or as a CD-ROM drive. In * addition to providing an example of a genuinely useful composite * function for a USB device, it also illustrates a technique of * double-buffering for increased throughput. * * For more information about MSF and in particular its module * parameters and sysfs interface read the * <Documentation/usb/mass-storage.txt> file. */ /* * MSF is configured by specifying a fsg_config structure. It has the * following fields: * * nluns Number of LUNs function have (anywhere from 1 * to FSG_MAX_LUNS which is 8). * luns An array of LUN configuration values. This * should be filled for each LUN that * function will include (ie. for "nluns" * LUNs). Each element of the array has * the following fields: * ->filename The path to the backing file for the LUN. * Required if LUN is not marked as * removable. * ->ro Flag specifying access to the LUN shall be * read-only. This is implied if CD-ROM * emulation is enabled as well as when * it was impossible to open "filename" * in R/W mode. * ->removable Flag specifying that LUN shall be indicated as * being removable. * ->cdrom Flag specifying that LUN shall be reported as * being a CD-ROM. * ->nofua Flag specifying that FUA flag in SCSI WRITE(10,12) * commands for this LUN shall be ignored. * * vendor_name * product_name * release Information used as a reply to INQUIRY * request. To use default set to NULL, * NULL, 0xffff respectively. The first * field should be 8 and the second 16 * characters or less. * * can_stall Set to permit function to halt bulk endpoints. * Disabled on some USB devices known not * to work correctly. You should set it * to true. * * If "removable" is not set for a LUN then a backing file must be * specified. If it is set, then NULL filename means the LUN's medium * is not loaded (an empty string as "filename" in the fsg_config * structure causes error). The CD-ROM emulation includes a single * data track and no audio tracks; hence there need be only one * backing file per LUN. * * This function is heavily based on "File-backed Storage Gadget" by * Alan Stern which in turn is heavily based on "Gadget Zero" by David * Brownell. The driver's SCSI command interface was based on the * "Information technology - Small Computer System Interface - 2" * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93, * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>. * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which * was based on the "Universal Serial Bus Mass Storage Class UFI * Command Specification" document, Revision 1.0, December 14, 1998, * available at * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>. */ /* * Driver Design * * The MSF is fairly straightforward. There is a main kernel * thread that handles most of the work. Interrupt routines field * callbacks from the controller driver: bulk- and interrupt-request * completion notifications, endpoint-0 events, and disconnect events. * Completion events are passed to the main thread by wakeup calls. Many * ep0 requests are handled at interrupt time, but SetInterface, * SetConfiguration, and device reset requests are forwarded to the * thread in the form of "exceptions" using SIGUSR1 signals (since they * should interrupt any ongoing file I/O operations). * * The thread's main routine implements the standard command/data/status * parts of a SCSI interaction. It and its subroutines are full of tests * for pending signals/exceptions -- all this polling is necessary since * the kernel has no setjmp/longjmp equivalents. (Maybe this is an * indication that the driver really wants to be running in userspace.) * An important point is that so long as the thread is alive it keeps an * open reference to the backing file. This will prevent unmounting * the backing file's underlying filesystem and could cause problems * during system shutdown, for example. To prevent such problems, the * thread catches INT, TERM, and KILL signals and converts them into * an EXIT exception. * * In normal operation the main thread is started during the gadget's * fsg_bind() callback and stopped during fsg_unbind(). But it can * also exit when it receives a signal, and there's no point leaving * the gadget running when the thread is dead. As of this moment, MSF * provides no way to deregister the gadget when thread dies -- maybe * a callback functions is needed. * * To provide maximum throughput, the driver uses a circular pipeline of * buffer heads (struct fsg_buffhd). In principle the pipeline can be * arbitrarily long; in practice the benefits don't justify having more * than 2 stages (i.e., double buffering). But it helps to think of the * pipeline as being a long one. Each buffer head contains a bulk-in and * a bulk-out request pointer (since the buffer can be used for both * output and input -- directions always are given from the host's * point of view) as well as a pointer to the buffer and various state * variables. * * Use of the pipeline follows a simple protocol. There is a variable * (fsg->next_buffhd_to_fill) that points to the next buffer head to use. * At any time that buffer head may still be in use from an earlier * request, so each buffer head has a state variable indicating whether * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the * buffer head to be EMPTY, filling the buffer either by file I/O or by * USB I/O (during which the buffer head is BUSY), and marking the buffer * head FULL when the I/O is complete. Then the buffer will be emptied * (again possibly by USB I/O, during which it is marked BUSY) and * finally marked EMPTY again (possibly by a completion routine). * * A module parameter tells the driver to avoid stalling the bulk * endpoints wherever the transport specification allows. This is * necessary for some UDCs like the SuperH, which cannot reliably clear a * halt on a bulk endpoint. However, under certain circumstances the * Bulk-only specification requires a stall. In such cases the driver * will halt the endpoint and set a flag indicating that it should clear * the halt in software during the next device reset. Hopefully this * will permit everything to work correctly. Furthermore, although the * specification allows the bulk-out endpoint to halt when the host sends * too much data, implementing this would cause an unavoidable race. * The driver will always use the "no-stall" approach for OUT transfers. * * One subtle point concerns sending status-stage responses for ep0 * requests. Some of these requests, such as device reset, can involve * interrupting an ongoing file I/O operation, which might take an * arbitrarily long time. During that delay the host might give up on * the original ep0 request and issue a new one. When that happens the * driver should not notify the host about completion of the original * request, as the host will no longer be waiting for it. So the driver * assigns to each ep0 request a unique tag, and it keeps track of the * tag value of the request associated with a long-running exception * (device-reset, interface-change, or configuration-change). When the * exception handler is finished, the status-stage response is submitted * only if the current ep0 request tag is equal to the exception request * tag. Thus only the most recently received ep0 request will get a * status-stage response. * * Warning: This driver source file is too long. It ought to be split up * into a header file plus about 3 separate .c files, to handle the details * of the Gadget, USB Mass Storage, and SCSI protocols. */ /* #define VERBOSE_DEBUG */ /* #define DUMP_MSGS */ #include <linux/blkdev.h> #include <linux/completion.h> #include <linux/dcache.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/fcntl.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/kref.h> #include <linux/kthread.h> #include <linux/limits.h> #include <linux/rwsem.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/freezer.h> #include <linux/module.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include <linux/usb/composite.h> #include "gadget_chips.h" #include "configfs.h" #ifdef CONFIG_LGE_USB_G_AUTORUN #include <linux/miscdevice.h> #include <linux/switch.h> /* to get autorun user mode */ #include "u_lgeusb.h" #endif /*------------------------------------------------------------------------*/ #define FSG_DRIVER_DESC "Mass Storage Function" #define FSG_DRIVER_VERSION "2009/09/11" static const char fsg_string_interface[] = "Mass Storage"; #ifdef CONFIG_LGE_USB_G_AUTORUN /* Belows are LGE-customized SCSI cmd and * sub-cmd for autorun processing. * 2011-03-09, hyunhui.park@lge.com */ #define SC_LGE_SPE 0xF1 #define SUB_CODE_MODE_CHANGE 0x01 #define SUB_CODE_GET_VALUE 0x02 #define SUB_CODE_PROBE_DEV 0xff #define TYPE_MOD_CHG_TO_ACM 0x01 #define TYPE_MOD_CHG_TO_UMS 0x02 #define TYPE_MOD_CHG_TO_MTP 0x03 #define TYPE_MOD_CHG_TO_ASK 0x05 #define TYPE_MOD_CHG_TO_CGO 0x08 #define TYPE_MOD_CHG_TO_TET 0x09 #define TYPE_MOD_CHG_TO_FDG 0x0A #define TYPE_MOD_CHG_TO_PTP 0x0B #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) #define TYPE_MOD_CHG_TO_MUL 0x0C #endif #define TYPE_MOD_CHG_TO_MIDI 0x0D #define TYPE_MOD_CHG2_TO_ACM 0x81 #define TYPE_MOD_CHG2_TO_UMS 0x82 #define TYPE_MOD_CHG2_TO_MTP 0x83 #define TYPE_MOD_CHG2_TO_ASK 0x85 #define TYPE_MOD_CHG2_TO_CGO 0x86 #define TYPE_MOD_CHG2_TO_TET 0x87 #define TYPE_MOD_CHG2_TO_FDG 0x88 #define TYPE_MOD_CHG2_TO_PTP 0x89 #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) #define TYPE_MOD_CHG2_TO_MUL 0x8A #endif #define TYPE_MOD_CHG2_TO_MIDI 0x8B /* ACK TO SEND HOST PC */ #define ACK_STATUS_TO_HOST 0x10 #define ACK_SW_REV_TO_HOST 0x12 #define ACK_MEID_TO_HOST 0x13 #define ACK_MODEL_TO_HOST 0x14 #define ACK_SUB_VER_TO_HOST 0x15 #define SUB_ACK_STATUS_ACM 0x00 #define SUB_ACK_STATUS_MTP 0x01 #define SUB_ACK_STATUS_UMS 0x02 #define SUB_ACK_STATUS_ASK 0x03 #define SUB_ACK_STATUS_CGO 0x04 #define SUB_ACK_STATUS_TET 0x05 #define SUB_ACK_STATUS_PTP 0x06 #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) /*For multiple configuration, but actually ISO don't know this. *TODO : Need to clear this interface. */ #define SUB_ACK_STATUS_MUL 0x07 #endif #define SUB_ACK_STATUS_MIDI 0x08 #endif /* CONFIG_LGE_USB_G_AUTORUN */ #include "storage_common.h" #include "f_mass_storage.h" #ifdef CONFIG_LGE_USB_G_AUTORUN /* Belows are uevent string to communicate with * android framework and application. * 2011-03-09, hyunhui.park@lge.com */ static char *envp_ack[2] = {"AUTORUN=ACK", NULL}; #ifndef CONFIG_LGE_USB_G_AUTORUN_VZW static char *envp_mode[2] = {"AUTORUN=change_mode", NULL}; #else static char *envp_mode[][2] = { {"AUTORUN=change_unknown", NULL}, {"AUTORUN=change_acm", NULL}, {"AUTORUN=change_mtp", NULL}, {"AUTORUN=change_ums", NULL}, {"AUTORUN=change_ask", NULL}, {"AUTORUN=change_charge", NULL}, {"AUTORUN=change_tether", NULL}, {"AUTORUN=change_fdg", NULL}, {"AUTORUN=change_ptp", NULL}, {"AUTORUN=query_value", NULL}, {"AUTORUN=device_info", NULL}, #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) {"AUTORUN=change_mul", NULL}, #endif {"AUTORUN=change_midi", NULL}, }; #endif enum chg_mode_state { MODE_STATE_UNKNOWN = 0, MODE_STATE_ACM, MODE_STATE_MTP, MODE_STATE_UMS, MODE_STATE_ASK, MODE_STATE_CGO, MODE_STATE_TET, MODE_STATE_FDG, MODE_STATE_PTP, MODE_STATE_GET_VALUE, MODE_STATE_PROBE_DEV, #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) MODE_STATE_MUL, #endif MODE_STATE_MIDI, }; enum check_mode_state { ACK_STATUS_ACM = SUB_ACK_STATUS_ACM, ACK_STATUS_MTP = SUB_ACK_STATUS_MTP, ACK_STATUS_UMS = SUB_ACK_STATUS_UMS, ACK_STATUS_ASK = SUB_ACK_STATUS_ASK, ACK_STATUS_CGO = SUB_ACK_STATUS_CGO, ACK_STATUS_TET = SUB_ACK_STATUS_TET, ACK_STATUS_PTP = SUB_ACK_STATUS_PTP, #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) ACK_STATUS_MUL = SUB_ACK_STATUS_MUL, #endif ACK_STATUS_MIDI= SUB_ACK_STATUS_MIDI, ACK_STATUS_ERR, }; /* file operations for /dev/usb_autorun */ static const struct file_operations autorun_fops = { .owner = THIS_MODULE, }; static struct miscdevice autorun_device = { .minor = MISC_DYNAMIC_MINOR, .name = "usb_autorun", .fops = &autorun_fops, }; static unsigned int user_mode; static unsigned int already_acked; DEFINE_MUTEX(autorun_lock); #endif /* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */ static struct usb_string fsg_strings[] = { {FSG_STRING_INTERFACE, fsg_string_interface}, {} }; static struct usb_gadget_strings fsg_stringtab = { .language = 0x0409, /* en-us */ .strings = fsg_strings, }; static struct usb_gadget_strings *fsg_strings_array[] = { &fsg_stringtab, NULL, }; /*-------------------------------------------------------------------------*/ /* * If USB mass storage vfs operation is stuck for more than 10 sec * host will initiate the reset. Configure the timer with 9 sec to print * the error message before host is intiating the resume on it. */ #define MSC_VFS_TIMER_PERIOD_MS 9000 static int msc_vfs_timer_period_ms = MSC_VFS_TIMER_PERIOD_MS; module_param(msc_vfs_timer_period_ms, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(msc_vfs_timer_period_ms, "Set period for MSC VFS timer"); static int write_error_after_csw_sent; static int must_report_residue; static int csw_sent; struct fsg_dev; struct fsg_common; /* Data shared by all the FSG instances. */ struct fsg_common { struct usb_gadget *gadget; struct usb_composite_dev *cdev; struct fsg_dev *fsg, *new_fsg; wait_queue_head_t fsg_wait; /* filesem protects: backing files in use */ struct rw_semaphore filesem; /* lock protects: state, all the req_busy's */ spinlock_t lock; struct usb_ep *ep0; /* Copy of gadget->ep0 */ struct usb_request *ep0req; /* Copy of cdev->req */ unsigned int ep0_req_tag; struct fsg_buffhd *next_buffhd_to_fill; struct fsg_buffhd *next_buffhd_to_drain; struct fsg_buffhd *buffhds; unsigned int fsg_num_buffers; int cmnd_size; u8 cmnd[MAX_COMMAND_SIZE]; unsigned int nluns; unsigned int lun; struct fsg_lun **luns; struct fsg_lun *curlun; unsigned int bulk_out_maxpacket; enum fsg_state state; /* For exception handling */ unsigned int exception_req_tag; enum data_direction data_dir; u32 data_size; u32 data_size_from_cmnd; u32 tag; u32 residue; u32 usb_amount_left; unsigned int can_stall:1; unsigned int free_storage_on_release:1; unsigned int phase_error:1; unsigned int short_packet_received:1; unsigned int bad_lun_okay:1; unsigned int running:1; unsigned int sysfs:1; int thread_wakeup_needed; struct completion thread_notifier; struct task_struct *thread_task; /* Callback functions. */ const struct fsg_operations *ops; /* Gadget's private data. */ void *private_data; char inquiry_string[INQUIRY_MAX_LEN]; /* LUN name for sysfs purpose */ char name[FSG_MAX_LUNS][LUN_NAME_LEN]; #ifdef CONFIG_LGE_USB_G_AUTORUN /* LGE-customized USB mode */ enum chg_mode_state mode_state; const char *thread_name; #endif struct kref ref; struct timer_list vfs_timer; }; struct fsg_dev { struct usb_function function; struct usb_gadget *gadget; /* Copy of cdev->gadget */ struct fsg_common *common; u16 interface_number; unsigned int bulk_in_enabled:1; unsigned int bulk_out_enabled:1; unsigned long atomic_bitflags; #define IGNORE_BULK_OUT 0 struct usb_ep *bulk_in; struct usb_ep *bulk_out; }; static void msc_usb_vfs_timer_func(unsigned long data) { struct fsg_common *common = (struct fsg_common *) data; switch (common->data_dir) { case DATA_DIR_FROM_HOST: dev_err(&common->curlun->dev, "usb mass storage stuck in vfs_write\n"); break; case DATA_DIR_TO_HOST: dev_err(&common->curlun->dev, "usb mass storage stuck in vfs_read\n"); break; default: dev_err(&common->curlun->dev, "usb mass storage stuck in vfs_sync\n"); break; } } static inline int __fsg_is_set(struct fsg_common *common, const char *func, unsigned line) { if (common->fsg) return 1; ERROR(common, "common->fsg is NULL in %s at %u\n", func, line); WARN_ON(1); return 0; } #define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__)) static inline struct fsg_dev *fsg_from_func(struct usb_function *f) { return container_of(f, struct fsg_dev, function); } typedef void (*fsg_routine_t)(struct fsg_dev *); static int send_status(struct fsg_common *common); static int exception_in_progress(struct fsg_common *common) { return common->state > FSG_STATE_IDLE; } /* Make bulk-out requests be divisible by the maxpacket size */ static void set_bulk_out_req_length(struct fsg_common *common, struct fsg_buffhd *bh, unsigned int length) { unsigned int rem; bh->bulk_out_intended_length = length; rem = length % common->bulk_out_maxpacket; if (rem > 0) length += common->bulk_out_maxpacket - rem; bh->outreq->length = length; } /*-------------------------------------------------------------------------*/ static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep) { const char *name; if (ep == fsg->bulk_in) name = "bulk-in"; else if (ep == fsg->bulk_out) name = "bulk-out"; else name = ep->name; DBG(fsg, "%s set halt\n", name); return usb_ep_set_halt(ep); } /*-------------------------------------------------------------------------*/ /* These routines may be called in process context or in_irq */ /* Caller must hold fsg->lock */ static void wakeup_thread(struct fsg_common *common) { smp_wmb(); /* ensure the write of bh->state is complete */ /* Tell the main thread that something has happened */ common->thread_wakeup_needed = 1; if (common->thread_task) wake_up_process(common->thread_task); } static void raise_exception(struct fsg_common *common, enum fsg_state new_state) { unsigned long flags; /* * Do nothing if a higher-priority exception is already in progress. * If a lower-or-equal priority exception is in progress, preempt it * and notify the main thread by sending it a signal. */ spin_lock_irqsave(&common->lock, flags); if (common->state <= new_state) { common->exception_req_tag = common->ep0_req_tag; common->state = new_state; if (common->thread_task) send_sig_info(SIGUSR1, SEND_SIG_FORCED, common->thread_task); } spin_unlock_irqrestore(&common->lock, flags); } /*-------------------------------------------------------------------------*/ static int ep0_queue(struct fsg_common *common) { int rc; rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC); common->ep0->driver_data = common; if (rc != 0 && rc != -ESHUTDOWN) { /* We can't do much more than wait for a reset */ WARNING(common, "error in submission: %s --> %d\n", common->ep0->name, rc); } return rc; } /*-------------------------------------------------------------------------*/ /* Completion handlers. These always run in_irq. */ static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req) { struct fsg_common *common = ep->driver_data; struct fsg_buffhd *bh = req->context; if (req->status || req->actual != req->length) pr_debug("%s --> %d, %u/%u\n", __func__, req->status, req->actual, req->length); if (req->status == -ECONNRESET) /* Request was cancelled */ usb_ep_fifo_flush(ep); /* Hold the lock while we update the request and buffer states */ smp_wmb(); /* * Disconnect and completion might race each other and driver data * is set to NULL during ep disable. So, add a check if that is case. */ if (!common) { bh->inreq_busy = 0; bh->state = BUF_STATE_EMPTY; return; } spin_lock(&common->lock); bh->inreq_busy = 0; bh->state = BUF_STATE_EMPTY; wakeup_thread(common); spin_unlock(&common->lock); } static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req) { struct fsg_common *common = ep->driver_data; struct fsg_buffhd *bh = req->context; dump_msg(common, "bulk-out", req->buf, req->actual); if (req->status || req->actual != bh->bulk_out_intended_length) DBG(common, "%s --> %d, %u/%u\n", __func__, req->status, req->actual, bh->bulk_out_intended_length); if (req->status == -ECONNRESET) /* Request was cancelled */ usb_ep_fifo_flush(ep); /* Hold the lock while we update the request and buffer states */ smp_wmb(); spin_lock(&common->lock); bh->outreq_busy = 0; bh->state = BUF_STATE_FULL; wakeup_thread(common); spin_unlock(&common->lock); } static int fsg_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl) { struct fsg_dev *fsg = fsg_from_func(f); struct usb_request *req = fsg->common->ep0req; u16 w_index = le16_to_cpu(ctrl->wIndex); u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); if (!fsg_is_set(fsg->common)) return -EOPNOTSUPP; ++fsg->common->ep0_req_tag; /* Record arrival of a new request */ req->context = NULL; req->length = 0; dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl)); switch (ctrl->bRequest) { case US_BULK_RESET_REQUEST: if (ctrl->bRequestType != (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE)) break; if (w_index != fsg->interface_number || w_value != 0 || w_length != 0) return -EDOM; /* * Raise an exception to stop the current operation * and reinitialize our state. */ DBG(fsg, "bulk reset request\n"); raise_exception(fsg->common, FSG_STATE_RESET); return USB_GADGET_DELAYED_STATUS; case US_BULK_GET_MAX_LUN: if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE)) break; if (w_index != fsg->interface_number || w_value != 0 || w_length != 1) return -EDOM; VDBG(fsg, "get max LUN\n"); *(u8 *)req->buf = fsg->common->nluns - 1; /* Respond with data/status */ req->length = min((u16)1, w_length); return ep0_queue(fsg->common); } VDBG(fsg, "unknown class-specific control req %02x.%02x v%04x i%04x l%u\n", ctrl->bRequestType, ctrl->bRequest, le16_to_cpu(ctrl->wValue), w_index, w_length); return -EOPNOTSUPP; } /*-------------------------------------------------------------------------*/ /* All the following routines run in process context */ /* Use this for bulk or interrupt transfers, not ep0 */ static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep, struct usb_request *req, int *pbusy, enum fsg_buffer_state *state) { int rc; if (ep == fsg->bulk_in) dump_msg(fsg, "bulk-in", req->buf, req->length); spin_lock_irq(&fsg->common->lock); *pbusy = 1; *state = BUF_STATE_BUSY; spin_unlock_irq(&fsg->common->lock); rc = usb_ep_queue(ep, req, GFP_KERNEL); if (rc == 0) return; /* All good, we're done */ *pbusy = 0; *state = BUF_STATE_EMPTY; /* We can't do much more than wait for a reset */ /* * Note: currently the net2280 driver fails zero-length * submissions if DMA is enabled. */ if (rc != -ESHUTDOWN && !(rc == -EOPNOTSUPP && req->length == 0)) WARNING(fsg, "error in submission: %s --> %d\n", ep->name, rc); } static bool start_in_transfer(struct fsg_common *common, struct fsg_buffhd *bh) { if (!fsg_is_set(common)) return false; start_transfer(common->fsg, common->fsg->bulk_in, bh->inreq, &bh->inreq_busy, &bh->state); return true; } static bool start_out_transfer(struct fsg_common *common, struct fsg_buffhd *bh) { if (!fsg_is_set(common)) return false; start_transfer(common->fsg, common->fsg->bulk_out, bh->outreq, &bh->outreq_busy, &bh->state); return true; } static int sleep_thread(struct fsg_common *common, bool can_freeze) { int rc = 0; /* Wait until a signal arrives or we are woken up */ for (;;) { if (can_freeze) try_to_freeze(); set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) { rc = -EINTR; break; } spin_lock_irq(&common->lock); if (common->thread_wakeup_needed) { spin_unlock_irq(&common->lock); break; } spin_unlock_irq(&common->lock); schedule(); } __set_current_state(TASK_RUNNING); spin_lock_irq(&common->lock); common->thread_wakeup_needed = 0; spin_unlock_irq(&common->lock); smp_rmb(); /* ensure the latest bh->state is visible */ return rc; } /*-------------------------------------------------------------------------*/ static int do_read(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; u32 lba; struct fsg_buffhd *bh; int rc; u32 amount_left; loff_t file_offset, file_offset_tmp; unsigned int amount; ssize_t nread; ktime_t start, diff; /* * Get the starting Logical Block Address and check that it's * not too big. */ if (common->cmnd[0] == READ_6) lba = get_unaligned_be24(&common->cmnd[1]); else { lba = get_unaligned_be32(&common->cmnd[2]); /* * We allow DPO (Disable Page Out = don't save data in the * cache) and FUA (Force Unit Access = don't read from the * cache), but we don't implement them. */ if ((common->cmnd[1] & ~0x18) != 0) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } } if (lba >= curlun->num_sectors) { curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return -EINVAL; } file_offset = ((loff_t) lba) << curlun->blkbits; /* Carry out the file reads */ amount_left = common->data_size_from_cmnd; if (unlikely(amount_left == 0)) return -EIO; /* No default reply */ for (;;) { /* * Figure out how much we need to read: * Try to read the remaining amount. * But don't read more than the buffer size. * And don't try to read past the end of the file. */ amount = min(amount_left, FSG_BUFLEN); amount = min((loff_t)amount, curlun->file_length - file_offset); /* Wait for the next buffer to become available */ spin_lock_irq(&common->lock); bh = common->next_buffhd_to_fill; while (bh->state != BUF_STATE_EMPTY) { spin_unlock_irq(&common->lock); rc = sleep_thread(common, false); if (rc) return rc; spin_lock_irq(&common->lock); } spin_unlock_irq(&common->lock); /* * If we were asked to read past the end of file, * end with an empty buffer. */ if (amount == 0) { curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; curlun->sense_data_info = file_offset >> curlun->blkbits; curlun->info_valid = 1; spin_lock_irq(&common->lock); bh->inreq->length = 0; bh->state = BUF_STATE_FULL; spin_unlock_irq(&common->lock); break; } /* Perform the read */ file_offset_tmp = file_offset; start = ktime_get(); mod_timer(&common->vfs_timer, jiffies + msecs_to_jiffies(msc_vfs_timer_period_ms)); nread = vfs_read(curlun->filp, (char __user *)bh->buf, amount, &file_offset_tmp); del_timer_sync(&common->vfs_timer); VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, (unsigned long long)file_offset, (int)nread); diff = ktime_sub(ktime_get(), start); curlun->perf.rbytes += nread; curlun->perf.rtime = ktime_add(curlun->perf.rtime, diff); if (signal_pending(current)) return -EINTR; if (nread < 0) { LDBG(curlun, "error in file read: %d\n", (int)nread); nread = 0; } else if (nread < amount) { LDBG(curlun, "partial file read: %d/%u\n", (int)nread, amount); nread = round_down(nread, curlun->blksize); } file_offset += nread; amount_left -= nread; common->residue -= nread; /* * Except at the end of the transfer, nread will be * equal to the buffer size, which is divisible by the * bulk-in maxpacket size. */ spin_lock_irq(&common->lock); bh->inreq->length = nread; bh->state = BUF_STATE_FULL; spin_unlock_irq(&common->lock); /* If an error occurred, report it and its position */ if (nread < amount) { curlun->sense_data = SS_UNRECOVERED_READ_ERROR; curlun->sense_data_info = file_offset >> curlun->blkbits; curlun->info_valid = 1; break; } if (amount_left == 0) break; /* No more left to read */ /* Send this buffer and go read some more */ bh->inreq->zero = 0; if (!start_in_transfer(common, bh)) /* Don't know what to do if common->fsg is NULL */ return -EIO; common->next_buffhd_to_fill = bh->next; } return -EIO; /* No default reply */ } /*-------------------------------------------------------------------------*/ static int do_write(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; u32 lba; struct fsg_buffhd *bh; int get_some_more; u32 amount_left_to_req, amount_left_to_write; loff_t usb_offset, file_offset, file_offset_tmp; unsigned int amount; ssize_t nwritten; ktime_t start, diff; int rc, i; if (curlun->ro) { curlun->sense_data = SS_WRITE_PROTECTED; return -EINVAL; } spin_lock(&curlun->filp->f_lock); curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */ spin_unlock(&curlun->filp->f_lock); /* * Get the starting Logical Block Address and check that it's * not too big */ if (common->cmnd[0] == WRITE_6) lba = get_unaligned_be24(&common->cmnd[1]); else { lba = get_unaligned_be32(&common->cmnd[2]); /* * We allow DPO (Disable Page Out = don't save data in the * cache) and FUA (Force Unit Access = write directly to the * medium). We don't implement DPO; we implement FUA by * performing synchronous output. */ if (common->cmnd[1] & ~0x18) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } if (!curlun->nofua && (common->cmnd[1] & 0x08)) { /* FUA */ spin_lock(&curlun->filp->f_lock); curlun->filp->f_flags |= O_SYNC; spin_unlock(&curlun->filp->f_lock); } } if (lba >= curlun->num_sectors) { curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return -EINVAL; } /* Carry out the file writes */ get_some_more = 1; file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits; amount_left_to_req = common->data_size_from_cmnd; amount_left_to_write = common->data_size_from_cmnd; while (amount_left_to_write > 0) { /* Queue a request for more data from the host */ bh = common->next_buffhd_to_fill; if (bh->state == BUF_STATE_EMPTY && get_some_more) { /* * Figure out how much we want to get: * Try to get the remaining amount, * but not more than the buffer size. */ amount = min(amount_left_to_req, FSG_BUFLEN); /* Beyond the end of the backing file? */ if (usb_offset >= curlun->file_length) { get_some_more = 0; curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; curlun->sense_data_info = usb_offset >> curlun->blkbits; curlun->info_valid = 1; continue; } /* Get the next buffer */ usb_offset += amount; common->usb_amount_left -= amount; amount_left_to_req -= amount; if (amount_left_to_req == 0) get_some_more = 0; /* * Except at the end of the transfer, amount will be * equal to the buffer size, which is divisible by * the bulk-out maxpacket size. */ set_bulk_out_req_length(common, bh, amount); if (!start_out_transfer(common, bh)) /* Dunno what to do if common->fsg is NULL */ return -EIO; common->next_buffhd_to_fill = bh->next; continue; } /* Write the received data to the backing file */ bh = common->next_buffhd_to_drain; if (bh->state == BUF_STATE_EMPTY && !get_some_more) break; /* We stopped early */ /* * If the csw packet is already submmitted to the hardware, * by marking the state of buffer as full, then by checking * the residue, we make sure that this csw packet is not * written on to the storage media. */ if (bh->state == BUF_STATE_FULL && common->residue) { smp_rmb(); common->next_buffhd_to_drain = bh->next; bh->state = BUF_STATE_EMPTY; /* Did something go wrong with the transfer? */ if (bh->outreq->status != 0) { curlun->sense_data = SS_COMMUNICATION_FAILURE; curlun->sense_data_info = file_offset >> curlun->blkbits; curlun->info_valid = 1; break; } amount = bh->outreq->actual; if (curlun->file_length - file_offset < amount) { LERROR(curlun, "write %u @ %llu beyond end %llu\n", amount, (unsigned long long)file_offset, (unsigned long long)curlun->file_length); amount = curlun->file_length - file_offset; } /* Don't accept excess data. The spec doesn't say * what to do in this case. We'll ignore the error. */ amount = min(amount, bh->bulk_out_intended_length); /* Don't write a partial block */ amount = round_down(amount, curlun->blksize); if (amount == 0) goto empty_write; /* Perform the write */ file_offset_tmp = file_offset; start = ktime_get(); mod_timer(&common->vfs_timer, jiffies + msecs_to_jiffies(msc_vfs_timer_period_ms)); nwritten = vfs_write(curlun->filp, (char __user *)bh->buf, amount, &file_offset_tmp); del_timer_sync(&common->vfs_timer); VLDBG(curlun, "file write %u @ %llu -> %d\n", amount, (unsigned long long)file_offset, (int)nwritten); diff = ktime_sub(ktime_get(), start); curlun->perf.wbytes += nwritten; curlun->perf.wtime = ktime_add(curlun->perf.wtime, diff); if (signal_pending(current)) return -EINTR; /* Interrupted! */ if (nwritten < 0) { LDBG(curlun, "error in file write: %d\n", (int)nwritten); nwritten = 0; } else if (nwritten < amount) { LDBG(curlun, "partial file write: %d/%u\n", (int)nwritten, amount); nwritten = round_down(nwritten, curlun->blksize); } file_offset += nwritten; amount_left_to_write -= nwritten; common->residue -= nwritten; /* If an error occurred, report it and its position */ if (nwritten < amount) { curlun->sense_data = SS_WRITE_ERROR; curlun->sense_data_info = file_offset >> curlun->blkbits; curlun->info_valid = 1; write_error_after_csw_sent = 1; goto write_error; break; } write_error: if ((nwritten == amount) && !csw_sent) { if (write_error_after_csw_sent) break; /* * If residue still exists and nothing left to * write, device must send correct residue to * host in this case. */ if (!amount_left_to_write && common->residue) { must_report_residue = 1; break; } /* * Check if any of the buffer is in the * busy state, if any buffer is in busy state, * means the complete data is not received * yet from the host. So there is no point in * csw right away without the complete data. */ for (i = 0; i < common->fsg_num_buffers; i++) { if (common->buffhds[i].state == BUF_STATE_BUSY) break; } if (!amount_left_to_req && i == common->fsg_num_buffers) { csw_sent = 1; send_status(common); } } empty_write: /* Did the host decide to stop early? */ if (bh->outreq->actual < bh->bulk_out_intended_length) { common->short_packet_received = 1; break; } continue; } /* Wait for something to happen */ rc = sleep_thread(common, false); if (rc) return rc; } return -EIO; /* No default reply */ } /*-------------------------------------------------------------------------*/ static int do_synchronize_cache(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; int rc; /* We ignore the requested LBA and write out all file's * dirty data buffers. */ mod_timer(&common->vfs_timer, jiffies + msecs_to_jiffies(msc_vfs_timer_period_ms)); rc = fsg_lun_fsync_sub(curlun); if (rc) curlun->sense_data = SS_WRITE_ERROR; del_timer_sync(&common->vfs_timer); return 0; } /*-------------------------------------------------------------------------*/ static void invalidate_sub(struct fsg_lun *curlun) { struct file *filp = curlun->filp; struct inode *inode = file_inode(filp); unsigned long rc; rc = invalidate_mapping_pages(inode->i_mapping, 0, -1); VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc); } static int do_verify(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; u32 lba; u32 verification_length; struct fsg_buffhd *bh = common->next_buffhd_to_fill; loff_t file_offset, file_offset_tmp; u32 amount_left; unsigned int amount; ssize_t nread; /* * Get the starting Logical Block Address and check that it's * not too big. */ lba = get_unaligned_be32(&common->cmnd[2]); if (lba >= curlun->num_sectors) { curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return -EINVAL; } /* * We allow DPO (Disable Page Out = don't save data in the * cache) but we don't implement it. */ if (common->cmnd[1] & ~0x10) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } verification_length = get_unaligned_be16(&common->cmnd[7]); if (unlikely(verification_length == 0)) return -EIO; /* No default reply */ /* Prepare to carry out the file verify */ amount_left = verification_length << curlun->blkbits; file_offset = ((loff_t) lba) << curlun->blkbits; /* Write out all the dirty buffers before invalidating them */ mod_timer(&common->vfs_timer, jiffies + msecs_to_jiffies(msc_vfs_timer_period_ms)); fsg_lun_fsync_sub(curlun); del_timer_sync(&common->vfs_timer); if (signal_pending(current)) return -EINTR; invalidate_sub(curlun); if (signal_pending(current)) return -EINTR; /* Just try to read the requested blocks */ while (amount_left > 0) { /* * Figure out how much we need to read: * Try to read the remaining amount, but not more than * the buffer size. * And don't try to read past the end of the file. */ amount = min(amount_left, FSG_BUFLEN); amount = min((loff_t)amount, curlun->file_length - file_offset); if (amount == 0) { curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; curlun->sense_data_info = file_offset >> curlun->blkbits; curlun->info_valid = 1; break; } /* Perform the read */ file_offset_tmp = file_offset; mod_timer(&common->vfs_timer, jiffies + msecs_to_jiffies(msc_vfs_timer_period_ms)); nread = vfs_read(curlun->filp, (char __user *) bh->buf, amount, &file_offset_tmp); del_timer_sync(&common->vfs_timer); VLDBG(curlun, "file read %u @ %llu -> %d\n", amount, (unsigned long long) file_offset, (int) nread); if (signal_pending(current)) return -EINTR; if (nread < 0) { LDBG(curlun, "error in file verify: %d\n", (int)nread); nread = 0; } else if (nread < amount) { LDBG(curlun, "partial file verify: %d/%u\n", (int)nread, amount); nread = round_down(nread, curlun->blksize); } if (nread == 0) { curlun->sense_data = SS_UNRECOVERED_READ_ERROR; curlun->sense_data_info = file_offset >> curlun->blkbits; curlun->info_valid = 1; break; } file_offset += nread; amount_left -= nread; } return 0; } /*-------------------------------------------------------------------------*/ static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; u8 *buf = (u8 *) bh->buf; if (!curlun) { /* Unsupported LUNs are okay */ common->bad_lun_okay = 1; memset(buf, 0, 36); buf[0] = 0x7f; /* Unsupported, no device-type */ buf[4] = 31; /* Additional length */ return 36; } buf[0] = curlun->cdrom ? TYPE_ROM : TYPE_DISK; buf[1] = curlun->removable ? 0x80 : 0; buf[2] = 2; /* ANSI SCSI level 2 */ buf[3] = 2; /* SCSI-2 INQUIRY data format */ buf[4] = 31; /* Additional length */ buf[5] = 0; /* No special options */ buf[6] = 0; buf[7] = 0; memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string); return 36; } #ifdef CONFIG_LGE_USB_G_AUTORUN /* Add function which handles LGE-customized command from PC. * 2011-03-09, hyunhui.park@lge.com */ static int do_ack_status(struct fsg_common *common, struct fsg_buffhd *bh, u8 ack) { u8 *buf = (u8 *) bh->buf; if (!common->curlun) { /* Unsupported LUNs are okay */ common->bad_lun_okay = 1; buf[0] = 0xf; return 1; } buf[0] = ack; /* Old froyo version */ /* if(ack == SUB_ACK_STATUS_ACM) buf[0] = SUB_ACK_STATUS_ACM; else if(ack == SUB_ACK_STATUS_MTP) buf[0] = SUB_ACK_STATUS_MTP; else if(ack == SUB_ACK_STATUS_UMS) buf[0] = SUB_ACK_STATUS_UMS; else if(ack == SUB_ACK_STATUS_ASK) buf[0] = SUB_ACK_STATUS_ASK; else if(ack == SUB_ACK_STATUS_CGO) buf[0] = SUB_ACK_STATUS_CGO; else if(ack == SUB_ACK_STATUS_TET) buf[0] = SUB_ACK_STATUS_TET; */ return 1; } static int do_get_sw_ver(struct fsg_common *common, struct fsg_buffhd *bh) { u8 *buf = (u8 *) bh->buf; char sw_ver[9] = {0, }; int i; /* msm_get_SW_VER_type(sw_ver); */ if (lgeusb_get_sw_ver(sw_ver) < 0) strlcpy(sw_ver, "00000000", 9); memset(buf, 0, 9); for (i = 0; i < strlen(sw_ver); i++) { if (sw_ver[i] >= 'a' && sw_ver[i] <= 'z') sw_ver[i] -= 32; } strlcpy(buf, sw_ver, PAGE_SIZE); pr_info("[AUTORUN] %s: sw_ver: %s\n", __func__, buf); return 9; } static int do_get_serial(struct fsg_common *common, struct fsg_buffhd *bh) { u8 *buf = (u8 *) bh->buf; int i; char imei_temp[15] = {0, }; u8 imei_hex[7]; /* msm_get_MEID_type(imei_temp); */ if (lgeusb_get_phone_id(imei_temp) < 0) strlcpy(imei_temp, "00000000000000", 15); if (hex2bin(imei_hex, imei_temp, 7) < 0) pr_err("%s [AUTORUN] : Error on hex2bin\n", __func__); for (i = 0; i < 7; i++) buf[6-i] = imei_hex[i]; pr_info("[AUTORUN] %s: meid: %02x%02x%02x%02x%02x%02x%02x\n", __func__, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6]); return 7; } static int do_get_model(struct fsg_common *common, struct fsg_buffhd *bh) { u8 *buf = (u8 *) bh->buf; char model[7] = {0, }; if (lgeusb_get_model_name(model) < 0) strlcpy(buf, "VS930", PAGE_SIZE); else strlcpy(buf, model, PAGE_SIZE); pr_info("[AUTORUN] %s: model: %s\n", __func__, buf); return strlen(buf); } static int do_get_sub_ver(struct fsg_common *common, struct fsg_buffhd *bh) { u8 *buf = (u8 *) bh->buf; char sub_ver[3] = {0, }; /* msm_get_SUB_VER_type(sub_ver); */ if (lgeusb_get_sub_ver(sub_ver) < 0) sub_ver[0] = '0'; if (strlen(sub_ver) > 1) { if (sub_ver[0] == '0') *buf = sub_ver[1] - '0'; else if (sub_ver[0] == '1') *buf = 'a' + sub_ver[1] - '0' - 87; else if (sub_ver[0] == '2') *buf = 'k' + sub_ver[1] - '0' - 87; else if (sub_ver[0] == '3' && (sub_ver[1] < '6' && sub_ver[1] >= '0')) *buf = 'u' + sub_ver[1] - '0' - 87; else *buf = 0; } else *buf = sub_ver[0] - '0'; pr_info("[AUTORUN] %s: sub_ver: %d\n", __func__, (char)*buf); return 1; } #endif static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; u8 *buf = (u8 *) bh->buf; u32 sd, sdinfo; int valid; /* * From the SCSI-2 spec., section 7.9 (Unit attention condition): * * If a REQUEST SENSE command is received from an initiator * with a pending unit attention condition (before the target * generates the contingent allegiance condition), then the * target shall either: * a) report any pending sense data and preserve the unit * attention condition on the logical unit, or, * b) report the unit attention condition, may discard any * pending sense data, and clear the unit attention * condition on the logical unit for that initiator. * * FSG normally uses option a); enable this code to use option b). */ #if 0 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) { curlun->sense_data = curlun->unit_attention_data; curlun->unit_attention_data = SS_NO_SENSE; } #endif if (!curlun) { /* Unsupported LUNs are okay */ common->bad_lun_okay = 1; sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; sdinfo = 0; valid = 0; } else { sd = curlun->sense_data; sdinfo = curlun->sense_data_info; valid = curlun->info_valid << 7; curlun->sense_data = SS_NO_SENSE; curlun->sense_data_info = 0; curlun->info_valid = 0; } memset(buf, 0, 18); buf[0] = valid | 0x70; /* Valid, current error */ buf[2] = SK(sd); put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */ buf[7] = 18 - 8; /* Additional sense length */ buf[12] = ASC(sd); buf[13] = ASCQ(sd); return 18; } static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; u32 lba = get_unaligned_be32(&common->cmnd[2]); int pmi = common->cmnd[8]; u8 *buf = (u8 *)bh->buf; /* Check the PMI and LBA fields */ if (pmi > 1 || (pmi == 0 && lba != 0)) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } put_unaligned_be32(curlun->num_sectors - 1, &buf[0]); /* Max logical block */ put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */ return 8; } static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; int msf = common->cmnd[1] & 0x02; u32 lba = get_unaligned_be32(&common->cmnd[2]); u8 *buf = (u8 *)bh->buf; if (common->cmnd[1] & ~0x02) { /* Mask away MSF */ curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } if (lba >= curlun->num_sectors) { curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return -EINVAL; } memset(buf, 0, 8); buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */ store_cdrom_address(&buf[4], msf, lba); return 8; } static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; int msf = common->cmnd[1] & 0x02; int start_track = common->cmnd[6]; u8 *buf = (u8 *)bh->buf; #ifdef CONFIG_LGE_USB_G_CDROM_MAC_SUPPORT u8 format; int ret; #endif if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */ start_track > 1) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } #ifdef CONFIG_LGE_USB_G_CDROM_MAC_SUPPORT format = common->cmnd[2] & 0xf; /* * Check if CDB is old style SFF-8020i * i.e. format is in 2 MSBs of byte 9 * Mac OS-X host sends us this. */ if (format == 0) format = (common->cmnd[9] >> 6) & 0x3; ret = fsg_get_toc(curlun, msf, format, buf); if (ret < 0) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } return ret; #else /* original */ memset(buf, 0, 20); buf[1] = (20-2); /* TOC data length */ buf[2] = 1; /* First track number */ buf[3] = 1; /* Last track number */ buf[5] = 0x16; /* Data track, copying allowed */ buf[6] = 0x01; /* Only track is number 1 */ store_cdrom_address(&buf[8], msf, 0); buf[13] = 0x16; /* Lead-out track is data */ buf[14] = 0xAA; /* Lead-out track number */ store_cdrom_address(&buf[16], msf, curlun->num_sectors); return 20; #endif } static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; int mscmnd = common->cmnd[0]; u8 *buf = (u8 *) bh->buf; u8 *buf0 = buf; int pc, page_code; int changeable_values, all_pages; int valid_page = 0; int len, limit; if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */ curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } pc = common->cmnd[2] >> 6; page_code = common->cmnd[2] & 0x3f; if (pc == 3) { curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED; return -EINVAL; } changeable_values = (pc == 1); all_pages = (page_code == 0x3f); /* * Write the mode parameter header. Fixed values are: default * medium type, no cache control (DPOFUA), and no block descriptors. * The only variable value is the WriteProtect bit. We will fill in * the mode data length later. */ memset(buf, 0, 8); if (mscmnd == MODE_SENSE) { buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */ buf += 4; limit = 255; } else { /* MODE_SENSE_10 */ buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */ buf += 8; limit = 65535; /* Should really be FSG_BUFLEN */ } /* No block descriptors */ /* * The mode pages, in numerical order. The only page we support * is the Caching page. */ if (page_code == 0x08 || all_pages) { valid_page = 1; buf[0] = 0x08; /* Page code */ buf[1] = 10; /* Page length */ memset(buf+2, 0, 10); /* None of the fields are changeable */ if (!changeable_values) { buf[2] = 0x04; /* Write cache enable, */ /* Read cache not disabled */ /* No cache retention priorities */ put_unaligned_be16(0xffff, &buf[4]); /* Don't disable prefetch */ /* Minimum prefetch = 0 */ put_unaligned_be16(0xffff, &buf[8]); /* Maximum prefetch */ put_unaligned_be16(0xffff, &buf[10]); /* Maximum prefetch ceiling */ } buf += 12; } /* * Check that a valid page was requested and the mode data length * isn't too long. */ len = buf - buf0; if (!valid_page || len > limit) { curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } /* Store the mode data length */ if (mscmnd == MODE_SENSE) buf0[0] = len - 1; else put_unaligned_be16(len - 2, buf0); return len; } static int do_start_stop(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; int loej, start; if (!curlun) { return -EINVAL; } else if (!curlun->removable) { curlun->sense_data = SS_INVALID_COMMAND; return -EINVAL; } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */ (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */ curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } loej = common->cmnd[4] & 0x02; start = common->cmnd[4] & 0x01; /* * Our emulation doesn't support mounting; the medium is * available for use as soon as it is loaded. */ if (start) { if (!fsg_lun_is_open(curlun)) { curlun->sense_data = SS_MEDIUM_NOT_PRESENT; return -EINVAL; } return 0; } /* Are we allowed to unload the media? */ if (curlun->prevent_medium_removal) { LDBG(curlun, "unload attempt prevented\n"); curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED; return -EINVAL; } #ifdef CONFIG_LGE_USB_G_AUTORUN /* XXX: This feature is only for USB Autorun. Don't use it at other. */ if (!loej || curlun->cdrom) return 0; #else if (!loej) return 0; #endif up_read(&common->filesem); down_write(&common->filesem); fsg_lun_close(curlun); up_write(&common->filesem); down_read(&common->filesem); return 0; } static int do_prevent_allow(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; int prevent; if (!common->curlun) { return -EINVAL; } else if (!common->curlun->removable) { common->curlun->sense_data = SS_INVALID_COMMAND; return -EINVAL; } prevent = common->cmnd[4] & 0x01; if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */ curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } if (!curlun->nofua && curlun->prevent_medium_removal && !prevent) { mod_timer(&common->vfs_timer, jiffies + msecs_to_jiffies(msc_vfs_timer_period_ms)); fsg_lun_fsync_sub(curlun); del_timer_sync(&common->vfs_timer); } curlun->prevent_medium_removal = prevent; return 0; } static int do_read_format_capacities(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; u8 *buf = (u8 *) bh->buf; buf[0] = buf[1] = buf[2] = 0; buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */ buf += 4; put_unaligned_be32(curlun->num_sectors, &buf[0]); /* Number of blocks */ put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */ buf[4] = 0x02; /* Current capacity */ return 12; } static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh) { struct fsg_lun *curlun = common->curlun; /* We don't support MODE SELECT */ if (curlun) curlun->sense_data = SS_INVALID_COMMAND; return -EINVAL; } /*-------------------------------------------------------------------------*/ static int halt_bulk_in_endpoint(struct fsg_dev *fsg) { int rc; rc = fsg_set_halt(fsg, fsg->bulk_in); if (rc == -EAGAIN) VDBG(fsg, "delayed bulk-in endpoint halt\n"); while (rc != 0) { if (rc != -EAGAIN) { WARNING(fsg, "usb_ep_set_halt -> %d\n", rc); rc = 0; break; } /* Wait for a short time and then try again */ if (msleep_interruptible(100) != 0) return -EINTR; rc = usb_ep_set_halt(fsg->bulk_in); } return rc; } static int wedge_bulk_in_endpoint(struct fsg_dev *fsg) { int rc; DBG(fsg, "bulk-in set wedge\n"); rc = usb_ep_set_wedge(fsg->bulk_in); if (rc == -EAGAIN) VDBG(fsg, "delayed bulk-in endpoint wedge\n"); while (rc != 0) { if (rc != -EAGAIN) { WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc); rc = 0; break; } /* Wait for a short time and then try again */ if (msleep_interruptible(100) != 0) return -EINTR; rc = usb_ep_set_wedge(fsg->bulk_in); } return rc; } static int throw_away_data(struct fsg_common *common) { struct fsg_buffhd *bh; u32 amount; int rc; for (bh = common->next_buffhd_to_drain; bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0; bh = common->next_buffhd_to_drain) { /* Throw away the data in a filled buffer */ if (bh->state == BUF_STATE_FULL) { smp_rmb(); bh->state = BUF_STATE_EMPTY; common->next_buffhd_to_drain = bh->next; /* A short packet or an error ends everything */ if (bh->outreq->actual < bh->bulk_out_intended_length || bh->outreq->status != 0) { raise_exception(common, FSG_STATE_ABORT_BULK_OUT); return -EINTR; } continue; } /* Try to submit another request if we need one */ bh = common->next_buffhd_to_fill; if (bh->state == BUF_STATE_EMPTY && common->usb_amount_left > 0) { amount = min(common->usb_amount_left, FSG_BUFLEN); /* * Except at the end of the transfer, amount will be * equal to the buffer size, which is divisible by * the bulk-out maxpacket size. */ set_bulk_out_req_length(common, bh, amount); if (!start_out_transfer(common, bh)) /* Dunno what to do if common->fsg is NULL */ return -EIO; common->next_buffhd_to_fill = bh->next; common->usb_amount_left -= amount; continue; } /* Otherwise wait for something to happen */ rc = sleep_thread(common, true); if (rc) return rc; } return 0; } static int finish_reply(struct fsg_common *common) { struct fsg_buffhd *bh = common->next_buffhd_to_fill; int rc = 0; switch (common->data_dir) { case DATA_DIR_NONE: break; /* Nothing to send */ /* * If we don't know whether the host wants to read or write, * this must be CB or CBI with an unknown command. We mustn't * try to send or receive any data. So stall both bulk pipes * if we can and wait for a reset. */ case DATA_DIR_UNKNOWN: if (!common->can_stall) { /* Nothing */ } else if (fsg_is_set(common)) { fsg_set_halt(common->fsg, common->fsg->bulk_out); rc = halt_bulk_in_endpoint(common->fsg); } else { /* Don't know what to do if common->fsg is NULL */ rc = -EIO; } break; /* All but the last buffer of data must have already been sent */ case DATA_DIR_TO_HOST: if (common->data_size == 0) { /* Nothing to send */ /* Don't know what to do if common->fsg is NULL */ } else if (!fsg_is_set(common)) { rc = -EIO; /* If there's no residue, simply send the last buffer */ } else if (common->residue == 0) { bh->inreq->zero = 0; if (!start_in_transfer(common, bh)) return -EIO; common->next_buffhd_to_fill = bh->next; /* * For Bulk-only, mark the end of the data with a short * packet. If we are allowed to stall, halt the bulk-in * endpoint. (Note: This violates the Bulk-Only Transport * specification, which requires us to pad the data if we * don't halt the endpoint. Presumably nobody will mind.) */ } else { bh->inreq->zero = 1; if (!start_in_transfer(common, bh)) rc = -EIO; common->next_buffhd_to_fill = bh->next; if (common->can_stall) rc = halt_bulk_in_endpoint(common->fsg); } break; /* * We have processed all we want from the data the host has sent. * There may still be outstanding bulk-out requests. */ case DATA_DIR_FROM_HOST: if (common->residue == 0) { /* Nothing to receive */ /* Did the host stop sending unexpectedly early? */ } else if (common->short_packet_received) { raise_exception(common, FSG_STATE_ABORT_BULK_OUT); rc = -EINTR; /* * We haven't processed all the incoming data. Even though * we may be allowed to stall, doing so would cause a race. * The controller may already have ACK'ed all the remaining * bulk-out packets, in which case the host wouldn't see a * STALL. Not realizing the endpoint was halted, it wouldn't * clear the halt -- leading to problems later on. */ #if 0 } else if (common->can_stall) { if (fsg_is_set(common)) fsg_set_halt(common->fsg, common->fsg->bulk_out); raise_exception(common, FSG_STATE_ABORT_BULK_OUT); rc = -EINTR; #endif /* * We can't stall. Read in the excess data and throw it * all away. */ } else { rc = throw_away_data(common); } break; } return rc; } static int send_status(struct fsg_common *common) { struct fsg_lun *curlun = common->curlun; struct fsg_buffhd *bh; struct bulk_cs_wrap *csw; int rc; u8 status = US_BULK_STAT_OK; u32 sd, sdinfo = 0; /* Wait for the next buffer to become available */ spin_lock_irq(&common->lock); bh = common->next_buffhd_to_fill; while (bh->state != BUF_STATE_EMPTY) { spin_unlock_irq(&common->lock); rc = sleep_thread(common, true); if (rc) return rc; spin_lock_irq(&common->lock); } spin_unlock_irq(&common->lock); if (curlun) { sd = curlun->sense_data; sdinfo = curlun->sense_data_info; } else if (common->bad_lun_okay) sd = SS_NO_SENSE; else sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; if (common->phase_error) { DBG(common, "sending phase-error status\n"); status = US_BULK_STAT_PHASE; sd = SS_INVALID_COMMAND; } else if (sd != SS_NO_SENSE) { DBG(common, "sending command-failure status\n"); status = US_BULK_STAT_FAIL; VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;" " info x%x\n", SK(sd), ASC(sd), ASCQ(sd), sdinfo); } /* Store and send the Bulk-only CSW */ csw = (void *)bh->buf; csw->Signature = cpu_to_le32(US_BULK_CS_SIGN); csw->Tag = common->tag; csw->Residue = cpu_to_le32(common->residue); /* * Since csw is being sent early, before * writing on to storage media, need to set * residue to zero,assuming that write will succeed. */ if (write_error_after_csw_sent || must_report_residue) { write_error_after_csw_sent = 0; must_report_residue = 0; } else csw->Residue = 0; csw->Status = status; bh->inreq->length = US_BULK_CS_WRAP_LEN; bh->inreq->zero = 0; if (!start_in_transfer(common, bh)) /* Don't know what to do if common->fsg is NULL */ return -EIO; common->next_buffhd_to_fill = bh->next; return 0; } /*-------------------------------------------------------------------------*/ /* * Check whether the command is properly formed and whether its data size * and direction agree with the values we already have. */ static int check_command(struct fsg_common *common, int cmnd_size, enum data_direction data_dir, unsigned int mask, int needs_medium, const char *name) { int i; unsigned int lun = common->cmnd[1] >> 5; static const char dirletter[4] = {'u', 'o', 'i', 'n'}; char hdlen[20]; struct fsg_lun *curlun; hdlen[0] = 0; if (common->data_dir != DATA_DIR_UNKNOWN) sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir], common->data_size); VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n", name, cmnd_size, dirletter[(int) data_dir], common->data_size_from_cmnd, common->cmnd_size, hdlen); /* * We can't reply at all until we know the correct data direction * and size. */ if (common->data_size_from_cmnd == 0) data_dir = DATA_DIR_NONE; if (common->data_size < common->data_size_from_cmnd) { /* * Host data size < Device data size is a phase error. * Carry out the command, but only transfer as much as * we are allowed. */ common->data_size_from_cmnd = common->data_size; common->phase_error = 1; } common->residue = common->data_size; common->usb_amount_left = common->data_size; /* Conflicting data directions is a phase error */ if (common->data_dir != data_dir && common->data_size_from_cmnd > 0) { common->phase_error = 1; return -EINVAL; } /* Verify the length of the command itself */ if (cmnd_size != common->cmnd_size) { /* * Special case workaround: There are plenty of buggy SCSI * implementations. Many have issues with cbw->Length * field passing a wrong command size. For those cases we * always try to work around the problem by using the length * sent by the host side provided it is at least as large * as the correct command length. * Examples of such cases would be MS-Windows, which issues * REQUEST SENSE with cbw->Length == 12 where it should * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and * REQUEST SENSE with cbw->Length == 10 where it should * be 6 as well. */ if (cmnd_size <= common->cmnd_size) { DBG(common, "%s is buggy! Expected length %d " "but we got %d\n", name, cmnd_size, common->cmnd_size); cmnd_size = common->cmnd_size; } else { common->phase_error = 1; return -EINVAL; } } /* Check that the LUN values are consistent */ if (common->lun != lun) DBG(common, "using LUN %u from CBW, not LUN %u from CDB\n", common->lun, lun); /* Check the LUN */ curlun = common->curlun; if (curlun) { if (common->cmnd[0] != REQUEST_SENSE) { curlun->sense_data = SS_NO_SENSE; curlun->sense_data_info = 0; curlun->info_valid = 0; } } else { common->bad_lun_okay = 0; /* * INQUIRY and REQUEST SENSE commands are explicitly allowed * to use unsupported LUNs; all others may not. */ if (common->cmnd[0] != INQUIRY && common->cmnd[0] != REQUEST_SENSE) { DBG(common, "unsupported LUN %u\n", common->lun); return -EINVAL; } } /* * If a unit attention condition exists, only INQUIRY and * REQUEST SENSE commands are allowed; anything else must fail. */ if (curlun && curlun->unit_attention_data != SS_NO_SENSE && common->cmnd[0] != INQUIRY && common->cmnd[0] != REQUEST_SENSE) { curlun->sense_data = curlun->unit_attention_data; curlun->unit_attention_data = SS_NO_SENSE; return -EINVAL; } /* Check that only command bytes listed in the mask are non-zero */ common->cmnd[1] &= 0x1f; /* Mask away the LUN */ for (i = 1; i < cmnd_size; ++i) { if (common->cmnd[i] && !(mask & (1 << i))) { if (curlun) curlun->sense_data = SS_INVALID_FIELD_IN_CDB; return -EINVAL; } } /* If the medium isn't mounted and the command needs to access * it, return an error. */ if (curlun && !fsg_lun_is_open(curlun) && needs_medium) { curlun->sense_data = SS_MEDIUM_NOT_PRESENT; return -EINVAL; } return 0; } /* wrapper of check_command for data size in blocks handling */ static int check_command_size_in_blocks(struct fsg_common *common, int cmnd_size, enum data_direction data_dir, unsigned int mask, int needs_medium, const char *name) { if (common->curlun) common->data_size_from_cmnd <<= common->curlun->blkbits; return check_command(common, cmnd_size, data_dir, mask, needs_medium, name); } static int do_scsi_command(struct fsg_common *common) { struct fsg_buffhd *bh; int rc; int reply = -EINVAL; int i; static char unknown[16]; dump_cdb(common); /* Wait for the next buffer to become available for data or status */ spin_lock_irq(&common->lock); bh = common->next_buffhd_to_fill; common->next_buffhd_to_drain = bh; while (bh->state != BUF_STATE_EMPTY) { spin_unlock_irq(&common->lock); rc = sleep_thread(common, true); if (rc) return rc; spin_lock_irq(&common->lock); } spin_unlock_irq(&common->lock); common->phase_error = 0; common->short_packet_received = 0; down_read(&common->filesem); /* We're using the backing file */ switch (common->cmnd[0]) { case INQUIRY: common->data_size_from_cmnd = common->cmnd[4]; reply = check_command(common, 6, DATA_DIR_TO_HOST, (1<<4), 0, "INQUIRY"); if (reply == 0) reply = do_inquiry(common, bh); break; #ifdef CONFIG_LGE_USB_G_AUTORUN case SC_LGE_SPE: pr_info("%s : SC_LGE_SPE - %x %x %x\n", __func__, common->cmnd[0], common->cmnd[1], common->cmnd[2]); common->mode_state = MODE_STATE_UNKNOWN; switch (common->cmnd[1]) { case SUB_CODE_MODE_CHANGE: switch (common->cmnd[2]) { case TYPE_MOD_CHG_TO_ACM: case TYPE_MOD_CHG2_TO_ACM: common->mode_state = MODE_STATE_ACM; break; case TYPE_MOD_CHG_TO_UMS: case TYPE_MOD_CHG2_TO_UMS: common->mode_state = MODE_STATE_UMS; break; case TYPE_MOD_CHG_TO_MTP: case TYPE_MOD_CHG2_TO_MTP: common->mode_state = MODE_STATE_MTP; break; case TYPE_MOD_CHG_TO_ASK: case TYPE_MOD_CHG2_TO_ASK: common->mode_state = MODE_STATE_ASK; break; case TYPE_MOD_CHG_TO_CGO: case TYPE_MOD_CHG2_TO_CGO: common->mode_state = MODE_STATE_CGO; break; case TYPE_MOD_CHG_TO_TET: case TYPE_MOD_CHG2_TO_TET: common->mode_state = MODE_STATE_TET; break; case TYPE_MOD_CHG_TO_FDG: case TYPE_MOD_CHG2_TO_FDG: common->mode_state = MODE_STATE_FDG; break; case TYPE_MOD_CHG_TO_PTP: case TYPE_MOD_CHG2_TO_PTP: common->mode_state = MODE_STATE_PTP; break; #if defined(CONFIG_LGE_USB_G_AUTORUN_VZW) && defined(CONFIG_LGE_USB_G_MULTIPLE_CONFIGURATION) case TYPE_MOD_CHG_TO_MUL: case TYPE_MOD_CHG2_TO_MUL: common->mode_state = MODE_STATE_MUL; break; #endif case TYPE_MOD_CHG_TO_MIDI: case TYPE_MOD_CHG2_TO_MIDI: common->mode_state = MODE_STATE_MIDI; break; default: common->mode_state = MODE_STATE_UNKNOWN; } pr_info("%s: SC_LGE_MODE - %d\n", __func__, common->mode_state); #ifndef CONFIG_LGE_USB_G_AUTORUN_VZW kobject_uevent_env(&autorun_device.this_device->kobj, KOBJ_CHANGE, envp_mode); #else kobject_uevent_env(&autorun_device.this_device->kobj, KOBJ_CHANGE, (char **)(&envp_mode[common->mode_state])); #endif already_acked = 0; reply = 0; break; case SUB_CODE_GET_VALUE: switch (common->cmnd[2]) { case ACK_STATUS_TO_HOST: /* 0xf1 0x02 0x10 */ /* If some error exists, we set default mode to ACM mode */ common->mode_state = MODE_STATE_GET_VALUE; if (user_mode >= ACK_STATUS_ERR) { pr_err("%s [AUTORUN] : Error on user mode setting, set default mode (ACM)\n" , __func__); user_mode = ACK_STATUS_ACM; } else pr_info("%s [AUTORUN] : send user mode to PC %d\n" , __func__, user_mode); common->data_size_from_cmnd = 1; reply = check_command(common, 6, DATA_DIR_TO_HOST, (7<<1), 1, "ACK_STATUS"); if (reply == 0) reply = do_ack_status(common, bh, user_mode); if (!already_acked) { kobject_uevent_env( &autorun_device.this_device->kobj, KOBJ_CHANGE, envp_ack); already_acked = 1; } break; case ACK_SW_REV_TO_HOST: /* 0xf1 0x02 0x12 */ common->data_size_from_cmnd = 9; reply = check_command(common, 6, DATA_DIR_TO_HOST, (7<<1), 1, "ACK_SW_REV"); if (reply == 0) reply = do_get_sw_ver(common, bh); break; case ACK_MEID_TO_HOST: /* 0xf1 0x02 0x13 */ common->data_size_from_cmnd = 7; reply = check_command(common, 6, DATA_DIR_TO_HOST, (7<<1), 1, "ACK_SERIAL"); if (reply == 0) reply = do_get_serial(common, bh); break; case ACK_MODEL_TO_HOST: /* 0xf1 0x02 0x14 */ common->data_size_from_cmnd = 7; reply = check_command(common, 6, DATA_DIR_TO_HOST, (7<<1), 1, "ACK_MODEL_NAME"); if (reply == 0) reply = do_get_model(common, bh); break; case ACK_SUB_VER_TO_HOST: /* 0xf1 0x02 0x15 */ common->data_size_from_cmnd = 1; reply = check_command(common, 6, DATA_DIR_TO_HOST, (7<<1), 1, "ACK_SUB_VERSION"); if (reply == 0) reply = do_get_sub_ver(common, bh); break; default: break; } break; case SUB_CODE_PROBE_DEV: common->mode_state = MODE_STATE_PROBE_DEV; reply = 0; break; default: common->mode_state = MODE_STATE_UNKNOWN; reply = 0; break; } /* switch (common->cmnd[1]) */ break; #endif /* CONFIG_LGE_USB_G_AUTORUN */ case MODE_SELECT: common->data_size_from_cmnd = common->cmnd[4]; reply = check_command(common, 6, DATA_DIR_FROM_HOST, (1<<1) | (1<<4), 0, "MODE SELECT(6)"); if (reply == 0) reply = do_mode_select(common, bh); break; case MODE_SELECT_10: common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); reply = check_command(common, 10, DATA_DIR_FROM_HOST, (1<<1) | (3<<7), 0, "MODE SELECT(10)"); if (reply == 0) reply = do_mode_select(common, bh); break; case MODE_SENSE: common->data_size_from_cmnd = common->cmnd[4]; reply = check_command(common, 6, DATA_DIR_TO_HOST, (1<<1) | (1<<2) | (1<<4), 0, "MODE SENSE(6)"); if (reply == 0) reply = do_mode_sense(common, bh); break; case MODE_SENSE_10: common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); reply = check_command(common, 10, DATA_DIR_TO_HOST, (1<<1) | (1<<2) | (3<<7), 0, "MODE SENSE(10)"); if (reply == 0) reply = do_mode_sense(common, bh); break; case ALLOW_MEDIUM_REMOVAL: common->data_size_from_cmnd = 0; reply = check_command(common, 6, DATA_DIR_NONE, (1<<4), 0, "PREVENT-ALLOW MEDIUM REMOVAL"); if (reply == 0) reply = do_prevent_allow(common); break; case READ_6: i = common->cmnd[4]; common->data_size_from_cmnd = (i == 0) ? 256 : i; reply = check_command_size_in_blocks(common, 6, DATA_DIR_TO_HOST, (7<<1) | (1<<4), 1, "READ(6)"); if (reply == 0) reply = do_read(common); break; case READ_10: common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); reply = check_command_size_in_blocks(common, 10, DATA_DIR_TO_HOST, (1<<1) | (0xf<<2) | (3<<7), 1, "READ(10)"); if (reply == 0) reply = do_read(common); break; case READ_12: common->data_size_from_cmnd = get_unaligned_be32(&common->cmnd[6]); reply = check_command_size_in_blocks(common, 12, DATA_DIR_TO_HOST, (1<<1) | (0xf<<2) | (0xf<<6), 1, "READ(12)"); if (reply == 0) reply = do_read(common); break; case READ_CAPACITY: common->data_size_from_cmnd = 8; reply = check_command(common, 10, DATA_DIR_TO_HOST, (0xf<<2) | (1<<8), 1, "READ CAPACITY"); if (reply == 0) reply = do_read_capacity(common, bh); break; case READ_HEADER: if (!common->curlun || !common->curlun->cdrom) goto unknown_cmnd; common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); reply = check_command(common, 10, DATA_DIR_TO_HOST, (3<<7) | (0x1f<<1), 1, "READ HEADER"); if (reply == 0) reply = do_read_header(common, bh); break; case READ_TOC: if (!common->curlun || !common->curlun->cdrom) goto unknown_cmnd; common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); #ifdef CONFIG_LGE_USB_G_CDROM_MAC_SUPPORT reply = check_command(common, 10, DATA_DIR_TO_HOST, (0xf<<6) | (1<<1), 1, "READ TOC"); #else /* original */ reply = check_command(common, 10, DATA_DIR_TO_HOST, (7<<6) | (1<<1), 1, "READ TOC"); #endif if (reply == 0) reply = do_read_toc(common, bh); break; case READ_FORMAT_CAPACITIES: common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); reply = check_command(common, 10, DATA_DIR_TO_HOST, (3<<7), 1, "READ FORMAT CAPACITIES"); if (reply == 0) reply = do_read_format_capacities(common, bh); break; case REQUEST_SENSE: common->data_size_from_cmnd = common->cmnd[4]; reply = check_command(common, 6, DATA_DIR_TO_HOST, (1<<4), 0, "REQUEST SENSE"); if (reply == 0) reply = do_request_sense(common, bh); break; case START_STOP: common->data_size_from_cmnd = 0; reply = check_command(common, 6, DATA_DIR_NONE, (1<<1) | (1<<4), 0, "START-STOP UNIT"); if (reply == 0) reply = do_start_stop(common); break; case SYNCHRONIZE_CACHE: common->data_size_from_cmnd = 0; reply = check_command(common, 10, DATA_DIR_NONE, (0xf<<2) | (3<<7), 1, "SYNCHRONIZE CACHE"); if (reply == 0) reply = do_synchronize_cache(common); break; case TEST_UNIT_READY: common->data_size_from_cmnd = 0; reply = check_command(common, 6, DATA_DIR_NONE, 0, 1, "TEST UNIT READY"); break; /* * Although optional, this command is used by MS-Windows. We * support a minimal version: BytChk must be 0. */ case VERIFY: common->data_size_from_cmnd = 0; reply = check_command(common, 10, DATA_DIR_NONE, (1<<1) | (0xf<<2) | (3<<7), 1, "VERIFY"); if (reply == 0) reply = do_verify(common); break; case WRITE_6: i = common->cmnd[4]; common->data_size_from_cmnd = (i == 0) ? 256 : i; reply = check_command_size_in_blocks(common, 6, DATA_DIR_FROM_HOST, (7<<1) | (1<<4), 1, "WRITE(6)"); if (reply == 0) reply = do_write(common); break; case WRITE_10: common->data_size_from_cmnd = get_unaligned_be16(&common->cmnd[7]); reply = check_command_size_in_blocks(common, 10, DATA_DIR_FROM_HOST, (1<<1) | (0xf<<2) | (3<<7), 1, "WRITE(10)"); if (reply == 0) reply = do_write(common); break; case WRITE_12: common->data_size_from_cmnd = get_unaligned_be32(&common->cmnd[6]); reply = check_command_size_in_blocks(common, 12, DATA_DIR_FROM_HOST, (1<<1) | (0xf<<2) | (0xf<<6), 1, "WRITE(12)"); if (reply == 0) reply = do_write(common); break; /* * Some mandatory commands that we recognize but don't implement. * They don't mean much in this setting. It's left as an exercise * for anyone interested to implement RESERVE and RELEASE in terms * of Posix locks. */ case FORMAT_UNIT: case RELEASE: case RESERVE: case SEND_DIAGNOSTIC: /* Fall through */ default: unknown_cmnd: common->data_size_from_cmnd = 0; sprintf(unknown, "Unknown x%02x", common->cmnd[0]); reply = check_command(common, common->cmnd_size, DATA_DIR_UNKNOWN, ~0, 0, unknown); if (reply == 0) { common->curlun->sense_data = SS_INVALID_COMMAND; reply = -EINVAL; } break; } up_read(&common->filesem); if (reply == -EINTR || signal_pending(current)) return -EINTR; /* Set up the single reply buffer for finish_reply() */ if (reply == -EINVAL) reply = 0; /* Error reply length */ if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) { reply = min((u32)reply, common->data_size_from_cmnd); bh->inreq->length = reply; bh->state = BUF_STATE_FULL; common->residue -= reply; } /* Otherwise it's already set */ return 0; } /*-------------------------------------------------------------------------*/ static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh) { struct usb_request *req = bh->outreq; struct bulk_cb_wrap *cbw = req->buf; struct fsg_common *common = fsg->common; /* Was this a real packet? Should it be ignored? */ if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags)) return -EINVAL; /* Is the CBW valid? */ if (req->actual != US_BULK_CB_WRAP_LEN || cbw->Signature != cpu_to_le32( US_BULK_CB_SIGN)) { DBG(fsg, "invalid CBW: len %u sig 0x%x\n", req->actual, le32_to_cpu(cbw->Signature)); /* * The Bulk-only spec says we MUST stall the IN endpoint * (6.6.1), so it's unavoidable. It also says we must * retain this state until the next reset, but there's * no way to tell the controller driver it should ignore * Clear-Feature(HALT) requests. * * We aren't required to halt the OUT endpoint; instead * we can simply accept and discard any data received * until the next reset. */ wedge_bulk_in_endpoint(fsg); set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags); return -EINVAL; } /* Is the CBW meaningful? */ if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~US_BULK_FLAG_IN || cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) { DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, " "cmdlen %u\n", cbw->Lun, cbw->Flags, cbw->Length); /* * We can do anything we want here, so let's stall the * bulk pipes if we are allowed to. */ if (common->can_stall) { fsg_set_halt(fsg, fsg->bulk_out); halt_bulk_in_endpoint(fsg); } return -EINVAL; } /* Save the command for later */ common->cmnd_size = cbw->Length; memcpy(common->cmnd, cbw->CDB, common->cmnd_size); if (cbw->Flags & US_BULK_FLAG_IN) common->data_dir = DATA_DIR_TO_HOST; else common->data_dir = DATA_DIR_FROM_HOST; common->data_size = le32_to_cpu(cbw->DataTransferLength); if (common->data_size == 0) common->data_dir = DATA_DIR_NONE; common->lun = cbw->Lun; if (common->lun < common->nluns) common->curlun = common->luns[common->lun]; else common->curlun = NULL; common->tag = cbw->Tag; return 0; } static int get_next_command(struct fsg_common *common) { struct fsg_buffhd *bh; int rc = 0; /* Wait for the next buffer to become available */ spin_lock_irq(&common->lock); bh = common->next_buffhd_to_fill; while (bh->state != BUF_STATE_EMPTY) { spin_unlock_irq(&common->lock); rc = sleep_thread(common, true); if (rc) return rc; spin_lock_irq(&common->lock); } spin_unlock_irq(&common->lock); /* Queue a request to read a Bulk-only CBW */ set_bulk_out_req_length(common, bh, US_BULK_CB_WRAP_LEN); if (!start_out_transfer(common, bh)) /* Don't know what to do if common->fsg is NULL */ return -EIO; /* * We will drain the buffer in software, which means we * can reuse it for the next filling. No need to advance * next_buffhd_to_fill. */ /* Wait for the CBW to arrive */ spin_lock_irq(&common->lock); while (bh->state != BUF_STATE_FULL) { spin_unlock_irq(&common->lock); rc = sleep_thread(common, true); if (rc) return rc; spin_lock_irq(&common->lock); } spin_unlock_irq(&common->lock); smp_rmb(); rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO; spin_lock_irq(&common->lock); bh->state = BUF_STATE_EMPTY; spin_unlock_irq(&common->lock); return rc; } /*-------------------------------------------------------------------------*/ static int alloc_request(struct fsg_common *common, struct usb_ep *ep, struct usb_request **preq) { *preq = usb_ep_alloc_request(ep, GFP_ATOMIC); if (*preq) return 0; ERROR(common, "can't allocate request for %s\n", ep->name); return -ENOMEM; } /* Reset interface setting and re-init endpoint state (toggle etc). */ static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg) { struct fsg_dev *fsg; int i, rc = 0; if (common->running) DBG(common, "reset interface\n"); reset: /* Deallocate the requests */ if (common->fsg) { fsg = common->fsg; for (i = 0; i < common->fsg_num_buffers; ++i) { struct fsg_buffhd *bh = &common->buffhds[i]; if (bh->inreq) { usb_ep_free_request(fsg->bulk_in, bh->inreq); bh->inreq = NULL; } if (bh->outreq) { usb_ep_free_request(fsg->bulk_out, bh->outreq); bh->outreq = NULL; } } common->fsg = NULL; wake_up(&common->fsg_wait); } common->running = 0; if (!new_fsg || rc) return rc; common->fsg = new_fsg; fsg = common->fsg; /* Allocate the requests */ for (i = 0; i < common->fsg_num_buffers; ++i) { struct fsg_buffhd *bh = &common->buffhds[i]; rc = alloc_request(common, fsg->bulk_in, &bh->inreq); if (rc) goto reset; rc = alloc_request(common, fsg->bulk_out, &bh->outreq); if (rc) goto reset; bh->inreq->buf = bh->outreq->buf = bh->buf; bh->inreq->context = bh->outreq->context = bh; bh->inreq->complete = bulk_in_complete; bh->outreq->complete = bulk_out_complete; } common->running = 1; for (i = 0; i < common->nluns; ++i) if (common->luns[i]) common->luns[i]->unit_attention_data = SS_RESET_OCCURRED; return rc; } /****************************** ALT CONFIGS ******************************/ static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt) { struct fsg_dev *fsg = fsg_from_func(f); struct fsg_common *common = fsg->common; int rc; /* Enable the endpoints */ rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_in); if (rc) goto err_exit; rc = usb_ep_enable(fsg->bulk_in); if (rc) goto err_exit; fsg->bulk_in->driver_data = common; fsg->bulk_in_enabled = 1; rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_out); if (rc) goto reset_bulk_int; rc = usb_ep_enable(fsg->bulk_out); if (rc) goto reset_bulk_int; fsg->bulk_out->driver_data = common; fsg->bulk_out_enabled = 1; common->bulk_out_maxpacket = usb_endpoint_maxp(fsg->bulk_out->desc); clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags); csw_sent = 0; write_error_after_csw_sent = 0; fsg->common->new_fsg = fsg; raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); return USB_GADGET_DELAYED_STATUS; reset_bulk_int: usb_ep_disable(fsg->bulk_in); fsg->bulk_in_enabled = 0; err_exit: return rc; } static void fsg_disable(struct usb_function *f) { struct fsg_dev *fsg = fsg_from_func(f); /* Disable the endpoints */ if (fsg->bulk_in_enabled) { usb_ep_disable(fsg->bulk_in); fsg->bulk_in->driver_data = NULL; fsg->bulk_in_enabled = 0; } if (fsg->bulk_out_enabled) { usb_ep_disable(fsg->bulk_out); fsg->bulk_out->driver_data = NULL; fsg->bulk_out_enabled = 0; } fsg->common->new_fsg = NULL; raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); } /*-------------------------------------------------------------------------*/ static void handle_exception(struct fsg_common *common) { siginfo_t info; int i; struct fsg_buffhd *bh; enum fsg_state old_state; struct fsg_lun *curlun; unsigned int exception_req_tag; unsigned long flags; /* * Clear the existing signals. Anything but SIGUSR1 is converted * into a high-priority EXIT exception. */ for (;;) { int sig = dequeue_signal_lock(current, &current->blocked, &info); if (!sig) break; if (sig != SIGUSR1) { if (common->state < FSG_STATE_EXIT) DBG(common, "Main thread exiting on signal\n"); WARN_ON(1); pr_err("%s: signal(%d) received from PID(%d) UID(%d)\n", __func__, sig, info.si_pid, info.si_uid); raise_exception(common, FSG_STATE_EXIT); } } /* Cancel all the pending transfers */ if (likely(common->fsg)) { for (i = 0; i < common->fsg_num_buffers; ++i) { bh = &common->buffhds[i]; if (bh->inreq_busy) usb_ep_dequeue(common->fsg->bulk_in, bh->inreq); if (bh->outreq_busy) usb_ep_dequeue(common->fsg->bulk_out, bh->outreq); } /* Wait until everything is idle */ for (;;) { int num_active = 0; spin_lock_irq(&common->lock); for (i = 0; i < common->fsg_num_buffers; ++i) { bh = &common->buffhds[i]; #ifdef CONFIG_LGE_USB_G_AUTORUN if (common->fsg->bulk_in->desc == NULL) bh->inreq_busy = 0; if (common->fsg->bulk_out->desc == NULL) bh->outreq_busy = 0; #endif num_active += bh->inreq_busy + bh->outreq_busy; } spin_unlock_irq(&common->lock); if (num_active == 0) break; if (sleep_thread(common, true)) return; } /* Clear out the controller's fifos */ if (common->fsg->bulk_in_enabled) usb_ep_fifo_flush(common->fsg->bulk_in); if (common->fsg->bulk_out_enabled) usb_ep_fifo_flush(common->fsg->bulk_out); } /* * Reset the I/O buffer states and pointers, the SCSI * state, and the exception. Then invoke the handler. */ spin_lock_irqsave(&common->lock, flags); for (i = 0; i < common->fsg_num_buffers; ++i) { bh = &common->buffhds[i]; bh->state = BUF_STATE_EMPTY; } common->next_buffhd_to_fill = &common->buffhds[0]; common->next_buffhd_to_drain = &common->buffhds[0]; exception_req_tag = common->exception_req_tag; old_state = common->state; if (old_state == FSG_STATE_ABORT_BULK_OUT) common->state = FSG_STATE_STATUS_PHASE; else { for (i = 0; i < common->nluns; ++i) { curlun = common->luns[i]; if (!curlun) continue; curlun->prevent_medium_removal = 0; curlun->sense_data = SS_NO_SENSE; curlun->unit_attention_data = SS_NO_SENSE; curlun->sense_data_info = 0; curlun->info_valid = 0; } common->state = FSG_STATE_IDLE; } spin_unlock_irqrestore(&common->lock, flags); /* Carry out any extra actions required for the exception */ switch (old_state) { case FSG_STATE_ABORT_BULK_OUT: send_status(common); spin_lock_irq(&common->lock); if (common->state == FSG_STATE_STATUS_PHASE) common->state = FSG_STATE_IDLE; spin_unlock_irq(&common->lock); break; case FSG_STATE_RESET: /* * In case we were forced against our will to halt a * bulk endpoint, clear the halt now. (The SuperH UDC * requires this.) */ if (!fsg_is_set(common)) break; if (test_and_clear_bit(IGNORE_BULK_OUT, &common->fsg->atomic_bitflags)) usb_ep_clear_halt(common->fsg->bulk_in); if (common->ep0_req_tag == exception_req_tag) { /* Complete the status stage */ if (common->cdev) usb_composite_setup_continue(common->cdev); else ep0_queue(common); } /* * Technically this should go here, but it would only be * a waste of time. Ditto for the INTERFACE_CHANGE and * CONFIG_CHANGE cases. */ /* for (i = 0; i < common->nluns; ++i) */ /* if (common->luns[i]) */ /* common->luns[i]->unit_attention_data = */ /* SS_RESET_OCCURRED; */ break; case FSG_STATE_CONFIG_CHANGE: do_set_interface(common, common->new_fsg); if (common->new_fsg) usb_composite_setup_continue(common->cdev); break; case FSG_STATE_EXIT: case FSG_STATE_TERMINATED: do_set_interface(common, NULL); /* Free resources */ spin_lock_irq(&common->lock); common->state = FSG_STATE_TERMINATED; /* Stop the thread */ spin_unlock_irq(&common->lock); break; case FSG_STATE_INTERFACE_CHANGE: case FSG_STATE_DISCONNECT: case FSG_STATE_COMMAND_PHASE: case FSG_STATE_DATA_PHASE: case FSG_STATE_STATUS_PHASE: case FSG_STATE_IDLE: break; } } /*-------------------------------------------------------------------------*/ static int fsg_main_thread(void *common_) { struct fsg_common *common = common_; /* * Allow the thread to be killed by a signal, but set the signal mask * to block everything but INT, TERM, KILL, and USR1. */ allow_signal(SIGINT); allow_signal(SIGTERM); allow_signal(SIGKILL); allow_signal(SIGUSR1); /* Allow the thread to be frozen */ set_freezable(); /* * Arrange for userspace references to be interpreted as kernel * pointers. That way we can pass a kernel pointer to a routine * that expects a __user pointer and it will work okay. */ set_fs(get_ds()); /* The main loop */ while (common->state != FSG_STATE_TERMINATED) { if (exception_in_progress(common) || signal_pending(current)) { handle_exception(common); continue; } if (!common->running) { sleep_thread(common, true); continue; } if (get_next_command(common)) continue; spin_lock_irq(&common->lock); if (!exception_in_progress(common)) common->state = FSG_STATE_DATA_PHASE; spin_unlock_irq(&common->lock); if (do_scsi_command(common) || finish_reply(common)) continue; spin_lock_irq(&common->lock); if (!exception_in_progress(common)) common->state = FSG_STATE_STATUS_PHASE; spin_unlock_irq(&common->lock); /* * Since status is already sent for write scsi command, * need to skip sending status once again if it is a * write scsi command. */ if (csw_sent) { csw_sent = 0; continue; } if (send_status(common)) continue; spin_lock_irq(&common->lock); if (!exception_in_progress(common)) common->state = FSG_STATE_IDLE; spin_unlock_irq(&common->lock); } spin_lock_irq(&common->lock); common->thread_task = NULL; spin_unlock_irq(&common->lock); if (!common->ops || !common->ops->thread_exits || common->ops->thread_exits(common) < 0) { struct fsg_lun **curlun_it = common->luns; unsigned i = common->nluns; down_write(&common->filesem); for (; i--; ++curlun_it) { struct fsg_lun *curlun = *curlun_it; if (!curlun || !fsg_lun_is_open(curlun)) continue; fsg_lun_close(curlun); curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT; } up_write(&common->filesem); } /* Let fsg_unbind() know the thread has exited */ complete_and_exit(&common->thread_notifier, 0); } #ifdef CONFIG_LGE_USB_G_AUTORUN static ssize_t fsg_show_usbmode(struct device *dev, struct device_attribute *attr, char *buf) { int ret; ret = snprintf(buf, PAGE_SIZE, "%d", user_mode); pr_info("autorun read user mode : %d\n", user_mode); return ret; } static ssize_t fsg_store_usbmode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret = 0; unsigned long tmp; ret = kstrtoul(buf, 10, &tmp); if (ret) return -EINVAL; mutex_lock(&autorun_lock); user_mode = (unsigned int)tmp; mutex_unlock(&autorun_lock); pr_info("autorun write user mode : %d\n", user_mode); return count; } #endif /*************************** DEVICE ATTRIBUTES ***************************/ #ifdef CONFIG_LGE_USB_G_AUTORUN static DEVICE_ATTR(cdrom_usbmode, 0664, fsg_show_usbmode, fsg_store_usbmode); #endif static ssize_t ro_show(struct device *dev, struct device_attribute *attr, char *buf) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); return fsg_show_ro(curlun, buf); } static ssize_t nofua_show(struct device *dev, struct device_attribute *attr, char *buf) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); return fsg_show_nofua(curlun, buf); } static ssize_t file_show(struct device *dev, struct device_attribute *attr, char *buf) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); struct rw_semaphore *filesem = dev_get_drvdata(dev); return fsg_show_file(curlun, filesem, buf); } static ssize_t ro_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); struct rw_semaphore *filesem = dev_get_drvdata(dev); return fsg_store_ro(curlun, filesem, buf, count); } static ssize_t nofua_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); return fsg_store_nofua(curlun, buf, count); } static ssize_t file_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); struct rw_semaphore *filesem = dev_get_drvdata(dev); return fsg_store_file(curlun, filesem, buf, count); } static DEVICE_ATTR_RW(ro); static DEVICE_ATTR_RW(nofua); static DEVICE_ATTR_RW(file); DEVICE_ATTR(perf, 0644, fsg_show_perf, fsg_store_perf); static struct device_attribute dev_attr_ro_cdrom = __ATTR_RO(ro); static struct device_attribute dev_attr_file_nonremovable = __ATTR_RO(file); /****************************** FSG COMMON ******************************/ static void fsg_common_release(struct kref *ref); static void fsg_lun_release(struct device *dev) { /* Nothing needs to be done */ } void fsg_common_get(struct fsg_common *common) { kref_get(&common->ref); } EXPORT_SYMBOL_GPL(fsg_common_get); void fsg_common_put(struct fsg_common *common) { kref_put(&common->ref, fsg_common_release); } EXPORT_SYMBOL_GPL(fsg_common_put); /* check if fsg_num_buffers is within a valid range */ static inline int fsg_num_buffers_validate(unsigned int fsg_num_buffers) { if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4) return 0; pr_err("fsg_num_buffers %u is out of range (%d to %d)\n", fsg_num_buffers, 2, 4); return -EINVAL; } static struct fsg_common *fsg_common_setup(struct fsg_common *common) { if (!common) { common = kzalloc(sizeof(*common), GFP_KERNEL); if (!common) return ERR_PTR(-ENOMEM); common->free_storage_on_release = 1; } else { common->free_storage_on_release = 0; } init_rwsem(&common->filesem); spin_lock_init(&common->lock); kref_init(&common->ref); init_completion(&common->thread_notifier); init_waitqueue_head(&common->fsg_wait); common->state = FSG_STATE_TERMINATED; return common; } void fsg_common_set_sysfs(struct fsg_common *common, bool sysfs) { common->sysfs = sysfs; } EXPORT_SYMBOL_GPL(fsg_common_set_sysfs); static void _fsg_common_free_buffers(struct fsg_buffhd *buffhds, unsigned n) { if (buffhds) { struct fsg_buffhd *bh = buffhds; while (n--) { kfree(bh->buf); ++bh; } kfree(buffhds); } } int fsg_common_set_num_buffers(struct fsg_common *common, unsigned int n) { struct fsg_buffhd *bh, *buffhds; int i, rc; size_t extra_buf_alloc = 0; if (common->gadget) extra_buf_alloc = common->gadget->extra_buf_alloc; rc = fsg_num_buffers_validate(n); if (rc != 0) return rc; buffhds = kcalloc(n, sizeof(*buffhds), GFP_KERNEL); if (!buffhds) return -ENOMEM; /* Data buffers cyclic list */ bh = buffhds; i = n; goto buffhds_first_it; do { bh->next = bh + 1; ++bh; buffhds_first_it: bh->buf = kmalloc(FSG_BUFLEN + extra_buf_alloc, GFP_KERNEL); if (unlikely(!bh->buf)) goto error_release; } while (--i); bh->next = buffhds; _fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers); common->fsg_num_buffers = n; common->buffhds = buffhds; return 0; error_release: /* * "buf"s pointed to by heads after n - i are NULL * so releasing them won't hurt */ _fsg_common_free_buffers(buffhds, n); return -ENOMEM; } EXPORT_SYMBOL_GPL(fsg_common_set_num_buffers); static inline void fsg_common_remove_sysfs(struct fsg_lun *lun) { device_remove_file(&lun->dev, &dev_attr_nofua); /* * device_remove_file() => * * here the attr (e.g. dev_attr_ro) is only used to be passed to: * * sysfs_remove_file() => * * here e.g. both dev_attr_ro_cdrom and dev_attr_ro are in * the same namespace and * from here only attr->name is passed to: * * sysfs_hash_and_remove() * * attr->name is the same for dev_attr_ro_cdrom and * dev_attr_ro * attr->name is the same for dev_attr_file and * dev_attr_file_nonremovable * * so we don't differentiate between removing e.g. dev_attr_ro_cdrom * and dev_attr_ro */ device_remove_file(&lun->dev, &dev_attr_ro); device_remove_file(&lun->dev, &dev_attr_file); #ifdef CONFIG_LGE_USB_G_AUTORUN device_remove_file(&lun->dev, &dev_attr_cdrom_usbmode); #endif } void fsg_common_remove_lun(struct fsg_lun *lun, bool sysfs) { #ifdef CONFIG_LGE_USB_G_AUTORUN int rc; /* if fsg common object is cdrom, deregister autorun misc device */ if (lun->cdrom) { rc = misc_deregister(&autorun_device); if (rc) { pr_err("USB cdrom gadget driver failed to deinitialize\n"); } } #endif if (sysfs) { fsg_common_remove_sysfs(lun); device_unregister(&lun->dev); } fsg_lun_close(lun); kfree(lun); } EXPORT_SYMBOL_GPL(fsg_common_remove_lun); static void _fsg_common_remove_luns(struct fsg_common *common, int n) { int i; for (i = 0; i < n; ++i) if (common->luns[i]) { fsg_common_remove_lun(common->luns[i], common->sysfs); common->luns[i] = NULL; } } EXPORT_SYMBOL_GPL(fsg_common_remove_luns); void fsg_common_remove_luns(struct fsg_common *common) { _fsg_common_remove_luns(common, common->nluns); } void fsg_common_free_luns(struct fsg_common *common) { unsigned long flags; fsg_common_remove_luns(common); spin_lock_irqsave(&common->lock, flags); kfree(common->luns); common->luns = NULL; common->nluns = 0; spin_unlock_irqrestore(&common->lock, flags); } EXPORT_SYMBOL_GPL(fsg_common_free_luns); int fsg_common_set_nluns(struct fsg_common *common, int nluns) { struct fsg_lun **curlun; /* Find out how many LUNs there should be */ if (nluns < 1 || nluns > FSG_MAX_LUNS) { pr_err("invalid number of LUNs: %u\n", nluns); return -EINVAL; } curlun = kcalloc(nluns, sizeof(*curlun), GFP_KERNEL); if (unlikely(!curlun)) return -ENOMEM; if (common->luns) fsg_common_free_luns(common); common->luns = curlun; common->nluns = nluns; pr_info("Number of LUNs=%d\n", common->nluns); return 0; } EXPORT_SYMBOL_GPL(fsg_common_set_nluns); void fsg_common_set_ops(struct fsg_common *common, const struct fsg_operations *ops) { common->ops = ops; } EXPORT_SYMBOL_GPL(fsg_common_set_ops); void fsg_common_free_buffers(struct fsg_common *common) { _fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers); common->buffhds = NULL; } EXPORT_SYMBOL_GPL(fsg_common_free_buffers); int fsg_common_set_cdev(struct fsg_common *common, struct usb_composite_dev *cdev, bool can_stall) { struct usb_string *us; common->gadget = cdev->gadget; common->ep0 = cdev->gadget->ep0; common->ep0req = cdev->req; common->cdev = cdev; us = usb_gstrings_attach(cdev, fsg_strings_array, ARRAY_SIZE(fsg_strings)); if (IS_ERR(us)) return PTR_ERR(us); fsg_intf_desc.iInterface = us[FSG_STRING_INTERFACE].id; /* * Some peripheral controllers are known not to be able to * halt bulk endpoints correctly. If one of them is present, * disable stalls. */ common->can_stall = can_stall && !(gadget_is_at91(common->gadget)); return 0; } EXPORT_SYMBOL_GPL(fsg_common_set_cdev); static inline int fsg_common_add_sysfs(struct fsg_common *common, struct fsg_lun *lun) { int rc; rc = device_register(&lun->dev); if (rc) { put_device(&lun->dev); return rc; } rc = device_create_file(&lun->dev, lun->cdrom ? &dev_attr_ro_cdrom : &dev_attr_ro); if (rc) goto error; rc = device_create_file(&lun->dev, lun->removable ? &dev_attr_file : &dev_attr_file_nonremovable); if (rc) goto error; rc = device_create_file(&lun->dev, &dev_attr_nofua); if (rc) goto error; #ifdef CONFIG_LGE_USB_G_AUTORUN rc = device_create_file(&lun->dev, &dev_attr_cdrom_usbmode); if (rc) dev_err(&lun->dev, "failed to create sysfs entry: %d\n", rc); #endif return 0; error: /* removing nonexistent files is a no-op */ fsg_common_remove_sysfs(lun); device_unregister(&lun->dev); return rc; } int fsg_common_create_lun(struct fsg_common *common, struct fsg_lun_config *cfg, unsigned int id, const char *name, const char **name_pfx) { struct fsg_lun *lun; char *pathbuf, *p; int rc = -ENOMEM; if (!common->nluns || !common->luns) return -ENODEV; if (common->luns[id]) return -EBUSY; if (!cfg->filename && !cfg->removable) { pr_err("no file given for LUN%d\n", id); return -EINVAL; } lun = kzalloc(sizeof(*lun), GFP_KERNEL); if (!lun) return -ENOMEM; lun->name_pfx = name_pfx; lun->cdrom = !!cfg->cdrom; lun->ro = cfg->cdrom || cfg->ro; lun->initially_ro = lun->ro; lun->removable = !!cfg->removable; if (!common->sysfs) { /* we DON'T own the name!*/ lun->name = name; } else { lun->dev.release = fsg_lun_release; lun->dev.parent = &common->gadget->dev; dev_set_drvdata(&lun->dev, &common->filesem); dev_set_name(&lun->dev, "%s", name); lun->name = dev_name(&lun->dev); rc = fsg_common_add_sysfs(common, lun); if (rc) { pr_info("failed to register LUN%d: %d\n", id, rc); goto error_sysfs; } } common->luns[id] = lun; if (cfg->filename) { rc = fsg_lun_open(lun, cfg->filename); if (rc) goto error_lun; } pathbuf = kmalloc(PATH_MAX, GFP_KERNEL); p = "(no medium)"; if (fsg_lun_is_open(lun)) { p = "(error)"; if (pathbuf) { p = d_path(&lun->filp->f_path, pathbuf, PATH_MAX); if (IS_ERR(p)) p = "(error)"; } } pr_info("LUN: %s%s%sfile: %s\n", lun->removable ? "removable " : "", lun->ro ? "read only " : "", lun->cdrom ? "CD-ROM " : "", p); kfree(pathbuf); #ifdef CONFIG_LGE_USB_G_AUTORUN /* if fsg common object is cdrom, register autorun misc device */ if (lun->cdrom) { rc = misc_register(&autorun_device); if (rc) { pr_err("USB cdrom gadget driver failed to initialize\n"); goto error_lun; } } #endif return 0; error_lun: if (common->sysfs) { fsg_common_remove_sysfs(lun); device_unregister(&lun->dev); } fsg_lun_close(lun); common->luns[id] = NULL; error_sysfs: kfree(lun); return rc; } EXPORT_SYMBOL_GPL(fsg_common_create_lun); int fsg_common_create_luns(struct fsg_common *common, struct fsg_config *cfg) { char buf[8]; /* enough for 100000000 different numbers, decimal */ int i, rc; for (i = 0; i < common->nluns; ++i) { #ifdef CONFIG_LGE_USB_G_AUTORUN snprintf(buf, sizeof(buf), cfg->lun_name_format ? cfg->lun_name_format : "lun%d", i); #else snprintf(buf, sizeof(buf), "lun%d", i); #endif rc = fsg_common_create_lun(common, &cfg->luns[i], i, buf, NULL); if (rc) goto fail; } pr_info("Number of LUNs=%d\n", common->nluns); return 0; fail: _fsg_common_remove_luns(common, i); return rc; } EXPORT_SYMBOL_GPL(fsg_common_create_luns); void fsg_common_set_inquiry_string(struct fsg_common *common, const char *vn, const char *pn) { int i; /* Prepare inquiryString */ i = get_default_bcdDevice(); snprintf(common->inquiry_string, sizeof(common->inquiry_string), "%-8s%-16s%04x", vn ?: "Linux", /* Assume product name dependent on the first LUN */ pn ?: ((*common->luns)->cdrom ? "File-CD Gadget" : "File-Stor Gadget"), i); } EXPORT_SYMBOL_GPL(fsg_common_set_inquiry_string); int fsg_common_run_thread(struct fsg_common *common) { common->state = FSG_STATE_IDLE; /* Tell the thread to start working */ #ifdef CONFIG_LGE_USB_G_AUTORUN common->thread_task = kthread_create(fsg_main_thread, common, common->thread_name ? common->thread_name : "file-storage"); #else common->thread_task = kthread_create(fsg_main_thread, common, "file-storage"); #endif if (IS_ERR(common->thread_task)) { common->state = FSG_STATE_TERMINATED; return PTR_ERR(common->thread_task); } DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task)); wake_up_process(common->thread_task); return 0; } EXPORT_SYMBOL_GPL(fsg_common_run_thread); static void fsg_common_release(struct kref *ref) { struct fsg_common *common = container_of(ref, struct fsg_common, ref); /* If the thread isn't already dead, tell it to exit now */ if (common->state != FSG_STATE_TERMINATED) { raise_exception(common, FSG_STATE_EXIT); wait_for_completion(&common->thread_notifier); } if (likely(common->luns)) { struct fsg_lun **lun_it = common->luns; unsigned i = common->nluns; /* In error recovery common->nluns may be zero. */ for (; i; --i, ++lun_it) { struct fsg_lun *lun = *lun_it; if (!lun) continue; if (common->sysfs) fsg_common_remove_sysfs(lun); fsg_lun_close(lun); if (common->sysfs) device_unregister(&lun->dev); kfree(lun); } kfree(common->luns); } _fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers); if (common->free_storage_on_release) kfree(common); } int fsg_sysfs_update(struct fsg_common *common, struct device *dev, bool create) { int ret = 0, i; pr_debug("%s(): common->nluns:%d\n", __func__, common->nluns); if (create) { for (i = 0; i < common->nluns; i++) { if (i == 0) snprintf(common->name[i], 8, "lun"); else snprintf(common->name[i], 8, "lun%d", i-1); ret = sysfs_create_link(&dev->kobj, &common->luns[i]->dev.kobj, common->name[i]); if (ret) { pr_err("%s(): failed creating sysfs:%d %s)\n", __func__, i, common->name[i]); goto remove_sysfs; } } } else { i = common->nluns; goto remove_sysfs; } return 0; remove_sysfs: for (; i > 0; i--) { pr_debug("%s(): delete sysfs for lun(id:%d)(name:%s)\n", __func__, i, common->name[i-1]); sysfs_remove_link(&dev->kobj, common->name[i-1]); } return ret; } EXPORT_SYMBOL(fsg_sysfs_update); /*-------------------------------------------------------------------------*/ static int fsg_bind(struct usb_configuration *c, struct usb_function *f) { struct fsg_dev *fsg = fsg_from_func(f); struct usb_gadget *gadget = c->cdev->gadget; int i; struct usb_ep *ep; unsigned max_burst; int ret; struct fsg_opts *opts; opts = fsg_opts_from_func_inst(f->fi); if (!opts->no_configfs) { ret = fsg_common_set_cdev(fsg->common, c->cdev, fsg->common->can_stall); if (ret) return ret; #ifndef CONFIG_LGE_USB_G_AUTORUN fsg_common_set_inquiry_string(fsg->common, NULL, NULL); #endif ret = fsg_common_run_thread(fsg->common); if (ret) return ret; } fsg->gadget = gadget; /* New interface */ i = usb_interface_id(c, f); if (i < 0) return i; fsg_intf_desc.bInterfaceNumber = i; fsg->interface_number = i; /* Find all the endpoints we will use */ ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc); if (!ep) goto autoconf_fail; ep->driver_data = fsg->common; /* claim the endpoint */ fsg->bulk_in = ep; ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc); if (!ep) goto autoconf_fail; ep->driver_data = fsg->common; /* claim the endpoint */ fsg->bulk_out = ep; /* Assume endpoint addresses are the same for both speeds */ fsg_hs_bulk_in_desc.bEndpointAddress = fsg_fs_bulk_in_desc.bEndpointAddress; fsg_hs_bulk_out_desc.bEndpointAddress = fsg_fs_bulk_out_desc.bEndpointAddress; /* Calculate bMaxBurst, we know packet size is 1024 */ max_burst = min_t(unsigned, FSG_BUFLEN / 1024, 15); fsg_ss_bulk_in_desc.bEndpointAddress = fsg_fs_bulk_in_desc.bEndpointAddress; fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst; fsg_ss_bulk_out_desc.bEndpointAddress = fsg_fs_bulk_out_desc.bEndpointAddress; fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst; ret = usb_assign_descriptors(f, fsg_fs_function, fsg_hs_function, fsg_ss_function); if (ret) goto autoconf_fail; return 0; autoconf_fail: ERROR(fsg, "unable to autoconfigure all endpoints\n"); return -ENOTSUPP; } /****************************** ALLOCATE FUNCTION *************************/ static void fsg_unbind(struct usb_configuration *c, struct usb_function *f) { struct fsg_dev *fsg = fsg_from_func(f); struct fsg_common *common = fsg->common; DBG(fsg, "unbind\n"); if (fsg->common->fsg == fsg) { fsg->common->new_fsg = NULL; raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE); /* FIXME: make interruptible or killable somehow? */ wait_event(common->fsg_wait, common->fsg != fsg); } usb_free_all_descriptors(&fsg->function); } static inline struct fsg_lun_opts *to_fsg_lun_opts(struct config_item *item) { return container_of(to_config_group(item), struct fsg_lun_opts, group); } static inline struct fsg_opts *to_fsg_opts(struct config_item *item) { return container_of(to_config_group(item), struct fsg_opts, func_inst.group); } CONFIGFS_ATTR_STRUCT(fsg_lun_opts); CONFIGFS_ATTR_OPS(fsg_lun_opts); static void fsg_lun_attr_release(struct config_item *item) { struct fsg_lun_opts *lun_opts; lun_opts = to_fsg_lun_opts(item); kfree(lun_opts); } static struct configfs_item_operations fsg_lun_item_ops = { .release = fsg_lun_attr_release, .show_attribute = fsg_lun_opts_attr_show, .store_attribute = fsg_lun_opts_attr_store, }; static ssize_t fsg_lun_opts_file_show(struct fsg_lun_opts *opts, char *page) { struct fsg_opts *fsg_opts; fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); return fsg_show_file(opts->lun, &fsg_opts->common->filesem, page); } static ssize_t fsg_lun_opts_file_store(struct fsg_lun_opts *opts, const char *page, size_t len) { struct fsg_opts *fsg_opts; fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); return fsg_store_file(opts->lun, &fsg_opts->common->filesem, page, len); } static struct fsg_lun_opts_attribute fsg_lun_opts_file = __CONFIGFS_ATTR(file, S_IRUGO | S_IWUSR, fsg_lun_opts_file_show, fsg_lun_opts_file_store); static ssize_t fsg_lun_opts_ro_show(struct fsg_lun_opts *opts, char *page) { return fsg_show_ro(opts->lun, page); } static ssize_t fsg_lun_opts_ro_store(struct fsg_lun_opts *opts, const char *page, size_t len) { struct fsg_opts *fsg_opts; fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); return fsg_store_ro(opts->lun, &fsg_opts->common->filesem, page, len); } static struct fsg_lun_opts_attribute fsg_lun_opts_ro = __CONFIGFS_ATTR(ro, S_IRUGO | S_IWUSR, fsg_lun_opts_ro_show, fsg_lun_opts_ro_store); static ssize_t fsg_lun_opts_removable_show(struct fsg_lun_opts *opts, char *page) { return fsg_show_removable(opts->lun, page); } static ssize_t fsg_lun_opts_removable_store(struct fsg_lun_opts *opts, const char *page, size_t len) { return fsg_store_removable(opts->lun, page, len); } static struct fsg_lun_opts_attribute fsg_lun_opts_removable = __CONFIGFS_ATTR(removable, S_IRUGO | S_IWUSR, fsg_lun_opts_removable_show, fsg_lun_opts_removable_store); static ssize_t fsg_lun_opts_cdrom_show(struct fsg_lun_opts *opts, char *page) { return fsg_show_cdrom(opts->lun, page); } static ssize_t fsg_lun_opts_cdrom_store(struct fsg_lun_opts *opts, const char *page, size_t len) { struct fsg_opts *fsg_opts; fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); return fsg_store_cdrom(opts->lun, &fsg_opts->common->filesem, page, len); } static struct fsg_lun_opts_attribute fsg_lun_opts_cdrom = __CONFIGFS_ATTR(cdrom, S_IRUGO | S_IWUSR, fsg_lun_opts_cdrom_show, fsg_lun_opts_cdrom_store); static ssize_t fsg_lun_opts_nofua_show(struct fsg_lun_opts *opts, char *page) { return fsg_show_nofua(opts->lun, page); } static ssize_t fsg_lun_opts_nofua_store(struct fsg_lun_opts *opts, const char *page, size_t len) { return fsg_store_nofua(opts->lun, page, len); } static struct fsg_lun_opts_attribute fsg_lun_opts_nofua = __CONFIGFS_ATTR(nofua, S_IRUGO | S_IWUSR, fsg_lun_opts_nofua_show, fsg_lun_opts_nofua_store); static struct configfs_attribute *fsg_lun_attrs[] = { &fsg_lun_opts_file.attr, &fsg_lun_opts_ro.attr, &fsg_lun_opts_removable.attr, &fsg_lun_opts_cdrom.attr, &fsg_lun_opts_nofua.attr, NULL, }; static struct config_item_type fsg_lun_type = { .ct_item_ops = &fsg_lun_item_ops, .ct_attrs = fsg_lun_attrs, .ct_owner = THIS_MODULE, }; static struct config_group *fsg_lun_make(struct config_group *group, const char *name) { struct fsg_lun_opts *opts; struct fsg_opts *fsg_opts; struct fsg_lun_config config; char *num_str; u8 num; int ret; num_str = strchr(name, '.'); if (!num_str) { pr_err("Unable to locate . in LUN.NUMBER\n"); return ERR_PTR(-EINVAL); } num_str++; ret = kstrtou8(num_str, 0, &num); if (ret) return ERR_PTR(ret); fsg_opts = to_fsg_opts(&group->cg_item); if (num >= FSG_MAX_LUNS) return ERR_PTR(-ERANGE); mutex_lock(&fsg_opts->lock); if (fsg_opts->refcnt || fsg_opts->common->luns[num]) { ret = -EBUSY; goto out; } opts = kzalloc(sizeof(*opts), GFP_KERNEL); if (!opts) { ret = -ENOMEM; goto out; } memset(&config, 0, sizeof(config)); config.removable = true; ret = fsg_common_create_lun(fsg_opts->common, &config, num, name, (const char **)&group->cg_item.ci_name); if (ret) { kfree(opts); goto out; } opts->lun = fsg_opts->common->luns[num]; opts->lun_id = num; mutex_unlock(&fsg_opts->lock); config_group_init_type_name(&opts->group, name, &fsg_lun_type); return &opts->group; out: mutex_unlock(&fsg_opts->lock); return ERR_PTR(ret); } static void fsg_lun_drop(struct config_group *group, struct config_item *item) { struct fsg_lun_opts *lun_opts; struct fsg_opts *fsg_opts; lun_opts = to_fsg_lun_opts(item); fsg_opts = to_fsg_opts(&group->cg_item); mutex_lock(&fsg_opts->lock); if (fsg_opts->refcnt) { struct config_item *gadget; gadget = group->cg_item.ci_parent->ci_parent; unregister_gadget_item(gadget); } fsg_common_remove_lun(lun_opts->lun, fsg_opts->common->sysfs); fsg_opts->common->luns[lun_opts->lun_id] = NULL; lun_opts->lun_id = 0; mutex_unlock(&fsg_opts->lock); config_item_put(item); } CONFIGFS_ATTR_STRUCT(fsg_opts); CONFIGFS_ATTR_OPS(fsg_opts); static void fsg_attr_release(struct config_item *item) { struct fsg_opts *opts = to_fsg_opts(item); usb_put_function_instance(&opts->func_inst); } static struct configfs_item_operations fsg_item_ops = { .release = fsg_attr_release, .show_attribute = fsg_opts_attr_show, .store_attribute = fsg_opts_attr_store, }; static ssize_t fsg_opts_stall_show(struct fsg_opts *opts, char *page) { int result; mutex_lock(&opts->lock); result = sprintf(page, "%d", opts->common->can_stall); mutex_unlock(&opts->lock); return result; } static ssize_t fsg_opts_stall_store(struct fsg_opts *opts, const char *page, size_t len) { int ret; bool stall; mutex_lock(&opts->lock); if (opts->refcnt) { mutex_unlock(&opts->lock); return -EBUSY; } ret = strtobool(page, &stall); if (!ret) { opts->common->can_stall = stall; ret = len; } mutex_unlock(&opts->lock); return ret; } static struct fsg_opts_attribute fsg_opts_stall = __CONFIGFS_ATTR(stall, S_IRUGO | S_IWUSR, fsg_opts_stall_show, fsg_opts_stall_store); #ifdef CONFIG_USB_GADGET_DEBUG_FILES static ssize_t fsg_opts_num_buffers_show(struct fsg_opts *opts, char *page) { int result; mutex_lock(&opts->lock); result = sprintf(page, "%d", opts->common->fsg_num_buffers); mutex_unlock(&opts->lock); return result; } static ssize_t fsg_opts_num_buffers_store(struct fsg_opts *opts, const char *page, size_t len) { int ret; u8 num; mutex_lock(&opts->lock); if (opts->refcnt) { ret = -EBUSY; goto end; } ret = kstrtou8(page, 0, &num); if (ret) goto end; ret = fsg_num_buffers_validate(num); if (ret) goto end; fsg_common_set_num_buffers(opts->common, num); ret = len; end: mutex_unlock(&opts->lock); return ret; } static struct fsg_opts_attribute fsg_opts_num_buffers = __CONFIGFS_ATTR(num_buffers, S_IRUGO | S_IWUSR, fsg_opts_num_buffers_show, fsg_opts_num_buffers_store); #endif static struct configfs_attribute *fsg_attrs[] = { &fsg_opts_stall.attr, #ifdef CONFIG_USB_GADGET_DEBUG_FILES &fsg_opts_num_buffers.attr, #endif NULL, }; static struct configfs_group_operations fsg_group_ops = { .make_group = fsg_lun_make, .drop_item = fsg_lun_drop, }; static struct config_item_type fsg_func_type = { .ct_item_ops = &fsg_item_ops, .ct_group_ops = &fsg_group_ops, .ct_attrs = fsg_attrs, .ct_owner = THIS_MODULE, }; static void fsg_free_inst(struct usb_function_instance *fi) { struct fsg_opts *opts; opts = fsg_opts_from_func_inst(fi); fsg_common_put(opts->common); kfree(opts); } static struct usb_function_instance *fsg_alloc_inst(void) { struct fsg_opts *opts; struct fsg_lun_config config; int rc; opts = kzalloc(sizeof(*opts), GFP_KERNEL); if (!opts) return ERR_PTR(-ENOMEM); mutex_init(&opts->lock); opts->func_inst.free_func_inst = fsg_free_inst; opts->common = fsg_common_setup(opts->common); if (IS_ERR(opts->common)) { rc = PTR_ERR(opts->common); goto release_opts; } rc = fsg_common_set_nluns(opts->common, FSG_MAX_LUNS); if (rc) goto release_opts; rc = fsg_common_set_num_buffers(opts->common, CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS); if (rc) goto release_luns; pr_info(FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n"); memset(&config, 0, sizeof(config)); config.removable = true; rc = fsg_common_create_lun(opts->common, &config, 0, "lun.0", (const char **)&opts->func_inst.group.cg_item.ci_name); opts->lun0.lun = opts->common->luns[0]; opts->lun0.lun_id = 0; config_group_init_type_name(&opts->lun0.group, "lun.0", &fsg_lun_type); opts->default_groups[0] = &opts->lun0.group; opts->func_inst.group.default_groups = opts->default_groups; config_group_init_type_name(&opts->func_inst.group, "", &fsg_func_type); return &opts->func_inst; release_luns: kfree(opts->common->luns); release_opts: kfree(opts); return ERR_PTR(rc); } static void fsg_free(struct usb_function *f) { struct fsg_dev *fsg; struct fsg_opts *opts; fsg = container_of(f, struct fsg_dev, function); opts = container_of(f->fi, struct fsg_opts, func_inst); mutex_lock(&opts->lock); opts->refcnt--; mutex_unlock(&opts->lock); kfree(fsg); } static struct usb_function *fsg_alloc(struct usb_function_instance *fi) { struct fsg_opts *opts = fsg_opts_from_func_inst(fi); struct fsg_common *common = opts->common; struct fsg_dev *fsg; fsg = kzalloc(sizeof(*fsg), GFP_KERNEL); if (unlikely(!fsg)) return ERR_PTR(-ENOMEM); mutex_lock(&opts->lock); opts->refcnt++; mutex_unlock(&opts->lock); fsg->function.name = FSG_DRIVER_DESC; fsg->function.bind = fsg_bind; fsg->function.unbind = fsg_unbind; fsg->function.setup = fsg_setup; fsg->function.set_alt = fsg_set_alt; fsg->function.disable = fsg_disable; fsg->function.free_func = fsg_free; fsg->common = common; setup_timer(&common->vfs_timer, msc_usb_vfs_timer_func, (unsigned long) common); return &fsg->function; } DECLARE_USB_FUNCTION_INIT(mass_storage, fsg_alloc_inst, fsg_alloc); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Michal Nazarewicz"); #ifdef CONFIG_LGE_USB_G_AUTORUN void fsg_common_set_thread_name(struct fsg_common *common, const char *tn) { common->thread_name = tn; } EXPORT_SYMBOL_GPL(fsg_common_set_thread_name); static struct usb_function_instance *csg_alloc_inst(void) { struct fsg_opts *opts; struct fsg_lun_config config; int rc; opts = kzalloc(sizeof(*opts), GFP_KERNEL); if (!opts) return ERR_PTR(-ENOMEM); mutex_init(&opts->lock); opts->func_inst.free_func_inst = fsg_free_inst; opts->common = fsg_common_setup(opts->common); if (IS_ERR(opts->common)) { rc = PTR_ERR(opts->common); goto release_opts; } rc = fsg_common_set_nluns(opts->common, FSG_MAX_LUNS); if (rc) goto release_opts; rc = fsg_common_set_num_buffers(opts->common, CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS); if (rc) goto release_luns; pr_info(FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n"); memset(&config, 0, sizeof(config)); config.removable = true; rc = fsg_common_create_lun(opts->common, &config, 0, "lun.0", (const char **)&opts->func_inst.group.cg_item.ci_name); opts->lun0.lun = opts->common->luns[0]; opts->lun0.lun_id = 0; config_group_init_type_name(&opts->lun0.group, "lun.0", &fsg_lun_type); opts->default_groups[0] = &opts->lun0.group; opts->func_inst.group.default_groups = opts->default_groups; config_group_init_type_name(&opts->func_inst.group, "", &fsg_func_type); return &opts->func_inst; release_luns: kfree(opts->common->luns); release_opts: kfree(opts); return ERR_PTR(rc); } static struct usb_function *csg_alloc(struct usb_function_instance *fi) { struct fsg_opts *opts = fsg_opts_from_func_inst(fi); struct fsg_common *common = opts->common; struct fsg_dev *csg; csg = kzalloc(sizeof(*csg), GFP_KERNEL); if (unlikely(!csg)) return ERR_PTR(-ENOMEM); mutex_lock(&opts->lock); opts->refcnt++; mutex_unlock(&opts->lock); /* share fsg function apis */ csg->function.name = "cdrom_storage"; csg->function.strings = fsg_strings_array; csg->function.bind = fsg_bind; csg->function.unbind = fsg_unbind; csg->function.setup = fsg_setup; csg->function.set_alt = fsg_set_alt; csg->function.disable = fsg_disable; csg->function.free_func = fsg_free; csg->common = common; setup_timer(&common->vfs_timer, msc_usb_vfs_timer_func, (unsigned long) common); return &csg->function; } DECLARE_USB_FUNCTION_INIT(cdrom_storage, csg_alloc_inst, csg_alloc); #endif /************************* Module parameters *************************/ void fsg_config_from_params(struct fsg_config *cfg, const struct fsg_module_parameters *params, unsigned int fsg_num_buffers) { struct fsg_lun_config *lun; unsigned i; /* Configure LUNs */ cfg->nluns = min(params->luns ?: (params->file_count ?: 1u), (unsigned)FSG_MAX_LUNS); for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) { lun->ro = !!params->ro[i]; lun->cdrom = !!params->cdrom[i]; lun->removable = !!params->removable[i]; lun->filename = params->file_count > i && params->file[i][0] ? params->file[i] : NULL; } /* Let MSF use defaults */ cfg->vendor_name = NULL; cfg->product_name = NULL; cfg->ops = NULL; cfg->private_data = NULL; /* Finalise */ cfg->can_stall = params->stall; cfg->fsg_num_buffers = fsg_num_buffers; } EXPORT_SYMBOL_GPL(fsg_config_from_params);
mericon/Xp_Kernel_LGH850
virt/drivers/usb/gadget/function/f_mass_storage.c
C
gpl-2.0
123,279
// SPDX-License-Identifier: GPL-2.0 OR MIT /* * Copyright (C) 2015-2016 The fiat-crypto Authors. * Copyright (C) 2018-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. * * This is a machine-generated formally verified implementation of Curve25519 * ECDH from: <https://github.com/mit-plv/fiat-crypto>. Though originally * machine generated, it has been tweaked to be suitable for use in the kernel. * It is optimized for 32-bit machines and machines that cannot work efficiently * with 128-bit integer types. */ /* fe means field element. Here the field is \Z/(2^255-19). An element t, * entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 * t[3]+2^102 t[4]+...+2^230 t[9]. * fe limbs are bounded by 1.125*2^26,1.125*2^25,1.125*2^26,1.125*2^25,etc. * Multiplication and carrying produce fe from fe_loose. */ typedef struct fe { u32 v[10]; } fe; /* fe_loose limbs are bounded by 3.375*2^26,3.375*2^25,3.375*2^26,3.375*2^25,etc * Addition and subtraction produce fe_loose from (fe, fe). */ typedef struct fe_loose { u32 v[10]; } fe_loose; static __always_inline void fe_frombytes_impl(u32 h[10], const u8 *s) { /* Ignores top bit of s. */ u32 a0 = get_unaligned_le32(s); u32 a1 = get_unaligned_le32(s+4); u32 a2 = get_unaligned_le32(s+8); u32 a3 = get_unaligned_le32(s+12); u32 a4 = get_unaligned_le32(s+16); u32 a5 = get_unaligned_le32(s+20); u32 a6 = get_unaligned_le32(s+24); u32 a7 = get_unaligned_le32(s+28); h[0] = a0&((1<<26)-1); /* 26 used, 32-26 left. 26 */ h[1] = (a0>>26) | ((a1&((1<<19)-1))<< 6); /* (32-26) + 19 = 6+19 = 25 */ h[2] = (a1>>19) | ((a2&((1<<13)-1))<<13); /* (32-19) + 13 = 13+13 = 26 */ h[3] = (a2>>13) | ((a3&((1<< 6)-1))<<19); /* (32-13) + 6 = 19+ 6 = 25 */ h[4] = (a3>> 6); /* (32- 6) = 26 */ h[5] = a4&((1<<25)-1); /* 25 */ h[6] = (a4>>25) | ((a5&((1<<19)-1))<< 7); /* (32-25) + 19 = 7+19 = 26 */ h[7] = (a5>>19) | ((a6&((1<<12)-1))<<13); /* (32-19) + 12 = 13+12 = 25 */ h[8] = (a6>>12) | ((a7&((1<< 6)-1))<<20); /* (32-12) + 6 = 20+ 6 = 26 */ h[9] = (a7>> 6)&((1<<25)-1); /* 25 */ } static __always_inline void fe_frombytes(fe *h, const u8 *s) { fe_frombytes_impl(h->v, s); } static __always_inline u8 /*bool*/ addcarryx_u25(u8 /*bool*/ c, u32 a, u32 b, u32 *low) { /* This function extracts 25 bits of result and 1 bit of carry * (26 total), so a 32-bit intermediate is sufficient. */ u32 x = a + b + c; *low = x & ((1 << 25) - 1); return (x >> 25) & 1; } static __always_inline u8 /*bool*/ addcarryx_u26(u8 /*bool*/ c, u32 a, u32 b, u32 *low) { /* This function extracts 26 bits of result and 1 bit of carry * (27 total), so a 32-bit intermediate is sufficient. */ u32 x = a + b + c; *low = x & ((1 << 26) - 1); return (x >> 26) & 1; } static __always_inline u8 /*bool*/ subborrow_u25(u8 /*bool*/ c, u32 a, u32 b, u32 *low) { /* This function extracts 25 bits of result and 1 bit of borrow * (26 total), so a 32-bit intermediate is sufficient. */ u32 x = a - b - c; *low = x & ((1 << 25) - 1); return x >> 31; } static __always_inline u8 /*bool*/ subborrow_u26(u8 /*bool*/ c, u32 a, u32 b, u32 *low) { /* This function extracts 26 bits of result and 1 bit of borrow *(27 total), so a 32-bit intermediate is sufficient. */ u32 x = a - b - c; *low = x & ((1 << 26) - 1); return x >> 31; } static __always_inline u32 cmovznz32(u32 t, u32 z, u32 nz) { t = -!!t; /* all set if nonzero, 0 if 0 */ return (t&nz) | ((~t)&z); } static __always_inline void fe_freeze(u32 out[10], const u32 in1[10]) { { const u32 x17 = in1[9]; { const u32 x18 = in1[8]; { const u32 x16 = in1[7]; { const u32 x14 = in1[6]; { const u32 x12 = in1[5]; { const u32 x10 = in1[4]; { const u32 x8 = in1[3]; { const u32 x6 = in1[2]; { const u32 x4 = in1[1]; { const u32 x2 = in1[0]; { u32 x20; u8/*bool*/ x21 = subborrow_u26(0x0, x2, 0x3ffffed, &x20); { u32 x23; u8/*bool*/ x24 = subborrow_u25(x21, x4, 0x1ffffff, &x23); { u32 x26; u8/*bool*/ x27 = subborrow_u26(x24, x6, 0x3ffffff, &x26); { u32 x29; u8/*bool*/ x30 = subborrow_u25(x27, x8, 0x1ffffff, &x29); { u32 x32; u8/*bool*/ x33 = subborrow_u26(x30, x10, 0x3ffffff, &x32); { u32 x35; u8/*bool*/ x36 = subborrow_u25(x33, x12, 0x1ffffff, &x35); { u32 x38; u8/*bool*/ x39 = subborrow_u26(x36, x14, 0x3ffffff, &x38); { u32 x41; u8/*bool*/ x42 = subborrow_u25(x39, x16, 0x1ffffff, &x41); { u32 x44; u8/*bool*/ x45 = subborrow_u26(x42, x18, 0x3ffffff, &x44); { u32 x47; u8/*bool*/ x48 = subborrow_u25(x45, x17, 0x1ffffff, &x47); { u32 x49 = cmovznz32(x48, 0x0, 0xffffffff); { u32 x50 = (x49 & 0x3ffffed); { u32 x52; u8/*bool*/ x53 = addcarryx_u26(0x0, x20, x50, &x52); { u32 x54 = (x49 & 0x1ffffff); { u32 x56; u8/*bool*/ x57 = addcarryx_u25(x53, x23, x54, &x56); { u32 x58 = (x49 & 0x3ffffff); { u32 x60; u8/*bool*/ x61 = addcarryx_u26(x57, x26, x58, &x60); { u32 x62 = (x49 & 0x1ffffff); { u32 x64; u8/*bool*/ x65 = addcarryx_u25(x61, x29, x62, &x64); { u32 x66 = (x49 & 0x3ffffff); { u32 x68; u8/*bool*/ x69 = addcarryx_u26(x65, x32, x66, &x68); { u32 x70 = (x49 & 0x1ffffff); { u32 x72; u8/*bool*/ x73 = addcarryx_u25(x69, x35, x70, &x72); { u32 x74 = (x49 & 0x3ffffff); { u32 x76; u8/*bool*/ x77 = addcarryx_u26(x73, x38, x74, &x76); { u32 x78 = (x49 & 0x1ffffff); { u32 x80; u8/*bool*/ x81 = addcarryx_u25(x77, x41, x78, &x80); { u32 x82 = (x49 & 0x3ffffff); { u32 x84; u8/*bool*/ x85 = addcarryx_u26(x81, x44, x82, &x84); { u32 x86 = (x49 & 0x1ffffff); { u32 x88; addcarryx_u25(x85, x47, x86, &x88); out[0] = x52; out[1] = x56; out[2] = x60; out[3] = x64; out[4] = x68; out[5] = x72; out[6] = x76; out[7] = x80; out[8] = x84; out[9] = x88; }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} } static __always_inline void fe_tobytes(u8 s[32], const fe *f) { u32 h[10]; fe_freeze(h, f->v); s[0] = h[0] >> 0; s[1] = h[0] >> 8; s[2] = h[0] >> 16; s[3] = (h[0] >> 24) | (h[1] << 2); s[4] = h[1] >> 6; s[5] = h[1] >> 14; s[6] = (h[1] >> 22) | (h[2] << 3); s[7] = h[2] >> 5; s[8] = h[2] >> 13; s[9] = (h[2] >> 21) | (h[3] << 5); s[10] = h[3] >> 3; s[11] = h[3] >> 11; s[12] = (h[3] >> 19) | (h[4] << 6); s[13] = h[4] >> 2; s[14] = h[4] >> 10; s[15] = h[4] >> 18; s[16] = h[5] >> 0; s[17] = h[5] >> 8; s[18] = h[5] >> 16; s[19] = (h[5] >> 24) | (h[6] << 1); s[20] = h[6] >> 7; s[21] = h[6] >> 15; s[22] = (h[6] >> 23) | (h[7] << 3); s[23] = h[7] >> 5; s[24] = h[7] >> 13; s[25] = (h[7] >> 21) | (h[8] << 4); s[26] = h[8] >> 4; s[27] = h[8] >> 12; s[28] = (h[8] >> 20) | (h[9] << 6); s[29] = h[9] >> 2; s[30] = h[9] >> 10; s[31] = h[9] >> 18; } /* h = f */ static __always_inline void fe_copy(fe *h, const fe *f) { memmove(h, f, sizeof(u32) * 10); } static __always_inline void fe_copy_lt(fe_loose *h, const fe *f) { memmove(h, f, sizeof(u32) * 10); } /* h = 0 */ static __always_inline void fe_0(fe *h) { memset(h, 0, sizeof(u32) * 10); } /* h = 1 */ static __always_inline void fe_1(fe *h) { memset(h, 0, sizeof(u32) * 10); h->v[0] = 1; } static void fe_add_impl(u32 out[10], const u32 in1[10], const u32 in2[10]) { { const u32 x20 = in1[9]; { const u32 x21 = in1[8]; { const u32 x19 = in1[7]; { const u32 x17 = in1[6]; { const u32 x15 = in1[5]; { const u32 x13 = in1[4]; { const u32 x11 = in1[3]; { const u32 x9 = in1[2]; { const u32 x7 = in1[1]; { const u32 x5 = in1[0]; { const u32 x38 = in2[9]; { const u32 x39 = in2[8]; { const u32 x37 = in2[7]; { const u32 x35 = in2[6]; { const u32 x33 = in2[5]; { const u32 x31 = in2[4]; { const u32 x29 = in2[3]; { const u32 x27 = in2[2]; { const u32 x25 = in2[1]; { const u32 x23 = in2[0]; out[0] = (x5 + x23); out[1] = (x7 + x25); out[2] = (x9 + x27); out[3] = (x11 + x29); out[4] = (x13 + x31); out[5] = (x15 + x33); out[6] = (x17 + x35); out[7] = (x19 + x37); out[8] = (x21 + x39); out[9] = (x20 + x38); }}}}}}}}}}}}}}}}}}}} } /* h = f + g * Can overlap h with f or g. */ static __always_inline void fe_add(fe_loose *h, const fe *f, const fe *g) { fe_add_impl(h->v, f->v, g->v); } static void fe_sub_impl(u32 out[10], const u32 in1[10], const u32 in2[10]) { { const u32 x20 = in1[9]; { const u32 x21 = in1[8]; { const u32 x19 = in1[7]; { const u32 x17 = in1[6]; { const u32 x15 = in1[5]; { const u32 x13 = in1[4]; { const u32 x11 = in1[3]; { const u32 x9 = in1[2]; { const u32 x7 = in1[1]; { const u32 x5 = in1[0]; { const u32 x38 = in2[9]; { const u32 x39 = in2[8]; { const u32 x37 = in2[7]; { const u32 x35 = in2[6]; { const u32 x33 = in2[5]; { const u32 x31 = in2[4]; { const u32 x29 = in2[3]; { const u32 x27 = in2[2]; { const u32 x25 = in2[1]; { const u32 x23 = in2[0]; out[0] = ((0x7ffffda + x5) - x23); out[1] = ((0x3fffffe + x7) - x25); out[2] = ((0x7fffffe + x9) - x27); out[3] = ((0x3fffffe + x11) - x29); out[4] = ((0x7fffffe + x13) - x31); out[5] = ((0x3fffffe + x15) - x33); out[6] = ((0x7fffffe + x17) - x35); out[7] = ((0x3fffffe + x19) - x37); out[8] = ((0x7fffffe + x21) - x39); out[9] = ((0x3fffffe + x20) - x38); }}}}}}}}}}}}}}}}}}}} } /* h = f - g * Can overlap h with f or g. */ static __always_inline void fe_sub(fe_loose *h, const fe *f, const fe *g) { fe_sub_impl(h->v, f->v, g->v); } static void fe_mul_impl(u32 out[10], const u32 in1[10], const u32 in2[10]) { { const u32 x20 = in1[9]; { const u32 x21 = in1[8]; { const u32 x19 = in1[7]; { const u32 x17 = in1[6]; { const u32 x15 = in1[5]; { const u32 x13 = in1[4]; { const u32 x11 = in1[3]; { const u32 x9 = in1[2]; { const u32 x7 = in1[1]; { const u32 x5 = in1[0]; { const u32 x38 = in2[9]; { const u32 x39 = in2[8]; { const u32 x37 = in2[7]; { const u32 x35 = in2[6]; { const u32 x33 = in2[5]; { const u32 x31 = in2[4]; { const u32 x29 = in2[3]; { const u32 x27 = in2[2]; { const u32 x25 = in2[1]; { const u32 x23 = in2[0]; { u64 x40 = ((u64)x23 * x5); { u64 x41 = (((u64)x23 * x7) + ((u64)x25 * x5)); { u64 x42 = ((((u64)(0x2 * x25) * x7) + ((u64)x23 * x9)) + ((u64)x27 * x5)); { u64 x43 = (((((u64)x25 * x9) + ((u64)x27 * x7)) + ((u64)x23 * x11)) + ((u64)x29 * x5)); { u64 x44 = (((((u64)x27 * x9) + (0x2 * (((u64)x25 * x11) + ((u64)x29 * x7)))) + ((u64)x23 * x13)) + ((u64)x31 * x5)); { u64 x45 = (((((((u64)x27 * x11) + ((u64)x29 * x9)) + ((u64)x25 * x13)) + ((u64)x31 * x7)) + ((u64)x23 * x15)) + ((u64)x33 * x5)); { u64 x46 = (((((0x2 * ((((u64)x29 * x11) + ((u64)x25 * x15)) + ((u64)x33 * x7))) + ((u64)x27 * x13)) + ((u64)x31 * x9)) + ((u64)x23 * x17)) + ((u64)x35 * x5)); { u64 x47 = (((((((((u64)x29 * x13) + ((u64)x31 * x11)) + ((u64)x27 * x15)) + ((u64)x33 * x9)) + ((u64)x25 * x17)) + ((u64)x35 * x7)) + ((u64)x23 * x19)) + ((u64)x37 * x5)); { u64 x48 = (((((((u64)x31 * x13) + (0x2 * (((((u64)x29 * x15) + ((u64)x33 * x11)) + ((u64)x25 * x19)) + ((u64)x37 * x7)))) + ((u64)x27 * x17)) + ((u64)x35 * x9)) + ((u64)x23 * x21)) + ((u64)x39 * x5)); { u64 x49 = (((((((((((u64)x31 * x15) + ((u64)x33 * x13)) + ((u64)x29 * x17)) + ((u64)x35 * x11)) + ((u64)x27 * x19)) + ((u64)x37 * x9)) + ((u64)x25 * x21)) + ((u64)x39 * x7)) + ((u64)x23 * x20)) + ((u64)x38 * x5)); { u64 x50 = (((((0x2 * ((((((u64)x33 * x15) + ((u64)x29 * x19)) + ((u64)x37 * x11)) + ((u64)x25 * x20)) + ((u64)x38 * x7))) + ((u64)x31 * x17)) + ((u64)x35 * x13)) + ((u64)x27 * x21)) + ((u64)x39 * x9)); { u64 x51 = (((((((((u64)x33 * x17) + ((u64)x35 * x15)) + ((u64)x31 * x19)) + ((u64)x37 * x13)) + ((u64)x29 * x21)) + ((u64)x39 * x11)) + ((u64)x27 * x20)) + ((u64)x38 * x9)); { u64 x52 = (((((u64)x35 * x17) + (0x2 * (((((u64)x33 * x19) + ((u64)x37 * x15)) + ((u64)x29 * x20)) + ((u64)x38 * x11)))) + ((u64)x31 * x21)) + ((u64)x39 * x13)); { u64 x53 = (((((((u64)x35 * x19) + ((u64)x37 * x17)) + ((u64)x33 * x21)) + ((u64)x39 * x15)) + ((u64)x31 * x20)) + ((u64)x38 * x13)); { u64 x54 = (((0x2 * ((((u64)x37 * x19) + ((u64)x33 * x20)) + ((u64)x38 * x15))) + ((u64)x35 * x21)) + ((u64)x39 * x17)); { u64 x55 = (((((u64)x37 * x21) + ((u64)x39 * x19)) + ((u64)x35 * x20)) + ((u64)x38 * x17)); { u64 x56 = (((u64)x39 * x21) + (0x2 * (((u64)x37 * x20) + ((u64)x38 * x19)))); { u64 x57 = (((u64)x39 * x20) + ((u64)x38 * x21)); { u64 x58 = ((u64)(0x2 * x38) * x20); { u64 x59 = (x48 + (x58 << 0x4)); { u64 x60 = (x59 + (x58 << 0x1)); { u64 x61 = (x60 + x58); { u64 x62 = (x47 + (x57 << 0x4)); { u64 x63 = (x62 + (x57 << 0x1)); { u64 x64 = (x63 + x57); { u64 x65 = (x46 + (x56 << 0x4)); { u64 x66 = (x65 + (x56 << 0x1)); { u64 x67 = (x66 + x56); { u64 x68 = (x45 + (x55 << 0x4)); { u64 x69 = (x68 + (x55 << 0x1)); { u64 x70 = (x69 + x55); { u64 x71 = (x44 + (x54 << 0x4)); { u64 x72 = (x71 + (x54 << 0x1)); { u64 x73 = (x72 + x54); { u64 x74 = (x43 + (x53 << 0x4)); { u64 x75 = (x74 + (x53 << 0x1)); { u64 x76 = (x75 + x53); { u64 x77 = (x42 + (x52 << 0x4)); { u64 x78 = (x77 + (x52 << 0x1)); { u64 x79 = (x78 + x52); { u64 x80 = (x41 + (x51 << 0x4)); { u64 x81 = (x80 + (x51 << 0x1)); { u64 x82 = (x81 + x51); { u64 x83 = (x40 + (x50 << 0x4)); { u64 x84 = (x83 + (x50 << 0x1)); { u64 x85 = (x84 + x50); { u64 x86 = (x85 >> 0x1a); { u32 x87 = ((u32)x85 & 0x3ffffff); { u64 x88 = (x86 + x82); { u64 x89 = (x88 >> 0x19); { u32 x90 = ((u32)x88 & 0x1ffffff); { u64 x91 = (x89 + x79); { u64 x92 = (x91 >> 0x1a); { u32 x93 = ((u32)x91 & 0x3ffffff); { u64 x94 = (x92 + x76); { u64 x95 = (x94 >> 0x19); { u32 x96 = ((u32)x94 & 0x1ffffff); { u64 x97 = (x95 + x73); { u64 x98 = (x97 >> 0x1a); { u32 x99 = ((u32)x97 & 0x3ffffff); { u64 x100 = (x98 + x70); { u64 x101 = (x100 >> 0x19); { u32 x102 = ((u32)x100 & 0x1ffffff); { u64 x103 = (x101 + x67); { u64 x104 = (x103 >> 0x1a); { u32 x105 = ((u32)x103 & 0x3ffffff); { u64 x106 = (x104 + x64); { u64 x107 = (x106 >> 0x19); { u32 x108 = ((u32)x106 & 0x1ffffff); { u64 x109 = (x107 + x61); { u64 x110 = (x109 >> 0x1a); { u32 x111 = ((u32)x109 & 0x3ffffff); { u64 x112 = (x110 + x49); { u64 x113 = (x112 >> 0x19); { u32 x114 = ((u32)x112 & 0x1ffffff); { u64 x115 = (x87 + (0x13 * x113)); { u32 x116 = (u32) (x115 >> 0x1a); { u32 x117 = ((u32)x115 & 0x3ffffff); { u32 x118 = (x116 + x90); { u32 x119 = (x118 >> 0x19); { u32 x120 = (x118 & 0x1ffffff); out[0] = x117; out[1] = x120; out[2] = (x119 + x93); out[3] = x96; out[4] = x99; out[5] = x102; out[6] = x105; out[7] = x108; out[8] = x111; out[9] = x114; }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} } static __always_inline void fe_mul_ttt(fe *h, const fe *f, const fe *g) { fe_mul_impl(h->v, f->v, g->v); } static __always_inline void fe_mul_tlt(fe *h, const fe_loose *f, const fe *g) { fe_mul_impl(h->v, f->v, g->v); } static __always_inline void fe_mul_tll(fe *h, const fe_loose *f, const fe_loose *g) { fe_mul_impl(h->v, f->v, g->v); } static void fe_sqr_impl(u32 out[10], const u32 in1[10]) { { const u32 x17 = in1[9]; { const u32 x18 = in1[8]; { const u32 x16 = in1[7]; { const u32 x14 = in1[6]; { const u32 x12 = in1[5]; { const u32 x10 = in1[4]; { const u32 x8 = in1[3]; { const u32 x6 = in1[2]; { const u32 x4 = in1[1]; { const u32 x2 = in1[0]; { u64 x19 = ((u64)x2 * x2); { u64 x20 = ((u64)(0x2 * x2) * x4); { u64 x21 = (0x2 * (((u64)x4 * x4) + ((u64)x2 * x6))); { u64 x22 = (0x2 * (((u64)x4 * x6) + ((u64)x2 * x8))); { u64 x23 = ((((u64)x6 * x6) + ((u64)(0x4 * x4) * x8)) + ((u64)(0x2 * x2) * x10)); { u64 x24 = (0x2 * ((((u64)x6 * x8) + ((u64)x4 * x10)) + ((u64)x2 * x12))); { u64 x25 = (0x2 * (((((u64)x8 * x8) + ((u64)x6 * x10)) + ((u64)x2 * x14)) + ((u64)(0x2 * x4) * x12))); { u64 x26 = (0x2 * (((((u64)x8 * x10) + ((u64)x6 * x12)) + ((u64)x4 * x14)) + ((u64)x2 * x16))); { u64 x27 = (((u64)x10 * x10) + (0x2 * ((((u64)x6 * x14) + ((u64)x2 * x18)) + (0x2 * (((u64)x4 * x16) + ((u64)x8 * x12)))))); { u64 x28 = (0x2 * ((((((u64)x10 * x12) + ((u64)x8 * x14)) + ((u64)x6 * x16)) + ((u64)x4 * x18)) + ((u64)x2 * x17))); { u64 x29 = (0x2 * (((((u64)x12 * x12) + ((u64)x10 * x14)) + ((u64)x6 * x18)) + (0x2 * (((u64)x8 * x16) + ((u64)x4 * x17))))); { u64 x30 = (0x2 * (((((u64)x12 * x14) + ((u64)x10 * x16)) + ((u64)x8 * x18)) + ((u64)x6 * x17))); { u64 x31 = (((u64)x14 * x14) + (0x2 * (((u64)x10 * x18) + (0x2 * (((u64)x12 * x16) + ((u64)x8 * x17)))))); { u64 x32 = (0x2 * ((((u64)x14 * x16) + ((u64)x12 * x18)) + ((u64)x10 * x17))); { u64 x33 = (0x2 * ((((u64)x16 * x16) + ((u64)x14 * x18)) + ((u64)(0x2 * x12) * x17))); { u64 x34 = (0x2 * (((u64)x16 * x18) + ((u64)x14 * x17))); { u64 x35 = (((u64)x18 * x18) + ((u64)(0x4 * x16) * x17)); { u64 x36 = ((u64)(0x2 * x18) * x17); { u64 x37 = ((u64)(0x2 * x17) * x17); { u64 x38 = (x27 + (x37 << 0x4)); { u64 x39 = (x38 + (x37 << 0x1)); { u64 x40 = (x39 + x37); { u64 x41 = (x26 + (x36 << 0x4)); { u64 x42 = (x41 + (x36 << 0x1)); { u64 x43 = (x42 + x36); { u64 x44 = (x25 + (x35 << 0x4)); { u64 x45 = (x44 + (x35 << 0x1)); { u64 x46 = (x45 + x35); { u64 x47 = (x24 + (x34 << 0x4)); { u64 x48 = (x47 + (x34 << 0x1)); { u64 x49 = (x48 + x34); { u64 x50 = (x23 + (x33 << 0x4)); { u64 x51 = (x50 + (x33 << 0x1)); { u64 x52 = (x51 + x33); { u64 x53 = (x22 + (x32 << 0x4)); { u64 x54 = (x53 + (x32 << 0x1)); { u64 x55 = (x54 + x32); { u64 x56 = (x21 + (x31 << 0x4)); { u64 x57 = (x56 + (x31 << 0x1)); { u64 x58 = (x57 + x31); { u64 x59 = (x20 + (x30 << 0x4)); { u64 x60 = (x59 + (x30 << 0x1)); { u64 x61 = (x60 + x30); { u64 x62 = (x19 + (x29 << 0x4)); { u64 x63 = (x62 + (x29 << 0x1)); { u64 x64 = (x63 + x29); { u64 x65 = (x64 >> 0x1a); { u32 x66 = ((u32)x64 & 0x3ffffff); { u64 x67 = (x65 + x61); { u64 x68 = (x67 >> 0x19); { u32 x69 = ((u32)x67 & 0x1ffffff); { u64 x70 = (x68 + x58); { u64 x71 = (x70 >> 0x1a); { u32 x72 = ((u32)x70 & 0x3ffffff); { u64 x73 = (x71 + x55); { u64 x74 = (x73 >> 0x19); { u32 x75 = ((u32)x73 & 0x1ffffff); { u64 x76 = (x74 + x52); { u64 x77 = (x76 >> 0x1a); { u32 x78 = ((u32)x76 & 0x3ffffff); { u64 x79 = (x77 + x49); { u64 x80 = (x79 >> 0x19); { u32 x81 = ((u32)x79 & 0x1ffffff); { u64 x82 = (x80 + x46); { u64 x83 = (x82 >> 0x1a); { u32 x84 = ((u32)x82 & 0x3ffffff); { u64 x85 = (x83 + x43); { u64 x86 = (x85 >> 0x19); { u32 x87 = ((u32)x85 & 0x1ffffff); { u64 x88 = (x86 + x40); { u64 x89 = (x88 >> 0x1a); { u32 x90 = ((u32)x88 & 0x3ffffff); { u64 x91 = (x89 + x28); { u64 x92 = (x91 >> 0x19); { u32 x93 = ((u32)x91 & 0x1ffffff); { u64 x94 = (x66 + (0x13 * x92)); { u32 x95 = (u32) (x94 >> 0x1a); { u32 x96 = ((u32)x94 & 0x3ffffff); { u32 x97 = (x95 + x69); { u32 x98 = (x97 >> 0x19); { u32 x99 = (x97 & 0x1ffffff); out[0] = x96; out[1] = x99; out[2] = (x98 + x72); out[3] = x75; out[4] = x78; out[5] = x81; out[6] = x84; out[7] = x87; out[8] = x90; out[9] = x93; }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} } static __always_inline void fe_sq_tl(fe *h, const fe_loose *f) { fe_sqr_impl(h->v, f->v); } static __always_inline void fe_sq_tt(fe *h, const fe *f) { fe_sqr_impl(h->v, f->v); } static __always_inline void fe_loose_invert(fe *out, const fe_loose *z) { fe t0; fe t1; fe t2; fe t3; int i; fe_sq_tl(&t0, z); fe_sq_tt(&t1, &t0); for (i = 1; i < 2; ++i) fe_sq_tt(&t1, &t1); fe_mul_tlt(&t1, z, &t1); fe_mul_ttt(&t0, &t0, &t1); fe_sq_tt(&t2, &t0); fe_mul_ttt(&t1, &t1, &t2); fe_sq_tt(&t2, &t1); for (i = 1; i < 5; ++i) fe_sq_tt(&t2, &t2); fe_mul_ttt(&t1, &t2, &t1); fe_sq_tt(&t2, &t1); for (i = 1; i < 10; ++i) fe_sq_tt(&t2, &t2); fe_mul_ttt(&t2, &t2, &t1); fe_sq_tt(&t3, &t2); for (i = 1; i < 20; ++i) fe_sq_tt(&t3, &t3); fe_mul_ttt(&t2, &t3, &t2); fe_sq_tt(&t2, &t2); for (i = 1; i < 10; ++i) fe_sq_tt(&t2, &t2); fe_mul_ttt(&t1, &t2, &t1); fe_sq_tt(&t2, &t1); for (i = 1; i < 50; ++i) fe_sq_tt(&t2, &t2); fe_mul_ttt(&t2, &t2, &t1); fe_sq_tt(&t3, &t2); for (i = 1; i < 100; ++i) fe_sq_tt(&t3, &t3); fe_mul_ttt(&t2, &t3, &t2); fe_sq_tt(&t2, &t2); for (i = 1; i < 50; ++i) fe_sq_tt(&t2, &t2); fe_mul_ttt(&t1, &t2, &t1); fe_sq_tt(&t1, &t1); for (i = 1; i < 5; ++i) fe_sq_tt(&t1, &t1); fe_mul_ttt(out, &t1, &t0); } static __always_inline void fe_invert(fe *out, const fe *z) { fe_loose l; fe_copy_lt(&l, z); fe_loose_invert(out, &l); } /* Replace (f,g) with (g,f) if b == 1; * replace (f,g) with (f,g) if b == 0. * * Preconditions: b in {0,1} */ static __always_inline void fe_cswap(fe *f, fe *g, unsigned int b) { unsigned i; b = 0 - b; for (i = 0; i < 10; i++) { u32 x = f->v[i] ^ g->v[i]; x &= b; f->v[i] ^= x; g->v[i] ^= x; } } /* NOTE: based on fiat-crypto fe_mul, edited for in2=121666, 0, 0.*/ static __always_inline void fe_mul_121666_impl(u32 out[10], const u32 in1[10]) { { const u32 x20 = in1[9]; { const u32 x21 = in1[8]; { const u32 x19 = in1[7]; { const u32 x17 = in1[6]; { const u32 x15 = in1[5]; { const u32 x13 = in1[4]; { const u32 x11 = in1[3]; { const u32 x9 = in1[2]; { const u32 x7 = in1[1]; { const u32 x5 = in1[0]; { const u32 x38 = 0; { const u32 x39 = 0; { const u32 x37 = 0; { const u32 x35 = 0; { const u32 x33 = 0; { const u32 x31 = 0; { const u32 x29 = 0; { const u32 x27 = 0; { const u32 x25 = 0; { const u32 x23 = 121666; { u64 x40 = ((u64)x23 * x5); { u64 x41 = (((u64)x23 * x7) + ((u64)x25 * x5)); { u64 x42 = ((((u64)(0x2 * x25) * x7) + ((u64)x23 * x9)) + ((u64)x27 * x5)); { u64 x43 = (((((u64)x25 * x9) + ((u64)x27 * x7)) + ((u64)x23 * x11)) + ((u64)x29 * x5)); { u64 x44 = (((((u64)x27 * x9) + (0x2 * (((u64)x25 * x11) + ((u64)x29 * x7)))) + ((u64)x23 * x13)) + ((u64)x31 * x5)); { u64 x45 = (((((((u64)x27 * x11) + ((u64)x29 * x9)) + ((u64)x25 * x13)) + ((u64)x31 * x7)) + ((u64)x23 * x15)) + ((u64)x33 * x5)); { u64 x46 = (((((0x2 * ((((u64)x29 * x11) + ((u64)x25 * x15)) + ((u64)x33 * x7))) + ((u64)x27 * x13)) + ((u64)x31 * x9)) + ((u64)x23 * x17)) + ((u64)x35 * x5)); { u64 x47 = (((((((((u64)x29 * x13) + ((u64)x31 * x11)) + ((u64)x27 * x15)) + ((u64)x33 * x9)) + ((u64)x25 * x17)) + ((u64)x35 * x7)) + ((u64)x23 * x19)) + ((u64)x37 * x5)); { u64 x48 = (((((((u64)x31 * x13) + (0x2 * (((((u64)x29 * x15) + ((u64)x33 * x11)) + ((u64)x25 * x19)) + ((u64)x37 * x7)))) + ((u64)x27 * x17)) + ((u64)x35 * x9)) + ((u64)x23 * x21)) + ((u64)x39 * x5)); { u64 x49 = (((((((((((u64)x31 * x15) + ((u64)x33 * x13)) + ((u64)x29 * x17)) + ((u64)x35 * x11)) + ((u64)x27 * x19)) + ((u64)x37 * x9)) + ((u64)x25 * x21)) + ((u64)x39 * x7)) + ((u64)x23 * x20)) + ((u64)x38 * x5)); { u64 x50 = (((((0x2 * ((((((u64)x33 * x15) + ((u64)x29 * x19)) + ((u64)x37 * x11)) + ((u64)x25 * x20)) + ((u64)x38 * x7))) + ((u64)x31 * x17)) + ((u64)x35 * x13)) + ((u64)x27 * x21)) + ((u64)x39 * x9)); { u64 x51 = (((((((((u64)x33 * x17) + ((u64)x35 * x15)) + ((u64)x31 * x19)) + ((u64)x37 * x13)) + ((u64)x29 * x21)) + ((u64)x39 * x11)) + ((u64)x27 * x20)) + ((u64)x38 * x9)); { u64 x52 = (((((u64)x35 * x17) + (0x2 * (((((u64)x33 * x19) + ((u64)x37 * x15)) + ((u64)x29 * x20)) + ((u64)x38 * x11)))) + ((u64)x31 * x21)) + ((u64)x39 * x13)); { u64 x53 = (((((((u64)x35 * x19) + ((u64)x37 * x17)) + ((u64)x33 * x21)) + ((u64)x39 * x15)) + ((u64)x31 * x20)) + ((u64)x38 * x13)); { u64 x54 = (((0x2 * ((((u64)x37 * x19) + ((u64)x33 * x20)) + ((u64)x38 * x15))) + ((u64)x35 * x21)) + ((u64)x39 * x17)); { u64 x55 = (((((u64)x37 * x21) + ((u64)x39 * x19)) + ((u64)x35 * x20)) + ((u64)x38 * x17)); { u64 x56 = (((u64)x39 * x21) + (0x2 * (((u64)x37 * x20) + ((u64)x38 * x19)))); { u64 x57 = (((u64)x39 * x20) + ((u64)x38 * x21)); { u64 x58 = ((u64)(0x2 * x38) * x20); { u64 x59 = (x48 + (x58 << 0x4)); { u64 x60 = (x59 + (x58 << 0x1)); { u64 x61 = (x60 + x58); { u64 x62 = (x47 + (x57 << 0x4)); { u64 x63 = (x62 + (x57 << 0x1)); { u64 x64 = (x63 + x57); { u64 x65 = (x46 + (x56 << 0x4)); { u64 x66 = (x65 + (x56 << 0x1)); { u64 x67 = (x66 + x56); { u64 x68 = (x45 + (x55 << 0x4)); { u64 x69 = (x68 + (x55 << 0x1)); { u64 x70 = (x69 + x55); { u64 x71 = (x44 + (x54 << 0x4)); { u64 x72 = (x71 + (x54 << 0x1)); { u64 x73 = (x72 + x54); { u64 x74 = (x43 + (x53 << 0x4)); { u64 x75 = (x74 + (x53 << 0x1)); { u64 x76 = (x75 + x53); { u64 x77 = (x42 + (x52 << 0x4)); { u64 x78 = (x77 + (x52 << 0x1)); { u64 x79 = (x78 + x52); { u64 x80 = (x41 + (x51 << 0x4)); { u64 x81 = (x80 + (x51 << 0x1)); { u64 x82 = (x81 + x51); { u64 x83 = (x40 + (x50 << 0x4)); { u64 x84 = (x83 + (x50 << 0x1)); { u64 x85 = (x84 + x50); { u64 x86 = (x85 >> 0x1a); { u32 x87 = ((u32)x85 & 0x3ffffff); { u64 x88 = (x86 + x82); { u64 x89 = (x88 >> 0x19); { u32 x90 = ((u32)x88 & 0x1ffffff); { u64 x91 = (x89 + x79); { u64 x92 = (x91 >> 0x1a); { u32 x93 = ((u32)x91 & 0x3ffffff); { u64 x94 = (x92 + x76); { u64 x95 = (x94 >> 0x19); { u32 x96 = ((u32)x94 & 0x1ffffff); { u64 x97 = (x95 + x73); { u64 x98 = (x97 >> 0x1a); { u32 x99 = ((u32)x97 & 0x3ffffff); { u64 x100 = (x98 + x70); { u64 x101 = (x100 >> 0x19); { u32 x102 = ((u32)x100 & 0x1ffffff); { u64 x103 = (x101 + x67); { u64 x104 = (x103 >> 0x1a); { u32 x105 = ((u32)x103 & 0x3ffffff); { u64 x106 = (x104 + x64); { u64 x107 = (x106 >> 0x19); { u32 x108 = ((u32)x106 & 0x1ffffff); { u64 x109 = (x107 + x61); { u64 x110 = (x109 >> 0x1a); { u32 x111 = ((u32)x109 & 0x3ffffff); { u64 x112 = (x110 + x49); { u64 x113 = (x112 >> 0x19); { u32 x114 = ((u32)x112 & 0x1ffffff); { u64 x115 = (x87 + (0x13 * x113)); { u32 x116 = (u32) (x115 >> 0x1a); { u32 x117 = ((u32)x115 & 0x3ffffff); { u32 x118 = (x116 + x90); { u32 x119 = (x118 >> 0x19); { u32 x120 = (x118 & 0x1ffffff); out[0] = x117; out[1] = x120; out[2] = (x119 + x93); out[3] = x96; out[4] = x99; out[5] = x102; out[6] = x105; out[7] = x108; out[8] = x111; out[9] = x114; }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} } static __always_inline void fe_mul121666(fe *h, const fe_loose *f) { fe_mul_121666_impl(h->v, f->v); } static void curve25519_generic(u8 out[CURVE25519_KEY_SIZE], const u8 scalar[CURVE25519_KEY_SIZE], const u8 point[CURVE25519_KEY_SIZE]) { fe x1, x2, z2, x3, z3; fe_loose x2l, z2l, x3l; unsigned swap = 0; int pos; u8 e[32]; memcpy(e, scalar, 32); curve25519_clamp_secret(e); /* The following implementation was transcribed to Coq and proven to * correspond to unary scalar multiplication in affine coordinates given * that x1 != 0 is the x coordinate of some point on the curve. It was * also checked in Coq that doing a ladderstep with x1 = x3 = 0 gives * z2' = z3' = 0, and z2 = z3 = 0 gives z2' = z3' = 0. The statement was * quantified over the underlying field, so it applies to Curve25519 * itself and the quadratic twist of Curve25519. It was not proven in * Coq that prime-field arithmetic correctly simulates extension-field * arithmetic on prime-field values. The decoding of the byte array * representation of e was not considered. * * Specification of Montgomery curves in affine coordinates: * <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Spec/MontgomeryCurve.v#L27> * * Proof that these form a group that is isomorphic to a Weierstrass * curve: * <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/AffineProofs.v#L35> * * Coq transcription and correctness proof of the loop * (where scalarbits=255): * <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/XZ.v#L118> * <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/XZProofs.v#L278> * preconditions: 0 <= e < 2^255 (not necessarily e < order), * fe_invert(0) = 0 */ fe_frombytes(&x1, point); fe_1(&x2); fe_0(&z2); fe_copy(&x3, &x1); fe_1(&z3); for (pos = 254; pos >= 0; --pos) { fe tmp0, tmp1; fe_loose tmp0l, tmp1l; /* loop invariant as of right before the test, for the case * where x1 != 0: * pos >= -1; if z2 = 0 then x2 is nonzero; if z3 = 0 then x3 * is nonzero * let r := e >> (pos+1) in the following equalities of * projective points: * to_xz (r*P) === if swap then (x3, z3) else (x2, z2) * to_xz ((r+1)*P) === if swap then (x2, z2) else (x3, z3) * x1 is the nonzero x coordinate of the nonzero * point (r*P-(r+1)*P) */ unsigned b = 1 & (e[pos / 8] >> (pos & 7)); swap ^= b; fe_cswap(&x2, &x3, swap); fe_cswap(&z2, &z3, swap); swap = b; /* Coq transcription of ladderstep formula (called from * transcribed loop): * <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/XZ.v#L89> * <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/XZProofs.v#L131> * x1 != 0 <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/XZProofs.v#L217> * x1 = 0 <https://github.com/mit-plv/fiat-crypto/blob/2456d821825521f7e03e65882cc3521795b0320f/src/Curves/Montgomery/XZProofs.v#L147> */ fe_sub(&tmp0l, &x3, &z3); fe_sub(&tmp1l, &x2, &z2); fe_add(&x2l, &x2, &z2); fe_add(&z2l, &x3, &z3); fe_mul_tll(&z3, &tmp0l, &x2l); fe_mul_tll(&z2, &z2l, &tmp1l); fe_sq_tl(&tmp0, &tmp1l); fe_sq_tl(&tmp1, &x2l); fe_add(&x3l, &z3, &z2); fe_sub(&z2l, &z3, &z2); fe_mul_ttt(&x2, &tmp1, &tmp0); fe_sub(&tmp1l, &tmp1, &tmp0); fe_sq_tl(&z2, &z2l); fe_mul121666(&z3, &tmp1l); fe_sq_tl(&x3, &x3l); fe_add(&tmp0l, &tmp0, &z3); fe_mul_ttt(&z3, &x1, &z2); fe_mul_tll(&z2, &tmp1l, &tmp0l); } /* here pos=-1, so r=e, so to_xz (e*P) === if swap then (x3, z3) * else (x2, z2) */ fe_cswap(&x2, &x3, swap); fe_cswap(&z2, &z3, swap); fe_invert(&z2, &z2); fe_mul_ttt(&x2, &x2, &z2); fe_tobytes(out, &x2); memzero_explicit(&x1, sizeof(x1)); memzero_explicit(&x2, sizeof(x2)); memzero_explicit(&z2, sizeof(z2)); memzero_explicit(&x3, sizeof(x3)); memzero_explicit(&z3, sizeof(z3)); memzero_explicit(&x2l, sizeof(x2l)); memzero_explicit(&z2l, sizeof(z2l)); memzero_explicit(&x3l, sizeof(x3l)); memzero_explicit(&e, sizeof(e)); }
WireGuard/WireGuard
src/crypto/zinc/curve25519/curve25519-fiat32.c
C
gpl-2.0
30,164
/* * Copyright (c) 2007 Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/cpumask.h> #include <linux/module.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/mlx4/driver.h> #include <linux/mlx4/device.h> #include <linux/mlx4/cmd.h> #include "mlx4_en.h" MODULE_AUTHOR("Liran Liss, Yevgeny Petrilin"); MODULE_DESCRIPTION("Mellanox ConnectX HCA Ethernet driver"); MODULE_LICENSE("Dual BSD/GPL"); MODULE_VERSION(DRV_VERSION " ("DRV_RELDATE")"); static const char mlx4_en_version[] = DRV_NAME ": Mellanox ConnectX HCA Ethernet driver v" DRV_VERSION " (" DRV_RELDATE ")\n"; #define MLX4_EN_PARM_INT(X, def_val, desc) \ static unsigned int X = def_val;\ module_param(X , uint, 0444); \ MODULE_PARM_DESC(X, desc); /* * Device scope module parameters */ /* Enable RSS TCP traffic */ MLX4_EN_PARM_INT(tcp_rss, 1, "Enable RSS for incomming TCP traffic or disabled (0)"); /* Enable RSS UDP traffic */ MLX4_EN_PARM_INT(udp_rss, 1, "Enable RSS for incomming UDP traffic or disabled (0)"); /* Priority pausing */ MLX4_EN_PARM_INT(pfctx, 0, "Priority based Flow Control policy on TX[7:0]." " Per priority bit mask"); MLX4_EN_PARM_INT(pfcrx, 0, "Priority based Flow Control policy on RX[7:0]." " Per priority bit mask"); MLX4_EN_PARM_INT(num_lro, ~0, "Dummy parameter for backward compatibility" ); MLX4_EN_PARM_INT(rss_mask, ~0, "Dummy parameter for backward compatibility" ); MLX4_EN_PARM_INT(rss_xor, ~0, "Dummy parameter for backward compatibility" ); static int mlx4_en_get_profile(struct mlx4_en_dev *mdev) { struct mlx4_en_profile *params = &mdev->profile; int i; params->tcp_rss = tcp_rss; params->udp_rss = udp_rss; if (params->udp_rss && !(mdev->dev->caps.flags & MLX4_DEV_CAP_FLAG_UDP_RSS)) { mlx4_warn(mdev, "UDP RSS is not supported on this device.\n"); params->udp_rss = 0; } for (i = 1; i <= MLX4_MAX_PORTS; i++) { params->prof[i].rx_pause = 1; params->prof[i].rx_ppp = pfcrx; params->prof[i].tx_pause = 1; params->prof[i].tx_ppp = pfctx; params->prof[i].tx_ring_size = MLX4_EN_DEF_TX_RING_SIZE; params->prof[i].rx_ring_size = MLX4_EN_DEF_RX_RING_SIZE; params->prof[i].tx_ring_num = MLX4_EN_NUM_TX_RINGS + (!!pfcrx) * MLX4_EN_NUM_PPP_RINGS; } if ( num_lro != ~0 || rss_mask != ~0 || rss_xor != ~0 ) mlx4_warn(mdev, "Obsolete parameter passed, ignoring.\n"); return 0; } static void *mlx4_en_get_netdev(struct mlx4_dev *dev, void *ctx, u8 port) { struct mlx4_en_dev *endev = ctx; return endev->pndev[port]; } static void mlx4_en_event(struct mlx4_dev *dev, void *endev_ptr, enum mlx4_dev_event event, int port) { struct mlx4_en_dev *mdev = (struct mlx4_en_dev *) endev_ptr; struct mlx4_en_priv *priv; if (!mdev->pndev[port]) return; priv = netdev_priv(mdev->pndev[port]); switch (event) { case MLX4_DEV_EVENT_PORT_UP: case MLX4_DEV_EVENT_PORT_DOWN: /* To prevent races, we poll the link state in a separate task rather than changing it here */ priv->link_state = event; queue_work(mdev->workqueue, &priv->linkstate_task); break; case MLX4_DEV_EVENT_CATASTROPHIC_ERROR: mlx4_err(mdev, "Internal error detected, restarting device\n"); break; default: mlx4_warn(mdev, "Unhandled event: %d\n", event); } } static void mlx4_en_remove(struct mlx4_dev *dev, void *endev_ptr) { struct mlx4_en_dev *mdev = endev_ptr; int i; mutex_lock(&mdev->state_lock); mdev->device_up = false; mutex_unlock(&mdev->state_lock); mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_ETH) if (mdev->pndev[i]) mlx4_en_destroy_netdev(mdev->pndev[i]); flush_workqueue(mdev->workqueue); destroy_workqueue(mdev->workqueue); mlx4_mr_free(dev, &mdev->mr); iounmap(mdev->uar_map); mlx4_uar_free(dev, &mdev->priv_uar); mlx4_pd_free(dev, mdev->priv_pdn); kfree(mdev); } static void *mlx4_en_add(struct mlx4_dev *dev) { static int mlx4_en_version_printed; struct mlx4_en_dev *mdev; int i; int err; if (!mlx4_en_version_printed) { printk(KERN_INFO "%s", mlx4_en_version); mlx4_en_version_printed++; } mdev = kzalloc(sizeof *mdev, GFP_KERNEL); if (!mdev) { dev_err(&dev->pdev->dev, "Device struct alloc failed, " "aborting.\n"); err = -ENOMEM; goto err_free_res; } if (mlx4_pd_alloc(dev, &mdev->priv_pdn)) goto err_free_dev; if (mlx4_uar_alloc(dev, &mdev->priv_uar)) goto err_pd; mdev->uar_map = ioremap((phys_addr_t) mdev->priv_uar.pfn << PAGE_SHIFT, PAGE_SIZE); if (!mdev->uar_map) goto err_uar; spin_lock_init(&mdev->uar_lock); mdev->dev = dev; mdev->dma_device = &(dev->pdev->dev); mdev->pdev = dev->pdev; mdev->device_up = false; mdev->LSO_support = !!(dev->caps.flags & (1 << 15)); if (!mdev->LSO_support) mlx4_warn(mdev, "LSO not supported, please upgrade to later " "FW version to enable LSO\n"); if (mlx4_mr_alloc(mdev->dev, mdev->priv_pdn, 0, ~0ull, MLX4_PERM_LOCAL_WRITE | MLX4_PERM_LOCAL_READ, 0, 0, &mdev->mr)) { mlx4_err(mdev, "Failed allocating memory region\n"); goto err_map; } if (mlx4_mr_enable(mdev->dev, &mdev->mr)) { mlx4_err(mdev, "Failed enabling memory region\n"); goto err_mr; } /* Build device profile according to supplied module parameters */ err = mlx4_en_get_profile(mdev); if (err) { mlx4_err(mdev, "Bad module parameters, aborting.\n"); goto err_mr; } /* Configure which ports to start according to module parameters */ mdev->port_cnt = 0; mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_ETH) mdev->port_cnt++; mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_ETH) { if (!dev->caps.comp_pool) { mdev->profile.prof[i].rx_ring_num = rounddown_pow_of_two(max_t(int, MIN_RX_RINGS, min_t(int, dev->caps.num_comp_vectors, MAX_RX_RINGS))); } else { mdev->profile.prof[i].rx_ring_num = rounddown_pow_of_two( min_t(int, dev->caps.comp_pool/ dev->caps.num_ports - 1 , MAX_MSIX_P_PORT - 1)); } } /* Create our own workqueue for reset/multicast tasks * Note: we cannot use the shared workqueue because of deadlocks caused * by the rtnl lock */ mdev->workqueue = create_singlethread_workqueue("mlx4_en"); if (!mdev->workqueue) { err = -ENOMEM; goto err_mr; } /* At this stage all non-port specific tasks are complete: * mark the card state as up */ mutex_init(&mdev->state_lock); mdev->device_up = true; /* Setup ports */ /* Create a netdev for each port */ mlx4_foreach_port(i, dev, MLX4_PORT_TYPE_ETH) { mlx4_info(mdev, "Activating port:%d\n", i); if (mlx4_en_init_netdev(mdev, i, &mdev->profile.prof[i])) mdev->pndev[i] = NULL; } return mdev; err_mr: mlx4_mr_free(dev, &mdev->mr); err_map: if (!mdev->uar_map) iounmap(mdev->uar_map); err_uar: mlx4_uar_free(dev, &mdev->priv_uar); err_pd: mlx4_pd_free(dev, mdev->priv_pdn); err_free_dev: kfree(mdev); err_free_res: return NULL; } static struct mlx4_interface mlx4_en_interface = { .add = mlx4_en_add, .remove = mlx4_en_remove, .event = mlx4_en_event, .get_dev = mlx4_en_get_netdev, .protocol = MLX4_PROT_ETH, }; static int __init mlx4_en_init(void) { return mlx4_register_interface(&mlx4_en_interface); } static void __exit mlx4_en_cleanup(void) { mlx4_unregister_interface(&mlx4_en_interface); } module_init(mlx4_en_init); module_exit(mlx4_en_cleanup);
XXLRay/linux-2.6.32-rhel6.x86_64
drivers/net/mlx4/en_main.c
C
gpl-2.0
8,619
<?php /* Copyright 2009, idesigneco.com http://idesigneco.com */ class IDE_Validator { public static function validate($method, $data, $arguments = null) { $method = '_'.$method; if(method_exists('IDE_Validator', $method)) { return self::$method($data, $arguments); } } private static function _notEmpty($data) { $data = trim($data); if($data) return true; return false; } private static function _isNumeric($data) { return is_numeric($data); } private static function _isAlpha($data) { return eregi('[^a-z]', $data) ? false : true; } private static function _isAlphaNumeric($data) { return eregi('[^a-z0-9]', $data) ? false : true; } private static function _inLengthRange($data, $lengths) { $data = trim($data); return (strlen($data) >= $lengths[0] && strlen($data) <= $lengths[1]); } private static function _longerThan($data, $length) { $data = trim($data); return (strlen($data) >= $length); } private static function _shorterThan($data, $length) { $data = trim($data); return (strlen($data) <= $length); } private static function _isEmail($data) { if(preg_match('/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $data)) return true; else return false; } } ?>
CoHoop/CoHoop-Blog
wp-content/themes/econews/admin/IDE_Validator.class.php
PHP
gpl-2.0
1,253
<? /* LibreSSL - CAcert web application Copyright (C) 2004-2008 CAcert Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ $img = "/www/stamp/images/CAverify.png"; $arr = explode("//", mysql_real_escape_string(trim($_REQUEST['refer'])), 2); $arr = explode("/", $arr['1'], 2); $ref = $arr['0']; $arr = explode("//", mysql_real_escape_string(trim($_SERVER['HTTP_REFERER'])), 2); $arr = explode("/", $arr['1'], 2); $siteref = $arr['0']; if($_REQUEST['debug'] != 1) header('Content-type: image/png'); $im = imagecreatefrompng($img); if($ref == "" || ($ref != $siteref && $siteref != "")) { $tc = imagecolorallocate ($im, 255, 0, 0); imagestring ($im, 2, 1, 30, "INVALID DOMAIN", $tc); imagestring ($im, 2, 1, 45, "Click to Report", $tc); imagepng($im); exit; } list($invalid, $info) = checkhostname($ref); if($invalid > 0) { $tc = imagecolorallocate ($im, 255, 0, 0); imagestring ($im, 2, 1, 30, "INVALID DOMAIN", $tc); imagestring ($im, 2, 1, 45, "Click to Report", $tc); imagepng($im); exit; } $tz = intval($_REQUEST['tz']); $now = date("Y-m-d", gmmktime("U") + ($tz * 3600)); $tc = imagecolorallocate ($im, 0, 0, 0); imagestring ($im, 4, 1, 27, "Valid Cert!", $tc); imagestring ($im, 1, 7, 42, "Click to Verify", $tc); imagestring ($im, 1, 20, 52, $now, $tc); imagepng($im); ?>
BenBE/CAcert
stamp/displogo.php
PHP
gpl-2.0
1,971
#!/usr/bin/env bash plan 20 . "$LIB_DIR/report_formatting.sh" is \ "$(shorten 10485760 1)" \ "10.0M" \ "10485760, 1 precision, default divisor => 10.0M" is \ "$(shorten 3145728000 1)" \ "2.9G" \ "3145728000, 1 precision, default divisor => 2.9G" is \ "$(shorten 3145728000 1 1000)" \ "3.1G" \ "3145728000, 1 precision, divisor 1000 => 3.1G" is \ "$(shorten 0 0)" \ "0" \ "0, 0 precision, default divisor => 0" is \ "$(shorten 1572864000 1)" \ "1.5G" \ "1572864000, 1 precision, default divisor => 1.5G" is \ "$(shorten 1572864000 1 1000)" \ "1.6G" \ "1572864000, 1 precision, divisor 1000 => 1.6G" is \ "$(shorten 364 0)" \ "364" \ "364, 0 precision, default divisor => 364" is \ "$(shorten 364 1)" \ "364.0" \ "364, 1 precision, default divisor => 364" is \ "$(shorten 649216 1)" \ "634.0k" \ "649216, 1 precision, default divisor => 634.0k" is \ "$(shorten 6492100000006 1)" \ "5.9T" \ "6492100000006, 1 precision, default divisor => 5.9T" is \ "$(shorten 6492100000006 1 1000)" \ "6.5T" \ "6492100000006, 1 precision, divisor 1000 => 6.5T" is "$(shorten 1059586048 1)" \ "1010.5M" \ "1059586048 => 1010.5M (bug 993436)" # section is \ "$(section "A")" \ "# A ##########################################################" \ "Sanity check, section works" is \ "$(section "A B C")" \ "# A B C ######################################################" \ "section doesn't replaces spaces with #s" is \ "$(section "A_B_C")" \ "# A#B#C#######################################################" \ "replace extra underscores with #s" # name_val NAME_VAL_LEN=0 is \ "$(name_val "A" "B")" \ "A | B" \ "name_val and NAME_VAL_LEN work" # fuzz is $(fuzz 11) "10" "fuzz 11" is $(fuzz 49) "50" "fuzz 49" # fuzzy_pct is \ "$( fuzzy_pct 28 64 )" \ "45%" \ "fuzzy_pct of 64 and 28 is 45" is \ "$( fuzzy_pct 40 400 )" \ "10%" \ "fuzzy_pct of 40 and 400 is 10" # ########################################################################### # Done # ###########################################################################
fipar/percona-toolkit
t/lib/bash/report_formatting.sh
Shell
gpl-2.0
2,654
<?php # TemaTres : aplicación para la gestión de lenguajes documentales # # # # # Copyright (C) 2004-2008 Diego Ferreyra tematres@r020.com.ar # Distribuido bajo Licencia GNU Public License, versión 2 (de junio de 1.991) Free Software Foundation # ############################################################################################################### # // Config char encode (only can be: utf-8 or iso-8859-1) $CFG["_CHAR_ENCODE"] ='utf-8'; $page_encode = (in_array($CFG["_CHAR_ENCODE"],array('utf-8','iso-8859-1'))) ? $CFG["_CHAR_ENCODE"] : 'utf-8'; header ('Content-type: text/html; charset='.$page_encode.''); //Config lang $lang=''; $tematres_lang=''; $lang_install=(isset($_GET["lang_install"])) ? $_GET["lang_install"] : 'es'; $lang = $tematres_lang=(in_array($lang_install,array('ca','de','en','es','fr','it','nl','pt'))) ? $lang_install : 'es'; //1. check if config file exist if ( !file_exists('db.tematres.php')) { return message('<div class="error">Configuration file <code>db.tematres.php</code> not found!</div><br/>') ; } else { include('db.tematres.php'); } require_once(T3_ABSPATH . 'common/lang/'.$lang.'-utf-8.inc.php') ; function message($mess) { echo "" ; echo $mess ; echo "<br/>" ; } function checkInstall($lang) { GLOBAL $install_message; $conf_file_path = str_replace("install.php","db.tematres.php","http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']) ; //1. check if config file exist if ( !file_exists('db.tematres.php') ) { return message('<div class="error">'.sprintf($install_message[201],$conf_file_path).'</div><br/>') ; } else { message("<div><span class=\"success\">$install_message[202]</span></div><br/>") ; include('db.tematres.php'); } if($DBCFG["debugMode"]==0) { //silent warnings error_reporting(0); $label_login=''; $label_dbname=''; $label_server=''; } else { $label_login=$DBCFG["DBLogin"]; $label_dbname=$DBCFG["DBName"]; $label_server=$DBCFG["Server"]; }; //2. check connection to server require_once(T3_ABSPATH . 'common/include/adodb5/adodb.inc.php'); //default driver $DBCFG["DBdriver"]=($DBCFG["DBdriver"]) ? $DBCFG["DBdriver"] : "mysqli"; $DB = NewADOConnection($DBCFG["DBdriver"]); if(!$DB->Connect($DBCFG["Server"], $DBCFG["DBLogin"], $DBCFG["DBPass"])) { return message('<div class="error">'.sprintf($install_message[203],$label_server,$label_login,$conf_file_path).'</div><br/>') ; } else { message('<div><span class="success">'.sprintf($install_message[204],$label_server).'</span></div><br/>') ; } //~ //3. check connection to database if(!$DB->Connect($DBCFG["Server"], $DBCFG["DBLogin"], $DBCFG["DBPass"],$DBCFG["DBName"])) { return message('<div class="error">'.sprintf($install_message[205],$label_dbname,$label_server,$conf_file_path).'</div><br/>'); } else { message('<div><span class="success">'.sprintf($install_message[206],$label_dbname,$label_server).'</span></div>'); } //4. check tables $sql=$DB->Execute('SHOW TABLES from `'.$DBCFG["DBName"].'` where `tables_in_'.$DBCFG["DBName"].'` in (\''.$DBCFG["DBprefix"].'config\',\''.$DBCFG["DBprefix"].'indice\',\''.$DBCFG["DBprefix"].'notas\',\''.$DBCFG["DBprefix"].'tabla_rel\',\''.$DBCFG["DBprefix"].'tema\',\''.$DBCFG["DBprefix"].'usuario\',\''.$DBCFG["DBprefix"].'values\')'); if ($DB->Affected_Rows()=='7') { return message("<div class=\"error\">$install_message[301]</div>") ; } else { //Final step: dump or form if ( isset($_POST['send']) ) { $sqlInstall=SQLtematres($DBCFG,$DB); } else { echo HTMLformInstall($lang); } } } function SQLtematres($DBCFG,$DB) { // Si se establecio un charset para la conexion if(@$DBCFG["DBcharset"]){ $DB->Execute("SET NAMES $DBCFG[DBcharset]"); } $prefix=$DBCFG["DBprefix"] ; $result1 = $DB->Execute("CREATE TABLE `".$prefix."config` ( `id` int(5) unsigned NOT NULL auto_increment, `titulo` varchar(255) NOT NULL default '', `autor` varchar(255) NOT NULL default '', `idioma` char(5) NOT NULL default 'es', `cobertura` text, `keywords` varchar(255) default NULL, `tipo` varchar(100) default NULL, `polijerarquia` tinyint(1) NOT NULL default '1', `cuando` date NOT NULL default '0000-00-00', `observa` text, `url_base` varchar(255) default NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM ;") ; //If create table --> insert data if($result1) { $today = date("Y-m-d") ; $url = str_replace("install.php","","http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']) ; $title = ($_POST['title']) ? $DB->qstr(trim($_POST["title"]),get_magic_quotes_gpc()) : "'TemaTres'"; $author = ($_POST['author']) ? $DB->qstr(trim($_POST["author"]),get_magic_quotes_gpc()) : "'TemaTres'"; $tematres_lang=$DB->qstr(trim($_POST["lang"]),get_magic_quotes_gpc()); $tematres_lang=($tematres_lang) ? $tematres_lang : 'es'; $comment = ''; $result2 = $DB->Execute("INSERT INTO `".$prefix."config` (`id`, `titulo`, `autor`, `idioma`, `tipo`, `polijerarquia`, `cuando`, `observa`, `url_base`) VALUES (1, $title, $author, $tematres_lang, 'Controlled vocabulary', 2, '$today', NULL, '$url');") ; } $result3 = $DB->Execute("CREATE TABLE `".$prefix."indice` ( `tema_id` int(11) NOT NULL default '0', `indice` varchar(250) NOT NULL default '', PRIMARY KEY (`tema_id`), KEY `indice` (`indice`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM COMMENT='indice de temas';") ; $result4 = $DB->Execute("CREATE TABLE `".$prefix."notas` ( `id` int(11) NOT NULL auto_increment, `id_tema` int(11) NOT NULL default '0', `tipo_nota` char(3) NOT NULL default 'NA', `lang_nota` varchar(7) default NULL, `nota` mediumtext NOT NULL, `cuando` datetime NOT NULL default '0000-00-00 00:00:00', `uid` int(5) NOT NULL default '0', PRIMARY KEY (`id`), KEY `id_tema` (`id_tema`), KEY `orden_notas` (`tipo_nota`,`lang_nota`), FULLTEXT `notas` (`nota`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM ;") ; $result5 = $DB->Execute("CREATE TABLE `".$prefix."tabla_rel` ( `id_mayor` int(5) NOT NULL default '0', `id_menor` int(5) NOT NULL default '0', `t_relacion` tinyint(1) unsigned NOT NULL default '0', `rel_rel_id` int(22) NULL, `id` int(9) unsigned NOT NULL auto_increment, `uid` int(10) unsigned NOT NULL default '0', `cuando` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `NewIndex` (`id_mayor`,`id_menor`), KEY `unico` (`t_relacion`), KEY `id_menor` (`id_menor`), KEY `id_mayor` (`id_mayor`), KEY `rel_rel_id` (`rel_rel_id`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM ;") ; $result6 = $DB->Execute("CREATE TABLE `".$prefix."tema` ( `tema_id` int(10) NOT NULL auto_increment, `code` VARCHAR( 150 ) NULL COMMENT 'code_term' , `tema` varchar(250) default NULL, `tesauro_id` int(5) NOT NULL default '0', `uid` tinyint(3) unsigned NOT NULL default '0', `cuando` datetime NOT NULL default '0000-00-00 00:00:00', `uid_final` int(5) unsigned default NULL, `cuando_final` datetime default NULL, `estado_id` int(5) NOT NULL default '13', `cuando_estado` datetime NOT NULL default '0000-00-00 00:00:00', `isMetaTerm` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`tema_id`), KEY ( `code` ), KEY `tema` (`tema`), KEY `cuando` (`cuando`,`cuando_final`), KEY `uid` (`uid`,`uid_final`), KEY `tesauro_id` (`tesauro_id`), KEY `estado_id` (`estado_id`), KEY `isMetaTerm` (`isMetaTerm`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM ;") ; $result61 = $DB->Execute("CREATE TABLE IF NOT EXISTS `".$prefix."term2tterm` ( `tterm_id` int(22) NOT NULL AUTO_INCREMENT, `tvocab_id` int(22) NOT NULL, `tterm_url` varchar(200) NOT NULL, `tterm_uri` varchar(200) NOT NULL, `tterm_string` varchar(250) NOT NULL, `cuando` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `cuando_last` timestamp NULL DEFAULT NULL, `uid` int(22) NOT NULL, `tema_id` int(22) NOT NULL, PRIMARY KEY (`tterm_id`), KEY `tvocab_id` (`tvocab_id`,`cuando`,`cuando_last`,`uid`), KEY `tema_id` (`tema_id`), KEY `target_terms` (`tterm_string`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM;") ; $result62 = $DB->Execute("CREATE TABLE IF NOT EXISTS `".$prefix."tvocab` ( `tvocab_id` int(22) NOT NULL AUTO_INCREMENT, `tvocab_label` varchar(150) NOT NULL, `tvocab_tag` varchar(20) NOT NULL, `tvocab_lang` VARCHAR( 5 ), `tvocab_title` varchar(200) NOT NULL, `tvocab_url` varchar(250) NOT NULL, `tvocab_uri_service` varchar(250) NOT NULL, `tvocab_status` tinyint(1) NOT NULL, `cuando` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `uid` int(22) NOT NULL, PRIMARY KEY (`tvocab_id`), KEY `uid` (`uid`), KEY `status` (`tvocab_status`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;") ; $result7 = $DB->Execute("CREATE TABLE `".$prefix."usuario` ( `APELLIDO` varchar(150) default NULL, `NOMBRES` varchar(150) default NULL, `uid` int(9) unsigned default NULL, `cuando` date default NULL, `id` int(11) unsigned NOT NULL auto_increment, `mail` varchar(255) default NULL, `pass` varchar(60) NOT NULL default '', `orga` varchar(255) default NULL, `nivel` tinyint(1) unsigned NOT NULL default '2', `estado` set('ACTIVO','BAJA') NOT NULL default 'BAJA', `hasta` datetime NOT NULL default '0000-00-00 00:00:00', `user_activation_key` varchar(60) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mail` (`mail`), KEY `pass` (`pass`), KEY `user_activation_key` (`user_activation_key`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM ;") ; $result9 = $DB->Execute("CREATE TABLE `".$prefix."values` ( `value_id` int(11) NOT NULL auto_increment, `value_type` varchar(64) NOT NULL default '0', `value` longtext NOT NULL , `value_order` tinyint(4) default NULL, `value_code` varchar(20) default NULL, PRIMARY KEY (`value_id`), KEY `value_type` (`value_type`) ) DEFAULT CHARSET=utf8 ENGINE=MyISAM COMMENT='general values table';") ; $result10 = $DB->Execute("CREATE TABLE `".$prefix."uri` ( `uri_id` int(22) NOT NULL AUTO_INCREMENT, `tema_id` int(22) NOT NULL, `uri_type_id` int(22) NOT NULL, `uri` tinytext NOT NULL, `uid` int(22) NOT NULL, `cuando` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`uri_id`), KEY `tema_id` (`tema_id`) ) CHARSET=utf8 ENGINE=MyISAM COMMENT='external URIs associated to terms';"); $result10 = $DB->Execute("INSERT INTO `".$prefix."values` (`value_id`, `value_type`, `value`, `value_order`, `value_code`) VALUES (2, 't_relacion', 'Termino relacionado', NULL, 'TR'), (3, 't_relacion', 'Termino superior', NULL, 'TG'), (4, 't_relacion', 'Usado por', NULL, 'UP'), (5, 't_relacion', 'Equivalencia parcial', NULL, 'EQ_P'), (6, 't_relacion', 'Equivalencia total', NULL, 'EQ'), (7, 't_relacion', 'No equivalencia', NULL, 'EQ_NO'), (8, 't_nota', 'Nota de alcance', 1, 'NA'), (9, 't_nota', 'Nota histórica', 2, 'NH'), (10, 't_nota', 'Nota bibliografica', 3, 'NB'), (11, 't_nota', 'Nota privada', 4, 'NP'), (1, 't_usuario', 'Admin', NULL, 'admin'), (12, 't_estado', 'termino candidato', 1, 'C'), (13, 't_estado', 'termino activo', 2, 'A'), (14, 't_estado', 'termino rechazado', 3, 'R'), (15, 't_nota', 'Nota catalográfica', 2, 'NC'), (16, 'config', '_USE_CODE', 1, '0'), (17, 'config', '_SHOW_CODE', 1, '0'), (18, 'config', 'CFG_MAX_TREE_DEEP', NULL, '3'), (19, 'config', 'CFG_VIEW_STATUS', NULL, '0'), (20, 'config', 'CFG_SIMPLE_WEB_SERVICE', NULL, '1'), (21, 'config', 'CFG_NUM_SHOW_TERMSxSTATUS', NULL, '200'), (22, 'config', 'CFG_MIN_SEARCH_SIZE', NULL, '2'), (23, 'config', '_SHOW_TREE', '1', '1'), (24, 'config', '_PUBLISH_SKOS', '1', '0'), (25,'4', 'Spelling variant', NULL, 'SP'), (26,'4', 'MisSpelling', NULL, 'MS'), (27,'3', 'Partitive', NULL, 'P'), (28,'3', 'Instance', NULL, 'I'), (30,'4', 'Abbreviation', NULL, 'AB'), (31,'4', 'Full form of the term', NULL, 'FT'), (32,'URI_TYPE', 'broadMatch', NULL, 'broadMatch'), (33,'URI_TYPE', 'closeMatch', NULL, 'closeMatch'), (34,'URI_TYPE', 'exactMatch', NULL, 'exactMatch'), (35,'URI_TYPE', 'relatedMatch', NULL, 'relatedMatch'), (36,'URI_TYPE', 'narrowMatch', NULL, 'narrowMatch'), (37,'DATESTAMP',now(), NULL,'NOTE_CHANGE'), (38,'DATESTAMP',now(), NULL,'TERM_CHANGE'), (39,'DATESTAMP',now(), NULL,'TTERM_CHANGE'), (40,'DATESTAMP',now(), NULL,'THES_CHANGE'), (41,'METADATA',NULL, 2,'dc:contributor'), (42,'METADATA',NULL, 5,'dc:publisher'), (43,'METADATA',NULL, 9,'dc:rights'), (44,'4', 'Hidden', NULL, 'H'), (45, 'config', 'CFG_SEARCH_METATERM', NULL, '0'), (46, 'config', 'CFG_ENABLE_SPARQL', NULL, '0'), (47, 'config', 'CFG_SUGGESTxWORD', NULL, '1') "); //If create table --> insert data if(is_object($result7)) { $admin_mail=($_POST['mail']) ? $DB->qstr(trim($_POST['mail']),get_magic_quotes_gpc()) : "'admin@r020.com.ar'"; $admin_name=($_POST['name']) ? $DB->qstr(trim($_POST['name']),get_magic_quotes_gpc()) : "'admin name'"; $admin_surname=($_POST['s_name']) ? $DB->qstr(trim($_POST['s_name']),get_magic_quotes_gpc()) : "'admin sur name'"; $admin_pass=($_POST['mdp']) ? trim($_POST['mdp']) : "'admin'"; require_once(T3_ABSPATH . 'common/include/fun.gral.php'); $admin_pass_hash=(CFG_HASH_PASS==1) ? t3_hash_password($admin_pass) : $admin_pass; $admin_pass_hash=($admin_pass_hash) ? $DB->qstr(trim($admin_pass_hash),get_magic_quotes_gpc()) : "'admin'"; $result8=$DB->Execute("INSERT INTO `".$prefix."usuario` (`APELLIDO`, `NOMBRES`, `uid`, `cuando`, `id`, `mail`, `pass`, `orga`, `nivel`, `estado`, `hasta`) VALUES ($admin_name,$admin_surname, 1, now(), 1, $admin_mail,$admin_pass_hash, 'TemaTres', 1, 'ACTIVO', now())") ; //echo $DB->ErrorMsg(); //Tematres installed if(is_object($result8)) { GLOBAL $install_message; $return_true = '<div class="information">'; $return_true .= '<h3>'.ucfirst(LABEL_bienvenida).'</h3>' ; $return_true .= '<span style="text-decoration: underline">'.$install_message[306].'</span>' ; //~ Not echo for security //~ $return_true .='<li>'.ucfirst(LABEL_mail).': '.$admin_mail.'</li>' ; //~ $return_true .= '<li>'.ucfirst(LABEL_pass).' : '.$admin_pass.'</li>' ; $return_true .='</div>'; message($return_true); } } } function HTMLformInstall($lang_install) { GLOBAL $install_message; require_once(T3_ABSPATH . 'common/include/config.tematres.php'); require_once(T3_ABSPATH . 'common/include/fun.gral.php'); $arrayLang=array(); foreach ($CFG["ISO639-1"] as $langs) { array_push($arrayLang,"$langs[0]#$langs[1]"); }; $rows='<div><form class="myform" id="formulaire" name="formulaire" method="post" action=""> <fieldset> <legend style="margin-bottom: 5px;">'.ucfirst(LABEL_lcDatos).'</legend>'; $rows.='<div><label for="title">'.ucfirst(LABEL_Titulo).'</label> <input type="text" class="campo" id="title" name="title"/></div> <div><label for="author">'.ucfirst(LABEL_Autor).'</label> <input type="text" name="author" id="author" class="campo"/></div>'; $rows.='<div class="formdiv"> <label for="'.FORM_LABEL_Idioma.'" accesskey="l">'.LABEL_Idioma.'</label> <select id="lang" name="lang">'.doSelectForm($arrayLang,$lang_install).'</select> </div>'; $rows.='</fieldset>'; $rows.='<fieldset> <legend style="margin-bottom: 5px;">'.ucfirst(MENU_NuevoUsuario).'</legend> <div><label for="name">'.ucfirst(LABEL_nombre).'</label> <input type="text" name="name"/></div> <div><label for="s_name">'.ucfirst(LABEL_apellido).'</label> <input type="text" name="s_name"/></div> <div><label for="mail">'.ucfirst(LABEL_mail).'</label> <input type="text" name="mail"/> </div> <div><label for="mdp">'.ucfirst(LABEL_pass).'</label> <input type="password" name="mdp" id="mdp" onkeyup="test_password();" onclick="if (document.formulaire.saisie.value == \'password\') this.value = \'\'; test_password();"/> <img src="images/sec0.png" name="img_secu" height="20" width="0"/> </div> <div><label for="mdp">'.ucfirst(LABEL_repass).'</label> <input type="password" name="repass" /> </div> <input name="resultat" type="hidden" value="bon" /> <input name="securite" type="hidden" value="" /> '; $rows.='<div style="margin-left:15em"><input class="submit ui-corner-all" type="submit" name="send" value="'.ucfirst(LABEL_Enviar).'" /></div> </fieldset> </form></div>'; return $rows; }; ?> <!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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo $install_message[101]; ?></title> <link rel="stylesheet" href="../common/css/install.css" type="text/css" media="all" /> <link type="image/x-icon" href="../common/images/tematres.ico" rel="icon" /> <link type="image/x-icon" href="../common/images/tematres.ico" rel="shortcut icon" /> <script type="text/javascript"> function test_password() { var securite = 0 ; document.formulaire.mdp.value = document.formulaire.mdp.value.replace(/[^A-Za-z0-9_-]/g,"_") ; document.formulaire.resultat.value = "rien" ; if ( document.formulaire.mdp.value.match(/[A-Z]/) ) securite++ ; if ( document.formulaire.mdp.value.match(/[a-z]/) ) securite++ ; if ( document.formulaire.mdp.value.match(/[0-9]/) ) securite++ ; //document.formulaire.resultat.value = document.formulaire.saisie.value.length ; var longueur = document.formulaire.mdp.value.length ; if ( longueur >= 4 ) securite++ ; if ( longueur >= 6 ) securite++ ; if ( longueur >= 8 ) securite++ ; //document.formulaire.securite.value = securite + " (de 1 Ã 6)"; document.img_secu.width = securite * 9 *securite + 10 ; switch ( securite ) { case 0 : document.img_secu.src = "../common/images/sec0.png" ; break ; case 1 : document.img_secu.src = "../common/images/sec1.png" ; break ; case 2 : document.img_secu.src = "../common/images/sec1.png" ; break ; case 3 : document.img_secu.src = "../common/images/sec2.png" ; break ; case 4 : document.img_secu.src = "../common/images/sec3.png" ; break ; case 5 : document.img_secu.src = "../common/images/sec3.png" ; break ; case 6 : document.img_secu.src = "../common/images/sec4.png" ; break ; default : document.img_secu.src = "../common/images/sec1.png" ; } } </script> <script type="text/javascript" src="../common/jq/lib/jquery-1.8.0.min.js"></script> <script type="text/javascript" src="../common/forms/jquery.validate.min.js"></script> <script type="text/javascript">$("#formulaire").validate({});</script> <?php if($lang!=='en') echo '<script src="../common/forms/localization/messages_'.$lang.'.js" type="text/javascript"></script>'; ?> <script id="install_script" type="text/javascript"> $(document).ready(function() { var validator = $("#formulaire").validate({ rules: {'title': {required: true}, 'author': {required: true}, 'mail': {required: true,email: true}, 'mdp': { required:true, minlength: 5}, 'repass': {equalTo: "#mdp"} }, debug: true, errorElement: "label", submitHandler: function(form) { form.submit(); } }); }); </script> </head> <body onload="test_password();"> <div id="header"> <h1><?php echo $install_message[101];?></h1> </div> <div id="bodyText"> <div id="select_lang"> <form class="myform" action="install.php" method="get" name="lang" id="lang"> <label for="lang_install"><?php echo LABEL_Idioma;?></label> <select id="lang_install" name="lang_install" onChange="document.lang.submit()"> <option><?php echo LABEL_Idioma;?></option> <option value="ca">català</option> <option value="en">english</option> <option value="es">español</option> <option value="fr">fran&ccedil;ais</option> <option value="pt">portug&uuml;&eacute;s</option> </select> </form> </div> <div class="clear"> <?php echo checkInstall($lang); ?> </div> <!-- ###### Footer ###### --> </div> <div> <div id="footer" style="height: 50px;"> <!-- NB: outer <div> required for correct rendering in IE --> <div style="float: left; width: 70px;"> <a href="http://r020.com.ar/tematres/" title="TemaTres: vocabulary server"><img src="common/images/tematresfoot.jpg" alt="TemaTres" /></a> </div> <div> <strong>TemaTres</strong> <span class="footerCol2"> Vocabulary Server</span> </div> <div> <strong><?php echo LABEL_URI ?>: </strong> <span class="footerCol2"> <?php echo str_replace("install.php","","http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']);?></span> </div> </div></div> </body> </html>
SIBiUSP/tematres
version181/src/install.php
PHP
gpl-2.0
22,231
<?php /** This file is part of KCFinder project * * @desc Settings panel functionality * @package KCFinder * @version 2.31 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010, 2011 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */?> browser.initSettings = function() { if (!this.shows.length) { var showInputs = $('#show input[type="checkbox"]').toArray(); $.each(showInputs, function (i, input) { browser.shows[i] = input.name; }); } var shows = this.shows; if (!_.kuki.isSet('showname')) { _.kuki.set('showname', 'on'); $.each(shows, function (i, val) { if (val != "name") _.kuki.set('show' + val, 'off'); }); } $('#show input[type="checkbox"]').click(function() { var kuki = $(this).get(0).checked ? 'on' : 'off'; _.kuki.set('show' + $(this).get(0).name, kuki) if ($(this).get(0).checked) $('#files .file div.' + $(this).get(0).name).css('display', 'block'); else $('#files .file div.' + $(this).get(0).name).css('display', 'none'); }); $.each(shows, function(i, val) { var checked = (_.kuki.get('show' + val) == 'on') ? 'checked' : ''; $('#show input[name="' + val + '"]').get(0).checked = checked; }); if (!this.orders.length) { var orderInputs = $('#order input[type="radio"]').toArray(); $.each(orderInputs, function (i, input) { browser.orders[i] = input.value; }); } var orders = this.orders; if (!_.kuki.isSet('order')) _.kuki.set('order', 'name'); if (!_.kuki.isSet('orderDesc')) _.kuki.set('orderDesc', 'off'); $('#order input[value="' + _.kuki.get('order') + '"]').get(0).checked = true; $('#order input[name="desc"]').get(0).checked = (_.kuki.get('orderDesc') == 'on'); $('#order input[type="radio"]').click(function() { _.kuki.set('order', $(this).get(0).value); browser.orderFiles(); }); $('#order input[name="desc"]').click(function() { _.kuki.set('orderDesc', $(this).get(0).checked ? "on" : "off"); browser.orderFiles(); }); if (!_.kuki.isSet('view')) _.kuki.set('view', 'thumbs'); if (_.kuki.get('view') == "list") { $('#show input').each(function() { this.checked = true; }); $('#show input').each(function() { this.disabled = true; }); } $('#view input[value="' + _.kuki.get('view') + '"]').get(0).checked = true; $('#view input').click(function() { var view = $(this).attr('value'); if (_.kuki.get('view') != view) { _.kuki.set('view', view); if (view == 'list') { $('#show input').each(function() { this.checked = true; }); $('#show input').each(function() { this.disabled = true; }); } else { $.each(browser.shows, function(i, val) { $('#show input[name="' + val + '"]').get(0).checked = (_.kuki.get('show' + val) == "on"); }); $('#show input').each(function() { this.disabled = false; }); } } browser.refresh(); }); };
loadedcommerce/Loaded6CE
Loaded_Commerce_CE/admin/editors/kcfinder/js/browser/settings.js
JavaScript
gpl-2.0
3,422
var http = require('http'); function jsonHttpRequest(host, port, data, callback){ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', 'Accept': 'application/json' } }; var req = http.request(options, function(res){ var replyData = ''; res.setEncoding('utf8'); res.on('data', function(chunk){ replyData += chunk; }); res.on('end', function(){ var replyJson; try{ replyJson = JSON.parse(replyData); } catch(e){ callback(e); return; } callback(null, replyJson); }); }); req.on('error', function(e){ callback(e); }); req.end(data); } function rpc(host, port, method, params, callback){ var data = JSON.stringify({ id: "0", jsonrpc: "2.0", method: method, params: params }); jsonHttpRequest(host, port, data, function(error, replyJson){ if (error){ callback(error); return; } callback(replyJson.error, replyJson.result) }); } function batchRpc(host, port, array, callback){ var rpcArray = []; for (var i = 0; i < array.length; i++){ rpcArray.push({ id: i.toString(), jsonrpc: "2.0", method: array[i][0], params: array[i][1] }); } var data = JSON.stringify(rpcArray); jsonHttpRequest(host, port, data, callback); } module.exports = function(daemonConfig, walletConfig){ return { batchRpcDaemon: function(batchArray, callback){ batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback); }, rpcDaemon: function(method, params, callback){ rpc(daemonConfig.host, daemonConfig.port, method, params, callback); }, rpcWallet: function(method, params, callback){ rpc(walletConfig.host, walletConfig.port, method, params, callback); } } };
xpbcreator/pebblepool
lib/apiInterfaces.js
JavaScript
gpl-2.0
2,222
// you need the Oopo ps3libraries to work with freetype #include <ft2build.h> #include <freetype/freetype.h> #include <freetype/ftglyph.h> #include "ttf_render.h" /******************************************************************************************************************************************************/ /* TTF functions to load and convert fonts */ /******************************************************************************************************************************************************/ static int ttf_inited = 0; static FT_Library freetype; static FT_Face face[4]; static int f_face[4] = {0, 0, 0, 0}; int TTFLoadFont(int set, char * path, void * from_memory, int size_from_memory) { if(!ttf_inited) FT_Init_FreeType(&freetype); ttf_inited = 1; f_face[set] = 0; if(path) { if(FT_New_Face(freetype, path, 0, &face[set])<0) return -1; } else if(FT_New_Memory_Face(freetype, from_memory, size_from_memory, 0, &face[set])) { return -1; } f_face[set] = 1; return 0; } /* release all */ void TTFUnloadFont() { if(!ttf_inited) return; FT_Done_FreeType(freetype); ttf_inited = 0; } /* function to render the character chr : character from 0 to 255 bitmap: u8 bitmap passed to render the character character (max 256 x 256 x 1 (8 bits Alpha)) *w : w is the bitmap width as input and the width of the character (used to increase X) as output *h : h is the bitmap height as input and the height of the character (used to Y correction combined with y_correction) as output y_correction : the Y correction to display the character correctly in the screen */ void TTF_to_Bitmap(u8 chr, u8 * bitmap, short *w, short *h, short *y_correction) { if(f_face[0]) FT_Set_Pixel_Sizes(face[0], (*w), (*h)); if(f_face[1]) FT_Set_Pixel_Sizes(face[1], (*w), (*h)); if(f_face[2]) FT_Set_Pixel_Sizes(face[2], (*w), (*h)); if(f_face[3]) FT_Set_Pixel_Sizes(face[3], (*w), (*h)); FT_GlyphSlot slot; memset(bitmap, 0, (*w) * (*h)); FT_UInt index; if(f_face[0] && (index = FT_Get_Char_Index(face[0], (char) chr))!=0 && !FT_Load_Glyph(face[0], index, FT_LOAD_RENDER )) slot = face[0]->glyph; else if(f_face[1] && (index = FT_Get_Char_Index(face[1], (char) chr))!=0 && !FT_Load_Glyph(face[1], index, FT_LOAD_RENDER )) slot = face[1]->glyph; else if(f_face[2] && (index = FT_Get_Char_Index(face[2], (char) chr))!=0 && !FT_Load_Glyph(face[2], index, FT_LOAD_RENDER )) slot = face[2]->glyph; else if(f_face[3] && (index = FT_Get_Char_Index(face[3], (char) chr))!=0 && !FT_Load_Glyph(face[3], index, FT_LOAD_RENDER )) slot = face[3]->glyph; else {(*w) = 0; return;} int n, m, ww; *y_correction = (*h) - 1 - slot->bitmap_top; ww = 0; for(n = 0; n < slot->bitmap.rows; n++) { for (m = 0; m < slot->bitmap.width; m++) { if(m >= (*w) || n >= (*h)) continue; bitmap[m] = (u8) slot->bitmap.buffer[ww + m]; } bitmap += *w; ww += slot->bitmap.width; } *w = ((slot->advance.x + 31) >> 6) + ((slot->bitmap_left < 0) ? -slot->bitmap_left : 0); *h = slot->bitmap.rows; } int Render_String_UTF8(u16 * bitmap, int w, int h, u8 *string, int sw, int sh) { int posx = 0; int n, m, ww, ww2; u8 color; u32 ttf_char; if(f_face[0]) FT_Set_Pixel_Sizes(face[0], sw, sh); if(f_face[1]) FT_Set_Pixel_Sizes(face[1], sw, sh); if(f_face[2]) FT_Set_Pixel_Sizes(face[2], sw, sh); if(f_face[3]) FT_Set_Pixel_Sizes(face[3], sw, sh); //FT_Set_Pixel_Sizes(face, sw, sh); FT_GlyphSlot slot = NULL; memset(bitmap, 0, w * h * 2); while(*string) { if(*string == 32 || *string == 9) {posx += sw>>1; string++; continue;} if(*string & 128) { m = 1; if((*string & 0xf8) == 0xf0) { // 4 bytes ttf_char = (u32) (*(string++) & 3); m = 3; } else if((*string & 0xE0) == 0xE0) { // 3 bytes ttf_char = (u32) (*(string++) & 0xf); m = 2; } else if((*string & 0xE0) == 0xC0) { // 2 bytes ttf_char = (u32) (*(string++) & 0x1f); m = 1; } else {string++; continue;} // error! for(n = 0; n < m; n++) { if(!*string) break; // error! if((*string & 0xc0) != 0x80) break; // error! ttf_char = (ttf_char <<6) |((u32) (*(string++) & 63)); } if((n != m) && !*string) break; } else ttf_char = (u32) *(string++); if(ttf_char == 13 || ttf_char == 10) ttf_char='/'; FT_UInt index; if(f_face[0] && (index = FT_Get_Char_Index(face[0], ttf_char))!=0 && !FT_Load_Glyph(face[0], index, FT_LOAD_RENDER )) slot = face[0]->glyph; else if(f_face[1] && (index = FT_Get_Char_Index(face[1], ttf_char))!=0 && !FT_Load_Glyph(face[1], index, FT_LOAD_RENDER )) slot = face[1]->glyph; else if(f_face[2] && (index = FT_Get_Char_Index(face[2], ttf_char))!=0 && !FT_Load_Glyph(face[2], index, FT_LOAD_RENDER )) slot = face[2]->glyph; else if(f_face[3] && (index = FT_Get_Char_Index(face[3], ttf_char))!=0 && !FT_Load_Glyph(face[3], index, FT_LOAD_RENDER )) slot = face[3]->glyph; else ttf_char = 0; if(ttf_char!=0 && slot->bitmap.buffer) { ww = ww2 = 0; int y_correction = sh - 1 - slot->bitmap_top; if(y_correction < 0) y_correction = 0; ww2 = y_correction * w; for(n = 0; n < slot->bitmap.rows; n++) { if(n + y_correction >= h) break; for (m = 0; m < slot->bitmap.width; m++) { if(m + posx >= w) continue; color = (u8) slot->bitmap.buffer[ww + m]; if(color) bitmap[posx + m + ww2] = (color<<8) | 0xfff; } ww2 += w; ww += slot->bitmap.width; } } if(slot) posx+= slot->bitmap.width; } return posx; } // constructor dinámico de fuentes 32 x 32 typedef struct ttf_dyn { u32 ttf; u16 *text; u32 r_use; u16 y_start; u16 width; u16 height; u16 flags; } ttf_dyn; #define MAX_CHARS 1600 static ttf_dyn ttf_font_datas[MAX_CHARS]; static u32 r_use= 0; float Y_ttf = 0.0f; float Z_ttf = 0.0f; static int Win_X_ttf = 0; static int Win_Y_ttf = 0; static int Win_W_ttf = 848; static int Win_H_ttf = 512; static u32 Win_flag = 0; void set_ttf_window(int x, int y, int width, int height, u32 mode) { Win_X_ttf = x; Win_Y_ttf = y; Win_W_ttf = width; Win_H_ttf = height; Win_flag = mode; Y_ttf = 0.0f; Z_ttf = 0.0f; } u16 * init_ttf_table(u16 *texture) { int n; r_use = 0; for(n = 0; n < MAX_CHARS; n++) { memset(&ttf_font_datas[n], 0, sizeof(ttf_dyn)); ttf_font_datas[n].text = texture; texture += 32 * 32; } return texture; } void reset_ttf_frame(void) { int n; for(n = 0; n < MAX_CHARS; n++) { ttf_font_datas[n].flags &= 1; } r_use++; } static void DrawBox_ttf(float x, float y, float z, float w, float h, u32 rgba) { tiny3d_SetPolygon(TINY3D_QUADS); tiny3d_VertexPos(x , y , z); tiny3d_VertexColor(rgba); tiny3d_VertexPos(x + w, y , z); tiny3d_VertexPos(x + w, y + h, z); tiny3d_VertexPos(x , y + h, z); tiny3d_End(); } static void DrawTextBox_ttf(float x, float y, float z, float w, float h, u32 rgba, float tx, float ty) { tiny3d_SetPolygon(TINY3D_QUADS); tiny3d_VertexPos(x , y , z); tiny3d_VertexColor(rgba); tiny3d_VertexTexture(0.0f , 0.0f); tiny3d_VertexPos(x + w, y , z); tiny3d_VertexTexture(tx, 0.0f); tiny3d_VertexPos(x + w, y + h, z); tiny3d_VertexTexture(tx, ty); tiny3d_VertexPos(x , y + h, z); tiny3d_VertexTexture(0.0f , ty); tiny3d_End(); } #define UX 30 #define UY 24 int display_ttf_string(int posx, int posy, char *string, u32 color, u32 bkcolor, int sw, int sh) { int l,n, m, ww, ww2; u8 colorc; u32 ttf_char; u8 *ustring = (u8 *) string; int lenx = 0; while(*ustring) { if(posy >= Win_H_ttf) break; if(*ustring == 32 || *ustring == 9) {posx += sw>>1; ustring++; continue;} if(*ustring & 128) { m = 1; if((*ustring & 0xf8) == 0xf0) { // 4 bytes ttf_char = (u32) (*(ustring++) & 3); m = 3; } else if((*ustring & 0xE0) == 0xE0) { // 3 bytes ttf_char = (u32) (*(ustring++) & 0xf); m = 2; } else if((*ustring & 0xE0) == 0xC0) { // 2 bytes ttf_char = (u32) (*(ustring++) & 0x1f); m = 1; } else {ustring++;continue;} // error! for(n = 0; n < m; n++) { if(!*ustring) break; // error! if((*ustring & 0xc0) != 0x80) break; // error! ttf_char = (ttf_char <<6) |((u32) (*(ustring++) & 63)); } if((n != m) && !*ustring) break; } else ttf_char = (u32) *(ustring++); if(Win_flag & WIN_SKIP_LF) { if(ttf_char == '\r' || ttf_char == '\n') ttf_char = '/'; } else { if(Win_flag & WIN_DOUBLE_LF) { if(ttf_char == '\r') {if(posx > lenx) lenx = posx; posx = 0;continue;} if(ttf_char == '\n') {posy += sh;continue;} } else { if(ttf_char == '\n') {if(posx > lenx) lenx = posx; posx = 0;posy += sh;continue;} } } if(ttf_char < 32) ttf_char='?'; // search ttf_char if(ttf_char < 128) n= ttf_char; else { m = 0; int rel = 0; for(n= 128; n < MAX_CHARS; n++) { if(!(ttf_font_datas[n].flags & 1)) m = n; if((ttf_font_datas[n].flags & 3) == 1) { int trel = r_use - ttf_font_datas[n].r_use; if(m == 0) {m = n; rel = trel;} else if(rel > trel) {m = n; rel = trel;} } if(ttf_font_datas[n].ttf == ttf_char) break; } if(m == 0) m = 128; } if(n >= MAX_CHARS) {ttf_font_datas[m].flags = 0; l = m;} else l = n; u16 * bitmap = ttf_font_datas[l].text; // building the character if(!(ttf_font_datas[l].flags & 1)) { if(f_face[0]) FT_Set_Pixel_Sizes(face[0], UX, UY); if(f_face[1]) FT_Set_Pixel_Sizes(face[1], UX, UY); if(f_face[2]) FT_Set_Pixel_Sizes(face[2], UX, UY); if(f_face[3]) FT_Set_Pixel_Sizes(face[3], UX, UY); FT_GlyphSlot slot = NULL; memset(bitmap, 0, 32 * 32 * 2); /////////// FT_UInt index; if(f_face[0] && (index = FT_Get_Char_Index(face[0], ttf_char)) != 0 && !FT_Load_Glyph(face[0], index, FT_LOAD_RENDER )) slot = face[0]->glyph; else if(f_face[1] && (index = FT_Get_Char_Index(face[1], ttf_char)) != 0 && !FT_Load_Glyph(face[1], index, FT_LOAD_RENDER )) slot = face[1]->glyph; else if(f_face[2] && (index = FT_Get_Char_Index(face[2], ttf_char)) != 0 && !FT_Load_Glyph(face[2], index, FT_LOAD_RENDER )) slot = face[2]->glyph; else if(f_face[3] && (index = FT_Get_Char_Index(face[3], ttf_char)) != 0 && !FT_Load_Glyph(face[3], index, FT_LOAD_RENDER )) slot = face[3]->glyph; else ttf_char = 0; if(ttf_char != 0) { ww = ww2 = 0; int y_correction = UY - 1 - slot->bitmap_top; if(y_correction < 0) y_correction = 0; ttf_font_datas[l].flags = 1; ttf_font_datas[l].y_start = y_correction; ttf_font_datas[l].height = slot->bitmap.rows; ttf_font_datas[l].width = slot->bitmap.width; ttf_font_datas[l].ttf = ttf_char; for(n = 0; n < slot->bitmap.rows; n++) { if(n >= 32) break; for (m = 0; m < slot->bitmap.width; m++) { if(m >= 32) continue; colorc = (u8) slot->bitmap.buffer[ww + m]; if(colorc) bitmap[m + ww2] = (colorc<<8) | 0xfff; } ww2 += 32; ww += slot->bitmap.width; } } } // displaying the character ttf_font_datas[l].flags |= 2; // in use ttf_font_datas[l].r_use = r_use; tiny3d_SetTextureWrap(0, tiny3d_TextureOffset(bitmap), 32, 32, 32 * 2, TINY3D_TEX_FORMAT_A4R4G4B4, TEXTWRAP_CLAMP, TEXTWRAP_CLAMP,1); //DrawTextBox_ttf((float) posx, (float) posy/* + ((float) ttf_font_datas[l].y_start * sh) * 0.03125f*/, 0.0f, (float) sw, (float) sh, color, // 0.0309375f * (float) ttf_font_datas[l].width, 0.0309375f * (float) ttf_font_datas[l].height); if((Win_flag & WIN_AUTO_LF) && (posx + (ttf_font_datas[l].width * sw / 32) + 1) > Win_W_ttf) { posx = 0; posy += sh; } u32 ccolor = color; u32 cx =(ttf_font_datas[l].width * sw / 32) + 1; // skip if out of window if((posx + cx) > Win_W_ttf || (posy + sh) > Win_H_ttf ) ccolor = 0; if(ccolor) { DrawBox_ttf((float) (Win_X_ttf + posx), (float) (Win_Y_ttf + posy) + ((float) ttf_font_datas[l].y_start * sh) * 0.03125f, Z_ttf, (float) sw, (float) sh, bkcolor); DrawTextBox_ttf((float) (Win_X_ttf + posx), (float) (Win_Y_ttf + posy) + ((float) ttf_font_datas[l].y_start * sh) * 0.03125f, Z_ttf, (float) sw, (float) sh, color, 0.99f, 0.99f); } posx+= cx; } Y_ttf = (float) posy + sh; if(posx < lenx) posx = lenx; return posx; }
Alexandersss/IRISMAN-UNOFFICIAL
source/ttf_render.c
C
gpl-3.0
14,796
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using MissionPlanner; using GMap.NET; using GMap.NET.WindowsForms; using GMap.NET.WindowsForms.Markers; using MissionPlanner.Utilities; using ProjNet.CoordinateSystems; using ProjNet.CoordinateSystems.Transformations; namespace MissionPlanner { public class Grid { public static MissionPlanner.Plugin.PluginHost Host2; const float rad2deg = (float)(180 / Math.PI); const float deg2rad = (float)(1.0 / rad2deg); public struct linelatlng { // start of line public utmpos p1; // end of line public utmpos p2; // used as a base for grid along line (initial setout) public utmpos basepnt; } public enum StartPosition { Home = 0, BottomLeft = 1, TopLeft = 2, BottomRight = 3, TopRight = 4 } static void addtomap(linelatlng pos) { return; //List<PointLatLng> list = new List<PointLatLng>(); //list.Add(pos.p1.ToLLA()); //list.Add(pos.p2.ToLLA()); // polygons.Routes.Add(new GMapRoute(list, "test") { Stroke = new System.Drawing.Pen(System.Drawing.Color.Yellow,4) }); //.Markers.Add(new GMapMarkerGoogleRed(pnt)); //map.ZoomAndCenterRoutes("polygons"); // map.Invalidate(); } /// <summary> /// this is a debug function /// </summary> /// <param name="pos"></param> /// <param name="tag"></param> static void addtomap(utmpos pos, string tag) { //tag = (no++).ToString(); //polygons.Markers.Add(new GMapMarkerGoogleRed(pos.ToLLA()));// { ToolTipText = tag, ToolTipMode = MarkerTooltipMode.Always } ); //map.ZoomAndCenterMarkers("polygons"); //map.Invalidate(); } public static List<PointLatLngAlt> CreateGrid(List<PointLatLngAlt> polygon, double altitude, double distance, double spacing, double angle, double overshoot1,double overshoot2, StartPosition startpos, bool shutter, float minLaneSeparation, float leadin = 0) { if (spacing < 10 && spacing != 0) spacing = 10; if (distance < 0.1) distance = 0.1; if (polygon.Count == 0) return new List<PointLatLngAlt>(); // Make a non round number in case of corner cases if (minLaneSeparation != 0) minLaneSeparation += 0.5F; // Lane Separation in meters double minLaneSeparationINMeters = minLaneSeparation * distance; List<PointLatLngAlt> ans = new List<PointLatLngAlt>(); // utm zone distance calcs will be done in int utmzone = polygon[0].GetUTMZone(); // utm position list List<utmpos> utmpositions = utmpos.ToList(PointLatLngAlt.ToUTM(utmzone, polygon), utmzone); // close the loop if its not already if (utmpositions[0] != utmpositions[utmpositions.Count - 1]) utmpositions.Add(utmpositions[0]); // make a full loop // get mins/maxs of coverage area Rect area = getPolyMinMax(utmpositions); // get initial grid // used to determine the size of the outer grid area double diagdist = area.DiagDistance(); // somewhere to store out generated lines List<linelatlng> grid = new List<linelatlng>(); // number of lines we need int lines = 0; // get start point middle double x = area.MidWidth; double y = area.MidHeight; addtomap(new utmpos(x, y, utmzone),"Base"); // get left extent double xb1 = x; double yb1 = y; // to the left newpos(ref xb1, ref yb1, angle - 90, diagdist / 2 + distance); // backwards newpos(ref xb1, ref yb1, angle + 180, diagdist / 2 + distance); utmpos left = new utmpos(xb1, yb1, utmzone); addtomap(left, "left"); // get right extent double xb2 = x; double yb2 = y; // to the right newpos(ref xb2, ref yb2, angle + 90, diagdist / 2 + distance); // backwards newpos(ref xb2, ref yb2, angle + 180, diagdist / 2 + distance); utmpos right = new utmpos(xb2, yb2, utmzone); addtomap(right,"right"); // set start point to left hand side x = xb1; y = yb1; // draw the outergrid, this is a grid that cover the entire area of the rectangle plus more. while (lines < ((diagdist + distance * 2) / distance)) { // copy the start point to generate the end point double nx = x; double ny = y; newpos(ref nx, ref ny, angle, diagdist + distance*2); linelatlng line = new linelatlng(); line.p1 = new utmpos(x, y, utmzone); line.p2 = new utmpos(nx, ny, utmzone); line.basepnt = new utmpos(x, y, utmzone); grid.Add(line); // addtomap(line); newpos(ref x, ref y, angle + 90, distance); lines++; } // find intersections with our polygon // store lines that dont have any intersections List<linelatlng> remove = new List<linelatlng>(); int gridno = grid.Count; // cycle through our grid for (int a = 0; a < gridno; a++) { double closestdistance = double.MaxValue; double farestdistance = double.MinValue; utmpos closestpoint = utmpos.Zero; utmpos farestpoint = utmpos.Zero; // somewhere to store our intersections List<utmpos> matchs = new List<utmpos>(); int b = -1; int crosses = 0; utmpos newutmpos = utmpos.Zero; foreach (utmpos pnt in utmpositions) { b++; if (b == 0) { continue; } newutmpos = FindLineIntersection(utmpositions[b - 1], utmpositions[b], grid[a].p1, grid[a].p2); if (!newutmpos.IsZero) { crosses++; matchs.Add(newutmpos); if (closestdistance > grid[a].p1.GetDistance(newutmpos)) { closestpoint.y = newutmpos.y; closestpoint.x = newutmpos.x; closestpoint.zone = newutmpos.zone; closestdistance = grid[a].p1.GetDistance(newutmpos); } if (farestdistance < grid[a].p1.GetDistance(newutmpos)) { farestpoint.y = newutmpos.y; farestpoint.x = newutmpos.x; farestpoint.zone = newutmpos.zone; farestdistance = grid[a].p1.GetDistance(newutmpos); } } } if (crosses == 0) // outside our polygon { if (!PointInPolygon(grid[a].p1, utmpositions) && !PointInPolygon(grid[a].p2, utmpositions)) remove.Add(grid[a]); } else if (crosses == 1) // bad - shouldnt happen { } else if (crosses == 2) // simple start and finish { linelatlng line = grid[a]; line.p1 = closestpoint; line.p2 = farestpoint; grid[a] = line; } else // multiple intersections { linelatlng line = grid[a]; remove.Add(line); while (matchs.Count > 1) { linelatlng newline = new linelatlng(); closestpoint = findClosestPoint(closestpoint, matchs); newline.p1 = closestpoint; matchs.Remove(closestpoint); closestpoint = findClosestPoint(closestpoint, matchs); newline.p2 = closestpoint; matchs.Remove(closestpoint); newline.basepnt = line.basepnt; grid.Add(newline); } } } // cleanup and keep only lines that pass though our polygon foreach (linelatlng line in remove) { grid.Remove(line); } // debug foreach (linelatlng line in grid) { addtomap(line); } if (grid.Count == 0) return ans; utmpos startposutm; switch (startpos) { default: case StartPosition.Home: startposutm = new utmpos(Host2.cs.HomeLocation); break; case StartPosition.BottomLeft: startposutm = new utmpos(area.Left, area.Bottom, utmzone); break; case StartPosition.BottomRight: startposutm = new utmpos(area.Right, area.Bottom, utmzone); break; case StartPosition.TopLeft: startposutm = new utmpos(area.Left, area.Top, utmzone); break; case StartPosition.TopRight: startposutm = new utmpos(area.Right, area.Top, utmzone); break; } // find closest line point to startpos linelatlng closest = findClosestLine(startposutm, grid, 0 /*Lane separation does not apply to starting point*/, angle); utmpos lastpnt; // get the closes point from the line we picked if (closest.p1.GetDistance(startposutm) < closest.p2.GetDistance(startposutm)) { lastpnt = closest.p1; } else { lastpnt = closest.p2; } while (grid.Count > 0) { // for each line, check which end of the line is the next closest if (closest.p1.GetDistance(lastpnt) < closest.p2.GetDistance(lastpnt)) { utmpos newstart = newpos(closest.p1, angle, -leadin); addtomap(newstart, "S"); ans.Add(newstart); if (spacing > 0) { for (int d = (int)(spacing - ((closest.basepnt.GetDistance(closest.p1)) % spacing)); d < (closest.p1.GetDistance(closest.p2)); d += (int)spacing) { double ax = closest.p1.x; double ay = closest.p1.y; newpos(ref ax, ref ay, angle, d); addtomap(new utmpos(ax,ay,utmzone),"M"); ans.Add((new utmpos(ax, ay, utmzone) { Tag = "M" })); } } utmpos newend = newpos(closest.p2, angle, overshoot1); addtomap(newend, "E"); ans.Add(newend); lastpnt = closest.p2; grid.Remove(closest); if (grid.Count == 0) break; closest = findClosestLine(newend, grid, minLaneSeparationINMeters, angle); } else { utmpos newstart = newpos(closest.p2, angle, leadin); addtomap(newstart, "E"); ans.Add(newstart); if (spacing > 0) { for (int d = (int)((closest.basepnt.GetDistance(closest.p2)) % spacing); d < (closest.p1.GetDistance(closest.p2)); d += (int)spacing) { double ax = closest.p2.x; double ay = closest.p2.y; newpos(ref ax, ref ay, angle, -d); addtomap(new utmpos(ax, ay, utmzone), "M"); ans.Add((new utmpos(ax, ay, utmzone) { Tag = "M" })); } } utmpos newend = newpos(closest.p1, angle, -overshoot2); // if (overshoot2 > 0) // ans.Add(new utmpos(closest.p1) { Tag = "M" }); addtomap(newend, "E"); ans.Add(newend); lastpnt = closest.p1; grid.Remove(closest); if (grid.Count == 0) break; closest = findClosestLine(newend, grid, minLaneSeparationINMeters, angle); } } // set the altitude on all points ans.ForEach(plla => { plla.Alt = altitude; }); return ans; } static Rect getPolyMinMax(List<utmpos> utmpos) { if (utmpos.Count == 0) return new Rect(); double minx, miny, maxx, maxy; minx = maxx = utmpos[0].x; miny = maxy = utmpos[0].y; foreach (utmpos pnt in utmpos) { minx = Math.Min(minx, pnt.x); maxx = Math.Max(maxx, pnt.x); miny = Math.Min(miny, pnt.y); maxy = Math.Max(maxy, pnt.y); } return new Rect(minx, maxy, maxx - minx,miny - maxy); } // polar to rectangular static void newpos(ref double x, ref double y, double bearing, double distance) { double degN = 90 - bearing; if (degN < 0) degN += 360; x = x + distance * Math.Cos(degN * deg2rad); y = y + distance * Math.Sin(degN * deg2rad); } // polar to rectangular static utmpos newpos(utmpos input, double bearing, double distance) { double degN = 90 - bearing; if (degN < 0) degN += 360; double x = input.x + distance * Math.Cos(degN * deg2rad); double y = input.y + distance * Math.Sin(degN * deg2rad); return new utmpos(x, y, input.zone); } /// <summary> /// from http://stackoverflow.com/questions/1119451/how-to-tell-if-a-line-intersects-a-polygon-in-c /// </summary> /// <param name="start1"></param> /// <param name="end1"></param> /// <param name="start2"></param> /// <param name="end2"></param> /// <returns></returns> public static utmpos FindLineIntersection(utmpos start1, utmpos end1, utmpos start2, utmpos end2) { double denom = ((end1.x - start1.x) * (end2.y - start2.y)) - ((end1.y - start1.y) * (end2.x - start2.x)); // AB & CD are parallel if (denom == 0) return utmpos.Zero; double numer = ((start1.y - start2.y) * (end2.x - start2.x)) - ((start1.x - start2.x) * (end2.y - start2.y)); double r = numer / denom; double numer2 = ((start1.y - start2.y) * (end1.x - start1.x)) - ((start1.x - start2.x) * (end1.y - start1.y)); double s = numer2 / denom; if ((r < 0 || r > 1) || (s < 0 || s > 1)) return utmpos.Zero; // Find intersection point utmpos result = new utmpos(); result.x = start1.x + (r * (end1.x - start1.x)); result.y = start1.y + (r * (end1.y - start1.y)); result.zone = start1.zone; return result; } static utmpos findClosestPoint(utmpos start, List<utmpos> list) { utmpos answer = utmpos.Zero; double currentbest = double.MaxValue; foreach (utmpos pnt in list) { double dist1 = start.GetDistance(pnt); if (dist1 < currentbest) { answer = pnt; currentbest = dist1; } } return answer; } // Add an angle while normalizing output in the range 0...360 static double AddAngle(double angle, double degrees) { angle += degrees; angle = angle % 360; while (angle < 0) { angle += 360; } return angle; } static linelatlng findClosestLine(utmpos start, List<linelatlng> list, double minDistance, double angle) { // By now, just add 5.000 km to our lines so they are long enough to allow intersection double METERS_TO_EXTEND = 5000000; double perperndicularOrientation = AddAngle(angle, 90); // Calculation of a perpendicular line to the grid lines containing the "start" point /* * --------------------------------------|------------------------------------------ * --------------------------------------|------------------------------------------ * -------------------------------------start--------------------------------------- * --------------------------------------|------------------------------------------ * --------------------------------------|------------------------------------------ * --------------------------------------|------------------------------------------ * --------------------------------------|------------------------------------------ * --------------------------------------|------------------------------------------ */ utmpos start_perpendicular_line = newpos(start, perperndicularOrientation, -METERS_TO_EXTEND); utmpos stop_perpendicular_line = newpos(start, perperndicularOrientation, METERS_TO_EXTEND); // Store one intersection point per grid line Dictionary<utmpos, linelatlng> intersectedPoints = new Dictionary<utmpos, linelatlng>(); // lets order distances from every intersected point per line with the "start" point Dictionary<double, utmpos> ordered_min_to_max = new Dictionary<double, utmpos>(); foreach (linelatlng line in list) { // Extend line at both ends so it intersecs for sure with our perpendicular line utmpos extended_line_start = newpos(line.p1, angle, -METERS_TO_EXTEND); utmpos extended_line_stop = newpos(line.p2, angle, METERS_TO_EXTEND); // Calculate intersection point utmpos p = FindLineIntersection(extended_line_start, extended_line_stop, start_perpendicular_line, stop_perpendicular_line); // Store it intersectedPoints[p] = line; // Calculate distances between interesected point and "start" (i.e. line and start) double distance_p = start.GetDistance(p); if (!ordered_min_to_max.ContainsKey(distance_p)) ordered_min_to_max.Add(distance_p, p); } // Acquire keys and sort them. List<double> ordered_keys = ordered_min_to_max.Keys.ToList(); ordered_keys.Sort(); // Lets select a line that is the closest to "start" point but "mindistance" away at least. // If we have only one line, return that line whatever the minDistance says double key = double.MaxValue; int i = 0; while (key == double.MaxValue && i < ordered_keys.Count) { if (ordered_keys[i] >= minDistance) key = ordered_keys[i]; i++; } // If no line is selected (because all of them are closer than minDistance, then get the farest one if (key == double.MaxValue) key = ordered_keys[ordered_keys.Count-1]; // return line return intersectedPoints[ordered_min_to_max[key]]; } static bool PointInPolygon(utmpos p, List<utmpos> poly) { utmpos p1, p2; bool inside = false; if (poly.Count < 3) { return inside; } utmpos oldPoint = new utmpos(poly[poly.Count - 1]); for (int i = 0; i < poly.Count; i++) { utmpos newPoint = new utmpos(poly[i]); if (newPoint.y > oldPoint.y) { p1 = oldPoint; p2 = newPoint; } else { p1 = newPoint; p2 = oldPoint; } if ((newPoint.y < p.y) == (p.y <= oldPoint.y) && ((double)p.x - (double)p1.x) * (double)(p2.y - p1.y) < ((double)p2.x - (double)p1.x) * (double)(p.y - p1.y)) { inside = !inside; } oldPoint = newPoint; } return inside; } } }
marcoarruda/MissionPlanner
ExtLibs/Grid/Grid.cs
C#
gpl-3.0
22,856
<?php /***************************************************************************\ * SPIP, Systeme de publication pour l'internet * * * * Copyright (c) 2001-2014 * * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribue sous licence GNU/GPL. * * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) return; include_spip('inc/dump'); function dump_afficher_tables_restaurees_erreurs($status_file) { $status = dump_lire_status($status_file); $tables = $status['tables_copiees']; $corps = ""; $erreurs = array(); if (!$tables) return "<p>"._T("dump:erreur_aucune_donnee_restauree")."</p>"; // lister les tables copiees aller verifier dans la base // qu'on a le bon nombre de donnees foreach($tables as $t=>$n) { if (!sql_showtable($t,true) OR $n===0) $erreurs[$t] = _T('dump:erreur_table_absente',array('table'=>"<strong>$t</strong>")); else { $n = abs(intval($n)); $n_dump = intval(sql_countsel($t)); if ($n_dump<$n) $erreurs[$t] = _T('dump:erreur_table_donnees_manquantes',array('table'=>"<strong>$t</strong>"));; } } if (count($erreurs)) $corps = "<ul class='spip'><li>".implode("</li><li class='spip'>",$erreurs)."</li></ul>"; return $corps; } ?>
imagesdesmaths/spip
plugins-dist/dump/prive/squelettes/contenu/restaurer_fonctions.php
PHP
gpl-3.0
1,631
---------------------------------- -- Area: Kuftal Tunnel -- NM: Amemet -- ToDo: Amemet should walk in a big circle ----------------------------------- ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) -- Set Amemet's Window Open Time local wait = math.random(7200,43200); -- 2-12 hours SetServerVariable("[POP]Amemet", os.time(t) + wait); DeterMob(mob:getID(), true); -- Set PH back to normal, then set to respawn spawn local PH = GetServerVariable("[PH]Amemet"); SetServerVariable("[PH]Amemet", 0); DeterMob(PH, false); GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH)); end;
nesstea/darkstar
scripts/zones/Kuftal_Tunnel/mobs/Amemet.lua
Lua
gpl-3.0
696
/** * Module dependencies */ var XMLHttpRequest = require('xmlhttprequest-ssl'); var XHR = require('./polling-xhr'); var JSONP = require('./polling-jsonp'); var websocket = require('./websocket'); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } }
tohshige/test
used12_1801_bak/node_modules/engine.io-client/lib/transports/index.js
JavaScript
gpl-3.0
1,140
describe('Application controller', function(){ beforeEach(module('mpk')); var scope, applicationController, kanbanRepositoryMock, themesProviderMock, window; var renamer, saver; beforeEach(inject(function($rootScope, $controller, $window){ renamer = jasmine.createSpy('Kanban Rename Function'); saver = jasmine.createSpy('Kanban Saver'); kanbanRepositoryMock = { load: function(){ return validSampleKanban.kanbans;}, getLastUsed: function(){ return validSampleKanban.kanbans['Stuff to do at home']}, all: function() { return validSampleKanban.kanbans;}, getTheme: function() { return 'default-dark'; }, renameLastUsedTo: renamer, save: saver, get: function(name) { return validSampleKanban.kanbans[name]; }, setLastUsed: function(kanban) { return kanban; }, }; window = $window; themesProviderMock = {setCurrentTheme: function(){}}; scope = $rootScope.$new(); applicationController = $controller('ApplicationController', {$scope: scope, kanbanRepository: kanbanRepositoryMock, themesProvider: themesProviderMock, $window: window, $routeParams: {}}); })); it("should change name of the Kanban to new name", function(){ scope.newName = 'foobarboo'; scope.allKanbans = []; scope.rename(); expect(renamer).toHaveBeenCalledWith(scope.newName); expect(saver).toHaveBeenCalled(); expect(scope.allKanbans).not.toEqual([]); }); it("should set the Text field variable of the name", function(){ expect(scope.newName).toBe('Stuff to do at home'); }); it("should switch to editing when clicking Kanban Name editing", function(){ expect(scope.editingName).toBeFalsy(); scope.editingKanbanName(); expect(scope.editingName).toBeTruthy(); }); it("should add switch to option to Switch Menu", function(){ expect(scope.switchToList.length).toBe(scope.allKanbans.length+1); }); var validSampleKanban = {"kanbans": {"Stuff to do at home":{"name":"Stuff to do at home","numberOfColumns":3, "columns":[ {"name":"Not started","cards":[{"name":"This little piggy went to lunch","color":"CCD0FC"},{"name":"Foo bar","color":"FCE4D4"}]}, {"name":"In progress","cards":[{"name":"another on a bit longer text this time","color":"FAFFA1"},{"name":"And another one","color":"94D6FF"}]}, {"name":"Done","cards":[{"name":"bar foo","color":"FCE4D4"},{"name":"Another on","color":"FCC19D"},{"name":"New one","color":"FC9AFB"}]} ] }, "foobarboo":{"name":"foobarboo","numberOfColumns":3, "columns":[ {"name":"Col 1","cards":[]}, {"name":"Col 2","cards":[]}, {"name":"Col 3","cards":[]}, ] }}, "lastUsed":"Stuff to do at home", "theme":"default-dark", "lastUpdated":"1391554268110"}; });
Khamull/my-personal-kanban
test/spec/controllers/ApplicationControllerSpec.js
JavaScript
gpl-3.0
2,691
# # CBRAIN Project # # Copyright (C) 2008-2012 # The Royal Institution for the Advancement of Learning # McGill University # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class RemoveBourreauToolJoin < ActiveRecord::Migration def self.up remove_index :bourreaux_tools, :bourreau_id remove_index :bourreaux_tools, :tool_id drop_table :bourreaux_tools end def self.down create_table :bourreaux_tools, :id => false do |t| t.integer :tool_id t.integer :bourreau_id end add_index :bourreaux_tools, :bourreau_id add_index :bourreaux_tools, :tool_id end end
crocodoyle/cbrain
BrainPortal/db/migrate/20110506152411_remove_bourreau_tool_join.rb
Ruby
gpl-3.0
1,215
<!-- Autor=Javier Cancela Fecha= 17/02/2016 Licencia=GPL v3 Versión=1.0 Descripción= Copyright (C) 2016 Javier Cancela This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --> <ul> <li><a href="index.php">Página inicial</a></li> </ul>
cancelajavi/2-DAW
Tema5/plantillaPaco/vista/html/enlace_inicio.html
HTML
gpl-3.0
866
--TEST-- Test xml_get_error_code() function : error conditions --SKIPIF-- <?php if (!extension_loaded("xml")) { print "skip - XML extension not loaded"; } ?> --FILE-- <?php /* Prototype : proto int xml_get_error_code(resource parser) * Description: Get XML parser error code * Source code: ext/xml/xml.c * Alias to functions: */ echo "*** Testing xml_get_error_code() : error conditions ***\n"; // Zero arguments echo "\n-- Testing xml_get_error_code() function with Zero arguments --\n"; var_dump( xml_get_error_code() ); //Test xml_get_error_code with one more than the expected number of arguments echo "\n-- Testing xml_get_error_code() function with more than expected no. of arguments --\n"; $extra_arg = 10; var_dump( xml_get_error_code(null, $extra_arg) ); echo "Done"; ?> --EXPECTF-- *** Testing xml_get_error_code() : error conditions *** -- Testing xml_get_error_code() function with Zero arguments -- Warning: xml_get_error_code() expects exactly 1 parameter, 0 given in %s on line %d NULL -- Testing xml_get_error_code() function with more than expected no. of arguments -- Warning: xml_get_error_code() expects exactly 1 parameter, 2 given in %s on line %d NULL Done
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/php-5.5.11/ext/xml/tests/xml_get_error_code_error.phpt
PHP
gpl-3.0
1,204
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\console\controllers; use Yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\console\Controller; use yii\console\Exception; use yii\console\ExitCode; use yii\helpers\Console; use yii\helpers\FileHelper; use yii\test\FixtureTrait; /** * Manages fixture data loading and unloading. * * ``` * #load fixtures from UsersFixture class with default namespace "tests\unit\fixtures" * yii fixture/load User * * #also a short version of this command (generate action is default) * yii fixture User * * #load all fixtures * yii fixture "*" * * #load all fixtures except User * yii fixture "*, -User" * * #load fixtures with different namespace. * yii fixture/load User --namespace=alias\my\custom\namespace\goes\here * ``` * * The `unload` sub-command can be used similarly to unload fixtures. * * @author Mark Jebri <mark.github@yandex.ru> * @since 2.0 */ class FixtureController extends Controller { use FixtureTrait; /** * @var string controller default action ID. */ public $defaultAction = 'load'; /** * @var string default namespace to search fixtures in */ public $namespace = 'tests\unit\fixtures'; /** * @var array global fixtures that should be applied when loading and unloading. By default it is set to `InitDbFixture` * that disables and enables integrity check, so your data can be safely loaded. */ public $globalFixtures = [ 'yii\test\InitDbFixture', ]; /** * {@inheritdoc} */ public function options($actionID) { return array_merge(parent::options($actionID), [ 'namespace', 'globalFixtures', ]); } /** * {@inheritdoc} * @since 2.0.8 */ public function optionAliases() { return array_merge(parent::optionAliases(), [ 'g' => 'globalFixtures', 'n' => 'namespace', ]); } /** * Loads the specified fixture data. * * For example, * * ``` * # load the fixture data specified by User and UserProfile. * # any existing fixture data will be removed first * yii fixture/load "User, UserProfile" * * # load all available fixtures found under 'tests\unit\fixtures' * yii fixture/load "*" * * # load all fixtures except User and UserProfile * yii fixture/load "*, -User, -UserProfile" * ``` * * @param array $fixturesInput * @return int return code * @throws Exception if the specified fixture does not exist. */ public function actionLoad(array $fixturesInput = []) { if ($fixturesInput === []) { $this->printHelpMessage(); return ExitCode::OK; } $filtered = $this->filterFixtures($fixturesInput); $except = $filtered['except']; if (!$this->needToApplyAll($fixturesInput[0])) { $fixtures = $filtered['apply']; $foundFixtures = $this->findFixtures($fixtures); $notFoundFixtures = array_diff($fixtures, $foundFixtures); if ($notFoundFixtures) { $this->notifyNotFound($notFoundFixtures); } } else { $foundFixtures = $this->findFixtures(); } $fixturesToLoad = array_diff($foundFixtures, $except); if (!$foundFixtures) { throw new Exception( 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } if (!$fixturesToLoad) { $this->notifyNothingToLoad($foundFixtures, $except); return ExitCode::OK; } if (!$this->confirmLoad($fixturesToLoad, $except)) { return ExitCode::OK; } $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToLoad)); if (!$fixtures) { throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . ''); } $fixturesObjects = $this->createFixtures($fixtures); $this->unloadFixtures($fixturesObjects); $this->loadFixtures($fixturesObjects); $this->notifyLoaded($fixtures); return ExitCode::OK; } /** * Unloads the specified fixtures. * * For example, * * ``` * # unload the fixture data specified by User and UserProfile. * yii fixture/unload "User, UserProfile" * * # unload all fixtures found under 'tests\unit\fixtures' * yii fixture/unload "*" * * # unload all fixtures except User and UserProfile * yii fixture/unload "*, -User, -UserProfile" * ``` * * @param array $fixturesInput * @return int return code * @throws Exception if the specified fixture does not exist. */ public function actionUnload(array $fixturesInput = []) { if ($fixturesInput === []) { $this->printHelpMessage(); return ExitCode::OK; } $filtered = $this->filterFixtures($fixturesInput); $except = $filtered['except']; if (!$this->needToApplyAll($fixturesInput[0])) { $fixtures = $filtered['apply']; $foundFixtures = $this->findFixtures($fixtures); $notFoundFixtures = array_diff($fixtures, $foundFixtures); if ($notFoundFixtures) { $this->notifyNotFound($notFoundFixtures); } } else { $foundFixtures = $this->findFixtures(); } $fixturesToUnload = array_diff($foundFixtures, $except); if (!$foundFixtures) { throw new Exception( 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } if (!$fixturesToUnload) { $this->notifyNothingToUnload($foundFixtures, $except); return ExitCode::OK; } if (!$this->confirmUnload($fixturesToUnload, $except)) { return ExitCode::OK; } $fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload)); if (!$fixtures) { throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".'); } $this->unloadFixtures($this->createFixtures($fixtures)); $this->notifyUnloaded($fixtures); } /** * Show help message. * @param array $fixturesInput */ private function printHelpMessage() { $this->stdout($this->getHelpSummary() . "\n"); $helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]); $this->stdout("Use $helpCommand to get usage info.\n"); } /** * Notifies user that fixtures were successfully loaded. * @param array $fixtures */ private function notifyLoaded($fixtures) { $this->stdout("Fixtures were successfully loaded from namespace:\n", Console::FG_YELLOW); $this->stdout("\t\"" . Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN); $this->outputList($fixtures); } /** * Notifies user that there are no fixtures to load according input conditions. * @param array $foundFixtures array of found fixtures * @param array $except array of names of fixtures that should not be loaded */ public function notifyNothingToLoad($foundFixtures, $except) { $this->stdout("Fixtures to load could not be found according given conditions:\n\n", Console::FG_RED); $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW); $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN); if (count($foundFixtures)) { $this->stdout("\nFixtures founded under the namespace:\n\n", Console::FG_YELLOW); $this->outputList($foundFixtures); } if (count($except)) { $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW); $this->outputList($except); } } /** * Notifies user that there are no fixtures to unload according input conditions. * @param array $foundFixtures array of found fixtures * @param array $except array of names of fixtures that should not be loaded */ public function notifyNothingToUnload($foundFixtures, $except) { $this->stdout("Fixtures to unload could not be found according to given conditions:\n\n", Console::FG_RED); $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW); $this->stdout("\t" . $this->namespace . "\n", Console::FG_GREEN); if (count($foundFixtures)) { $this->stdout("\nFixtures found under the namespace:\n\n", Console::FG_YELLOW); $this->outputList($foundFixtures); } if (count($except)) { $this->stdout("\nFixtures that will NOT be unloaded: \n\n", Console::FG_YELLOW); $this->outputList($except); } } /** * Notifies user that fixtures were successfully unloaded. * @param array $fixtures */ private function notifyUnloaded($fixtures) { $this->stdout("\nFixtures were successfully unloaded from namespace: ", Console::FG_YELLOW); $this->stdout(Yii::getAlias($this->namespace) . "\"\n\n", Console::FG_GREEN); $this->outputList($fixtures); } /** * Notifies user that fixtures were not found under fixtures path. * @param array $fixtures */ private function notifyNotFound($fixtures) { $this->stdout("Some fixtures were not found under path:\n", Console::BG_RED); $this->stdout("\t" . $this->getFixturePath() . "\n\n", Console::FG_GREEN); $this->stdout("Check that they have correct namespace \"{$this->namespace}\" \n", Console::BG_RED); $this->outputList($fixtures); $this->stdout("\n"); } /** * Prompts user with confirmation if fixtures should be loaded. * @param array $fixtures * @param array $except * @return bool */ private function confirmLoad($fixtures, $except) { $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW); $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN); if (count($this->globalFixtures)) { $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW); $this->outputList($this->globalFixtures); } if (count($fixtures)) { $this->stdout("\nFixtures below will be loaded:\n\n", Console::FG_YELLOW); $this->outputList($fixtures); } if (count($except)) { $this->stdout("\nFixtures that will NOT be loaded: \n\n", Console::FG_YELLOW); $this->outputList($except); } $this->stdout("\nBe aware that:\n", Console::BOLD); $this->stdout("Applying leads to purging of certain data in the database!\n", Console::FG_RED); return $this->confirm("\nLoad above fixtures?"); } /** * Prompts user with confirmation for fixtures that should be unloaded. * @param array $fixtures * @param array $except * @return bool */ private function confirmUnload($fixtures, $except) { $this->stdout("Fixtures namespace is: \n", Console::FG_YELLOW); $this->stdout("\t" . $this->namespace . "\n\n", Console::FG_GREEN); if (count($this->globalFixtures)) { $this->stdout("Global fixtures will be used:\n\n", Console::FG_YELLOW); $this->outputList($this->globalFixtures); } if (count($fixtures)) { $this->stdout("\nFixtures below will be unloaded:\n\n", Console::FG_YELLOW); $this->outputList($fixtures); } if (count($except)) { $this->stdout("\nFixtures that will NOT be unloaded:\n\n", Console::FG_YELLOW); $this->outputList($except); } return $this->confirm("\nUnload fixtures?"); } /** * Outputs data to the console as a list. * @param array $data */ private function outputList($data) { foreach ($data as $index => $item) { $this->stdout("\t" . ($index + 1) . ". {$item}\n", Console::FG_GREEN); } } /** * Checks if needed to apply all fixtures. * @param string $fixture * @return bool */ public function needToApplyAll($fixture) { return $fixture === '*'; } /** * Finds fixtures to be loaded, for example "User", if no fixtures were specified then all of them * will be searching by suffix "Fixture.php". * @param array $fixtures fixtures to be loaded * @return array Array of found fixtures. These may differ from input parameter as not all fixtures may exists. */ private function findFixtures(array $fixtures = []) { $fixturesPath = $this->getFixturePath(); $filesToSearch = ['*Fixture.php']; $findAll = ($fixtures === []); if (!$findAll) { $filesToSearch = []; foreach ($fixtures as $fileName) { $filesToSearch[] = $fileName . 'Fixture.php'; } } $files = FileHelper::findFiles($fixturesPath, ['only' => $filesToSearch]); $foundFixtures = []; foreach ($files as $fixture) { $foundFixtures[] = $this->getFixtureRelativeName($fixture); } return $foundFixtures; } /** * Calculates fixture's name * Basically, strips [[getFixturePath()]] and `Fixture.php' suffix from fixture's full path. * @see getFixturePath() * @param string $fullFixturePath Full fixture path * @return string Relative fixture name */ private function getFixtureRelativeName($fullFixturePath) { $fixturesPath = FileHelper::normalizePath($this->getFixturePath()); $fullFixturePath = FileHelper::normalizePath($fullFixturePath); $relativeName = substr($fullFixturePath, strlen($fixturesPath) + 1); $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . DIRECTORY_SEPARATOR; return $relativeDir . basename($fullFixturePath, 'Fixture.php'); } /** * Returns valid fixtures config that can be used to load them. * @param array $fixtures fixtures to configure * @return array */ private function getFixturesConfig($fixtures) { $config = []; foreach ($fixtures as $fixture) { $isNamespaced = (strpos($fixture, '\\') !== false); // replace linux' path slashes to namespace backslashes, in case if $fixture is non-namespaced relative path $fixture = str_replace('/', '\\', $fixture); $fullClassName = $isNamespaced ? $fixture : $this->namespace . '\\' . $fixture; if (class_exists($fullClassName)) { $config[] = $fullClassName; } elseif (class_exists($fullClassName . 'Fixture')) { $config[] = $fullClassName . 'Fixture'; } } return $config; } /** * Filters fixtures by splitting them in two categories: one that should be applied and not. * * If fixture is prefixed with "-", for example "-User", that means that fixture should not be loaded, * if it is not prefixed it is considered as one to be loaded. Returns array: * * ```php * [ * 'apply' => [ * 'User', * ... * ], * 'except' => [ * 'Custom', * ... * ], * ] * ``` * @param array $fixtures * @return array fixtures array with 'apply' and 'except' elements. */ private function filterFixtures($fixtures) { $filtered = [ 'apply' => [], 'except' => [], ]; foreach ($fixtures as $fixture) { if (mb_strpos($fixture, '-') !== false) { $filtered['except'][] = str_replace('-', '', $fixture); } else { $filtered['apply'][] = $fixture; } } return $filtered; } /** * Returns fixture path that determined on fixtures namespace. * @throws InvalidConfigException if fixture namespace is invalid * @return string fixture path */ private function getFixturePath() { try { return Yii::getAlias('@' . str_replace('\\', '/', $this->namespace)); } catch (InvalidParamException $e) { throw new InvalidConfigException('Invalid fixture namespace: "' . $this->namespace . '". Please, check your FixtureController::namespace parameter'); } } }
Pgans/yii2a-devices
vendor/yiisoft/yiisoft/yii2/console/controllers/FixtureController.php
PHP
gpl-3.0
17,131
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | \\ / A nd | For copyright notice see file Copyright \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. Class Foam::fv::d2dt2Scheme Description Abstract base class for d2dt2 schemes. SourceFiles d2dt2Scheme.C \*---------------------------------------------------------------------------*/ #ifndef d2dt2Scheme_H #define d2dt2Scheme_H #include "tmp.H" #include "dimensionedType.H" #include "volFieldsFwd.H" #include "surfaceFieldsFwd.H" #include "typeInfo.H" #include "runTimeSelectionTables.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { template<class Type> class fvMatrix; class fvMesh; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fv { /*---------------------------------------------------------------------------*\ Class d2dt2Scheme Declaration \*---------------------------------------------------------------------------*/ template<class Type> class d2dt2Scheme : public refCount { protected: // Protected data const fvMesh& mesh_; // Private Member Functions //- Disallow copy construct d2dt2Scheme(const d2dt2Scheme&); //- Disallow default bitwise assignment void operator=(const d2dt2Scheme&); public: //- Runtime type information virtual const word& type() const = 0; // Declare run-time constructor selection tables declareRunTimeSelectionTable ( tmp, d2dt2Scheme, Istream, (const fvMesh& mesh, Istream& schemeData), (mesh, schemeData) ); // Constructors //- Construct from mesh d2dt2Scheme(const fvMesh& mesh) : mesh_(mesh) {} //- Construct from mesh and Istream d2dt2Scheme(const fvMesh& mesh, Istream&) : mesh_(mesh) {} // Selectors //- Return a pointer to a new d2dt2Scheme created on freestore static tmp<d2dt2Scheme<Type> > New ( const fvMesh& mesh, Istream& schemeData ); // Destructor virtual ~d2dt2Scheme(); // Member Functions //- Return mesh reference const fvMesh& mesh() const { return mesh_; } virtual tmp<GeometricField<Type, fvPatchField, volMesh> > fvcD2dt2 ( const GeometricField<Type, fvPatchField, volMesh>& ) = 0; virtual tmp<GeometricField<Type, fvPatchField, volMesh> > fvcD2dt2 ( const volScalarField&, const GeometricField<Type, fvPatchField, volMesh>& ) = 0; virtual tmp<fvMatrix<Type> > fvmD2dt2 ( GeometricField<Type, fvPatchField, volMesh>& ) = 0; virtual tmp<fvMatrix<Type> > fvmD2dt2 ( const dimensionedScalar&, GeometricField<Type, fvPatchField, volMesh>& ) = 0; virtual tmp<fvMatrix<Type> > fvmD2dt2 ( const volScalarField&, GeometricField<Type, fvPatchField, volMesh>& ) = 0; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fv // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Add the patch constructor functions to the hash tables #define makeFvD2dt2TypeScheme(SS, Type) \ \ defineNamedTemplateTypeNameAndDebug(SS<Type>, 0); \ \ d2dt2Scheme<Type>::addIstreamConstructorToTable<SS<Type> > \ add##SS##Type##IstreamConstructorToTable_; #define makeFvD2dt2Scheme(SS) \ \ makeFvD2dt2TypeScheme(SS, scalar) \ makeFvD2dt2TypeScheme(SS, vector) \ makeFvD2dt2TypeScheme(SS, sphericalTensor) \ makeFvD2dt2TypeScheme(SS, symmTensor) \ makeFvD2dt2TypeScheme(SS, symmTensor4thOrder) \ makeFvD2dt2TypeScheme(SS, diagTensor) \ makeFvD2dt2TypeScheme(SS, tensor) // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "d2dt2Scheme.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/openfoam-extend-foam-extend-3.1
src/finiteVolume/finiteVolume/d2dt2Schemes/d2dt2Scheme/d2dt2Scheme.H
C++
gpl-3.0
5,948
<?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_Document_GoogleCloudDocumentaiV1beta1DocumentTextAnchorTextSegment extends Google_Model { public $endIndex; public $startIndex; public function setEndIndex($endIndex) { $this->endIndex = $endIndex; } public function getEndIndex() { return $this->endIndex; } public function setStartIndex($startIndex) { $this->startIndex = $startIndex; } public function getStartIndex() { return $this->startIndex; } }
ftisunpar/BlueTape
vendor/google/apiclient-services/src/Google/Service/Document/GoogleCloudDocumentaiV1beta1DocumentTextAnchorTextSegment.php
PHP
gpl-3.0
1,066
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_firewall_ssl_server short_description: Configure SSL servers in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify firewall feature and ssl_server category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true version_added: 2.9 state: description: - Indicates whether to create or remove the object. This attribute was present already in previous version in a deeper level. It has been moved out to this outer level. type: str required: false choices: - present - absent version_added: 2.9 firewall_ssl_server: description: - Configure SSL servers. default: null type: dict suboptions: state: description: - B(Deprecated) - Starting with Ansible 2.9 we recommend using the top-level 'state' parameter. - HORIZONTALLINE - Indicates whether to create or remove the object. type: str required: false choices: - present - absent add_header_x_forwarded_proto: description: - Enable/disable adding an X-Forwarded-Proto header to forwarded requests. type: str choices: - enable - disable ip: description: - IPv4 address of the SSL server. type: str mapped_port: description: - Mapped server service port (1 - 65535). type: int name: description: - Server name. required: true type: str port: description: - Server service port (1 - 65535). type: int ssl_algorithm: description: - Relative strength of encryption algorithms accepted in negotiation. type: str choices: - high - medium - low ssl_cert: description: - Name of certificate for SSL connections to this server. Source vpn.certificate.local.name. type: str ssl_client_renegotiation: description: - Allow or block client renegotiation by server. type: str choices: - allow - deny - secure ssl_dh_bits: description: - Bit-size of Diffie-Hellman (DH) prime used in DHE-RSA negotiation. type: str choices: - 768 - 1024 - 1536 - 2048 ssl_max_version: description: - Highest SSL/TLS version to negotiate. type: str choices: - tls-1.0 - tls-1.1 - tls-1.2 ssl_min_version: description: - Lowest SSL/TLS version to negotiate. type: str choices: - tls-1.0 - tls-1.1 - tls-1.2 ssl_mode: description: - SSL/TLS mode for encryption and decryption of traffic. type: str choices: - half - full ssl_send_empty_frags: description: - Enable/disable sending empty fragments to avoid attack on CBC IV. type: str choices: - enable - disable url_rewrite: description: - Enable/disable rewriting the URL. type: str choices: - enable - disable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure SSL servers. fortios_firewall_ssl_server: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" firewall_ssl_server: add_header_x_forwarded_proto: "enable" ip: "<your_own_value>" mapped_port: "5" name: "default_name_6" port: "7" ssl_algorithm: "high" ssl_cert: "<your_own_value> (source vpn.certificate.local.name)" ssl_client_renegotiation: "allow" ssl_dh_bits: "768" ssl_max_version: "tls-1.0" ssl_min_version: "tls-1.0" ssl_mode: "half" ssl_send_empty_frags: "enable" url_rewrite: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_firewall_ssl_server_data(json): option_list = ['add_header_x_forwarded_proto', 'ip', 'mapped_port', 'name', 'port', 'ssl_algorithm', 'ssl_cert', 'ssl_client_renegotiation', 'ssl_dh_bits', 'ssl_max_version', 'ssl_min_version', 'ssl_mode', 'ssl_send_empty_frags', 'url_rewrite'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for i, elem in enumerate(data): data[i] = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def firewall_ssl_server(data, fos): vdom = data['vdom'] if 'state' in data and data['state']: state = data['state'] elif 'state' in data['firewall_ssl_server'] and data['firewall_ssl_server']: state = data['firewall_ssl_server']['state'] else: state = True firewall_ssl_server_data = data['firewall_ssl_server'] filtered_data = underscore_to_hyphen(filter_firewall_ssl_server_data(firewall_ssl_server_data)) if state == "present": return fos.set('firewall', 'ssl-server', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('firewall', 'ssl-server', mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_firewall(data, fos): if data['firewall_ssl_server']: resp = firewall_ssl_server(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "firewall_ssl_server": { "required": False, "type": "dict", "default": None, "options": { "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "add_header_x_forwarded_proto": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "ip": {"required": False, "type": "str"}, "mapped_port": {"required": False, "type": "int"}, "name": {"required": True, "type": "str"}, "port": {"required": False, "type": "int"}, "ssl_algorithm": {"required": False, "type": "str", "choices": ["high", "medium", "low"]}, "ssl_cert": {"required": False, "type": "str"}, "ssl_client_renegotiation": {"required": False, "type": "str", "choices": ["allow", "deny", "secure"]}, "ssl_dh_bits": {"required": False, "type": "str", "choices": ["768", "1024", "1536", "2048"]}, "ssl_max_version": {"required": False, "type": "str", "choices": ["tls-1.0", "tls-1.1", "tls-1.2"]}, "ssl_min_version": {"required": False, "type": "str", "choices": ["tls-1.0", "tls-1.1", "tls-1.2"]}, "ssl_mode": {"required": False, "type": "str", "choices": ["half", "full"]}, "ssl_send_empty_frags": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "url_rewrite": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_firewall(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_firewall(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
simonwydooghe/ansible
lib/ansible/modules/network/fortios/fortios_firewall_ssl_server.py
Python
gpl-3.0
15,241
body { -webkit-touch-callout: none; -webkit-text-size-adjust: none; -webkit-user-select: none; background-color:#32383d; font-family: 'RobotoRegular', 'Droid Sans', 'Segoe UI', Segoe, 'San Francisco', 'Helvetica Neue', Helvetica, Arial, Geneva, sans-serif; font-size:12px; } .app { background: url(../images/cordova.png) no-repeat center top; background-size: contain; position: absolute; left: 50%; top: 50%; height: 30px; width: 250px; text-align: center; padding: 200px 0px 0px 0px; margin: -125px; } .event { border-radius: 4px; -webkit-border-radius: 4px; color: #FFFFFF; margin: 27px; padding: 4px 0px; text-transform: uppercase; background-color: #696969; animation: fade 3000ms infinite; -webkit-animation: fade 3000ms infinite; } .ready { background-color: #4B946A; } @keyframes fade { from { opacity: 1.0; } 50% { opacity: 0.4; } to { opacity: 1.0; } } @-webkit-keyframes fade { from { opacity: 1.0; } 50% { opacity: 0.4; } to { opacity: 1.0; } } @media screen and (orientation: portrait) { } @media screen and (orientation: landscape) { }
ch0c4/todobetaserie
www/css/index.css
CSS
gpl-3.0
1,242
CCOLLECT_CONF=./conf ./ccollect.sh daily -v remote1
greendeath/ccollect
test/remote.sh
Shell
gpl-3.0
52
/* ---------------------------------------------------------------------------- * SAM Software Package License * ---------------------------------------------------------------------------- * Copyright (c) 2011, Atmel Corporation * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------------- */ /** * \file * * \par Purpose * * Configuration and handling of interrupts on PIO status changes. The API * provided here have several advantages over the traditional PIO interrupt * configuration approach: * - It is highly portable * - It automatically demultiplexes interrupts when multiples pins have been * configured on a single PIO controller * - It allows a group of pins to share the same interrupt * * However, it also has several minor drawbacks that may prevent from using it * in particular applications: * - It enables the clocks of all PIO controllers * - PIO controllers all share the same interrupt handler, which does the * demultiplexing and can be slower than direct configuration * - It reserves space for a fixed number of interrupts, which can be * increased by modifying the appropriate constant in pio_it.c. * * \par Usage * * -# Initialize the PIO interrupt mechanism using PIO_InitializeInterrupts() * with the desired priority (0 ... 7). * -# Configure a status change interrupt on one or more pin(s) with * PIO_ConfigureIt(). * -# Enable & disable interrupts on pins using PIO_EnableIt() and * PIO_DisableIt(). */ #ifndef _PIO_IT_ #define _PIO_IT_ /* * Headers */ #include "pio.h" #ifdef __cplusplus extern "C" { #endif /* * Global functions */ extern void PIO_InitializeInterrupts( uint32_t dwPriority ) ; extern void PIO_ConfigureIt( const Pin *pPin, void (*handler)( const Pin* ) ) ; extern void PIO_EnableIt( const Pin *pPin ) ; extern void PIO_DisableIt( const Pin *pPin ) ; extern void PIO_IT_InterruptHandler( void ) ; extern void PioInterruptHandler( uint32_t id, Pio *pPio ) ; extern void PIO_CaptureHandler( void ) ; #ifdef __cplusplus } #endif #endif /* #ifndef _PIO_IT_ */
RobsonRojas/frertos-udemy
Keil-FreeRTOS-Sample-Project/Keil-FreeRTOS/FreeRTOSv9.0.0/FreeRTOS/Demo/CORTEX_M7_SAMV71_Xplained_IAR_Keil/libchip_samv7/include/pio_it.h
C
gpl-3.0
3,373
/** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.ide.ui.io.internal; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import com.aptana.ide.ui.io.FileSystemUtils; import com.aptana.ide.ui.io.Utils; /** * @author Michael Xia (mxia@aptana.com) */ public class FileSystemObjectPropertyTester extends PropertyTester { private static final String PROPERTY_IS_DIRECTORY = "isDirectory"; //$NON-NLS-1$ private static final String PROPERTY_IS_LOCAL = "isLocal"; //$NON-NLS-1$ private static final String PROPERTY_IS_SYMLINK = "isSymlink"; //$NON-NLS-1$ private static final String PROPERTY_IS_PRIVATE = "isPrivate"; //$NON-NLS-1$ public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { if (receiver instanceof IAdaptable) { IAdaptable adaptable = (IAdaptable) receiver; IFileStore fileStore = Utils.getFileStore(adaptable); IFileInfo fileInfo = Utils.getFileInfo(adaptable, EFS.NONE); boolean value = toBoolean(expectedValue); if (PROPERTY_IS_DIRECTORY.equals(property)) { return fileInfo.isDirectory() == value; } else if (PROPERTY_IS_SYMLINK.equals(property)) { return fileInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) == value; } else if (PROPERTY_IS_PRIVATE.equals(property)) { return FileSystemUtils.isPrivate(fileInfo) == value; } else if (PROPERTY_IS_LOCAL.equals(property)) { try { return (fileStore.toLocalFile(EFS.NONE, null) != null) == value; } catch (CoreException ignore) { // ignores the exception ignore.getCause(); } return false; } } return false; } private static boolean toBoolean(Object value) { if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } else if (value instanceof String) { return Boolean.parseBoolean((String) value); } return false; } }
HossainKhademian/Studio3
plugins/com.aptana.ui.io/src/com/aptana/ide/ui/io/internal/FileSystemObjectPropertyTester.java
Java
gpl-3.0
2,631
<?php /** * Users Online Module 1.2 * $Id: mod_comprofileronline.php 1838 2012-09-27 14:28:21Z beat $ * * @version 1.2 * @package Community Builder 1.2 * @Copyright (C) 2004-2011 Beat and 2000 - 2003 Miro International Pty Ltd * @ All rights reserved * @ Mambo Open Source is Free Software * @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html **/ if ( ! ( defined( '_VALID_CB' ) || defined( '_JEXEC' ) || defined( '_VALID_MOS' ) ) ) { die( 'Direct Access to this location is not allowed.' ); } /** * CB framework * @global CBframework $_CB_framework */ global $_CB_framework, $_CB_database, $ueConfig, $mainframe; if ( defined( 'JPATH_ADMINISTRATOR' ) ) { if ( ! file_exists( JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php' ) ) { echo 'CB not installed'; return; } include_once( JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php' ); } else { if ( ! file_exists( $mainframe->getCfg( 'absolute_path' ) . '/administrator/components/com_comprofiler/plugin.foundation.php' ) ) { echo 'CB not installed'; return; } include_once( $mainframe->getCfg( 'absolute_path' ) . '/administrator/components/com_comprofiler/plugin.foundation.php' ); } cbimport( 'cb.database' ); cbimport( 'language.front' ); function getNameFormatOnline($name,$uname,$format) { if ( $format != 3 ) { $name = str_replace( array("&amp;","&quot;","&#039;","&lt;","&gt;"), array("&","\"","'","<",">"), $name ); } SWITCH ($format) { CASE 1 : $returnName = $name; break; CASE 2 : $returnName = $name." (".$uname.")"; break; CASE 3 : $returnName = $uname; break; CASE 4 : $returnName = $uname." (".$name.")"; break; } return $returnName; } // $params is defined by include: ignore this warning: if (is_callable(array($params,"get"))) { // Mambo 4.5.0 compatibility $class_sfx = $params->get( 'moduleclass_sfx'); $pretext = $params->get( 'pretext', "" ); $posttext = $params->get( 'posttext', "" ); } else { $class_sfx = ''; $pretext = ''; $posttext = ''; } $query = "SELECT DISTINCT a.username, a.userid, u.name" ."\n FROM #__session AS a, #__users AS u" ."\n WHERE (a.userid = u.id) AND (a.guest = 0) AND " . ( ( checkJversion() >= 1 ) ? "(a.client_id = 0)" : "(NOT ( a.usertype is NULL OR a.usertype = ''))" ) ."\n ORDER BY " . ( ( $ueConfig['name_format'] > 2 ) ? "a.username" : "u.name" ) . " ASC"; $_CB_database->setQuery($query); $rows = $_CB_database->loadObjectList(); $result = ''; if ( count( $rows ) > 0) { $result .= "<ul class='mod_login".$class_sfx."'>\n"; // style='list-style-type:none; margin:0px; padding:0px; font-weight:bold;' foreach($rows as $row) { $result .= "<li><a href='" . $_CB_framework->userProfileUrl( (int) $row->userid ) . "' class='mod_login".$class_sfx."'>".htmlspecialchars(getNameFormatOnline($row->name,$row->username,$ueConfig['name_format']))."</a></li>\n"; } $result .= "</ul>\n"; if ( $pretext != '' ) { $result = $pretext . "<br />\n" . $result; } $result .= $posttext; } else { $result .= _UE_NONE; } echo $result; ?>
rboomsma/barspelers
modules/mod_comprofileronline/mod_comprofileronline.php
PHP
gpl-3.0
3,166
<?php // This file is part of Moodle - https://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <https://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['admindirname'] = 'Φάκελος διαχειριστή'; $string['availablelangs'] = 'Λίστα διαθέσιμων πακέτων γλωσσών'; $string['chooselanguagehead'] = 'Επιλογή γλώσσας'; $string['chooselanguagesub'] = 'Παρακαλούμε, επιλέξτε γλώσσα για την εγκατάσταση. Αυτή η γλώσσα θα χρησιμοποιηθεί επίσης ως προεπιλεγμένη γλώσσα για τον ιστότοπο, αν και μπορεί να αλλάξει αργότερα.'; $string['clialreadyconfigured'] = 'Το αρχείο ρυθμίσεων config.php υπάρχει ήδη. Χρησιμοποιήστε το admin/cli/install_database.php για να εγκαταστήσετε το Moodle για αυτόν τον ιστότοπο.'; $string['clialreadyinstalled'] = 'Το αρχείο ρυθμίσεων config.php υπάρχει ήδη. Χρησιμοποιήστε το admin/cli/install_database.php για να αναβαθμίσετε το Moodle για αυτόν τον ιστότοπο.'; $string['cliinstallheader'] = 'Moodle {$a} πρόγραμμα εγκατάστασης γραμμής εντολών'; $string['databasehost'] = 'Κεντρικός H/Y που φιλοξενεί την Βάση Δεδομένων'; $string['databasename'] = 'Όνομα Βάσης Δεδομένων'; $string['databasetypehead'] = 'Επιλογή οδηγού βάσης δεδομένων'; $string['dataroot'] = 'Φάκελος δεδομένων'; $string['datarootpermission'] = 'Άδεια φακέλων/καταλόγων δεδομένων'; $string['dbprefix'] = 'Πρόθεμα πινάκων'; $string['dirroot'] = 'Φάκελος Moodle'; $string['environmenthead'] = 'Έλεγχος περιβάλλοντος...'; $string['environmentsub2'] = 'Κάθε έκδοση Moodle έχει κάποια ελάχιστη απαίτηση σχετικά με την έκδοση της PHP και ενός αριθμού από αναγκαίες επεκτάσεις PHP. Ο πλήρης έλεγχος του περιβάλλοντος πραγματοποιείται πριν κάθε εγκατάσταση και αναβάθμιση. Παρακαλούμε επικοινωνήστε με τον διαχειριστή του εξυπηρετητή εάν δεν ξέρετε πως να εγκαταστήσετε νέα έκδοση της PHP ή να ενεργοποιήσετε επεκτάσεις της.'; $string['errorsinenvironment'] = 'Ο έλεγχος του περιβάλλοντος απέτυχε!'; $string['installation'] = 'Εγκατάσταση'; $string['langdownloaderror'] = 'Δυστυχώς η γλώσσα «{$a}» δεν είναι εγκατεστημένη. Η εγκατάσταση θα συνεχιστεί στα αγγλικά.'; $string['memorylimithelp'] = '<p>Το όριο μνήμης της PHP στον εξυπηρετητή σας είναι ορισμένο αυτή τη στιγμή στα {$a}.</p> <p>Αυτό μπορεί να προκαλέσει προβλήματα μνήμης στο Moodle στη συνέχεια, ειδικά αν έχετε πολλά ενεργοποιημένα αρθρώματα και/ή πολλούς χρήστες.</p> <p>Συνιστάται η ρύθμιση της PHP με μεγαλύτερο όριο, αν αυτό είναι δυνατό, π.χ. 40M. Υπάρχουν πολλοί τρόποι να το κάνετε αυτό, τους οποίους μπορείτε να δοκιμάσετε:</p> <ol> <li>Αν έχετε τη δυνατότητα, κάνετε επαναμεταγλώττιση της PHP με την παράμετρο <i>--enable-memory-limit</i>. Αυτό θα επιτρέψει στο Moodle να ορίσει μόνο του το όριο μνήμης.</li> <li>Αν έχετε πρόσβαση στο αρχείο php.ini, μπορείτε να αλλάξετε τη ρύθμιση <b>memory_limit</b> σε 40M. Αν δεν έχετε πρόσβαση ζητήστε από το διαχειριστή να το κάνει για εσάς.</li> <li>Σε κάποιους εξυπηρετητές PHP μπορείτε να δημιουργήσετε ένα αρχείο .htaccess στο φάκελο του Moodle που να περιέχει την παρακάτω γραμμή: <blockquote>php_value memory_limit 40M</div></blockquote> <p>Ωστόσο, σε κάποιους εξυπηρετητές αυτό θα εμποδίσει τη λειτουργία <b>όλων</b> των σελίδων PHP (θα βλέπετε σφάλματα όταν ανοίγετε τις σελίδες), οπότε θα πρέπει να διαγράψετε το αρχείο .htaccess.</p></li> </ol>'; $string['paths'] = 'Μονοπάτια'; $string['pathserrcreatedataroot'] = 'Ο φάκελος δεδομένων ({$a->dataroot}) δεν μπορεί να δημιουργηθεί από το πρόγραμμα εγκατάστασης.'; $string['pathshead'] = 'Επιβεβαίωση μονοπατιών'; $string['pathsrodataroot'] = 'Ο Φάκελος Δεδομένων δεν είναι εγγράψιμος.'; $string['pathsroparentdataroot'] = 'Ο γονικός φάκελος ({$a->parent}) δεν είναι εγγράψιμος. Ο φάκελος δεδομένων ({$a->dataroot}) δεν μπορεί να δημιουργηθεί από το πρόγραμμα εγκατάστασης.'; $string['pathssubadmindir'] = 'Κάποιοι λίγοι κεντρικοί υπολογιστές ιστού χρησιμοποιούν το /admin ως ειδική διεύθυνση URL για την πρόσβαση σε κάποιο πίνακα ελέγχου ή κάτι τέτοιο. Δυστυχώς αυτό έρχεται σε αντίθεση με την τυπική τοποθεσία των σελίδων διαχείρισης (admin) του Moodle. Αυτό μπορεί να διορθωθεί με την μετονομασία του admin φακέλου στην εγκατάστασή σας, και βάζοντας αυτό το καινούργιο όνομα εδώ. Για παράδειγμα: <em>moodleadmin</em>. Αυτό θα διορθώσει όλους τους συνδέσμους με το admin στην διεύθυνσή τους σε όλη την εγκατάσταση του Moodle σας.'; $string['pathssubdataroot'] = '<p>Ένας φάκελος όπου το Moodle θα αποθηκεύει όλα τα ανεβασμένα από τους χρήστες αρχεία.</p><p>Αυτός ο φάκελος θα πρέπει να είναι αναγνώσιμος ΚΑΙ ΕΓΓΡΑΨΙΜΟΣ από τον χρήστη του εξυπηρετητή ιστού (συνήθως «nobody» ή «apache»).</p><p>Δεν πρέπει να είναι προσβάσιμος κατευθείαν από τον ιστό.</p><p>Αν ο φάκελος δεν υπάρχει, η διαδικασία εγκατάστασης θα προσπαθήσει να τον δημιουργήσει.</p>'; $string['pathssubdirroot'] = '<p>Η πλήρης διαδρομή του φακέλου που περιέχει τα αρχεία κώδικα του Moodle.</p>'; $string['pathssubwwwroot'] = '<p>Η πλήρης διεύθυνση από την οποία θα γίνεται η πρόσβαση στο Moodle, δηλαδή η διεύθυνση που οι χρήστες θα εισάγουν στην γραμμή διεύθυνσης του περιηγητή, για να έχουν πρόσβαση στου Moodle.</p> <p>Δεν είναι δυνατόν να έχετε πρόβαση στο Moodle χρησιμοποιώντας πολλαπλές διευθύνσεις. Εάν ο ιστότοπος θα είναι προσβάσιμος μέσω πολλαπλών διευθύνσεων τότε επιλέξτε την ευκολότερη και εγκαταστήστε μια μόνιμη ανακατεύθυνση για καθεμία από τις άλλες διευθύνσεις.</p> <p>Εάν ο ιστότοπός σας είναι προσβάσιμος τόσο από το Διαδίκτυο όσο και από ένα εσωτερικό δίκτυο (που συχνά λέγεται intranet) τότε χρησιμοποιήστε εδώ την δημόσια διεύθυνση.</p> <p>Αν η τρέχουσα διεύθυνση δεν είναι σωστή, παρακαλούμε αλλάξτε την URL διεύθυνση στην γραμμή διευθύνσεων του περιηγητή σας και επανεκκινήστε την εγκατάσταση.</p>'; $string['pathsunsecuredataroot'] = 'Η τοποθεσία του Φάκελου Δεδομένων δεν είναι ασφαλής'; $string['pathswrongadmindir'] = 'Ο φάκελος Admin δεν υπάρχει'; $string['phpextension'] = 'Επέκταση {$a} της PHP'; $string['phpversion'] = 'Έκδοση της PHP'; $string['phpversionhelp'] = 'p>Το Moodle απαιτεί η έκδοση της PHP να είναι τουλάχιστον 5.6.5 ή 7.1 (η 7.0.x έχει κάποιους περιορισμούς στη μηχανή).</p> <p>Αυτή τη στιγμή εκτελείτε την έκδοση {$a}</p> <p>Πρέπει να αναβαθμίσετε την PHP ή να μεταφερθείτε σε έναν κεντρικό Η/Υ με μια νεότερη έκδοση της PHP!</p>'; $string['welcomep10'] = '{$a->installername} ({$a->installerversion})'; $string['welcomep20'] = 'Βλέπετε αυτή τη σελίδα γιατί εγκαταστήσατε και ξεκινήσατε με επιτυχία το πακέτο <strong>{$a->packname} {$a->packversion}</strong> στον υπολογιστή σας. Συγχαρητήρια!'; $string['welcomep30'] = 'Αυτή η έκδοση/διανομή <strong>{$a->installername}</strong> περιλαμβάνει τις εφαρμογές για τη δημιουργία ενός περιβάλλοντος μέσα στο οποίο θα λειτουργεί το <strong>Moodle</strong>, ονομαστικά:'; $string['welcomep40'] = 'Το πακέτο περιλαμβάνει επίσης το <strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong>.'; $string['welcomep50'] = 'Η χρήση όλων των εφαρμογών σε αυτό το πακέτο υπόκειται στις αντίστοιχες άδειες χρήσης. Ολόκληρο το πακέτο <strong>{$a->installername}</strong> είναι <a href="https://www.opensource.org/docs/definition_plain.html">λογισμικό ανοικτού κώδικα</a> και διανέμεται με την άδεια χρήσης <a href="https://www.gnu.org/copyleft/gpl.html">GPL</a>.'; $string['welcomep60'] = 'Οι παρακάτω σελίδες θα σας καθοδηγήσουν με εύκολα βήματα στην εγκατάσταση και ρύθμιση του <strong>Moodle</strong> στον υπολογιστή σας. Μπορείτε να δεχθείτε τις προεπιλεγμένες ρυθμίσεις ή προαιρετικά, να τις τροποποιήσετε ανάλογα με τις ανάγκες σας.'; $string['welcomep70'] = 'Πατήστε το κουμπί «Συνέχεια» για να συνεχίσετε με την εγκατάσταση του <strong>Moodle</strong>.'; $string['wwwroot'] = 'Διεύθυνση ιστού';
markn86/moodle
install/lang/el/install.php
PHP
gpl-3.0
12,875
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.contrib.auth.models import User from account.models import Account class Migration(DataMigration): def forwards(self, orm): # we need to associate each user to an account object for user in User.objects.all(): a = Account() a.user = user a.language = 'en' # default language a.save() def backwards(self, orm): # we need to delete all the accounts records Account.objects.all().delete() models = { 'actstream.action': { 'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'}, 'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}), 'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 1, 14, 4, 17, 6, 973224)'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 1, 14, 4, 17, 6, 974570)'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 1, 14, 4, 17, 6, 974509)'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'relationships': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_to'", 'symmetrical': 'False', 'through': "orm['relationships.Relationship']", 'to': "orm['auth.User']"}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.profile': { 'Meta': {'object_name': 'Profile'}, 'area': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}), 'delivery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'organization': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'profile': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'profile'", 'unique': 'True', 'null': 'True', 'to': "orm['auth.User']"}), 'voice': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'zipcode': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'people.role': { 'Meta': {'object_name': 'Role'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'relationships.relationship': { 'Meta': {'ordering': "('created',)", 'unique_together': "(('from_user', 'to_user', 'status', 'site'),)", 'object_name': 'Relationship'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'from_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'from_users'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'related_name': "'relationships'", 'to': "orm['sites.Site']"}), 'status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['relationships.RelationshipStatus']"}), 'to_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'to_users'", 'to': "orm['auth.User']"}), 'weight': ('django.db.models.fields.FloatField', [], {'default': '1.0', 'null': 'True', 'blank': 'True'}) }, 'relationships.relationshipstatus': { 'Meta': {'ordering': "('name',)", 'object_name': 'RelationshipStatus'}, 'from_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'symmetrical_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'to_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) } } complete_apps = ['people']
GISPPU/GrenadaLandInformation
geonode/people/migrations/0003_link_users_to_account.py
Python
gpl-3.0
10,196
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Prototype Unit test file | Number</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" charset="utf-8"> var eventResults = {}; var originalElement = window.Element; </script> <script src="../../../dist/prototype.js" type="text/javascript"></script> <script src="../../lib/unittest.js" type="text/javascript"></script> <link rel="stylesheet" href="../../test.css" type="text/css" /> <script src="../number_test.js" type="text/javascript"></script> </head> <body> <h1>Prototype Unit test file</h1> <h2>Number</h2> <!-- This file is programmatically generated. Do not attempt to modify it. Instead, modify --> <!-- Log output start --> <div id="testlog"></div> <!-- Log output end --> <!-- HTML Fixtures start --> <!-- HTML Fixtures end --> </body> </html> <script type="text/javascript" charset="utf-8"> eventResults.endOfDocument = true; </script>
Yukarumya/Yukarum-Redfoxes
dom/tests/mochitest/ajax/prototype/test/unit/tmp/number_test.html
HTML
mpl-2.0
1,159
<html> <head> <title>Iframe test for bug 304459</title> </head> <body"> <script> Object.prototype.x = "oops"; </script> </body> </html>
Yukarumya/Yukarum-Redfoxes
dom/tests/mochitest/bugs/iframe_bug304459-1.html
HTML
mpl-2.0
139
/** * 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. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. * * Contributor(s): CIRG, University of Washington, Seattle WA. */ package us.mn.state.health.lims.systemuser.valueholder; import us.mn.state.health.lims.common.valueholder.EnumValueItemImpl; import us.mn.state.health.lims.systemusermodule.valueholder.PermissionAgent; public class SystemUser extends EnumValueItemImpl implements PermissionAgent{ private static final long serialVersionUID = 1L; private String id; private String firstName; private String lastName; private String loginName; private String isActive; private String isEmployee; private String externalId; private String initials; public SystemUser() { } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getLoginName() { return loginName; } public void setExternalId(String externalId) { this.externalId = externalId; } public String getExternalId() { return externalId; } public void setInitials(String initials) { this.initials = initials; } public String getInitials() { return initials; } public void setIsActive(String isActive) { this.isActive = isActive; } public String getIsActive() { return isActive; } public void setIsEmployee(String isEmployee) { this.isEmployee = isEmployee; } public String getIsEmployee() { return isEmployee; } public String getNameForDisplay() { return firstName + " " + lastName; } public String getDisplayName() { return getLastName() + "," + getFirstName(); } public String getShortNameForDisplay() { return getNameForDisplay(); } }
openelisglobal/openelisglobal-core
app/src/us/mn/state/health/lims/systemuser/valueholder/SystemUser.java
Java
mpl-2.0
2,524
<%! from django.utils.translation import ugettext as _ %> <%! from datetime import datetime, timedelta %> <%! import pytz %> <%page args="section_data"/> <%include file="add_coupon_modal.html" args="section_data=section_data" /> <%include file="edit_coupon_modal.html" args="section_data=section_data" /> <%include file="set_course_mode_price_modal.html" args="section_data=section_data" /> <%include file="generate_registarion_codes_modal.html" args="section_data=section_data" /> <div class="ecommerce-wrapper"> <h3 class="error-msgs" id="error-msg"></h3> <div id = "accordion"> <div class="wrap"> <h2>${_('Registration Codes')}</h2> <div> %if section_data['sales_admin']: <span class="code_tip">${_('Click to generate Registration Codes')} <a id="registration_code_generation_link" href="#reg_code_generation_modal" class="add blue-button">${_('Generate Registration Codes')}</a> </span> %endif <p>${_('Click to generate a CSV file of all Course Registrations Codes:')}</p> <p> <form action="${ section_data['get_registration_code_csv_url'] }" id="download_registration_codes" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }"> <input type="text" name="download_company_name" placeholder="Company Name (Optional)"/> <input type="submit" name="list-registration-codes-csv" value="${_("Download Registration Codes")}" data-csv="true"> </form> </p> <p>${_('Click to generate a CSV file of all Active Course Registrations Codes:')}</p> <p> <form action="${ section_data['active_registration_code_csv_url'] }" id="active_registration_codes" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }"> <input type="text" name="active_company_name" placeholder="Company Name (Optional)"/> <input type="submit" name="active-registration-codes-csv" value="${_("Active Registration Codes")}" data-csv="true"> </form> </p> <p>${_('Click to generate a CSV file of all Spent Course Registrations Codes:')}</p> <p> <form action="${ section_data['spent_registration_code_csv_url'] }" id="spent_registration_codes" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }"> <input type="text" name="spent_company_name" placeholder="Company Name (Optional)"/> <input type="submit" name="spent-registration-codes-csv" value="${_("Spent Registration Codes")}" data-csv="true"> </form> </p> <a id="registration_code_generation_link-trigger" href="#registration_code_generation_modal" rel="leanModal"></a> </div> </div> <!-- end wrap --> %if section_data['coupons_enabled']: <div class="wrap"> <h2>${_("Course Price")}</h2> <div> <span class="tip">${_("Course Price: ")}<span>${section_data['currency_symbol']}${section_data['course_price']}</span> %if section_data['access']['finance_admin'] is True: <a id="course_price_link" href="#set-course-mode-price-modal" rel="leanModal" class="add blue-button">+ ${_('Set Price')}</a> %endif </span> </div> </div> %endif <!-- end wrap --> %if section_data['access']['finance_admin']: <div class="wrap"> <h2>${_("Sales")}</h2> <div> %if section_data['total_amount'] is not None: <span><strong>${_("Total CC Amount: ")}</strong></span><span>$${section_data['total_amount']}</span> %endif <span class="csv_tip"> <div > ${_("Click to generate a CSV file for all sales records in this course")} <input type="button" class="add blue-button" name="list-sale-csv" value="${_("Download All Invoice Sales")}" data-endpoint="${ section_data['get_sale_records_url'] }" data-csv="true"> <input type="button" class="add blue-button" name="list-order-sale-csv" value="${_("Download All CC Sales")}" data-endpoint="${ section_data['get_sale_order_records_url'] }" data-csv="true"> </div> </span> <hr> <p>${_("Enter the invoice number to invalidate or re-validate sale")}</p> <span class="invalid_sale"> <input type="number" id="invoice_number" placeholder= "${_("Enter Invoice Number")}"/> <input type="button" class="add blue-button" id="invalidate_invoice" value="${_("Invalidate Sale")}"> <input type="button" class="add blue-button" id="re_validate_invoice" value="${_("Revalidate Sale")}"> </span> </div> </div><!-- end wrap --> %endif %if section_data['coupons_enabled']: <div class="wrap"> <h2>${_("Coupons List")}</h2> <div> <span class="csv_tip">${_("Click to generate a CSV file of all Coupon Codes:")} <input class="add blue-button" type="button" name="download-coupon-codes-csv" value="${_("Download coupon codes")}" data-endpoint="${ section_data['download_coupon_codes_url'] }" data-csv="true"> </span> <span class="tip">${_("Coupons Information")} <a id="add_coupon_link" href="#add-coupon-modal" rel="leanModal" class="add blue-button">+ ${_("Add Coupon")}</a></span> <div class="wrapper-content wrapper"> <section class="content"> %if len(section_data['coupons']): <table class="coupons-table"> <thead> <tr class="coupons-headings"> <th class="c_code">${_("Code")}</th> <th class="c_dsc">${_("Description")}</th> <th class="c_expiry">${_("Expiry Date")}</th> <th class="c_discount">${_("Discount (%)")}</th> <th class="c_count">${_("Redeem Count")}</th> <th class="c_action">${_("Actions")}</th> </tr> </thead> <tbody> %for coupon in section_data['coupons']: <% current_date = datetime.now(pytz.UTC) %> <% coupon_expiry_date = coupon.expiration_date %> %if coupon.is_active == False: <tr class="coupons-items inactive_coupon"> %elif coupon_expiry_date is not None and current_date >= coupon_expiry_date: <tr class="coupons-items expired_coupon"> %else: <tr class="coupons-items"> %endif <td>${_('{code}').format(code=coupon.code)}</td> <td>${_('{description}').format(description=coupon.description)}</td> <td> ${coupon.display_expiry_date} </td> <td>${_('{discount}').format(discount=coupon.percentage_discount)}</td> <td>${ coupon.couponredemption_set.filter(order__status='purchased').count() }</td> <td><a data-item-id="${coupon.id}" class='remove_coupon' href='#'>[x]</a><a href="#edit-modal" data-item-id="${coupon.id}" class="edit-right">${_('Edit')}</a></td> </tr> %endfor </tbody> </table> <a id="edit-modal-trigger" href="#edit-coupon-modal" rel="leanModal"></a> %endif </section> </div> </div> </div> %endif <!-- end wrap --> </div> </div> <script> $(function () { var icons = { header: "ui-fa-circle-arrow-e", activeHeader: "ui-fa-circle-arrow-s" }; var act = 0; $("#accordion").accordion( { heightStyle: 'content', activate: function(event, ui) { var active = jQuery("#accordion").accordion('option', 'active'); $.cookie('saved_index', null); $.cookie('saved_index', active); $('#error-msg').val(''); $("#error-msg").fadeOut(2000 , function(){ $('#error-msg').hide() }); }, animate: 400, header: "> div.wrap >h2", icons:icons, active:isNaN(parseInt($.cookie('saved_index'))) ? 0 : parseInt($.cookie('saved_index')), collapsible: true }); $('a[rel*=leanModal]').leanModal(); $.each($("a.edit-right"), function () { if ($(this).parent().parent('tr').hasClass('inactive_coupon')) { $(this).removeAttr('href') } }); $.each($("a.remove_coupon"), function () { if ($(this).parent().parent('tr').hasClass('inactive_coupon')) { $(this).removeAttr('href') } }); $('#registration_code_generation_link').click(function(event){ event.preventDefault(); $.ajax({ type: "POST", url: "${section_data['get_user_invoice_preference_url']}", success: function (data) { $('#invoice-copy').prop('checked', data.invoice_copy); $('#registration_code_generation_link-trigger').click(); } }); }); $('#invalidate_invoice, #re_validate_invoice').click(function (event) { event.preventDefault(); var event_type = "re_validate" if($(event.target).attr('id')=='invalidate_invoice'){ event_type = "invalidate" } if($('#invoice_number').val() == "") { $('#error-msg').attr('class','error-msgs') $('#error-msg').html("${_('Invoice number should not be empty.')}").show(); return } $.ajax({ type: "POST", data: {invoice_number: $('#invoice_number').val(), event_type:event_type}, url: "${section_data['sale_validation_url']}", success: function (data) { $('#error-msg').attr('class','success-msgs') $('#error-msg').html(data.message).show(); $('#invoice_number').val(''); }, error: function(jqXHR, textStatus, errorThrown) { $('#error-msg').attr('class','error-msgs') $('#error-msg').html(jqXHR.responseText).show(); } }); }); $('a.edit-right').click(function (event) { $('#edit_coupon_form #coupon_form_error').attr('style', 'display: none'); $('#edit_coupon_form #coupon_form_error').text(); event.preventDefault(); event.stopPropagation(); var coupon_id = $(this).data('item-id'); $('#coupon_id').val(coupon_id); if ($(this).parent().parent('tr').hasClass('inactive_coupon')) { return false; } $.ajax({ type: "POST", data: {id: coupon_id}, url: "${section_data['ajax_get_coupon_info']}", success: function (data) { $('#error-msg').val(''); $('#error-msg').hide() $('input#edit_coupon_code').val(data.coupon_code); $('input#edit_coupon_discount').val(data.coupon_discount); $('textarea#edit_coupon_description').val(data.coupon_description); $('input#edit_coupon_course_id').val(data.coupon_course_id); if (data.expiry_date) { $('input#edit_coupon_expiration_date').val(data.expiry_date); } else { $('input#edit_coupon_expiration_date').val("${_('Never Expires')}"); } $('#edit-modal-trigger').click(); }, error: function(jqXHR, textStatus, errorThrown) { var data = $.parseJSON(jqXHR.responseText); $('#error-msg').attr('class','error-msgs') $('#error-msg').html(data.message).show(); } }); }); $('a.remove_coupon').click(function (event) { var anchor = $(this); if (anchor.data("disabled")) { return false; } anchor.data("disabled", "disabled"); event.preventDefault(); if ($(this).parent().parent('tr').hasClass('inactive_coupon')) { return false; } $.ajax({ type: "POST", data: {id: $(this).data('item-id')}, url: "${section_data['ajax_remove_coupon_url']}", success: function (data) { anchor.removeData("disabled"); location.reload(true); }, error: function(jqXHR, textStatus, errorThrown) { var data = $.parseJSON(jqXHR.responseText); $('#error-msg').attr('class','error-msgs') $('#error-msg').html(data.message).show(); anchor.removeData("disabled"); } }); }); var generate_registration_code_form = $("form#generate_codes"); var generate_registration_button = $('input[name="generate-registration-codes-csv"]'); var registration_code_error = $('#generate_codes #registration_code_form_error'); function validateEmail(sEmail) { filter = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/ return filter.test(sEmail) } generate_registration_code_form.submit(function () { registration_code_error.attr('style', 'display: none'); generate_registration_button.attr('disabled', true); var total_registration_codes = $('input[name="total_registration_codes"]').val(); var recipient_name = $('input[name="recipient_name"]').val(); var recipient_email = $('input[name="recipient_email"]').val(); var sale_price = $('input[name="sale_price"]').val(); var company_name = $('input[name="company_name"]').val(); var company_contact_name = $('input[name="company_contact_name"]').val(); var company_contact_email = $('input[name="company_contact_email"]').val(); var address_line = $('input[name="address_line_1"]').val(); if (company_name == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the company name'); generate_registration_button.removeAttr('disabled'); return false; } if (($.isNumeric(company_name))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the non-numeric value for company name'); generate_registration_button.removeAttr('disabled'); return false; } if (company_contact_name == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the company contact name'); generate_registration_button.removeAttr('disabled'); return false; } if (($.isNumeric(company_contact_name))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the non-numeric value for company contact name'); generate_registration_button.removeAttr('disabled'); return false; } if (company_contact_email == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the company contact email'); generate_registration_button.removeAttr('disabled'); return false; } if (!(validateEmail(company_contact_email))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the valid email address'); generate_registration_button.removeAttr('disabled'); return false; } if (recipient_name == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the recipient name'); generate_registration_button.removeAttr('disabled'); return false; } if (($.isNumeric(recipient_name))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the non-numeric value for recipient name'); generate_registration_button.removeAttr('disabled'); return false; } if (recipient_email == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the recipient email'); generate_registration_button.removeAttr('disabled'); return false; } if (!(validateEmail(recipient_email))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the valid email address'); generate_registration_button.removeAttr('disabled'); return false; } if (address_line == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the billing address'); generate_registration_button.removeAttr('disabled'); return false; } if (sale_price == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the sale price'); generate_registration_button.removeAttr('disabled'); return false } if (!($.isNumeric(sale_price))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the numeric value for sale price'); generate_registration_button.removeAttr('disabled'); return false } if (total_registration_codes == '') { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the total registration codes'); generate_registration_button.removeAttr('disabled'); return false } if (!($.isNumeric(total_registration_codes))) { registration_code_error.attr('style', 'display: block !important'); registration_code_error.text('Please enter the numeric value for total registration codes'); generate_registration_button.removeAttr('disabled'); return false; } var modal_overLay = $('#lean_overlay') var registration_code_modal = $('#registration_code_generation_modal'); registration_code_modal.hide(); modal_overLay.hide(); }); $('#update_coupon_button').click(function () { $("#update_coupon_button").attr('disabled', true); var coupon_id = $.trim($('#coupon_id').val()); var description = $.trim($('#edit_coupon_description').val()); $.ajax({ type: "POST", data: { "coupon_id" : coupon_id, "description": description }, url: "${section_data['ajax_update_coupon']}", success: function (data) { location.reload(true); }, error: function(jqXHR, textStatus, errorThrown) { var data = $.parseJSON(jqXHR.responseText); $("#update_coupon_button").removeAttr('disabled'); $('#edit_coupon_form #coupon_form_error').attr('style', 'display: block !important'); $('#edit_coupon_form #coupon_form_error').text(data.message); } }); }); $('#course_price_link').click(function () { reset_input_fields(); }); $('#add_coupon_link').click(function () { reset_input_fields(); }); $('#registration_code_generation_link').click(function () { reset_input_fields(); $('input[name="generate-registration-codes-csv"]').removeAttr('disabled'); }); $('#set_course_button').click(function () { $("#set_course_button").attr('disabled', true); // Get the Code and Discount value and trim it var course_price = $.trim($('#mode_price').val()); var currency = $.trim($('#course_mode_currency').val()); // Check if empty of not if (course_price === '') { $('#set_price_form #course_form_error').attr('style', 'display: block !important'); $('#set_price_form #course_form_error').text("${_('Please enter the course price')}"); $("#set_course_button").removeAttr('disabled'); return false; } if (!$.isNumeric(course_price)) { $("#set_course_button").removeAttr('disabled'); $('#set_price_form #course_form_error').attr('style', 'display: block !important'); $('#set_price_form #course_form_error').text("${_('Please enter the numeric value for course price')}"); return false; } if (currency == '') { $('#set_price_form #course_form_error').attr('style', 'display: block !important'); $('#set_price_form #course_form_error').text("${_('Please select the currency')}"); $("#set_course_button").removeAttr('disabled'); return false; } $.ajax({ type: "POST", data: { "course_price" : course_price, "currency": currency }, url: "${section_data['set_course_mode_url']}", success: function (data) { location.reload(true); }, error: function(jqXHR, textStatus, errorThrown) { var data = $.parseJSON(jqXHR.responseText); $("#set_course_button").removeAttr('disabled'); $('#set_price_form #course_form_error').attr('style', 'display: block !important'); $('#set_price_form #course_form_error').text(data.message); } }); }); $('#add_coupon_button').click(function () { $("#add_coupon_button").attr('disabled', true); // Get the Code and Discount value and trim it var code = $.trim($('#coupon_code').val()); var coupon_discount = $.trim($('#coupon_discount').val()); var course_id = $.trim($('#coupon_course_id').val()); var description = $.trim($('#coupon_description').val()); var expiration_date = $.trim($('#coupon_expiration_date').val()); // Check if empty of not if (code === '') { $("#add_coupon_button").removeAttr('disabled'); $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important'); $('#add_coupon_form #coupon_form_error').text("${_('Please enter the coupon code')}"); return false; } if (parseInt(coupon_discount) > 100) { $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important'); $('#add_coupon_form #coupon_form_error').text("${_('Please enter the coupon discount value less than or equal to 100')}"); $("#add_coupon_button").removeAttr('disabled'); return false; } if (!$.isNumeric(coupon_discount)) { $("#add_coupon_button").removeAttr('disabled'); $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important'); $('#add_coupon_form #coupon_form_error').text("${_('Please enter the numeric value for discount')}"); return false; } $.ajax({ type: "POST", data: { "code" : code, "discount": coupon_discount, "course_id": course_id, "description": description, "expiration_date": expiration_date }, url: "${section_data['ajax_add_coupon']}", success: function (data) { location.reload(true); }, error: function(jqXHR, textStatus, errorThrown) { var data = $.parseJSON(jqXHR.responseText); $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important'); $('#add_coupon_form #coupon_form_error').text(data.message); $("#add_coupon_button").removeAttr('disabled'); } }); }); // removing close link's default behavior $('.close-modal').click(function (e) { $("#update_coupon_button").removeAttr('disabled'); $("#add_coupon_button").removeAttr('disabled'); $("#set_course_button").removeAttr('disabled'); $('input[name="generate-registration-codes-csv"]').removeAttr('disabled'); reset_input_fields(); e.preventDefault(); }); var onModalClose = function () { $("#add-coupon-modal").attr("aria-hidden", "true"); $(".remove_coupon").focus(); $("#edit-coupon-modal").attr("aria-hidden", "true"); $(".edit-right").focus(); $("#set-course-mode-price-modal").attr("aria-hidden", "true"); $("#registration_code_generation_modal").attr("aria-hidden", "true"); $("#add_coupon_button").removeAttr('disabled'); $("#set_course_button").removeAttr('disabled'); $("#update_coupon_button").removeAttr('disabled'); $('input[name="generate-registration-codes-csv"]').removeAttr('disabled'); reset_input_fields(); }; var cycle_modal_tab = function (from_element_name, to_element_name) { $(from_element_name).on('keydown', function (e) { var keyCode = e.keyCode || e.which; var TAB_KEY = 9; // 9 corresponds to the tab key if (keyCode === TAB_KEY) { e.preventDefault(); $(to_element_name).focus(); } }); }; $("#add-coupon-modal .close-modal").click(onModalClose); $("#edit-coupon-modal .close-modal").click(onModalClose); $('#registration_code_generation_modal .close-modal').click(onModalClose); $("#set-course-mode-price-modal .close-modal").click(reset_input_fields); // Hitting the ESC key will exit the modal $("#add-coupon-modal, #edit-coupon-modal, #set-course-mode-price-modal, #registration_code_generation_modal").on("keydown", function (e) { var keyCode = e.keyCode || e.which; // 27 is the ESC key if (keyCode === 27) { e.preventDefault(); $("#add-coupon-modal .close-modal").click(); $("#set-course-mode-price-modal .close-modal").click(); $("#edit-coupon-modal .close-modal").click(); $('#registration_code_generation_modal .close-modal').click(); } }); }); var reset_input_fields = function () { $('#error-msg').val(''); $('#error-msg').hide() $('#add_coupon_form #coupon_form_error').attr('style', 'display: none'); $('#set_price_form #course_form_error').attr('style', 'display: none'); $('#generate_codes #registration_code_form_error').attr('style', 'display: none'); $('#add_coupon_form #coupon_form_error').text(); $('input#mode_price').val(''); $('input#coupon_code').val(''); $('input#coupon_discount').val(''); $('textarea#coupon_description').val(''); $('input[name="company_name"]').val(''); $('input[name="total_registration_codes"]').val(''); $('input[name="address_line_1"]').val(''); $('input[name="address_line_2"]').val(''); $('input[name="address_line_3"]').val(''); $('input[name="city"]').val(''); $('input[name="state"]').val(''); $('input[name="zip"]').val(''); $('input[name="country"]').val(''); $('input[name="customer_reference_number"]').val(''); $('input[name="recipient_name"]').val(''); $('input[name="sale_price"]').val(''); $('input[name="recipient_email"]').val(''); $('input[name="company_contact_name"]').val(''); $('input[name="company_contact_email"]').val(''); $('input[name="invoice"]').attr('checked', 'checked'); $('input[name="company_reference"]').val(''); $('input[name="internal_reference"]').val(''); } </script>
jswope00/griffinx
lms/templates/instructor/instructor_dashboard_2/e-commerce.html
HTML
agpl-3.0
28,417
module Spec module Example module Subject module ExampleGroupMethods # Defines an explicit subject for an example group which can then be the # implicit receiver (through delegation) of calls to +should+. # # == Examples # # describe CheckingAccount, "with $50" do # subject { CheckingAccount.new(:amount => 50, :currency => :USD) } # it { should have_a_balance_of(50, :USD) } # it { should_not be_overdrawn } # its(:currency) { should == :USD } # end # # See +ExampleMethods#should+ for more information about this approach. def subject(&block) block.nil? ? explicit_subject || implicit_subject : @explicit_subject_block = block end def its(attribute, &block) describe(attribute) do example do self.class.class_eval do define_method(:subject) do super().send(attribute) end end instance_eval(&block) end end end attr_reader :explicit_subject_block # :nodoc: private def explicit_subject group = self while group.respond_to?(:explicit_subject_block) return group.explicit_subject_block if group.explicit_subject_block group = group.superclass end end def implicit_subject (described_class ? proc {described_class.new} : proc {description_args.first}) end end module ExampleMethods alias_method :__should_for_example_group__, :should alias_method :__should_not_for_example_group__, :should_not # Returns the subject defined in ExampleGroupMethods#subject. The # subject block is only executed once per example, the result of which # is cached and returned by any subsequent calls to +subject+. # # If a class is passed to +describe+ and no subject is explicitly # declared in the example group, then +subject+ will return a new # instance of that class. # # == Examples # # # explicit subject defined by the subject method # describe Person do # subject { Person.new(:birthdate => 19.years.ago) } # it "should be eligible to vote" do # subject.should be_eligible_to_vote # end # end # # # implicit subject => { Person.new } # describe Person do # it "should be eligible to vote" do # subject.should be_eligible_to_vote # end # end def subject @subject ||= instance_eval(&self.class.subject) end # When +should+ is called with no explicit receiver, the call is # delegated to the object returned by +subject+. Combined with # an implicit subject (see +subject+), this supports very concise # expressions. # # == Examples # # describe Person do # it { should be_eligible_to_vote } # end def should(matcher=nil, message=nil) self == subject ? self.__should_for_example_group__(matcher) : subject.should(matcher,message) end # Just like +should+, +should_not+ delegates to the subject (implicit or # explicit) of the example group. # # == Examples # # describe Person do # it { should_not be_eligible_to_vote } # end def should_not(matcher=nil, message=nil) self == subject ? self.__should_not_for_example_group__(matcher) : subject.should_not(matcher,message) end end end end end
ging/vcc
vendor/gems/rspec-1.3.1/lib/spec/example/subject.rb
Ruby
agpl-3.0
3,848
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.examples.readers; import java.awt.Color; import java.awt.Dimension; public class ReadCanvas extends javax.swing.JPanel { private int[] readers; private int[] writers; public ReadCanvas() { readers = new int[3]; writers = new int[3]; this.setPreferredSize(new Dimension(300, 300)); } public void setRead(int id, boolean state) { readers[id] = (state) ? 1 : 0; // Casting bool into int.. repaint(); } public void setWrite(int id, boolean state) { writers[id] = (state) ? 1 : 0; // Casting bool into int.. repaint(); } public void setWait(int id, boolean isReader) { if (isReader) { readers[id] = -1; } else { writers[id] = -1; } } @Override protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); // Text layout g.setColor(Color.black); g.drawString("Readers", 10, 10); g.drawString("Writers", 10, 140); for (int current = 0; current < 3; current++) { // Reader's image if (readers[current] == 1) { g.setColor(Color.red); } else if (readers[current] == -1) { g.setColor(Color.orange); } else { g.setColor(Color.green); } g.fillRect(10 + (current * 50), 30, 40, 60); // Writer's image if (writers[current] == 1) { g.setColor(Color.red); } else if (writers[current] == -1) { g.setColor(Color.orange); } else { g.setColor(Color.green); } g.fillRect(10 + (current * 50), 170, 40, 60); } // Legende g.setColor(Color.green); g.fillRect(160, 120, 10, 10); // vert g.setColor(Color.orange); g.fillRect(160, 140, 10, 10); // orange g.setColor(Color.red); g.fillRect(160, 160, 10, 10); // rouge g.setColor(Color.black); g.drawString(" : Available", 170, 128); g.drawString(" : Waiting for Read or Write lock", 170, 148); g.drawString(" : Reading or Writing", 170, 168); } }
acontes/programming
src/Examples/org/objectweb/proactive/examples/readers/ReadCanvas.java
Java
agpl-3.0
3,705
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.sql.optimizer; import com.foundationdb.sql.NamedParamsTestBase; import com.foundationdb.sql.TestBase; import com.foundationdb.sql.parser.StatementNode; import com.foundationdb.junit.NamedParameterizedRunner; import com.foundationdb.junit.NamedParameterizedRunner.TestParameters; import com.foundationdb.junit.Parameterization; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.IOException; import java.util.Collection; @RunWith(NamedParameterizedRunner.class) public class ViewTest extends OptimizerTestBase implements TestBase.GenerateAndCheckResult { public static final File RESOURCE_DIR = new File(OptimizerTestBase.RESOURCE_DIR, "view"); @TestParameters public static Collection<Parameterization> statements() throws Exception { return NamedParamsTestBase.namedCases(sqlAndExpected(RESOURCE_DIR)); } public ViewTest(String caseName, String sql, String expected, String error) { super(caseName, sql, expected, error); } @Before public void loadDDL() throws Exception { loadSchema(new File(RESOURCE_DIR, "schema.ddl")); } @Test public void testView() throws Exception { generateAndCheckResult(); } @Override public String generateResult() throws Exception { StatementNode stmt = parser.parseStatement(sql); binder.bind(stmt); return getTree(stmt); } @Override public void checkResult(String result) throws IOException { assertEqualsWithoutHashes(caseName, expected, result); } }
AydinSakar/sql-layer
src/test/java/com/foundationdb/sql/optimizer/ViewTest.java
Java
agpl-3.0
2,378
/** * Shopware 4 * Copyright © shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ /** * Shopware UI - Main Backend Application Bootstrap * * This file bootstrapps the complete backend structure. */ //{block name="backend/index/application"} Ext.define('Shopware.apps.Index', { /** * Extends from our special controller, which handles the * sub-application behavior and the event bus * @string */ extend:'Enlight.app.SubApplication', /** * Enables our bulk loading technique. * @booelan */ bulkLoad: true, /** * Sets the loading path for the sub-application. * * Note that you'll need a "loadAction" in your * controller (server-side) * @string */ loadPath: '{url action=load}', /** * Required controllers for module (subapplication) * @array */ controllers:[ 'Main', 'Widgets', 'ErrorReporter' ], /** * Requires class for the module (subapplication) */ requires: [ 'Shopware.container.Viewport' ], /** * Required views for module (subapplication) * @array */ views: [ 'Main', 'Menu', 'Footer', 'Search', 'widgets.Window', 'widgets.Sales', 'widgets.Upload', 'widgets.Visitors', 'widgets.Orders', 'widgets.Notice', 'widgets.Merchant', 'widgets.Base', 'merchant.Window' ], /** * Required models for the module * @array */ models: [ 'Widget', 'WidgetSettings', 'Turnover', 'Batch', 'Customers', 'Visitors', 'Orders', 'Merchant', 'MerchantMail' ], /** * Required stores for the module * @array */ stores: [ 'Widget', 'WidgetSettings' ] }); //{/block}
Chaz0r/test
templates/_default/backend/index/app.js
JavaScript
agpl-3.0
2,751
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------------- * SpiderWebPlotTests.java * ----------------------- * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 10-Jun-2005 : Version 1 (DG); * 01-Jun-2006 : Added testDrawWithNullInfo() method (DG); * 05-Feb-2007 : Added more checks to testCloning (DG); * 21-Jun-2007 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.plot.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.JFreeChart; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.SpiderWebPlot; import org.jfree.chart.urls.StandardCategoryURLGenerator; import org.jfree.chart.util.Rotation; import org.jfree.chart.util.TableOrder; import org.jfree.data.category.DefaultCategoryDataset; /** * Tests for the {@link SpiderWebPlot} class. */ public class SpiderWebPlotTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(SpiderWebPlotTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public SpiderWebPlotTests(String name) { super(name); } /** * Some checks for the equals() method. */ public void testEquals() { SpiderWebPlot p1 = new SpiderWebPlot(new DefaultCategoryDataset()); SpiderWebPlot p2 = new SpiderWebPlot(new DefaultCategoryDataset()); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); // dataExtractOrder p1.setDataExtractOrder(TableOrder.BY_COLUMN); assertFalse(p1.equals(p2)); p2.setDataExtractOrder(TableOrder.BY_COLUMN); assertTrue(p1.equals(p2)); // headPercent p1.setHeadPercent(0.321); assertFalse(p1.equals(p2)); p2.setHeadPercent(0.321); assertTrue(p1.equals(p2)); // interiorGap p1.setInteriorGap(0.123); assertFalse(p1.equals(p2)); p2.setInteriorGap(0.123); assertTrue(p1.equals(p2)); // startAngle p1.setStartAngle(0.456); assertFalse(p1.equals(p2)); p2.setStartAngle(0.456); assertTrue(p1.equals(p2)); // direction p1.setDirection(Rotation.ANTICLOCKWISE); assertFalse(p1.equals(p2)); p2.setDirection(Rotation.ANTICLOCKWISE); assertTrue(p1.equals(p2)); // maxValue p1.setMaxValue(123.4); assertFalse(p1.equals(p2)); p2.setMaxValue(123.4); assertTrue(p1.equals(p2)); // legendItemShape p1.setLegendItemShape(new Rectangle(1, 2, 3, 4)); assertFalse(p1.equals(p2)); p2.setLegendItemShape(new Rectangle(1, 2, 3, 4)); assertTrue(p1.equals(p2)); // seriesPaint p1.setSeriesPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.white)); assertFalse(p1.equals(p2)); p2.setSeriesPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.white)); assertTrue(p1.equals(p2)); // seriesPaintList p1.setSeriesPaint(1, new GradientPaint(1.0f, 2.0f, Color.yellow, 3.0f, 4.0f, Color.white)); assertFalse(p1.equals(p2)); p2.setSeriesPaint(1, new GradientPaint(1.0f, 2.0f, Color.yellow, 3.0f, 4.0f, Color.white)); assertTrue(p1.equals(p2)); // baseSeriesPaint p1.setBaseSeriesPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.black)); assertFalse(p1.equals(p2)); p2.setBaseSeriesPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.black)); assertTrue(p1.equals(p2)); // seriesOutlinePaint p1.setSeriesOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.black)); assertFalse(p1.equals(p2)); p2.setSeriesOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.black)); assertTrue(p1.equals(p2)); // seriesOutlinePaintList p1.setSeriesOutlinePaint(1, new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.green)); assertFalse(p1.equals(p2)); p2.setSeriesOutlinePaint(1, new GradientPaint(1.0f, 2.0f, Color.blue, 3.0f, 4.0f, Color.green)); assertTrue(p1.equals(p2)); // baseSeriesOutlinePaint p1.setBaseSeriesOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.cyan, 3.0f, 4.0f, Color.green)); assertFalse(p1.equals(p2)); p2.setBaseSeriesOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.cyan, 3.0f, 4.0f, Color.green)); assertTrue(p1.equals(p2)); // seriesOutlineStroke BasicStroke s = new BasicStroke(1.23f); p1.setSeriesOutlineStroke(s); assertFalse(p1.equals(p2)); p2.setSeriesOutlineStroke(s); assertTrue(p1.equals(p2)); // seriesOutlineStrokeList p1.setSeriesOutlineStroke(1, s); assertFalse(p1.equals(p2)); p2.setSeriesOutlineStroke(1, s); assertTrue(p1.equals(p2)); // baseSeriesOutlineStroke p1.setBaseSeriesOutlineStroke(s); assertFalse(p1.equals(p2)); p2.setBaseSeriesOutlineStroke(s); assertTrue(p1.equals(p2)); // webFilled p1.setWebFilled(false); assertFalse(p1.equals(p2)); p2.setWebFilled(false); assertTrue(p1.equals(p2)); // axisLabelGap p1.setAxisLabelGap(0.11); assertFalse(p1.equals(p2)); p2.setAxisLabelGap(0.11); assertTrue(p1.equals(p2)); // labelFont p1.setLabelFont(new Font("Serif", Font.PLAIN, 9)); assertFalse(p1.equals(p2)); p2.setLabelFont(new Font("Serif", Font.PLAIN, 9)); assertTrue(p1.equals(p2)); // labelPaint p1.setLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertFalse(p1.equals(p2)); p2.setLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertTrue(p1.equals(p2)); // labelGenerator p1.setLabelGenerator(new StandardCategoryItemLabelGenerator("XYZ: {0}", new DecimalFormat("0.000"))); assertFalse(p1.equals(p2)); p2.setLabelGenerator(new StandardCategoryItemLabelGenerator("XYZ: {0}", new DecimalFormat("0.000"))); assertTrue(p1.equals(p2)); // toolTipGenerator p1.setToolTipGenerator(new StandardCategoryToolTipGenerator()); assertFalse(p1.equals(p2)); p2.setToolTipGenerator(new StandardCategoryToolTipGenerator()); assertTrue(p1.equals(p2)); // urlGenerator p1.setURLGenerator(new StandardCategoryURLGenerator()); assertFalse(p1.equals(p2)); p2.setURLGenerator(new StandardCategoryURLGenerator()); assertTrue(p1.equals(p2)); // axisLinePaint p1.setAxisLinePaint(Color.red); assertFalse(p1.equals(p2)); p2.setAxisLinePaint(Color.red); assertTrue(p1.equals(p2)); // axisLineStroke p1.setAxisLineStroke(new BasicStroke(1.1f)); assertFalse(p1.equals(p2)); p2.setAxisLineStroke(new BasicStroke(1.1f)); assertTrue(p1.equals(p2)); } /** * Confirm that cloning works. */ public void testCloning() { SpiderWebPlot p1 = new SpiderWebPlot(new DefaultCategoryDataset()); Rectangle2D legendShape = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0); p1.setLegendItemShape(legendShape); SpiderWebPlot p2 = null; try { p2 = (SpiderWebPlot) p1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(p1 != p2); assertTrue(p1.getClass() == p2.getClass()); assertTrue(p1.equals(p2)); // change the legendItemShape legendShape.setRect(4.0, 3.0, 2.0, 1.0); assertFalse(p1.equals(p2)); p2.setLegendItemShape(legendShape); assertTrue(p1.equals(p2)); // change a series paint p1.setSeriesPaint(1, Color.black); assertFalse(p1.equals(p2)); p2.setSeriesPaint(1, Color.black); assertTrue(p1.equals(p2)); // change a series outline paint p1.setSeriesOutlinePaint(0, Color.red); assertFalse(p1.equals(p2)); p2.setSeriesOutlinePaint(0, Color.red); assertTrue(p1.equals(p2)); // change a series outline stroke p1.setSeriesOutlineStroke(0, new BasicStroke(1.1f)); assertFalse(p1.equals(p2)); p2.setSeriesOutlineStroke(0, new BasicStroke(1.1f)); assertTrue(p1.equals(p2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { SpiderWebPlot p1 = new SpiderWebPlot(new DefaultCategoryDataset()); SpiderWebPlot p2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(p1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); p2 = (SpiderWebPlot) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(p1, p2); } /** * Draws the chart with a null info object to make sure that no exceptions * are thrown. */ public void testDrawWithNullInfo() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(35.0, "S1", "C1"); dataset.addValue(45.0, "S1", "C2"); dataset.addValue(55.0, "S1", "C3"); dataset.addValue(15.0, "S1", "C4"); dataset.addValue(25.0, "S1", "C5"); SpiderWebPlot plot = new SpiderWebPlot(dataset); JFreeChart chart = new JFreeChart(plot); boolean success = false; try { BufferedImage image = new BufferedImage(200 , 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); success = true; } catch (Exception e) { success = false; } assertTrue(success); } }
ilyessou/jfreechart
tests/org/jfree/chart/plot/junit/SpiderWebPlotTests.java
Java
lgpl-2.1
12,593
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------- * CategoryStepRenderer.java * ------------------------- * * (C) Copyright 2004-2008, by Brian Cole and Contributors. * * Original Author: Brian Cole; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 21-Apr-2004 : Version 1, contributed by Brian Cole (DG); * 22-Apr-2004 : Fixed Checkstyle complaints (DG); * 05-Nov-2004 : Modified drawItem() signature (DG); * 08-Mar-2005 : Added equals() method (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 30-Nov-2006 : Added checks for series visibility (DG); * 22-Feb-2007 : Use new state object for reusable line, enable chart entities * (for tooltips, URLs), added new getLegendItem() override (DG); * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG); * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG); * 17-Jun-2008 : Apply legend shape, font and paint attributes (DG); * */ package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.renderer.xy.XYStepRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.util.PublicCloneable; /** * A "step" renderer similar to {@link XYStepRenderer} but * that can be used with the {@link CategoryPlot} class. The example shown * here is generated by the <code>CategoryStepChartDemo1.java</code> program * included in the JFreeChart Demo Collection: * <br><br> * <img src="../../../../../images/CategoryStepRendererSample.png" * alt="CategoryStepRendererSample.png" /> */ public class CategoryStepRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** * State information for the renderer. */ protected static class State extends CategoryItemRendererState { /** * A working line for re-use to avoid creating large numbers of * objects. */ public Line2D line; /** * Creates a new state instance. * * @param info collects plot rendering information (<code>null</code> * permitted). */ public State(PlotRenderingInfo info) { super(info); this.line = new Line2D.Double(); } } /** For serialization. */ private static final long serialVersionUID = -5121079703118261470L; /** The stagger width. */ public static final int STAGGER_WIDTH = 5; // could make this configurable /** * A flag that controls whether or not the steps for multiple series are * staggered. */ private boolean stagger = false; /** * Creates a new renderer (stagger defaults to <code>false</code>). */ public CategoryStepRenderer() { this(false); } /** * Creates a new renderer. * * @param stagger should the horizontal part of the step be staggered by * series? */ public CategoryStepRenderer(boolean stagger) { this.stagger = stagger; setBaseLegendShape(new Rectangle2D.Double(-4.0, -3.0, 8.0, 6.0)); } /** * Returns the flag that controls whether the series steps are staggered. * * @return A boolean. */ public boolean getStagger() { return this.stagger; } /** * Sets the flag that controls whether or not the series steps are * staggered and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param shouldStagger a boolean. */ public void setStagger(boolean shouldStagger) { this.stagger = shouldStagger; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { CategoryPlot p = getPlot(); if (p == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = p.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); LegendItem item = new LegendItem(label, description, toolTipText, urlText, shape, paint); item.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { item.setLabelPaint(labelPaint); } item.setSeriesKey(dataset.getRowKey(series)); item.setSeriesIndex(series); item.setDataset(dataset); item.setDatasetIndex(datasetIndex); return item; } /** * Creates a new state instance. This method is called from * {@link #initialise(Graphics2D, Rectangle2D, CategoryPlot, int, * PlotRenderingInfo)}, and we override it to ensure that the state * contains a working Line2D instance. * * @param info the plot rendering info (<code>null</code> is permitted). * * @return A new state instance. */ @Override protected CategoryItemRendererState createState(PlotRenderingInfo info) { return new State(info); } /** * Draws a line taking into account the specified orientation. * <p> * In version 1.0.5, the signature of this method was changed by the * addition of the 'state' parameter. This is an incompatible change, but * is considered a low risk because it is unlikely that anyone has * subclassed this renderer. If this *does* cause trouble for you, please * report it as a bug. * * @param g2 the graphics device. * @param state the renderer state. * @param orientation the plot orientation. * @param x0 the x-coordinate for the start of the line. * @param y0 the y-coordinate for the start of the line. * @param x1 the x-coordinate for the end of the line. * @param y1 the y-coordinate for the end of the line. */ protected void drawLine(Graphics2D g2, State state, PlotOrientation orientation, double x0, double y0, double x1, double y1) { if (orientation == PlotOrientation.VERTICAL) { state.line.setLine(x0, y0, x1, y1); g2.draw(state.line); } else if (orientation == PlotOrientation.HORIZONTAL) { state.line.setLine(y0, x0, y1, x1); // switch x and y g2.draw(state.line); } } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area in which the data is drawn. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible if (!getItemVisible(row, column)) { return; } Number value = dataset.getValue(row, column); if (value == null) { return; } PlotOrientation orientation = plot.getOrientation(); // current data point... double x1s = domainAxis.getCategoryStart(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x1 = domainAxis.getCategoryMiddle(column, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x1e = 2 * x1 - x1s; // or: x1s + 2*(x1-x1s) double y1 = rangeAxis.valueToJava2D(value.doubleValue(), dataArea, plot.getRangeAxisEdge()); g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); if (column != 0) { Number previousValue = dataset.getValue(row, column - 1); if (previousValue != null) { // previous data point... double previous = previousValue.doubleValue(); double x0s = domainAxis.getCategoryStart(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x0 = domainAxis.getCategoryMiddle(column - 1, getColumnCount(), dataArea, plot.getDomainAxisEdge()); double x0e = 2 * x0 - x0s; // or: x0s + 2*(x0-x0s) double y0 = rangeAxis.valueToJava2D(previous, dataArea, plot.getRangeAxisEdge()); if (getStagger()) { int xStagger = row * STAGGER_WIDTH; if (xStagger > (x1s - x0e)) { xStagger = (int) (x1s - x0e); } x1s = x0e + xStagger; } drawLine(g2, (State) state, orientation, x0e, y0, x1s, y0); // extend x0's flat bar drawLine(g2, (State) state, orientation, x1s, y0, x1s, y1); // upright bar } } drawLine(g2, (State) state, orientation, x1s, y1, x1e, y1); // x1's flat bar // draw the item labels if there are any... if (isItemLabelVisible(row, column)) { drawItemLabel(g2, orientation, dataset, row, column, x1, y1, (value.doubleValue() < 0.0)); } // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { Rectangle2D hotspot = new Rectangle2D.Double(); if (orientation == PlotOrientation.VERTICAL) { hotspot.setRect(x1s, y1, x1e - x1s, 4.0); } else { hotspot.setRect(y1 - 2.0, x1s, 4.0, x1e - x1s); } addItemEntity(entities, dataset, row, column, hotspot); } } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryStepRenderer)) { return false; } CategoryStepRenderer that = (CategoryStepRenderer) obj; if (this.stagger != that.stagger) { return false; } return super.equals(obj); } }
sternze/CurrentTopics_JFreeChart
source/org/jfree/chart/renderer/category/CategoryStepRenderer.java
Java
lgpl-2.1
13,685
// --------------------------------------------------------------------- // // Copyright (C) 2001 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include "../tests.h" #include <deal.II/base/quadrature_lib.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/vector.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/mapping_q1_eulerian.h> #include <deal.II/fe/fe_values.h> #include <vector> #include <fstream> #include <string> template<int dim> inline void show_values(FiniteElement<dim> &fe, const char *name) { deallog.push (name); Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 2., 5.); // shift one point of the cell // somehow if (dim > 1) tr.begin_active()->vertex(dim==2 ? 3 : 5)(dim-1) += 1./std::sqrt(2.); DoFHandler<dim> dof(tr); dof.distribute_dofs(fe); // construct the MappingQ1Eulerian // object FESystem<dim> mapping_fe(FE_Q<dim>(1), dim); DoFHandler<dim> flowfield_dof_handler(tr); flowfield_dof_handler.distribute_dofs(mapping_fe); Vector<double> map_points(flowfield_dof_handler.n_dofs()); MappingQ1Eulerian<dim> mapping(map_points, flowfield_dof_handler); QGauss<dim> quadrature_formula(2); FEValues<dim> fe_values(mapping, fe, quadrature_formula, UpdateFlags(update_values | update_JxW_values | update_gradients | update_second_derivatives)); typename DoFHandler<dim>::cell_iterator c = dof.begin(); fe_values.reinit(c); for (unsigned int k=0; k<quadrature_formula.size(); ++k) { deallog << quadrature_formula.point(k) << std::endl; deallog << "JxW: " << fe_values.JxW(k) << std::endl; for (unsigned int i=0; i<fe.dofs_per_cell; ++i) { deallog << "Values: " << fe_values.shape_value(i,k); deallog << ", Grad: " << fe_values.shape_grad(i,k); deallog << ", 2nd: " << fe_values.shape_hessian(i,k); deallog << std::endl; } } deallog.pop (); } template<int dim> void show_values() { FE_Q<dim> q1(1); show_values(q1, "Q1"); FE_Q<dim> q2(2); show_values(q2, "Q2"); } int main() { std::ofstream logfile ("output"); deallog << std::setprecision(2); deallog << std::fixed; deallog.attach(logfile); deallog.threshold_double(1.e-10); deallog.push ("1d"); show_values<1>(); deallog.pop (); deallog.push ("2d"); show_values<2>(); deallog.pop (); deallog.push ("3d"); show_values<3>(); deallog.pop (); return 0; }
jperryhouts/dealii
tests/mappings/mapping_q1_eulerian.cc
C++
lgpl-2.1
3,231
/*************************************************************************** * Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #include "Base/BoundBox.h" // inclusion of the generated files (generated out of BoundBoxPy.xml) #include "MatrixPy.h" #include "VectorPy.h" #include "GeometryPyCXX.h" #include "BoundBoxPy.h" #include "BoundBoxPy.cpp" using namespace Base; // returns a string which represent the object e.g. when printed in python std::string BoundBoxPy::representation(void) const { std::stringstream str; str << "BoundBox ("; str << getBoundBoxPtr()->MinX << ", " << getBoundBoxPtr()->MinY << ", " << getBoundBoxPtr()->MinZ << ", " << getBoundBoxPtr()->MaxX << ", " << getBoundBoxPtr()->MaxY << ", " << getBoundBoxPtr()->MaxZ ; str << ")"; return str.str(); } PyObject *BoundBoxPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper { // create a new instance of BoundBoxPy and the Twin object return new BoundBoxPy(new BoundBox3d); } // constructor method int BoundBoxPy::PyInit(PyObject* args, PyObject* /*kwd*/) { if (PyArg_ParseTuple(args, "")) { return 0; } PyErr_Clear(); // set by PyArg_ParseTuple() double xMin=0.0,yMin=0.0,zMin=0.0,xMax=0.0,yMax=0.0,zMax=0.0; PyObject *object1, *object2; BoundBoxPy::PointerType ptr = getBoundBoxPtr(); if (PyArg_ParseTuple(args, "d|ddddd", &xMin, &yMin, &zMin, &xMax, &yMax, &zMax)) { ptr->MaxX = xMax; ptr->MaxY = yMax; ptr->MaxZ = zMax; ptr->MinX = xMin; ptr->MinY = yMin; ptr->MinZ = zMin; return 0; } PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args,"O!O!",&PyTuple_Type, &object1, &PyTuple_Type, &object2)) { try { Vector3d v1 = getVectorFromTuple<double>(object1); Vector3d v2 = getVectorFromTuple<double>(object2); ptr->Add(v1); ptr->Add(v2); return 0; } catch (const Py::Exception&) { return -1; } } PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args,"O!O!",&(Base::VectorPy::Type), &object1, &(Base::VectorPy::Type), &object2)) { // Note: must be static_cast, not reinterpret_cast ptr->Add(*(static_cast<Base::VectorPy*>(object1)->getVectorPtr())); ptr->Add(*(static_cast<Base::VectorPy*>(object2)->getVectorPtr())); return 0; } PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object1)) { // Note: must be static_cast, not reinterpret_cast *ptr = *(static_cast<Base::BoundBoxPy*>(object1)->getBoundBoxPtr()); return 0; } PyErr_SetString(PyExc_TypeError, "Either six floats, two instances of " "Vector/Tuple or instance of BoundBox expected"); return -1; } PyObject* BoundBoxPy::setVoid(PyObject *args) { if (!PyArg_ParseTuple(args,"")) return 0; getBoundBoxPtr()->SetVoid(); Py_Return; } PyObject* BoundBoxPy::isValid(PyObject *args) { if (!PyArg_ParseTuple(args,"")) return 0; return PyBool_FromLong(getBoundBoxPtr()->IsValid() ? 1 : 0); } PyObject* BoundBoxPy::add(PyObject *args) { double x,y,z; PyObject *object; if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { getBoundBoxPtr()->Add(Vector3d(x,y,z)); Py_Return; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { getBoundBoxPtr()->Add(getVectorFromTuple<double>(object)); Py_Return; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { getBoundBoxPtr()->Add(*(static_cast<Base::VectorPy*>(object)->getVectorPtr())); Py_Return; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!;Need a Vector, BoundBox or three floats as argument",&(Base::BoundBoxPy::Type), &object)) { getBoundBoxPtr()->Add(*(static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr())); Py_Return; } PyErr_SetString(PyExc_TypeError, "Either three floats, instance of Vector or instance of BoundBox expected"); return 0; } PyObject* BoundBoxPy::getPoint(PyObject *args) { int index; if (!PyArg_ParseTuple(args,"i",&index)) return 0; if (index < 0 || index > 7) { PyErr_SetString (PyExc_IndexError, "Invalid bounding box"); return 0; } Base::Vector3d pnt = getBoundBoxPtr()->CalcPoint(index); return new Base::VectorPy(new Base::Vector3d(pnt)); } PyObject* BoundBoxPy::getEdge(PyObject *args) { int index; if (!PyArg_ParseTuple(args,"i",&index)) return 0; if (index < 0 || index > 11) { PyErr_SetString (PyExc_IndexError, "Invalid bounding box"); return 0; } Base::Vector3d pnt1, pnt2; getBoundBoxPtr()->CalcEdge(index, pnt1, pnt2); Py::Tuple tuple(2); tuple.setItem(0, Py::Vector(pnt1)); tuple.setItem(1, Py::Vector(pnt2)); return Py::new_reference_to(tuple); } PyObject* BoundBoxPy::closestPoint(PyObject *args) { double x,y,z; PyObject *object; Base::Vector3d vec; do { if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { vec = Vector3d(x,y,z); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { vec = getVectorFromTuple<double>(object); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { vec = *(static_cast<Base::VectorPy*>(object)->getVectorPtr()); break; } else { PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); return 0; } } while(false); Base::Vector3d point = getBoundBoxPtr()->ClosestPoint(vec); return new Base::VectorPy(new Base::Vector3d(point)); } PyObject* BoundBoxPy::intersect(PyObject *args) { PyObject *object,*object2; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); return 0; } do { if (PyArg_ParseTuple(args,"O!O!",&(Base::VectorPy::Type), &object, &(Base::VectorPy::Type), &object2)) { retVal = getBoundBoxPtr()->IsCutLine( *(static_cast<Base::VectorPy*>(object )->getVectorPtr()), *(static_cast<Base::VectorPy*>(object2)->getVectorPtr())); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) { if (!static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); return 0; } retVal = getBoundBoxPtr()->Intersect(*(static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr())); break; } PyErr_SetString(PyExc_TypeError, "Either BoundBox or two Vectors expected"); return 0; } while(false); return Py::new_reference_to(retVal); } PyObject* BoundBoxPy::intersected(PyObject *args) { if (!getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); return 0; } PyObject *object; if (!PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) return 0; if (!static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); return 0; } Base::BoundBox3d bbox = getBoundBoxPtr()->Intersected(*static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr()); return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); } PyObject* BoundBoxPy::united(PyObject *args) { if (!getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); return 0; } PyObject *object; if (!PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) return 0; if (!static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); return 0; } Base::BoundBox3d bbox = getBoundBoxPtr()->United(*static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr()); return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); } PyObject* BoundBoxPy::enlarge(PyObject *args) { double s; if (!PyArg_ParseTuple(args, "d;Need float parameter to enlarge", &s)) return 0; getBoundBoxPtr()->Enlarge(s); Py_Return; } PyObject* BoundBoxPy::getIntersectionPoint(PyObject *args) { PyObject *object,*object2; double epsilon=0.0001; if (PyArg_ParseTuple(args,"O!O!|d:Need base and direction vector", &(Base::VectorPy::Type), &object,&(Base::VectorPy::Type), &object2, &epsilon)) { Base::Vector3d point; bool ok = getBoundBoxPtr()->IntersectionPoint( *(static_cast<Base::VectorPy*>(object)->getVectorPtr()), *(static_cast<Base::VectorPy*>(object2)->getVectorPtr()), point, epsilon); if (ok) { return new VectorPy(point); } else { PyErr_SetString(Base::BaseExceptionFreeCADError, "No intersection"); return 0; } } else return 0; } PyObject* BoundBoxPy::move(PyObject *args) { double x,y,z; PyObject *object; Base::Vector3d vec; do { if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { vec = Vector3d(x,y,z); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!:Need vector to move",&PyTuple_Type, &object)) { vec = getVectorFromTuple<double>(object); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!:Need vector to move",&(Base::VectorPy::Type), &object)) { vec = *(static_cast<Base::VectorPy*>(object)->getVectorPtr()); break; } else { PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); return 0; } } while(false); getBoundBoxPtr()->MoveX(vec.x); getBoundBoxPtr()->MoveY(vec.y); getBoundBoxPtr()->MoveZ(vec.z); Py_Return; } PyObject* BoundBoxPy::scale(PyObject *args) { double x,y,z; PyObject *object; Base::Vector3d vec; do { if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { vec = Vector3d(x,y,z); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!:Need vector to scale",&PyTuple_Type, &object)) { vec = getVectorFromTuple<double>(object); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!:Need vector to scale",&(Base::VectorPy::Type), &object)) { vec = *(static_cast<Base::VectorPy*>(object)->getVectorPtr()); break; } else { PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); return 0; } } while(false); getBoundBoxPtr()->ScaleX(vec.x); getBoundBoxPtr()->ScaleY(vec.y); getBoundBoxPtr()->ScaleZ(vec.z); Py_Return; } PyObject* BoundBoxPy::transformed(PyObject *args) { PyObject *mat; if (!PyArg_ParseTuple(args,"O!", &(Base::MatrixPy::Type), &mat)) return 0; if (!getBoundBoxPtr()->IsValid()) throw Py::FloatingPointError("Cannot transform invalid bounding box"); Base::BoundBox3d bbox = getBoundBoxPtr()->Transformed(*static_cast<Base::MatrixPy*>(mat)->getMatrixPtr()); return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); } PyObject* BoundBoxPy::isCutPlane(PyObject *args) { PyObject *object,*object2; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); return 0; } if (PyArg_ParseTuple(args,"O!O!:Need base and normal vector of a plane", &(Base::VectorPy::Type), &object,&(Base::VectorPy::Type), &object2)) retVal = getBoundBoxPtr()->IsCutPlane( *(static_cast<Base::VectorPy*>(object)->getVectorPtr()), *(static_cast<Base::VectorPy*>(object2)->getVectorPtr())); else return 0; return Py::new_reference_to(retVal); } PyObject* BoundBoxPy::isInside(PyObject *args) { double x,y,z; PyObject *object; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box"); return 0; } do { if (PyArg_ParseTuple(args, "ddd", &x,&y,&z)) { retVal = getBoundBoxPtr()->IsInBox(Vector3d(x,y,z)); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&PyTuple_Type, &object)) { retVal = getBoundBoxPtr()->IsInBox(getVectorFromTuple<double>(object)); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { retVal = getBoundBoxPtr()->IsInBox(*(static_cast<Base::VectorPy*>(object)->getVectorPtr())); break; } PyErr_Clear(); if (PyArg_ParseTuple(args,"O!",&(Base::BoundBoxPy::Type), &object)) { if (!static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr()->IsValid()) { PyErr_SetString (PyExc_FloatingPointError, "Invalid bounding box argument"); return 0; } retVal = getBoundBoxPtr()->IsInBox(*(static_cast<Base::BoundBoxPy*>(object)->getBoundBoxPtr())); break; } PyErr_SetString(PyExc_TypeError, "Either three floats, Vector(s) or BoundBox expected"); return 0; } while(false); return Py::new_reference_to(retVal); } Py::Object BoundBoxPy::getCenter(void) const { return Py::Vector(getBoundBoxPtr()->GetCenter()); } Py::Float BoundBoxPy::getXMax(void) const { return Py::Float(getBoundBoxPtr()->MaxX); } void BoundBoxPy::setXMax(Py::Float arg) { getBoundBoxPtr()->MaxX = arg; } Py::Float BoundBoxPy::getYMax(void) const { return Py::Float(getBoundBoxPtr()->MaxY); } void BoundBoxPy::setYMax(Py::Float arg) { getBoundBoxPtr()->MaxY = arg; } Py::Float BoundBoxPy::getZMax(void) const { return Py::Float(getBoundBoxPtr()->MaxZ); } void BoundBoxPy::setZMax(Py::Float arg) { getBoundBoxPtr()->MaxZ = arg; } Py::Float BoundBoxPy::getXMin(void) const { return Py::Float(getBoundBoxPtr()->MinX); } void BoundBoxPy::setXMin(Py::Float arg) { getBoundBoxPtr()->MinX = arg; } Py::Float BoundBoxPy::getYMin(void) const { return Py::Float(getBoundBoxPtr()->MinY); } void BoundBoxPy::setYMin(Py::Float arg) { getBoundBoxPtr()->MinY = arg; } Py::Float BoundBoxPy::getZMin(void) const { return Py::Float(getBoundBoxPtr()->MinZ); } void BoundBoxPy::setZMin(Py::Float arg) { getBoundBoxPtr()->MinZ = arg; } Py::Float BoundBoxPy::getXLength(void) const { return Py::Float(getBoundBoxPtr()->LengthX()); } Py::Float BoundBoxPy::getYLength(void) const { return Py::Float(getBoundBoxPtr()->LengthY()); } Py::Float BoundBoxPy::getZLength(void) const { return Py::Float(getBoundBoxPtr()->LengthZ()); } Py::Float BoundBoxPy::getDiagonalLength(void) const { if (!getBoundBoxPtr()->IsValid()) throw Py::FloatingPointError("Cannot determine diagonal length of invalid bounding box"); return Py::Float(getBoundBoxPtr()->CalcDiagonalLength()); } PyObject *BoundBoxPy::getCustomAttributes(const char* /*attr*/) const { return 0; } int BoundBoxPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; }
sanguinariojoe/FreeCAD
src/Base/BoundBoxPyImp.cpp
C++
lgpl-2.1
18,177
description( "This test checks that iterating a large array backwards works correctly." ); var bytes = new Array(); function prepare(nbytes) { var i = nbytes - 1; while (i >= 0) { bytes[i] = new Number(i); i -= 1; } } function verify(nbytes) { var i = nbytes - 1; while (i >= 0) { if (bytes[i] != i) return false; i -= 1; } return true; } prepare(32768); shouldBeTrue('verify(32768)'); prepare(65536); shouldBeTrue('verify(65536)'); prepare(120000); shouldBeTrue('verify(120000)');
youfoh/webkit-efl
LayoutTests/fast/js/script-tests/array-iterate-backwards.js
JavaScript
lgpl-2.1
560
//////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports.avoidstarimport; import com.puppycrawl.tools.checkstyle.checks.imports.*; import java.io.*; import java.lang.*; import java.sql.Connection; import java.util.List; import java.util.List; import java.lang.AbstractMethodError; import java.util.Iterator; import java.util.Enumeration; import java.util.Arrays; import javax.swing.JToolBar; import javax.swing.JToggleButton; import javax.swing.ScrollPaneLayout; import javax.swing.BorderFactory; import static java.io.File.listRoots; import static javax.swing.WindowConstants.*; import static javax.swing.WindowConstants.*; import static java.io.File.createTempFile; import static java.io.File.*; import java.awt.Component; import java.awt.Graphics2D; import java.awt.HeadlessException; import java.awt.Label; import java.util.Date; import java.util.Calendar; import java.util.BitSet; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.CheckerTest; import com.puppycrawl.tools.checkstyle.Definitions; import com.puppycrawl.tools.checkstyle.ConfigurationLoaderTest; import com.puppycrawl.tools.checkstyle.PackageNamesLoader; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.DefaultLogger; /** * Test case for imports * Here's an import used only by javadoc: {@link Date}. * @author Oliver Burn * @author lkuehne * @author Michael Studman * @see Calendar Should avoid unused import for Calendar **/ class InputAvoidStarImportDefault { /** ignore **/ private Class mUse1 = Connection.class; /** ignore **/ private Class mUse2 = java.io.File.class; /** ignore **/ private Class mUse3 = Iterator[].class; /** ignore **/ private Class mUse4 = java.util.Enumeration[].class; /** usage of illegal import **/ private String ftpClient = null; /** usage via static method, both normal and fully qualified */ { int[] x = {}; Arrays.sort(x); Object obj = javax.swing.BorderFactory.createEmptyBorder(); File[] files = listRoots(); } /** usage of inner class as type */ private JToolBar.Separator mSep = null; /** usage of inner class in Constructor */ private Object mUse5 = new Object(); /** usage of inner class in constructor, fully qualified */ private Object mUse6 = new javax.swing.JToggleButton.ToggleButtonModel(); /** we use class name as member's name. * also an inline JavaDoc-only import {@link Vector linkText} */ private int Component; /** * method comment with JavaDoc-only import {@link BitSet#aMethod()} */ public void Label() {} /** * Renders to a {@linkplain Graphics2D graphics context}. * @throws HeadlessException if no graphis environment can be found. * @exception HeadlessException if no graphis environment can be found. */ public void render() {} /** * First is a class with a method with arguments {@link TestClass1#method1(TestClass2)}. * Next is a class with typed method {@link TestClass3#method2(TestClass4, TestClass5)}. * * @param param1 with a link {@link TestClass6} * @throws TestClass7 when broken * @deprecated in 1 for removal in 2. Use {@link TestClass8} */ public void aMethodWithManyLinks() {} }
jochenvdv/checkstyle
src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/avoidstarimport/InputAvoidStarImportDefault.java
Java
lgpl-2.1
3,561
//---------------------------- spherical_manifold_01.cc --------------------------- // Copyright (C) 2011 - 2015 by the mathLab team. // // This file is subject to LGPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- spherical_manifold_02.cc --------------------------- // Test that the flat manifold does what it should on a sphere. #include "../tests.h" #include <fstream> #include <deal.II/base/logstream.h> // all include files you need here #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/tria_boundary_lib.h> #include <deal.II/grid/manifold_lib.h> #include <deal.II/grid/grid_out.h> // Helper function template <int dim, int spacedim> void test(unsigned int ref=1) { SphericalManifold<dim,spacedim> manifold; Triangulation<dim,spacedim> tria; GridGenerator::hyper_ball (tria); typename Triangulation<dim,spacedim>::active_cell_iterator cell; for(cell = tria.begin_active(); cell != tria.end(); ++cell) cell->set_all_manifold_ids(1); for(cell = tria.begin_active(); cell != tria.end(); ++cell) { if(cell->center().distance(Point<spacedim>()) < 1e-10) cell->set_all_manifold_ids(0); } tria.set_manifold(1, manifold); tria.refine_global(2); GridOut gridout; gridout.write_msh(tria, deallog.get_file_stream()); } int main () { std::ofstream logfile("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); test<2,2>(); test<3,3>(); return 0; }
natashasharma/dealii
tests/manifold/spherical_manifold_02.cc
C++
lgpl-2.1
1,788
/* * Copyright (C) 2005-2013 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.web.auth; import org.apache.commons.codec.digest.DigestUtils; /** * {@link WebCredentials} holding username and the md5 hash of the password. * * @author Alex Miller */ public class BasicAuthCredentials implements WebCredentials { private static final long serialVersionUID = 2626445241420904072L; private String userName; private String password; /** * Default constructor */ public BasicAuthCredentials(String userName, String password) { this.userName = userName; this.password = DigestUtils.md5Hex(password); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.password == null) ? 0 : this.password.hashCode()); result = prime * result + ((this.userName == null) ? 0 : this.userName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BasicAuthCredentials other = (BasicAuthCredentials) obj; if (this.password == null) { if (other.password != null) { return false; } } else if (!this.password.equals(other.password)) { return false; } if (this.userName == null) { if (other.userName != null) { return false; } } else if (!this.userName.equals(other.userName)) { return false; } return true; } }
Tybion/community-edition
projects/remote-api/source/java/org/alfresco/repo/web/auth/BasicAuthCredentials.java
Java
lgpl-3.0
2,349
/* * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ImageDocument_h #define ImageDocument_h #include "HTMLDocument.h" namespace WebCore { class CachedImage; class ImageDocumentElement; class ImageDocument : public HTMLDocument { public: static PassRefPtr<ImageDocument> create(Frame* frame, const KURL& url) { return adoptRef(new ImageDocument(frame, url)); } CachedImage* cachedImage(); ImageDocumentElement* imageElement() const { return m_imageElement; } void disconnectImageElement() { m_imageElement = 0; } void windowSizeChanged(); void imageUpdated(); void imageClicked(int x, int y); private: ImageDocument(Frame*, const KURL&); virtual PassRefPtr<DocumentParser> createParser(); virtual bool isImageDocument() const { return true; } void createDocumentStructure(); void resizeImageToFit(); void restoreImageSize(); bool imageFitsInWindow() const; bool shouldShrinkToFit() const; float scale() const; ImageDocumentElement* m_imageElement; // Whether enough of the image has been loaded to determine its size bool m_imageSizeIsKnown; // Whether the image is shrunk to fit or not bool m_didShrinkImage; // Whether the image should be shrunk or not bool m_shouldShrinkImage; }; } #endif // ImageDocument_h
nawawi/wkhtmltopdf
webkit/Source/WebCore/html/ImageDocument.h
C
lgpl-3.0
2,619
'use strict'; var ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = { entry: { 'index': './index.styl', 'index-no-normalize': './style/index.styl' }, output: { filename: 'index.css' }, module: { loaders: [ { test: /\.styl$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!stylus-loader') } ] }, plugins: [ new ExtractTextPlugin('[name].css') ] }
odedgol/trackingUi
node_modules/react-input-field/build-style.config.js
JavaScript
unlicense
524
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Diagnostics.Telemetry { /// <summary> /// Contains the counts of registered actions for an analyzer. /// </summary> internal class AnalyzerActionCounts { internal static AnalyzerActionCounts Empty = new AnalyzerActionCounts(AnalyzerActions.Empty); internal static AnalyzerActionCounts Create(AnalyzerActions analyzerActions) { if (analyzerActions == null) { return Empty; } return new AnalyzerActionCounts(analyzerActions); } private AnalyzerActionCounts(AnalyzerActions analyzerActions) { CompilationStartActionsCount = analyzerActions.CompilationStartActionsCount; CompilationEndActionsCount = analyzerActions.CompilationEndActionsCount; CompilationActionsCount = analyzerActions.CompilationActionsCount; SyntaxTreeActionsCount = analyzerActions.SyntaxTreeActionsCount; SemanticModelActionsCount = analyzerActions.SemanticModelActionsCount; SymbolActionsCount = analyzerActions.SymbolActionsCount; SyntaxNodeActionsCount = analyzerActions.SyntaxNodeActionsCount; CodeBlockStartActionsCount = analyzerActions.CodeBlockStartActionsCount; CodeBlockEndActionsCount = analyzerActions.CodeBlockEndActionsCount; CodeBlockActionsCount = analyzerActions.CodeBlockActionsCount; } /// <summary> /// Count of registered compilation start actions. /// </summary> public int CompilationStartActionsCount { get; } /// <summary> /// Count of registered compilation end actions. /// </summary> public int CompilationEndActionsCount { get; } /// <summary> /// Count of registered compilation actions. /// </summary> public int CompilationActionsCount { get; } /// <summary> /// Count of registered syntax tree actions. /// </summary> public int SyntaxTreeActionsCount { get; } /// <summary> /// Count of registered semantic model actions. /// </summary> public int SemanticModelActionsCount { get; } /// <summary> /// Count of registered symbol actions. /// </summary> public int SymbolActionsCount { get; } /// <summary> /// Count of registered syntax node actions. /// </summary> public int SyntaxNodeActionsCount { get; } /// <summary> /// Count of code block start actions. /// </summary> public int CodeBlockStartActionsCount { get; } /// <summary> /// Count of code block end actions. /// </summary> public int CodeBlockEndActionsCount { get; } /// <summary> /// Count of code block actions. /// </summary> public int CodeBlockActionsCount { get; } } }
VPashkov/roslyn
src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerActionCounts.cs
C#
apache-2.0
3,138
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.spatial; import org.apache.lucene.util.LuceneTestCase; import org.elasticsearch.license.License; import org.elasticsearch.license.TestUtils; import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.test.VersionUtils; /** * This class overrides the {@link SpatialPlugin} in order * to provide the integration test clusters a hook into a real * {@link XPackLicenseState}. In the cases that this is used, the * actual license's operation mode is not important */ public class LocalStateSpatialPlugin extends SpatialPlugin { protected XPackLicenseState getLicenseState() { TestUtils.UpdatableLicenseState licenseState = new TestUtils.UpdatableLicenseState(); License.OperationMode operationMode = License.OperationMode.TRIAL; licenseState.update(operationMode, true, Long.MAX_VALUE, VersionUtils.randomVersion(LuceneTestCase.random())); return licenseState; } }
robin13/elasticsearch
x-pack/plugin/spatial/src/test/java/org/elasticsearch/xpack/spatial/LocalStateSpatialPlugin.java
Java
apache-2.0
1,211
<?php abstract class PhabricatorEditEngineSettingsPanel extends PhabricatorSettingsPanel { final public function processRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $user = $this->getUser(); if ($user && ($user->getPHID() === $viewer->getPHID())) { $is_self = true; } else { $is_self = false; } if ($user && $user->getPHID()) { $profile_uri = '/people/manage/'.$user->getID().'/'; } else { $profile_uri = null; } $engine = id(new PhabricatorSettingsEditEngine()) ->setController($this->getController()) ->setNavigation($this->getNavigation()) ->setHideHeader(true) ->setIsSelfEdit($is_self) ->setProfileURI($profile_uri); $preferences = $this->getPreferences(); $engine->setTargetObject($preferences); return $engine->buildResponse(); } final public function isEnabled() { // Only enable the panel if it has any fields. $field_keys = $this->getPanelSettingsKeys(); return (bool)$field_keys; } final public function newEditEnginePage() { $field_keys = $this->getPanelSettingsKeys(); if (!$field_keys) { return null; } $key = $this->getPanelKey(); $label = $this->getPanelName(); $panel_uri = $this->getPanelURI(); return id(new PhabricatorEditPage()) ->setKey($key) ->setLabel($label) ->setViewURI($panel_uri) ->setFieldKeys($field_keys); } final public function getPanelSettingsKeys() { $viewer = $this->getViewer(); $settings = PhabricatorSetting::getAllEnabledSettings($viewer); $this_key = $this->getPanelKey(); $panel_settings = array(); foreach ($settings as $setting) { if ($setting->getSettingPanelKey() == $this_key) { $panel_settings[] = $setting; } } return mpull($panel_settings, 'getSettingKey'); } }
dannysu/phabricator
src/applications/settings/panel/PhabricatorEditEngineSettingsPanel.php
PHP
apache-2.0
1,888
#include <ctype.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <confd.h> #include "linuxcfg_api.h" #include "utils.h" void find_process_ids(inode_pid_pair_t * pairs, int size) { char name[1024]; DIR *dir; struct dirent *d; int pid = 0; int cnt = 0; unsigned inode; int i; if ((dir = opendir("/proc")) == NULL) return; while ((d = readdir(dir)) != NULL && cnt < size) { DIR *dir1; struct dirent *d1; int pos; char crap; if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1) continue; pos = sprintf(name, "/proc/%d/fd/", pid); if ((dir1 = opendir(name)) == NULL) continue; while ((d1 = readdir(dir1)) != NULL && cnt < size) { int fd, n; char lnk[64]; if (sscanf(d1->d_name, "%d", &fd) != 1) continue; sprintf(name + pos, "%d", fd); n = readlink(name, lnk, sizeof(lnk) - 1); if (n + 1 < sizeof(lnk)) { lnk[n] = 0; if (sscanf(lnk, "socket:[%u]", &inode) != 1) continue; for (i = 0; i < size; i++) { if (pairs[i].inode == inode) { cnt++; pairs[i].process_id = pid; break; } } } } closedir(dir1); } closedir(dir); } /** * Some address strings contain addresses in network byte order, some * do not. If conv_hton is true, the address is assumed in host byte * order and converted to network byte order. */ ssize_t _scanaddr(inet_address_t * addr, const char *src, uint32_t type, int conv_hton) { struct in_addr addr4; struct in6_addr addr6; void *ptr; int len; if (type == INET(ipv4)) { sscanf(src, "%x", &addr4.s_addr); if (conv_hton) addr4.s_addr = ntohl(addr4.s_addr); ptr = &addr4.s_addr; len = sizeof(addr4.s_addr); } else { sscanf(src, "%8x%8x%8x%8x", addr6.s6_addr32, addr6.s6_addr32 + 1, addr6.s6_addr32 + 2, addr6.s6_addr32 + 3); if (conv_hton) { int i; for (i = 0; i < 4; i++) addr6.s6_addr32[i] = ntohl(addr6.s6_addr32[i]); } ptr = &addr6.s6_addr32; len = sizeof(addr6.s6_addr32); } if (len <= ADDRLEN) { memcpy(addr->address, ptr, len); addr->addr_len = len; return len; } else return -1; } ssize_t scanaddr_nbo(inet_address_t * addr, const char *src, uint32_t type) { return _scanaddr(addr, src, type, 1); } ssize_t scanaddr(inet_address_t * addr, const char *src, uint32_t type) { return _scanaddr(addr, src, type, 0); } ssize_t scan_addr_port(inet_address_t * addr, uint32_t * port, const char *src, uint32_t type) { ssize_t len = 0; char *p = strchr(src, ':'); if (p != NULL && (len = scanaddr(addr, src, type)) >= 0) sscanf(p + 1, "%x", port); return len; } char *get_net_snmp_line(char *buf, size_t len, const char *proto) { FILE *fp; char pproto[256], *pptr = NULL; int plen; plen = sprintf(pproto, "%s:", proto); if ((fp = fopen("/proc/net/snmp", "r")) == NULL) { error("could not open /proc/net/snmp: %s", strerror(errno)); return NULL; } while (fgets(buf, len, fp) != NULL) { if (strncmp(buf, pproto, plen) == 0) { if (fgets(buf, len, fp) != NULL && strncmp(buf, pproto, plen) == 0) { pptr = buf + plen + 1; break; } } } fclose(fp); return pptr; } int get_ioctl_socket() { static int fd = -1; if (fd < 0) fd = socket(AF_INET, SOCK_STREAM, 0); return fd; } static int netlink_sd = -1; static uint8_t rcvbuf[32768]; static uint8_t sndbuf[512]; int get_netlink_sd() { if (netlink_sd >= 0) return netlink_sd; int sd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (sd < 0) { error("\n%s - Failed socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE): " "err \"%s\"\n", __FUNCTION__, strerror(errno)); return -1; } int rcvbuf_size = sizeof(rcvbuf); if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, &rcvbuf_size, sizeof(rcvbuf_size)) < 0) { error("\n%s - Failed setsockopt(... , SOL_SOCKET, SO_RCVBUF, ...) : " "err \"%s\"\n", __FUNCTION__, strerror(errno)); return -1; } return (netlink_sd = sd); } int netlink_process(int nlmsg_type, int (*process) (struct nlmsghdr * nlmsghdr_p, void *arg), void *arg) { struct sockaddr_nl addr; struct nlmsghdr *nl_hdr; struct rtmsg *rt_hdr; int nlmsg_done = 0; int sd = get_netlink_sd(); memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; memset(sndbuf, 0, sizeof(sndbuf)); nl_hdr = (struct nlmsghdr *) sndbuf; nl_hdr->nlmsg_type = nlmsg_type; nl_hdr->nlmsg_pid = getpid(); nl_hdr->nlmsg_seq = 0; nl_hdr->nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; nl_hdr->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); rt_hdr = (struct rtmsg *) NLMSG_DATA(nl_hdr); rt_hdr->rtm_table = RT_TABLE_MAIN; if (sendto (sd, sndbuf, nl_hdr->nlmsg_len, 0, (struct sockaddr *) &addr, sizeof(struct sockaddr_nl)) < 0) { error("\n%s - Failed sendto() : err \"%s\"\n", __FUNCTION__, strerror(errno)); return -1; } do { int rcv_cnt; struct nlmsghdr *nlmsghdr_p; struct rtmsg *rtmsg_p; socklen_t sock_len; memset(rcvbuf, 0, sizeof(rcvbuf)); sock_len = sizeof(struct sockaddr_nl); rcv_cnt = recvfrom(sd, rcvbuf, sizeof(rcvbuf), 0, (struct sockaddr *) &addr, &sock_len); if (rcv_cnt < 0) { error("\n%s - Failed recvfrom() : err \"%s\"\n", __FUNCTION__, strerror(errno)); break; } nlmsghdr_p = (struct nlmsghdr *) rcvbuf; while (NLMSG_OK(nlmsghdr_p, rcv_cnt)) { if (nlmsghdr_p->nlmsg_type == NLMSG_ERROR) { error("\n%s - netling message error\n", __FUNCTION__); return -1; } if (nlmsghdr_p->nlmsg_type & NLMSG_DONE) { nlmsg_done = 1; break; } rtmsg_p = NLMSG_DATA(nlmsghdr_p); if (rtmsg_p->rtm_dst_len != 0) { nlmsghdr_p = NLMSG_NEXT(nlmsghdr_p, rcv_cnt); continue; } process(nlmsghdr_p, arg); nlmsghdr_p = NLMSG_NEXT(nlmsghdr_p, rcv_cnt); } // while NLMSG_OK } while (!nlmsg_done); return 0; } // Parsing utilities int get_uint_dec(char **pos, unsigned int *value) { char chr = **pos; uint64_t val; if (!chr) return -1; while (!isdigit((unsigned char) chr)) { (*pos)++; chr = **pos; if (!chr) return -1; } val = (uint64_t) chr - '0'; (*pos)++; chr = **pos; while (isdigit((unsigned char) chr)) { val *= 10; val += (uint64_t) chr - '0'; (*pos)++; chr = **pos; } *value = val; return 0; } int get_uint64_dec(char **pos, uint64_t * value) { char chr = **pos; uint64_t val; *value = 0; if (!chr) return -1; while (!isdigit((unsigned char) chr)) { (*pos)++; chr = **pos; if (!chr) return -1; } val = (uint64_t) chr - '0'; (*pos)++; chr = **pos; while (isdigit((unsigned char) chr)) { val *= 10; val += (uint64_t) chr - '0'; (*pos)++; chr = **pos; } *value = val; return 0; } int get_name(char **pos, char *name) { int i = 0; char chr = **pos; name[0] = '\0'; if (!chr) return -1; while (chr && !isalnum((unsigned char) chr) && (chr != '_')) { (*pos)++; chr = **pos; } if (!chr) return -1; name[i++] = chr; (*pos)++; chr = **pos; while (isalnum((unsigned char) chr) || (chr == '_')) { name[i++] = chr; (*pos)++; chr = **pos; } name[i] = '\0'; return 0; } int get_uint_hex(char **pos, unsigned int *value) { char chr = **pos; if (!chr) return -1; while (!isxdigit((unsigned char) chr)) { if (!chr) return -1; (*pos)++; chr = **pos; if (!chr) return -1; } *value = hex_val(chr); (*pos)++; chr = **pos; while (isxdigit((unsigned char) chr)) { *value *= 16; *value += hex_val(chr); (*pos)++; chr = **pos; } return 0; } int get_byte_field_hex(char **pos, uint8_t * field, int max_size) { char chr = **pos; uint8_t *field_pos = field; int i = 0; if (!chr) return -1; while (!isxdigit((unsigned char) chr)) { if (!chr) return -1; (*pos)++; chr = **pos; if (!chr) return 0; } while (isxdigit((unsigned char) chr)) { if (i & 1) { *field_pos |= hex_val(chr); field_pos += 1; } else { if (field_pos >= (field + max_size)) { return -1; } *field_pos = hex_val(chr) << 4; } i++; (*pos)++; chr = **pos; } if (i & 1) { while (field_pos >= field) { *field_pos >>= 4; if (field_pos == field) { break; } *field_pos |= *(field_pos - 1) << 4; field_pos -= 1; } } return i; } int get_int_dec(char **pos, int *value) { char chr = **pos; char chr_last = 0; if (!chr) return -1; while (!isdigit((unsigned char) chr)) { (*pos)++; chr_last = chr; chr = **pos; if (!chr) return -1; } *value = chr - '0'; (*pos)++; chr = **pos; while (isdigit((unsigned char) chr)) { *value *= 10; *value += chr - '0'; (*pos)++; chr = **pos; } if (chr_last == '-') { *value *= -1; } return 0; } int _get_ip_addr_hex(char **pos, inet_address_t * addr, int *addr_type, int *is_zero, int reorder) { char str[128]; char chr; int i = 0; if (!pos || !addr) return -1; if (!(chr = **pos)) return -1; memset(str, 0, sizeof(str)); addr->addr_len = 0; *is_zero = 1; char *cc = NULL; while (!isxdigit((unsigned char) chr)) { (*pos)++; if (!(chr = **pos)) return -1; } while (isxdigit((unsigned char) chr)) { if (i < 127) str[i++] = chr; if (chr != '0') *is_zero = 0; (*pos)++; chr = **pos; } if (strlen(str) > 8) { struct in6_addr src; *addr_type = INET(ipv6); sscanf(str, "%8x%8x%8x%8x", src.s6_addr32, src.s6_addr32 + 1, src.s6_addr32 + 2, src.s6_addr32 + 3); if (reorder) { src.s6_addr32[0] = ntohl(src.s6_addr32[0]); src.s6_addr32[1] = ntohl(src.s6_addr32[1]); src.s6_addr32[2] = ntohl(src.s6_addr32[2]); src.s6_addr32[3] = ntohl(src.s6_addr32[3]); } addr->addr_len = sizeof(src.s6_addr32); cc = memcpy(addr->address, src.s6_addr32, addr->addr_len); } else { struct in_addr src; *addr_type = INET(ipv4); sscanf(str, "%X", &src.s_addr); addr->addr_len = sizeof(src.s_addr); cc = memcpy(addr->address, &src.s_addr, addr->addr_len); } if (!cc) { error("\n%s - Failed sinet_ntop(...); : err \"%s\"", __FUNCTION__, strerror(errno)); } return 0; } int get_ip_addr_hex(char **pos, inet_address_t * addr, int *addr_type, int *is_zero) { return _get_ip_addr_hex(pos, addr, addr_type, is_zero, 0); } int get_ip_addr_hex_h(char **pos, inet_address_t * addr, int *addr_type, int *is_zero) { return _get_ip_addr_hex(pos, addr, addr_type, is_zero, 1); } int empty_line(char *line) { int i; if (!line) return 1; for (i = 0; i < strlen(line); i++) { if (!isspace(line[i])) return 0; } return 1; } int hex_val(char chr) { int val = chr - '0'; if ((val >= 0) && (val < 10)) return val; val = chr - 'A'; if ((val >= 0) && (val < 6)) return val + 10; val = chr - 'a'; if ((val >= 0) && (val < 6)) return val + 10; return -1; }
kimjinyong/i2nsf-framework
Hackathon-111/SecurityController/confd-6.6/examples.confd/linuxcfg/ipmibs/utils.c
C
apache-2.0
12,990
var NAME = "InvalidDerefInputError"; var MESSAGE = "Deref can only be used with a non-primitive object from get, set, or call."; /** * An invalid deref input is when deref is used with input that is not generated * from a get, set, or a call. * * @param {String} message * @private */ function InvalidDerefInputError() { this.message = MESSAGE; this.stack = (new Error()).stack; } // instanceof will be an error, but stack will be correct because its defined in the constructor. InvalidDerefInputError.prototype = new Error(); InvalidDerefInputError.prototype.name = NAME; InvalidDerefInputError.name = NAME; InvalidDerefInputError.message = MESSAGE; module.exports = InvalidDerefInputError;
darioajr/falcor
lib/errors/InvalidDerefInputError.js
JavaScript
apache-2.0
708
/* * IzPack - Copyright 2001-2012 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.api.installer; /** * Display the requirement message * * @deprecated see {@link RequirementChecker}. */ @Deprecated public interface InstallerRequirementDisplay { void showMissingRequirementMessage(String message); }
codehaus/izpack
izpack-api/src/main/java/com/izforge/izpack/api/installer/InstallerRequirementDisplay.java
Java
apache-2.0
943
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Source listing for Daytime.3</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../tutdaytime3.html" title="Daytime.3 - An asynchronous TCP daytime server"> <link rel="prev" href="../tutdaytime3.html" title="Daytime.3 - An asynchronous TCP daytime server"> <link rel="next" href="../tutdaytime4.html" title="Daytime.4 - A synchronous UDP daytime client"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../tutdaytime3.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../tutdaytime3.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../tutdaytime4.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.tutorial.tutdaytime3.src"></a><a class="link" href="src.html" title="Source listing for Daytime.3">Source listing for Daytime.3</a> </h4></div></div></div> <pre class="programlisting"><span class="comment">//</span> <span class="comment">// server.cpp</span> <span class="comment">// ~~~~~~~~~~</span> <span class="comment">//</span> <span class="comment">// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)</span> <span class="comment">//</span> <span class="comment">// Distributed under the Boost Software License, Version 1.0. (See accompanying</span> <span class="comment">// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)</span> <span class="comment">//</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">ctime</span><span class="special">&gt;</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">iostream</span><span class="special">&gt;</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">string</span><span class="special">&gt;</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">bind</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">shared_ptr</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">enable_shared_from_this</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="special">#</span><span class="identifier">include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">asio</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="keyword">using</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">ip</span><span class="special">::</span><span class="identifier">tcp</span><span class="special">;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="identifier">make_daytime_string</span><span class="special">()</span> <span class="special">{</span> <span class="keyword">using</span> <span class="keyword">namespace</span> <span class="identifier">std</span><span class="special">;</span> <span class="comment">// For time_t, time and ctime;</span> <span class="identifier">time_t</span> <span class="identifier">now</span> <span class="special">=</span> <span class="identifier">time</span><span class="special">(</span><span class="number">0</span><span class="special">);</span> <span class="keyword">return</span> <span class="identifier">ctime</span><span class="special">(&amp;</span><span class="identifier">now</span><span class="special">);</span> <span class="special">}</span> <span class="keyword">class</span> <span class="identifier">tcp_connection</span> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">enable_shared_from_this</span><span class="special">&lt;</span><span class="identifier">tcp_connection</span><span class="special">&gt;</span> <span class="special">{</span> <span class="keyword">public</span><span class="special">:</span> <span class="keyword">typedef</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">shared_ptr</span><span class="special">&lt;</span><span class="identifier">tcp_connection</span><span class="special">&gt;</span> <span class="identifier">pointer</span><span class="special">;</span> <span class="keyword">static</span> <span class="identifier">pointer</span> <span class="identifier">create</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span><span class="special">&amp;</span> <span class="identifier">io_service</span><span class="special">)</span> <span class="special">{</span> <span class="keyword">return</span> <span class="identifier">pointer</span><span class="special">(</span><span class="keyword">new</span> <span class="identifier">tcp_connection</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">));</span> <span class="special">}</span> <span class="identifier">tcp</span><span class="special">::</span><span class="identifier">socket</span><span class="special">&amp;</span> <span class="identifier">socket</span><span class="special">()</span> <span class="special">{</span> <span class="keyword">return</span> <span class="identifier">socket_</span><span class="special">;</span> <span class="special">}</span> <span class="keyword">void</span> <span class="identifier">start</span><span class="special">()</span> <span class="special">{</span> <span class="identifier">message_</span> <span class="special">=</span> <span class="identifier">make_daytime_string</span><span class="special">();</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">async_write</span><span class="special">(</span><span class="identifier">socket_</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">buffer</span><span class="special">(</span><span class="identifier">message_</span><span class="special">),</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">bind</span><span class="special">(&amp;</span><span class="identifier">tcp_connection</span><span class="special">::</span><span class="identifier">handle_write</span><span class="special">,</span> <span class="identifier">shared_from_this</span><span class="special">(),</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">placeholders</span><span class="special">::</span><span class="identifier">error</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">placeholders</span><span class="special">::</span><span class="identifier">bytes_transferred</span><span class="special">));</span> <span class="special">}</span> <span class="keyword">private</span><span class="special">:</span> <span class="identifier">tcp_connection</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span><span class="special">&amp;</span> <span class="identifier">io_service</span><span class="special">)</span> <span class="special">:</span> <span class="identifier">socket_</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">)</span> <span class="special">{</span> <span class="special">}</span> <span class="keyword">void</span> <span class="identifier">handle_write</span><span class="special">(</span><span class="keyword">const</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span><span class="special">&amp;</span> <span class="comment">/*error*/</span><span class="special">,</span> <span class="identifier">size_t</span> <span class="comment">/*bytes_transferred*/</span><span class="special">)</span> <span class="special">{</span> <span class="special">}</span> <span class="identifier">tcp</span><span class="special">::</span><span class="identifier">socket</span> <span class="identifier">socket_</span><span class="special">;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> <span class="identifier">message_</span><span class="special">;</span> <span class="special">};</span> <span class="keyword">class</span> <span class="identifier">tcp_server</span> <span class="special">{</span> <span class="keyword">public</span><span class="special">:</span> <span class="identifier">tcp_server</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span><span class="special">&amp;</span> <span class="identifier">io_service</span><span class="special">)</span> <span class="special">:</span> <span class="identifier">acceptor_</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">,</span> <span class="identifier">tcp</span><span class="special">::</span><span class="identifier">endpoint</span><span class="special">(</span><span class="identifier">tcp</span><span class="special">::</span><span class="identifier">v4</span><span class="special">(),</span> <span class="number">13</span><span class="special">))</span> <span class="special">{</span> <span class="identifier">start_accept</span><span class="special">();</span> <span class="special">}</span> <span class="keyword">private</span><span class="special">:</span> <span class="keyword">void</span> <span class="identifier">start_accept</span><span class="special">()</span> <span class="special">{</span> <span class="identifier">tcp_connection</span><span class="special">::</span><span class="identifier">pointer</span> <span class="identifier">new_connection</span> <span class="special">=</span> <span class="identifier">tcp_connection</span><span class="special">::</span><span class="identifier">create</span><span class="special">(</span><span class="identifier">acceptor_</span><span class="special">.</span><span class="identifier">get_io_service</span><span class="special">());</span> <span class="identifier">acceptor_</span><span class="special">.</span><span class="identifier">async_accept</span><span class="special">(</span><span class="identifier">new_connection</span><span class="special">-&gt;</span><span class="identifier">socket</span><span class="special">(),</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">bind</span><span class="special">(&amp;</span><span class="identifier">tcp_server</span><span class="special">::</span><span class="identifier">handle_accept</span><span class="special">,</span> <span class="keyword">this</span><span class="special">,</span> <span class="identifier">new_connection</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">placeholders</span><span class="special">::</span><span class="identifier">error</span><span class="special">));</span> <span class="special">}</span> <span class="keyword">void</span> <span class="identifier">handle_accept</span><span class="special">(</span><span class="identifier">tcp_connection</span><span class="special">::</span><span class="identifier">pointer</span> <span class="identifier">new_connection</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span><span class="special">&amp;</span> <span class="identifier">error</span><span class="special">)</span> <span class="special">{</span> <span class="keyword">if</span> <span class="special">(!</span><span class="identifier">error</span><span class="special">)</span> <span class="special">{</span> <span class="identifier">new_connection</span><span class="special">-&gt;</span><span class="identifier">start</span><span class="special">();</span> <span class="special">}</span> <span class="identifier">start_accept</span><span class="special">();</span> <span class="special">}</span> <span class="identifier">tcp</span><span class="special">::</span><span class="identifier">acceptor</span> <span class="identifier">acceptor_</span><span class="special">;</span> <span class="special">};</span> <span class="keyword">int</span> <span class="identifier">main</span><span class="special">()</span> <span class="special">{</span> <span class="keyword">try</span> <span class="special">{</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span> <span class="identifier">io_service</span><span class="special">;</span> <span class="identifier">tcp_server</span> <span class="identifier">server</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">);</span> <span class="identifier">io_service</span><span class="special">.</span><span class="identifier">run</span><span class="special">();</span> <span class="special">}</span> <span class="keyword">catch</span> <span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">exception</span><span class="special">&amp;</span> <span class="identifier">e</span><span class="special">)</span> <span class="special">{</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">cerr</span> <span class="special">&lt;&lt;</span> <span class="identifier">e</span><span class="special">.</span><span class="identifier">what</span><span class="special">()</span> <span class="special">&lt;&lt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">endl</span><span class="special">;</span> <span class="special">}</span> <span class="keyword">return</span> <span class="number">0</span><span class="special">;</span> <span class="special">}</span> </pre> <p> Return to <a class="link" href="../tutdaytime3.html" title="Daytime.3 - An asynchronous TCP daytime server">Daytime.3 - An asynchronous TCP daytime server</a> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2013 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../tutdaytime3.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../tutdaytime3.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../tutdaytime4.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
NixaSoftware/CVis
venv/bin/doc/html/boost_asio/tutorial/tutdaytime3/src.html
HTML
apache-2.0
18,297
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.PageBuilder; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.SortOrder; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.gen.JoinCompiler; import com.facebook.presto.sql.gen.OrderingCompiler; import com.google.common.collect.ImmutableList; import io.airlift.log.Logger; import io.airlift.slice.Slice; import io.airlift.units.DataSize; import it.unimi.dsi.fastutil.Swapper; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.List; import java.util.Optional; import static com.facebook.presto.operator.SyntheticAddress.decodePosition; import static com.facebook.presto.operator.SyntheticAddress.decodeSliceIndex; import static com.facebook.presto.operator.SyntheticAddress.encodeSyntheticAddress; import static com.facebook.presto.sql.gen.JoinCompiler.LookupSourceFactory; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.google.common.base.MoreObjects.toStringHelper; import static io.airlift.slice.SizeOf.sizeOf; import static io.airlift.units.DataSize.Unit.BYTE; import static java.util.Objects.requireNonNull; /** * PagesIndex a low-level data structure which contains the address of every value position of every channel. * This data structure is not general purpose and is designed for a few specific uses: * <ul> * <li>Sort via the {@link #sort} method</li> * <li>Hash build via the {@link #createLookupSource} method</li> * <li>Positional output via the {@link #appendTo} method</li> * </ul> */ public class PagesIndex implements Swapper { private static final Logger log = Logger.get(PagesIndex.class); // todo this should be a services assigned in the constructor private static final OrderingCompiler orderingCompiler = new OrderingCompiler(); // todo this should be a services assigned in the constructor private static final JoinCompiler joinCompiler = new JoinCompiler(); private final List<Type> types; private final LongArrayList valueAddresses; private final ObjectArrayList<Block>[] channels; private int nextBlockToCompact; private int positionCount; private long pagesMemorySize; private long estimatedSize; public PagesIndex(List<Type> types, int expectedPositions) { this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); this.valueAddresses = new LongArrayList(expectedPositions); //noinspection rawtypes channels = (ObjectArrayList<Block>[]) new ObjectArrayList[types.size()]; for (int i = 0; i < channels.length; i++) { channels[i] = ObjectArrayList.wrap(new Block[1024], 0); } } public List<Type> getTypes() { return types; } public int getPositionCount() { return positionCount; } public LongArrayList getValueAddresses() { return valueAddresses; } public ObjectArrayList<Block> getChannel(int channel) { return channels[channel]; } public void clear() { for (ObjectArrayList<Block> channel : channels) { channel.clear(); } valueAddresses.clear(); positionCount = 0; pagesMemorySize = 0; estimatedSize = calculateEstimatedSize(); } public void addPage(Page page) { // ignore empty pages if (page.getPositionCount() == 0) { return; } positionCount += page.getPositionCount(); int pageIndex = (channels.length > 0) ? channels[0].size() : 0; for (int i = 0; i < channels.length; i++) { Block block = page.getBlock(i); channels[i].add(block); pagesMemorySize += block.getRetainedSizeInBytes(); } for (int position = 0; position < page.getPositionCount(); position++) { long sliceAddress = encodeSyntheticAddress(pageIndex, position); valueAddresses.add(sliceAddress); } estimatedSize = calculateEstimatedSize(); } public DataSize getEstimatedSize() { return new DataSize(estimatedSize, BYTE); } public void compact() { for (int channel = 0; channel < types.size(); channel++) { ObjectArrayList<Block> blocks = channels[channel]; for (int i = nextBlockToCompact; i < blocks.size(); i++) { Block block = blocks.get(i); if (block.getSizeInBytes() < block.getRetainedSizeInBytes()) { // Copy the block to compact its size Block compactedBlock = block.copyRegion(0, block.getPositionCount()); blocks.set(i, compactedBlock); pagesMemorySize -= block.getRetainedSizeInBytes(); pagesMemorySize += compactedBlock.getRetainedSizeInBytes(); } } } nextBlockToCompact = channels[0].size(); estimatedSize = calculateEstimatedSize(); } private long calculateEstimatedSize() { long elementsSize = (channels.length > 0) ? sizeOf(channels[0].elements()) : 0; long channelsArraySize = elementsSize * channels.length; long addressesArraySize = sizeOf(valueAddresses.elements()); return pagesMemorySize + channelsArraySize + addressesArraySize; } public Type getType(int channel) { return types.get(channel); } @Override public void swap(int a, int b) { long[] elements = valueAddresses.elements(); long temp = elements[a]; elements[a] = elements[b]; elements[b] = temp; } public int buildPage(int position, int[] outputChannels, PageBuilder pageBuilder) { while (!pageBuilder.isFull() && position < positionCount) { long pageAddress = valueAddresses.getLong(position); int blockIndex = decodeSliceIndex(pageAddress); int blockPosition = decodePosition(pageAddress); // append the row pageBuilder.declarePosition(); for (int i = 0; i < outputChannels.length; i++) { int outputChannel = outputChannels[i]; Type type = types.get(outputChannel); Block block = this.channels[outputChannel].get(blockIndex); type.appendTo(block, blockPosition, pageBuilder.getBlockBuilder(i)); } position++; } return position; } public void appendTo(int channel, int position, BlockBuilder output) { long pageAddress = valueAddresses.getLong(position); Type type = types.get(channel); Block block = channels[channel].get(decodeSliceIndex(pageAddress)); int blockPosition = decodePosition(pageAddress); type.appendTo(block, blockPosition, output); } public boolean isNull(int channel, int position) { long pageAddress = valueAddresses.getLong(position); Block block = channels[channel].get(decodeSliceIndex(pageAddress)); int blockPosition = decodePosition(pageAddress); return block.isNull(blockPosition); } public boolean getBoolean(int channel, int position) { long pageAddress = valueAddresses.getLong(position); Block block = channels[channel].get(decodeSliceIndex(pageAddress)); int blockPosition = decodePosition(pageAddress); return types.get(channel).getBoolean(block, blockPosition); } public long getLong(int channel, int position) { long pageAddress = valueAddresses.getLong(position); Block block = channels[channel].get(decodeSliceIndex(pageAddress)); int blockPosition = decodePosition(pageAddress); return types.get(channel).getLong(block, blockPosition); } public double getDouble(int channel, int position) { long pageAddress = valueAddresses.getLong(position); Block block = channels[channel].get(decodeSliceIndex(pageAddress)); int blockPosition = decodePosition(pageAddress); return types.get(channel).getDouble(block, blockPosition); } public Slice getSlice(int channel, int position) { long pageAddress = valueAddresses.getLong(position); Block block = channels[channel].get(decodeSliceIndex(pageAddress)); int blockPosition = decodePosition(pageAddress); return types.get(channel).getSlice(block, blockPosition); } public void sort(List<Integer> sortChannels, List<SortOrder> sortOrders) { sort(sortChannels, sortOrders, 0, getPositionCount()); } public void sort(List<Integer> sortChannels, List<SortOrder> sortOrders, int startPosition, int endPosition) { createPagesIndexComparator(sortChannels, sortOrders).sort(this, startPosition, endPosition); } public boolean positionEqualsPosition(PagesHashStrategy partitionHashStrategy, int leftPosition, int rightPosition) { long leftAddress = valueAddresses.getLong(leftPosition); int leftPageIndex = decodeSliceIndex(leftAddress); int leftPagePosition = decodePosition(leftAddress); long rightAddress = valueAddresses.getLong(rightPosition); int rightPageIndex = decodeSliceIndex(rightAddress); int rightPagePosition = decodePosition(rightAddress); return partitionHashStrategy.positionEqualsPosition(leftPageIndex, leftPagePosition, rightPageIndex, rightPagePosition); } public boolean positionEqualsRow(PagesHashStrategy pagesHashStrategy, int indexPosition, int rightPosition, Page rightPage) { long pageAddress = valueAddresses.getLong(indexPosition); int pageIndex = decodeSliceIndex(pageAddress); int pagePosition = decodePosition(pageAddress); return pagesHashStrategy.positionEqualsRow(pageIndex, pagePosition, rightPosition, rightPage); } private PagesIndexOrdering createPagesIndexComparator(List<Integer> sortChannels, List<SortOrder> sortOrders) { List<Type> sortTypes = sortChannels.stream() .map(types::get) .collect(toImmutableList()); return orderingCompiler.compilePagesIndexOrdering(sortTypes, sortChannels, sortOrders); } public LookupSource createLookupSource(List<Integer> joinChannels) { return createLookupSource(joinChannels, Optional.empty(), Optional.empty()); } public PagesHashStrategy createPagesHashStrategy(List<Integer> joinChannels, Optional<Integer> hashChannel) { return createPagesHashStrategy(joinChannels, hashChannel, Optional.empty()); } public PagesHashStrategy createPagesHashStrategy(List<Integer> joinChannels, Optional<Integer> hashChannel, Optional<JoinFilterFunction> joinFilterFunction) { try { return joinCompiler.compilePagesHashStrategyFactory(types, joinChannels) .createPagesHashStrategy(ImmutableList.copyOf(channels), hashChannel); } catch (Exception e) { log.error(e, "Lookup source compile failed for types=%s error=%s", types, e); } // if compilation fails, use interpreter return new SimplePagesHashStrategy(types, ImmutableList.<List<Block>>copyOf(channels), joinChannels, hashChannel, joinFilterFunction); } public LookupSource createLookupSource(List<Integer> joinChannels, Optional<Integer> hashChannel, Optional<JoinFilterFunction> filterFunction) { if (!filterFunction.isPresent() && !joinChannels.isEmpty()) { // todo compiled implementation of lookup join does not support: // (1) case with join function and the case // (2) when we are joining with empty join channels. // Ad (1) we need to add support for filter function into compiled PagesHashStrategy/JoinProbe // Ad (2) this code path will trigger only for OUTER joins. To fix that we need to add support for // OUTER joins into NestedLoopsJoin and remove "type == INNER" condition in LocalExecutionPlanner.visitJoin() try { LookupSourceFactory lookupSourceFactory = joinCompiler.compileLookupSourceFactory(types, joinChannels); LookupSource lookupSource = lookupSourceFactory.createLookupSource( valueAddresses, ImmutableList.<List<Block>>copyOf(channels), hashChannel); return lookupSource; } catch (Exception e) { log.error(e, "Lookup source compile failed for types=%s error=%s", types, e); } } // if compilation fails PagesHashStrategy hashStrategy = new SimplePagesHashStrategy( types, ImmutableList.<List<Block>>copyOf(channels), joinChannels, hashChannel, filterFunction); return new InMemoryJoinHash(valueAddresses, hashStrategy); } @Override public String toString() { return toStringHelper(this) .add("positionCount", positionCount) .add("types", types) .add("estimatedSize", estimatedSize) .toString(); } }
totticarter/presto
presto-main/src/main/java/com/facebook/presto/operator/PagesIndex.java
Java
apache-2.0
14,085
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using KafkaNet.Common; using KafkaNet.Statistics; namespace KafkaNet.Protocol { public class ProduceRequest : BaseRequest, IKafkaRequest<ProduceResponse> { /// <summary> /// Provide a hint to the broker call not to expect a response for requests without Acks. /// </summary> public override bool ExpectResponse { get { return Acks != 0; } } /// <summary> /// Indicates the type of kafka encoding this request is. /// </summary> public ApiKeyRequestType ApiKey { get { return ApiKeyRequestType.Produce; } } /// <summary> /// Time kafka will wait for requested ack level before returning. /// </summary> public int TimeoutMS = 1000; /// <summary> /// Level of ack required by kafka. 0 immediate, 1 written to leader, 2+ replicas synced, -1 all replicas /// </summary> public Int16 Acks = 1; /// <summary> /// Collection of payloads to post to kafka /// </summary> public List<Payload> Payload = new List<Payload>(); public KafkaDataPayload Encode() { return EncodeProduceRequest(this); } public IEnumerable<ProduceResponse> Decode(byte[] payload) { return DecodeProduceResponse(payload); } #region Protocol... private KafkaDataPayload EncodeProduceRequest(ProduceRequest request) { int totalCompressedBytes = 0; if (request.Payload == null) request.Payload = new List<Payload>(); var groupedPayloads = (from p in request.Payload group p by new { p.Topic, p.Partition, p.Codec } into tpc select tpc).ToList(); using (var message = EncodeHeader(request) .Pack(request.Acks) .Pack(request.TimeoutMS) .Pack(groupedPayloads.Count)) { foreach (var groupedPayload in groupedPayloads) { var payloads = groupedPayload.ToList(); message.Pack(groupedPayload.Key.Topic, StringPrefixEncoding.Int16) .Pack(payloads.Count) .Pack(groupedPayload.Key.Partition); switch (groupedPayload.Key.Codec) { case MessageCodec.CodecNone: message.Pack(Message.EncodeMessageSet(payloads.SelectMany(x => x.Messages))); break; case MessageCodec.CodecGzip: var compressedBytes = CreateGzipCompressedMessage(payloads.SelectMany(x => x.Messages)); Interlocked.Add(ref totalCompressedBytes, compressedBytes.CompressedAmount); message.Pack(Message.EncodeMessageSet(new[] { compressedBytes.CompressedMessage })); break; default: throw new NotSupportedException(string.Format("Codec type of {0} is not supported.", groupedPayload.Key.Codec)); } } var result = new KafkaDataPayload { Buffer = message.Payload(), CorrelationId = request.CorrelationId, MessageCount = request.Payload.Sum(x => x.Messages.Count) }; StatisticsTracker.RecordProduceRequest(result.MessageCount, result.Buffer.Length, totalCompressedBytes); return result; } } private CompressedMessageResult CreateGzipCompressedMessage(IEnumerable<Message> messages) { var messageSet = Message.EncodeMessageSet(messages); var gZipBytes = Compression.Zip(messageSet); var compressedMessage = new Message { Attribute = (byte)(0x00 | (ProtocolConstants.AttributeCodeMask & (byte)MessageCodec.CodecGzip)), Value = gZipBytes }; return new CompressedMessageResult { CompressedAmount = messageSet.Length - compressedMessage.Value.Length, CompressedMessage = compressedMessage }; } private IEnumerable<ProduceResponse> DecodeProduceResponse(byte[] data) { using (var stream = new BigEndianBinaryReader(data)) { var correlationId = stream.ReadInt32(); var topicCount = stream.ReadInt32(); for (int i = 0; i < topicCount; i++) { var topic = stream.ReadInt16String(); var partitionCount = stream.ReadInt32(); for (int j = 0; j < partitionCount; j++) { var response = new ProduceResponse() { Topic = topic, PartitionId = stream.ReadInt32(), Error = stream.ReadInt16(), Offset = stream.ReadInt64() }; yield return response; } } } } #endregion } class CompressedMessageResult { public int CompressedAmount { get; set; } public Message CompressedMessage { get; set; } } public class ProduceResponse { /// <summary> /// The topic the offset came from. /// </summary> public string Topic { get; set; } /// <summary> /// The partition the offset came from. /// </summary> public int PartitionId { get; set; } /// <summary> /// Error response code. 0 is success. /// </summary> public Int16 Error { get; set; } /// <summary> /// The offset number to commit as completed. /// </summary> public long Offset { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((ProduceResponse)obj); } protected bool Equals(ProduceResponse other) { return string.Equals(Topic, other.Topic) && PartitionId == other.PartitionId && Error == other.Error && Offset == other.Offset; } public override int GetHashCode() { unchecked { int hashCode = (Topic != null ? Topic.GetHashCode() : 0); hashCode = (hashCode * 397) ^ PartitionId; hashCode = (hashCode * 397) ^ Error.GetHashCode(); hashCode = (hashCode * 397) ^ Offset.GetHashCode(); return hashCode; } } } }
CenturyLinkCloud/kafka-net
src/kafka-net/Protocol/ProduceRequest.cs
C#
apache-2.0
7,324
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Description; using _02aContentNegotation.Models; namespace _02aContentNegotation.Controllers { public class DemoController : ApiController { private static readonly List<DemoItem> Items; static DemoController() { Items = new List<DemoItem>(); var random = new Random(); for (var x = 0; x < 10; x++) { var item = new DemoItem {Number = random.Next(1, 100)}; item.Text = string.Format("Generated text {0}", item.Number); Items.Add(item); } } public IEnumerable<DemoItem> Get() { return Items; } [ResponseType(typeof(DemoItem))] public IHttpActionResult Get(string id) { var item = Items.FirstOrDefault(i => i.Id == id); if (item != null) { return Ok(item); } return NotFound(); } [ResponseType(typeof(DemoItem))] public IHttpActionResult Post([FromBody]DemoItem value) { if (value == null) { return BadRequest("Item cannot be null."); } if (Items.Exists(i => i.Id == value.Id)) { return BadRequest("Id must be unique."); } Items.Add(value); return Ok(value); } [ResponseType(typeof(DemoItem))] public IHttpActionResult Put(string id, [FromBody]DemoItem value) { if (value == null) { return BadRequest("Item cannot be null."); } var item = Items.FirstOrDefault(i => i.Id == value.Id); if (item == null) { return NotFound(); } item.Number = value.Number; item.Text = value.Text; return Ok(item); } public IHttpActionResult Delete(string id) { var item = Items.FirstOrDefault(i => i.Id == id); if (item == null) { return NotFound(); } Items.Remove(item); return Ok(); } } }
brianbrawe/MVA-WebAPIDesign
02 - Basic Design/02aContentNegotation/Controllers/DemoController.cs
C#
apache-2.0
2,348
package org.pitest.maven; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.Test; public class PathToJavaClassConverterTest { private static final String SRC = new File("src/java") .getAbsolutePath(); private final PathToJavaClassConverter testee = new PathToJavaClassConverter( SRC); @Test public void shouldReturnNoMatchedForFilesNotUnderSourceTree() { assertFalse(this.testee.apply("not/under/source/tree/File.java").iterator() .hasNext()); } @Test public void shouldConvertFileInPackageDefaultToJavaClassName() { assertEquals("InDefault*", apply("InDefault.java")); } @Test public void shouldConvertFileInPackageToJavaClassName() { assertEquals("com.example.Class*", apply("com/example/Class.java")); } @Test public void shouldConvertFilesWithOddCaseExtensionsToJavaClassName() { assertEquals("com.example.Class*", apply("com/example/Class.JaVa")); } @Test public void shouldNotConvertFilesWithoutExtension() { assertFalse(this.testee.apply(SRC + "/File").iterator().hasNext()); } @Test public void shouldConvertFilesWithDotInPath() { assertTrue(this.testee.apply(SRC + "/foo.bar/File.java").iterator() .hasNext()); } @Test public void shouldIncludeWildCardInGeneratedGlobToCatchInnerClasses() { assertTrue(apply("foo.java").endsWith("*")); } @Test public void shouldConvertBackslashPathsRegardlessOfOs() { assertEquals("com.example.Class*", apply("com\\example\\Class.java")); } private String apply(final String value) { return this.testee.apply(SRC + "/" + value).iterator().next(); } }
michaelmnich/pitest-lib
pitest-maven/src/test/java/org/pitest/maven/PathToJavaClassConverterTest.java
Java
apache-2.0
1,854
--- title: "Custom window patterns" --- <!-- 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. --> # Custom window patterns The samples on this page demonstrate common custom window patterns. You can create custom windows with [`WindowFn` functions](/documentation/programming-guide/#provided-windowing-functions). For more information, see the [programming guide section on windowing](/documentation/programming-guide/#windowing). **Note**: Custom merging windows isn't supported in Python (with fnapi). ## Using data to dynamically set session window gaps You can modify the [`assignWindows`](https://beam.apache.org/releases/javadoc/current/index.html?org/apache/beam/sdk/transforms/windowing/SlidingWindows.html) function to use data-driven gaps, then window incoming data into sessions. Access the `assignWindows` function through `WindowFn.AssignContext.element()`. The original, fixed-duration `assignWindows` function is: {{< highlight java >}} {{< code_sample "examples/java/src/main/java/org/apache/beam/examples/snippets/Snippets.java" CustomSessionWindow1 >}} {{< /highlight >}} ### Creating data-driven gaps To create data-driven gaps, add the following snippets to the `assignWindows` function: - A default value for when the custom gap is not present in the data - A way to set the attribute from the main pipeline as a method of the custom windows For example, the following function assigns each element to a window between the timestamp and `gapDuration`: {{< highlight java >}} {{< code_sample "examples/java/src/main/java/org/apache/beam/examples/snippets/Snippets.java" CustomSessionWindow3 >}} {{< /highlight >}} Then, set the `gapDuration` field in a windowing function: {{< highlight java >}} {{< code_sample "examples/java/src/main/java/org/apache/beam/examples/snippets/Snippets.java" CustomSessionWindow2 >}} {{< /highlight >}} ### Windowing messages into sessions After creating data-driven gaps, you can window incoming data into the new, custom sessions. First, set the session length to the gap duration: {{< highlight java >}} {{< code_sample "examples/java/src/main/java/org/apache/beam/examples/snippets/Snippets.java" CustomSessionWindow4 >}} {{< /highlight >}} Lastly, window data into sessions in your pipeline: {{< highlight java >}} {{< code_sample "examples/java/src/main/java/org/apache/beam/examples/snippets/Snippets.java" CustomSessionWindow6 >}} {{< /highlight >}} ### Example data and windows The following test data tallies two users' scores with and without the `gap` attribute: ``` .apply("Create data", Create.timestamped( TimestampedValue.of("{\"user\":\"user-1\",\"score\":\"12\",\"gap\":\"5\"}", new Instant()), TimestampedValue.of("{\"user\":\"user-2\",\"score\":\"4\"}", new Instant()), TimestampedValue.of("{\"user\":\"user-1\",\"score\":\"-3\",\"gap\":\"5\"}", new Instant().plus(2000)), TimestampedValue.of("{\"user\":\"user-1\",\"score\":\"2\",\"gap\":\"5\"}", new Instant().plus(9000)), TimestampedValue.of("{\"user\":\"user-1\",\"score\":\"7\",\"gap\":\"5\"}", new Instant().plus(12000)), TimestampedValue.of("{\"user\":\"user-2\",\"score\":\"10\"}", new Instant().plus(12000))) .withCoder(StringUtf8Coder.of())) ``` The diagram below visualizes the test data: ![Two sets of data and the standard and dynamic sessions with which the data is windowed.](/images/standard-vs-dynamic-sessions.png) #### Standard sessions Standard sessions use the following windows and scores: ``` user=user-2, score=4, window=[2019-05-26T13:28:49.122Z..2019-05-26T13:28:59.122Z) user=user-1, score=18, window=[2019-05-26T13:28:48.582Z..2019-05-26T13:29:12.774Z) user=user-2, score=10, window=[2019-05-26T13:29:03.367Z..2019-05-26T13:29:13.367Z) ``` User #1 sees two events separated by 12 seconds. With standard sessions, the gap defaults to 10 seconds; both scores are in different sessions, so the scores aren't added. User #2 sees four events, seperated by two, seven, and three seconds, respectively. Since none of the gaps are greater than the default, the four events are in the same standard session and added together (18 points). #### Dynamic sessions The dynamic sessions specify a five-second gap, so they use the following windows and scores: ``` user=user-2, score=4, window=[2019-05-26T14:30:22.969Z..2019-05-26T14:30:32.969Z) user=user-1, score=9, window=[2019-05-26T14:30:22.429Z..2019-05-26T14:30:30.553Z) user=user-1, score=9, window=[2019-05-26T14:30:33.276Z..2019-05-26T14:30:41.849Z) user=user-2, score=10, window=[2019-05-26T14:30:37.357Z..2019-05-26T14:30:47.357Z) ``` With dynamic sessions, User #2 gets different scores. The third messages arrives seven seconds after the second message, so it's grouped into a different session. The large, 18-point session is split into two 9-point sessions.
lukecwik/incubator-beam
website/www/site/content/en/documentation/patterns/custom-windows.md
Markdown
apache-2.0
5,337
using System; using System.Collections.Generic; using System.Linq; using Android.Content; using Android.OS; using Android.Util; using Android.Widget; using EstimoteSdk; using JavaObject = Java.Lang.Object; namespace Estimotes.Droid { class FindSpecificBeacon : BeaconFinder, BeaconManager.IRangingListener { static readonly string Tag = typeof(FindSpecificBeacon).FullName; Beacon _beacon; bool _isSearching; Region _region; public EventHandler<BeaconFoundEventArgs> BeaconFound = delegate { }; public FindSpecificBeacon(Context context) : base(context) { BeaconManager.SetRangingListener(this); } public void OnBeaconsDiscovered(Region region, IList<Beacon> beacons) { Log.Debug(Tag, "Found {0} beacons", beacons.Count); Beacon foundBeacon = (from b in beacons where b.MacAddress.Equals(_beacon.MacAddress) select b).FirstOrDefault(); if (foundBeacon != null) { BeaconFound(this, new BeaconFoundEventArgs(foundBeacon)); } } public override void OnServiceReady() { if (_region == null) { throw new Exception("What happened to the _region?"); } try { BeaconManager.StartRanging(_region); Log.Debug(Tag, "Looking for beacons in the region."); _isSearching = true; } catch (RemoteException e) { _isSearching = false; Toast.MakeText(Context, "Cannot start ranging, something terrible happened!", ToastLength.Long).Show(); Log.Error(Tag, "Cannot start ranging, {0}", e); } } public void LookForBeacon(Region region, Beacon beacon) { _beacon = beacon; _region = region; BeaconManager.Connect(this); } public override void Stop() { if (_isSearching) { BeaconManager.StopRanging(_region); base.Stop(); _region = null; _beacon = null; _isSearching = false; } } } }
OctanMan/Estimotes-Xamarin
samples/Estimotes.Droid/FindSpecificBeacon.cs
C#
apache-2.0
2,365
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark import java.util.Collections import java.util.concurrent.TimeUnit import org.apache.spark.api.java.JavaFutureAction import org.apache.spark.rdd.RDD import org.apache.spark.scheduler.{JobFailed, JobSucceeded, JobWaiter} import scala.concurrent._ import scala.concurrent.duration.Duration import scala.util.{Failure, Try} /** * A future for the result of an action to support cancellation. This is an extension of the * Scala Future interface to support cancellation. */ trait FutureAction[T] extends Future[T] { // Note that we redefine methods of the Future trait here explicitly so we can specify a different // documentation (with reference to the word "action"). /** * Cancels the execution of this action. */ def cancel() /** * Blocks until this action completes. * @param atMost maximum wait time, which may be negative (no waiting is done), Duration.Inf * for unbounded waiting, or a finite positive duration * @return this FutureAction */ override def ready(atMost: Duration)(implicit permit: CanAwait): FutureAction.this.type /** * Awaits and returns the result (of type T) of this action. * @param atMost maximum wait time, which may be negative (no waiting is done), Duration.Inf * for unbounded waiting, or a finite positive duration * @throws Exception exception during action execution * @return the result value if the action is completed within the specific maximum wait time */ @throws(classOf[Exception]) override def result(atMost: Duration)(implicit permit: CanAwait): T /** * When this action is completed, either through an exception, or a value, applies the provided * function. */ def onComplete[U](func: (Try[T]) => U)(implicit executor: ExecutionContext) /** * Returns whether the action has already been completed with a value or an exception. */ override def isCompleted: Boolean /** * Returns whether the action has been cancelled. */ def isCancelled: Boolean /** * The value of this Future. * * If the future is not completed the returned value will be None. If the future is completed * the value will be Some(Success(t)) if it contains a valid result, or Some(Failure(error)) if * it contains an exception. */ override def value: Option[Try[T]] /** * Blocks and returns the result of this job. */ @throws(classOf[Exception]) def get(): T = Await.result(this, Duration.Inf) /** * Returns the job IDs run by the underlying async operation. * * This returns the current snapshot of the job list. Certain operations may run multiple * jobs, so multiple calls to this method may return different lists. */ def jobIds: Seq[Int] } /** * A [[FutureAction]] holding the result of an action that triggers a single job. Examples include * count, collect, reduce. */ class SimpleFutureAction[T] private[spark](jobWaiter: JobWaiter[_], resultFunc: => T) extends FutureAction[T] { @volatile private var _cancelled: Boolean = false override def cancel() { _cancelled = true jobWaiter.cancel() } override def ready(atMost: Duration)(implicit permit: CanAwait): SimpleFutureAction.this.type = { if (!atMost.isFinite()) { awaitResult() } else jobWaiter.synchronized { val finishTime = System.currentTimeMillis() + atMost.toMillis while (!isCompleted) { val time = System.currentTimeMillis() if (time >= finishTime) { throw new TimeoutException } else { jobWaiter.wait(finishTime - time) } } } this } @throws(classOf[Exception]) override def result(atMost: Duration)(implicit permit: CanAwait): T = { ready(atMost)(permit) awaitResult() match { case scala.util.Success(res) => res case scala.util.Failure(e) => throw e } } override def onComplete[U](func: (Try[T]) => U)(implicit executor: ExecutionContext) { executor.execute(new Runnable { override def run() { func(awaitResult()) } }) } override def isCompleted: Boolean = jobWaiter.jobFinished override def isCancelled: Boolean = _cancelled override def value: Option[Try[T]] = { if (jobWaiter.jobFinished) { Some(awaitResult()) } else { None } } private def awaitResult(): Try[T] = { jobWaiter.awaitResult() match { case JobSucceeded => scala.util.Success(resultFunc) case JobFailed(e: Exception) => scala.util.Failure(e) } } def jobIds: Seq[Int] = Seq(jobWaiter.jobId) } /** * A [[FutureAction]] for actions that could trigger multiple Spark jobs. Examples include take, * takeSample. Cancellation works by setting the cancelled flag to true and interrupting the * action thread if it is being blocked by a job. */ class ComplexFutureAction[T] extends FutureAction[T] { // Pointer to the thread that is executing the action. It is set when the action is run. @volatile private var thread: Thread = _ // A flag indicating whether the future has been cancelled. This is used in case the future // is cancelled before the action was even run (and thus we have no thread to interrupt). @volatile private var _cancelled: Boolean = false @volatile private var jobs: Seq[Int] = Nil // A promise used to signal the future. private val p = promise[T]() override def cancel(): Unit = this.synchronized { _cancelled = true if (thread != null) { thread.interrupt() } } /** * Executes some action enclosed in the closure. To properly enable cancellation, the closure * should use runJob implementation in this promise. See takeAsync for example. */ def run(func: => T)(implicit executor: ExecutionContext): this.type = { scala.concurrent.future { thread = Thread.currentThread try { p.success(func) } catch { case e: Exception => p.failure(e) } finally { // This lock guarantees when calling `thread.interrupt()` in `cancel`, // thread won't be set to null. ComplexFutureAction.this.synchronized { thread = null } } } this } /** * Runs a Spark job. This is a wrapper around the same functionality provided by SparkContext * to enable cancellation. */ def runJob[T, U, R]( rdd: RDD[T], processPartition: Iterator[T] => U, partitions: Seq[Int], resultHandler: (Int, U) => Unit, resultFunc: => R) { // If the action hasn't been cancelled yet, submit the job. The check and the submitJob // command need to be in an atomic block. val job = this.synchronized { if (!isCancelled) { rdd.context.submitJob(rdd, processPartition, partitions, resultHandler, resultFunc) } else { throw new SparkException("Action has been cancelled") } } this.jobs = jobs ++ job.jobIds // Wait for the job to complete. If the action is cancelled (with an interrupt), // cancel the job and stop the execution. This is not in a synchronized block because // Await.ready eventually waits on the monitor in FutureJob.jobWaiter. try { Await.ready(job, Duration.Inf) } catch { case e: InterruptedException => job.cancel() throw new SparkException("Action has been cancelled") } } override def isCancelled: Boolean = _cancelled @throws(classOf[InterruptedException]) @throws(classOf[scala.concurrent.TimeoutException]) override def ready(atMost: Duration)(implicit permit: CanAwait): this.type = { p.future.ready(atMost)(permit) this } @throws(classOf[Exception]) override def result(atMost: Duration)(implicit permit: CanAwait): T = { p.future.result(atMost)(permit) } override def onComplete[U](func: (Try[T]) => U)(implicit executor: ExecutionContext): Unit = { p.future.onComplete(func)(executor) } override def isCompleted: Boolean = p.isCompleted override def value: Option[Try[T]] = p.future.value def jobIds: Seq[Int] = jobs } private[spark] class JavaFutureActionWrapper[S, T](futureAction: FutureAction[S], converter: S => T) extends JavaFutureAction[T] { import scala.collection.JavaConverters._ override def isCancelled: Boolean = futureAction.isCancelled override def isDone: Boolean = { // According to java.util.Future's Javadoc, this returns True if the task was completed, // whether that completion was due to successful execution, an exception, or a cancellation. futureAction.isCancelled || futureAction.isCompleted } override def jobIds(): java.util.List[java.lang.Integer] = { Collections.unmodifiableList(futureAction.jobIds.map(Integer.valueOf).asJava) } private def getImpl(timeout: Duration): T = { // This will throw TimeoutException on timeout: Await.ready(futureAction, timeout) futureAction.value.get match { case scala.util.Success(value) => converter(value) case Failure(exception) => if (isCancelled) { throw new CancellationException("Job cancelled").initCause(exception) } else { // java.util.Future.get() wraps exceptions in ExecutionException throw new ExecutionException("Exception thrown by job", exception) } } } override def get(): T = getImpl(Duration.Inf) override def get(timeout: Long, unit: TimeUnit): T = getImpl(Duration.fromNanos(unit.toNanos(timeout))) override def cancel(mayInterruptIfRunning: Boolean): Boolean = synchronized { if (isDone) { // According to java.util.Future's Javadoc, this should return false if the task is completed. false } else { // We're limited in terms of the semantics we can provide here; our cancellation is // asynchronous and doesn't provide a mechanism to not cancel if the job is running. futureAction.cancel() true } } }
ArvinDevel/onlineAggregationOnSparkV2
core/src/main/scala/org/apache/spark/FutureAction.scala
Scala
apache-2.0
10,744
"""Support for ZHA covers.""" from __future__ import annotations import asyncio import functools import logging from zigpy.zcl.foundation import Status from homeassistant.components.cover import ( ATTR_CURRENT_POSITION, ATTR_POSITION, DEVICE_CLASS_DAMPER, DEVICE_CLASS_SHADE, DOMAIN, CoverEntity, ) from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .core import discovery from .core.const import ( CHANNEL_COVER, CHANNEL_LEVEL, CHANNEL_ON_OFF, CHANNEL_SHADE, DATA_ZHA, DATA_ZHA_DISPATCHERS, SIGNAL_ADD_ENTITIES, SIGNAL_ATTR_UPDATED, SIGNAL_SET_LEVEL, ) from .core.registries import ZHA_ENTITIES from .core.typing import ChannelType, ZhaDeviceType from .entity import ZhaEntity _LOGGER = logging.getLogger(__name__) STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, DOMAIN) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Zigbee Home Automation cover from config entry.""" entities_to_create = hass.data[DATA_ZHA][DOMAIN] unsub = async_dispatcher_connect( hass, SIGNAL_ADD_ENTITIES, functools.partial( discovery.async_add_entities, async_add_entities, entities_to_create ), ) hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub) @STRICT_MATCH(channel_names=CHANNEL_COVER) class ZhaCover(ZhaEntity, CoverEntity): """Representation of a ZHA cover.""" def __init__(self, unique_id, zha_device, channels, **kwargs): """Init this sensor.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._cover_channel = self.cluster_channels.get(CHANNEL_COVER) self._current_position = None async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._cover_channel, SIGNAL_ATTR_UPDATED, self.async_set_position ) @callback def async_restore_last_state(self, last_state): """Restore previous state.""" self._state = last_state.state if "current_position" in last_state.attributes: self._current_position = last_state.attributes["current_position"] @property def is_closed(self): """Return if the cover is closed.""" if self.current_cover_position is None: return None return self.current_cover_position == 0 @property def is_opening(self): """Return if the cover is opening or not.""" return self._state == STATE_OPENING @property def is_closing(self): """Return if the cover is closing or not.""" return self._state == STATE_CLOSING @property def current_cover_position(self): """Return the current position of ZHA cover. None is unknown, 0 is closed, 100 is fully open. """ return self._current_position @callback def async_set_position(self, attr_id, attr_name, value): """Handle position update from channel.""" _LOGGER.debug("setting position: %s", value) self._current_position = 100 - value if self._current_position == 0: self._state = STATE_CLOSED elif self._current_position == 100: self._state = STATE_OPEN self.async_write_ha_state() @callback def async_update_state(self, state): """Handle state update from channel.""" _LOGGER.debug("state=%s", state) self._state = state self.async_write_ha_state() async def async_open_cover(self, **kwargs): """Open the window cover.""" res = await self._cover_channel.up_open() if isinstance(res, list) and res[1] is Status.SUCCESS: self.async_update_state(STATE_OPENING) async def async_close_cover(self, **kwargs): """Close the window cover.""" res = await self._cover_channel.down_close() if isinstance(res, list) and res[1] is Status.SUCCESS: self.async_update_state(STATE_CLOSING) async def async_set_cover_position(self, **kwargs): """Move the roller shutter to a specific position.""" new_pos = kwargs[ATTR_POSITION] res = await self._cover_channel.go_to_lift_percentage(100 - new_pos) if isinstance(res, list) and res[1] is Status.SUCCESS: self.async_update_state( STATE_CLOSING if new_pos < self._current_position else STATE_OPENING ) async def async_stop_cover(self, **kwargs): """Stop the window cover.""" res = await self._cover_channel.stop() if isinstance(res, list) and res[1] is Status.SUCCESS: self._state = STATE_OPEN if self._current_position > 0 else STATE_CLOSED self.async_write_ha_state() async def async_update(self): """Attempt to retrieve the open/close state of the cover.""" await super().async_update() await self.async_get_state() async def async_get_state(self, from_cache=True): """Fetch the current state.""" _LOGGER.debug("polling current state") if self._cover_channel: pos = await self._cover_channel.get_attribute_value( "current_position_lift_percentage", from_cache=from_cache ) _LOGGER.debug("read pos=%s", pos) if pos is not None: self._current_position = 100 - pos self._state = ( STATE_OPEN if self.current_cover_position > 0 else STATE_CLOSED ) else: self._current_position = None self._state = None @STRICT_MATCH(channel_names={CHANNEL_LEVEL, CHANNEL_ON_OFF, CHANNEL_SHADE}) class Shade(ZhaEntity, CoverEntity): """ZHA Shade.""" _attr_device_class = DEVICE_CLASS_SHADE def __init__( self, unique_id: str, zha_device: ZhaDeviceType, channels: list[ChannelType], **kwargs, ) -> None: """Initialize the ZHA light.""" super().__init__(unique_id, zha_device, channels, **kwargs) self._on_off_channel = self.cluster_channels[CHANNEL_ON_OFF] self._level_channel = self.cluster_channels[CHANNEL_LEVEL] self._position = None self._is_open = None @property def current_cover_position(self): """Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """ return self._position @property def is_closed(self) -> bool | None: """Return True if shade is closed.""" if self._is_open is None: return None return not self._is_open async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() self.async_accept_signal( self._on_off_channel, SIGNAL_ATTR_UPDATED, self.async_set_open_closed ) self.async_accept_signal( self._level_channel, SIGNAL_SET_LEVEL, self.async_set_level ) @callback def async_restore_last_state(self, last_state): """Restore previous state.""" self._is_open = last_state.state == STATE_OPEN if ATTR_CURRENT_POSITION in last_state.attributes: self._position = last_state.attributes[ATTR_CURRENT_POSITION] @callback def async_set_open_closed(self, attr_id: int, attr_name: str, value: bool) -> None: """Set open/closed state.""" self._is_open = bool(value) self.async_write_ha_state() @callback def async_set_level(self, value: int) -> None: """Set the reported position.""" value = max(0, min(255, value)) self._position = int(value * 100 / 255) self.async_write_ha_state() async def async_open_cover(self, **kwargs): """Open the window cover.""" res = await self._on_off_channel.on() if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't open cover: %s", res) return self._is_open = True self.async_write_ha_state() async def async_close_cover(self, **kwargs): """Close the window cover.""" res = await self._on_off_channel.off() if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't open cover: %s", res) return self._is_open = False self.async_write_ha_state() async def async_set_cover_position(self, **kwargs): """Move the roller shutter to a specific position.""" new_pos = kwargs[ATTR_POSITION] res = await self._level_channel.move_to_level_with_on_off( new_pos * 255 / 100, 1 ) if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't set cover's position: %s", res) return self._position = new_pos self.async_write_ha_state() async def async_stop_cover(self, **kwargs) -> None: """Stop the cover.""" res = await self._level_channel.stop() if not isinstance(res, list) or res[1] != Status.SUCCESS: self.debug("couldn't stop cover: %s", res) return @STRICT_MATCH( channel_names={CHANNEL_LEVEL, CHANNEL_ON_OFF}, manufacturers="Keen Home Inc" ) class KeenVent(Shade): """Keen vent cover.""" _attr_device_class = DEVICE_CLASS_DAMPER async def async_open_cover(self, **kwargs): """Open the cover.""" position = self._position or 100 tasks = [ self._level_channel.move_to_level_with_on_off(position * 255 / 100, 1), self._on_off_channel.on(), ] results = await asyncio.gather(*tasks, return_exceptions=True) if any(isinstance(result, Exception) for result in results): self.debug("couldn't open cover") return self._is_open = True self._position = position self.async_write_ha_state()
lukas-hetzenecker/home-assistant
homeassistant/components/zha/cover.py
Python
apache-2.0
10,222
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.storm.wordcount; import org.apache.storm.topology.IRichBolt; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.TypeExtractor; import org.apache.flink.examples.java.wordcount.util.WordCountData; import org.apache.flink.storm.wordcount.operators.BoltTokenizer; import org.apache.flink.storm.wrappers.BoltWrapper; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * Implements the "WordCount" program that computes a simple word occurrence histogram over text files in a streaming * fashion. The tokenizer step is performed by a {@link IRichBolt Bolt}. * <p> * The input is a plain text file with lines separated by newline characters. * <p> * Usage: <code>WordCount &lt;text path&gt; &lt;result path&gt;</code><br> * If no parameters are provided, the program is run with default data from {@link WordCountData}. * <p> * This example shows how to: * <ul> * <li>use a Bolt within a Flink Streaming program.</li> * </ul> */ public class BoltTokenizerWordCount { // ************************************************************************* // PROGRAM // ************************************************************************* public static void main(final String[] args) throws Exception { if (!parseParameters(args)) { return; } // set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // get input data final DataStream<String> text = getTextDataStream(env); final DataStream<Tuple2<String, Integer>> counts = text // split up the lines in pairs (2-tuples) containing: (word,1) // this is done by a bolt that is wrapped accordingly .transform("BoltTokenizer", TypeExtractor.getForObject(new Tuple2<String, Integer>("", 0)), new BoltWrapper<String, Tuple2<String, Integer>>(new BoltTokenizer())) // group by the tuple field "0" and sum up tuple field "1" .keyBy(0).sum(1); // emit result if (fileOutput) { counts.writeAsText(outputPath); } else { counts.print(); } // execute program env.execute("Streaming WordCount with bolt tokenizer"); } // ************************************************************************* // UTIL METHODS // ************************************************************************* private static boolean fileOutput = false; private static String textPath; private static String outputPath; private static boolean parseParameters(final String[] args) { if (args.length > 0) { // parse input arguments fileOutput = true; if (args.length == 2) { textPath = args[0]; outputPath = args[1]; } else { System.err.println("Usage: BoltTokenizerWordCount <text path> <result path>"); return false; } } else { System.out.println("Executing BoltTokenizerWordCount example with built-in default data"); System.out.println(" Provide parameters to read input data from a file"); System.out.println(" Usage: BoltTokenizerWordCount <text path> <result path>"); } return true; } private static DataStream<String> getTextDataStream(final StreamExecutionEnvironment env) { if (fileOutput) { // read the text file from given input path return env.readTextFile(textPath); } return env.fromElements(WordCountData.WORDS); } }
WangTaoTheTonic/flink
flink-contrib/flink-storm-examples/src/main/java/org/apache/flink/storm/wordcount/BoltTokenizerWordCount.java
Java
apache-2.0
4,236
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.util; import com.google.common.base.Predicate; import org.jf.dexlib2.AccessFlags; import org.jf.dexlib2.iface.Field; import javax.annotation.Nonnull; import javax.annotation.Nullable; public final class FieldUtil { public static Predicate<Field> FIELD_IS_STATIC = new Predicate<Field>() { @Override public boolean apply(@Nullable Field input) { return input != null && isStatic(input); } }; public static Predicate<Field> FIELD_IS_INSTANCE = new Predicate<Field>() { @Override public boolean apply(@Nullable Field input) { return input != null && !isStatic(input); } }; private FieldUtil() { } public static boolean isStatic(@Nonnull Field field) { return AccessFlags.STATIC.isSet(field.getAccessFlags()); } }
thecocce/show-java
app/src/main/java/org/jf/dexlib2/util/FieldUtil.java
Java
apache-2.0
2,416
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.expressions.codegen import scala.annotation.tailrec import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.expressions.aggregate.NoOp import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData} import org.apache.spark.sql.types._ /** * Java can not access Projection (in package object) */ abstract class BaseProjection extends Projection {} /** * Generates byte code that produces a [[InternalRow]] object (not an [[UnsafeRow]]) that can update * itself based on a new input [[InternalRow]] for a fixed set of [[Expression Expressions]]. */ object GenerateSafeProjection extends CodeGenerator[Seq[Expression], Projection] { protected def canonicalize(in: Seq[Expression]): Seq[Expression] = in.map(ExpressionCanonicalizer.execute) protected def bind(in: Seq[Expression], inputSchema: Seq[Attribute]): Seq[Expression] = in.map(BindReferences.bindReference(_, inputSchema)) private def createCodeForStruct( ctx: CodegenContext, input: String, schema: StructType): ExprCode = { val tmp = ctx.freshName("tmp") val output = ctx.freshName("safeRow") val values = ctx.freshName("values") // These expressions could be split into multiple functions ctx.addMutableState("Object[]", values, s"$values = null;") val rowClass = classOf[GenericInternalRow].getName val fieldWriters = schema.map(_.dataType).zipWithIndex.map { case (dt, i) => val converter = convertToSafe(ctx, ctx.getValue(tmp, dt, i.toString), dt) s""" if (!$tmp.isNullAt($i)) { ${converter.code} $values[$i] = ${converter.value}; } """ } val allFields = ctx.splitExpressions(tmp, fieldWriters) val code = s""" final InternalRow $tmp = $input; $values = new Object[${schema.length}]; $allFields final InternalRow $output = new $rowClass($values); $values = null; """ ExprCode(code, "false", output) } private def createCodeForArray( ctx: CodegenContext, input: String, elementType: DataType): ExprCode = { val tmp = ctx.freshName("tmp") val output = ctx.freshName("safeArray") val values = ctx.freshName("values") val numElements = ctx.freshName("numElements") val index = ctx.freshName("index") val arrayClass = classOf[GenericArrayData].getName val elementConverter = convertToSafe(ctx, ctx.getValue(tmp, elementType, index), elementType) val code = s""" final ArrayData $tmp = $input; final int $numElements = $tmp.numElements(); final Object[] $values = new Object[$numElements]; for (int $index = 0; $index < $numElements; $index++) { if (!$tmp.isNullAt($index)) { ${elementConverter.code} $values[$index] = ${elementConverter.value}; } } final ArrayData $output = new $arrayClass($values); """ ExprCode(code, "false", output) } private def createCodeForMap( ctx: CodegenContext, input: String, keyType: DataType, valueType: DataType): ExprCode = { val tmp = ctx.freshName("tmp") val output = ctx.freshName("safeMap") val mapClass = classOf[ArrayBasedMapData].getName val keyConverter = createCodeForArray(ctx, s"$tmp.keyArray()", keyType) val valueConverter = createCodeForArray(ctx, s"$tmp.valueArray()", valueType) val code = s""" final MapData $tmp = $input; ${keyConverter.code} ${valueConverter.code} final MapData $output = new $mapClass(${keyConverter.value}, ${valueConverter.value}); """ ExprCode(code, "false", output) } @tailrec private def convertToSafe( ctx: CodegenContext, input: String, dataType: DataType): ExprCode = dataType match { case s: StructType => createCodeForStruct(ctx, input, s) case ArrayType(elementType, _) => createCodeForArray(ctx, input, elementType) case MapType(keyType, valueType, _) => createCodeForMap(ctx, input, keyType, valueType) case udt: UserDefinedType[_] => convertToSafe(ctx, input, udt.sqlType) case _ => ExprCode("", "false", input) } protected def create(expressions: Seq[Expression]): Projection = { val ctx = newCodeGenContext() val expressionCodes = expressions.zipWithIndex.map { case (NoOp, _) => "" case (e, i) => val evaluationCode = e.genCode(ctx) val converter = convertToSafe(ctx, evaluationCode.value, e.dataType) evaluationCode.code + s""" if (${evaluationCode.isNull}) { mutableRow.setNullAt($i); } else { ${converter.code} ${ctx.setColumn("mutableRow", e.dataType, i, converter.value)}; } """ } val allExpressions = ctx.splitExpressions(ctx.INPUT_ROW, expressionCodes) val codeBody = s""" public java.lang.Object generate(Object[] references) { return new SpecificSafeProjection(references); } class SpecificSafeProjection extends ${classOf[BaseProjection].getName} { private Object[] references; private InternalRow mutableRow; ${ctx.declareMutableStates()} public SpecificSafeProjection(Object[] references) { this.references = references; mutableRow = (InternalRow) references[references.length - 1]; ${ctx.initMutableStates()} } public void initialize(int partitionIndex) { ${ctx.initPartition()} } public java.lang.Object apply(java.lang.Object _i) { InternalRow ${ctx.INPUT_ROW} = (InternalRow) _i; $allExpressions return mutableRow; } ${ctx.declareAddedFunctions()} } """ val code = CodeFormatter.stripOverlappingComments( new CodeAndComment(codeBody, ctx.getPlaceHolderToComments())) logDebug(s"code for ${expressions.mkString(",")}:\n${CodeFormatter.format(code)}") val (clazz, _) = CodeGenerator.compile(code) val resultRow = new SpecificInternalRow(expressions.map(_.dataType)) clazz.generate(ctx.references.toArray :+ resultRow).asInstanceOf[Projection] } }
1haodian/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GenerateSafeProjection.scala
Scala
apache-2.0
7,022
/** ****************************************************************************** * @file stm32l5xx_hal_usart.c * @author MCD Application Team * @brief USART HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Universal Synchronous/Asynchronous Receiver Transmitter * Peripheral (USART). * + Initialization and de-initialization functions * + IO operation functions * + Peripheral Control functions * + Peripheral State and Error functions * @verbatim =============================================================================== ##### How to use this driver ##### =============================================================================== [..] The USART HAL driver can be used as follows: (#) Declare a USART_HandleTypeDef handle structure (eg. USART_HandleTypeDef husart). (#) Initialize the USART low level resources by implementing the HAL_USART_MspInit() API: (++) Enable the USARTx interface clock. (++) USART pins configuration: (+++) Enable the clock for the USART GPIOs. (+++) Configure these USART pins as alternate function pull-up. (++) NVIC configuration if you need to use interrupt process (HAL_USART_Transmit_IT(), HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs): (+++) Configure the USARTx interrupt priority. (+++) Enable the NVIC USART IRQ handle. (++) USART interrupts handling: -@@- The specific USART interrupts (Transmission complete interrupt, RXNE interrupt and Error Interrupts) will be managed using the macros __HAL_USART_ENABLE_IT() and __HAL_USART_DISABLE_IT() inside the transmit and receive process. (++) DMA Configuration if you need to use DMA process (HAL_USART_Transmit_DMA() HAL_USART_Receive_DMA() and HAL_USART_TransmitReceive_DMA() APIs): (+++) Declare a DMA handle structure for the Tx/Rx channel. (+++) Enable the DMAx interface clock. (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. (+++) Configure the DMA Tx/Rx channel. (+++) Associate the initialized DMA handle to the USART DMA Tx/Rx handle. (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel. (#) Program the Baud Rate, Word Length, Stop Bit, Parity, and Mode (Receiver/Transmitter) in the husart handle Init structure. (#) Initialize the USART registers by calling the HAL_USART_Init() API: (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customized HAL_USART_MspInit(&husart) API. [..] (@) To configure and enable/disable the USART to wake up the MCU from stop mode, resort to UART API's HAL_UARTEx_StopModeWakeUpSourceConfig(), HAL_UARTEx_EnableStopMode() and HAL_UARTEx_DisableStopMode() in casting the USART handle to UART type UART_HandleTypeDef. ##### Callback registration ##### ================================== [..] The compilation define USE_HAL_USART_REGISTER_CALLBACKS when set to 1 allows the user to configure dynamically the driver callbacks. [..] Use Function @ref HAL_USART_RegisterCallback() to register a user callback. Function @ref HAL_USART_RegisterCallback() allows to register following callbacks: (+) TxHalfCpltCallback : Tx Half Complete Callback. (+) TxCpltCallback : Tx Complete Callback. (+) RxHalfCpltCallback : Rx Half Complete Callback. (+) RxCpltCallback : Rx Complete Callback. (+) TxRxCpltCallback : Tx Rx Complete Callback. (+) ErrorCallback : Error Callback. (+) AbortCpltCallback : Abort Complete Callback. (+) RxFifoFullCallback : Rx Fifo Full Callback. (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. (+) MspInitCallback : USART MspInit. (+) MspDeInitCallback : USART MspDeInit. This function takes as parameters the HAL peripheral handle, the Callback ID and a pointer to the user callback function. [..] Use function @ref HAL_USART_UnRegisterCallback() to reset a callback to the default weak (surcharged) function. @ref HAL_USART_UnRegisterCallback() takes as parameters the HAL peripheral handle, and the Callback ID. This function allows to reset following callbacks: (+) TxHalfCpltCallback : Tx Half Complete Callback. (+) TxCpltCallback : Tx Complete Callback. (+) RxHalfCpltCallback : Rx Half Complete Callback. (+) RxCpltCallback : Rx Complete Callback. (+) TxRxCpltCallback : Tx Rx Complete Callback. (+) ErrorCallback : Error Callback. (+) AbortCpltCallback : Abort Complete Callback. (+) RxFifoFullCallback : Rx Fifo Full Callback. (+) TxFifoEmptyCallback : Tx Fifo Empty Callback. (+) MspInitCallback : USART MspInit. (+) MspDeInitCallback : USART MspDeInit. [..] By default, after the @ref HAL_USART_Init() and when the state is HAL_USART_STATE_RESET all callbacks are set to the corresponding weak (surcharged) functions: examples @ref HAL_USART_TxCpltCallback(), @ref HAL_USART_RxHalfCpltCallback(). Exception done for MspInit and MspDeInit functions that are respectively reset to the legacy weak (surcharged) functions in the @ref HAL_USART_Init() and @ref HAL_USART_DeInit() only when these callbacks are null (not registered beforehand). If not, MspInit or MspDeInit are not null, the @ref HAL_USART_Init() and @ref HAL_USART_DeInit() keep and use the user MspInit/MspDeInit callbacks (registered beforehand). [..] Callbacks can be registered/unregistered in HAL_USART_STATE_READY state only. Exception done MspInit/MspDeInit that can be registered/unregistered in HAL_USART_STATE_READY or HAL_USART_STATE_RESET state, thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit. In that case first register the MspInit/MspDeInit user callbacks using @ref HAL_USART_RegisterCallback() before calling @ref HAL_USART_DeInit() or @ref HAL_USART_Init() function. [..] When The compilation define USE_HAL_USART_REGISTER_CALLBACKS is set to 0 or not defined, the callback registration feature is not available and weak (surcharged) callbacks are used. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32l5xx_hal.h" /** @addtogroup STM32L5xx_HAL_Driver * @{ */ /** @defgroup USART USART * @brief HAL USART Synchronous module driver * @{ */ #ifdef HAL_USART_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /** @defgroup USART_Private_Constants USART Private Constants * @{ */ #define USART_DUMMY_DATA ((uint16_t) 0xFFFF) /*!< USART transmitted dummy data */ #define USART_TEACK_REACK_TIMEOUT 1000U /*!< USART TX or RX enable acknowledge time-out value */ #define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8 | \ USART_CR1_FIFOEN )) /*!< USART CR1 fields of parameters set by USART_SetConfig API */ #define USART_CR2_FIELDS ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | USART_CR2_CLKEN | \ USART_CR2_LBCL | USART_CR2_STOP | USART_CR2_SLVEN | \ USART_CR2_DIS_NSS)) /*!< USART CR2 fields of parameters set by USART_SetConfig API */ #define USART_CR3_FIELDS ((uint32_t)(USART_CR3_TXFTCFG | USART_CR3_RXFTCFG )) /*!< USART or USART CR3 fields of parameters set by USART_SetConfig API */ #define USART_BRR_MIN 0x10U /* USART BRR minimum authorized value */ #define USART_BRR_MAX 0xFFFFU /* USART BRR maximum authorized value */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** @addtogroup USART_Private_Functions * @{ */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ static void USART_EndTransfer(USART_HandleTypeDef *husart); static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); static void USART_DMAError(DMA_HandleTypeDef *hdma); static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma); static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma); static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma); static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout); static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart); static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart); static void USART_TxISR_8BIT(USART_HandleTypeDef *husart); static void USART_TxISR_16BIT(USART_HandleTypeDef *husart); static void USART_TxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart); static void USART_TxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); static void USART_EndTransmit_IT(USART_HandleTypeDef *husart); static void USART_RxISR_8BIT(USART_HandleTypeDef *husart); static void USART_RxISR_16BIT(USART_HandleTypeDef *husart); static void USART_RxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart); static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup USART_Exported_Functions USART Exported Functions * @{ */ /** @defgroup USART_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to initialize the USART in asynchronous and in synchronous modes. (+) For the asynchronous mode only these parameters can be configured: (++) Baud Rate (++) Word Length (++) Stop Bit (++) Parity: If the parity is enabled, then the MSB bit of the data written in the data register is transmitted but is changed by the parity bit. (++) USART polarity (++) USART phase (++) USART LastBit (++) Receiver/transmitter modes [..] The HAL_USART_Init() function follows the USART synchronous configuration procedure (details for the procedure are available in reference manual). @endverbatim Depending on the frame length defined by the M1 and M0 bits (7-bit, 8-bit or 9-bit), the possible USART formats are listed in the following table. Table 1. USART frame format. +-----------------------------------------------------------------------+ | M1 bit | M0 bit | PCE bit | USART frame | |---------|---------|-----------|---------------------------------------| | 0 | 0 | 0 | | SB | 8 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 1 | 0 | | SB | 9 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | |---------|---------|-----------|---------------------------------------| | 1 | 0 | 0 | | SB | 7 bit data | STB | | |---------|---------|-----------|---------------------------------------| | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | +-----------------------------------------------------------------------+ * @{ */ /** * @brief Initialize the USART mode according to the specified * parameters in the USART_InitTypeDef and initialize the associated handle. * @param husart USART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) { /* Check the USART handle allocation */ if (husart == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_USART_INSTANCE(husart->Instance)); if (husart->State == HAL_USART_STATE_RESET) { /* Allocate lock resource and initialize it */ husart->Lock = HAL_UNLOCKED; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) USART_InitCallbacksToDefault(husart); if (husart->MspInitCallback == NULL) { husart->MspInitCallback = HAL_USART_MspInit; } /* Init the low level hardware */ husart->MspInitCallback(husart); #else /* Init the low level hardware : GPIO, CLOCK */ HAL_USART_MspInit(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } husart->State = HAL_USART_STATE_BUSY; /* Disable the Peripheral */ __HAL_USART_DISABLE(husart); /* Set the Usart Communication parameters */ if (USART_SetConfig(husart) == HAL_ERROR) { return HAL_ERROR; } /* In Synchronous mode, the following bits must be kept cleared: - LINEN bit in the USART_CR2 register - HDSEL, SCEN and IREN bits in the USART_CR3 register.*/ husart->Instance->CR2 &= ~USART_CR2_LINEN; husart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); /* Enable the Peripheral */ __HAL_USART_ENABLE(husart); /* TEACK and/or REACK to check before moving husart->State to Ready */ return (USART_CheckIdleState(husart)); } /** * @brief DeInitialize the USART peripheral. * @param husart USART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart) { /* Check the USART handle allocation */ if (husart == NULL) { return HAL_ERROR; } /* Check the parameters */ assert_param(IS_USART_INSTANCE(husart->Instance)); husart->State = HAL_USART_STATE_BUSY; husart->Instance->CR1 = 0x0U; husart->Instance->CR2 = 0x0U; husart->Instance->CR3 = 0x0U; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) if (husart->MspDeInitCallback == NULL) { husart->MspDeInitCallback = HAL_USART_MspDeInit; } /* DeInit the low level hardware */ husart->MspDeInitCallback(husart); #else /* DeInit the low level hardware */ HAL_USART_MspDeInit(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_RESET; /* Process Unlock */ __HAL_UNLOCK(husart); return HAL_OK; } /** * @brief Initialize the USART MSP. * @param husart USART handle. * @retval None */ __weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_MspInit can be implemented in the user file */ } /** * @brief DeInitialize the USART MSP. * @param husart USART handle. * @retval None */ __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_MspDeInit can be implemented in the user file */ } #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /** * @brief Register a User USART Callback * To be used instead of the weak predefined callback * @param husart usart handle * @param CallbackID ID of the callback to be registered * This parameter can be one of the following values: * @arg @ref HAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID * @arg @ref HAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID * @arg @ref HAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID * @arg @ref HAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID * @arg @ref HAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID * @arg @ref HAL_USART_ERROR_CB_ID Error Callback ID * @arg @ref HAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID * @arg @ref HAL_USART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID * @arg @ref HAL_USART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID * @arg @ref HAL_USART_MSPINIT_CB_ID MspInit Callback ID * @arg @ref HAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID * @param pCallback pointer to the Callback function * @retval HAL status + */ HAL_StatusTypeDef HAL_USART_RegisterCallback(USART_HandleTypeDef *husart, HAL_USART_CallbackIDTypeDef CallbackID, pUSART_CallbackTypeDef pCallback) { HAL_StatusTypeDef status = HAL_OK; if (pCallback == NULL) { /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; return HAL_ERROR; } /* Process locked */ __HAL_LOCK(husart); if (husart->State == HAL_USART_STATE_READY) { switch (CallbackID) { case HAL_USART_TX_HALFCOMPLETE_CB_ID : husart->TxHalfCpltCallback = pCallback; break; case HAL_USART_TX_COMPLETE_CB_ID : husart->TxCpltCallback = pCallback; break; case HAL_USART_RX_HALFCOMPLETE_CB_ID : husart->RxHalfCpltCallback = pCallback; break; case HAL_USART_RX_COMPLETE_CB_ID : husart->RxCpltCallback = pCallback; break; case HAL_USART_TX_RX_COMPLETE_CB_ID : husart->TxRxCpltCallback = pCallback; break; case HAL_USART_ERROR_CB_ID : husart->ErrorCallback = pCallback; break; case HAL_USART_ABORT_COMPLETE_CB_ID : husart->AbortCpltCallback = pCallback; break; case HAL_USART_RX_FIFO_FULL_CB_ID : husart->RxFifoFullCallback = pCallback; break; case HAL_USART_TX_FIFO_EMPTY_CB_ID : husart->TxFifoEmptyCallback = pCallback; break; case HAL_USART_MSPINIT_CB_ID : husart->MspInitCallback = pCallback; break; case HAL_USART_MSPDEINIT_CB_ID : husart->MspDeInitCallback = pCallback; break; default : /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else if (husart->State == HAL_USART_STATE_RESET) { switch (CallbackID) { case HAL_USART_MSPINIT_CB_ID : husart->MspInitCallback = pCallback; break; case HAL_USART_MSPDEINIT_CB_ID : husart->MspDeInitCallback = pCallback; break; default : /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else { /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(husart); return status; } /** * @brief Unregister an UART Callback * UART callaback is redirected to the weak predefined callback * @param husart uart handle * @param CallbackID ID of the callback to be unregistered * This parameter can be one of the following values: * @arg @ref HAL_USART_TX_HALFCOMPLETE_CB_ID Tx Half Complete Callback ID * @arg @ref HAL_USART_TX_COMPLETE_CB_ID Tx Complete Callback ID * @arg @ref HAL_USART_RX_HALFCOMPLETE_CB_ID Rx Half Complete Callback ID * @arg @ref HAL_USART_RX_COMPLETE_CB_ID Rx Complete Callback ID * @arg @ref HAL_USART_TX_RX_COMPLETE_CB_ID Rx Complete Callback ID * @arg @ref HAL_USART_ERROR_CB_ID Error Callback ID * @arg @ref HAL_USART_ABORT_COMPLETE_CB_ID Abort Complete Callback ID * @arg @ref HAL_USART_RX_FIFO_FULL_CB_ID Rx Fifo Full Callback ID * @arg @ref HAL_USART_TX_FIFO_EMPTY_CB_ID Tx Fifo Empty Callback ID * @arg @ref HAL_USART_MSPINIT_CB_ID MspInit Callback ID * @arg @ref HAL_USART_MSPDEINIT_CB_ID MspDeInit Callback ID * @retval HAL status */ HAL_StatusTypeDef HAL_USART_UnRegisterCallback(USART_HandleTypeDef *husart, HAL_USART_CallbackIDTypeDef CallbackID) { HAL_StatusTypeDef status = HAL_OK; /* Process locked */ __HAL_LOCK(husart); if (HAL_USART_STATE_READY == husart->State) { switch (CallbackID) { case HAL_USART_TX_HALFCOMPLETE_CB_ID : husart->TxHalfCpltCallback = HAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ break; case HAL_USART_TX_COMPLETE_CB_ID : husart->TxCpltCallback = HAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ break; case HAL_USART_RX_HALFCOMPLETE_CB_ID : husart->RxHalfCpltCallback = HAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ break; case HAL_USART_RX_COMPLETE_CB_ID : husart->RxCpltCallback = HAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ break; case HAL_USART_TX_RX_COMPLETE_CB_ID : husart->TxRxCpltCallback = HAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ break; case HAL_USART_ERROR_CB_ID : husart->ErrorCallback = HAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ break; case HAL_USART_ABORT_COMPLETE_CB_ID : husart->AbortCpltCallback = HAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ break; case HAL_USART_RX_FIFO_FULL_CB_ID : husart->RxFifoFullCallback = HAL_USARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ break; case HAL_USART_TX_FIFO_EMPTY_CB_ID : husart->TxFifoEmptyCallback = HAL_USARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ break; case HAL_USART_MSPINIT_CB_ID : husart->MspInitCallback = HAL_USART_MspInit; /* Legacy weak MspInitCallback */ break; case HAL_USART_MSPDEINIT_CB_ID : husart->MspDeInitCallback = HAL_USART_MspDeInit; /* Legacy weak MspDeInitCallback */ break; default : /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else if (HAL_USART_STATE_RESET == husart->State) { switch (CallbackID) { case HAL_USART_MSPINIT_CB_ID : husart->MspInitCallback = HAL_USART_MspInit; break; case HAL_USART_MSPDEINIT_CB_ID : husart->MspDeInitCallback = HAL_USART_MspDeInit; break; default : /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; break; } } else { /* Update the error code */ husart->ErrorCode |= HAL_USART_ERROR_INVALID_CALLBACK; /* Return error status */ status = HAL_ERROR; } /* Release Lock */ __HAL_UNLOCK(husart); return status; } #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ /** * @} */ /** @defgroup USART_Exported_Functions_Group2 IO operation functions * @brief USART Transmit and Receive functions * @verbatim =============================================================================== ##### IO operation functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART synchronous data transfers. [..] The USART supports master mode only: it cannot receive or send data related to an input clock (SCLK is always an output). [..] (#) There are two modes of transfer: (++) Blocking mode: The communication is performed in polling mode. The HAL status of all data processing is returned by the same function after finishing transfer. (++) No-Blocking mode: The communication is performed using Interrupts or DMA, These API's return the HAL status. The end of the data processing will be indicated through the dedicated USART IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. The HAL_USART_TxCpltCallback(), HAL_USART_RxCpltCallback() and HAL_USART_TxRxCpltCallback() user callbacks will be executed respectively at the end of the transmit or Receive process The HAL_USART_ErrorCallback()user callback will be executed when a communication error is detected (#) Blocking mode API's are : (++) HAL_USART_Transmit() in simplex mode (++) HAL_USART_Receive() in full duplex receive only (++) HAL_USART_TransmitReceive() in full duplex mode (#) Non-Blocking mode API's with Interrupt are : (++) HAL_USART_Transmit_IT() in simplex mode (++) HAL_USART_Receive_IT() in full duplex receive only (++) HAL_USART_TransmitReceive_IT() in full duplex mode (++) HAL_USART_IRQHandler() (#) No-Blocking mode API's with DMA are : (++) HAL_USART_Transmit_DMA() in simplex mode (++) HAL_USART_Receive_DMA() in full duplex receive only (++) HAL_USART_TransmitReceive_DMA() in full duplex mode (++) HAL_USART_DMAPause() (++) HAL_USART_DMAResume() (++) HAL_USART_DMAStop() (#) A set of Transfer Complete Callbacks are provided in Non_Blocking mode: (++) HAL_USART_TxCpltCallback() (++) HAL_USART_RxCpltCallback() (++) HAL_USART_TxHalfCpltCallback() (++) HAL_USART_RxHalfCpltCallback() (++) HAL_USART_ErrorCallback() (++) HAL_USART_TxRxCpltCallback() (#) Non-Blocking mode transfers could be aborted using Abort API's : (++) HAL_USART_Abort() (++) HAL_USART_Abort_IT() (#) For Abort services based on interrupts (HAL_USART_Abort_IT), a Abort Complete Callbacks is provided: (++) HAL_USART_AbortCpltCallback() (#) In Non-Blocking mode transfers, possible errors are split into 2 categories. Errors are handled as follows : (++) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception . Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type, and HAL_USART_ErrorCallback() user callback is executed. Transfer is kept ongoing on USART side. If user wants to abort it, Abort services should be called by user. (++) Error is considered as Blocking : Transfer could not be completed properly and is aborted. This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode. Error code is set to allow user to identify error type, and HAL_USART_ErrorCallback() user callback is executed. @endverbatim * @{ */ /** * @brief Simplex send an amount of data in blocking mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data is handled as a set of u16. In this case, Size must indicate the number * of u16 provided through pTxData. * @param husart USART handle. * @param pTxData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be sent. * @param Timeout Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout) { uint8_t *ptxdata8bits; uint16_t *ptxdata16bits; uint32_t tickstart; if (husart->State == HAL_USART_STATE_READY) { if ((pTxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX; /* Init tickstart for timeout managment*/ tickstart = HAL_GetTick(); husart->TxXferSize = Size; husart->TxXferCount = Size; /* In case of 9bits/No Parity transfer, pTxData needs to be handled as a uint16_t pointer */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { ptxdata8bits = NULL; ptxdata16bits = (uint16_t *) pTxData; } else { ptxdata8bits = pTxData; ptxdata16bits = NULL; } /* Check the remaining data to be sent */ while (husart->TxXferCount > 0U) { if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (ptxdata8bits == NULL) { husart->Instance->TDR = (uint16_t)(*ptxdata16bits & 0x01FFU); ptxdata16bits++; } else { husart->Instance->TDR = (uint8_t)(*ptxdata8bits & 0xFFU); ptxdata8bits++; } husart->TxXferCount--; } if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } /* Clear Transmission Complete Flag */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); /* Clear overrun flag and discard the received data */ __HAL_USART_CLEAR_OREFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); /* At end of Tx process, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in blocking mode. * @note To receive synchronous data, dummy data are simultaneously transmitted. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of u16. In this case, Size must indicate the number * of u16 available through pRxData. * @param husart USART handle. * @param pRxData Pointer to data buffer (u8 or u16 data elements). * @param Size Amount of data elements (u8 or u16) to be received. * @param Timeout Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) { uint8_t *prxdata8bits; uint16_t *prxdata16bits; uint16_t uhMask; uint32_t tickstart; if (husart->State == HAL_USART_STATE_READY) { if ((pRxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_RX; /* Init tickstart for timeout managment*/ tickstart = HAL_GetTick(); husart->RxXferSize = Size; husart->RxXferCount = Size; /* Computation of USART mask to apply to RDR register */ USART_MASK_COMPUTATION(husart); uhMask = husart->Mask; /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { prxdata8bits = NULL; prxdata16bits = (uint16_t *) pRxData; } else { prxdata8bits = pRxData; prxdata16bits = NULL; } /* as long as data have to be received */ while (husart->RxXferCount > 0U) { if (husart->SlaveMode == USART_SLAVEMODE_DISABLE) { /* Wait until TXE flag is set to send dummy byte in order to generate the * clock for the slave to send data. * Whatever the frame length (7, 8 or 9-bit long), the same dummy value * can be written for all the cases. */ if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x0FF); } /* Wait for RXNE Flag */ if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (prxdata8bits == NULL) { *prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask); prxdata16bits++; } else { *prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); prxdata8bits++; } husart->RxXferCount--; } /* Clear SPI slave underrun flag and discard transmit data */ if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) { __HAL_USART_CLEAR_UDRFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* At end of Rx process, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Full-Duplex Send and Receive an amount of data in blocking mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number * of u16 available through pTxData and through pRxData. * @param husart USART handle. * @param pTxData pointer to TX data buffer (u8 or u16 data elements). * @param pRxData pointer to RX data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be sent (same amount to be received). * @param Timeout Timeout duration. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) { uint8_t *prxdata8bits; uint16_t *prxdata16bits; uint8_t *ptxdata8bits; uint16_t *ptxdata16bits; uint16_t uhMask; uint16_t rxdatacount; uint32_t tickstart; if (husart->State == HAL_USART_STATE_READY) { if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_RX; /* Init tickstart for timeout managment*/ tickstart = HAL_GetTick(); husart->RxXferSize = Size; husart->TxXferSize = Size; husart->TxXferCount = Size; husart->RxXferCount = Size; /* Computation of USART mask to apply to RDR register */ USART_MASK_COMPUTATION(husart); uhMask = husart->Mask; /* In case of 9bits/No Parity transfer, pRxData needs to be handled as a uint16_t pointer */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { prxdata8bits = NULL; ptxdata8bits = NULL; ptxdata16bits = (uint16_t *) pTxData; prxdata16bits = (uint16_t *) pRxData; } else { prxdata8bits = pRxData; ptxdata8bits = pTxData; ptxdata16bits = NULL; prxdata16bits = NULL; } if ((husart->TxXferCount == 0x01U) || (husart->SlaveMode == USART_SLAVEMODE_ENABLE)) { /* Wait until TXE flag is set to send data */ if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (ptxdata8bits == NULL) { husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask); ptxdata16bits++; } else { husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU)); ptxdata8bits++; } husart->TxXferCount--; } /* Check the remain data to be sent */ /* rxdatacount is a temporary variable for MISRAC2012-Rule-13.5 */ rxdatacount = husart->RxXferCount; while ((husart->TxXferCount > 0U) || (rxdatacount > 0U)) { if (husart->TxXferCount > 0U) { /* Wait until TXE flag is set to send data */ if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (ptxdata8bits == NULL) { husart->Instance->TDR = (uint16_t)(*ptxdata16bits & uhMask); ptxdata16bits++; } else { husart->Instance->TDR = (uint8_t)(*ptxdata8bits & (uint8_t)(uhMask & 0xFFU)); ptxdata8bits++; } husart->TxXferCount--; } if (husart->RxXferCount > 0U) { /* Wait for RXNE Flag */ if (USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK) { return HAL_TIMEOUT; } if (prxdata8bits == NULL) { *prxdata16bits = (uint16_t)(husart->Instance->RDR & uhMask); prxdata16bits++; } else { *prxdata8bits = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); prxdata8bits++; } husart->RxXferCount--; } rxdatacount = husart->RxXferCount; } /* At end of TxRx process, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Send an amount of data in interrupt mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data is handled as a set of u16. In this case, Size must indicate the number * of u16 provided through pTxData. * @param husart USART handle. * @param pTxData pointer to data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be sent. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) { if (husart->State == HAL_USART_STATE_READY) { if ((pTxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->pTxBuffPtr = pTxData; husart->TxXferSize = Size; husart->TxXferCount = Size; husart->TxISR = NULL; husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX; /* The USART Error Interrupts: (Frame error, noise error, overrun error) are not managed by the USART Transmit Process to avoid the overrun interrupt when the usart mode is configured for transmit and receive "USART_MODE_TX_RX" to benefit for the frame error and noise interrupts the usart mode should be configured only for transmit "USART_MODE_TX" */ /* Configure Tx interrupt processing */ if (husart->FifoMode == USART_FIFOMODE_ENABLE) { /* Set the Tx ISR function pointer according to the data word length */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { husart->TxISR = USART_TxISR_16BIT_FIFOEN; } else { husart->TxISR = USART_TxISR_8BIT_FIFOEN; } /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the TX FIFO threshold interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TXFT); } else { /* Set the Tx ISR function pointer according to the data word length */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { husart->TxISR = USART_TxISR_16BIT; } else { husart->TxISR = USART_TxISR_8BIT; } /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the USART Transmit Data Register Empty Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TXE); } return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in interrupt mode. * @note To receive synchronous data, dummy data are simultaneously transmitted. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of u16. In this case, Size must indicate the number * of u16 available through pRxData. * @param husart USART handle. * @param pRxData pointer to data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be received. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) { uint16_t nb_dummy_data; if (husart->State == HAL_USART_STATE_READY) { if ((pRxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->pRxBuffPtr = pRxData; husart->RxXferSize = Size; husart->RxXferCount = Size; husart->RxISR = NULL; USART_MASK_COMPUTATION(husart); husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_RX; /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ SET_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Configure Rx interrupt processing */ if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) { /* Set the Rx ISR function pointer according to the data word length */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { husart->RxISR = USART_RxISR_16BIT_FIFOEN; } else { husart->RxISR = USART_RxISR_8BIT_FIFOEN; } /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the USART Parity Error interrupt and RX FIFO Threshold interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); SET_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); } else { /* Set the Rx ISR function pointer according to the data word length */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { husart->RxISR = USART_RxISR_16BIT; } else { husart->RxISR = USART_RxISR_8BIT; } /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the USART Parity Error and Data Register not empty Interrupts */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); } if (husart->SlaveMode == USART_SLAVEMODE_DISABLE) { /* Send dummy data in order to generate the clock for the Slave to send the next data. When FIFO mode is disabled only one data must be transferred. When FIFO mode is enabled data must be transmitted until the RX FIFO reaches its threshold. */ if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) { for (nb_dummy_data = husart->NbRxDataToProcess ; nb_dummy_data > 0U ; nb_dummy_data--) { husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } } else { husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } } return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Full-Duplex Send and Receive an amount of data in interrupt mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number * of u16 available through pTxData and through pRxData. * @param husart USART handle. * @param pTxData pointer to TX data buffer (u8 or u16 data elements). * @param pRxData pointer to RX data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be sent (same amount to be received). * @retval HAL status */ HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { if (husart->State == HAL_USART_STATE_READY) { if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->pRxBuffPtr = pRxData; husart->RxXferSize = Size; husart->RxXferCount = Size; husart->pTxBuffPtr = pTxData; husart->TxXferSize = Size; husart->TxXferCount = Size; /* Computation of USART mask to apply to RDR register */ USART_MASK_COMPUTATION(husart); husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX_RX; /* Configure TxRx interrupt processing */ if ((husart->FifoMode == USART_FIFOMODE_ENABLE) && (Size >= husart->NbRxDataToProcess)) { /* Set the Rx ISR function pointer according to the data word length */ if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { husart->TxISR = USART_TxISR_16BIT_FIFOEN; husart->RxISR = USART_RxISR_16BIT_FIFOEN; } else { husart->TxISR = USART_TxISR_8BIT_FIFOEN; husart->RxISR = USART_RxISR_8BIT_FIFOEN; } /* Process Locked */ __HAL_UNLOCK(husart); /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ SET_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Enable the USART Parity Error interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); /* Enable the TX and RX FIFO Threshold interrupts */ SET_BIT(husart->Instance->CR3, (USART_CR3_TXFTIE | USART_CR3_RXFTIE)); } else { if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) { husart->TxISR = USART_TxISR_16BIT; husart->RxISR = USART_RxISR_16BIT; } else { husart->TxISR = USART_TxISR_8BIT; husart->RxISR = USART_RxISR_8BIT; } /* Process Locked */ __HAL_UNLOCK(husart); /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ SET_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Enable the USART Parity Error and USART Data Register not empty Interrupts */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE_RXFNEIE); /* Enable the USART Transmit Data Register Empty Interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_TXEIE_TXFNFIE); } return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Send an amount of data in DMA mode. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data is handled as a set of u16. In this case, Size must indicate the number * of u16 provided through pTxData. * @param husart USART handle. * @param pTxData pointer to data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be sent. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) { HAL_StatusTypeDef status = HAL_OK; uint32_t *tmp; if (husart->State == HAL_USART_STATE_READY) { if ((pTxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->pTxBuffPtr = pTxData; husart->TxXferSize = Size; husart->TxXferCount = Size; husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX; if (husart->hdmatx != NULL) { /* Set the USART DMA transfer complete callback */ husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; /* Set the USART DMA Half transfer complete callback */ husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; /* Set the DMA error callback */ husart->hdmatx->XferErrorCallback = USART_DMAError; /* Enable the USART transmit DMA channel */ tmp = (uint32_t *)&pTxData; status = HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, Size); } if (status == HAL_OK) { /* Clear the TC flag in the ICR register */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the DMA transfer for transmit request by setting the DMAT bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); return HAL_OK; } else { /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; /* Process Unlocked */ __HAL_UNLOCK(husart); /* Restore husart->State to ready */ husart->State = HAL_USART_STATE_READY; return HAL_ERROR; } } else { return HAL_BUSY; } } /** * @brief Receive an amount of data in DMA mode. * @note When the USART parity is enabled (PCE = 1), the received data contain * the parity bit (MSB position). * @note The USART DMA transmit channel must be configured in order to generate the clock for the slave. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the received data is handled as a set of u16. In this case, Size must indicate the number * of u16 available through pRxData. * @param husart USART handle. * @param pRxData pointer to data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be received. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) { HAL_StatusTypeDef status = HAL_OK; uint32_t *tmp = (uint32_t *)&pRxData; /* Check that a Rx process is not already ongoing */ if (husart->State == HAL_USART_STATE_READY) { if ((pRxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->pRxBuffPtr = pRxData; husart->RxXferSize = Size; husart->pTxBuffPtr = pRxData; husart->TxXferSize = Size; husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_RX; if (husart->hdmarx != NULL) { /* Set the USART DMA Rx transfer complete callback */ husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; /* Set the USART DMA Half transfer complete callback */ husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; /* Set the USART DMA Rx transfer error callback */ husart->hdmarx->XferErrorCallback = USART_DMAError; /* Enable the USART receive DMA channel */ status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t *)tmp, Size); } if ((status == HAL_OK) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Enable the USART transmit DMA channel: the transmit channel is used in order to generate in the non-blocking mode the clock to the slave device, this mode isn't a simplex receive mode but a full-duplex receive mode */ /* Set the USART DMA Tx Complete and Error callback to Null */ if (husart->hdmatx != NULL) { husart->hdmatx->XferErrorCallback = NULL; husart->hdmatx->XferHalfCpltCallback = NULL; husart->hdmatx->XferCpltCallback = NULL; status = HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, Size); } } if (status == HAL_OK) { /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the USART Parity Error Interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ SET_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Enable the DMA transfer for the receiver request by setting the DMAR bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* Enable the DMA transfer for transmit request by setting the DMAT bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); return HAL_OK; } else { if (husart->hdmarx != NULL) { status = HAL_DMA_Abort(husart->hdmarx); } /* No need to check on error code */ UNUSED(status); /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; /* Process Unlocked */ __HAL_UNLOCK(husart); /* Restore husart->State to ready */ husart->State = HAL_USART_STATE_READY; return HAL_ERROR; } } else { return HAL_BUSY; } } /** * @brief Full-Duplex Transmit Receive an amount of data in non-blocking mode. * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. * @note When UART parity is not enabled (PCE = 0), and Word Length is configured to 9 bits (M1-M0 = 01), * the sent data and the received data are handled as sets of u16. In this case, Size must indicate the number * of u16 available through pTxData and through pRxData. * @param husart USART handle. * @param pTxData pointer to TX data buffer (u8 or u16 data elements). * @param pRxData pointer to RX data buffer (u8 or u16 data elements). * @param Size amount of data elements (u8 or u16) to be received/sent. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) { HAL_StatusTypeDef status; uint32_t *tmp; if (husart->State == HAL_USART_STATE_READY) { if ((pTxData == NULL) || (pRxData == NULL) || (Size == 0U)) { return HAL_ERROR; } /* Process Locked */ __HAL_LOCK(husart); husart->pRxBuffPtr = pRxData; husart->RxXferSize = Size; husart->pTxBuffPtr = pTxData; husart->TxXferSize = Size; husart->ErrorCode = HAL_USART_ERROR_NONE; husart->State = HAL_USART_STATE_BUSY_TX_RX; if ((husart->hdmarx != NULL) && (husart->hdmatx != NULL)) { /* Set the USART DMA Rx transfer complete callback */ husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; /* Set the USART DMA Half transfer complete callback */ husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; /* Set the USART DMA Tx transfer complete callback */ husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; /* Set the USART DMA Half transfer complete callback */ husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; /* Set the USART DMA Tx transfer error callback */ husart->hdmatx->XferErrorCallback = USART_DMAError; /* Set the USART DMA Rx transfer error callback */ husart->hdmarx->XferErrorCallback = USART_DMAError; /* Enable the USART receive DMA channel */ tmp = (uint32_t *)&pRxData; status = HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t *)tmp, Size); /* Enable the USART transmit DMA channel */ if (status == HAL_OK) { tmp = (uint32_t *)&pTxData; status = HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t *)tmp, (uint32_t)&husart->Instance->TDR, Size); } } else { status = HAL_ERROR; } if (status == HAL_OK) { /* Process Unlocked */ __HAL_UNLOCK(husart); /* Enable the USART Parity Error Interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ SET_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Clear the TC flag in the ICR register */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_TCF); /* Enable the DMA transfer for the receiver request by setting the DMAR bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* Enable the DMA transfer for transmit request by setting the DMAT bit in the USART CR3 register */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); return HAL_OK; } else { if (husart->hdmarx != NULL) { status = HAL_DMA_Abort(husart->hdmarx); } /* No need to check on error code */ UNUSED(status); /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; /* Process Unlocked */ __HAL_UNLOCK(husart); /* Restore husart->State to ready */ husart->State = HAL_USART_STATE_READY; return HAL_ERROR; } } else { return HAL_BUSY; } } /** * @brief Pause the DMA Transfer. * @param husart USART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; /* Process Locked */ __HAL_LOCK(husart); if ((HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) && (state == HAL_USART_STATE_BUSY_TX)) { /* Disable the USART DMA Tx request */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); } else if ((state == HAL_USART_STATE_BUSY_RX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) { /* Disable the USART DMA Tx request */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); } if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) { /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Disable the USART DMA Rx request */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); } } else { /* Nothing to do */ } /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_OK; } /** * @brief Resume the DMA Transfer. * @param husart USART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; /* Process Locked */ __HAL_LOCK(husart); if (state == HAL_USART_STATE_BUSY_TX) { /* Enable the USART DMA Tx request */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); } else if ((state == HAL_USART_STATE_BUSY_RX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { /* Clear the Overrun flag before resuming the Rx transfer*/ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF); /* Reenable PE and ERR (Frame error, noise error, overrun error) interrupts */ SET_BIT(husart->Instance->CR1, USART_CR1_PEIE); SET_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Enable the USART DMA Rx request before the DMA Tx request */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* Enable the USART DMA Tx request */ SET_BIT(husart->Instance->CR3, USART_CR3_DMAT); } else { /* Nothing to do */ } /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_OK; } /** * @brief Stop the DMA Transfer. * @param husart USART handle. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart) { /* The Lock is not implemented on this API to allow the user application to call the HAL USART API under callbacks HAL_USART_TxCpltCallback() / HAL_USART_RxCpltCallback() / HAL_USART_TxHalfCpltCallback / HAL_USART_RxHalfCpltCallback: indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of the stream and the corresponding call back is executed. */ /* Disable the USART Tx/Rx DMA requests */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* Abort the USART DMA tx channel */ if (husart->hdmatx != NULL) { if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK) { if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; return HAL_TIMEOUT; } } } /* Abort the USART DMA rx channel */ if (husart->hdmarx != NULL) { if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK) { if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; return HAL_TIMEOUT; } } } USART_EndTransfer(husart); husart->State = HAL_USART_STATE_READY; return HAL_OK; } /** * @brief Abort ongoing transfers (blocking mode). * @param husart USART handle. * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable USART Interrupts (Tx and Rx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode) * - Set handle State to READY * @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed. * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Abort(USART_HandleTypeDef *husart) { /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); /* Disable the USART DMA Tx request if enabled */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) { CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); /* Abort the USART DMA Tx channel : use blocking DMA Abort API (no callback) */ if (husart->hdmatx != NULL) { /* Set the USART DMA Abort callback to Null. No call back execution at end of DMA abort procedure */ husart->hdmatx->XferAbortCallback = NULL; if (HAL_DMA_Abort(husart->hdmatx) != HAL_OK) { if (HAL_DMA_GetError(husart->hdmatx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; return HAL_TIMEOUT; } } } } /* Disable the USART DMA Rx request if enabled */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) { CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* Abort the USART DMA Rx channel : use blocking DMA Abort API (no callback) */ if (husart->hdmarx != NULL) { /* Set the USART DMA Abort callback to Null. No call back execution at end of DMA abort procedure */ husart->hdmarx->XferAbortCallback = NULL; if (HAL_DMA_Abort(husart->hdmarx) != HAL_OK) { if (HAL_DMA_GetError(husart->hdmarx) == HAL_DMA_ERROR_TIMEOUT) { /* Set error code to DMA */ husart->ErrorCode = HAL_USART_ERROR_DMA; return HAL_TIMEOUT; } } } } /* Reset Tx and Rx transfer counters */ husart->TxXferCount = 0U; husart->RxXferCount = 0U; /* Clear the Error flags in the ICR register */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); /* Flush the whole TX FIFO (if needed) */ if (husart->FifoMode == USART_FIFOMODE_ENABLE) { __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* Discard the received data */ __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); /* Restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* Reset Handle ErrorCode to No Error */ husart->ErrorCode = HAL_USART_ERROR_NONE; return HAL_OK; } /** * @brief Abort ongoing transfers (Interrupt mode). * @param husart USART handle. * @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode. * This procedure performs following operations : * - Disable USART Interrupts (Tx and Rx) * - Disable the DMA transfer in the peripheral register (if enabled) * - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode) * - Set handle State to READY * - At abort completion, call user abort complete callback * @note This procedure is executed in Interrupt mode, meaning that abort procedure could be * considered as completed only when user abort complete callback is executed (not when exiting function). * @retval HAL status */ HAL_StatusTypeDef HAL_USART_Abort_IT(USART_HandleTypeDef *husart) { uint32_t abortcplt = 1U; /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); /* If DMA Tx and/or DMA Rx Handles are associated to USART Handle, DMA Abort complete callbacks should be initialised before any call to DMA Abort functions */ /* DMA Tx Handle is valid */ if (husart->hdmatx != NULL) { /* Set DMA Abort Complete callback if USART DMA Tx request if enabled. Otherwise, set it to NULL */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) { husart->hdmatx->XferAbortCallback = USART_DMATxAbortCallback; } else { husart->hdmatx->XferAbortCallback = NULL; } } /* DMA Rx Handle is valid */ if (husart->hdmarx != NULL) { /* Set DMA Abort Complete callback if USART DMA Rx request if enabled. Otherwise, set it to NULL */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) { husart->hdmarx->XferAbortCallback = USART_DMARxAbortCallback; } else { husart->hdmarx->XferAbortCallback = NULL; } } /* Disable the USART DMA Tx request if enabled */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAT)) { /* Disable DMA Tx at USART level */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); /* Abort the USART DMA Tx channel : use non blocking DMA Abort API (callback) */ if (husart->hdmatx != NULL) { /* USART Tx DMA Abort callback has already been initialised : will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ /* Abort DMA TX */ if (HAL_DMA_Abort_IT(husart->hdmatx) != HAL_OK) { husart->hdmatx->XferAbortCallback = NULL; } else { abortcplt = 0U; } } } /* Disable the USART DMA Rx request if enabled */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) { CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* Abort the USART DMA Rx channel : use non blocking DMA Abort API (callback) */ if (husart->hdmarx != NULL) { /* USART Rx DMA Abort callback has already been initialised : will lead to call HAL_USART_AbortCpltCallback() at end of DMA abort procedure */ /* Abort DMA RX */ if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) { husart->hdmarx->XferAbortCallback = NULL; abortcplt = 1U; } else { abortcplt = 0U; } } } /* if no DMA abort complete callback execution is required => call user Abort Complete callback */ if (abortcplt == 1U) { /* Reset Tx and Rx transfer counters */ husart->TxXferCount = 0U; husart->RxXferCount = 0U; /* Reset errorCode */ husart->ErrorCode = HAL_USART_ERROR_NONE; /* Clear the Error flags in the ICR register */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); /* Flush the whole TX FIFO (if needed) */ if (husart->FifoMode == USART_FIFOMODE_ENABLE) { __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* Discard the received data */ __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); /* Restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* As no DMA to be aborted, call directly user Abort complete callback */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Abort Complete Callback */ husart->AbortCpltCallback(husart); #else /* Call legacy weak Abort Complete Callback */ HAL_USART_AbortCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } return HAL_OK; } /** * @brief Handle USART interrupt request. * @param husart USART handle. * @retval None */ void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) { uint32_t isrflags = READ_REG(husart->Instance->ISR); uint32_t cr1its = READ_REG(husart->Instance->CR1); uint32_t cr3its = READ_REG(husart->Instance->CR3); uint32_t errorflags; uint32_t errorcode; /* If no error occurs */ errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE | USART_ISR_UDR)); if (errorflags == 0U) { /* USART in mode Receiver ---------------------------------------------------*/ if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_RXFTIE) != 0U))) { if (husart->RxISR != NULL) { husart->RxISR(husart); } return; } } /* If some errors occur */ if ((errorflags != 0U) && (((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U) || ((cr1its & (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)) != 0U))) { /* USART parity error interrupt occurred -------------------------------------*/ if (((isrflags & USART_ISR_PE) != 0U) && ((cr1its & USART_CR1_PEIE) != 0U)) { __HAL_USART_CLEAR_IT(husart, USART_CLEAR_PEF); husart->ErrorCode |= HAL_USART_ERROR_PE; } /* USART frame error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_FE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_USART_CLEAR_IT(husart, USART_CLEAR_FEF); husart->ErrorCode |= HAL_USART_ERROR_FE; } /* USART noise error interrupt occurred --------------------------------------*/ if (((isrflags & USART_ISR_NE) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { __HAL_USART_CLEAR_IT(husart, USART_CLEAR_NEF); husart->ErrorCode |= HAL_USART_ERROR_NE; } /* USART Over-Run interrupt occurred -----------------------------------------*/ if (((isrflags & USART_ISR_ORE) != 0U) && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & (USART_CR3_RXFTIE | USART_CR3_EIE)) != 0U))) { __HAL_USART_CLEAR_IT(husart, USART_CLEAR_OREF); husart->ErrorCode |= HAL_USART_ERROR_ORE; } /* USART SPI slave underrun error interrupt occurred -------------------------*/ if (((isrflags & USART_ISR_UDR) != 0U) && ((cr3its & USART_CR3_EIE) != 0U)) { /* Ignore SPI slave underrun errors when reception is going on */ if (husart->State == HAL_USART_STATE_BUSY_RX) { __HAL_USART_CLEAR_UDRFLAG(husart); return; } else { __HAL_USART_CLEAR_UDRFLAG(husart); husart->ErrorCode |= HAL_USART_ERROR_UDR; } } /* Call USART Error Call back function if need be --------------------------*/ if (husart->ErrorCode != HAL_USART_ERROR_NONE) { /* USART in mode Receiver ---------------------------------------------------*/ if (((isrflags & USART_ISR_RXNE_RXFNE) != 0U) && (((cr1its & USART_CR1_RXNEIE_RXFNEIE) != 0U) || ((cr3its & USART_CR3_RXFTIE) != 0U))) { if (husart->RxISR != NULL) { husart->RxISR(husart); } } /* If Overrun error occurs, or if any error occurs in DMA mode reception, consider error as blocking */ errorcode = husart->ErrorCode & HAL_USART_ERROR_ORE; if ((HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) || (errorcode != 0U)) { /* Blocking error : transfer is aborted Set the USART state ready to be able to start again the process, Disable Interrupts, and disable DMA requests, if ongoing */ USART_EndTransfer(husart); /* Disable the USART DMA Rx request if enabled */ if (HAL_IS_BIT_SET(husart->Instance->CR3, USART_CR3_DMAR)) { CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR | USART_CR3_DMAR); /* Abort the USART DMA Tx channel */ if (husart->hdmatx != NULL) { /* Set the USART Tx DMA Abort callback to NULL : no callback executed at end of DMA abort procedure */ husart->hdmatx->XferAbortCallback = NULL; /* Abort DMA TX */ (void)HAL_DMA_Abort_IT(husart->hdmatx); } /* Abort the USART DMA Rx channel */ if (husart->hdmarx != NULL) { /* Set the USART Rx DMA Abort callback : will lead to call HAL_USART_ErrorCallback() at end of DMA abort procedure */ husart->hdmarx->XferAbortCallback = USART_DMAAbortOnError; /* Abort DMA RX */ if (HAL_DMA_Abort_IT(husart->hdmarx) != HAL_OK) { /* Call Directly husart->hdmarx->XferAbortCallback function in case of error */ husart->hdmarx->XferAbortCallback(husart->hdmarx); } } else { /* Call user error callback */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Error Callback */ husart->ErrorCallback(husart); #else /* Call legacy weak Error Callback */ HAL_USART_ErrorCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } } else { /* Call user error callback */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Error Callback */ husart->ErrorCallback(husart); #else /* Call legacy weak Error Callback */ HAL_USART_ErrorCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } } else { /* Non Blocking error : transfer could go on. Error is notified to user through user error callback */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Error Callback */ husart->ErrorCallback(husart); #else /* Call legacy weak Error Callback */ HAL_USART_ErrorCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ husart->ErrorCode = HAL_USART_ERROR_NONE; } } return; } /* End if some error occurs */ /* USART in mode Transmitter ------------------------------------------------*/ if (((isrflags & USART_ISR_TXE_TXFNF) != 0U) && (((cr1its & USART_CR1_TXEIE_TXFNFIE) != 0U) || ((cr3its & USART_CR3_TXFTIE) != 0U))) { if (husart->TxISR != NULL) { husart->TxISR(husart); } return; } /* USART in mode Transmitter (transmission end) -----------------------------*/ if (((isrflags & USART_ISR_TC) != 0U) && ((cr1its & USART_CR1_TCIE) != 0U)) { USART_EndTransmit_IT(husart); return; } /* USART TX Fifo Empty occurred ----------------------------------------------*/ if (((isrflags & USART_ISR_TXFE) != 0U) && ((cr1its & USART_CR1_TXFEIE) != 0U)) { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Fifo Empty Callback */ husart->TxFifoEmptyCallback(husart); #else /* Call legacy weak Tx Fifo Empty Callback */ HAL_USARTEx_TxFifoEmptyCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ return; } /* USART RX Fifo Full occurred ----------------------------------------------*/ if (((isrflags & USART_ISR_RXFF) != 0U) && ((cr1its & USART_CR1_RXFFIE) != 0U)) { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Fifo Full Callback */ husart->RxFifoFullCallback(husart); #else /* Call legacy weak Rx Fifo Full Callback */ HAL_USARTEx_RxFifoFullCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ return; } } /** * @brief Tx Transfer completed callback. * @param husart USART handle. * @retval None */ __weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_TxCpltCallback can be implemented in the user file. */ } /** * @brief Tx Half Transfer completed callback. * @param husart USART handle. * @retval None */ __weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, the HAL_USART_TxHalfCpltCallback can be implemented in the user file. */ } /** * @brief Rx Transfer completed callback. * @param husart USART handle. * @retval None */ __weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE: This function should not be modified, when the callback is needed, the HAL_USART_RxCpltCallback can be implemented in the user file. */ } /** * @brief Rx Half Transfer completed callback. * @param husart USART handle. * @retval None */ __weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_RxHalfCpltCallback can be implemented in the user file */ } /** * @brief Tx/Rx Transfers completed callback for the non-blocking process. * @param husart USART handle. * @retval None */ __weak void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_TxRxCpltCallback can be implemented in the user file */ } /** * @brief USART error callback. * @param husart USART handle. * @retval None */ __weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_ErrorCallback can be implemented in the user file. */ } /** * @brief USART Abort Complete callback. * @param husart USART handle. * @retval None */ __weak void HAL_USART_AbortCpltCallback(USART_HandleTypeDef *husart) { /* Prevent unused argument(s) compilation warning */ UNUSED(husart); /* NOTE : This function should not be modified, when the callback is needed, the HAL_USART_AbortCpltCallback can be implemented in the user file. */ } /** * @} */ /** @defgroup USART_Exported_Functions_Group4 Peripheral State and Error functions * @brief USART Peripheral State and Error functions * @verbatim ============================================================================== ##### Peripheral State and Error functions ##### ============================================================================== [..] This subsection provides functions allowing to : (+) Return the USART handle state (+) Return the USART handle error code @endverbatim * @{ */ /** * @brief Return the USART handle state. * @param husart pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART. * @retval USART handle state */ HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart) { return husart->State; } /** * @brief Return the USART error code. * @param husart pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART. * @retval USART handle Error Code */ uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart) { return husart->ErrorCode; } /** * @} */ /** * @} */ /** @defgroup USART_Private_Functions USART Private Functions * @{ */ /** * @brief Initialize the callbacks to their default values. * @param husart USART handle. * @retval none */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) void USART_InitCallbacksToDefault(USART_HandleTypeDef *husart) { /* Init the USART Callback settings */ husart->TxHalfCpltCallback = HAL_USART_TxHalfCpltCallback; /* Legacy weak TxHalfCpltCallback */ husart->TxCpltCallback = HAL_USART_TxCpltCallback; /* Legacy weak TxCpltCallback */ husart->RxHalfCpltCallback = HAL_USART_RxHalfCpltCallback; /* Legacy weak RxHalfCpltCallback */ husart->RxCpltCallback = HAL_USART_RxCpltCallback; /* Legacy weak RxCpltCallback */ husart->TxRxCpltCallback = HAL_USART_TxRxCpltCallback; /* Legacy weak TxRxCpltCallback */ husart->ErrorCallback = HAL_USART_ErrorCallback; /* Legacy weak ErrorCallback */ husart->AbortCpltCallback = HAL_USART_AbortCpltCallback; /* Legacy weak AbortCpltCallback */ husart->RxFifoFullCallback = HAL_USARTEx_RxFifoFullCallback; /* Legacy weak RxFifoFullCallback */ husart->TxFifoEmptyCallback = HAL_USARTEx_TxFifoEmptyCallback; /* Legacy weak TxFifoEmptyCallback */ } #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ /** * @brief End ongoing transfer on USART peripheral (following error detection or Transfer completion). * @param husart USART handle. * @retval None */ static void USART_EndTransfer(USART_HandleTypeDef *husart) { /* Disable TXEIE, TCIE, RXNE, RXFT, TXFT, PE and ERR (Frame error, noise error, overrun error) interrupts */ CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE | USART_CR1_TXEIE_TXFNFIE | USART_CR1_TCIE)); CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE | USART_CR3_TXFTIE)); /* At end of process, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; } /** * @brief DMA USART transmit process complete callback. * @param hdma DMA handle. * @retval None */ static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); /* DMA Normal mode */ if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) { husart->TxXferCount = 0U; if (husart->State == HAL_USART_STATE_BUSY_TX) { /* Disable the DMA transfer for transmit request by resetting the DMAT bit in the USART CR3 register */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); } } /* DMA Circular mode */ else { if (husart->State == HAL_USART_STATE_BUSY_TX) { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Complete Callback */ husart->TxCpltCallback(husart); #else /* Call legacy weak Tx Complete Callback */ HAL_USART_TxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } } } /** * @brief DMA USART transmit process half complete callback. * @param hdma DMA handle. * @retval None */ static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Half Complete Callback */ husart->TxHalfCpltCallback(husart); #else /* Call legacy weak Tx Half Complete Callback */ HAL_USART_TxHalfCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /** * @brief DMA USART receive process complete callback. * @param hdma DMA handle. * @retval None */ static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); /* DMA Normal mode */ if (HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC)) { husart->RxXferCount = 0U; /* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */ CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Disable the DMA RX transfer for the receiver request by resetting the DMAR bit in USART CR3 register */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAR); /* similarly, disable the DMA TX transfer that was started to provide the clock to the slave device */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_DMAT); if (husart->State == HAL_USART_STATE_BUSY_RX) { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Complete Callback */ husart->RxCpltCallback(husart); #else /* Call legacy weak Rx Complete Callback */ HAL_USART_RxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ else { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } husart->State = HAL_USART_STATE_READY; } /* DMA circular mode */ else { if (husart->State == HAL_USART_STATE_BUSY_RX) { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Complete Callback */ husart->RxCpltCallback(husart); #else /* Call legacy weak Rx Complete Callback */ HAL_USART_RxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /* The USART state is HAL_USART_STATE_BUSY_TX_RX */ else { #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } } } /** * @brief DMA USART receive process half complete callback. * @param hdma DMA handle. * @retval None */ static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Half Complete Callback */ husart->RxHalfCpltCallback(husart); #else /* Call legacy weak Rx Half Complete Callback */ HAL_USART_RxHalfCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /** * @brief DMA USART communication error callback. * @param hdma DMA handle. * @retval None */ static void USART_DMAError(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); husart->RxXferCount = 0U; husart->TxXferCount = 0U; USART_EndTransfer(husart); husart->ErrorCode |= HAL_USART_ERROR_DMA; husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Error Callback */ husart->ErrorCallback(husart); #else /* Call legacy weak Error Callback */ HAL_USART_ErrorCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /** * @brief DMA USART communication abort callback, when initiated by HAL services on Error * (To be called at end of DMA Abort procedure following error occurrence). * @param hdma DMA handle. * @retval None */ static void USART_DMAAbortOnError(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); husart->RxXferCount = 0U; husart->TxXferCount = 0U; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Error Callback */ husart->ErrorCallback(husart); #else /* Call legacy weak Error Callback */ HAL_USART_ErrorCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /** * @brief DMA USART Tx communication abort callback, when initiated by user * (To be called at end of DMA Tx Abort procedure following user abort request). * @note When this callback is executed, User Abort complete call back is called only if no * Abort still ongoing for Rx DMA Handle. * @param hdma DMA handle. * @retval None */ static void USART_DMATxAbortCallback(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); husart->hdmatx->XferAbortCallback = NULL; /* Check if an Abort process is still ongoing */ if (husart->hdmarx != NULL) { if (husart->hdmarx->XferAbortCallback != NULL) { return; } } /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ husart->TxXferCount = 0U; husart->RxXferCount = 0U; /* Reset errorCode */ husart->ErrorCode = HAL_USART_ERROR_NONE; /* Clear the Error flags in the ICR register */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); /* Restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* Call user Abort complete callback */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Abort Complete Callback */ husart->AbortCpltCallback(husart); #else /* Call legacy weak Abort Complete Callback */ HAL_USART_AbortCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /** * @brief DMA USART Rx communication abort callback, when initiated by user * (To be called at end of DMA Rx Abort procedure following user abort request). * @note When this callback is executed, User Abort complete call back is called only if no * Abort still ongoing for Tx DMA Handle. * @param hdma DMA handle. * @retval None */ static void USART_DMARxAbortCallback(DMA_HandleTypeDef *hdma) { USART_HandleTypeDef *husart = (USART_HandleTypeDef *)(hdma->Parent); husart->hdmarx->XferAbortCallback = NULL; /* Check if an Abort process is still ongoing */ if (husart->hdmatx != NULL) { if (husart->hdmatx->XferAbortCallback != NULL) { return; } } /* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */ husart->TxXferCount = 0U; husart->RxXferCount = 0U; /* Reset errorCode */ husart->ErrorCode = HAL_USART_ERROR_NONE; /* Clear the Error flags in the ICR register */ __HAL_USART_CLEAR_FLAG(husart, USART_CLEAR_OREF | USART_CLEAR_NEF | USART_CLEAR_PEF | USART_CLEAR_FEF); /* Restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; /* Call user Abort complete callback */ #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Abort Complete Callback */ husart->AbortCpltCallback(husart); #else /* Call legacy weak Abort Complete Callback */ HAL_USART_AbortCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } /** * @brief Handle USART Communication Timeout. * @param husart USART handle. * @param Flag Specifies the USART flag to check. * @param Status the Flag status (SET or RESET). * @param Tickstart Tick start value * @param Timeout timeout duration. * @retval HAL status */ static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout) { /* Wait until flag is set */ while ((__HAL_USART_GET_FLAG(husart, Flag) ? SET : RESET) == Status) { /* Check for the Timeout */ if (Timeout != HAL_MAX_DELAY) { if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0U)) { husart->State = HAL_USART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_TIMEOUT; } } } return HAL_OK; } /** * @brief Configure the USART peripheral. * @param husart USART handle. * @retval HAL status */ static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart) { uint32_t tmpreg; USART_ClockSourceTypeDef clocksource; HAL_StatusTypeDef ret = HAL_OK; uint16_t brrtemp; uint32_t usartdiv = 0x00000000; uint32_t pclk; /* Check the parameters */ assert_param(IS_USART_POLARITY(husart->Init.CLKPolarity)); assert_param(IS_USART_PHASE(husart->Init.CLKPhase)); assert_param(IS_USART_LASTBIT(husart->Init.CLKLastBit)); assert_param(IS_USART_BAUDRATE(husart->Init.BaudRate)); assert_param(IS_USART_WORD_LENGTH(husart->Init.WordLength)); assert_param(IS_USART_STOPBITS(husart->Init.StopBits)); assert_param(IS_USART_PARITY(husart->Init.Parity)); assert_param(IS_USART_MODE(husart->Init.Mode)); assert_param(IS_USART_PRESCALER(husart->Init.ClockPrescaler)); /*-------------------------- USART CR1 Configuration -----------------------*/ /* Clear M, PCE, PS, TE and RE bits and configure * the USART Word Length, Parity and Mode: * set the M bits according to husart->Init.WordLength value * set PCE and PS bits according to husart->Init.Parity value * set TE and RE bits according to husart->Init.Mode value * force OVER8 to 1 to allow to reach the maximum speed (Fclock/8) */ tmpreg = (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode | USART_CR1_OVER8; MODIFY_REG(husart->Instance->CR1, USART_CR1_FIELDS, tmpreg); /*---------------------------- USART CR2 Configuration ---------------------*/ /* Clear and configure the USART Clock, CPOL, CPHA, LBCL STOP and SLVEN bits: * set CPOL bit according to husart->Init.CLKPolarity value * set CPHA bit according to husart->Init.CLKPhase value * set LBCL bit according to husart->Init.CLKLastBit value (used in SPI master mode only) * set STOP[13:12] bits according to husart->Init.StopBits value */ tmpreg = (uint32_t)(USART_CLOCK_ENABLE); tmpreg |= (uint32_t)husart->Init.CLKLastBit; tmpreg |= ((uint32_t)husart->Init.CLKPolarity | (uint32_t)husart->Init.CLKPhase); tmpreg |= (uint32_t)husart->Init.StopBits; MODIFY_REG(husart->Instance->CR2, USART_CR2_FIELDS, tmpreg); /*-------------------------- USART PRESC Configuration -----------------------*/ /* Configure * - USART Clock Prescaler : set PRESCALER according to husart->Init.ClockPrescaler value */ MODIFY_REG(husart->Instance->PRESC, USART_PRESC_PRESCALER, husart->Init.ClockPrescaler); /*-------------------------- USART BRR Configuration -----------------------*/ /* BRR is filled-up according to OVER8 bit setting which is forced to 1 */ USART_GETCLOCKSOURCE(husart, clocksource); switch (clocksource) { case USART_CLOCKSOURCE_PCLK1: pclk = HAL_RCC_GetPCLK1Freq(); usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); break; case USART_CLOCKSOURCE_PCLK2: pclk = HAL_RCC_GetPCLK2Freq(); usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); break; case USART_CLOCKSOURCE_HSI: usartdiv = (uint32_t)(USART_DIV_SAMPLING8(HSI_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); break; case USART_CLOCKSOURCE_SYSCLK: pclk = HAL_RCC_GetSysClockFreq(); usartdiv = (uint32_t)(USART_DIV_SAMPLING8(pclk, husart->Init.BaudRate, husart->Init.ClockPrescaler)); break; case USART_CLOCKSOURCE_LSE: usartdiv = (uint32_t)(USART_DIV_SAMPLING8(LSE_VALUE, husart->Init.BaudRate, husart->Init.ClockPrescaler)); break; default: ret = HAL_ERROR; break; } /* USARTDIV must be greater than or equal to 0d16 and smaller than or equal to ffff */ if ((usartdiv >= USART_BRR_MIN) && (usartdiv <= USART_BRR_MAX)) { brrtemp = (uint16_t)(usartdiv & 0xFFF0U); brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U); husart->Instance->BRR = brrtemp; } else { ret = HAL_ERROR; } /* Initialize the number of data to process during RX/TX ISR execution */ husart->NbTxDataToProcess = 1U; husart->NbRxDataToProcess = 1U; /* Clear ISR function pointers */ husart->RxISR = NULL; husart->TxISR = NULL; return ret; } /** * @brief Check the USART Idle State. * @param husart USART handle. * @retval HAL status */ static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart) { uint32_t tickstart; /* Initialize the USART ErrorCode */ husart->ErrorCode = HAL_USART_ERROR_NONE; /* Init tickstart for timeout managment*/ tickstart = HAL_GetTick(); /* Check if the Transmitter is enabled */ if ((husart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) { /* Wait until TEACK flag is set */ if (USART_WaitOnFlagUntilTimeout(husart, USART_ISR_TEACK, RESET, tickstart, USART_TEACK_REACK_TIMEOUT) != HAL_OK) { /* Timeout occurred */ return HAL_TIMEOUT; } } /* Check if the Receiver is enabled */ if ((husart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) { /* Wait until REACK flag is set */ if (USART_WaitOnFlagUntilTimeout(husart, USART_ISR_REACK, RESET, tickstart, USART_TEACK_REACK_TIMEOUT) != HAL_OK) { /* Timeout occurred */ return HAL_TIMEOUT; } } /* Initialize the USART state*/ husart->State = HAL_USART_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(husart); return HAL_OK; } /** * @brief Simplex send an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Transmit_IT(). * @note The USART errors are not managed to avoid the overrun error. * @note ISR function executed when FIFO mode is disabled and when the * data word length is less than 9 bits long. * @param husart USART handle. * @retval None */ static void USART_TxISR_8BIT(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; /* Check that a Tx process is ongoing */ if ((state == HAL_USART_STATE_BUSY_TX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { if (husart->TxXferCount == 0U) { /* Disable the USART Transmit data register empty interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); } else { husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr & (uint8_t)0xFF); husart->pTxBuffPtr++; husart->TxXferCount--; } } } /** * @brief Simplex send an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Transmit_IT(). * @note The USART errors are not managed to avoid the overrun error. * @note ISR function executed when FIFO mode is disabled and when the * data word length is 9 bits long. * @param husart USART handle. * @retval None */ static void USART_TxISR_16BIT(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; uint16_t *tmp; if ((state == HAL_USART_STATE_BUSY_TX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { if (husart->TxXferCount == 0U) { /* Disable the USART Transmit data register empty interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); } else { tmp = (uint16_t *) husart->pTxBuffPtr; husart->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); husart->pTxBuffPtr += 2U; husart->TxXferCount--; } } } /** * @brief Simplex send an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Transmit_IT(). * @note The USART errors are not managed to avoid the overrun error. * @note ISR function executed when FIFO mode is enabled and when the * data word length is less than 9 bits long. * @param husart USART handle. * @retval None */ static void USART_TxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; uint16_t nb_tx_data; /* Check that a Tx process is ongoing */ if ((state == HAL_USART_STATE_BUSY_TX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { for (nb_tx_data = husart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) { if (husart->TxXferCount == 0U) { /* Disable the TX FIFO threshold interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TXFT); /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); break; /* force exit loop */ } else if (__HAL_USART_GET_FLAG(husart, USART_FLAG_TXFNF) == SET) { husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr & (uint8_t)0xFF); husart->pTxBuffPtr++; husart->TxXferCount--; } else { /* Nothing to do */ } } } } /** * @brief Simplex send an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Transmit_IT(). * @note The USART errors are not managed to avoid the overrun error. * @note ISR function executed when FIFO mode is enabled and when the * data word length is 9 bits long. * @param husart USART handle. * @retval None */ static void USART_TxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; uint16_t *tmp; uint16_t nb_tx_data; /* Check that a Tx process is ongoing */ if ((state == HAL_USART_STATE_BUSY_TX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { for (nb_tx_data = husart->NbTxDataToProcess ; nb_tx_data > 0U ; nb_tx_data--) { if (husart->TxXferCount == 0U) { /* Disable the TX FIFO threshold interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TXFT); /* Enable the USART Transmit Complete Interrupt */ __HAL_USART_ENABLE_IT(husart, USART_IT_TC); break; /* force exit loop */ } else if (__HAL_USART_GET_FLAG(husart, USART_FLAG_TXFNF) == SET) { tmp = (uint16_t *) husart->pTxBuffPtr; husart->Instance->TDR = (uint16_t)(*tmp & 0x01FFU); husart->pTxBuffPtr += 2U; husart->TxXferCount--; } else { /* Nothing to do */ } } } } /** * @brief Wraps up transmission in non-blocking mode. * @param husart Pointer to a USART_HandleTypeDef structure that contains * the configuration information for the specified USART module. * @retval None */ static void USART_EndTransmit_IT(USART_HandleTypeDef *husart) { /* Disable the USART Transmit Complete Interrupt */ __HAL_USART_DISABLE_IT(husart, USART_IT_TC); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); /* Clear TxISR function pointer */ husart->TxISR = NULL; if (husart->State == HAL_USART_STATE_BUSY_TX) { /* Clear overrun flag and discard the received data */ __HAL_USART_CLEAR_OREFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); /* Tx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Complete Callback */ husart->TxCpltCallback(husart); #else /* Call legacy weak Tx Complete Callback */ HAL_USART_TxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else if (husart->RxXferCount == 0U) { /* TxRx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } /** * @brief Simplex receive an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Receive_IT(). * @note ISR function executed when FIFO mode is disabled and when the * data word length is less than 9 bits long. * @param husart USART handle * @retval None */ static void USART_RxISR_8BIT(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; uint16_t txdatacount; uint16_t uhMask = husart->Mask; uint32_t txftie; if ((state == HAL_USART_STATE_BUSY_RX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { *husart->pRxBuffPtr = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); husart->pRxBuffPtr++; husart->RxXferCount--; if (husart->RxXferCount == 0U) { /* Disable the USART Parity Error Interrupt and RXNE interrupt*/ CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Clear RxISR function pointer */ husart->RxISR = NULL; /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); txdatacount = husart->TxXferCount; if (state == HAL_USART_STATE_BUSY_RX) { /* Clear SPI slave underrun flag and discard transmit data */ if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) { __HAL_USART_CLEAR_UDRFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* Rx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Complete Callback */ husart->RxCpltCallback(husart); #else /* Call legacy weak Rx Complete Callback */ HAL_USART_RxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && (txftie != USART_CR3_TXFTIE) && (txdatacount == 0U)) { /* TxRx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } else if ((state == HAL_USART_STATE_BUSY_RX) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } else { /* Nothing to do */ } } } /** * @brief Simplex receive an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Receive_IT(). * @note ISR function executed when FIFO mode is disabled and when the * data word length is 9 bits long. * @param husart USART handle * @retval None */ static void USART_RxISR_16BIT(USART_HandleTypeDef *husart) { const HAL_USART_StateTypeDef state = husart->State; uint16_t txdatacount; uint16_t *tmp; uint16_t uhMask = husart->Mask; uint32_t txftie; if ((state == HAL_USART_STATE_BUSY_RX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { tmp = (uint16_t *) husart->pRxBuffPtr; *tmp = (uint16_t)(husart->Instance->RDR & uhMask); husart->pRxBuffPtr += 2U; husart->RxXferCount--; if (husart->RxXferCount == 0U) { /* Disable the USART Parity Error Interrupt and RXNE interrupt*/ CLEAR_BIT(husart->Instance->CR1, (USART_CR1_RXNEIE_RXFNEIE | USART_CR1_PEIE)); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ CLEAR_BIT(husart->Instance->CR3, USART_CR3_EIE); /* Clear RxISR function pointer */ husart->RxISR = NULL; /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); txdatacount = husart->TxXferCount; if (state == HAL_USART_STATE_BUSY_RX) { /* Clear SPI slave underrun flag and discard transmit data */ if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) { __HAL_USART_CLEAR_UDRFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* Rx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Complete Callback */ husart->RxCpltCallback(husart); #else /* Call legacy weak Rx Complete Callback */ HAL_USART_RxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && (txftie != USART_CR3_TXFTIE) && (txdatacount == 0U)) { /* TxRx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } else if ((state == HAL_USART_STATE_BUSY_RX) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } else { /* Nothing to do */ } } } /** * @brief Simplex receive an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Receive_IT(). * @note ISR function executed when FIFO mode is enabled and when the * data word length is less than 9 bits long. * @param husart USART handle * @retval None */ static void USART_RxISR_8BIT_FIFOEN(USART_HandleTypeDef *husart) { HAL_USART_StateTypeDef state = husart->State; uint16_t txdatacount; uint16_t rxdatacount; uint16_t uhMask = husart->Mask; uint16_t nb_rx_data; uint32_t txftie; /* Check that a Rx process is ongoing */ if ((state == HAL_USART_STATE_BUSY_RX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { for (nb_rx_data = husart->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) { if (__HAL_USART_GET_FLAG(husart, USART_FLAG_RXFNE) == SET) { *husart->pRxBuffPtr = (uint8_t)(husart->Instance->RDR & (uint8_t)(uhMask & 0xFFU)); husart->pRxBuffPtr++; husart->RxXferCount--; if (husart->RxXferCount == 0U) { /* Disable the USART Parity Error Interrupt */ CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* Clear RxISR function pointer */ husart->RxISR = NULL; /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); txdatacount = husart->TxXferCount; if (state == HAL_USART_STATE_BUSY_RX) { /* Clear SPI slave underrun flag and discard transmit data */ if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) { __HAL_USART_CLEAR_UDRFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* Rx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; state = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Complete Callback */ husart->RxCpltCallback(husart); #else /* Call legacy weak Rx Complete Callback */ HAL_USART_RxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && (txftie != USART_CR3_TXFTIE) && (txdatacount == 0U)) { /* TxRx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; state = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } else if ((state == HAL_USART_STATE_BUSY_RX) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } else { /* Nothing to do */ } } } /* When remaining number of bytes to receive is less than the RX FIFO threshold, next incoming frames are processed as if FIFO mode was disabled (i.e. one interrupt per received frame). */ rxdatacount = husart->RxXferCount; if (((rxdatacount != 0U)) && (rxdatacount < husart->NbRxDataToProcess)) { /* Disable the USART RXFT interrupt*/ CLEAR_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); /* Update the RxISR function pointer */ husart->RxISR = USART_RxISR_8BIT; /* Enable the USART Data Register Not Empty interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); if ((husart->TxXferCount == 0U) && (state == HAL_USART_STATE_BUSY_TX_RX) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } } } else { /* Clear RXNE interrupt flag */ __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); } } /** * @brief Simplex receive an amount of data in non-blocking mode. * @note Function called under interruption only, once * interruptions have been enabled by HAL_USART_Receive_IT(). * @note ISR function executed when FIFO mode is enabled and when the * data word length is 9 bits long. * @param husart USART handle * @retval None */ static void USART_RxISR_16BIT_FIFOEN(USART_HandleTypeDef *husart) { HAL_USART_StateTypeDef state = husart->State; uint16_t txdatacount; uint16_t rxdatacount; uint16_t *tmp; uint16_t uhMask = husart->Mask; uint16_t nb_rx_data; uint32_t txftie; /* Check that a Tx process is ongoing */ if ((state == HAL_USART_STATE_BUSY_RX) || (state == HAL_USART_STATE_BUSY_TX_RX)) { for (nb_rx_data = husart->NbRxDataToProcess ; nb_rx_data > 0U ; nb_rx_data--) { if (__HAL_USART_GET_FLAG(husart, USART_FLAG_RXFNE) == SET) { tmp = (uint16_t *) husart->pRxBuffPtr; *tmp = (uint16_t)(husart->Instance->RDR & uhMask); husart->pRxBuffPtr += 2U; husart->RxXferCount--; if (husart->RxXferCount == 0U) { /* Disable the USART Parity Error Interrupt */ CLEAR_BIT(husart->Instance->CR1, USART_CR1_PEIE); /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) and RX FIFO Threshold interrupt */ CLEAR_BIT(husart->Instance->CR3, (USART_CR3_EIE | USART_CR3_RXFTIE)); /* Clear RxISR function pointer */ husart->RxISR = NULL; /* txftie and txdatacount are temporary variables for MISRAC2012-Rule-13.5 */ txftie = READ_BIT(husart->Instance->CR3, USART_CR3_TXFTIE); txdatacount = husart->TxXferCount; if (state == HAL_USART_STATE_BUSY_RX) { /* Clear SPI slave underrun flag and discard transmit data */ if (husart->SlaveMode == USART_SLAVEMODE_ENABLE) { __HAL_USART_CLEAR_UDRFLAG(husart); __HAL_USART_SEND_REQ(husart, USART_TXDATA_FLUSH_REQUEST); } /* Rx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; state = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Rx Complete Callback */ husart->RxCpltCallback(husart); #else /* Call legacy weak Rx Complete Callback */ HAL_USART_RxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else if ((READ_BIT(husart->Instance->CR1, USART_CR1_TCIE) != USART_CR1_TCIE) && (txftie != USART_CR3_TXFTIE) && (txdatacount == 0U)) { /* TxRx process is completed, restore husart->State to Ready */ husart->State = HAL_USART_STATE_READY; state = HAL_USART_STATE_READY; #if (USE_HAL_USART_REGISTER_CALLBACKS == 1) /* Call registered Tx Rx Complete Callback */ husart->TxRxCpltCallback(husart); #else /* Call legacy weak Tx Rx Complete Callback */ HAL_USART_TxRxCpltCallback(husart); #endif /* USE_HAL_USART_REGISTER_CALLBACKS */ } else { /* Nothing to do */ } } else if ((state == HAL_USART_STATE_BUSY_RX) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } else { /* Nothing to do */ } } } /* When remaining number of bytes to receive is less than the RX FIFO threshold, next incoming frames are processed as if FIFO mode was disabled (i.e. one interrupt per received frame). */ rxdatacount = husart->RxXferCount; if (((rxdatacount != 0U)) && (rxdatacount < husart->NbRxDataToProcess)) { /* Disable the USART RXFT interrupt*/ CLEAR_BIT(husart->Instance->CR3, USART_CR3_RXFTIE); /* Update the RxISR function pointer */ husart->RxISR = USART_RxISR_16BIT; /* Enable the USART Data Register Not Empty interrupt */ SET_BIT(husart->Instance->CR1, USART_CR1_RXNEIE_RXFNEIE); if ((husart->TxXferCount == 0U) && (state == HAL_USART_STATE_BUSY_TX_RX) && (husart->SlaveMode == USART_SLAVEMODE_DISABLE)) { /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ husart->Instance->TDR = (USART_DUMMY_DATA & (uint16_t)0x00FF); } } } else { /* Clear RXNE interrupt flag */ __HAL_USART_SEND_REQ(husart, USART_RXDATA_FLUSH_REQUEST); } } /** * @} */ #endif /* HAL_USART_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
mbedmicro/mbed
targets/TARGET_STM/TARGET_STM32L5/STM32Cube_FW/STM32L5xx_HAL_Driver/stm32l5xx_hal_usart.c
C
apache-2.0
123,962
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.management.relation; import java.util.ArrayList; // for Javadoc import java.util.List; import java.io.Serializable; /** * The RelationType interface has to be implemented by any class expected to * represent a relation type. * * @since 1.5 */ public interface RelationType extends Serializable { // // Accessors // /** * Returns the relation type name. * * @return the relation type name. */ public String getRelationTypeName(); /** * Returns the list of role definitions (ArrayList of RoleInfo objects). * * @return an {@link ArrayList} of {@link RoleInfo}. */ public List<RoleInfo> getRoleInfos(); /** * Returns the role info (RoleInfo object) for the given role info name * (null if not found). * * @param roleInfoName role info name * * @return RoleInfo object providing role definition * does not exist * * @exception IllegalArgumentException if null parameter * @exception RoleInfoNotFoundException if no role info with that name in * relation type. */ public RoleInfo getRoleInfo(String roleInfoName) throws IllegalArgumentException, RoleInfoNotFoundException; }
shun634501730/java_source_cn
src_en/javax/management/relation/RelationType.java
Java
apache-2.0
1,475
###### What does your Pull Request do (check all that apply)? Choose the most relevant items and use the following title template to name your Pull Request. - [ ] New Instant Answer: **`New {IA Name} Instant Answer`** - [ ] Improvement - [ ] Bug fix: **`{IA Name}: Fix {Issue number or one-line description}`** - [ ] Enhancement: **`{IA Name}: {Description of Improvements}`** - [ ] Non–Instant Answer - [ ] Other (Role, Template, Test, Documentation, etc.): **`{SpiceRole/Templates/Tests/Docs}: {Short Description}`** ###### Description of changes Provide an overview of the changes this pull request introduces. ###### Which issues (if any) does this fix? Fixes #NNNN - how specifically does it fix the issue? ###### People to notify (@mention interested parties) --- Instant Answer Page: https://duck.co/ia/view/{{ID}} [Maintainer](http://docs.duckduckhack.com/maintaining/guidelines.html): @mention
whalenrp/zeroclickinfo-spice
.github/PULL_REQUEST_TEMPLATE.md
Markdown
apache-2.0
928
#include "cbase.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Dummy classes for entities that are created clientside. Stops warnings about unknown entities when loading the map class CASW_Snow_Volume_Dummy : public CServerOnlyPointEntity { DECLARE_CLASS( CASW_Snow_Volume_Dummy, CServerOnlyPointEntity ); public: virtual void Spawn() { BaseClass::Spawn(); UTIL_Remove(this); } }; class CASW_Scanner_Noise_Dummy : public CServerOnlyPointEntity { DECLARE_CLASS( CASW_Scanner_Noise_Dummy, CServerOnlyPointEntity ); public: virtual void Spawn() { BaseClass::Spawn(); UTIL_Remove(this); } }; LINK_ENTITY_TO_CLASS( asw_snow_volume, CASW_Snow_Volume_Dummy ); LINK_ENTITY_TO_CLASS( asw_scanner_noise, CASW_Scanner_Noise_Dummy );
ppittle/AlienSwarmDirectorMod
trunk/src/game/server/swarm/asw_clientside_dummies.cpp
C++
apache-2.0
790
#region Copyright //======================================================================================= // Microsoft Azure Customer Advisory Team // // This sample is supplemental to the technical guidance published on my personal // blog at http://blogs.msdn.com/b/paolos/. // // Author: Paolo Salvatori //======================================================================================= // Copyright (c) Microsoft Corporation. All rights reserved. // // LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE // FILES 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. //======================================================================================= #endregion #region Using Directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.Serialization; using System.Xml.Serialization; using Microsoft.ServiceBus.Messaging; using Newtonsoft.Json; #endregion namespace Microsoft.WindowsAzure.CAT.ServiceBusExplorer { [Serializable] [XmlType(TypeName = "event", Namespace = "http://schemas.microsoft.com/servicebusexplorer")] [XmlRoot(ElementName = "event", Namespace = "http://schemas.microsoft.com/servicebusexplorer", IsNullable = false)] [DataContract(Name = "event", Namespace = "http://schemas.microsoft.com/servicebusexplorer")] public class OnOffDeviceMessage { /// <summary> /// Gets or sets the device id. /// </summary> [XmlElement(ElementName = "eventId", Namespace = "http://schemas.microsoft.com/servicebusexplorer")] [JsonProperty(PropertyName = "eventId", Order = 1)] public int EventId { get; set; } /// <summary> /// Gets or sets the device id. /// </summary> [XmlElement(ElementName = "deviceId", Namespace = "http://schemas.microsoft.com/servicebusexplorer")] [JsonProperty(PropertyName = "deviceId", Order = 2)] public int DeviceId { get; set; } /// <summary> /// Gets or sets the device value. /// </summary> [XmlElement(ElementName = "value", Namespace = "http://schemas.microsoft.com/servicebusexplorer")] [JsonProperty(PropertyName = "value", Order = 3)] public OnOff Value { get; set; } /// <summary> /// Gets or sets the event timestamp. /// </summary> [XmlElement(ElementName = "timestamp", Namespace = "http://schemas.microsoft.com/servicebusexplorer")] [JsonProperty(PropertyName = "timestamp", Order = 4)] public DateTime Timestamp { get; set; } } public class OnOffDeviceBrokeredMessageGenerator : IBrokeredMessageGenerator, IDisposable { #region Public Constants //*************************** // Constants //*************************** private const string GeneratorProperties = "Generator Properties"; private const string CustomProperties = "Custom Properties"; private const string SystemProperties = "System Properties"; private const string MinDeviceIdDescription = "Gets or sets the minimum device id."; private const string MaxDeviceIdDescription = "Gets or sets the maximum device id."; private const string AlertPercentageDescription = "Gets or sets the percentage of alert states generated by the component."; private const string AlertStateDescription = "Gets or sets the alert state."; private const string MessageFormatDescription = "Gets or sets the message format: Json or Xml."; private const string CityDescription = "Gets or sets the city."; private const string CountryDescription = "Gets or sets the country."; private const string LabelDescription = "Gets or sets the Label property of the BrokeredMessage."; //*************************** // Formats //*************************** private const string ExceptionFormat = "Exception: {0}"; private const string InnerExceptionFormat = "InnerException: {0}"; private const string BrokeredMessageCreatedFormat = "[ThresholdDeviceBrokeredMessageGenerator] {0} objects have been successfully created."; #endregion #region Public Static Fields public static int EventId; #endregion #region Public Constructor public OnOffDeviceBrokeredMessageGenerator() { MinDeviceId = 1; MaxDeviceId = 100; AlertPercentage = 10; AlertState = (int)OnOff.Off; City = "Milan"; Country = "Italy"; Label = "Service Bus Explorer"; } #endregion #region IBrokeredMessageGenerator Methods public IEnumerable<BrokeredMessage> GenerateBrokeredMessageCollection(int brokeredMessageCount, WriteToLogDelegate writeToLog) { if (brokeredMessageCount < 0) { return null; } var random = new Random(); var messageList = new List<BrokeredMessage>(); for (var i = 0; i < brokeredMessageCount; i++) { try { var normalState = AlertState == (int)OnOff.Off ? OnOff.On : OnOff.Off; var alertState = AlertState == (int)OnOff.Off ? OnOff.Off : OnOff.On; var payload = new OnOffDeviceEvent { EventId = EventId++, DeviceId = random.Next(MinDeviceId, MaxDeviceId + 1), Value = random.Next(1, 101) <= AlertPercentage ? alertState : normalState, Timestamp = DateTime.UtcNow }; var text = MessageFormat == MessageFormat.Json ? JsonSerializerHelper.Serialize(payload) : XmlSerializerHelper.Serialize(payload); var brokeredMessage = new BrokeredMessage(text.ToMemoryStream()) { MessageId = payload.DeviceId.ToString(CultureInfo.InvariantCulture), }; brokeredMessage.Properties.Add("eventId", payload.EventId); brokeredMessage.Properties.Add("deviceId", payload.DeviceId); brokeredMessage.Properties.Add("value", (int)payload.Value); brokeredMessage.Properties.Add("time", DateTime.UtcNow.Ticks); brokeredMessage.Properties.Add("city", City); brokeredMessage.Properties.Add("country", Country); brokeredMessage.Label = Label; messageList.Add(brokeredMessage); } catch (Exception ex) { if (!string.IsNullOrWhiteSpace(ex.Message)) { writeToLog(string.Format(CultureInfo.CurrentCulture, ExceptionFormat, ex.Message)); } if (ex.InnerException != null && !string.IsNullOrWhiteSpace(ex.InnerException.Message)) { writeToLog(string.Format(CultureInfo.CurrentCulture, InnerExceptionFormat, ex.InnerException.Message)); } } } if (writeToLog != null) { writeToLog(string.Format(BrokeredMessageCreatedFormat, messageList.Count)); } return messageList; } #endregion #region IDisposable Methods public void Dispose() { } #endregion #region Public Properties [Category(GeneratorProperties)] [Description(MinDeviceIdDescription)] [DefaultValue(1)] public int MinDeviceId { get; set; } [Category(GeneratorProperties)] [Description(MaxDeviceIdDescription)] [DefaultValue(100)] public int MaxDeviceId { get; set; } [Category(GeneratorProperties)] [Description(AlertPercentageDescription)] public int AlertPercentage { get; set; } [Category(GeneratorProperties)] [Description(AlertStateDescription)] public int AlertState { get; set; } [Category(GeneratorProperties)] [Description(MessageFormatDescription)] public MessageFormat MessageFormat { get; set; } [Category(CustomProperties)] [Description(CityDescription)] public string City { get; set; } [Category(CustomProperties)] [Description(CountryDescription)] public string Country { get; set; } [Category(SystemProperties)] [Description(LabelDescription)] public string Label { get; set; } #endregion } }
kdcllc/ServiceBusExplorer
src/Helpers/OnOffDeviceBrokeredMessageGenerator.cs
C#
apache-2.0
9,240
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf.jaxrs; import java.lang.reflect.Method; import java.util.Map; import javax.ws.rs.client.AsyncInvoker; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MultivaluedMap; import org.apache.cxf.message.Exchange; /** * Interface to bind between Camel and CXF exchange for RESTful resources. */ public interface CxfRsBinding { /** * Populate the camel exchange from the CxfRsRequest, the exchange will be consumed * by the processor which the CxfRsConsumer attached. * * @param camelExchange camel exchange object * @param cxfExchange cxf exchange object * @param method the method which is need for the camel component * @param paramArray the parameter list for the method invocation */ void populateExchangeFromCxfRsRequest(Exchange cxfExchange, org.apache.camel.Exchange camelExchange, Method method, Object[] paramArray); /** * Populate the CxfRsResponse object from the camel exchange * * @param camelExchange camel exchange object * @param cxfExchange cxf exchange object * @return the response object * @throws Exception can be thrown if error in the binding process */ Object populateCxfRsResponseFromExchange(org.apache.camel.Exchange camelExchange, Exchange cxfExchange) throws Exception; /** * Bind the camel in message body to a request body that gets passed * to CXF RS {@link org.apache.cxf.jaxrs.client.WebClient} APIs. * * @param camelMessage the source message * @param camelExchange the Camel exchange * @return the request object to be passed to invoke a WebClient * @throws Exception can be thrown if error in the binding process */ Object bindCamelMessageBodyToRequestBody(org.apache.camel.Message camelMessage, org.apache.camel.Exchange camelExchange) throws Exception; /** * Bind the camel headers to request headers that gets passed to CXF RS * {@link org.apache.cxf.jaxrs.client.WebClient} APIs. * * @param camelHeaders the source headers * @param camelExchange the Camel exchange * @throws Exception can be thrown if error in the binding process * @return the headers */ MultivaluedMap<String, String> bindCamelHeadersToRequestHeaders(Map<String, Object> camelHeaders, org.apache.camel.Exchange camelExchange) throws Exception; /** * Bind the HTTP response body to camel out body * * @param response the response * @param camelExchange the exchange * @return the object to be set in the Camel out message body * @throws Exception can be thrown if error in the binding process */ Object bindResponseToCamelBody(Object response, org.apache.camel.Exchange camelExchange) throws Exception; /** * Bind the response headers to camel out headers. * * @param response the response * @param camelExchange the exchange * @return headers to be set in the Camel out message * @throws Exception can be thrown if error in the binding process */ Map<String, Object> bindResponseHeadersToCamelHeaders(Object response, org.apache.camel.Exchange camelExchange) throws Exception; /** * Bind the Camel message to a request {@link Entity} that gets passed to {@link AsyncInvoker#method(java.lang.String, javax.ws.rs.client.Entity, javax.ws.rs.client.InvocationCallback)}. * * @param camelMessage the source message * @param camelExchange the Camel exchange * @param body the message body * @throws Exception can be thrown if error in the binding process * @return the {@link Entity} to use */ Entity<Object> bindCamelMessageToRequestEntity(Object body, org.apache.camel.Message camelMessage, org.apache.camel.Exchange camelExchange) throws Exception; }
Fabryprog/camel
components/camel-cxf/src/main/java/org/apache/camel/component/cxf/jaxrs/CxfRsBinding.java
Java
apache-2.0
5,027
/* * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.cas.authentication.principal; import static org.junit.Assert.*; import org.jasig.cas.authentication.principal.Response.ResponseType; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; /** * * @author Scott Battaglia * @author Arnaud Lesueur * @since 3.1 * */ public class SimpleWebApplicationServiceImplTests { @Test public void verifyResponse() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "service"); final SimpleWebApplicationServiceImpl impl = SimpleWebApplicationServiceImpl.createServiceFrom(request); final Response response = impl.getResponse("ticketId"); assertNotNull(response); assertEquals(ResponseType.REDIRECT, response.getResponseType()); } @Test public void verifyCreateSimpleWebApplicationServiceImplFromServiceAttribute() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute("service", "service"); final SimpleWebApplicationServiceImpl impl = SimpleWebApplicationServiceImpl.createServiceFrom(request); assertNotNull(impl); } @Test public void verifyResponseForJsession() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "http://www.cnn.com/;jsession=test"); final WebApplicationService impl = SimpleWebApplicationServiceImpl.createServiceFrom(request); assertEquals("http://www.cnn.com/", impl.getId()); } @Test public void verifyResponseWithNoTicket() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "service"); final WebApplicationService impl = SimpleWebApplicationServiceImpl.createServiceFrom(request); final Response response = impl.getResponse(null); assertNotNull(response); assertEquals(ResponseType.REDIRECT, response.getResponseType()); assertFalse(response.getUrl().contains("ticket=")); } @Test public void verifyResponseWithNoTicketAndNoParameterInServiceURL() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "http://foo.com/"); final WebApplicationService impl = SimpleWebApplicationServiceImpl.createServiceFrom(request); final Response response = impl.getResponse(null); assertNotNull(response); assertEquals(ResponseType.REDIRECT, response.getResponseType()); assertFalse(response.getUrl().contains("ticket=")); assertEquals("http://foo.com/", response.getUrl()); } @Test public void verifyResponseWithNoTicketAndOneParameterInServiceURL() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "http://foo.com/?param=test"); final WebApplicationService impl = SimpleWebApplicationServiceImpl.createServiceFrom(request); final Response response = impl.getResponse(null); assertNotNull(response); assertEquals(ResponseType.REDIRECT, response.getResponseType()); assertEquals("http://foo.com/?param=test", response.getUrl()); } }
keshvari/cas
cas-server-core/src/test/java/org/jasig/cas/authentication/principal/SimpleWebApplicationServiceImplTests.java
Java
apache-2.0
4,203
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.buildout; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.configurations.ParamsGroup; import com.intellij.facet.Facet; import com.intellij.facet.FacetManager; import com.intellij.facet.FacetType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.LineTokenizer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.jetbrains.python.HelperPackage; import com.jetbrains.python.PythonHelper; import com.jetbrains.python.PythonHelpersLocator; import com.jetbrains.python.buildout.config.BuildoutCfgLanguage; import com.jetbrains.python.buildout.config.psi.impl.BuildoutCfgFile; import com.jetbrains.python.facet.FacetLibraryConfigurator; import com.jetbrains.python.facet.LibraryContributingFacet; import com.jetbrains.python.facet.PythonPathContributingFacet; import com.jetbrains.python.run.PythonCommandLineState; import com.jetbrains.python.sdk.PythonEnvUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Facet for buildout support. * Knows which script in bin/ contains paths we want to add. * User: dcheryasov * Date: Jul 25, 2010 3:23:50 PM */ public class BuildoutFacet extends Facet<BuildoutFacetConfiguration> implements PythonPathContributingFacet, LibraryContributingFacet { private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.buildout.BuildoutFacet"); @NonNls public static final String BUILDOUT_CFG = "buildout.cfg"; @NonNls public static final String SCRIPT_SUFFIX = "-script"; private static final String BUILDOUT_LIB_NAME = "Buildout Eggs"; public BuildoutFacet(@NotNull final FacetType facetType, @NotNull final Module module, @NotNull final String name, @NotNull final BuildoutFacetConfiguration configuration, Facet underlyingFacet) { super(facetType, module, name, configuration, underlyingFacet); VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() { @Override public void contentsChanged(@NotNull VirtualFileEvent event) { if (Comparing.equal(event.getFile(), getScript())) { updatePaths(); attachLibrary(module); } } }, this); } @Nullable public static VirtualFile getRunner(VirtualFile baseDir) { if (baseDir == null) return null; final VirtualFile cfg = baseDir.findChild(BUILDOUT_CFG); if (cfg != null && !cfg.isDirectory()) { VirtualFile eggs = baseDir.findChild("eggs"); if (eggs != null && eggs.isDirectory()) { VirtualFile bin = baseDir.findChild("bin"); if (bin != null && bin.isDirectory()) { if (ApplicationManager.getApplication().isDispatchThread() || !ApplicationManager.getApplication().isReadAccessAllowed()) { bin.refresh(false, false); } final String exe; if (SystemInfo.isWindows || SystemInfo.isOS2) { exe = "buildout.exe"; } else { exe = "buildout"; } VirtualFile runner = bin.findChild(exe); if (runner != null && !runner.isDirectory()) { return runner; } } } } return null; } @NotNull public static List<VirtualFile> getExtraPathForAllOpenModules() { final List<VirtualFile> results = new ArrayList<VirtualFile>(); for (Project project : ProjectManager.getInstance().getOpenProjects()) { for (Module module : ModuleManager.getInstance(project).getModules()) { final BuildoutFacet buildoutFacet = getInstance(module); if (buildoutFacet != null) { for (String path : buildoutFacet.getConfiguration().getPaths()) { final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); if (file != null) { results.add(file); } } } } } return results; } /** * Generates a <code>sys.path[0:0] = [...]</code> with paths that buildout script wants. * * @param additionalPythonPath * @param module to get a buildout facet from * @return the statement, or null if there's no buildout facet. */ @Nullable public String getPathPrependStatement(List<String> additionalPythonPath) { StringBuilder sb = new StringBuilder("sys.path[0:0]=["); for (String s : additionalPythonPath) { sb.append("'").append(s).append("',"); // NOTE: we assume that quotes and spaces are escaped in paths back in the buildout script we extracted them from. } sb.append("]"); return sb.toString(); } @Override public void initFacet() { updateLibrary(); } @Override public void updateLibrary() { updatePaths(); attachLibrary(getModule()); } @Override public void removeLibrary() { detachLibrary(getModule()); } public void updatePaths() { BuildoutFacetConfiguration config = getConfiguration(); final VirtualFile script = getScript(); if (script != null) { config.setPaths(extractBuildoutPaths(script)); } } @Nullable public VirtualFile getScript() { return LocalFileSystem.getInstance().findFileByPath(getConfiguration().getScriptName()); } @Nullable public static List<String> extractBuildoutPaths(@NotNull VirtualFile script) { try { List<String> paths = extractFromScript(script); if (paths == null) { VirtualFile root = script.getParent().getParent(); String partName = FileUtil.getNameWithoutExtension(script.getName()); if (SystemInfo.isWindows && partName.endsWith(SCRIPT_SUFFIX)) { partName = partName.substring(0, partName.length() - SCRIPT_SUFFIX.length()); } VirtualFile sitePy = root.findFileByRelativePath("parts/" + partName + "/site.py"); if (sitePy != null) { paths = extractFromSitePy(sitePy); } } return paths; } catch (IOException e) { LOG.info(e); return null; } } /** * Extracts paths from given script, assuming sys.path[0:0] assignment. * * @param script * @return extracted paths, or null if extraction fails. */ @Nullable public static List<String> extractFromScript(@NotNull VirtualFile script) throws IOException { String text = VfsUtil.loadText(script); Pattern pat = Pattern.compile("(?:^\\s*(['\"])(.*)(\\1),\\s*$)|(\\])", Pattern.MULTILINE); final String bait_string = "sys.path[0:0]"; int pos = text.indexOf(bait_string); List<String> ret = null; if (pos >= 0) { pos += bait_string.length(); Matcher scanner = pat.matcher(text); while (scanner.find(pos)) { String value = scanner.group(2); if (value != null) { if (ret == null) { ret = new ArrayList<String>(); } ret.add(value); pos = scanner.end(); } else { break; } // we've matched the ']', it's group(4) } } return ret; } /** * Extracts paths from site.py generated by buildout 1.5+ * * @param vFile path to site.py * @return extracted paths */ public static List<String> extractFromSitePy(VirtualFile vFile) throws IOException { List<String> result = new ArrayList<String>(); String text = VfsUtil.loadText(vFile); String[] lines = LineTokenizer.tokenize(text, false); int index = 0; while (index < lines.length && !lines[index].startsWith("def addsitepackages(")) { index++; } while (index < lines.length && !lines[index].trim().startsWith("buildout_paths = [")) { index++; } index++; while (index < lines.length && !lines[index].trim().equals("]")) { String line = lines[index].trim(); if (line.endsWith(",")) { line = line.substring(0, line.length() - 1); } if (line.startsWith("'") && line.endsWith("'")) { result.add(StringUtil.unescapeStringCharacters(line.substring(1, line.length() - 1))); } index++; } return result; } @Override public List<String> getAdditionalPythonPath() { BuildoutFacetConfiguration cfg = getConfiguration(); return cfg.getPaths(); } @Override public boolean acceptRootAsTopLevelPackage() { return false; } @Nullable public static BuildoutFacet getInstance(Module module) { return FacetManager.getInstance(module).getFacetByType(BuildoutFacetType.ID); } public void patchCommandLineForBuildout(GeneralCommandLine commandLine) { Map<String, String> env = commandLine.getEnvironment(); ParametersList params = commandLine.getParametersList(); // alter execution script ParamsGroup scriptParams = params.getParamsGroup(PythonCommandLineState.GROUP_SCRIPT); assert scriptParams != null; if (scriptParams.getParameters().size() > 0) { String normalScript = scriptParams.getParameters().get(0); // expect DjangoUtil.MANAGE_FILE HelperPackage engulfer = PythonHelper.BUILDOUT_ENGULFER; env.put("PYCHARM_ENGULF_SCRIPT", getConfiguration().getScriptName()); scriptParams.getParametersList().replaceOrPrepend(normalScript, engulfer.asParamString()); } // add pycharm helpers to pythonpath so that fixGetpass is importable PythonEnvUtil.addToPythonPath(env, PythonHelpersLocator.getHelpersRoot().getAbsolutePath()); /* // set prependable paths List<String> paths = facet.getAdditionalPythonPath(); if (paths != null) { path_value = PyUtil.joinWith(File.pathSeparator, paths); env.put("PYCHARM_PREPEND_SYSPATH", path_value); } */ } @Nullable public File getConfigFile() { final String scriptName = getConfiguration().getScriptName(); if (!StringUtil.isEmpty(scriptName)) { return new File(new File(scriptName).getParentFile().getParentFile(), BUILDOUT_CFG); } return null; } @Nullable public BuildoutCfgFile getConfigPsiFile() { File cfg = getConfigFile(); if (cfg != null && cfg.exists()) { try { // this method is called before the project initialization is complete, so it has to use createFileFromText() instead // of PsiManager.findFile() String text = FileUtil.loadFile(cfg); final PsiFile configFile = PsiFileFactory .getInstance(getModule().getProject()).createFileFromText("buildout.cfg", BuildoutCfgLanguage.INSTANCE, text); if (configFile != null && configFile instanceof BuildoutCfgFile) { return (BuildoutCfgFile)configFile; } } catch (Exception ignored) { } } return null; } public static List<File> getScripts(@Nullable BuildoutFacet buildoutFacet, final VirtualFile baseDir) { File rootPath = null; if (buildoutFacet != null) { final File configIOFile = buildoutFacet.getConfigFile(); if (configIOFile != null) { rootPath = configIOFile.getParentFile(); } } if (rootPath == null || !rootPath.exists()) { if (baseDir != null) { rootPath = new File(baseDir.getPath()); } } if (rootPath != null) { final File[] scripts = new File(rootPath, "bin").listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (SystemInfo.isWindows) { return name.endsWith("-script.py"); } String ext = FileUtilRt.getExtension(name); return ext.length() == 0 || FileUtil.namesEqual(ext, "py"); } }); if (scripts != null) { return Arrays.asList(scripts); } } return Collections.emptyList(); } @Nullable public static File findScript(@Nullable BuildoutFacet buildoutFacet, String name, final VirtualFile baseDir) { String scriptName = SystemInfo.isWindows ? name + SCRIPT_SUFFIX : name; final List<File> scripts = getScripts(buildoutFacet, baseDir); for (File script : scripts) { if (FileUtil.getNameWithoutExtension(script.getName()).equals(scriptName)) { return script; } } return null; } public static void attachLibrary(final Module module) { final BuildoutFacet facet = getInstance(module); if (facet == null) { return; } final List<String> paths = facet.getConfiguration().getPaths(); FacetLibraryConfigurator.attachPythonLibrary(module, null, BUILDOUT_LIB_NAME, paths); } public static void detachLibrary(final Module module) { FacetLibraryConfigurator.detachPythonLibrary(module, BUILDOUT_LIB_NAME); } }
MichaelNedzelsky/intellij-community
python/src/com/jetbrains/python/buildout/BuildoutFacet.java
Java
apache-2.0
14,105
# Update a user {generate_api_description(/users/{user_id}:patch)} ## Usage examples {start_tabs} {tab|python} {generate_code_example(python)|/users/{user_id}:patch|example} {tab|curl} {generate_code_example(curl)|/users/{user_id}:patch|example} {end_tabs} ## Parameters {generate_api_arguments_table|zulip.yaml|/users/{user_id}:patch} ## Response #### Example response A typical successful JSON response may look like: {generate_code_example|/users/{user_id}:patch|fixture(200)} A typical unsuccessful JSON response: {generate_code_example|/users/{user_id}:patch|fixture(400)}
showell/zulip
templates/zerver/api/update-user.md
Markdown
apache-2.0
593
<?php /* * This file is part of the overtrue/socialite. * * (c) overtrue <i@overtrue.me> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Overtrue\Socialite\Providers; use Overtrue\Socialite\AccessTokenInterface; use Overtrue\Socialite\ProviderInterface; use Overtrue\Socialite\User; /** * Class FacebookProvider. * * @link https://developers.facebook.com/docs/graph-api [Facebook - Graph API] */ class FacebookProvider extends AbstractProvider implements ProviderInterface { /** * The base Facebook Graph URL. * * @var string */ protected $graphUrl = 'https://graph.facebook.com'; /** * The Graph API version for the request. * * @var string */ protected $version = 'v2.5'; /** * The user fields being requested. * * @var array */ protected $fields = ['first_name', 'last_name', 'email', 'gender', 'verified']; /** * The scopes being requested. * * @var array */ protected $scopes = ['email']; /** * Display the dialog in a popup view. * * @var bool */ protected $popup = false; /** * {@inheritdoc} */ protected function getAuthUrl($state) { return $this->buildAuthUrlFromBase('https://www.facebook.com/'.$this->version.'/dialog/oauth', $state); } /** * {@inheritdoc} */ protected function getTokenUrl() { return $this->graphUrl.'/oauth/access_token'; } /** * Get the access token for the given code. * * @param string $code * * @return \Overtrue\Socialite\AccessToken */ public function getAccessToken($code) { $response = $this->getHttpClient()->get($this->getTokenUrl(), [ 'query' => $this->getTokenFields($code), ]); return $this->parseAccessToken($response->getBody()); } /** * {@inheritdoc} */ protected function parseAccessToken($body) { parse_str($body, $token); return parent::parseAccessToken($token); } /** * {@inheritdoc} */ protected function getUserByToken(AccessTokenInterface $token) { $appSecretProof = hash_hmac('sha256', $token->getToken(), $this->clientSecret); $response = $this->getHttpClient()->get($this->graphUrl.'/'.$this->version.'/me?access_token='.$token.'&appsecret_proof='.$appSecretProof.'&fields='.implode(',', $this->fields), [ 'headers' => [ 'Accept' => 'application/json', ], ]); return json_decode($response->getBody(), true); } /** * {@inheritdoc} */ protected function mapUserToObject(array $user) { $avatarUrl = $this->graphUrl.'/'.$this->version.'/'.$user['id'].'/picture'; $firstName = $this->arrayItem($user, 'first_name'); $lastName = $this->arrayItem($user, 'last_name'); return new User([ 'id' => $this->arrayItem($user, 'id'), 'nickname' => null, 'name' => $firstName.' '.$lastName, 'email' => $this->arrayItem($user, 'email'), 'avatar' => $avatarUrl.'?type=normal', 'avatar_original' => $avatarUrl.'?width=1920', ]); } /** * {@inheritdoc} */ protected function getCodeFields($state = null) { $fields = parent::getCodeFields($state); if ($this->popup) { $fields['display'] = 'popup'; } return $fields; } /** * Set the user fields to request from Facebook. * * @param array $fields * * @return $this */ public function fields(array $fields) { $this->fields = $fields; return $this; } /** * Set the dialog to be displayed as a popup. * * @return $this */ public function asPopup() { $this->popup = true; return $this; } }
evoshop/evo_maa
vendor/overtrue/socialite/src/Providers/FacebookProvider.php
PHP
apache-2.0
4,034
package plugins import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "net/url" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/plugins/transport" "github.com/docker/go-connections/sockets" "github.com/docker/go-connections/tlsconfig" ) const ( defaultTimeOut = 30 ) // NewClient creates a new plugin client (http). func NewClient(addr string, tlsConfig tlsconfig.Options) (*Client, error) { tr := &http.Transport{} c, err := tlsconfig.Client(tlsConfig) if err != nil { return nil, err } tr.TLSClientConfig = c u, err := url.Parse(addr) if err != nil { return nil, err } socket := u.Host if socket == "" { // valid local socket addresses have the host empty. socket = u.Path } if err := sockets.ConfigureTransport(tr, u.Scheme, socket); err != nil { return nil, err } scheme := httpScheme(u) clientTransport := transport.NewHTTPTransport(tr, scheme, socket) return NewClientWithTransport(clientTransport), nil } // NewClientWithTransport creates a new plugin client with a given transport. func NewClientWithTransport(tr transport.Transport) *Client { return &Client{ http: &http.Client{ Transport: tr, }, requestFactory: tr, } } // Client represents a plugin client. type Client struct { http *http.Client // http client to use requestFactory transport.RequestFactory } // Call calls the specified method with the specified arguments for the plugin. // It will retry for 30 seconds if a failure occurs when calling. func (c *Client) Call(serviceMethod string, args interface{}, ret interface{}) error { var buf bytes.Buffer if args != nil { if err := json.NewEncoder(&buf).Encode(args); err != nil { return err } } body, err := c.callWithRetry(serviceMethod, &buf, true) if err != nil { return err } defer body.Close() if ret != nil { if err := json.NewDecoder(body).Decode(&ret); err != nil { logrus.Errorf("%s: error reading plugin resp: %v", serviceMethod, err) return err } } return nil } // Stream calls the specified method with the specified arguments for the plugin and returns the response body func (c *Client) Stream(serviceMethod string, args interface{}) (io.ReadCloser, error) { var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(args); err != nil { return nil, err } return c.callWithRetry(serviceMethod, &buf, true) } // SendFile calls the specified method, and passes through the IO stream func (c *Client) SendFile(serviceMethod string, data io.Reader, ret interface{}) error { body, err := c.callWithRetry(serviceMethod, data, true) if err != nil { return err } if err := json.NewDecoder(body).Decode(&ret); err != nil { logrus.Errorf("%s: error reading plugin resp: %v", serviceMethod, err) return err } return nil } func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool) (io.ReadCloser, error) { req, err := c.requestFactory.NewRequest(serviceMethod, data) if err != nil { return nil, err } var retries int start := time.Now() for { resp, err := c.http.Do(req) if err != nil { if !retry { return nil, err } timeOff := backoff(retries) if abort(start, timeOff) { return nil, err } retries++ logrus.Warnf("Unable to connect to plugin: %s, retrying in %v", req.URL, timeOff) time.Sleep(timeOff) continue } if resp.StatusCode != http.StatusOK { b, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return nil, &statusError{resp.StatusCode, serviceMethod, err.Error()} } // Plugins' Response(s) should have an Err field indicating what went // wrong. Try to unmarshal into ResponseErr. Otherwise fallback to just // return the string(body) type responseErr struct { Err string } remoteErr := responseErr{} if err := json.Unmarshal(b, &remoteErr); err == nil { if remoteErr.Err != "" { return nil, &statusError{resp.StatusCode, serviceMethod, remoteErr.Err} } } // old way... return nil, &statusError{resp.StatusCode, serviceMethod, string(b)} } return resp.Body, nil } } func backoff(retries int) time.Duration { b, max := 1, defaultTimeOut for b < max && retries > 0 { b *= 2 retries-- } if b > max { b = max } return time.Duration(b) * time.Second } func abort(start time.Time, timeOff time.Duration) bool { return timeOff+time.Since(start) >= time.Duration(defaultTimeOut)*time.Second } func httpScheme(u *url.URL) string { scheme := u.Scheme if scheme != "https" { scheme = "http" } return scheme }
runshenzhu/swarmkit
vendor/github.com/docker/docker/pkg/plugins/client.go
GO
apache-2.0
4,564
using System; using System.Linq; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Localization; using Nop.Core.Domain.Polls; using Nop.Tests; using NUnit.Framework; namespace Nop.Data.Tests.Polls { [TestFixture] public class PollPersistenceTests : PersistenceTest { [Test] public void Can_save_and_load_poll() { var poll = new Poll { Name = "Name 1", SystemKeyword = "SystemKeyword 1", Published = true, ShowOnHomePage = true, DisplayOrder = 1, StartDateUtc = new DateTime(2010, 01, 01), EndDateUtc = new DateTime(2010, 01, 02), Language = new Language { Name = "English", LanguageCulture = "en-Us", } }; var fromDb = SaveAndLoadEntity(poll); fromDb.ShouldNotBeNull(); fromDb.Name.ShouldEqual("Name 1"); fromDb.SystemKeyword.ShouldEqual("SystemKeyword 1"); fromDb.Published.ShouldEqual(true); fromDb.ShowOnHomePage.ShouldEqual(true); fromDb.DisplayOrder.ShouldEqual(1); fromDb.StartDateUtc.ShouldEqual(new DateTime(2010, 01, 01)); fromDb.EndDateUtc.ShouldEqual(new DateTime(2010, 01, 02)); fromDb.Language.ShouldNotBeNull(); fromDb.Language.Name.ShouldEqual("English"); } [Test] public void Can_save_and_load_poll_with_answers() { var poll = new Poll { Name = "Name 1", SystemKeyword = "SystemKeyword 1", Published = true, ShowOnHomePage = true, DisplayOrder = 1, StartDateUtc = new DateTime(2010, 01, 01), EndDateUtc = new DateTime(2010, 01, 02), Language = new Language { Name = "English", LanguageCulture = "en-Us", } }; poll.PollAnswers.Add ( new PollAnswer { Name = "Answer 1", NumberOfVotes = 1, DisplayOrder = 2, } ); var fromDb = SaveAndLoadEntity(poll); fromDb.ShouldNotBeNull(); fromDb.PollAnswers.ShouldNotBeNull(); (fromDb.PollAnswers.Count == 1).ShouldBeTrue(); fromDb.PollAnswers.First().Name.ShouldEqual("Answer 1"); fromDb.PollAnswers.First().NumberOfVotes.ShouldEqual(1); fromDb.PollAnswers.First().DisplayOrder.ShouldEqual(2); } [Test] public void Can_save_and_load_poll_with_answer_and_votingrecord() { var poll = new Poll { Name = "Name 1", SystemKeyword = "SystemKeyword 1", Published = true, ShowOnHomePage = true, DisplayOrder = 1, StartDateUtc = new DateTime(2010, 01, 01), EndDateUtc = new DateTime(2010, 01, 02), Language = new Language { Name = "English", LanguageCulture = "en-Us", } }; poll.PollAnswers.Add ( new PollAnswer { Name = "Answer 1", NumberOfVotes = 1, DisplayOrder = 2, } ); poll.PollAnswers.First().PollVotingRecords.Add ( new PollVotingRecord { Customer = GetTestCustomer(), CreatedOnUtc = DateTime.UtcNow } ); var fromDb = SaveAndLoadEntity(poll); fromDb.ShouldNotBeNull(); fromDb.PollAnswers.ShouldNotBeNull(); (fromDb.PollAnswers.Count == 1).ShouldBeTrue(); fromDb.PollAnswers.First().PollVotingRecords.ShouldNotBeNull(); (fromDb.PollAnswers.First().PollVotingRecords.Count == 1).ShouldBeTrue(); } protected Customer GetTestCustomer() { return new Customer { CustomerGuid = Guid.NewGuid(), CreatedOnUtc = new DateTime(2010, 01, 01), LastActivityDateUtc = new DateTime(2010, 01, 02) }; } } }
jornfilho/nopCommerce
source/Tests/Nop.Data.Tests/Polls/PollPersistenceTests.cs
C#
apache-2.0
4,677
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.apache.storm.streams.processors; import java.io.Serializable; import java.util.Set; import org.apache.storm.annotation.InterfaceStability; /** * Context information passed to the {@link Processor}. */ @InterfaceStability.Unstable public interface ProcessorContext extends Serializable { /** * Forwards the input to all downstream processors. * * @param input the input * @param <T> the type of the input */ <T> void forward(T input); /** * Forwards the input to downstream processors at specified stream. * * @param input the input * @param stream the stream to forward * @param <T> the type of the input */ <T> void forward(T input, String stream); /** * Returns true if the processing is in a windowed context and should wait for punctuation before emitting results. * * @return whether this is a windowed context or not */ boolean isWindowed(); /** * Returns the windowed parent streams. These are the streams where punctuations arrive. * * @return the windowed parent streams */ Set<String> getWindowedParentStreams(); }
kishorvpatil/incubator-storm
storm-client/src/jvm/org/apache/storm/streams/processors/ProcessorContext.java
Java
apache-2.0
1,963
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.types; import org.apache.hadoop.hbase.util.Order; import org.apache.hadoop.hbase.util.OrderedBytes; import org.apache.hadoop.hbase.util.PositionedByteRange; import org.apache.yetus.audience.InterfaceAudience; /** * A {@code float} of 32-bits using a fixed-length encoding. Based on * {@link OrderedBytes#encodeFloat32(PositionedByteRange, float, Order)}. */ @InterfaceAudience.Public public class OrderedFloat32 extends OrderedBytesBase<Float> { /** * @deprecated since 3.0.0 and will be removed in 4.0.0 */ @Deprecated public static final OrderedFloat32 ASCENDING = new OrderedFloat32(Order.ASCENDING); /** * @deprecated since 3.0.0 and will be removed in 4.0.0 */ @Deprecated public static final OrderedFloat32 DESCENDING = new OrderedFloat32(Order.DESCENDING); /** * Creates a new 32-bit {@code float} with a fixed-length encoding. * * @param order the {@link Order} to use */ public OrderedFloat32(Order order) { super(order); } @Override public boolean isNullable() { return false; } @Override public int encodedLength(Float val) { return 5; } @Override public Class<Float> encodedClass() { return Float.class; } @Override public Float decode(PositionedByteRange src) { return OrderedBytes.decodeFloat32(src); } @Override public int encode(PositionedByteRange dst, Float val) { if (null == val) { throw new IllegalArgumentException("Null values not supported."); } return OrderedBytes.encodeFloat32(dst, val, order); } /** * Read a {@code float} value from the buffer {@code dst}. * * @param dst the {@link PositionedByteRange} to read the {@code float} from * @return the {@code float} read from the buffer */ public float decodeFloat(PositionedByteRange dst) { return OrderedBytes.decodeFloat32(dst); } /** * Write instance {@code val} into buffer {@code buff}. * * @param dst the {@link PositionedByteRange} to write to * @param val the value to write to {@code dst} * @return the number of bytes written */ public int encodeFloat(PositionedByteRange dst, float val) { return OrderedBytes.encodeFloat32(dst, val, order); } }
mahak/hbase
hbase-common/src/main/java/org/apache/hadoop/hbase/types/OrderedFloat32.java
Java
apache-2.0
3,048
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> #define BOOST_GEOMETRY_REPORT_OVERLAY_ERROR #define BOOST_GEOMETRY_NO_BOOST_TEST //#define BOOST_GEOMETRY_TIME_OVERLAY #include <test_overlay_p_q.hpp> #include <boost/program_options.hpp> #include <boost/random/linear_congruential.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/uniform_real.hpp> #include <boost/random/variate_generator.hpp> #include <boost/timer.hpp> template <typename MultiPolygon> inline void make_polygon(MultiPolygon& mp, int count_x, int count_y, int index, int width_x) { typedef typename bg::point_type<MultiPolygon>::type point_type; for(int j = 0; j < count_x; ++j) { for(int k = 0; k < count_y; ++k) { mp.push_back(typename MultiPolygon::value_type()); mp.back().outer().push_back(point_type(width_x + j * 10 + 1, k * 10 + 1)); mp.back().outer().push_back(point_type(width_x + j * 10 + width_x, k * 10 + 5 + index)); mp.back().outer().push_back(point_type(width_x + j * 10 + 5 + index, k * 10 + 7)); mp.back().outer().push_back(point_type(width_x + j * 10 + 1, k * 10 + 1)); } } } template <typename MultiPolygon> void test_intersects(int count_x, int count_y, int width_x, p_q_settings const& settings) { MultiPolygon mp; make_polygon(mp, count_x, count_y, 0, width_x); bool const b = bg::intersects(mp); if (b) { std::cout << " YES"; } if(settings.svg) { typedef typename bg::coordinate_type<MultiPolygon>::type coordinate_type; typedef typename bg::point_type<MultiPolygon>::type point_type; std::ostringstream filename; filename << "intersects_" << string_from_type<coordinate_type>::name() << ".svg"; std::ofstream svg(filename.str().c_str()); bg::svg_mapper<point_type> mapper(svg, 500, 500); mapper.add(mp); mapper.map(mp, "fill-opacity:0.5;fill:rgb(153,204,0);" "stroke:rgb(153,204,0);stroke-width:3"); } } template <typename T, bool Clockwise, bool Closed> void test_all(int count, int count_x, int count_y, int width_x, p_q_settings const& settings) { boost::timer t; typedef bg::model::polygon < bg::model::d2::point_xy<T>, Clockwise, Closed > polygon; typedef bg::model::multi_polygon < polygon > multi_polygon; for(int i = 0; i < count; i++) { test_intersects<multi_polygon>(count_x, count_y, width_x, settings); } std::cout << " type: " << string_from_type<T>::name() << " time: " << t.elapsed() << std::endl; } int main(int argc, char** argv) { try { namespace po = boost::program_options; po::options_description description("=== intersects ===\nAllowed options"); int width_x = 7; int count = 1; int count_x = 10; int count_y = 10; bool ccw = false; bool open = false; p_q_settings settings; description.add_options() ("help", "Help message") ("count", po::value<int>(&count)->default_value(1), "Number of tests") ("count_x", po::value<int>(&count_x)->default_value(10), "Triangle count in x-direction") ("count_y", po::value<int>(&count_y)->default_value(10), "Triangle count in y-direction") ("width_x", po::value<int>(&width_x)->default_value(7), "Width of triangle in x-direction") ("ccw", po::value<bool>(&ccw)->default_value(false), "Counter clockwise polygons") ("open", po::value<bool>(&open)->default_value(false), "Open polygons") ("wkt", po::value<bool>(&settings.wkt)->default_value(false), "Create a WKT of the inputs, for all tests") ("svg", po::value<bool>(&settings.svg)->default_value(false), "Create a SVG for all tests") ; po::variables_map varmap; po::store(po::parse_command_line(argc, argv, description), varmap); po::notify(varmap); if (varmap.count("help")) { std::cout << description << std::endl; return 1; } if (ccw && open) { test_all<double, false, false>(count, count_x, count_y, width_x, settings); } else if (ccw) { test_all<double, false, true>(count, count_x, count_y, width_x, settings); } else if (open) { test_all<double, true, false>(count, count_x, count_y, width_x, settings); } else { test_all<double, true, true>(count, count_x, count_y, width_x, settings); } #if defined(HAVE_TTMATH) // test_all<ttmath_big, true, true>(seed, count, max, svg, level); #endif } catch(std::exception const& e) { std::cout << "Exception " << e.what() << std::endl; } catch(...) { std::cout << "Other exception" << std::endl; } return 0; }
flingone/frameworks_base_cmds_remoted
libs/boost/libs/geometry/test/robustness/overlay/areal_areal/intersects.cpp
C++
apache-2.0
5,584