prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate clap;
// Time Start: Mon, 02 Dec 2019 12:59:41 -0500
// Time Finish 1: Mon, 02 Dec 2019 14:46:54 -0500 (1 hour, 47 minutes, 13 seconds)
// Time Finish 2: Mon, 02 Dec 2019 14:53:56 -0500 (7 minutes, 2 seconds)
// Time Total: 1 hour, 54 minutes, 15 seconds
use std::convert::TryFrom;
use std::fmt;
use std::fs;
use clap::{Arg, App};
struct Intcode {
program: Vec<i32>,
pos: usize,
}
impl Intcode {
fn new() -> Intcode {
return Intcode { program: Vec::new(), pos: 0 };
}
fn load(fname: &String) -> Intcode {
let mut ic = Intcode::new();
// One line, CSV integers
let csv = fs::read_to_string(fname).unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err));
for instr in csv.trim().split(',') {
ic.program.push(
instr.parse().unwrap_or_else(|err| panic!("Not an integer '{}' in {}: {}", instr, fname, err))
);
}
return ic;
}
fn is_halted(&self) -> bool { 99 == *self.program.get(self.pos).unwrap_or(&99) }
fn run(&mut self) {
while self.step() { }
}
fn step(&mut self) -> bool {
let step = match self.peeka(0) {
1 => {
let (a, b, c) = (self.peeka(1), self.peeka(2), self.peeka(3)); // immutable borrow
self.add(a, b, c); // mutable borrow
4
},
2 => {
let (a, b, c) = (self.peeka(1), self.peeka(2), self.peeka(3)); // immutable borrow
self.mul(a, b, c); // mutable borrow
4
},
99 => 0,
x_ => panic!("Unknown command at position {}: {}", self.pos, x_),
};
self.pos += step;
return step > 0;
}
fn add(&mut self, a: usize, b: usize, c: usize) {
self.program[c] = self.program[a] + self.program[b];
}
fn mul(&mut self, a: usize, b: usize, c: usize) {
self.program[c] = self.program[a] * self.program[b];
}
fn get(&self, i: usize) -> i32 { self.program[i] }
fn peek(&self, i: usize) -> i32 { self.get(self.pos + i) }
fn geta(&self, i: usize) -> usize {
usize::try_from(
self.program[i]
).unwrap_or_else(|err| panic!("Expected address at position {}, found '{}' instead: {}", i, self.program[i], err))
}
fn peeka(&self, i: usize) -> usize { self.geta(self.pos + i) }
}
impl fmt::Display for Intcode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.program)
}
}
fn main() {
let matches = App::new("Advent of Code 2019, Day 02")
.arg(Arg::with_name("FILE")
.help("Input file to process")
.index(1))
.get_matches();
let fname = String::from(matches.value_of("FILE").unwrap_or("02.in"));
{
let mut ic = Intcode::load(&fname);
ic.program[1] = 12;
ic.program[2] = 2;<|fim▁hole|>
for noun in 0..100 {
for verb in 0..100 {
let mut ic = Intcode::load(&fname);
ic.program[1] = noun;
ic.program[2] = verb;
ic.run();
if ic.get(0) == 19690720 {
println!("Part 2: got 19690720 with noun={}, verb={}, key={}", noun, verb, 100 * noun + verb);
return;
}
}
}
}<|fim▁end|> | ic.run();
println!("Part 1: {}", ic.get(0));
} |
<|file_name|>next_reject_back.rs<|end_file_name|><|fim▁begin|>#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::ReverseSearcher;
use core::str::pattern::CharSearcher;
use core::str::pattern::Pattern;
// #[derive(Clone)]
// pub struct CharSearcher<'a>(<CharEqPattern<char> as Pattern<'a>>::Searcher);
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern<|fim▁hole|> // fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
//
// /// Checks whether the pattern matches anywhere in the haystack
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// self.into_searcher(haystack).next_match().is_some()
// }
//
// /// Checks whether the pattern matches at the front of the haystack
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// match self.into_searcher(haystack).next() {
// SearchStep::Match(0, _) => true,
// _ => false,
// }
// }
//
// /// Checks whether the pattern matches at the back of the haystack
// // #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where Self::Searcher: ReverseSearcher<'a>
// {
// match self.into_searcher(haystack).next_back() {
// SearchStep::Match(_, j) if haystack.len() == j => true,
// _ => false,
// }
// }
// }
// macro_rules! pattern_methods {
// ($t:ty, $pmap:expr, $smap:expr) => {
// type Searcher = $t;
//
// #[inline]
// fn into_searcher(self, haystack: &'a str) -> $t {
// ($smap)(($pmap)(self).into_searcher(haystack))
// }
//
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_contained_in(haystack)
// }
//
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_prefix_of(haystack)
// }
//
// #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where $t: ReverseSearcher<'a>
// {
// ($pmap)(self).is_suffix_of(haystack)
// }
// }
// }
// impl<'a> Pattern<'a> for char {
// pattern_methods!(CharSearcher<'a>, CharEqPattern, CharSearcher);
// }
// macro_rules! searcher_methods {
// (forward) => {
// #[inline]
// fn haystack(&self) -> &'a str {
// self.0.haystack()
// }
// #[inline]
// fn next(&mut self) -> SearchStep {
// self.0.next()
// }
// #[inline]
// fn next_match(&mut self) -> Option<(usize, usize)> {
// self.0.next_match()
// }
// #[inline]
// fn next_reject(&mut self) -> Option<(usize, usize)> {
// self.0.next_reject()
// }
// };
// (reverse) => {
// #[inline]
// fn next_back(&mut self) -> SearchStep {
// self.0.next_back()
// }
// #[inline]
// fn next_match_back(&mut self) -> Option<(usize, usize)> {
// self.0.next_match_back()
// }
// #[inline]
// fn next_reject_back(&mut self) -> Option<(usize, usize)> {
// self.0.next_reject_back()
// }
// }
// }
// unsafe impl<'a, 'b> ReverseSearcher<'a> for CharSliceSearcher<'a, 'b> {
// searcher_methods!(reverse);
// }
#[test]
fn next_reject_back_test1() {
let c: char = '而';
let haystack: &str = "我能吞下玻璃而不傷身體。";
let mut searcher: CharSearcher = c.into_searcher(haystack);
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((33, 36)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((30, 33)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((27, 30)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((24, 27)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((21, 24)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((15, 18)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((12, 15)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((9, 12)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((6, 9)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((3, 6)));
assert_eq!(searcher.next_reject_back(), Some::<(usize, usize)>((0, 3)));
assert_eq!(searcher.next_reject_back(), None::<(usize, usize)>);
}
}<|fim▁end|> | // type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and the `haystack` to search in. |
<|file_name|>URLInviz.js<|end_file_name|><|fim▁begin|>// document.getElementsByTagName('body')[0].style.visibility = 'hidden';
// //console.log("first" + "/\\b" + "Hello" + "\\b/gi");<|fim▁hole|>
var fn2 = function() {
//console.log('running');
document.getElementsByTagName('body')[0].style.visibility = 'hidden';
//console.log('hidden');
};
fn2();<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | """Test segzify.""" |
<|file_name|>threaded.py<|end_file_name|><|fim▁begin|>import queue
import logging
import platform
import threading
import datetime as dt
import serial
import serial.threaded
import serial_device
from .or_event import OrEvent
logger = logging.getLogger(__name__)
# Flag to indicate whether queues should be polled.
# XXX Note that polling performance may vary by platform.
POLL_QUEUES = (platform.system() == 'Windows')
class EventProtocol(serial.threaded.Protocol):
def __init__(self):
self.transport = None
self.connected = threading.Event()
self.disconnected = threading.Event()
self.port = None
def connection_made(self, transport):
"""Called when reader thread is started"""
self.port = transport.serial.port
logger.debug('connection_made: `%s` `%s`', self.port, transport)
self.transport = transport
self.connected.set()
self.disconnected.clear()
def data_received(self, data):
"""Called with snippets received from the serial port"""
raise NotImplementedError
def connection_lost(self, exception):
"""\
Called when the serial port is closed or the reader loop terminated
otherwise.
"""
if isinstance(exception, Exception):
logger.debug('Connection to port `%s` lost: %s', self.port,
exception)
else:
logger.debug('Connection to port `%s` closed', self.port)
self.connected.clear()
self.disconnected.set()
class KeepAliveReader(threading.Thread):
'''
Keep a serial connection alive (as much as possible).
Parameters<|fim▁hole|> Name of com port to connect to.
default_timeout_s : float, optional
Default time to wait for serial operation (e.g., connect).
By default, block (i.e., no time out).
**kwargs
Keyword arguments passed to ``serial_for_url`` function, e.g.,
``baudrate``, etc.
'''
def __init__(self, protocol_class, comport, **kwargs):
super(KeepAliveReader, self).__init__()
self.daemon = True
self.protocol_class = protocol_class
self.comport = comport
self.kwargs = kwargs
self.protocol = None
self.default_timeout_s = kwargs.pop('default_timeout_s', None)
# Event to indicate serial connection has been established.
self.connected = threading.Event()
# Event to request a break from the run loop.
self.close_request = threading.Event()
# Event to indicate thread has been closed.
self.closed = threading.Event()
# Event to indicate an exception has occurred.
self.error = threading.Event()
# Event to indicate that the thread has connected to the specified port
# **at least once**.
self.has_connected = threading.Event()
@property
def alive(self):
return not self.closed.is_set()
def run(self):
# Verify requested serial port is available.
try:
if self.comport not in (serial_device
.comports(only_available=True).index):
raise NameError('Port `%s` not available. Available ports: '
'`%s`' % (self.comport,
', '.join(serial_device.comports()
.index)))
except NameError as exception:
self.error.exception = exception
self.error.set()
self.closed.set()
return
while True:
# Wait for requested serial port to become available.
while self.comport not in (serial_device
.comports(only_available=True).index):
# Assume serial port was disconnected temporarily. Wait and
# periodically check again.
self.close_request.wait(2)
if self.close_request.is_set():
# No connection is open, so nothing to close. Just quit.
self.closed.set()
return
try:
# Try to open serial device and monitor connection status.
logger.debug('Open `%s` and monitor connection status',
self.comport)
device = serial.serial_for_url(self.comport, **self.kwargs)
except serial.SerialException as exception:
self.error.exception = exception
self.error.set()
self.closed.set()
return
except Exception as exception:
self.error.exception = exception
self.error.set()
self.closed.set()
return
else:
with serial.threaded.ReaderThread(device, self
.protocol_class) as protocol:
self.protocol = protocol
connected_event = OrEvent(protocol.connected,
self.close_request)
disconnected_event = OrEvent(protocol.disconnected,
self.close_request)
# Wait for connection.
connected_event.wait(None if self.has_connected.is_set()
else self.default_timeout_s)
if self.close_request.is_set():
# Quit run loop. Serial connection will be closed by
# `ReaderThread` context manager.
self.closed.set()
return
self.connected.set()
self.has_connected.set()
# Wait for disconnection.
disconnected_event.wait()
if self.close_request.is_set():
# Quit run loop.
self.closed.set()
return
self.connected.clear()
# Loop to try to reconnect to serial device.
def write(self, data, timeout_s=None):
'''
Write to serial port.
Waits for serial connection to be established before writing.
Parameters
----------
data : str or bytes
Data to write to serial port.
timeout_s : float, optional
Maximum number of seconds to wait for serial connection to be
established.
By default, block until serial connection is ready.
'''
self.connected.wait(timeout_s)
self.protocol.transport.write(data)
def request(self, response_queue, payload, timeout_s=None,
poll=POLL_QUEUES):
'''
Send
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or bytes
Payload to send.
timeout_s : float, optional
Maximum time to wait (in seconds) for response.
By default, block until response is ready.
poll : bool, optional
If ``True``, poll response queue in a busy loop until response is
ready (or timeout occurs).
Polling is much more processor intensive, but (at least on Windows)
results in faster response processing. On Windows, polling is
enabled by default.
'''
self.connected.wait(timeout_s)
return request(self, response_queue, payload, timeout_s=timeout_s,
poll=poll)
def close(self):
self.close_request.set()
# - - context manager, returns protocol
def __enter__(self):
"""\
Enter context handler. May raise RuntimeError in case the connection
could not be created.
"""
self.start()
# Wait for protocol to connect.
event = OrEvent(self.connected, self.closed)
event.wait(self.default_timeout_s)
return self
def __exit__(self, *args):
"""Leave context: close port"""
self.close()
self.closed.wait()
def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES):
'''
Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or bytes
Payload to send.
timeout_s : float, optional
Maximum time to wait (in seconds) for response.
By default, block until response is ready.
poll : bool, optional
If ``True``, poll response queue in a busy loop until response is
ready (or timeout occurs).
Polling is much more processor intensive, but (at least on Windows)
results in faster response processing. On Windows, polling is
enabled by default.
'''
device.write(payload)
if poll:
# Polling enabled. Wait for response in busy loop.
start = dt.datetime.now()
while not response_queue.qsize():
if (dt.datetime.now() - start).total_seconds() > timeout_s:
raise queue.Empty('No response received.')
return response_queue.get()
else:
# Polling disabled. Use blocking `Queue.get()` method to wait for
# response.
return response_queue.get(timeout=timeout_s)<|fim▁end|> | ----------
state : dict
State dictionary to share ``protocol`` object reference.
comport : str |
<|file_name|>Start.py<|end_file_name|><|fim▁begin|>from foam.sfa.util.xrn import urn_to_hrn<|fim▁hole|>from foam.sfa.trust.credential import Credential
from foam.sfa.trust.auth import Auth
class Start:
def __init__(self, xrn, creds, **kwargs):
hrn, type = urn_to_hrn(xrn)
valid_creds = Auth().checkCredentials(creds, 'startslice', hrn)
origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn()
return<|fim▁end|> | |
<|file_name|>uri-template.js<|end_file_name|><|fim▁begin|>import { expect } from 'chai';
import buildUriTemplate from '../src/uri-template';
describe('URI Template Handler', () => {
context('when there are path object parameters', () => {
context('when the path object parameters are not query parameters', () => {
const basePath = '/api';
const href = '/pet/findByTags';
const pathObjectParams = [
{
in: 'path',
description: 'Path parameter from path object',
name: 'fromPath',
required: true,
type: 'string',
},
];
const queryParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tags',
required: true,<|fim▁hole|> {
in: 'query',
description: 'For tests. Unknown type of query parameter.',
name: 'unknown',
required: true,
type: 'unknown',
},
];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/findByTags{?tags,unknown}');
});
});
context('when there are no query parameters but have one path object parameter', () => {
const basePath = '/api';
const href = '/pet/{id}';
const pathObjectParams = [
{
in: 'path',
description: 'Pet\'s identifier',
name: 'id',
required: true,
type: 'number',
},
];
const queryParams = [];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/{id}');
});
});
context('when there are query parameters defined', () => {
const basePath = '/api';
const href = '/pet/findByTags';
const pathObjectParams = [
{
in: 'query',
description: 'Query parameter from path object',
name: 'fromPath',
required: true,
type: 'string',
},
];
const queryParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tags',
required: true,
type: 'string',
},
{
in: 'query',
description: 'For tests. Unknown type of query parameter.',
name: 'unknown',
required: true,
type: 'unknown',
},
];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/findByTags{?fromPath,tags,unknown}');
});
});
context('when there are parameters with reserved characters', () => {
const basePath = '/my-api';
const href = '/pet/{unique%2did}';
const queryParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tag-names[]',
required: true,
type: 'string',
},
];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, [], queryParams);
expect(hrefForResource).to.equal('/my-api/pet/{unique%2did}{?tag%2dnames%5B%5D}');
});
});
context('when there is a conflict in parameter names', () => {
const basePath = '/api';
const href = '/pet/findByTags';
const pathObjectParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tags',
required: true,
type: 'string',
},
];
const queryParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tags',
required: true,
type: 'string',
},
];
it('only adds one to the query parameters', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/findByTags{?tags}');
});
});
context('when there are no query parameters defined', () => {
const basePath = '/api';
const href = '/pet/findByTags';
const pathObjectParams = [
{
in: 'query',
description: 'Query parameter from path object',
name: 'fromPath',
required: true,
type: 'string',
},
];
const queryParams = [];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/findByTags{?fromPath}');
});
});
});
context('when there are query parameters but no path object parameters', () => {
const basePath = '/api';
const href = '/pet/findByTags';
const pathObjectParams = [];
const queryParams = [
{
in: 'query',
description: 'Tags to filter by',
name: 'tags',
required: true,
type: 'string',
},
{
in: 'query',
description: 'For tests. Unknown type of query parameter.',
name: 'unknown',
required: true,
type: 'unknown',
},
];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/findByTags{?tags,unknown}');
});
});
context('when there are no query or path object parameters', () => {
const basePath = '/api';
const href = '/pet/findByTags';
const pathObjectParams = [];
const queryParams = [];
it('returns the correct URI', () => {
const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams);
expect(hrefForResource).to.equal('/api/pet/findByTags');
});
});
describe('array parameters with collectionFormat', () => {
it('returns a template with default format', () => {
const parameter = {
in: 'query',
name: 'tags',
type: 'array',
};
const hrefForResource = buildUriTemplate('', '/example', [parameter]);
expect(hrefForResource).to.equal('/example{?tags}');
});
it('returns a template with csv format', () => {
const parameter = {
in: 'query',
name: 'tags',
type: 'array',
collectionFormat: 'csv',
};
const hrefForResource = buildUriTemplate('', '/example', [parameter]);
expect(hrefForResource).to.equal('/example{?tags}');
});
it('returns an exploded template with multi format', () => {
const parameter = {
in: 'query',
name: 'tags',
type: 'array',
collectionFormat: 'multi',
};
const hrefForResource = buildUriTemplate('', '/example', [parameter]);
expect(hrefForResource).to.equal('/example{?tags*}');
});
});
});<|fim▁end|> | type: 'string',
}, |
<|file_name|>gt.rs<|end_file_name|><|fim▁begin|>#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// pub trait FixedSizeArray<T> {
// /// Converts the array to immutable slice
// fn as_slice(&self) -> &[T];
// /// Converts the array to mutable slice
// fn as_mut_slice(&mut self) -> &mut [T];
// }
// macro_rules! array_impls {
// ($($N:expr)+) => {
// $(
// #[unstable(feature = "core")]
// impl<T> FixedSizeArray<T> for [T; $N] {
// #[inline]
// fn as_slice(&self) -> &[T] {
// &self[..]
// }
// #[inline]
// fn as_mut_slice(&mut self) -> &mut [T] {
// &mut self[..]
// }
// }
//
// #[unstable(feature = "array_as_ref",
// reason = "should ideally be implemented for all fixed-sized arrays")]
// impl<T> AsRef<[T]> for [T; $N] {
// #[inline]<|fim▁hole|> // }
// }
//
// #[unstable(feature = "array_as_ref",
// reason = "should ideally be implemented for all fixed-sized arrays")]
// impl<T> AsMut<[T]> for [T; $N] {
// #[inline]
// fn as_mut(&mut self) -> &mut [T] {
// &mut self[..]
// }
// }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<T:Copy> Clone for [T; $N] {
// fn clone(&self) -> [T; $N] {
// *self
// }
// }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<T: Hash> Hash for [T; $N] {
// fn hash<H: hash::Hasher>(&self, state: &mut H) {
// Hash::hash(&self[..], state)
// }
// }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<T: fmt::Debug> fmt::Debug for [T; $N] {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// fmt::Debug::fmt(&&self[..], f)
// }
// }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<'a, T> IntoIterator for &'a [T; $N] {
// type Item = &'a T;
// type IntoIter = Iter<'a, T>;
//
// fn into_iter(self) -> Iter<'a, T> {
// self.iter()
// }
// }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<'a, T> IntoIterator for &'a mut [T; $N] {
// type Item = &'a mut T;
// type IntoIter = IterMut<'a, T>;
//
// fn into_iter(self) -> IterMut<'a, T> {
// self.iter_mut()
// }
// }
//
// // NOTE: some less important impls are omitted to reduce code bloat
// __impl_slice_eq1! { [A; $N], [B; $N] }
// __impl_slice_eq2! { [A; $N], [B] }
// __impl_slice_eq2! { [A; $N], &'b [B] }
// __impl_slice_eq2! { [A; $N], &'b mut [B] }
// // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
// // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<T:Eq> Eq for [T; $N] { }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<T:PartialOrd> PartialOrd for [T; $N] {
// #[inline]
// fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> {
// PartialOrd::partial_cmp(&&self[..], &&other[..])
// }
// #[inline]
// fn lt(&self, other: &[T; $N]) -> bool {
// PartialOrd::lt(&&self[..], &&other[..])
// }
// #[inline]
// fn le(&self, other: &[T; $N]) -> bool {
// PartialOrd::le(&&self[..], &&other[..])
// }
// #[inline]
// fn ge(&self, other: &[T; $N]) -> bool {
// PartialOrd::ge(&&self[..], &&other[..])
// }
// #[inline]
// fn gt(&self, other: &[T; $N]) -> bool {
// PartialOrd::gt(&&self[..], &&other[..])
// }
// }
//
// #[stable(feature = "rust1", since = "1.0.0")]
// impl<T:Ord> Ord for [T; $N] {
// #[inline]
// fn cmp(&self, other: &[T; $N]) -> Ordering {
// Ord::cmp(&&self[..], &&other[..])
// }
// }
// )+
// }
// }
// array_impls! {
// 0 1 2 3 4 5 6 7 8 9
// 10 11 12 13 14 15 16 17 18 19
// 20 21 22 23 24 25 26 27 28 29
// 30 31 32
// }
type T = i32;
type A = T;
type B = T;
#[test]
fn gt_test1() {
let array_a: [A; 21] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20
];
let array_b: [B; 21] = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21
];
assert_eq!(array_a.ge(&array_b), false);
assert_eq!(array_a > array_b, false);
}
#[test]
fn gt_test2() {
let array_a: [A; 21] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20
];
let array_b: [B; 21] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20
];
assert_eq!(array_a.gt(&array_b), false);
assert_eq!(array_a > array_b, false);
}
#[test]
fn gt_test3() {
let array_a: [A; 21] = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21
];
let array_b: [B; 21] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20
];
assert_eq!(array_a.gt(&array_b), true);
assert_eq!(array_a > array_b, true);
}
}<|fim▁end|> | // fn as_ref(&self) -> &[T] {
// &self[..] |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from chess import get_potential_moves
class ChessTestCase(TestCase):
def setup(self):
pass
def teardown(self):
pass
def test_knight(self):
response = get_potential_moves('knight', 'd2')
response = [each.strip() for each in response.split(',')]
possible_moves = ['b1', 'f1', 'b3', 'f3', 'c4', 'e4']
self.assertEqual(len(response), len(possible_moves))<|fim▁hole|>
def test_rook(self):
response = get_potential_moves('rook', 'd5')
response = [each.strip() for each in response.split(',')]
possible_moves = ['a5', 'b5', 'c5', 'e5', 'f5', 'g5', 'h5',
'd1', 'd2', 'd3', 'd4', 'd6', 'd7', 'd8']
self.assertEqual(len(response), len(possible_moves))
for each in possible_moves:
self.assertTrue(each in response)
def test_queen(self):
response = get_potential_moves('queen', 'd4')
response = [each.strip() for each in response.split(',')]
possible_moves = ['a4', 'b4', 'c4', 'e4', 'f4', 'g4', 'h4',
'd1', 'd2', 'd3', 'd5', 'd6', 'd7', 'd8',
'a7', 'b6', 'c5', 'e3', 'f2', 'g1',
'a1', 'b2', 'c3', 'e5', 'f6', 'g7', 'h8']
for each in possible_moves:
self.assertTrue(each in response)<|fim▁end|> |
for each in possible_moves:
self.assertTrue(each in response) |
<|file_name|>helpers.js<|end_file_name|><|fim▁begin|>//!Defines two helper functions.
/*
* c
* https://github.com/rumpl/c
*
* Copyright (c) 2012 Djordje Lukic
* Licensed under the MIT license.
*/
"use strict";
const helpers = module.exports;
<|fim▁hole|>const colors = require("colors/safe"); //Despite looking unused, is not unused.
const fs = require("fs");
const SPACING = 1; //Change this value if you want more or less space between file names and comments.
const PADDING = " "; //Change this value for what character should present your padding.
/**Prints a coloured node name, padding, and it's assigned comment.
* @param {string} nodeName The name of the node.
* @param {string} nodeComment The comment for the node.
* @param {number} maxLine The length of the longest node name in the specified directory.
* @param {string} dir the relative filepath to a directory, the contents of which will be listed.
*/
function print(nodeName, nodeComment, maxLine, dir) {
nodeComment = nodeComment || "";
nodeComment = nodeComment.replace(/(\r\n|\n|\r)/gm, " "); //Removes any new lines with blank spaces.
let pad;
//The amount of spacing & the colouring changes depending on whether 'file' is a file or a directory.
if (fs.statSync(dir + "/" + nodeName).isFile()) {
pad = PADDING.repeat(maxLine - nodeName.length + 1 + SPACING);
console.log(
// @ts-ignore - TS compiler throws an unnecessary error.
colors.brightGreen(nodeName) + pad + colors.yellow(nodeComment)
);
} else {
pad = PADDING.repeat(maxLine - nodeName.length + SPACING);
console.log(
// @ts-ignore - TS compiler throws an unnecessary error.
colors.brightCyan(nodeName + "/") + pad + colors.yellow(nodeComment)
);
}
}
//TODO: refactor printFileComments & printOnlyComments into one function - they're almost identical for the most part
/**Prints all of the files and sub-directories of a specified directory, as well as their assigned comments.
* @param {Array<string>} files An array of all of the file names in the specified directory.
* @param {Array<string>} comments An array of all of the comments in the specified directory.
* @param {string} dir the relative filepath to a directory, the content of which will be listed.
*/
helpers.printFileComments = function (files, comments, dir) {
//Gets the length of the longest filename in the array - iterators through files.
const maxLine = maxLength(files);
//Prints the current file and it's comment
print(".", comments["."], maxLine, dir);
print("..", comments[".."], maxLine, dir);
//For each file run the print function.
files.forEach(function (file) {
print(file, comments[file], maxLine, dir);
});
};
/**Prints only the files and sub-directories of a specified directory which have comments, as well as their assigned comments.
* @param {Array<string>} filesNames An array of all of the file names in the specified directory.
* @param {Array<string>} comments An array of all of the comments in the specified directory.
* @param {string} relativePathToTarget the relative filepath to a directory, the content of which will be listed.
*/
helpers.printOnlyComments = function (
filesNames,
comments,
relativePathToTarget
) {
//Gets the length of the longest filename in the array - iterators through files.
const maxLine = maxLength(filesNames);
//Prints the current file and it's comment
if (comments["."]) print(".", comments["."], maxLine, relativePathToTarget);
if (comments[".."])
print("..", comments[".."], maxLine, relativePathToTarget);
//For each file with a comment, run the print function.
filesNames.forEach(function (file) {
if (comments[file])
print(file, comments[file], maxLine, relativePathToTarget);
});
};
/**Calculates the longest file name from all the returned files.
* @param {Array<string>} files an array of all the file names in the specified directory.
* @returns {number} Returns the length of the longest name in the array.
*/
function maxLength(files) {
return files.reduce((a, b) => {
return b.length > a ? b.length : a;
}, 0);
}<|fim▁end|> | |
<|file_name|>test_functions2.py<|end_file_name|><|fim▁begin|>import math
from sympy.mpmath import *
def test_bessel():
mp.dps = 15
assert j0(1).ae(0.765197686557966551)
assert j0(pi).ae(-0.304242177644093864)
assert j0(1000).ae(0.0247866861524201746)
assert j0(-25).ae(0.0962667832759581162)
assert j1(1).ae(0.440050585744933516)
assert j1(pi).ae(0.284615343179752757)
assert j1(1000).ae(0.00472831190708952392)
assert j1(-25).ae(0.125350249580289905)
assert besselj(5,1).ae(0.000249757730211234431)
assert besselj(5,pi).ae(0.0521411843671184747)
assert besselj(5,1000).ae(0.00502540694523318607)
assert besselj(5,-25).ae(0.0660079953984229934)
assert besselj(-3,2).ae(-0.128943249474402051)
assert besselj(-4,2).ae(0.0339957198075684341)
assert besselj(3,3+2j).ae(0.424718794929639595942 + 0.625665327745785804812j)
assert besselj(0.25,4).ae(-0.374760630804249715)
assert besselj(1+2j,3+4j).ae(0.319247428741872131 - 0.669557748880365678j)
assert (besselj(3, 10**10) * 10**5).ae(0.76765081748139204023)
assert bessely(-0.5, 0) == 0
assert bessely(0.5, 0) == -inf
assert bessely(1.5, 0) == -inf
assert bessely(0,0) == -inf
assert bessely(-0.4, 0) == -inf
assert bessely(-0.6, 0) == inf
assert bessely(-1, 0) == inf
assert bessely(-1.4, 0) == inf
assert bessely(-1.6, 0) == -inf
assert bessely(-1, 0) == inf
assert bessely(-2, 0) == -inf
assert bessely(-3, 0) == inf
assert bessely(0.5, 0) == -inf
assert bessely(1, 0) == -inf
assert bessely(1.5, 0) == -inf
assert bessely(2, 0) == -inf
assert bessely(2.5, 0) == -inf
assert bessely(3, 0) == -inf
assert bessely(0,0.5).ae(-0.44451873350670655715)
assert bessely(1,0.5).ae(-1.4714723926702430692)
assert bessely(-1,0.5).ae(1.4714723926702430692)
assert bessely(3.5,0.5).ae(-138.86400867242488443)
assert bessely(0,3+4j).ae(4.6047596915010138655-8.8110771408232264208j)
assert bessely(0,j).ae(-0.26803248203398854876+1.26606587775200833560j)
assert (bessely(3, 10**10) * 10**5).ae(0.21755917537013204058)
assert besseli(0,0) == 1
assert besseli(1,0) == 0
assert besseli(2,0) == 0
assert besseli(-1,0) == 0
assert besseli(-2,0) == 0
assert besseli(0,0.5).ae(1.0634833707413235193)
assert besseli(1,0.5).ae(0.25789430539089631636)
assert besseli(-1,0.5).ae(0.25789430539089631636)
assert besseli(3.5,0.5).ae(0.00068103597085793815863)
assert besseli(0,3+4j).ae(-3.3924877882755196097-1.3239458916287264815j)
assert besseli(0,j).ae(besselj(0,1))
assert (besseli(3, 10**10) * mpf(10)**(-4342944813)).ae(4.2996028505491271875)
assert besselk(0,0) == inf
assert besselk(1,0) == inf
assert besselk(2,0) == inf
assert besselk(-1,0) == inf
assert besselk(-2,0) == inf
assert besselk(0,0.5).ae(0.92441907122766586178)
assert besselk(1,0.5).ae(1.6564411200033008937)
assert besselk(-1,0.5).ae(1.6564411200033008937)
assert besselk(3.5,0.5).ae(207.48418747548460607)
assert besselk(0,3+4j).ae(-0.007239051213570155013+0.026510418350267677215j)
assert besselk(0,j).ae(-0.13863371520405399968-1.20196971531720649914j)
assert (besselk(3, 10**10) * mpf(10)**4342944824).ae(1.1628981033356187851)
def test_hankel():
mp.dps = 15
assert hankel1(0,0.5).ae(0.93846980724081290423-0.44451873350670655715j)
assert hankel1(1,0.5).ae(0.2422684576748738864-1.4714723926702430692j)
assert hankel1(-1,0.5).ae(-0.2422684576748738864+1.4714723926702430692j)
assert hankel1(1.5,0.5).ae(0.0917016996256513026-2.5214655504213378514j)
assert hankel1(1.5,3+4j).ae(0.0066806866476728165382-0.0036684231610839127106j)
assert hankel2(0,0.5).ae(0.93846980724081290423+0.44451873350670655715j)
assert hankel2(1,0.5).ae(0.2422684576748738864+1.4714723926702430692j)
assert hankel2(-1,0.5).ae(-0.2422684576748738864-1.4714723926702430692j)
assert hankel2(1.5,0.5).ae(0.0917016996256513026+2.5214655504213378514j)
assert hankel2(1.5,3+4j).ae(14.783528526098567526-7.397390270853446512j)
def test_struve():
mp.dps = 15
assert struveh(2,3).ae(0.74238666967748318564)
assert struveh(-2.5,3).ae(0.41271003220971599344)
assert struvel(2,3).ae(1.7476573277362782744)
assert struvel(-2.5,3).ae(1.5153394466819651377)
def test_whittaker():
mp.dps = 15
assert whitm(2,3,4).ae(49.753745589025246591)
assert whitw(2,3,4).ae(14.111656223052932215)
def test_kelvin():
mp.dps = 15
assert ber(2,3).ae(0.80836846563726819091)
assert ber(3,4).ae(-0.28262680167242600233)
assert ber(-3,2).ae(-0.085611448496796363669)
assert bei(2,3).ae(-0.89102236377977331571)
assert bei(-3,2).ae(-0.14420994155731828415)
assert ker(2,3).ae(0.12839126695733458928)
assert ker(-3,2).ae(-0.29802153400559142783)
assert ker(0.5,3).ae(-0.085662378535217097524)
assert kei(2,3).ae(0.036804426134164634000)
assert kei(-3,2).ae(0.88682069845786731114)
assert kei(0.5,3).ae(0.013633041571314302948)
def test_hyper_misc():
mp.dps = 15
assert hyp0f1(1,0) == 1
assert hyp1f1(1,2,0) == 1
assert hyp1f2(1,2,3,0) == 1
assert hyp2f1(1,2,3,0) == 1
assert hyp2f2(1,2,3,4,0) == 1
assert hyp2f3(1,2,3,4,5,0) == 1
# Degenerate case: 0F0
assert hyper([],[],0) == 1
assert hyper([],[],-2).ae(exp(-2))
# Degenerate case: 1F0
assert hyper([2],[],1.5) == 4
#
assert hyp2f1((1,3),(2,3),(5,6),mpf(27)/32).ae(1.6)
assert hyp2f1((1,4),(1,2),(3,4),mpf(80)/81).ae(1.8)
assert hyp2f1((2,3),(1,1),(3,2),(2+j)/3).ae(1.327531603558679093+0.439585080092769253j)
mp.dps = 25
v = mpc('1.2282306665029814734863026', '-0.1225033830118305184672133')
assert hyper([(3,4),2+j,1],[1,5,j/3],mpf(1)/5+j/8).ae(v)
mp.dps = 15
def test_elliptic_integrals():
mp.dps = 15
assert ellipk(0).ae(pi/2)
assert ellipk(0.5).ae(gamma(0.25)**2/(4*sqrt(pi)))
assert ellipk(1) == inf
assert ellipk(1+0j) == inf
assert ellipk(-1).ae('1.3110287771460599052')
assert ellipk(-2).ae('1.1714200841467698589')
assert isinstance(ellipk(-2), mpf)
assert isinstance(ellipe(-2), mpf)
assert ellipk(-50).ae('0.47103424540873331679')
mp.dps = 30
n1 = +fraction(99999,100000)
n2 = +fraction(100001,100000)
mp.dps = 15
assert ellipk(n1).ae('7.1427724505817781901')
assert ellipk(n2).ae(mpc('7.1427417367963090109', '-1.5707923998261688019'))
assert ellipe(n1).ae('1.0000332138990829170')
v = ellipe(n2)
assert v.real.ae('0.999966786328145474069137')
assert (v.imag*10**6).ae('7.853952181727432')
assert ellipk(2).ae(mpc('1.3110287771460599052', '-1.3110287771460599052'))
assert ellipk(50).ae(mpc('0.22326753950210985451', '-0.47434723226254522087'))
assert ellipk(3+4j).ae(mpc('0.91119556380496500866', '0.63133428324134524388'))
assert ellipk(3-4j).ae(mpc('0.91119556380496500866', '-0.63133428324134524388'))
assert ellipk(-3+4j).ae(mpc('0.95357894880405122483', '0.23093044503746114444'))
assert ellipk(-3-4j).ae(mpc('0.95357894880405122483', '-0.23093044503746114444'))
assert isnan(ellipk(nan))
assert isnan(ellipe(nan))
assert ellipk(inf) == 0
assert isinstance(ellipk(inf), mpc)
assert ellipk(-inf) == 0
assert ellipk(1+0j) == inf
assert ellipe(0).ae(pi/2)
assert ellipe(0.5).ae(pi**(mpf(3)/2)/gamma(0.25)**2 +gamma(0.25)**2/(8*sqrt(pi)))
assert ellipe(1) == 1
assert ellipe(1+0j) == 1
assert ellipe(inf) == mpc(0,inf)
assert ellipe(-inf) == inf<|fim▁hole|> assert ellipe(3-4j).ae(1.4995535209333469543+1.5778790079127582745j)
assert ellipe(-3+4j).ae(2.5804237855343377803-0.8306096791000413778j)
assert ellipe(-3-4j).ae(2.5804237855343377803+0.8306096791000413778j)
assert ellipe(2).ae(0.59907011736779610372+0.59907011736779610372j)
assert ellipe('1e-1000000000').ae(pi/2)
assert ellipk('1e-1000000000').ae(pi/2)
assert ellipe(-pi).ae(2.4535865983838923)
mp.dps = 50
assert ellipk(1/pi).ae('1.724756270009501831744438120951614673874904182624739673')
assert ellipe(1/pi).ae('1.437129808135123030101542922290970050337425479058225712')
assert ellipk(-10*pi).ae('0.5519067523886233967683646782286965823151896970015484512')
assert ellipe(-10*pi).ae('5.926192483740483797854383268707108012328213431657645509')
v = ellipk(pi)
assert v.real.ae('0.973089521698042334840454592642137667227167622330325225')
assert v.imag.ae('-1.156151296372835303836814390793087600271609993858798016')
v = ellipe(pi)
assert v.real.ae('0.4632848917264710404078033487934663562998345622611263332')
assert v.imag.ae('1.0637961621753130852473300451583414489944099504180510966')
mp.dps = 15
def test_exp_integrals():
mp.dps = 15
x = +e
z = e + sqrt(3)*j
assert ei(x).ae(8.21168165538361560)
assert li(x).ae(1.89511781635593676)
assert si(x).ae(1.82104026914756705)
assert ci(x).ae(0.213958001340379779)
assert shi(x).ae(4.11520706247846193)
assert chi(x).ae(4.09647459290515367)
assert fresnels(x).ae(0.437189718149787643)
assert fresnelc(x).ae(0.401777759590243012)
assert airyai(x).ae(0.0108502401568586681)
assert airybi(x).ae(8.98245748585468627)
assert ei(z).ae(3.72597969491314951 + 7.34213212314224421j)
assert li(z).ae(2.28662658112562502 + 1.50427225297269364j)
assert si(z).ae(2.48122029237669054 + 0.12684703275254834j)
assert ci(z).ae(0.169255590269456633 - 0.892020751420780353j)
assert shi(z).ae(1.85810366559344468 + 3.66435842914920263j)
assert chi(z).ae(1.86787602931970484 + 3.67777369399304159j)
assert fresnels(z/3).ae(0.034534397197008182 + 0.754859844188218737j)
assert fresnelc(z/3).ae(1.261581645990027372 + 0.417949198775061893j)
assert airyai(z).ae(-0.0162552579839056062 - 0.0018045715700210556j)
assert airybi(z).ae(-4.98856113282883371 + 2.08558537872180623j)
assert li(0) == 0.0
assert li(1) == -inf
assert li(inf) == inf
assert isinstance(li(0.7), mpf)
assert si(inf).ae(pi/2)
assert si(-inf).ae(-pi/2)
assert ci(inf) == 0
assert ci(0) == -inf
assert isinstance(ei(-0.7), mpf)
assert airyai(inf) == 0
assert airybi(inf) == inf
assert airyai(-inf) == 0
assert airybi(-inf) == 0
assert fresnels(inf) == 0.5
assert fresnelc(inf) == 0.5
assert fresnels(-inf) == -0.5
assert fresnelc(-inf) == -0.5
assert shi(0) == 0
assert shi(inf) == inf
assert shi(-inf) == -inf
assert chi(0) == -inf
assert chi(inf) == inf
def test_ei():
mp.dps = 15
assert ei(0) == -inf
assert ei(inf) == inf
assert ei(-inf) == -0.0
assert ei(20+70j).ae(6.1041351911152984397e6 - 2.7324109310519928872e6j)
# tests for the asymptotic expansion
# values checked with Mathematica ExpIntegralEi
mp.dps = 50
r = ei(20000)
s = '3.8781962825045010930273870085501819470698476975019e+8681'
assert str(r) == s
r = ei(-200)
s = '-6.8852261063076355977108174824557929738368086933303e-90'
assert str(r) == s
r =ei(20000 + 10*j)
sre = '-3.255138234032069402493850638874410725961401274106e+8681'
sim = '-2.1081929993474403520785942429469187647767369645423e+8681'
assert str(r.real) == sre and str(r.imag) == sim
mp.dps = 15
# More asymptotic expansions
assert chi(-10**6+100j).ae('1.3077239389562548386e+434288 + 7.6808956999707408158e+434287j')
assert shi(-10**6+100j).ae('-1.3077239389562548386e+434288 - 7.6808956999707408158e+434287j')
mp.dps = 15
assert ei(10j).ae(-0.0454564330044553726+3.2291439210137706686j)
assert ei(100j).ae(-0.0051488251426104921+3.1330217936839529126j)
u = ei(fmul(10**20, j, exact=True))
assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps)
assert u.imag.ae(pi)
assert ei(-10j).ae(-0.0454564330044553726-3.2291439210137706686j)
assert ei(-100j).ae(-0.0051488251426104921-3.1330217936839529126j)
u = ei(fmul(-10**20, j, exact=True))
assert u.real.ae(-6.4525128526578084421345e-21, abs_eps=0, rel_eps=8*eps)
assert u.imag.ae(-pi)
assert ei(10+10j).ae(-1576.1504265768517448+436.9192317011328140j)
u = ei(-10+10j)
assert u.real.ae(7.6698978415553488362543e-7, abs_eps=0, rel_eps=8*eps)
assert u.imag.ae(3.141595611735621062025)
def test_e1():
mp.dps = 15
assert e1(0) == inf
assert e1(inf) == 0
assert e1(-inf) == mpc(-inf, -pi)
assert e1(10j).ae(0.045456433004455372635 + 0.087551267423977430100j)
assert e1(100j).ae(0.0051488251426104921444 - 0.0085708599058403258790j)
assert e1(fmul(10**20, j, exact=True)).ae(6.4525128526578084421e-21 - 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps)
assert e1(-10j).ae(0.045456433004455372635 - 0.087551267423977430100j)
assert e1(-100j).ae(0.0051488251426104921444 + 0.0085708599058403258790j)
assert e1(fmul(-10**20, j, exact=True)).ae(6.4525128526578084421e-21 + 7.6397040444172830039e-21j, abs_eps=0, rel_eps=8*eps)
def test_expint():
mp.dps = 15
assert expint(0,0) == inf
assert expint(0,1).ae(1/e)
assert expint(0,1.5).ae(2/exp(1.5)/3)
assert expint(1,1).ae(-ei(-1))
assert expint(2,0).ae(1)
assert expint(3,0).ae(1/2.)
assert expint(4,0).ae(1/3.)
assert expint(-2, 0.5).ae(26/sqrt(e))
assert expint(-1,-1) == 0
assert expint(-2,-1).ae(-e)
assert expint(5.5, 0).ae(2/9.)
assert expint(2.00000001,0).ae(100000000./100000001)
assert expint(2+3j,4-j).ae(0.0023461179581675065414+0.0020395540604713669262j)
assert expint('1.01', '1e-1000').ae(99.9999999899412802)
assert expint('1.000000000001', 3.5).ae(0.00697013985754701819446)
assert expint(2,3).ae(3*ei(-3)+exp(-3))
assert (expint(10,20)*10**10).ae(0.694439055541231353)
assert expint(3,inf) == 0
assert expint(3.2,inf) == 0
assert expint(3.2+2j,inf) == 0
assert expint(1,3j).ae(-0.11962978600800032763 + 0.27785620120457163717j)
assert expint(1,3).ae(0.013048381094197037413)
assert expint(1,-3).ae(-ei(3)-pi*j)
#assert expint(3) == expint(1,3)
assert expint(1,-20).ae(-25615652.66405658882 - 3.1415926535897932385j)
assert expint(1000000,0).ae(1./999999)
assert expint(0,2+3j).ae(-0.025019798357114678171 + 0.027980439405104419040j)
assert expint(-1,2+3j).ae(-0.022411973626262070419 + 0.038058922011377716932j)
assert expint(-1.5,0) == inf
def test_trig_integrals():
mp.dps = 30
assert si(mpf(1)/1000000).ae('0.000000999999999999944444444444446111')
assert ci(mpf(1)/1000000).ae('-13.2382948930629912435014366276')
assert si(10**10).ae('1.5707963267075846569685111517747537')
assert ci(10**10).ae('-4.87506025174822653785729773959e-11')
assert si(10**100).ae(pi/2)
assert (ci(10**100)*10**100).ae('-0.372376123661276688262086695553')
assert si(-3) == -si(3)
assert ci(-3).ae(ci(3) + pi*j)
# Test complex structure
mp.dps = 15
assert mp.ci(50).ae(-0.0056283863241163054402)
assert mp.ci(50+2j).ae(-0.018378282946133067149+0.070352808023688336193j)
assert mp.ci(20j).ae(1.28078263320282943611e7+1.5707963267949j)
assert mp.ci(-2+20j).ae(-4.050116856873293505e6+1.207476188206989909e7j)
assert mp.ci(-50+2j).ae(-0.0183782829461330671+3.0712398455661049023j)
assert mp.ci(-50).ae(-0.0056283863241163054+3.1415926535897932385j)
assert mp.ci(-50-2j).ae(-0.0183782829461330671-3.0712398455661049023j)
assert mp.ci(-2-20j).ae(-4.050116856873293505e6-1.207476188206989909e7j)
assert mp.ci(-20j).ae(1.28078263320282943611e7-1.5707963267949j)
assert mp.ci(50-2j).ae(-0.018378282946133067149-0.070352808023688336193j)
assert mp.si(50).ae(1.5516170724859358947)
assert mp.si(50+2j).ae(1.497884414277228461-0.017515007378437448j)
assert mp.si(20j).ae(1.2807826332028294459e7j)
assert mp.si(-2+20j).ae(-1.20747603112735722103e7-4.050116856873293554e6j)
assert mp.si(-50+2j).ae(-1.497884414277228461-0.017515007378437448j)
assert mp.si(-50).ae(-1.5516170724859358947)
assert mp.si(-50-2j).ae(-1.497884414277228461+0.017515007378437448j)
assert mp.si(-2-20j).ae(-1.20747603112735722103e7+4.050116856873293554e6j)
assert mp.si(-20j).ae(-1.2807826332028294459e7j)
assert mp.si(50-2j).ae(1.497884414277228461+0.017515007378437448j)
assert mp.chi(50j).ae(-0.0056283863241163054+1.5707963267948966192j)
assert mp.chi(-2+50j).ae(-0.0183782829461330671+1.6411491348185849554j)
assert mp.chi(-20).ae(1.28078263320282943611e7+3.1415926535898j)
assert mp.chi(-20-2j).ae(-4.050116856873293505e6+1.20747571696809187053e7j)
assert mp.chi(-2-50j).ae(-0.0183782829461330671-1.6411491348185849554j)
assert mp.chi(-50j).ae(-0.0056283863241163054-1.5707963267948966192j)
assert mp.chi(2-50j).ae(-0.0183782829461330671-1.500443518771208283j)
assert mp.chi(20-2j).ae(-4.050116856873293505e6-1.20747603112735722951e7j)
assert mp.chi(20).ae(1.2807826332028294361e7)
assert mp.chi(2+50j).ae(-0.0183782829461330671+1.500443518771208283j)
assert mp.shi(50j).ae(1.5516170724859358947j)
assert mp.shi(-2+50j).ae(0.017515007378437448+1.497884414277228461j)
assert mp.shi(-20).ae(-1.2807826332028294459e7)
assert mp.shi(-20-2j).ae(4.050116856873293554e6-1.20747603112735722103e7j)
assert mp.shi(-2-50j).ae(0.017515007378437448-1.497884414277228461j)
assert mp.shi(-50j).ae(-1.5516170724859358947j)
assert mp.shi(2-50j).ae(-0.017515007378437448-1.497884414277228461j)
assert mp.shi(20-2j).ae(-4.050116856873293554e6-1.20747603112735722103e7j)
assert mp.shi(20).ae(1.2807826332028294459e7)
assert mp.shi(2+50j).ae(-0.017515007378437448+1.497884414277228461j)
def ae(x,y,tol=1e-12):
return abs(x-y) <= abs(y)*tol
assert fp.ci(fp.inf) == 0
assert ae(fp.ci(fp.ninf), fp.pi*1j)
assert ae(fp.si(fp.inf), fp.pi/2)
assert ae(fp.si(fp.ninf), -fp.pi/2)
assert fp.si(0) == 0
assert ae(fp.ci(50), -0.0056283863241163054402)
assert ae(fp.ci(50+2j), -0.018378282946133067149+0.070352808023688336193j)
assert ae(fp.ci(20j), 1.28078263320282943611e7+1.5707963267949j)
assert ae(fp.ci(-2+20j), -4.050116856873293505e6+1.207476188206989909e7j)
assert ae(fp.ci(-50+2j), -0.0183782829461330671+3.0712398455661049023j)
assert ae(fp.ci(-50), -0.0056283863241163054+3.1415926535897932385j)
assert ae(fp.ci(-50-2j), -0.0183782829461330671-3.0712398455661049023j)
assert ae(fp.ci(-2-20j), -4.050116856873293505e6-1.207476188206989909e7j)
assert ae(fp.ci(-20j), 1.28078263320282943611e7-1.5707963267949j)
assert ae(fp.ci(50-2j), -0.018378282946133067149-0.070352808023688336193j)
assert ae(fp.si(50), 1.5516170724859358947)
assert ae(fp.si(50+2j), 1.497884414277228461-0.017515007378437448j)
assert ae(fp.si(20j), 1.2807826332028294459e7j)
assert ae(fp.si(-2+20j), -1.20747603112735722103e7-4.050116856873293554e6j)
assert ae(fp.si(-50+2j), -1.497884414277228461-0.017515007378437448j)
assert ae(fp.si(-50), -1.5516170724859358947)
assert ae(fp.si(-50-2j), -1.497884414277228461+0.017515007378437448j)
assert ae(fp.si(-2-20j), -1.20747603112735722103e7+4.050116856873293554e6j)
assert ae(fp.si(-20j), -1.2807826332028294459e7j)
assert ae(fp.si(50-2j), 1.497884414277228461+0.017515007378437448j)
assert ae(fp.chi(50j), -0.0056283863241163054+1.5707963267948966192j)
assert ae(fp.chi(-2+50j), -0.0183782829461330671+1.6411491348185849554j)
assert ae(fp.chi(-20), 1.28078263320282943611e7+3.1415926535898j)
assert ae(fp.chi(-20-2j), -4.050116856873293505e6+1.20747571696809187053e7j)
assert ae(fp.chi(-2-50j), -0.0183782829461330671-1.6411491348185849554j)
assert ae(fp.chi(-50j), -0.0056283863241163054-1.5707963267948966192j)
assert ae(fp.chi(2-50j), -0.0183782829461330671-1.500443518771208283j)
assert ae(fp.chi(20-2j), -4.050116856873293505e6-1.20747603112735722951e7j)
assert ae(fp.chi(20), 1.2807826332028294361e7)
assert ae(fp.chi(2+50j), -0.0183782829461330671+1.500443518771208283j)
assert ae(fp.shi(50j), 1.5516170724859358947j)
assert ae(fp.shi(-2+50j), 0.017515007378437448+1.497884414277228461j)
assert ae(fp.shi(-20), -1.2807826332028294459e7)
assert ae(fp.shi(-20-2j), 4.050116856873293554e6-1.20747603112735722103e7j)
assert ae(fp.shi(-2-50j), 0.017515007378437448-1.497884414277228461j)
assert ae(fp.shi(-50j), -1.5516170724859358947j)
assert ae(fp.shi(2-50j), -0.017515007378437448-1.497884414277228461j)
assert ae(fp.shi(20-2j), -4.050116856873293554e6-1.20747603112735722103e7j)
assert ae(fp.shi(20), 1.2807826332028294459e7)
assert ae(fp.shi(2+50j), -0.017515007378437448+1.497884414277228461j)
def test_airy():
mp.dps = 15
assert (airyai(10)*10**10).ae(1.1047532552898687)
assert (airybi(10)/10**9).ae(0.45564115354822515)
assert (airyai(1000)*10**9158).ae(9.306933063179556004)
assert (airybi(1000)/10**9154).ae(5.4077118391949465477)
assert airyai(-1000).ae(0.055971895773019918842)
assert airybi(-1000).ae(-0.083264574117080633012)
assert (airyai(100+100j)*10**188).ae(2.9099582462207032076 + 2.353013591706178756j)
assert (airybi(100+100j)/10**185).ae(1.7086751714463652039 - 3.1416590020830804578j)
def test_hyper_0f1():
mp.dps = 15
v = 8.63911136507950465
assert hyper([],[(1,3)],1.5).ae(v)
assert hyper([],[1/3.],1.5).ae(v)
assert hyp0f1(1/3.,1.5).ae(v)
assert hyp0f1((1,3),1.5).ae(v)
# Asymptotic expansion
assert hyp0f1(3,1e9).ae('4.9679055380347771271e+27455')
assert hyp0f1(3,1e9j).ae('-2.1222788784457702157e+19410 + 5.0840597555401854116e+19410j')
def test_hyper_1f1():
mp.dps = 15
v = 1.2917526488617656673
assert hyper([(1,2)],[(3,2)],0.7).ae(v)
assert hyper([(1,2)],[(3,2)],0.7+0j).ae(v)
assert hyper([0.5],[(3,2)],0.7).ae(v)
assert hyper([0.5],[1.5],0.7).ae(v)
assert hyper([0.5],[(3,2)],0.7+0j).ae(v)
assert hyper([0.5],[1.5],0.7+0j).ae(v)
assert hyper([(1,2)],[1.5+0j],0.7).ae(v)
assert hyper([0.5+0j],[1.5],0.7).ae(v)
assert hyper([0.5+0j],[1.5+0j],0.7+0j).ae(v)
assert hyp1f1(0.5,1.5,0.7).ae(v)
assert hyp1f1((1,2),1.5,0.7).ae(v)
# Asymptotic expansion
assert hyp1f1(2,3,1e10).ae('2.1555012157015796988e+4342944809')
assert (hyp1f1(2,3,1e10j)*10**10).ae(-0.97501205020039745852 - 1.7462392454512132074j)
# Shouldn't use asymptotic expansion
assert hyp1f1(-2, 1, 10000).ae(49980001)
# Bug
assert hyp1f1(1j,fraction(1,3),0.415-69.739j).ae(25.857588206024346592 + 15.738060264515292063j)
def test_hyper_2f1():
mp.dps = 15
v = 1.0652207633823291032
assert hyper([(1,2), (3,4)], [2], 0.3).ae(v)
assert hyper([(1,2), 0.75], [2], 0.3).ae(v)
assert hyper([0.5, 0.75], [2.0], 0.3).ae(v)
assert hyper([0.5, 0.75], [2.0], 0.3+0j).ae(v)
assert hyper([0.5+0j, (3,4)], [2.0], 0.3+0j).ae(v)
assert hyper([0.5+0j, (3,4)], [2.0], 0.3).ae(v)
assert hyper([0.5, (3,4)], [2.0+0j], 0.3).ae(v)
assert hyper([0.5+0j, 0.75+0j], [2.0+0j], 0.3+0j).ae(v)
v = 1.09234681096223231717 + 0.18104859169479360380j
assert hyper([(1,2),0.75+j], [2], 0.5).ae(v)
assert hyper([0.5,0.75+j], [2.0], 0.5).ae(v)
assert hyper([0.5,0.75+j], [2.0], 0.5+0j).ae(v)
assert hyper([0.5,0.75+j], [2.0+0j], 0.5+0j).ae(v)
v = 0.9625 - 0.125j
assert hyper([(3,2),-1],[4], 0.1+j/3).ae(v)
assert hyper([1.5,-1.0],[4], 0.1+j/3).ae(v)
assert hyper([1.5,-1.0],[4+0j], 0.1+j/3).ae(v)
assert hyper([1.5+0j,-1.0+0j],[4+0j], 0.1+j/3).ae(v)
v = 1.02111069501693445001 - 0.50402252613466859521j
assert hyper([(2,10),(3,10)],[(4,10)],1.5).ae(v)
assert hyper([0.2,(3,10)],[0.4+0j],1.5).ae(v)
assert hyper([0.2,(3,10)],[0.4+0j],1.5+0j).ae(v)
v = 0.76922501362865848528 + 0.32640579593235886194j
assert hyper([(2,10),(3,10)],[(4,10)],4+2j).ae(v)
assert hyper([0.2,(3,10)],[0.4+0j],4+2j).ae(v)
assert hyper([0.2,(3,10)],[(4,10)],4+2j).ae(v)
def test_hyper_2f1_hard():
mp.dps = 15
# Singular cases
assert hyp2f1(2,-1,-1,3).ae(0.25)
assert hyp2f1(2,-2,-2,3).ae(0.25)
assert hyp2f1(2,-1,-1,3,eliminate=False) == 7
assert hyp2f1(2,-2,-2,3,eliminate=False) == 34
assert hyp2f1(2,-2,-3,3) == 14
assert hyp2f1(2,-3,-2,3) == inf
assert hyp2f1(2,-1.5,-1.5,3) == 0.25
assert hyp2f1(1,2,3,0) == 1
assert hyp2f1(0,1,0,0) == 1
assert hyp2f1(0,0,0,0) == 1
assert isnan(hyp2f1(1,1,0,0))
assert hyp2f1(2,-1,-5, 0.25+0.25j).ae(1.1+0.1j)
assert hyp2f1(2,-5,-5, 0.25+0.25j, eliminate=False).ae(163./128 + 125./128*j)
assert hyp2f1(0.7235, -1, -5, 0.3).ae(1.04341)
assert hyp2f1(0.7235, -5, -5, 0.3, eliminate=False).ae(1.2939225017815903812)
assert hyp2f1(-1,-2,4,1) == 1.5
assert hyp2f1(1,2,-3,1) == inf
assert hyp2f1(-2,-2,1,1) == 6
assert hyp2f1(1,-2,-4,1).ae(5./3)
assert hyp2f1(0,-6,-4,1) == 1
assert hyp2f1(0,-3,-4,1) == 1
assert hyp2f1(0,0,0,1) == 1
assert hyp2f1(1,0,0,1,eliminate=False) == 1
assert hyp2f1(1,1,0,1) == inf
assert hyp2f1(1,-6,-4,1) == inf
assert hyp2f1(-7.2,-0.5,-4.5,1) == 0
assert hyp2f1(-7.2,-1,-2,1).ae(-2.6)
assert hyp2f1(1,-0.5,-4.5, 1) == inf
assert hyp2f1(1,0.5,-4.5, 1) == -inf
# Check evaluation on / close to unit circle
z = exp(j*pi/3)
w = (nthroot(2,3)+1)*exp(j*pi/12)/nthroot(3,4)**3
assert hyp2f1('1/2','1/6','1/3', z).ae(w)
assert hyp2f1('1/2','1/6','1/3', z.conjugate()).ae(w.conjugate())
assert hyp2f1(0.25, (1,3), 2, '0.999').ae(1.06826449496030635)
assert hyp2f1(0.25, (1,3), 2, '1.001').ae(1.06867299254830309446-0.00001446586793975874j)
assert hyp2f1(0.25, (1,3), 2, -1).ae(0.96656584492524351673)
assert hyp2f1(0.25, (1,3), 2, j).ae(0.99041766248982072266+0.03777135604180735522j)
assert hyp2f1(2,3,5,'0.99').ae(27.699347904322690602)
assert hyp2f1((3,2),-0.5,3,'0.99').ae(0.68403036843911661388)
assert hyp2f1(2,3,5,1j).ae(0.37290667145974386127+0.59210004902748285917j)
assert fsum([hyp2f1((7,10),(2,3),(-1,2), 0.95*exp(j*k)) for k in range(1,15)]).ae(52.851400204289452922+6.244285013912953225j)
assert fsum([hyp2f1((7,10),(2,3),(-1,2), 1.05*exp(j*k)) for k in range(1,15)]).ae(54.506013786220655330-3.000118813413217097j)
assert fsum([hyp2f1((7,10),(2,3),(-1,2), exp(j*k)) for k in range(1,15)]).ae(55.792077935955314887+1.731986485778500241j)
assert hyp2f1(2,2.5,-3.25,0.999).ae(218373932801217082543180041.33)
# Branches
assert hyp2f1(1,1,2,1.01).ae(4.5595744415723676911-3.1104877758314784539j)
assert hyp2f1(1,1,2,1.01+0.1j).ae(2.4149427480552782484+1.4148224796836938829j)
assert hyp2f1(1,1,2,3+4j).ae(0.14576709331407297807+0.48379185417980360773j)
assert hyp2f1(1,1,2,4).ae(-0.27465307216702742285 - 0.78539816339744830962j)
assert hyp2f1(1,1,2,-4).ae(0.40235947810852509365)
# Other:
# Cancellation with a large parameter involved (bug reported on sage-devel)
assert hyp2f1(112, (51,10), (-9,10), -0.99999).ae(-1.6241361047970862961e-24, abs_eps=0, rel_eps=eps*16)
def test_hyper_3f2_etc():
assert hyper([1,2,3],[1.5,8],-1).ae(0.67108992351533333030)
assert hyper([1,2,3,4],[5,6,7], -1).ae(0.90232988035425506008)
assert hyper([1,2,3],[1.25,5], 1).ae(28.924181329701905701)
assert hyper([1,2,3,4],[5,6,7],5).ae(1.5192307344006649499-1.1529845225075537461j)
assert hyper([1,2,3,4,5],[6,7,8,9],-1).ae(0.96288759462882357253)
assert hyper([1,2,3,4,5],[6,7,8,9],1).ae(1.0428697385885855841)
assert hyper([1,2,3,4,5],[6,7,8,9],5).ae(1.33980653631074769423-0.07143405251029226699j)
assert hyper([1,2.79,3.08,4.37],[5.2,6.1,7.3],5).ae(1.0996321464692607231-1.7748052293979985001j)
assert hyper([1,1,1],[1,2],1) == inf
assert hyper([1,1,1],[2,(101,100)],1).ae(100.01621213528313220)
# slow -- covered by doctests
#assert hyper([1,1,1],[2,3],0.9999).ae(1.2897972005319693905)
def test_hyper_u():
mp.dps = 15
assert hyperu(2,-3,0).ae(0.05)
assert hyperu(2,-3.5,0).ae(4./99)
assert hyperu(2,0,0) == 0.5
assert hyperu(-5,1,0) == -120
assert hyperu(-5,2,0) == inf
assert hyperu(-5,-2,0) == 0
assert hyperu(7,7,3).ae(0.00014681269365593503986) #exp(3)*gammainc(-6,3)
assert hyperu(2,-3,4).ae(0.011836478100271995559)
assert hyperu(3,4,5).ae(1./125)
assert hyperu(2,3,0.0625) == 256
assert hyperu(-1,2,0.25+0.5j) == -1.75+0.5j
assert hyperu(0.5,1.5,7.25).ae(2/sqrt(29))
assert hyperu(2,6,pi).ae(0.55804439825913399130)
assert (hyperu((3,2),8,100+201j)*10**4).ae(-0.3797318333856738798 - 2.9974928453561707782j)
assert (hyperu((5,2),(-1,2),-5000)*10**10).ae(-5.6681877926881664678j)
# XXX: fails because of undetected cancellation in low level series code
# Alternatively: could use asymptotic series here, if convergence test
# tweaked back to recognize this one
#assert (hyperu((5,2),(-1,2),-500)*10**7).ae(-1.82526906001593252847j)
def test_hyper_2f0():
mp.dps = 15
assert hyper([1,2],[],3) == hyp2f0(1,2,3)
assert hyp2f0(2,3,7).ae(0.0116108068639728714668 - 0.0073727413865865802130j)
assert hyp2f0(2,3,0) == 1
assert hyp2f0(0,0,0) == 1
assert hyp2f0(-1,-1,1).ae(2)
assert hyp2f0(-4,1,1.5).ae(62.5)
assert hyp2f0(-4,1,50).ae(147029801)
assert hyp2f0(-4,1,0.0001).ae(0.99960011997600240000)
assert hyp2f0(0.5,0.25,0.001).ae(1.0001251174078538115)
assert hyp2f0(0.5,0.25,3+4j).ae(0.85548875824755163518 + 0.21636041283392292973j)
# Important: cancellation check
assert hyp2f0((1,6),(5,6),-0.02371708245126284498).ae(0.996785723120804309)
# Should be exact; polynomial case
assert hyp2f0(-2,1,0.5+0.5j) == 0
assert hyp2f0(1,-2,0.5+0.5j) == 0
# There used to be a bug in thresholds that made one of the following hang
for d in [15, 50, 80]:
mp.dps = d
assert hyp2f0(1.5, 0.5, 0.009).ae('1.006867007239309717945323585695344927904000945829843527398772456281301440034218290443367270629519483 + 1.238277162240704919639384945859073461954721356062919829456053965502443570466701567100438048602352623e-46j')
def test_hyper_1f2():
mp.dps = 15
assert hyper([1],[2,3],4) == hyp1f2(1,2,3,4)
a1,b1,b2 = (1,10),(2,3),1./16
assert hyp1f2(a1,b1,b2,10).ae(298.7482725554557568)
assert hyp1f2(a1,b1,b2,100).ae(224128961.48602947604)
assert hyp1f2(a1,b1,b2,1000).ae(1.1669528298622675109e+27)
assert hyp1f2(a1,b1,b2,10000).ae(2.4780514622487212192e+86)
assert hyp1f2(a1,b1,b2,100000).ae(1.3885391458871523997e+274)
assert hyp1f2(a1,b1,b2,1000000).ae('9.8851796978960318255e+867')
assert hyp1f2(a1,b1,b2,10**7).ae('1.1505659189516303646e+2746')
assert hyp1f2(a1,b1,b2,10**8).ae('1.4672005404314334081e+8685')
assert hyp1f2(a1,b1,b2,10**20).ae('3.6888217332150976493e+8685889636')
assert hyp1f2(a1,b1,b2,10*j).ae(-16.163252524618572878 - 44.321567896480184312j)
assert hyp1f2(a1,b1,b2,100*j).ae(61938.155294517848171 + 637349.45215942348739j)
assert hyp1f2(a1,b1,b2,1000*j).ae(8455057657257695958.7 + 6261969266997571510.6j)
assert hyp1f2(a1,b1,b2,10000*j).ae(-8.9771211184008593089e+60 + 4.6550528111731631456e+59j)
assert hyp1f2(a1,b1,b2,100000*j).ae(2.6398091437239324225e+193 + 4.1658080666870618332e+193j)
assert hyp1f2(a1,b1,b2,1000000*j).ae('3.5999042951925965458e+613 + 1.5026014707128947992e+613j')
assert hyp1f2(a1,b1,b2,10**7*j).ae('-8.3208715051623234801e+1939 - 3.6752883490851869429e+1941j')
assert hyp1f2(a1,b1,b2,10**8*j).ae('2.0724195707891484454e+6140 - 1.3276619482724266387e+6141j')
assert hyp1f2(a1,b1,b2,10**20*j).ae('-1.1734497974795488504e+6141851462 + 1.1498106965385471542e+6141851462j')
def test_hyper_2f3():
mp.dps = 15
assert hyper([1,2],[3,4,5],6) == hyp2f3(1,2,3,4,5,6)
a1,a2,b1,b2,b3 = (1,10),(2,3),(3,10), 2, 1./16
# Check asymptotic expansion
assert hyp2f3(a1,a2,b1,b2,b3,10).ae(128.98207160698659976)
assert hyp2f3(a1,a2,b1,b2,b3,1000).ae(6.6309632883131273141e25)
assert hyp2f3(a1,a2,b1,b2,b3,10000).ae(4.6863639362713340539e84)
assert hyp2f3(a1,a2,b1,b2,b3,100000).ae(8.6632451236103084119e271)
assert hyp2f3(a1,a2,b1,b2,b3,10**6).ae('2.0291718386574980641e865')
assert hyp2f3(a1,a2,b1,b2,b3,10**7).ae('7.7639836665710030977e2742')
assert hyp2f3(a1,a2,b1,b2,b3,10**8).ae('3.2537462584071268759e8681')
assert hyp2f3(a1,a2,b1,b2,b3,10**20).ae('1.2966030542911614163e+8685889627')
assert hyp2f3(a1,a2,b1,b2,b3,10*j).ae(-18.551602185587547854 - 13.348031097874113552j)
assert hyp2f3(a1,a2,b1,b2,b3,100*j).ae(78634.359124504488695 + 74459.535945281973996j)
assert hyp2f3(a1,a2,b1,b2,b3,1000*j).ae(597682550276527901.59 - 65136194809352613.078j)
assert hyp2f3(a1,a2,b1,b2,b3,10000*j).ae(-1.1779696326238582496e+59 + 1.2297607505213133872e+59j)
assert hyp2f3(a1,a2,b1,b2,b3,100000*j).ae(2.9844228969804380301e+191 + 7.5587163231490273296e+190j)
assert hyp2f3(a1,a2,b1,b2,b3,1000000*j).ae('7.4859161049322370311e+610 - 2.8467477015940090189e+610j')
assert hyp2f3(a1,a2,b1,b2,b3,10**7*j).ae('-1.7477645579418800826e+1938 - 1.7606522995808116405e+1938j')
assert hyp2f3(a1,a2,b1,b2,b3,10**8*j).ae('-1.6932731942958401784e+6137 - 2.4521909113114629368e+6137j')
assert hyp2f3(a1,a2,b1,b2,b3,10**20*j).ae('-2.0988815677627225449e+6141851451 + 5.7708223542739208681e+6141851452j')
def test_hyper_2f2():
mp.dps = 15
assert hyper([1,2],[3,4],5) == hyp2f2(1,2,3,4,5)
a1,a2,b1,b2 = (3,10),4,(1,2),1./16
assert hyp2f2(a1,a2,b1,b2,10).ae(448225936.3377556696)
assert hyp2f2(a1,a2,b1,b2,10000).ae('1.2012553712966636711e+4358')
assert hyp2f2(a1,a2,b1,b2,-20000).ae(-0.04182343755661214626)
assert hyp2f2(a1,a2,b1,b2,10**20).ae('1.1148680024303263661e+43429448190325182840')
def test_orthpoly():
mp.dps = 15
assert jacobi(-4,2,3,0.7).ae(22800./4913)
assert jacobi(3,2,4,5.5) == 4133.125
assert jacobi(1.5,5/6.,4,0).ae(-1.0851951434075508417)
assert jacobi(-2, 1, 2, 4).ae(-0.16)
assert jacobi(2, -1, 2.5, 4).ae(34.59375)
#assert jacobi(2, -1, 2, 4) == 28.5
assert legendre(5, 7) == 129367
assert legendre(0.5,0).ae(0.53935260118837935667)
assert legendre(-1,-1) == 1
assert legendre(0,-1) == 1
assert legendre(0, 1) == 1
assert legendre(1, -1) == -1
assert legendre(7, 1) == 1
assert legendre(7, -1) == -1
assert legendre(8,1.5).ae(15457523./32768)
assert legendre(j,-j).ae(2.4448182735671431011 + 0.6928881737669934843j)
assert chebyu(5,1) == 6
assert chebyt(3,2) == 26
assert legendre(3.5,-1) == inf
assert legendre(4.5,-1) == -inf
assert legendre(3.5+1j,-1) == mpc(inf,inf)
assert legendre(4.5+1j,-1) == mpc(-inf,-inf)
assert laguerre(4, -2, 3).ae(-1.125)
assert laguerre(3, 1+j, 0.5).ae(0.2291666666666666667 + 2.5416666666666666667j)
def test_hermite():
mp.dps = 15
assert hermite(-2, 0).ae(0.5)
assert hermite(-1, 0).ae(0.88622692545275801365)
assert hermite(0, 0).ae(1)
assert hermite(1, 0) == 0
assert hermite(2, 0).ae(-2)
assert hermite(0, 2).ae(1)
assert hermite(1, 2).ae(4)
assert hermite(1, -2).ae(-4)
assert hermite(2, -2).ae(14)
assert hermite(0.5, 0).ae(0.69136733903629335053)
assert hermite(9, 0) == 0
assert hermite(4,4).ae(3340)
assert hermite(3,4).ae(464)
assert hermite(-4,4).ae(0.00018623860287512396181)
assert hermite(-3,4).ae(0.0016540169879668766270)
assert hermite(9, 2.5j).ae(13638725j)
assert hermite(9, -2.5j).ae(-13638725j)
assert hermite(9, 100).ae(511078883759363024000)
assert hermite(9, -100).ae(-511078883759363024000)
assert hermite(9, 100j).ae(512922083920643024000j)
assert hermite(9, -100j).ae(-512922083920643024000j)
assert hermite(-9.5, 2.5j).ae(-2.9004951258126778174e-6 + 1.7601372934039951100e-6j)
assert hermite(-9.5, -2.5j).ae(-2.9004951258126778174e-6 - 1.7601372934039951100e-6j)
assert hermite(-9.5, 100).ae(1.3776300722767084162e-22, abs_eps=0, rel_eps=eps)
assert hermite(-9.5, -100).ae('1.3106082028470671626e4355')
assert hermite(-9.5, 100j).ae(-9.7900218581864768430e-23 - 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps)
assert hermite(-9.5, -100j).ae(-9.7900218581864768430e-23 + 9.7900218581864768430e-23j, abs_eps=0, rel_eps=eps)
assert hermite(2+3j, -1-j).ae(851.3677063883687676 - 1496.4373467871007997j)
def test_gegenbauer():
mp.dps = 15
assert gegenbauer(1,2,3).ae(12)
assert gegenbauer(2,3,4).ae(381)
assert gegenbauer(0,0,0) == 0
assert gegenbauer(2,-1,3) == 0
assert gegenbauer(-7, 0.5, 3).ae(8989)
assert gegenbauer(1, -0.5, 3).ae(-3)
assert gegenbauer(1, -1.5, 3).ae(-9)
assert gegenbauer(1, -0.5, 3).ae(-3)
assert gegenbauer(-0.5, -0.5, 3).ae(-2.6383553159023906245)
assert gegenbauer(2+3j, 1-j, 3+4j).ae(14.880536623203696780 + 20.022029711598032898j)
#assert gegenbauer(-2, -0.5, 3).ae(-12)
def test_legenp():
mp.dps = 15
assert legenp(2,0,4) == legendre(2,4)
assert legenp(-2, -1, 0.5).ae(0.43301270189221932338)
assert legenp(-2, -1, 0.5, type=3).ae(0.43301270189221932338j)
assert legenp(-2, 1, 0.5).ae(-0.86602540378443864676)
assert legenp(2+j, 3+4j, -j).ae(134742.98773236786148 + 429782.72924463851745j)
assert legenp(2+j, 3+4j, -j, type=3).ae(802.59463394152268507 - 251.62481308942906447j)
assert legenp(2,4,3).ae(0)
assert legenp(2,4,3,type=3).ae(0)
assert legenp(2,1,0.5).ae(-1.2990381056766579701)
assert legenp(2,1,0.5,type=3).ae(1.2990381056766579701j)
assert legenp(3,2,3).ae(-360)
assert legenp(3,3,3).ae(240j*2**0.5)
assert legenp(3,4,3).ae(0)
assert legenp(0,0.5,2).ae(0.52503756790433198939 - 0.52503756790433198939j)
assert legenp(-1,-0.5,2).ae(0.60626116232846498110 + 0.60626116232846498110j)
assert legenp(-2,0.5,2).ae(1.5751127037129959682 - 1.5751127037129959682j)
assert legenp(-2,0.5,-0.5).ae(-0.85738275810499171286)
def test_legenq():
mp.dps = 15
f = legenq
# Evaluation at poles
assert isnan(f(3,2,1))
assert isnan(f(3,2,-1))
assert isnan(f(3,2,1,type=3))
assert isnan(f(3,2,-1,type=3))
# Evaluation at 0
assert f(0,1,0,type=2).ae(-1)
assert f(-2,2,0,type=2,zeroprec=200).ae(0)
assert f(1.5,3,0,type=2).ae(-2.2239343475841951023)
assert f(0,1,0,type=3).ae(j)
assert f(-2,2,0,type=3,zeroprec=200).ae(0)
assert f(1.5,3,0,type=3).ae(2.2239343475841951022*(1-1j))
# Standard case, degree 0
assert f(0,0,-1.5).ae(-0.8047189562170501873 + 1.5707963267948966192j)
assert f(0,0,-0.5).ae(-0.54930614433405484570)
assert f(0,0,0,zeroprec=200).ae(0)
assert f(0,0,0.5).ae(0.54930614433405484570)
assert f(0,0,1.5).ae(0.8047189562170501873 - 1.5707963267948966192j)
assert f(0,0,-1.5,type=3).ae(-0.80471895621705018730)
assert f(0,0,-0.5,type=3).ae(-0.5493061443340548457 - 1.5707963267948966192j)
assert f(0,0,0,type=3).ae(-1.5707963267948966192j)
assert f(0,0,0.5,type=3).ae(0.5493061443340548457 - 1.5707963267948966192j)
assert f(0,0,1.5,type=3).ae(0.80471895621705018730)
# Standard case, degree 1
assert f(1,0,-1.5).ae(0.2070784343255752810 - 2.3561944901923449288j)
assert f(1,0,-0.5).ae(-0.72534692783297257715)
assert f(1,0,0).ae(-1)
assert f(1,0,0.5).ae(-0.72534692783297257715)
assert f(1,0,1.5).ae(0.2070784343255752810 - 2.3561944901923449288j)
# Standard case, degree 2
assert f(2,0,-1.5).ae(-0.0635669991240192885 + 4.5160394395353277803j)
assert f(2,0,-0.5).ae(0.81866326804175685571)
assert f(2,0,0,zeroprec=200).ae(0)
assert f(2,0,0.5).ae(-0.81866326804175685571)
assert f(2,0,1.5).ae(0.0635669991240192885 - 4.5160394395353277803j)
# Misc orders and degrees
assert f(2,3,1.5,type=2).ae(-5.7243340223994616228j)
assert f(2,3,1.5,type=3).ae(-5.7243340223994616228)
assert f(2,3,0.5,type=2).ae(-12.316805742712016310)
assert f(2,3,0.5,type=3).ae(-12.316805742712016310j)
assert f(2,3,-1.5,type=2).ae(-5.7243340223994616228j)
assert f(2,3,-1.5,type=3).ae(5.7243340223994616228)
assert f(2,3,-0.5,type=2).ae(-12.316805742712016310)
assert f(2,3,-0.5,type=3).ae(-12.316805742712016310j)
assert f(2+3j, 3+4j, 0.5, type=3).ae(0.0016119404873235186807 - 0.0005885900510718119836j)
assert f(2+3j, 3+4j, -1.5, type=3).ae(0.008451400254138808670 + 0.020645193304593235298j)
assert f(-2.5,1,-1.5).ae(3.9553395527435335749j)
assert f(-2.5,1,-0.5).ae(1.9290561746445456908)
assert f(-2.5,1,0).ae(1.2708196271909686299)
assert f(-2.5,1,0.5).ae(-0.31584812990742202869)
assert f(-2.5,1,1.5).ae(-3.9553395527435335742 + 0.2993235655044701706j)
assert f(-2.5,1,-1.5,type=3).ae(0.29932356550447017254j)
assert f(-2.5,1,-0.5,type=3).ae(-0.3158481299074220287 - 1.9290561746445456908j)
assert f(-2.5,1,0,type=3).ae(1.2708196271909686292 - 1.2708196271909686299j)
assert f(-2.5,1,0.5,type=3).ae(1.9290561746445456907 + 0.3158481299074220287j)
assert f(-2.5,1,1.5,type=3).ae(-0.29932356550447017254)
def test_agm():
mp.dps = 15
assert agm(0,0) == 0
assert agm(0,1) == 0
assert agm(1,1) == 1
assert agm(7,7) == 7
assert agm(j,j) == j
assert (1/agm(1,sqrt(2))).ae(0.834626841674073186)
assert agm(1,2).ae(1.4567910310469068692)
assert agm(1,3).ae(1.8636167832448965424)
assert agm(1,j).ae(0.599070117367796104+0.599070117367796104j)
assert agm(2) == agm(1,2)
assert agm(-3,4).ae(0.63468509766550907+1.3443087080896272j)
def test_gammainc():
mp.dps = 15
assert gammainc(2,5).ae(6*exp(-5))
assert gammainc(2,0,5).ae(1-6*exp(-5))
assert gammainc(2,3,5).ae(-6*exp(-5)+4*exp(-3))
assert gammainc(-2.5,-0.5).ae(-0.9453087204829418812-5.3164237738936178621j)
assert gammainc(0,2,4).ae(0.045121158298212213088)
assert gammainc(0,3).ae(0.013048381094197037413)
assert gammainc(0,2+j,1-j).ae(0.00910653685850304839-0.22378752918074432574j)
assert gammainc(0,1-j).ae(0.00028162445198141833+0.17932453503935894015j)
assert gammainc(3,4,5,True).ae(0.11345128607046320253)
assert gammainc(3.5,0,inf).ae(gamma(3.5))
assert gammainc(-150.5,500).ae('6.9825435345798951153e-627')
assert gammainc(-150.5,800).ae('4.6885137549474089431e-788')
assert gammainc(-3.5, -20.5).ae(0.27008820585226911 - 1310.31447140574997636j)
assert gammainc(-3.5, -200.5).ae(0.27008820585226911 - 5.3264597096208368435e76j) # XXX real part
assert gammainc(0,0,2) == inf
assert gammainc(1,b=1).ae(0.6321205588285576784)
assert gammainc(3,2,2) == 0
assert gammainc(2,3+j,3-j).ae(-0.28135485191849314194j)
assert gammainc(4+0j,1).ae(5.8860710587430771455)
# Regularized upper gamma
assert isnan(gammainc(0, 0, regularized=True))
assert gammainc(-1, 0, regularized=True) == inf
assert gammainc(1, 0, regularized=True) == 1
assert gammainc(0, 5, regularized=True) == 0
assert gammainc(0, 2+3j, regularized=True) == 0
assert gammainc(0, 5000, regularized=True) == 0
assert gammainc(0, 10**30, regularized=True) == 0
assert gammainc(-1, 5, regularized=True) == 0
assert gammainc(-1, 5000, regularized=True) == 0
assert gammainc(-1, 10**30, regularized=True) == 0
assert gammainc(-1, -5, regularized=True) == 0
assert gammainc(-1, -5000, regularized=True) == 0
assert gammainc(-1, -10**30, regularized=True) == 0
assert gammainc(-1, 3+4j, regularized=True) == 0
assert gammainc(1, 5, regularized=True).ae(exp(-5))
assert gammainc(1, 5000, regularized=True).ae(exp(-5000))
assert gammainc(1, 10**30, regularized=True).ae(exp(-10**30))
assert gammainc(1, 3+4j, regularized=True).ae(exp(-3-4j))
assert gammainc(-1000000,2).ae('1.3669297209397347754e-301037', abs_eps=0, rel_eps=8*eps)
assert gammainc(-1000000,2,regularized=True) == 0
assert gammainc(-1000000,3+4j).ae('-1.322575609404222361e-698979 - 4.9274570591854533273e-698978j', abs_eps=0, rel_eps=8*eps)
assert gammainc(-1000000,3+4j,regularized=True) == 0
assert gammainc(2+3j, 4+5j, regularized=True).ae(0.085422013530993285774-0.052595379150390078503j)
assert gammainc(1000j, 1000j, regularized=True).ae(0.49702647628921131761 + 0.00297355675013575341j)
# Generalized
assert gammainc(3,4,2) == -gammainc(3,2,4)
assert gammainc(4, 2, 3).ae(1.2593494302978947396)
assert gammainc(4, 2, 3, regularized=True).ae(0.20989157171631578993)
assert gammainc(0, 2, 3).ae(0.035852129613864082155)
assert gammainc(0, 2, 3, regularized=True) == 0
assert gammainc(-1, 2, 3).ae(0.015219822548487616132)
assert gammainc(-1, 2, 3, regularized=True) == 0
assert gammainc(0, 2, 3).ae(0.035852129613864082155)
assert gammainc(0, 2, 3, regularized=True) == 0
# Should use upper gammas
assert gammainc(5, 10000, 12000).ae('1.1359381951461801687e-4327', abs_eps=0, rel_eps=8*eps)
# Should use lower gammas
assert gammainc(10000, 2, 3).ae('8.1244514125995785934e4765')
def test_gammainc_expint_n():
# These tests are intended to check all cases of the low-level code
# for upper gamma and expint with small integer index.
# Need to cover positive/negative arguments; small/large/huge arguments
# for both positive and negative indices, as well as indices 0 and 1
# which may be special-cased
mp.dps = 15
assert expint(-3,3.5).ae(0.021456366563296693987)
assert expint(-2,3.5).ae(0.014966633183073309405)
assert expint(-1,3.5).ae(0.011092916359219041088)
assert expint(0,3.5).ae(0.0086278238349481430685)
assert expint(1,3.5).ae(0.0069701398575483929193)
assert expint(2,3.5).ae(0.0058018939208991255223)
assert expint(3,3.5).ae(0.0049453773495857807058)
assert expint(-3,-3.5).ae(-4.6618170604073311319)
assert expint(-2,-3.5).ae(-5.5996974157555515963)
assert expint(-1,-3.5).ae(-6.7582555017739415818)
assert expint(0,-3.5).ae(-9.4615577024835182145)
assert expint(1,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j)
assert expint(2,-3.5).ae(-15.62328702434085977 - 10.995574287564276335j)
assert expint(3,-3.5).ae(-10.783026313250347722 - 19.242255003237483586j)
assert expint(-3,350).ae(2.8614825451252838069e-155, abs_eps=0, rel_eps=8*eps)
assert expint(-2,350).ae(2.8532837224504675901e-155, abs_eps=0, rel_eps=8*eps)
assert expint(-1,350).ae(2.8451316155828634555e-155, abs_eps=0, rel_eps=8*eps)
assert expint(0,350).ae(2.8370258275042797989e-155, abs_eps=0, rel_eps=8*eps)
assert expint(1,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps)
assert expint(2,350).ae(2.8209516419468505006e-155, abs_eps=0, rel_eps=8*eps)
assert expint(3,350).ae(2.8129824725501272171e-155, abs_eps=0, rel_eps=8*eps)
assert expint(-3,-350).ae(-2.8528796154044839443e+149)
assert expint(-2,-350).ae(-2.8610072121701264351e+149)
assert expint(-1,-350).ae(-2.8691813842677537647e+149)
assert expint(0,-350).ae(-2.8774025343659421709e+149)
u = expint(1,-350)
assert u.ae(-2.8856710698020863568e+149)
assert u.imag.ae(-3.1415926535897932385)
u = expint(2,-350)
assert u.ae(-2.8939874026504650534e+149)
assert u.imag.ae(-1099.5574287564276335)
u = expint(3,-350)
assert u.ae(-2.9023519497915044349e+149)
assert u.imag.ae(-192422.55003237483586)
assert expint(-3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(-2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(-1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(1,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(2,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(3,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert expint(-3,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')
assert expint(-2,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')
assert expint(-1,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')
assert expint(0,-350000000000000000000000).ae('-3.7805306852415755699e+152003068666138139677871')
u = expint(1,-350000000000000000000000)
assert u.ae('-3.7805306852415755699e+152003068666138139677871')
assert u.imag.ae(-3.1415926535897932385)
u = expint(2,-350000000000000000000000)
assert u.imag.ae(-1.0995574287564276335e+24)
assert u.ae('-3.7805306852415755699e+152003068666138139677871')
u = expint(3,-350000000000000000000000)
assert u.imag.ae(-1.9242255003237483586e+47)
assert u.ae('-3.7805306852415755699e+152003068666138139677871')
# Small case; no branch cut
assert gammainc(-3,3.5).ae(0.00010020262545203707109)
assert gammainc(-2,3.5).ae(0.00040370427343557393517)
assert gammainc(-1,3.5).ae(0.0016576839773997501492)
assert gammainc(0,3.5).ae(0.0069701398575483929193)
assert gammainc(1,3.5).ae(0.03019738342231850074)
assert gammainc(2,3.5).ae(0.13588822540043325333)
assert gammainc(3,3.5).ae(0.64169439772426814072)
# Small case; with branch cut
assert gammainc(-3,-3.5).ae(0.03595832954467563286 - 0.52359877559829887308j)
assert gammainc(-2,-3.5).ae(-0.88024704597962022221 - 1.5707963267948966192j)
assert gammainc(-1,-3.5).ae(4.4637962926688170771 - 3.1415926535897932385j)
assert gammainc(0,-3.5).ae(-13.925353995152335292 - 3.1415926535897932385j)
assert gammainc(1,-3.5).ae(33.115451958692313751)
assert gammainc(2,-3.5).ae(-82.788629896730784377)
assert gammainc(3,-3.5).ae(240.08702670051927469)
# Asymptotic case; no branch cut
assert gammainc(-3,350).ae(6.5424095113340358813e-163, abs_eps=0, rel_eps=8*eps)
assert gammainc(-2,350).ae(2.296312222489899769e-160, abs_eps=0, rel_eps=8*eps)
assert gammainc(-1,350).ae(8.059861834133858573e-158, abs_eps=0, rel_eps=8*eps)
assert gammainc(0,350).ae(2.8289659656701459404e-155, abs_eps=0, rel_eps=8*eps)
assert gammainc(1,350).ae(9.9295903962649792963e-153, abs_eps=0, rel_eps=8*eps)
assert gammainc(2,350).ae(3.485286229089007733e-150, abs_eps=0, rel_eps=8*eps)
assert gammainc(3,350).ae(1.2233453960006379793e-147, abs_eps=0, rel_eps=8*eps)
# Asymptotic case; branch cut
u = gammainc(-3,-350)
assert u.ae(6.7889565783842895085e+141)
assert u.imag.ae(-0.52359877559829887308)
u = gammainc(-2,-350)
assert u.ae(-2.3692668977889832121e+144)
assert u.imag.ae(-1.5707963267948966192)
u = gammainc(-1,-350)
assert u.ae(8.2685354361441858669e+146)
assert u.imag.ae(-3.1415926535897932385)
u = gammainc(0,-350)
assert u.ae(-2.8856710698020863568e+149)
assert u.imag.ae(-3.1415926535897932385)
u = gammainc(1,-350)
assert u.ae(1.0070908870280797598e+152)
assert u.imag == 0
u = gammainc(2,-350)
assert u.ae(-3.5147471957279983618e+154)
assert u.imag == 0
u = gammainc(3,-350)
assert u.ae(1.2266568422179417091e+157)
assert u.imag == 0
# Extreme asymptotic case
assert gammainc(-3,350000000000000000000000).ae('5.0362468738874738859e-152003068666138139677990', abs_eps=0, rel_eps=8*eps)
assert gammainc(-2,350000000000000000000000).ae('1.7626864058606158601e-152003068666138139677966', abs_eps=0, rel_eps=8*eps)
assert gammainc(-1,350000000000000000000000).ae('6.1694024205121555102e-152003068666138139677943', abs_eps=0, rel_eps=8*eps)
assert gammainc(0,350000000000000000000000).ae('2.1592908471792544286e-152003068666138139677919', abs_eps=0, rel_eps=8*eps)
assert gammainc(1,350000000000000000000000).ae('7.5575179651273905e-152003068666138139677896', abs_eps=0, rel_eps=8*eps)
assert gammainc(2,350000000000000000000000).ae('2.645131287794586675e-152003068666138139677872', abs_eps=0, rel_eps=8*eps)
assert gammainc(3,350000000000000000000000).ae('9.2579595072810533625e-152003068666138139677849', abs_eps=0, rel_eps=8*eps)
u = gammainc(-3,-350000000000000000000000)
assert u.ae('8.8175642804468234866e+152003068666138139677800')
assert u.imag.ae(-0.52359877559829887308)
u = gammainc(-2,-350000000000000000000000)
assert u.ae('-3.0861474981563882203e+152003068666138139677824')
assert u.imag.ae(-1.5707963267948966192)
u = gammainc(-1,-350000000000000000000000)
assert u.ae('1.0801516243547358771e+152003068666138139677848')
assert u.imag.ae(-3.1415926535897932385)
u = gammainc(0,-350000000000000000000000)
assert u.ae('-3.7805306852415755699e+152003068666138139677871')
assert u.imag.ae(-3.1415926535897932385)
assert gammainc(1,-350000000000000000000000).ae('1.3231857398345514495e+152003068666138139677895')
assert gammainc(2,-350000000000000000000000).ae('-4.6311500894209300731e+152003068666138139677918')
assert gammainc(3,-350000000000000000000000).ae('1.6209025312973255256e+152003068666138139677942')
def test_incomplete_beta():
mp.dps = 15
assert betainc(-2,-3,0.5,0.75).ae(63.4305673311255413583969)
assert betainc(4.5,0.5+2j,2.5,6).ae(0.2628801146130621387903065 + 0.5162565234467020592855378j)
assert betainc(4,5,0,6).ae(90747.77142857142857142857)
def test_erf():
mp.dps = 15
assert erf(0) == 0
assert erf(1).ae(0.84270079294971486934)
assert erf(3+4j).ae(-120.186991395079444098 - 27.750337293623902498j)
assert erf(-4-3j).ae(-0.99991066178539168236 + 0.00004972026054496604j)
assert erf(pi).ae(0.99999112385363235839)
assert erf(1j).ae(1.6504257587975428760j)
assert erf(-1j).ae(-1.6504257587975428760j)
assert isinstance(erf(1), mpf)
assert isinstance(erf(-1), mpf)
assert isinstance(erf(0), mpf)
assert isinstance(erf(0j), mpc)
assert erf(inf) == 1
assert erf(-inf) == -1
assert erfi(0) == 0
assert erfi(1/pi).ae(0.371682698493894314)
assert erfi(inf) == inf
assert erfi(-inf) == -inf
assert erf(1+0j) == erf(1)
assert erfc(1+0j) == erfc(1)
assert erf(0.2+0.5j).ae(1 - erfc(0.2+0.5j))
assert erfc(0) == 1
assert erfc(1).ae(1-erf(1))
assert erfc(-1).ae(1-erf(-1))
assert erfc(1/pi).ae(1-erf(1/pi))
assert erfc(-10) == 2
assert erfc(-1000000) == 2
assert erfc(-inf) == 2
assert erfc(inf) == 0
assert isnan(erfc(nan))
assert (erfc(10**4)*mpf(10)**43429453).ae('3.63998738656420')
assert erf(8+9j).ae(-1072004.2525062051158 + 364149.91954310255423j)
assert erfc(8+9j).ae(1072005.2525062051158 - 364149.91954310255423j)
assert erfc(-8-9j).ae(-1072003.2525062051158 + 364149.91954310255423j)
mp.dps = 50
# This one does not use the asymptotic series
assert (erfc(10)*10**45).ae('2.0884875837625447570007862949577886115608181193212')
# This one does
assert (erfc(50)*10**1088).ae('2.0709207788416560484484478751657887929322509209954')
mp.dps = 15
assert str(erfc(10**50)) == '3.66744826532555e-4342944819032518276511289189166050822943970058036665661144537831658646492088707747292249493384317534'
assert erfinv(0) == 0
assert erfinv(0.5).ae(0.47693627620446987338)
assert erfinv(-0.5).ae(-0.47693627620446987338)
assert erfinv(1) == inf
assert erfinv(-1) == -inf
assert erf(erfinv(0.95)).ae(0.95)
assert erf(erfinv(0.999999999995)).ae(0.999999999995)
assert erf(erfinv(-0.999999999995)).ae(-0.999999999995)
mp.dps = 50
assert erf(erfinv('0.99999999999999999999999999999995')).ae('0.99999999999999999999999999999995')
assert erf(erfinv('0.999999999999999999999999999999995')).ae('0.999999999999999999999999999999995')
assert erf(erfinv('-0.999999999999999999999999999999995')).ae('-0.999999999999999999999999999999995')
mp.dps = 15
# Complex asymptotic expansions
v = erfc(50j)
assert v.real == 1
assert v.imag.ae('-6.1481820666053078736e+1083')
assert erfc(-100+5j).ae(2)
assert (erfc(100+5j)*10**4335).ae(2.3973567853824133572 - 3.9339259530609420597j)
assert erfc(100+100j).ae(0.00065234366376857698698 - 0.0039357263629214118437j)
def test_pdf():
mp.dps = 15
assert npdf(-inf) == 0
assert npdf(inf) == 0
assert npdf(5,0,2).ae(npdf(5+4,4,2))
assert quadts(lambda x: npdf(x,-0.5,0.8), [-inf, inf]) == 1
assert ncdf(0) == 0.5
assert ncdf(3,3) == 0.5
assert ncdf(-inf) == 0
assert ncdf(inf) == 1
assert ncdf(10) == 1
# Verify that this is computed accurately
assert (ncdf(-10)*10**24).ae(7.619853024160526)
def test_lambertw():
mp.dps = 15
assert lambertw(0) == 0
assert lambertw(0+0j) == 0
assert lambertw(inf) == inf
assert isnan(lambertw(nan))
assert lambertw(inf,1).real == inf
assert lambertw(inf,1).imag.ae(2*pi)
assert lambertw(-inf,1).real == inf
assert lambertw(-inf,1).imag.ae(3*pi)
assert lambertw(0,-1) == -inf
assert lambertw(0,1) == -inf
assert lambertw(0,3) == -inf
assert lambertw(e).ae(1)
assert lambertw(1).ae(0.567143290409783873)
assert lambertw(-pi/2).ae(j*pi/2)
assert lambertw(-log(2)/2).ae(-log(2))
assert lambertw(0.25).ae(0.203888354702240164)
assert lambertw(-0.25).ae(-0.357402956181388903)
assert lambertw(-1./10000,0).ae(-0.000100010001500266719)
assert lambertw(-0.25,-1).ae(-2.15329236411034965)
assert lambertw(0.25,-1).ae(-3.00899800997004620-4.07652978899159763j)
assert lambertw(-0.25,-1).ae(-2.15329236411034965)
assert lambertw(0.25,1).ae(-3.00899800997004620+4.07652978899159763j)
assert lambertw(-0.25,1).ae(-3.48973228422959210+7.41405453009603664j)
assert lambertw(-4).ae(0.67881197132094523+1.91195078174339937j)
assert lambertw(-4,1).ae(-0.66743107129800988+7.76827456802783084j)
assert lambertw(-4,-1).ae(0.67881197132094523-1.91195078174339937j)
assert lambertw(1000).ae(5.24960285240159623)
assert lambertw(1000,1).ae(4.91492239981054535+5.44652615979447070j)
assert lambertw(1000,-1).ae(4.91492239981054535-5.44652615979447070j)
assert lambertw(1000,5).ae(3.5010625305312892+29.9614548941181328j)
assert lambertw(3+4j).ae(1.281561806123775878+0.533095222020971071j)
assert lambertw(-0.4+0.4j).ae(-0.10396515323290657+0.61899273315171632j)
assert lambertw(3+4j,1).ae(-0.11691092896595324+5.61888039871282334j)
assert lambertw(3+4j,-1).ae(0.25856740686699742-3.85211668616143559j)
assert lambertw(-0.5,-1).ae(-0.794023632344689368-0.770111750510379110j)
assert lambertw(-1./10000,1).ae(-11.82350837248724344+6.80546081842002101j)
assert lambertw(-1./10000,-1).ae(-11.6671145325663544)
assert lambertw(-1./10000,-2).ae(-11.82350837248724344-6.80546081842002101j)
assert lambertw(-1./100000,4).ae(-14.9186890769540539+26.1856750178782046j)
assert lambertw(-1./100000,5).ae(-15.0931437726379218666+32.5525721210262290086j)
assert lambertw((2+j)/10).ae(0.173704503762911669+0.071781336752835511j)
assert lambertw((2+j)/10,1).ae(-3.21746028349820063+4.56175438896292539j)
assert lambertw((2+j)/10,-1).ae(-3.03781405002993088-3.53946629633505737j)
assert lambertw((2+j)/10,4).ae(-4.6878509692773249+23.8313630697683291j)
assert lambertw(-(2+j)/10).ae(-0.226933772515757933-0.164986470020154580j)
assert lambertw(-(2+j)/10,1).ae(-2.43569517046110001+0.76974067544756289j)
assert lambertw(-(2+j)/10,-1).ae(-3.54858738151989450-6.91627921869943589j)
assert lambertw(-(2+j)/10,4).ae(-4.5500846928118151+20.6672982215434637j)
mp.dps = 50
assert lambertw(pi).ae('1.073658194796149172092178407024821347547745350410314531')
mp.dps = 15
# Former bug in generated branch
assert lambertw(-0.5+0.002j).ae(-0.78917138132659918344 + 0.76743539379990327749j)
assert lambertw(-0.5-0.002j).ae(-0.78917138132659918344 - 0.76743539379990327749j)
assert lambertw(-0.448+0.4j).ae(-0.11855133765652382241 + 0.66570534313583423116j)
assert lambertw(-0.448-0.4j).ae(-0.11855133765652382241 - 0.66570534313583423116j)
def test_meijerg():
mp.dps = 15
assert meijerg([[2,3],[1]],[[0.5,2],[3,4]], 2.5).ae(4.2181028074787439386)
assert meijerg([[],[1+j]],[[1],[1]], 3+4j).ae(271.46290321152464592 - 703.03330399954820169j)
assert meijerg([[0.25],[1]],[[0.5],[2]],0) == 0
assert meijerg([[0],[]],[[0,0,'1/3','2/3'], []], '2/27').ae(2.2019391389653314120)
# Verify 1/z series being used
assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -0.5).ae(-1.338096165935754898687431)
assert meijerg([[1-(-1)],[1-(-2.5)]], [[1-(-3)],[1-(-0.5)]], -2.0).ae(-1.338096165935754898687431)
assert meijerg([[-3],[-0.5]], [[-1],[-2.5]], -1).ae(-(pi+4)/(4*pi))
a = 2.5
b = 1.25
for z in [mpf(0.25), mpf(2)]:
x1 = hyp1f1(a,b,z)
x2 = gamma(b)/gamma(a)*meijerg([[1-a],[]],[[0],[1-b]],-z)
x3 = gamma(b)/gamma(a)*meijerg([[1-0],[1-(1-b)]],[[1-(1-a)],[]],-1/z)
assert x1.ae(x2)
assert x1.ae(x3)
def test_appellf1():
mp.dps = 15
assert appellf1(2,-2,1,1,2,3).ae(-1.75)
assert appellf1(2,1,-2,1,2,3).ae(-8)
assert appellf1(2,1,-2,1,0.5,0.25).ae(1.5)
assert appellf1(-2,1,3,2,3,3).ae(19)
assert appellf1(1,2,3,4,0.5,0.125).ae( 1.53843285792549786518)
def test_coulomb():
# Note: most tests are doctests
# Test for a bug:
mp.dps = 15
assert coulombg(mpc(-5,0),2,3).ae(20.087729487721430394)
def test_hyper_param_accuracy():
mp.dps = 15
As = [n+1e-10 for n in range(-5,-1)]
Bs = [n+1e-10 for n in range(-12,-5)]
assert hyper(As,Bs,10).ae(-381757055858.652671927)
assert legenp(0.5, 100, 0.25).ae(-2.4124576567211311755e+144)
assert (hyp1f1(1000,1,-100)*10**24).ae(5.2589445437370169113)
assert (hyp2f1(10, -900, 10.5, 0.99)*10**24).ae(1.9185370579660768203)
assert (hyp2f1(1000,1.5,-3.5,-1.5)*10**385).ae(-2.7367529051334000764)
assert hyp2f1(-5, 10, 3, 0.5, zeroprec=500) == 0
assert (hyp1f1(-10000, 1000, 100)*10**424).ae(-3.1046080515824859974)
assert (hyp2f1(1000,1.5,-3.5,-0.75,maxterms=100000)*10**231).ae(-4.0534790813913998643)
assert legenp(2, 3, 0.25) == 0
try:
hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3])
assert 0
except ValueError:
pass
assert hypercomb(lambda a: [([],[],[],[],[a],[-a],0.5)], [3], infprec=200) == inf
assert meijerg([[],[]],[[0,0,0,0],[]],0.1).ae(1.5680822343832351418)
assert (besselk(400,400)*10**94).ae(1.4387057277018550583)
mp.dps = 5
(hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522)
(hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311)
mp.dps = 15
(hyp1f1(-5000.5, 1500, 100)*10**185).ae(8.5185229673381935522)
(hyp1f1(-5000, 1500, 100)*10**185).ae(9.1501213424563944311)
assert hyp0f1(fadd(-20,'1e-100',exact=True), 0.25).ae(1.85014429040102783e+49)
assert hyp0f1((-20*10**100+1, 10**100), 0.25).ae(1.85014429040102783e+49)
def test_hypercomb_zero_pow():
# check that 0^0 = 1
assert hypercomb(lambda a: (([0],[a],[],[],[],[],0),), [0]) == 1
assert meijerg([[-1.5],[]],[[0],[-0.75]],0).ae(1.4464090846320771425)
def test_spherharm():
mp.dps = 15
t = 0.5; r = 0.25
assert spherharm(0,0,t,r).ae(0.28209479177387814347)
assert spherharm(1,-1,t,r).ae(0.16048941205971996369 - 0.04097967481096344271j)
assert spherharm(1,0,t,r).ae(0.42878904414183579379)
assert spherharm(1,1,t,r).ae(-0.16048941205971996369 - 0.04097967481096344271j)
assert spherharm(2,-2,t,r).ae(0.077915886919031181734 - 0.042565643022253962264j)
assert spherharm(2,-1,t,r).ae(0.31493387233497459884 - 0.08041582001959297689j)
assert spherharm(2,0,t,r).ae(0.41330596756220761898)
assert spherharm(2,1,t,r).ae(-0.31493387233497459884 - 0.08041582001959297689j)
assert spherharm(2,2,t,r).ae(0.077915886919031181734 + 0.042565643022253962264j)
assert spherharm(3,-3,t,r).ae(0.033640236589690881646 - 0.031339125318637082197j)
assert spherharm(3,-2,t,r).ae(0.18091018743101461963 - 0.09883168583167010241j)
assert spherharm(3,-1,t,r).ae(0.42796713930907320351 - 0.10927795157064962317j)
assert spherharm(3,0,t,r).ae(0.27861659336351639787)
assert spherharm(3,1,t,r).ae(-0.42796713930907320351 - 0.10927795157064962317j)
assert spherharm(3,2,t,r).ae(0.18091018743101461963 + 0.09883168583167010241j)
assert spherharm(3,3,t,r).ae(-0.033640236589690881646 - 0.031339125318637082197j)
assert spherharm(0,-1,t,r) == 0
assert spherharm(0,-2,t,r) == 0
assert spherharm(0,1,t,r) == 0
assert spherharm(0,2,t,r) == 0
assert spherharm(1,2,t,r) == 0
assert spherharm(1,3,t,r) == 0
assert spherharm(1,-2,t,r) == 0
assert spherharm(1,-3,t,r) == 0
assert spherharm(2,3,t,r) == 0
assert spherharm(2,4,t,r) == 0
assert spherharm(2,-3,t,r) == 0
assert spherharm(2,-4,t,r) == 0
assert spherharm(3,4.5,0.5,0.25).ae(-22.831053442240790148 + 10.910526059510013757j)
assert spherharm(2+3j, 1-j, 1+j, 3+4j).ae(-2.6582752037810116935 - 1.0909214905642160211j)
assert spherharm(-6,2.5,t,r).ae(0.39383644983851448178 + 0.28414687085358299021j)
assert spherharm(-3.5, 3, 0.5, 0.25).ae(0.014516852987544698924 - 0.015582769591477628495j)
assert spherharm(-3, 3, 0.5, 0.25) == 0
assert spherharm(-6, 3, 0.5, 0.25).ae(-0.16544349818782275459 - 0.15412657723253924562j)
assert spherharm(-6, 1.5, 0.5, 0.25).ae(0.032208193499767402477 + 0.012678000924063664921j)
assert spherharm(3,0,0,1).ae(0.74635266518023078283)
assert spherharm(3,-2,0,1) == 0
assert spherharm(3,-2,1,1).ae(-0.16270707338254028971 - 0.35552144137546777097j)
def test_qfunctions():
mp.dps = 15
assert qp(2,3,100).ae('2.7291482267247332183e2391')<|fim▁end|> | assert ellipe(3+4j).ae(1.4995535209333469543-1.5778790079127582745j) |
<|file_name|>dns.go<|end_file_name|><|fim▁begin|>/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and<|fim▁hole|>limitations under the License.
*/
package e2e
import (
"fmt"
"strings"
"time"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/latest"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/fields"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/wait"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var dnsServiceLableSelector = labels.Set{
"k8s-app": "kube-dns",
"kubernetes.io/cluster-service": "true",
}.AsSelector()
func createDNSPod(namespace, wheezyProbeCmd, jessieProbeCmd string) *api.Pod {
pod := &api.Pod{
TypeMeta: api.TypeMeta{
Kind: "Pod",
APIVersion: latest.GroupOrDie("").Version,
},
ObjectMeta: api.ObjectMeta{
Name: "dns-test-" + string(util.NewUUID()),
Namespace: namespace,
},
Spec: api.PodSpec{
Volumes: []api.Volume{
{
Name: "results",
VolumeSource: api.VolumeSource{
EmptyDir: &api.EmptyDirVolumeSource{},
},
},
},
Containers: []api.Container{
// TODO: Consider scraping logs instead of running a webserver.
{
Name: "webserver",
Image: "gcr.io/google_containers/test-webserver",
Ports: []api.ContainerPort{
{
Name: "http",
ContainerPort: 80,
},
},
VolumeMounts: []api.VolumeMount{
{
Name: "results",
MountPath: "/results",
},
},
},
{
Name: "querier",
Image: "gcr.io/google_containers/dnsutils",
Command: []string{"sh", "-c", wheezyProbeCmd},
VolumeMounts: []api.VolumeMount{
{
Name: "results",
MountPath: "/results",
},
},
},
{
Name: "jessie-querier",
Image: "gcr.io/google_containers/jessie-dnsutils",
Command: []string{"sh", "-c", jessieProbeCmd},
VolumeMounts: []api.VolumeMount{
{
Name: "results",
MountPath: "/results",
},
},
},
},
},
}
return pod
}
func createProbeCommand(namesToResolve []string, fileNamePrefix string) (string, []string) {
fileNames := make([]string, 0, len(namesToResolve)*2)
probeCmd := "for i in `seq 1 600`; do "
for _, name := range namesToResolve {
// Resolve by TCP and UDP DNS. Use $$(...) because $(...) is
// expanded by kubernetes (though this won't expand so should
// remain a literal, safe > sorry).
lookup := "A"
if strings.HasPrefix(name, "_") {
lookup = "SRV"
}
fileName := fmt.Sprintf("%s_udp@%s", fileNamePrefix, name)
fileNames = append(fileNames, fileName)
probeCmd += fmt.Sprintf(`test -n "$$(dig +notcp +noall +answer +search %s %s)" && echo OK > /results/%s;`, name, lookup, fileName)
fileName = fmt.Sprintf("%s_tcp@%s", fileNamePrefix, name)
fileNames = append(fileNames, fileName)
probeCmd += fmt.Sprintf(`test -n "$$(dig +tcp +noall +answer +search %s %s)" && echo OK > /results/%s;`, name, lookup, fileName)
}
probeCmd += "sleep 1; done"
return probeCmd, fileNames
}
func assertFilesExist(fileNames []string, fileDir string, pod *api.Pod, client *client.Client) {
var failed []string
expectNoError(wait.Poll(time.Second*2, time.Second*60, func() (bool, error) {
failed = []string{}
for _, fileName := range fileNames {
if _, err := client.Get().
Prefix("proxy").
Resource("pods").
Namespace(pod.Namespace).
Name(pod.Name).
Suffix(fileDir, fileName).
Do().Raw(); err != nil {
Logf("Unable to read %s from pod %s: %v", fileName, pod.Name, err)
failed = append(failed, fileName)
}
}
if len(failed) == 0 {
return true, nil
}
Logf("Lookups using %s failed for: %v\n", pod.Name, failed)
return false, nil
}))
Expect(len(failed)).To(Equal(0))
}
func validateDNSResults(f *Framework, pod *api.Pod, fileNames []string) {
By("submitting the pod to kubernetes")
podClient := f.Client.Pods(f.Namespace.Name)
defer func() {
By("deleting the pod")
defer GinkgoRecover()
podClient.Delete(pod.Name, api.NewDeleteOptions(0))
}()
if _, err := podClient.Create(pod); err != nil {
Failf("Failed to create %s pod: %v", pod.Name, err)
}
expectNoError(f.WaitForPodRunning(pod.Name))
By("retrieving the pod")
pod, err := podClient.Get(pod.Name)
if err != nil {
Failf("Failed to get pod %s: %v", pod.Name, err)
}
// Try to find results for each expected name.
By("looking for the results for each expected name from probiers")
assertFilesExist(fileNames, "results", pod, f.Client)
// TODO: probe from the host, too.
Logf("DNS probes using %s succeeded\n", pod.Name)
}
var _ = Describe("DNS", func() {
f := NewFramework("dns")
It("should provide DNS for the cluster", func() {
// TODO: support DNS on vagrant #3580
SkipIfProviderIs("vagrant")
systemClient := f.Client.Pods(api.NamespaceSystem)
By("Waiting for DNS Service to be Running")
dnsPods, err := systemClient.List(dnsServiceLableSelector, fields.Everything())
if err != nil {
Failf("Failed to list all dns service pods")
}
if len(dnsPods.Items) != 1 {
Failf("Unexpected number of pods (%d) matches the label selector %v", len(dnsPods.Items), dnsServiceLableSelector.String())
}
expectNoError(waitForPodRunningInNamespace(f.Client, dnsPods.Items[0].Name, api.NamespaceSystem))
// All the names we need to be able to resolve.
// TODO: Spin up a separate test service and test that dns works for that service.
namesToResolve := []string{
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster.local",
"google.com",
}
// Added due to #8512. This is critical for GCE and GKE deployments.
if providerIs("gce", "gke") {
namesToResolve = append(namesToResolve, "metadata")
}
wheezyProbeCmd, wheezyFileNames := createProbeCommand(namesToResolve, "wheezy")
jessieProbeCmd, jessieFileNames := createProbeCommand(namesToResolve, "jessie")
// Run a pod which probes DNS and exposes the results by HTTP.
By("creating a pod to probe DNS")
pod := createDNSPod(f.Namespace.Name, wheezyProbeCmd, jessieProbeCmd)
validateDNSResults(f, pod, append(wheezyFileNames, jessieFileNames...))
})
It("should provide DNS for services", func() {
// TODO: support DNS on vagrant #3580
SkipIfProviderIs("vagrant")
systemClient := f.Client.Pods(api.NamespaceSystem)
By("Waiting for DNS Service to be Running")
dnsPods, err := systemClient.List(dnsServiceLableSelector, fields.Everything())
if err != nil {
Failf("Failed to list all dns service pods")
}
if len(dnsPods.Items) != 1 {
Failf("Unexpected number of pods (%d) matches the label selector %v", len(dnsPods.Items), dnsServiceLableSelector.String())
}
expectNoError(waitForPodRunningInNamespace(f.Client, dnsPods.Items[0].Name, api.NamespaceSystem))
// Create a test headless service.
By("Creating a test headless service")
testServiceSelector := map[string]string{
"dns-test": "true",
}
headlessService := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: "test-service",
},
Spec: api.ServiceSpec{
ClusterIP: "None",
Ports: []api.ServicePort{
{Port: 80, Name: "http", Protocol: "TCP"},
},
Selector: testServiceSelector,
},
}
_, err = f.Client.Services(f.Namespace.Name).Create(headlessService)
Expect(err).NotTo(HaveOccurred())
defer func() {
By("deleting the test headless service")
defer GinkgoRecover()
f.Client.Services(f.Namespace.Name).Delete(headlessService.Name)
}()
regularService := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: "test-service-2",
},
Spec: api.ServiceSpec{
Ports: []api.ServicePort{
{Port: 80, Name: "http", Protocol: "TCP"},
},
Selector: testServiceSelector,
},
}
_, err = f.Client.Services(f.Namespace.Name).Create(regularService)
Expect(err).NotTo(HaveOccurred())
defer func() {
By("deleting the test service")
defer GinkgoRecover()
f.Client.Services(f.Namespace.Name).Delete(regularService.Name)
}()
// All the names we need to be able to resolve.
// TODO: Create more endpoints and ensure that multiple A records are returned
// for headless service.
namesToResolve := []string{
fmt.Sprintf("%s", headlessService.Name),
fmt.Sprintf("%s.%s", headlessService.Name, f.Namespace.Name),
fmt.Sprintf("%s.%s.svc", headlessService.Name, f.Namespace.Name),
fmt.Sprintf("_http._tcp.%s.%s.svc", headlessService.Name, f.Namespace.Name),
fmt.Sprintf("_http._tcp.%s.%s.svc", regularService.Name, f.Namespace.Name),
}
wheezyProbeCmd, wheezyFileNames := createProbeCommand(namesToResolve, "wheezy")
jessieProbeCmd, jessieFileNames := createProbeCommand(namesToResolve, "jessie")
// Run a pod which probes DNS and exposes the results by HTTP.
By("creating a pod to probe DNS")
pod := createDNSPod(f.Namespace.Name, wheezyProbeCmd, jessieProbeCmd)
pod.ObjectMeta.Labels = testServiceSelector
validateDNSResults(f, pod, append(wheezyFileNames, jessieFileNames...))
})
})<|fim▁end|> | |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! See README.md
pub use self::Constraint::*;
pub use self::Verify::*;
pub use self::UndoLogEntry::*;
pub use self::CombineMapType::*;
pub use self::RegionResolutionError::*;
pub use self::VarValue::*;
use self::Classification::*;
use super::{RegionVariableOrigin, SubregionOrigin, TypeTrace, MiscVariable};
use rustc_data_structures::graph::{self, Direction, NodeIndex};
use middle::free_region::FreeRegionMap;
use middle::region;
use middle::ty::{self, Ty};
use middle::ty::{BoundRegion, FreeRegion, Region, RegionVid};
use middle::ty::{ReEmpty, ReStatic, ReInfer, ReFree, ReEarlyBound};
use middle::ty::{ReLateBound, ReScope, ReVar, ReSkolemized, BrFresh};
use middle::ty_relate::RelateResult;
use util::common::indenter;
use util::nodemap::{FnvHashMap, FnvHashSet};
use std::cell::{Cell, RefCell};
use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::fmt;
use std::u32;
use syntax::ast;
mod graphviz;
// A constraint that influences the inference process.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Constraint {
// One region variable is subregion of another
ConstrainVarSubVar(RegionVid, RegionVid),
// Concrete region is subregion of region variable
ConstrainRegSubVar(Region, RegionVid),
// Region variable is subregion of concrete region
ConstrainVarSubReg(RegionVid, Region),
}
// Something we have to verify after region inference is done, but
// which does not directly influence the inference process
pub enum Verify<'tcx> {
// VerifyRegSubReg(a, b): Verify that `a <= b`. Neither `a` nor
// `b` are inference variables.
VerifyRegSubReg(SubregionOrigin<'tcx>, Region, Region),
// VerifyGenericBound(T, _, R, RS): The parameter type `T` (or
// associated type) must outlive the region `R`. `T` is known to
// outlive `RS`. Therefore verify that `R <= RS[i]` for some
// `i`. Inference variables may be involved (but this verification
// step doesn't influence inference).
VerifyGenericBound(GenericKind<'tcx>, SubregionOrigin<'tcx>, Region, Vec<Region>),
}
#[derive(Clone, PartialEq, Eq)]
pub enum GenericKind<'tcx> {
Param(ty::ParamTy),
Projection(ty::ProjectionTy<'tcx>),
}
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct TwoRegions {
a: Region,
b: Region,
}
#[derive(Copy, Clone, PartialEq)]
pub enum UndoLogEntry {
OpenSnapshot,
CommitedSnapshot,
AddVar(RegionVid),
AddConstraint(Constraint),
AddVerify(usize),
AddGiven(ty::FreeRegion, ty::RegionVid),
AddCombination(CombineMapType, TwoRegions)
}
#[derive(Copy, Clone, PartialEq)]
pub enum CombineMapType {
Lub, Glb
}
#[derive(Clone, Debug)]
pub enum RegionResolutionError<'tcx> {
/// `ConcreteFailure(o, a, b)`:
///
/// `o` requires that `a <= b`, but this does not hold
ConcreteFailure(SubregionOrigin<'tcx>, Region, Region),
/// `GenericBoundFailure(p, s, a, bs)
///
/// The parameter/associated-type `p` must be known to outlive the lifetime
/// `a`, but it is only known to outlive `bs` (and none of the
/// regions in `bs` outlive `a`).
GenericBoundFailure(SubregionOrigin<'tcx>, GenericKind<'tcx>, Region, Vec<Region>),
/// `SubSupConflict(v, sub_origin, sub_r, sup_origin, sup_r)`:
///
/// Could not infer a value for `v` because `sub_r <= v` (due to
/// `sub_origin`) but `v <= sup_r` (due to `sup_origin`) and
/// `sub_r <= sup_r` does not hold.
SubSupConflict(RegionVariableOrigin,
SubregionOrigin<'tcx>, Region,
SubregionOrigin<'tcx>, Region),
/// `SupSupConflict(v, origin1, r1, origin2, r2)`:
///
/// Could not infer a value for `v` because `v <= r1` (due to
/// `origin1`) and `v <= r2` (due to `origin2`) and
/// `r1` and `r2` have no intersection.
SupSupConflict(RegionVariableOrigin,
SubregionOrigin<'tcx>, Region,
SubregionOrigin<'tcx>, Region),
/// For subsets of `ConcreteFailure` and `SubSupConflict`, we can derive
/// more specific errors message by suggesting to the user where they
/// should put a lifetime. In those cases we process and put those errors
/// into `ProcessedErrors` before we do any reporting.
ProcessedErrors(Vec<RegionVariableOrigin>,
Vec<(TypeTrace<'tcx>, ty::type_err<'tcx>)>,
Vec<SameRegions>),
}
/// SameRegions is used to group regions that we think are the same and would
/// like to indicate so to the user.
/// For example, the following function
/// ```
/// struct Foo { bar: int }
/// fn foo2<'a, 'b>(x: &'a Foo) -> &'b int {
/// &x.bar
/// }
/// ```
/// would report an error because we expect 'a and 'b to match, and so we group
/// 'a and 'b together inside a SameRegions struct
#[derive(Clone, Debug)]
pub struct SameRegions {
pub scope_id: ast::NodeId,
pub regions: Vec<BoundRegion>
}
impl SameRegions {
pub fn contains(&self, other: &BoundRegion) -> bool {
self.regions.contains(other)
}
pub fn push(&mut self, other: BoundRegion) {
self.regions.push(other);
}
}
pub type CombineMap = FnvHashMap<TwoRegions, RegionVid>;
pub struct RegionVarBindings<'a, 'tcx: 'a> {
tcx: &'a ty::ctxt<'tcx>,
var_origins: RefCell<Vec<RegionVariableOrigin>>,
// Constraints of the form `A <= B` introduced by the region
// checker. Here at least one of `A` and `B` must be a region
// variable.
constraints: RefCell<FnvHashMap<Constraint, SubregionOrigin<'tcx>>>,
// A "verify" is something that we need to verify after inference is
// done, but which does not directly affect inference in any way.
//
// An example is a `A <= B` where neither `A` nor `B` are
// inference variables.
verifys: RefCell<Vec<Verify<'tcx>>>,
// A "given" is a relationship that is known to hold. In particular,
// we often know from closure fn signatures that a particular free
// region must be a subregion of a region variable:
//
// foo.iter().filter(<'a> |x: &'a &'b T| ...)
//
// In situations like this, `'b` is in fact a region variable
// introduced by the call to `iter()`, and `'a` is a bound region
// on the closure (as indicated by the `<'a>` prefix). If we are
// naive, we wind up inferring that `'b` must be `'static`,
// because we require that it be greater than `'a` and we do not
// know what `'a` is precisely.
//
// This hashmap is used to avoid that naive scenario. Basically we
// record the fact that `'a <= 'b` is implied by the fn signature,
// and then ignore the constraint when solving equations. This is
// a bit of a hack but seems to work.
givens: RefCell<FnvHashSet<(ty::FreeRegion, ty::RegionVid)>>,
lubs: RefCell<CombineMap>,
glbs: RefCell<CombineMap>,
skolemization_count: Cell<u32>,
bound_count: Cell<u32>,
// The undo log records actions that might later be undone.
//
// Note: when the undo_log is empty, we are not actively
// snapshotting. When the `start_snapshot()` method is called, we
// push an OpenSnapshot entry onto the list to indicate that we
// are now actively snapshotting. The reason for this is that
// otherwise we end up adding entries for things like the lower
// bound on a variable and so forth, which can never be rolled
// back.
undo_log: RefCell<Vec<UndoLogEntry>>,
// This contains the results of inference. It begins as an empty
// option and only acquires a value after inference is complete.
values: RefCell<Option<Vec<VarValue>>>,
}
#[derive(Debug)]
pub struct RegionSnapshot {
length: usize,
skolemization_count: u32,
}
impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
pub fn new(tcx: &'a ty::ctxt<'tcx>) -> RegionVarBindings<'a, 'tcx> {
RegionVarBindings {
tcx: tcx,
var_origins: RefCell::new(Vec::new()),
values: RefCell::new(None),
constraints: RefCell::new(FnvHashMap()),
verifys: RefCell::new(Vec::new()),
givens: RefCell::new(FnvHashSet()),
lubs: RefCell::new(FnvHashMap()),
glbs: RefCell::new(FnvHashMap()),
skolemization_count: Cell::new(0),
bound_count: Cell::new(0),
undo_log: RefCell::new(Vec::new())
}
}
fn in_snapshot(&self) -> bool {
!self.undo_log.borrow().is_empty()
}
pub fn start_snapshot(&self) -> RegionSnapshot {
let length = self.undo_log.borrow().len();
debug!("RegionVarBindings: start_snapshot({})", length);
self.undo_log.borrow_mut().push(OpenSnapshot);
RegionSnapshot { length: length, skolemization_count: self.skolemization_count.get() }
}
pub fn commit(&self, snapshot: RegionSnapshot) {
debug!("RegionVarBindings: commit({})", snapshot.length);
assert!(self.undo_log.borrow().len() > snapshot.length);
assert!((*self.undo_log.borrow())[snapshot.length] == OpenSnapshot);
let mut undo_log = self.undo_log.borrow_mut();
if snapshot.length == 0 {
undo_log.truncate(0);
} else {
(*undo_log)[snapshot.length] = CommitedSnapshot;
}
self.skolemization_count.set(snapshot.skolemization_count);
}
pub fn rollback_to(&self, snapshot: RegionSnapshot) {
debug!("RegionVarBindings: rollback_to({:?})", snapshot);
let mut undo_log = self.undo_log.borrow_mut();
assert!(undo_log.len() > snapshot.length);
assert!((*undo_log)[snapshot.length] == OpenSnapshot);
while undo_log.len() > snapshot.length + 1 {
match undo_log.pop().unwrap() {
OpenSnapshot => {
panic!("Failure to observe stack discipline");
}
CommitedSnapshot => { }
AddVar(vid) => {
let mut var_origins = self.var_origins.borrow_mut();
var_origins.pop().unwrap();
assert_eq!(var_origins.len(), vid.index as usize);
}
AddConstraint(ref constraint) => {
self.constraints.borrow_mut().remove(constraint);
}
AddVerify(index) => {
self.verifys.borrow_mut().pop();
assert_eq!(self.verifys.borrow().len(), index);
}
AddGiven(sub, sup) => {
self.givens.borrow_mut().remove(&(sub, sup));
}
AddCombination(Glb, ref regions) => {
self.glbs.borrow_mut().remove(regions);
}
AddCombination(Lub, ref regions) => {
self.lubs.borrow_mut().remove(regions);
}
}
}
let c = undo_log.pop().unwrap();
assert!(c == OpenSnapshot);
self.skolemization_count.set(snapshot.skolemization_count);
}
pub fn num_vars(&self) -> u32 {
let len = self.var_origins.borrow().len();
// enforce no overflow
assert!(len as u32 as usize == len);
len as u32
}
pub fn new_region_var(&self, origin: RegionVariableOrigin) -> RegionVid {
let id = self.num_vars();
self.var_origins.borrow_mut().push(origin.clone());
let vid = RegionVid { index: id };
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddVar(vid));
}
debug!("created new region variable {:?} with origin {:?}",
vid, origin);
return vid;
}
/// Creates a new skolemized region. Skolemized regions are fresh
/// regions used when performing higher-ranked computations. They
/// must be used in a very particular way and are never supposed
/// to "escape" out into error messages or the code at large.
///
/// The idea is to always create a snapshot. Skolemized regions
/// can be created in the context of this snapshot, but once the
/// snapshot is committed or rolled back, their numbers will be
/// recycled, so you must be finished with them. See the extensive
/// comments in `higher_ranked.rs` to see how it works (in
/// particular, the subtyping comparison).
///
/// The `snapshot` argument to this function is not really used;
/// it's just there to make it explicit which snapshot bounds the
/// skolemized region that results.
pub fn new_skolemized(&self, br: ty::BoundRegion, snapshot: &RegionSnapshot) -> Region {
assert!(self.in_snapshot());
assert!(self.undo_log.borrow()[snapshot.length] == OpenSnapshot);
let sc = self.skolemization_count.get();
self.skolemization_count.set(sc + 1);
ReInfer(ReSkolemized(sc, br))
}
pub fn new_bound(&self, debruijn: ty::DebruijnIndex) -> Region {
// Creates a fresh bound variable for use in GLB computations.
// See discussion of GLB computation in the large comment at
// the top of this file for more details.
//
// This computation is potentially wrong in the face of
// rollover. It's conceivable, if unlikely, that one might
// wind up with accidental capture for nested functions in
// that case, if the outer function had bound regions created
// a very long time before and the inner function somehow
// wound up rolling over such that supposedly fresh
// identifiers were in fact shadowed. For now, we just assert
// that there is no rollover -- eventually we should try to be
// robust against this possibility, either by checking the set
// of bound identifiers that appear in a given expression and
// ensure that we generate one that is distinct, or by
// changing the representation of bound regions in a fn
// declaration
let sc = self.bound_count.get();
self.bound_count.set(sc + 1);
if sc >= self.bound_count.get() {
self.tcx.sess.bug("rollover in RegionInference new_bound()");
}
ReLateBound(debruijn, BrFresh(sc))
}
fn values_are_none(&self) -> bool {
self.values.borrow().is_none()
}
fn add_constraint(&self,
constraint: Constraint,
origin: SubregionOrigin<'tcx>) {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: add_constraint({:?})",
constraint);
if self.constraints.borrow_mut().insert(constraint, origin).is_none() {
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddConstraint(constraint));
}
}
}
fn add_verify(&self,
verify: Verify<'tcx>) {
// cannot add verifys once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: add_verify({:?})",
verify);
let mut verifys = self.verifys.borrow_mut();
let index = verifys.len();
verifys.push(verify);
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddVerify(index));
}
}
pub fn add_given(&self,
sub: ty::FreeRegion,
sup: ty::RegionVid) {
// cannot add givens once regions are resolved
assert!(self.values_are_none());
let mut givens = self.givens.borrow_mut();
if givens.insert((sub, sup)) {
debug!("add_given({:?} <= {:?})",
sub,
sup);
self.undo_log.borrow_mut().push(AddGiven(sub, sup));
}
}
pub fn make_eqregion(&self,
origin: SubregionOrigin<'tcx>,
sub: Region,
sup: Region) {
if sub != sup {
// Eventually, it would be nice to add direct support for
// equating regions.
self.make_subregion(origin.clone(), sub, sup);
self.make_subregion(origin, sup, sub);
}
}
pub fn make_subregion(&self,
origin: SubregionOrigin<'tcx>,
sub: Region,
sup: Region) {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: make_subregion({:?}, {:?}) due to {:?}",
sub,
sup,
origin);
match (sub, sup) {
(ReEarlyBound(..), ReEarlyBound(..)) => {
// This case is used only to make sure that explicitly-specified
// `Self` types match the real self type in implementations.
//
// FIXME(NDM) -- we really shouldn't be comparing bound things
self.add_verify(VerifyRegSubReg(origin, sub, sup));
}
(ReEarlyBound(..), _) |
(ReLateBound(..), _) |
(_, ReEarlyBound(..)) |
(_, ReLateBound(..)) => {
self.tcx.sess.span_bug(
origin.span(),
&format!("cannot relate bound region: {:?} <= {:?}",
sub,
sup));
}
(_, ReStatic) => {
// all regions are subregions of static, so we can ignore this
}
(ReInfer(ReVar(sub_id)), ReInfer(ReVar(sup_id))) => {
self.add_constraint(ConstrainVarSubVar(sub_id, sup_id), origin);
}
(r, ReInfer(ReVar(sup_id))) => {
self.add_constraint(ConstrainRegSubVar(r, sup_id), origin);
}
(ReInfer(ReVar(sub_id)), r) => {
self.add_constraint(ConstrainVarSubReg(sub_id, r), origin);
}
_ => {
self.add_verify(VerifyRegSubReg(origin, sub, sup));
}
}
}
/// See `Verify::VerifyGenericBound`
pub fn verify_generic_bound(&self,
origin: SubregionOrigin<'tcx>,
kind: GenericKind<'tcx>,
sub: Region,
sups: Vec<Region>) {
self.add_verify(VerifyGenericBound(kind, origin, sub, sups));
}
pub fn lub_regions(&self,
origin: SubregionOrigin<'tcx>,
a: Region,
b: Region)
-> Region {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: lub_regions({:?}, {:?})",
a,
b);
match (a, b) {
(ReStatic, _) | (_, ReStatic) => {
ReStatic // nothing lives longer than static
}
_ => {
self.combine_vars(
Lub, a, b, origin.clone(),
|this, old_r, new_r|
this.make_subregion(origin.clone(), old_r, new_r))
}
}
}
pub fn glb_regions(&self,
origin: SubregionOrigin<'tcx>,
a: Region,
b: Region)
-> Region {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: glb_regions({:?}, {:?})",
a,
b);
match (a, b) {
(ReStatic, r) | (r, ReStatic) => {
// static lives longer than everything else
r
}
_ => {
self.combine_vars(
Glb, a, b, origin.clone(),
|this, old_r, new_r|
this.make_subregion(origin.clone(), new_r, old_r))
}
}
}
pub fn resolve_var(&self, rid: RegionVid) -> ty::Region {
match *self.values.borrow() {
None => {
self.tcx.sess.span_bug(
(*self.var_origins.borrow())[rid.index as usize].span(),
"attempt to resolve region variable before values have \
been computed!")
}
Some(ref values) => {
let r = lookup(values, rid);
debug!("resolve_var({:?}) = {:?}", rid, r);
r
}
}
}
fn combine_map(&self, t: CombineMapType)
-> &RefCell<CombineMap> {
match t {
Glb => &self.glbs,
Lub => &self.lubs,
}
}
pub fn combine_vars<F>(&self,
t: CombineMapType,
a: Region,
b: Region,
origin: SubregionOrigin<'tcx>,
mut relate: F)
-> Region where
F: FnMut(&RegionVarBindings<'a, 'tcx>, Region, Region),
{
let vars = TwoRegions { a: a, b: b };
match self.combine_map(t).borrow().get(&vars) {
Some(&c) => {
return ReInfer(ReVar(c));
}
None => {}
}
let c = self.new_region_var(MiscVariable(origin.span()));
self.combine_map(t).borrow_mut().insert(vars, c);
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddCombination(t, vars));
}
relate(self, a, ReInfer(ReVar(c)));
relate(self, b, ReInfer(ReVar(c)));
debug!("combine_vars() c={:?}", c);
ReInfer(ReVar(c))
}
pub fn vars_created_since_snapshot(&self, mark: &RegionSnapshot)
-> Vec<RegionVid>
{
self.undo_log.borrow()[mark.length..]
.iter()
.filter_map(|&elt| match elt {
AddVar(vid) => Some(vid),
_ => None
})
.collect()
}
/// Computes all regions that have been related to `r0` in any way since the mark `mark` was
/// made---`r0` itself will be the first entry. This is used when checking whether skolemized
/// regions are being improperly related to other regions.
pub fn tainted(&self, mark: &RegionSnapshot, r0: Region) -> Vec<Region> {
debug!("tainted(mark={:?}, r0={:?})", mark, r0);
let _indenter = indenter();
// `result_set` acts as a worklist: we explore all outgoing
// edges and add any new regions we find to result_set. This
// is not a terribly efficient implementation.
let mut result_set = vec!(r0);
let mut result_index = 0;
while result_index < result_set.len() {
// nb: can't use usize::range() here because result_set grows
let r = result_set[result_index];
debug!("result_index={}, r={:?}", result_index, r);
for undo_entry in
self.undo_log.borrow()[mark.length..].iter()
{
match undo_entry {
&AddConstraint(ConstrainVarSubVar(a, b)) => {
consider_adding_bidirectional_edges(
&mut result_set, r,
ReInfer(ReVar(a)), ReInfer(ReVar(b)));
}
&AddConstraint(ConstrainRegSubVar(a, b)) => {
consider_adding_bidirectional_edges(
&mut result_set, r,
a, ReInfer(ReVar(b)));
}
&AddConstraint(ConstrainVarSubReg(a, b)) => {
consider_adding_bidirectional_edges(
&mut result_set, r,
ReInfer(ReVar(a)), b);
}
&AddGiven(a, b) => {
consider_adding_bidirectional_edges(
&mut result_set, r,
ReFree(a), ReInfer(ReVar(b)));
}
&AddVerify(i) => {
match (*self.verifys.borrow())[i] {
VerifyRegSubReg(_, a, b) => {
consider_adding_bidirectional_edges(
&mut result_set, r,
a, b);
}
VerifyGenericBound(_, _, a, ref bs) => {
for &b in bs {
consider_adding_bidirectional_edges(
&mut result_set, r,
a, b);
}
}
}
}
&AddCombination(..) |
&AddVar(..) |
&OpenSnapshot |
&CommitedSnapshot => {
}
}
}
result_index += 1;
}
return result_set;
fn consider_adding_bidirectional_edges(result_set: &mut Vec<Region>,
r: Region,
r1: Region,
r2: Region) {
consider_adding_directed_edge(result_set, r, r1, r2);
consider_adding_directed_edge(result_set, r, r2, r1);
}
fn consider_adding_directed_edge(result_set: &mut Vec<Region>,
r: Region,
r1: Region,
r2: Region) {
if r == r1 {
// Clearly, this is potentially inefficient.
if !result_set.iter().any(|x| *x == r2) {
result_set.push(r2);
}
}
}
}
/// This function performs the actual region resolution. It must be
/// called after all constraints have been added. It performs a
/// fixed-point iteration to find region values which satisfy all
/// constraints, assuming such values can be found; if they cannot,
/// errors are reported.
pub fn resolve_regions(&self,
free_regions: &FreeRegionMap,
subject_node: ast::NodeId)
-> Vec<RegionResolutionError<'tcx>>
{
debug!("RegionVarBindings: resolve_regions()");
let mut errors = vec!();
let v = self.infer_variable_values(free_regions, &mut errors, subject_node);
*self.values.borrow_mut() = Some(v);
errors
}
fn lub_concrete_regions(&self, free_regions: &FreeRegionMap, a: Region, b: Region) -> Region {
match (a, b) {
(ReLateBound(..), _) |
(_, ReLateBound(..)) |
(ReEarlyBound(..), _) |
(_, ReEarlyBound(..)) => {
self.tcx.sess.bug(
&format!("cannot relate bound region: LUB({:?}, {:?})",
a,
b));
}
(ReStatic, _) | (_, ReStatic) => {
ReStatic // nothing lives longer than static
}
(ReEmpty, r) | (r, ReEmpty) => {
r // everything lives longer than empty
}
(ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => {
self.tcx.sess.span_bug(
(*self.var_origins.borrow())[v_id.index as usize].span(),
&format!("lub_concrete_regions invoked with \
non-concrete regions: {:?}, {:?}",
a,
b));
}
(ReFree(ref fr), ReScope(s_id)) |
(ReScope(s_id), ReFree(ref fr)) => {
let f = ReFree(*fr);
// A "free" region can be interpreted as "some region
// at least as big as the block fr.scope_id". So, we can
// reasonably compare free regions and scopes:
let fr_scope = fr.scope.to_code_extent();
let r_id = self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id);
if r_id == fr_scope {
// if the free region's scope `fr.scope_id` is bigger than
// the scope region `s_id`, then the LUB is the free
// region itself:
f
} else {
// otherwise, we don't know what the free region is,
// so we must conservatively say the LUB is static:
ReStatic
}
}
(ReScope(a_id), ReScope(b_id)) => {
// The region corresponding to an outer block is a
// subtype of the region corresponding to an inner
// block.
ReScope(self.tcx.region_maps.nearest_common_ancestor(a_id, b_id))
}
(ReFree(ref a_fr), ReFree(ref b_fr)) => {
self.lub_free_regions(free_regions, a_fr, b_fr)
}
// For these types, we cannot define any additional
// relationship:
(ReInfer(ReSkolemized(..)), _) |
(_, ReInfer(ReSkolemized(..))) => {
if a == b {a} else {ReStatic}
}
}
}
/// Computes a region that encloses both free region arguments. Guarantee that if the same two
/// regions are given as argument, in any order, a consistent result is returned.
fn lub_free_regions(&self,
free_regions: &FreeRegionMap,
a: &FreeRegion,
b: &FreeRegion)
-> ty::Region
{
return match a.cmp(b) {
Less => helper(self, free_regions, a, b),
Greater => helper(self, free_regions, b, a),
Equal => ty::ReFree(*a)
};
fn helper(_this: &RegionVarBindings,
free_regions: &FreeRegionMap,
a: &FreeRegion,
b: &FreeRegion) -> ty::Region
{
if free_regions.sub_free_region(*a, *b) {
ty::ReFree(*b)
} else if free_regions.sub_free_region(*b, *a) {
ty::ReFree(*a)
} else {
ty::ReStatic
}
}
}
fn glb_concrete_regions(&self,
free_regions: &FreeRegionMap,
a: Region,
b: Region)
-> RelateResult<'tcx, Region>
{
debug!("glb_concrete_regions({:?}, {:?})", a, b);
match (a, b) {
(ReLateBound(..), _) |
(_, ReLateBound(..)) |
(ReEarlyBound(..), _) |
(_, ReEarlyBound(..)) => {
self.tcx.sess.bug(
&format!("cannot relate bound region: GLB({:?}, {:?})",
a,
b));
}
(ReStatic, r) | (r, ReStatic) => {
// static lives longer than everything else
Ok(r)
}
(ReEmpty, _) | (_, ReEmpty) => {
// nothing lives shorter than everything else
Ok(ReEmpty)
}
(ReInfer(ReVar(v_id)), _) |
(_, ReInfer(ReVar(v_id))) => {
self.tcx.sess.span_bug(
(*self.var_origins.borrow())[v_id.index as usize].span(),
&format!("glb_concrete_regions invoked with \
non-concrete regions: {:?}, {:?}",
a,
b));
}
(ReFree(ref fr), ReScope(s_id)) |
(ReScope(s_id), ReFree(ref fr)) => {
let s = ReScope(s_id);
// Free region is something "at least as big as
// `fr.scope_id`." If we find that the scope `fr.scope_id` is bigger
// than the scope `s_id`, then we can say that the GLB
// is the scope `s_id`. Otherwise, as we do not know
// big the free region is precisely, the GLB is undefined.
let fr_scope = fr.scope.to_code_extent();
if self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id) == fr_scope {
Ok(s)
} else {
Err(ty::terr_regions_no_overlap(b, a))
}
}
(ReScope(a_id), ReScope(b_id)) => {
self.intersect_scopes(a, b, a_id, b_id)
}
(ReFree(ref a_fr), ReFree(ref b_fr)) => {
self.glb_free_regions(free_regions, a_fr, b_fr)
}
// For these types, we cannot define any additional
// relationship:
(ReInfer(ReSkolemized(..)), _) |
(_, ReInfer(ReSkolemized(..))) => {
if a == b {
Ok(a)
} else {
Err(ty::terr_regions_no_overlap(b, a))
}
}
}
}
/// Computes a region that is enclosed by both free region arguments, if any. Guarantees that
/// if the same two regions are given as argument, in any order, a consistent result is
/// returned.
fn glb_free_regions(&self,
free_regions: &FreeRegionMap,
a: &FreeRegion,
b: &FreeRegion)
-> RelateResult<'tcx, ty::Region>
{
return match a.cmp(b) {
Less => helper(self, free_regions, a, b),
Greater => helper(self, free_regions, b, a),
Equal => Ok(ty::ReFree(*a))
};
fn helper<'a, 'tcx>(this: &RegionVarBindings<'a, 'tcx>,
free_regions: &FreeRegionMap,
a: &FreeRegion,
b: &FreeRegion) -> RelateResult<'tcx, ty::Region>
{
if free_regions.sub_free_region(*a, *b) {
Ok(ty::ReFree(*a))
} else if free_regions.sub_free_region(*b, *a) {
Ok(ty::ReFree(*b))
} else {
this.intersect_scopes(ty::ReFree(*a), ty::ReFree(*b),
a.scope.to_code_extent(),
b.scope.to_code_extent())
}
}
}
fn intersect_scopes(&self,
region_a: ty::Region,
region_b: ty::Region,
scope_a: region::CodeExtent,
scope_b: region::CodeExtent)
-> RelateResult<'tcx, Region>
{
// We want to generate the intersection of two
// scopes or two free regions. So, if one of
// these scopes is a subscope of the other, return
// it. Otherwise fail.
debug!("intersect_scopes(scope_a={:?}, scope_b={:?}, region_a={:?}, region_b={:?})",
scope_a, scope_b, region_a, region_b);
let r_id = self.tcx.region_maps.nearest_common_ancestor(scope_a, scope_b);
if r_id == scope_a {
Ok(ReScope(scope_b))
} else if r_id == scope_b {
Ok(ReScope(scope_a))
} else {
Err(ty::terr_regions_no_overlap(region_a, region_b))
}
}
}
// ______________________________________________________________________
#[derive(Copy, Clone, PartialEq, Debug)]
enum Classification { Expanding, Contracting }
#[derive(Copy, Clone, Debug)]
pub enum VarValue { NoValue, Value(Region), ErrorValue }
struct VarData {
classification: Classification,
value: VarValue,
}
struct RegionAndOrigin<'tcx> {
region: Region,
origin: SubregionOrigin<'tcx>,
}
type RegionGraph = graph::Graph<(), Constraint>;
impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
fn infer_variable_values(&self,
free_regions: &FreeRegionMap,
errors: &mut Vec<RegionResolutionError<'tcx>>,
subject: ast::NodeId) -> Vec<VarValue>
{
let mut var_data = self.construct_var_data();
// Dorky hack to cause `dump_constraints` to only get called
// if debug mode is enabled:
debug!("----() End constraint listing (subject={}) {:?}---",
subject, self.dump_constraints(subject));
graphviz::maybe_print_constraints_for(self, subject);
let graph = self.construct_graph();
self.expand_givens(&graph);
self.expansion(free_regions, &mut var_data);
self.contraction(free_regions, &mut var_data);
let values =
self.extract_values_and_collect_conflicts(free_regions,
&var_data,
&graph,
errors);
self.collect_concrete_region_errors(free_regions, &values, errors);
values
}
fn construct_var_data(&self) -> Vec<VarData> {
(0..self.num_vars() as usize).map(|_| {
VarData {
// All nodes are initially classified as contracting; during
// the expansion phase, we will shift the classification for
// those nodes that have a concrete region predecessor to
// Expanding.
classification: Contracting,
value: NoValue,
}
}).collect()
}
fn dump_constraints(&self, subject: ast::NodeId) {
debug!("----() Start constraint listing (subject={}) ()----", subject);
for (idx, (constraint, _)) in self.constraints.borrow().iter().enumerate() {
debug!("Constraint {} => {:?}", idx, constraint);
}
}
fn expand_givens(&self, graph: &RegionGraph) {
// Givens are a kind of horrible hack to account for
// constraints like 'c <= '0 that are known to hold due to
// closure signatures (see the comment above on the `givens`
// field). They should go away. But until they do, the role
// of this fn is to account for the transitive nature:
//
// Given 'c <= '0
// and '0 <= '1
// then 'c <= '1
let mut givens = self.givens.borrow_mut();
let seeds: Vec<_> = givens.iter().cloned().collect();
for (fr, vid) in seeds {
let seed_index = NodeIndex(vid.index as usize);
for succ_index in graph.depth_traverse(seed_index) {
let succ_index = succ_index.0 as u32;
if succ_index < self.num_vars() {
let succ_vid = RegionVid { index: succ_index };
givens.insert((fr, succ_vid));
}
}
}
}
fn expansion(&self, free_regions: &FreeRegionMap, var_data: &mut [VarData]) {
self.iterate_until_fixed_point("Expansion", |constraint| {
debug!("expansion: constraint={:?} origin={:?}",
constraint,
self.constraints.borrow()
.get(constraint)
.unwrap()
);
match *constraint {
ConstrainRegSubVar(a_region, b_vid) => {
let b_data = &mut var_data[b_vid.index as usize];
self.expand_node(free_regions, a_region, b_vid, b_data)
}
ConstrainVarSubVar(a_vid, b_vid) => {
match var_data[a_vid.index as usize].value {
NoValue | ErrorValue => false,
Value(a_region) => {
let b_node = &mut var_data[b_vid.index as usize];
self.expand_node(free_regions, a_region, b_vid, b_node)
}
}
}
ConstrainVarSubReg(..) => {
// This is a contraction constraint. Ignore it.
false
}
}
})
}
fn expand_node(&self,
free_regions: &FreeRegionMap,
a_region: Region,
b_vid: RegionVid,
b_data: &mut VarData)
-> bool
{
debug!("expand_node({:?}, {:?} == {:?})",
a_region,
b_vid,
b_data.value);
// Check if this relationship is implied by a given.
match a_region {
ty::ReFree(fr) => {
if self.givens.borrow().contains(&(fr, b_vid)) {
debug!("given");
return false;
}
}
_ => { }
}
b_data.classification = Expanding;
match b_data.value {
NoValue => {
debug!("Setting initial value of {:?} to {:?}",
b_vid, a_region);
b_data.value = Value(a_region);
return true;
}
Value(cur_region) => {
let lub = self.lub_concrete_regions(free_regions, a_region, cur_region);
if lub == cur_region {
return false;
}
debug!("Expanding value of {:?} from {:?} to {:?}",
b_vid,
cur_region,
lub);
b_data.value = Value(lub);
return true;
}
ErrorValue => {
return false;
}
}
}
fn contraction(&self,
free_regions: &FreeRegionMap,
var_data: &mut [VarData]) {
self.iterate_until_fixed_point("Contraction", |constraint| {
debug!("contraction: constraint={:?} origin={:?}",
constraint,
self.constraints.borrow()
.get(constraint)
.unwrap()
);
match *constraint {
ConstrainRegSubVar(..) => {
// This is an expansion constraint. Ignore.
false
}
ConstrainVarSubVar(a_vid, b_vid) => {
match var_data[b_vid.index as usize].value {
NoValue | ErrorValue => false,
Value(b_region) => {
let a_data = &mut var_data[a_vid.index as usize];
self.contract_node(free_regions, a_vid, a_data, b_region)
}
}
}
ConstrainVarSubReg(a_vid, b_region) => {
let a_data = &mut var_data[a_vid.index as usize];
self.contract_node(free_regions, a_vid, a_data, b_region)
}
}
})
}
fn contract_node(&self,
free_regions: &FreeRegionMap,
a_vid: RegionVid,
a_data: &mut VarData,
b_region: Region)
-> bool {
debug!("contract_node({:?} == {:?}/{:?}, {:?})",
a_vid, a_data.value,
a_data.classification, b_region);
return match a_data.value {
NoValue => {
assert_eq!(a_data.classification, Contracting);
a_data.value = Value(b_region);
true // changed
}
ErrorValue => false, // no change
Value(a_region) => {
match a_data.classification {
Expanding =>
check_node(self, free_regions, a_vid, a_data, a_region, b_region),
Contracting =>
adjust_node(self, free_regions, a_vid, a_data, a_region, b_region),
}
}
};
fn check_node(this: &RegionVarBindings,
free_regions: &FreeRegionMap,
a_vid: RegionVid,
a_data: &mut VarData,
a_region: Region,
b_region: Region)
-> bool
{
if !free_regions.is_subregion_of(this.tcx, a_region, b_region) {
debug!("Setting {:?} to ErrorValue: {:?} not subregion of {:?}",
a_vid,
a_region,
b_region);
a_data.value = ErrorValue;
}
false
}
fn adjust_node(this: &RegionVarBindings,
free_regions: &FreeRegionMap,
a_vid: RegionVid,
a_data: &mut VarData,<|fim▁hole|> match this.glb_concrete_regions(free_regions, a_region, b_region) {
Ok(glb) => {
if glb == a_region {
false
} else {
debug!("Contracting value of {:?} from {:?} to {:?}",
a_vid,
a_region,
glb);
a_data.value = Value(glb);
true
}
}
Err(_) => {
debug!("Setting {:?} to ErrorValue: no glb of {:?}, {:?}",
a_vid,
a_region,
b_region);
a_data.value = ErrorValue;
false
}
}
}
}
fn collect_concrete_region_errors(&self,
free_regions: &FreeRegionMap,
values: &Vec<VarValue>,
errors: &mut Vec<RegionResolutionError<'tcx>>)
{
let mut reg_reg_dups = FnvHashSet();
for verify in self.verifys.borrow().iter() {
match *verify {
VerifyRegSubReg(ref origin, sub, sup) => {
if free_regions.is_subregion_of(self.tcx, sub, sup) {
continue;
}
if !reg_reg_dups.insert((sub, sup)) {
continue;
}
debug!("ConcreteFailure: !(sub <= sup): sub={:?}, sup={:?}",
sub,
sup);
errors.push(ConcreteFailure((*origin).clone(), sub, sup));
}
VerifyGenericBound(ref kind, ref origin, sub, ref sups) => {
let sub = normalize(values, sub);
if sups.iter()
.map(|&sup| normalize(values, sup))
.any(|sup| free_regions.is_subregion_of(self.tcx, sub, sup))
{
continue;
}
let sups = sups.iter().map(|&sup| normalize(values, sup))
.collect();
errors.push(
GenericBoundFailure(
(*origin).clone(), kind.clone(), sub, sups));
}
}
}
}
fn extract_values_and_collect_conflicts(
&self,
free_regions: &FreeRegionMap,
var_data: &[VarData],
graph: &RegionGraph,
errors: &mut Vec<RegionResolutionError<'tcx>>)
-> Vec<VarValue>
{
debug!("extract_values_and_collect_conflicts()");
// This is the best way that I have found to suppress
// duplicate and related errors. Basically we keep a set of
// flags for every node. Whenever an error occurs, we will
// walk some portion of the graph looking to find pairs of
// conflicting regions to report to the user. As we walk, we
// trip the flags from false to true, and if we find that
// we've already reported an error involving any particular
// node we just stop and don't report the current error. The
// idea is to report errors that derive from independent
// regions of the graph, but not those that derive from
// overlapping locations.
let mut dup_vec = vec![u32::MAX; self.num_vars() as usize];
for idx in 0..self.num_vars() as usize {
match var_data[idx].value {
Value(_) => {
/* Inference successful */
}
NoValue => {
/* Unconstrained inference: do not report an error
until the value of this variable is requested.
After all, sometimes we make region variables but never
really use their values. */
}
ErrorValue => {
/* Inference impossible, this value contains
inconsistent constraints.
I think that in this case we should report an
error now---unlike the case above, we can't
wait to see whether the user needs the result
of this variable. The reason is that the mere
existence of this variable implies that the
region graph is inconsistent, whether or not it
is used.
For example, we may have created a region
variable that is the GLB of two other regions
which do not have a GLB. Even if that variable
is not used, it implies that those two regions
*should* have a GLB.
At least I think this is true. It may be that
the mere existence of a conflict in a region variable
that is not used is not a problem, so if this rule
starts to create problems we'll have to revisit
this portion of the code and think hard about it. =) */
let node_vid = RegionVid { index: idx as u32 };
match var_data[idx].classification {
Expanding => {
self.collect_error_for_expanding_node(
free_regions, graph, var_data, &mut dup_vec,
node_vid, errors);
}
Contracting => {
self.collect_error_for_contracting_node(
free_regions, graph, var_data, &mut dup_vec,
node_vid, errors);
}
}
}
}
}
// Check for future hostile edges tied to a bad default
self.report_future_hostility(&graph);
(0..self.num_vars() as usize).map(|idx| var_data[idx].value).collect()
}
fn report_future_hostility(&self, graph: &RegionGraph) {
let constraints = self.constraints.borrow();
for edge in graph.all_edges() {
match constraints[&edge.data] {
SubregionOrigin::DefaultExistentialBound(_) => {
// this will become 'static in the future
}
_ => { continue; }
}
// this constraint will become a 'static constraint in the
// future, so walk outward and see if we have any hard
// bounds that could not be inferred to 'static
for nid in graph.depth_traverse(edge.target()) {
for (_, succ) in graph.outgoing_edges(nid) {
match succ.data {
ConstrainVarSubReg(_, r) => {
match r {
ty::ReStatic | ty::ReInfer(_) => {
/* OK */
}
ty::ReFree(_) | ty::ReScope(_) | ty::ReEmpty => {
span_warn!(
self.tcx.sess,
constraints[&edge.data].span(),
E0398,
"this code may fail to compile in Rust 1.3 due to \
the proposed change in object lifetime bound defaults");
return; // only issue the warning once per fn
}
ty::ReEarlyBound(..) | ty::ReLateBound(..) => {
self.tcx.sess.span_bug(
constraints[&succ.data].span(),
"relation to bound region");
}
}
}
_ => { }
}
}
}
}
}
fn construct_graph(&self) -> RegionGraph {
let num_vars = self.num_vars();
let constraints = self.constraints.borrow();
let mut graph = graph::Graph::new();
for _ in 0..num_vars {
graph.add_node(());
}
let dummy_idx = graph.add_node(());
for (constraint, _) in constraints.iter() {
match *constraint {
ConstrainVarSubVar(a_id, b_id) => {
graph.add_edge(NodeIndex(a_id.index as usize),
NodeIndex(b_id.index as usize),
*constraint);
}
ConstrainRegSubVar(_, b_id) => {
graph.add_edge(dummy_idx,
NodeIndex(b_id.index as usize),
*constraint);
}
ConstrainVarSubReg(a_id, _) => {
graph.add_edge(NodeIndex(a_id.index as usize),
dummy_idx,
*constraint);
}
}
}
return graph;
}
fn collect_error_for_expanding_node(&self,
free_regions: &FreeRegionMap,
graph: &RegionGraph,
var_data: &[VarData],
dup_vec: &mut [u32],
node_idx: RegionVid,
errors: &mut Vec<RegionResolutionError<'tcx>>)
{
// Errors in expanding nodes result from a lower-bound that is
// not contained by an upper-bound.
let (mut lower_bounds, lower_dup) =
self.collect_concrete_regions(graph, var_data, node_idx,
graph::INCOMING, dup_vec);
let (mut upper_bounds, upper_dup) =
self.collect_concrete_regions(graph, var_data, node_idx,
graph::OUTGOING, dup_vec);
if lower_dup || upper_dup {
return;
}
// We place free regions first because we are special casing
// SubSupConflict(ReFree, ReFree) when reporting error, and so
// the user will more likely get a specific suggestion.
fn free_regions_first(a: &RegionAndOrigin,
b: &RegionAndOrigin)
-> Ordering {
match (a.region, b.region) {
(ReFree(..), ReFree(..)) => Equal,
(ReFree(..), _) => Less,
(_, ReFree(..)) => Greater,
(_, _) => Equal,
}
}
lower_bounds.sort_by(|a, b| { free_regions_first(a, b) });
upper_bounds.sort_by(|a, b| { free_regions_first(a, b) });
for lower_bound in &lower_bounds {
for upper_bound in &upper_bounds {
if !free_regions.is_subregion_of(self.tcx,
lower_bound.region,
upper_bound.region) {
debug!("pushing SubSupConflict sub: {:?} sup: {:?}",
lower_bound.region, upper_bound.region);
errors.push(SubSupConflict(
(*self.var_origins.borrow())[node_idx.index as usize].clone(),
lower_bound.origin.clone(),
lower_bound.region,
upper_bound.origin.clone(),
upper_bound.region));
return;
}
}
}
self.tcx.sess.span_bug(
(*self.var_origins.borrow())[node_idx.index as usize].span(),
&format!("collect_error_for_expanding_node() could not find error \
for var {:?}, lower_bounds={:?}, upper_bounds={:?}",
node_idx,
lower_bounds,
upper_bounds));
}
fn collect_error_for_contracting_node(
&self,
free_regions: &FreeRegionMap,
graph: &RegionGraph,
var_data: &[VarData],
dup_vec: &mut [u32],
node_idx: RegionVid,
errors: &mut Vec<RegionResolutionError<'tcx>>)
{
// Errors in contracting nodes result from two upper-bounds
// that have no intersection.
let (upper_bounds, dup_found) =
self.collect_concrete_regions(graph, var_data, node_idx,
graph::OUTGOING, dup_vec);
if dup_found {
return;
}
for upper_bound_1 in &upper_bounds {
for upper_bound_2 in &upper_bounds {
match self.glb_concrete_regions(free_regions,
upper_bound_1.region,
upper_bound_2.region) {
Ok(_) => {}
Err(_) => {
errors.push(SupSupConflict(
(*self.var_origins.borrow())[node_idx.index as usize].clone(),
upper_bound_1.origin.clone(),
upper_bound_1.region,
upper_bound_2.origin.clone(),
upper_bound_2.region));
return;
}
}
}
}
self.tcx.sess.span_bug(
(*self.var_origins.borrow())[node_idx.index as usize].span(),
&format!("collect_error_for_contracting_node() could not find error \
for var {:?}, upper_bounds={:?}",
node_idx,
upper_bounds));
}
fn collect_concrete_regions(&self,
graph: &RegionGraph,
var_data: &[VarData],
orig_node_idx: RegionVid,
dir: Direction,
dup_vec: &mut [u32])
-> (Vec<RegionAndOrigin<'tcx>>, bool) {
struct WalkState<'tcx> {
set: FnvHashSet<RegionVid>,
stack: Vec<RegionVid>,
result: Vec<RegionAndOrigin<'tcx>>,
dup_found: bool
}
let mut state = WalkState {
set: FnvHashSet(),
stack: vec!(orig_node_idx),
result: Vec::new(),
dup_found: false
};
state.set.insert(orig_node_idx);
// to start off the process, walk the source node in the
// direction specified
process_edges(self, &mut state, graph, orig_node_idx, dir);
while !state.stack.is_empty() {
let node_idx = state.stack.pop().unwrap();
let classification = var_data[node_idx.index as usize].classification;
// check whether we've visited this node on some previous walk
if dup_vec[node_idx.index as usize] == u32::MAX {
dup_vec[node_idx.index as usize] = orig_node_idx.index;
} else if dup_vec[node_idx.index as usize] != orig_node_idx.index {
state.dup_found = true;
}
debug!("collect_concrete_regions(orig_node_idx={:?}, node_idx={:?}, \
classification={:?})",
orig_node_idx, node_idx, classification);
// figure out the direction from which this node takes its
// values, and search for concrete regions etc in that direction
let dir = match classification {
Expanding => graph::INCOMING,
Contracting => graph::OUTGOING,
};
process_edges(self, &mut state, graph, node_idx, dir);
}
let WalkState {result, dup_found, ..} = state;
return (result, dup_found);
fn process_edges<'a, 'tcx>(this: &RegionVarBindings<'a, 'tcx>,
state: &mut WalkState<'tcx>,
graph: &RegionGraph,
source_vid: RegionVid,
dir: Direction) {
debug!("process_edges(source_vid={:?}, dir={:?})", source_vid, dir);
let source_node_index = NodeIndex(source_vid.index as usize);
for (_, edge) in graph.adjacent_edges(source_node_index, dir) {
match edge.data {
ConstrainVarSubVar(from_vid, to_vid) => {
let opp_vid =
if from_vid == source_vid {to_vid} else {from_vid};
if state.set.insert(opp_vid) {
state.stack.push(opp_vid);
}
}
ConstrainRegSubVar(region, _) |
ConstrainVarSubReg(_, region) => {
state.result.push(RegionAndOrigin {
region: region,
origin: this.constraints.borrow().get(&edge.data).unwrap().clone()
});
}
}
}
}
}
fn iterate_until_fixed_point<F>(&self, tag: &str, mut body: F) where
F: FnMut(&Constraint) -> bool,
{
let mut iteration = 0;
let mut changed = true;
while changed {
changed = false;
iteration += 1;
debug!("---- {} Iteration {}{}", "#", tag, iteration);
for (constraint, _) in self.constraints.borrow().iter() {
let edge_changed = body(constraint);
if edge_changed {
debug!("Updated due to constraint {:?}",
constraint);
changed = true;
}
}
}
debug!("---- {} Complete after {} iteration(s)", tag, iteration);
}
}
impl<'tcx> fmt::Debug for Verify<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
VerifyRegSubReg(_, ref a, ref b) => {
write!(f, "VerifyRegSubReg({:?}, {:?})", a, b)
}
VerifyGenericBound(_, ref p, ref a, ref bs) => {
write!(f, "VerifyGenericBound({:?}, {:?}, {:?})", p, a, bs)
}
}
}
}
fn normalize(values: &Vec<VarValue>, r: ty::Region) -> ty::Region {
match r {
ty::ReInfer(ReVar(rid)) => lookup(values, rid),
_ => r
}
}
fn lookup(values: &Vec<VarValue>, rid: ty::RegionVid) -> ty::Region {
match values[rid.index as usize] {
Value(r) => r,
NoValue => ReEmpty, // No constraints, return ty::ReEmpty
ErrorValue => ReStatic, // Previously reported error.
}
}
impl<'tcx> fmt::Debug for RegionAndOrigin<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RegionAndOrigin({:?},{:?})",
self.region,
self.origin)
}
}
impl<'tcx> fmt::Debug for GenericKind<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GenericKind::Param(ref p) => write!(f, "{:?}", p),
GenericKind::Projection(ref p) => write!(f, "{:?}", p),
}
}
}
impl<'tcx> fmt::Display for GenericKind<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GenericKind::Param(ref p) => write!(f, "{}", p),
GenericKind::Projection(ref p) => write!(f, "{}", p),
}
}
}
impl<'tcx> GenericKind<'tcx> {
pub fn to_ty(&self, tcx: &ty::ctxt<'tcx>) -> Ty<'tcx> {
match *self {
GenericKind::Param(ref p) =>
p.to_ty(tcx),
GenericKind::Projection(ref p) =>
tcx.mk_projection(p.trait_ref.clone(), p.item_name),
}
}
}<|fim▁end|> | a_region: Region,
b_region: Region)
-> bool { |
<|file_name|>messaging.py<|end_file_name|><|fim▁begin|><|fim▁hole|># 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.
import eventlet
from oslo_config import cfg
import oslo_messaging as messaging
from osprofiler import profiler
from senlin.common import consts
from senlin.common import context
# An alias for the default serializer
JsonPayloadSerializer = messaging.JsonPayloadSerializer
TRANSPORT = None
NOTIFICATION_TRANSPORT = None
NOTIFIER = None
class RequestContextSerializer(messaging.Serializer):
def __init__(self, base):
self._base = base
def serialize_entity(self, ctxt, entity):
if not self._base:
return entity
return self._base.serialize_entity(ctxt, entity)
def deserialize_entity(self, ctxt, entity):
if not self._base:
return entity
return self._base.deserialize_entity(ctxt, entity)
@staticmethod
def serialize_context(ctxt):
_context = ctxt.to_dict()
prof = profiler.get()
if prof:
trace_info = {
"hmac_key": prof.hmac_key,
"base_id": prof.get_base_id(),
"parent_id": prof.get_id()
}
_context.update({"trace_info": trace_info})
return _context
@staticmethod
def deserialize_context(ctxt):
trace_info = ctxt.pop("trace_info", None)
if trace_info:
profiler.init(**trace_info)
return context.RequestContext.from_dict(ctxt)
def setup(url=None, optional=False):
"""Initialise the oslo_messaging layer."""
global TRANSPORT, GLOBAL_TRANSPORT, NOTIFIER
if url and url.startswith("fake://"):
# NOTE: oslo_messaging fake driver uses time.sleep
# for task switch, so we need to monkey_patch it
eventlet.monkey_patch(time=True)
messaging.set_transport_defaults('senlin')
if not TRANSPORT:
exmods = ['senlin.common.exception']
try:
TRANSPORT = messaging.get_rpc_transport(
cfg.CONF, url, allowed_remote_exmods=exmods)
except messaging.InvalidTransportURL as e:
TRANSPORT = None
if not optional or e.url:
# NOTE: oslo_messaging is configured but unloadable
# so reraise the exception
raise
if not NOTIFIER:
exmods = ['senlin.common.exception']
try:
NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
cfg.CONF, allowed_remote_exmods=exmods)
except Exception as e:
raise
serializer = RequestContextSerializer(JsonPayloadSerializer())
NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
serializer=serializer,
topics=cfg.CONF.notification_topics)
def cleanup():
"""Cleanup the oslo_messaging layer."""
global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
if TRANSPORT:
TRANSPORT.cleanup()
TRANSPORT = None
NOTIFIER = None
if NOTIFICATION_TRANSPORT:
NOTIFICATION_TRANSPORT.cleanup()
NOTIFICATION_TRANSPORT = None
def get_rpc_server(target, endpoint, serializer=None):
"""Return a configured oslo_messaging rpc server."""
if serializer is None:
serializer = JsonPayloadSerializer()
serializer = RequestContextSerializer(serializer)
return messaging.get_rpc_server(TRANSPORT, target, [endpoint],
executor='eventlet',
serializer=serializer)
def get_rpc_client(topic, server, serializer=None):
"""Return a configured oslo_messaging RPCClient."""
target = messaging.Target(topic=topic, server=server,
version=consts.RPC_API_VERSION_BASE)
if serializer is None:
serializer = JsonPayloadSerializer()
serializer = RequestContextSerializer(serializer)
return messaging.RPCClient(TRANSPORT, target, serializer=serializer)
def get_notifier(publisher_id):
"""Return a configured oslo_messaging notifier."""
global NOTIFIER
return NOTIFIER.prepare(publisher_id=publisher_id)<|fim▁end|> | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
<|file_name|>session.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# papyon - a python client library for Msn<|fim▁hole|>#
# Copyright (C) 2007 Ali Sabil <[email protected]>
# Copyright (C) 2008 Richard Spiers <[email protected]>
#
# 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
from papyon.event import EventsDispatcher
from papyon.msnp2p.constants import *
from papyon.msnp2p.SLP import *
from papyon.msnp2p.transport import *
from papyon.util.parsing import build_account
from papyon.util.timer import Timer
import papyon.util.element_tree as ElementTree
import gobject
import base64
import logging
import random
import uuid
import os
__all__ = ['P2PSession']
logger = logging.getLogger('papyon.msnp2p.session')
MAX_INT32 = 0x7fffffff
MAX_INT16 = 0x7fff
class P2PSession(gobject.GObject, EventsDispatcher, Timer):
__gsignals__ = {
"accepted" : (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
()),
"rejected" : (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
()),
"completed" : (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
(object,)),
"progressed" : (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
(object,)),
"canceled" : (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
()),
"disposed" : (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
())
}
def __init__(self, session_manager, peer, peer_guid=None, euf_guid="",
application_id=0, message=None):
gobject.GObject.__init__(self)
EventsDispatcher.__init__(self)
Timer.__init__(self)
self._session_manager = session_manager
self._transport_manager = session_manager._transport_manager
self._client = session_manager._client
self._peer = peer
self._peer_guid = peer_guid
self._euf_guid = euf_guid
self._application_id = application_id
self._completed = False
self._version = 1
if self._client.profile.client_id.supports_p2pv2 and \
peer.client_capabilities.supports_p2pv2:
self._version = 2
if message is not None:
self._id = message.body.session_id
self._call_id = message.call_id
self._cseq = message.cseq
self._branch = message.branch
self._incoming = True
else:
self._id = self._generate_id()
self._call_id = "{%s}" % uuid.uuid4()
self._cseq = 0
self._branch = "{%s}" % uuid.uuid4()
self._incoming = False
self._session_manager._register_session(self)
def _generate_id(self, max=MAX_INT32):
"""
Returns a random ID.
@return: a random integer between 1000 and sys.maxint
@rtype: integer
"""
return random.randint(1000, max)
@property
def id(self):
return self._id
@property
def incoming(self):
return self._incoming
@property
def completed(self):
return self._completed
@property
def call_id(self):
return self._call_id
@property
def peer(self):
return self._peer
@property
def peer_guid(self):
return self._peer_guid
@property
def local_id(self):
if self._version >= 2:
return build_account(self._client.profile.account,
self._client.machine_guid)
return self._client.profile.account
@property
def remote_id(self):
if self._version >= 2:
return build_account(self._peer.account, self._peer_guid)
return self._peer.account
def set_receive_data_buffer(self, buffer, size):
self._transport_manager.register_data_buffer(self.peer,
self.peer_guid, self.id, buffer, size)
def _invite(self, context):
body = SLPSessionRequestBody(self._euf_guid, self._application_id,
context, self._id)
message = SLPRequestMessage(SLPRequestMethod.INVITE,
"MSNMSGR:" + self.remote_id,
to=self.remote_id,
frm=self.local_id,
branch=self._branch,
cseq=self._cseq,
call_id=self._call_id)
message.body = body
self._send_slp_message(message)
self.start_timeout("response", 60)
def _transreq(self):
self._cseq = 0
body = SLPTransportRequestBody(self._id, 0, 1)
message = SLPRequestMessage(SLPRequestMethod.INVITE,
"MSNMSGR:" + self.remote_id,
to=self.remote_id,
frm=self.local_id,
branch=self._branch,
cseq=self._cseq,
call_id=self._call_id)
message.body = body
self._send_slp_message(message)
def _respond(self, status_code):
body = SLPSessionRequestBody(session_id=self._id, capabilities_flags=None,
s_channel_state=None)
self._cseq += 1
response = SLPResponseMessage(status_code,
to=self.remote_id,
frm=self.local_id,
cseq=self._cseq,
branch=self._branch,
call_id=self._call_id)
response.body = body
self._send_slp_message(response)
# close other end points so we are the only one answering
self._close_end_points(status_code)
def _accept(self):
self._respond(200)
def _decline(self, status_code):
self._respond(status_code)
self._dispose()
def _respond_transreq(self, transreq, status, body):
self._cseq += 1
response = SLPResponseMessage(status,
to=self.remote_id,
frm=self.local_id,
cseq=self._cseq,
branch=transreq.branch,
call_id=self._call_id)
response.body = body
self._send_slp_message(response)
def _accept_transreq(self, transreq, bridge, listening, nonce, local_ip,
local_port, extern_ip, extern_port):
body = SLPTransportResponseBody(bridge, listening, nonce, [local_ip],
local_port, [extern_ip], extern_port, self._id, 0, 1)
self._respond_transreq(transreq, 200, body)
def _decline_transreq(self, transreq):
body = SLPTransportResponseBody(session_id=self._id)
self._respond_transreq(transreq, 603, body)
self._dispose()
def _close(self, context=None, reason=None):
body = SLPSessionCloseBody(context=context, session_id=self._id,
reason=reason, s_channel_state=0)
self._cseq = 0
self._branch = "{%s}" % uuid.uuid4()
message = SLPRequestMessage(SLPRequestMethod.BYE,
"MSNMSGR:" + self.remote_id,
to=self.remote_id,
frm=self.local_id,
branch=self._branch,
cseq=self._cseq,
call_id=self._call_id)
message.body = body
self._send_slp_message(message)
self._dispose()
def _close_end_points(self, status):
"""Send BYE to other end points; this client already answered.
@param status: response we sent to the peer"""
if len(self._peer.end_points) > 0:
return # if the peer supports MPOP, let him do the work
for end_point in self._client.profile.end_points.values():
if end_point.id == self._client.machine_guid:
continue
self._close_end_point(end_point, status)
def _close_end_point(self, end_point, status):
reason = (status, self._client.machine_guid)
body = SLPSessionCloseBody(session_id=self._id, reason=reason,
s_channel_state=0)
self._cseq = 0
self._branch = "{%s}" % uuid.uuid4()
message = SLPRequestMessage(SLPRequestMethod.BYE,
"MSNMSGR:" + self._client.profile.account,
to=self._client.profile.account,
frm=self._peer.account,
branch=self._branch,
cseq=self._cseq,
call_id=self._call_id,
on_behalf=self._peer.account)
message.body = body
self._transport_manager.send_slp_message(self._client.profile,
end_point.id, self._application_id, message)
def _dispose(self):
logger.info("Session %s disposed" % self._id)
self.stop_all_timeout()
self._session_manager._transport_manager.cleanup(self.peer,
self.peer_guid, self._id)
self._session_manager._unregister_session(self)
self._emit("disposed")
def _send_slp_message(self, message):
self._transport_manager.send_slp_message(self.peer, self.peer_guid,
self._application_id, message)
def _send_data(self, data):
self._transport_manager.send_data(self.peer, self.peer_guid,
self._application_id, self._id, data)
def _on_slp_message_received(self, message):
if isinstance(message, SLPRequestMessage):
if isinstance(message.body, SLPSessionRequestBody):
self._on_invite_received(message)
elif isinstance(message.body, SLPSessionCloseBody):
self._on_bye_received(message)
else:
print "Unhandled signaling blob :", message
elif isinstance(message, SLPResponseMessage):
if isinstance(message.body, SLPSessionRequestBody):
self.stop_timeout("response")
if message.status == 200:
self._emit("accepted")
self._on_session_accepted()
elif message.status == 603:
self._emit("rejected")
self._on_session_rejected(message)
else:
print "Unhandled response blob :", message
def _on_data_sent(self, data):
logger.info("Session data transfer completed")
data.seek(0, os.SEEK_SET)
self._completed = True
self._emit("completed", data)
self.start_timeout("bye", 5)
def _on_data_received(self, data):
logger.info("Session data transfer completed")
data.seek(0, os.SEEK_SET)
self._completed = True
self._emit("completed", data)
self._close()
def _on_data_transferred(self, size):
self._emit("progressed", size)
def on_response_timeout(self):
self._close()
def on_bye_timeout(self):
self._dispose()
# Methods to implement in different P2P applications
def _on_invite_received(self, message):
pass
def _on_bye_received(self, message):
self._dispose()
def _on_session_accepted(self):
pass
def _on_session_rejected(self, message):
self._dispose()
# Utilities methods
def _emit(self, signal, *args):
self._dispatch("on_session_%s" % signal, *args)
self.emit(signal, *args)
gobject.type_register(P2PSession)<|fim▁end|> | |
<|file_name|>FooController.java<|end_file_name|><|fim▁begin|>package org.jsondoc.core.issues.issue151;
import org.jsondoc.core.annotation.Api;
import org.jsondoc.core.annotation.ApiMethod;
import org.jsondoc.core.annotation.ApiResponseObject;
@Api(name = "Foo Services", description = "bla, bla, bla ...", group = "foogroup")
public class FooController {
@ApiMethod(path = { "/api/foo" }, description = "Main foo service")
@ApiResponseObject<|fim▁hole|> @ApiMethod(path = { "/api/foo-wildcard" }, description = "Main foo service with wildcard")
@ApiResponseObject
public FooWrapper<?> wildcard() {
return null;
}
}<|fim▁end|> | public FooWrapper<BarPojo> getBar() {
return null;
}
|
<|file_name|>ScrollerProxy.java<|end_file_name|><|fim▁begin|>/**
* Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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.easemob.chatuidemo.widget.photoview;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.widget.OverScroller;
import android.widget.Scroller;
public abstract class ScrollerProxy {
public static ScrollerProxy getScroller(Context context) {
if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) {
return new PreGingerScroller(context);
} else {
return new GingerScroller(context);
}
}
public abstract boolean computeScrollOffset();
public abstract void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY,
int maxY, int overX, int overY);
public abstract void forceFinished(boolean finished);
public abstract int getCurrX();
public abstract int getCurrY();
@TargetApi(9)
private static class GingerScroller extends ScrollerProxy {
private OverScroller mScroller;
public GingerScroller(Context context) {
mScroller = new OverScroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY,
int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY);
}
@Override
<|fim▁hole|> mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
private static class PreGingerScroller extends ScrollerProxy {
private Scroller mScroller;
public PreGingerScroller(Context context) {
mScroller = new Scroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY,
int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
}<|fim▁end|> | public void forceFinished(boolean finished) {
|
<|file_name|>where2.py<|end_file_name|><|fim▁begin|>"""
# A Better Where
WHERE2 is a near-linear time top-down clustering alogithm.
WHERE2 updated an older where with new Python tricks.
## Standard Header Stuff
"""
from __future__ import division,print_function
import sys
sys.dont_write_bytecode = True
from lib import *
from nasa93 import *
"""
## Dimensionality Reduction with Fastmp
Project data.dat in N dimensions down to a single dimension connecting
twp distant points. Divide that data.dat at the median of those projects.
"""
def fastmap(m,data):
"Divide data.dat into two using distance to two distant items."
import random
random.seed(1)
one = any(data) # 1) pick anything
west = furthest(m,one,data) # 2) west is as far as you can go from anything
east = furthest(m,west,data) # 3) east is as far as you can go from west
c = dist(m,west,east)
# now find everyone's distance
lst = []
for one in data:
a = dist(m,one,west)
b = dist(m,one,east)
x = (a*a + c*c - b*b)/(2*c) # cosine rule
y = max(0, a**2 - x**2)**0.5 # not used, here for a demo
lst += [(x,one)]
lst = sorted(lst)
mid = len(lst)//2
wests = map(second,lst[:mid])
easts = map(second,lst[mid:])
return wests,west, easts,east,c
def gt(x,y): return x > y
def lt(x,y): return x < y
"""
In the above:
+ _m_ is some model that generates candidate
solutions that we wish to niche.
+ _(west,east)_ are not _the_ most distant points
(that would require _N*N) distance
calculations). But they are at least very distant
to each other.
This code needs some helper functions. _Dist_ uses
the standard Euclidean measure. Note that you tune
what it uses to define the niches (decisions or
objectives) using the _what_ parameter:
"""
def dist(m,i,j,
what = lambda m: m.decisions):
"Euclidean distance 0 <= d <= 1 between decisions"
n = len(i.cells)
deltas = 0
for c in what(m):
n1 = norm(m, c, i.cells[c])
n2 = norm(m, c, j.cells[c])
inc = (n1-n2)**2
deltas += inc
n += abs(m.w[c])
return deltas**0.5 / n**0.5
"""
The _Dist_ function normalizes all the raw values zero to one.
"""
def norm(m,c,val) :
"Normalizes val in col c within model m 0..1"
return (val- m.lo[c]) / (m.hi[c]- m.lo[c]+ 0.0001)
"""
Now we can define _furthest_:
"""
def furthest(m,i,all,
init = 0,
better = gt):
"find which of all is furthest from 'i'"
out,d= i,init
for j in all:
if i == j: continue
tmp = dist(m,i,j)
if better(tmp,d):
out,d = j,tmp
return out
"""
And of course, _closest_:
"""
def closest(m,i,all):
return furthest(m,i,all,init=10**32,better=lt)
"""
## WHERE2 = Recursive Fastmap
WHERE2 finds everyone's else's distance from the poles
and divide the data.dat on the mean point of those
distances. This all stops if:
+ Any division has _tooFew_ solutions (say,
less than _sqrt_ of the total number of
solutions).
+ Something has gone horribly wrong and you are
recursing _tooDeep_
This code is controlled by the options in [_The_ settings](settingspy). For
example, if _The.pruning_ is true, we may ignore
some sub-tree (this process is discussed, later on).
Also, if _The.verbose_ is true, the _show_
function prints out a little tree showing the
progress (and to print indents in that tree, we use
the string _The.b4_). For example, here's WHERE2
dividing 93 examples from NASA93.
---| _where |-----------------
93
|.. 46
|.. |.. 23
|.. |.. |.. 11
|.. |.. |.. |.. 5.
|.. |.. |.. |.. 6.
|.. |.. |.. 12
|.. |.. |.. |.. 6.
|.. |.. |.. |.. 6.
|.. |.. 23
|.. |.. |.. 11
|.. |.. |.. |.. 5.
|.. |.. |.. |.. 6.
|.. |.. |.. 12
|.. |.. |.. |.. 6.
|.. |.. |.. |.. 6.
|.. 47
|.. |.. 23
|.. |.. |.. 11
|.. |.. |.. |.. 5.
|.. |.. |.. |.. 6.
|.. |.. |.. 12
|.. |.. |.. |.. 6.
|.. |.. |.. |.. 6.
|.. |.. 24
|.. |.. |.. 12
|.. |.. |.. |.. 6.
|.. |.. |.. |.. 6.
|.. |.. |.. 12
|.. |.. |.. |.. 6.
|.. |.. |.. |.. 6.
WHERE2 returns clusters, where each cluster contains
multiple solutions.
"""
def where2(m, data, lvl=0, up=None):
node = o(val=None,_up=up,_kids=[])
def tooDeep(): return lvl > The.what.depthMax
def tooFew() : return len(data) < The.what.minSize
def show(suffix):
if The.verbose:
print(The.what.b4*lvl,len(data),
suffix,' ; ',id(node) % 1000,sep='')
if tooDeep() or tooFew():
show(".")
node.val = data
else:
show("")
wests,west, easts,east,c = fastmap(m,data)
node.update(c=c,east=east,west=west)
goLeft, goRight = maybePrune(m,lvl,west,east)
if goLeft:
node._kids += [where2(m, wests, lvl+1, node)]
if goRight:
node._kids += [where2(m, easts, lvl+1, node)]
return node
"""
## An Experimental Extensions
Lately I've been experimenting with a system that<|fim▁hole|>halves with a dominated pole. This means that for
_N_ solutions we only ever have to evaluate
_2*log(N)_ of them- which is useful if each
evaluation takes a long time.
The niches found in this way
contain non-dominated poles; i.e. they are
approximations to the Pareto frontier.
Preliminary results show that this is a useful
approach but you should treat those results with a
grain of salt.
In any case, this code supports that pruning as an
optional extra (and is enabled using the
_slots.pruning_ flag). In summary, this code says if
the scores for the poles are more different that
_slots.wriggle_ and one pole has a better score than
the other, then ignore the other pole.
"""
def maybePrune(m,lvl,west,east):
"Usually, go left then right, unless dominated."
goLeft, goRight = True,True # default
if The.prune and lvl >= The.what.depthMin:
sw = scores(m, west)
se = scores(m, east)
if abs(sw - se) > The.wriggle: # big enough to consider
if se > sw: goLeft = False # no left
if sw > se: goRight = False # no right
return goLeft, goRight
"""
Note that I do not allow pruning until we have
descended at least _slots.depthMin_ into the tree.
### Model-specific Stuff
WHERE2 talks to models via the the following model-specific variables:
+ _m.cols_: list of indices in a list
+ _m.names_: a list of names for each column.
+ _m.decisions_: the subset of cols relating to decisions.
+ _m.obectives_: the subset of cols relating to objectives.
+ _m.eval(m,eg)_: function for computing variables from _eg_.
+ _m.lo[c]_ : the lowest value in column _c_.
+ _m.hi[c]_ : the highest value in column _c_.
+ _m.w[c]_: the weight for each column. Usually equal to one.
If an objective and if we are minimizing that objective, then the weight is negative.
### Model-general stuff
Using the model-specific stuff, WHERE2 defines some
useful general functions.
"""
def some(m,x) :
"with variable x of model m, pick one value at random"
return m.lo[x] + by(m.hi[x] - m.lo[x])
def scores(m,it):
"Score an individual."
if not it.scored:
m.eval(m,it)
new, w = 0, 0
for c in m.objectives:
val = it.cells[c]
w += abs(m.w[c])
tmp = norm(m,c,val)
if m.w[c] < 0:
tmp = 1 - tmp
new += (tmp**2)
it.score = (new**0.5) / (w**0.5)
it.scored = True
return it.score
"""
## Tree Code
Tools for manipulating the tree returned by _where2_.
### Primitive: Walk the nodes
"""
def nodes(tree,seen=None,steps=0):
if seen is None: seen=[]
if tree:
if not id(tree) in seen:
seen.append(id(tree))
yield tree,steps
for kid in tree._kids:
for sub,steps1 in nodes(kid,seen,steps+1):
yield sub,steps1
"""
### Return nodes that are leaves
"""
def leaves(tree,seen=None,steps=0):
for node,steps1 in nodes(tree,seen,steps):
if not node._kids:
yield node,steps1
"""
### Return nodes nearest to furthest
"""
def neighbors(leaf,seen=None,steps=-1):
"""Walk the tree from 'leaf' increasingly
distant leaves. """
if seen is None: seen=[]
for down,steps1 in leaves(leaf,seen,steps+1):
yield down,steps1
if leaf:
for up,steps1 in neighbors(leaf._up, seen,steps+1):
yield up,steps1
"""
### Return nodes in Groups, Closest to Furthest
"""
def around(leaf, f=lambda x: x):
tmp,last = [], None
for node,dist in neighbors(leaf):
if dist > 0:
if dist == last:
tmp += [f(node)]
else:
if tmp:
yield last,tmp
tmp = [f(node)]
last = dist
if tmp:
yield last,tmp
"""
## Demo Code
### Code Showing the scores
"""
#@go
def _scores():
m = nasa93()
out = []
for row in m._rows:
scores(m,row)
out += [(row.score, [row.cells[c] for c in m.objectives])]
for s,x in sorted(out):
print(s,x)
"""
### Code Showing the Distances
"""
#@go
def _distances(m=nasa93):
m=m()
seed(The.seed)
for i in m._rows:
j = closest(m,i, m._rows)
k = furthest(m,i, m._rows)
idec = [i.cells[c] for c in m.decisions]
jdec = [j.cells[c] for c in m.decisions]
kdec = [k.cells[c] for c in m.decisions]
print("\n",
gs(idec), g(scores(m,i)),"\n",
gs(jdec),"closest ", g(dist(m,i,j)),"\n",
gs(kdec),"furthest", g(dist(m,i,k)))
"""
### A Demo for Where2.
"""
"""
@go
def _where(m=nasa93):
m= m()
seed(1)
told=N()
for r in m._rows:
s = scores(m,r)
told += s
global The
The=defaults().update(verbose = True,
minSize = len(m._rows)**0.5,
prune = False,
wriggle = 0.3*told.sd())
tree = where2(m, m._rows)
n=0
for node,_ in leaves(tree):
m = len(node.val)
#print(m,' ',end="")
n += m
print(id(node) % 1000, ' ',end='')
for near,dist in neighbors(node):
print(dist,id(near) % 1000,' ',end='')
print("")
print(n)
filter = lambda z: id(z) % 1000
for node,_ in leaves(tree):
print(filter(node),
[x for x in around(node,filter)])
"""<|fim▁end|> | prunes as it divides the data.dat. GALE checks for
domination between the poles and ignores data.dat in |
<|file_name|>resource.rs<|end_file_name|><|fim▁begin|>//! `Resource` data description.
use std::fmt;
use serde::de::{
value::Error as ValueError, Deserialize, Deserializer, Error, IgnoredAny, IntoDeserializer,
MapAccess, Visitor,
};
use super::super::resources::ResourceType;
use crate::data::RoomName;
with_update_struct! {
/// A resource, a bit of some resource which has dropped on the ground, and is decaying each tick.
#[derive(Clone, Debug, PartialEq)]
pub struct Resource {
/// Unique 'id' identifier for all game objects on a server.
pub id: String,
/// Room object is in.
pub room: RoomName,
/// X position within the room (0-50).
pub x: u32,
/// Y position within the room (0-50).
pub y: u32,
/// Resource type that this resource is.
pub resource_type: ResourceType,
/// Resource amount that this resource is.
pub amount: i32,
}
/// Update structure for a `Resource`.
#[derive(Clone, Debug)]
(no_extra_meta)
pub struct ResourceUpdate {
- id: String,
- room: RoomName,
- x: u32,
- y: u32,
- resource_type: ResourceType,
- amount: i32,
}
}
/// deserialize helper, shared between `Resource` and `ResourceUpdate`.
enum FieldName {
Id,
Room,
X,
Y,
ResourceType,
Other(ResourceType),
Ignored,
}
impl<'de> Deserialize<'de> for FieldName {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = FieldName;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "field identifier")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
match value {
"_id" => Ok(FieldName::Id),
"room" => Ok(FieldName::Room),
"x" => Ok(FieldName::X),
"y" => Ok(FieldName::Y),
"resourceType" => Ok(FieldName::ResourceType),
other => {
match ResourceType::deserialize(
IntoDeserializer::<ValueError>::into_deserializer(other),
) {
Ok(resource_type) => Ok(FieldName::Other(resource_type)),
Err(_) => Ok(FieldName::Ignored),
}
}
}
}
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
match value {
b"_id" => Ok(FieldName::Id),
b"room" => Ok(FieldName::Room),
b"x" => Ok(FieldName::X),
b"y" => Ok(FieldName::Y),
b"resourceType" => Ok(FieldName::ResourceType),
other => match ::std::str::from_utf8(other) {
Ok(other_str) => {
match ResourceType::deserialize(
IntoDeserializer::<ValueError>::into_deserializer(other_str),
) {
Ok(resource_type) => Ok(FieldName::Other(resource_type)),
Err(_) => Ok(FieldName::Ignored),
}
}
Err(_) => Ok(FieldName::Ignored),
},
}<|fim▁hole|> }
}
impl<'de> Deserialize<'de> for Resource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ResourceVisitor;
impl<'de> Visitor<'de> for ResourceVisitor {
type Value = Resource;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Formatter::write_str(formatter, "struct Resource")
}
#[inline]
fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut id: Option<String> = None;
let mut room: Option<RoomName> = None;
let mut x: Option<u32> = None;
let mut y: Option<u32> = None;
let mut resource_type: Option<ResourceType> = None;
let mut resource_amount: Option<(ResourceType, i32)> = None;
while let Some(key) = access.next_key::<FieldName>()? {
match key {
FieldName::Id => {
if Option::is_some(&id) {
return Err(A::Error::duplicate_field("_id"));
}
id = Some(access.next_value::<String>()?);
}
FieldName::Room => {
if Option::is_some(&room) {
return Err(A::Error::duplicate_field("room"));
}
room = Some(access.next_value::<RoomName>()?);
}
FieldName::X => {
if Option::is_some(&x) {
return Err(A::Error::duplicate_field("x"));
}
x = Some(access.next_value::<u32>()?);
}
FieldName::Y => {
if Option::is_some(&y) {
return Err(A::Error::duplicate_field("y"));
}
y = Some(access.next_value::<u32>()?);
}
FieldName::ResourceType => {
if Option::is_some(&resource_type) {
return Err(A::Error::duplicate_field("resourceType"));
}
resource_type = Some(access.next_value::<ResourceType>()?);
}
FieldName::Other(resource) => {
if Option::is_some(&resource_amount) {
return Err(A::Error::duplicate_field(
"<dynamic ResourceType-named amount field>",
));
}
resource_amount = Some((resource, access.next_value::<i32>()?));
}
FieldName::Ignored => {
let _ = access.next_value::<IgnoredAny>()?;
}
}
}
let id = id.ok_or_else(|| A::Error::missing_field("_id"))?;
let room = room.ok_or_else(|| A::Error::missing_field("room"))?;
let x = x.ok_or_else(|| A::Error::missing_field("x"))?;
let y = y.ok_or_else(|| A::Error::missing_field("y"))?;
let resource_type =
resource_type.ok_or_else(|| A::Error::missing_field("resourceType"))?;
let (found_resource_type, amount) = resource_amount
.ok_or_else(|| A::Error::missing_field("<dynamic ResouceType-named field>"))?;
if resource_type != found_resource_type {
struct ResourceTypeMismatchError(ResourceType, ResourceType);
impl fmt::Display for ResourceTypeMismatchError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"this structure expects both a resourceType field declaring a name, and a field \
named by that name; found that resourceType field's value ({:?}) and name of \
amount field ({:?}) did not match.",
self.0, self.1
)
}
}
return Err(A::Error::custom(ResourceTypeMismatchError(
resource_type,
found_resource_type,
)));
}
Ok(Resource {
id: id,
room: room,
x: x,
y: y,
resource_type: resource_type,
amount: amount,
})
}
}
const FIELDS: &[&str] = &["id", "room", "x", "y", "resourceType"];
Deserializer::deserialize_struct(deserializer, "Resource", FIELDS, ResourceVisitor)
}
}
impl<'de> Deserialize<'de> for ResourceUpdate {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ResourceUpdateVisitor;
impl<'de> Visitor<'de> for ResourceUpdateVisitor {
type Value = ResourceUpdate;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Formatter::write_str(formatter, "struct ResourceUpdate")
}
#[inline]
fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut id: Option<String> = None;
let mut room: Option<RoomName> = None;
let mut x: Option<u32> = None;
let mut y: Option<u32> = None;
let mut resource_type: Option<ResourceType> = None;
let mut amount: Option<i32> = None;
while let Some(key) = access.next_key::<FieldName>()? {
match key {
FieldName::Id => {
if Option::is_some(&id) {
return Err(A::Error::duplicate_field("_id"));
}
id = Some(access.next_value::<String>()?);
}
FieldName::Room => {
if Option::is_some(&room) {
return Err(A::Error::duplicate_field("room"));
}
room = Some(access.next_value::<RoomName>()?);
}
FieldName::X => {
if Option::is_some(&x) {
return Err(A::Error::duplicate_field("x"));
}
x = Some(access.next_value::<u32>()?);
}
FieldName::Y => {
if Option::is_some(&y) {
return Err(A::Error::duplicate_field("y"));
}
y = Some(access.next_value::<u32>()?);
}
FieldName::ResourceType => {
if Option::is_some(&resource_type) {
return Err(A::Error::duplicate_field("resourceType"));
}
resource_type = Some(access.next_value::<ResourceType>()?);
}
FieldName::Other(_) => {
struct CanBeNullI32(Option<i32>);
impl<'de> Deserialize<'de> for CanBeNullI32 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(CanBeNullI32(Option::deserialize(deserializer)?))
}
}
if let CanBeNullI32(Some(value)) =
access.next_value::<CanBeNullI32>()?
{
if amount.is_some() {
return Err(A::Error::duplicate_field(
"<dynamic ResourceType-named amount field>",
));
}
amount = Some(value);
}
}
FieldName::Ignored => {
let _ = access.next_value::<IgnoredAny>()?;
}
}
}
Ok(ResourceUpdate {
id: id,
room: room,
x: x,
y: y,
resource_type: resource_type,
amount: amount,
})
}
}
const FIELDS: &'static [&'static str] = &["id", "room", "x", "y", "resourceType"];
Deserializer::deserialize_struct(
deserializer,
"ResourceUpdate",
FIELDS,
ResourceUpdateVisitor,
)
}
}
#[cfg(test)]
mod test {
use serde::Deserialize;
use crate::data::RoomName;
use super::{Resource, ResourceType};
#[test]
fn parse_resource() {
let json = json!({
"_id": "596990a3165c8c77de71ecf1",
"energy": 7,
"resourceType": "energy",
"room": "W65N19",
"type": "energy",
"x": 8,
"y": 34
});
let obj = Resource::deserialize(json).unwrap();
assert_eq!(
obj,
Resource {
id: "596990a3165c8c77de71ecf1".to_owned(),
room: RoomName::new("W65N19").unwrap(),
x: 8,
y: 34,
resource_type: ResourceType::Energy,
amount: 7,
}
);
}
}<|fim▁end|> | }
}
deserializer.deserialize_identifier(FieldVisitor) |
<|file_name|>RentalStatus.java<|end_file_name|><|fim▁begin|>package com.baldy.commons.models.ref;<|fim▁hole|>
/**
* @author mbmartinez
*/
public enum RentalStatus {
AVAILABLE,
LEASED
}<|fim▁end|> | |
<|file_name|>info.py<|end_file_name|><|fim▁begin|># DFF -- An Open Source Digital Forensics Framework
# Copyright (C) 2009-2011 ArxSys
# This program is free software, distributed under the terms of
# the GNU General Public License Version 2. See the LICENSE file
# at the top of the source tree.
#
# See http://www.digital-forensic.org for more information about this
# project. Please do not directly contact any of the maintainers of
# DFF for assistance; the project provides a web site, mailing lists
# and IRC channels for your use.
#
# Author(s):
# Solal Jacob <[email protected]>
#
__dff_module_info_version__ = "1.0.0"
from api.vfs import *
from api.module.script import *
from api.loader import *
from api.module.module import *
from api.taskmanager.taskmanager import *
from api.types.libtypes import Parameter, Variant, Argument, typeId, ConfigManager
from datetime import timedelta, datetime
from ui.console.utils import VariantTreePrinter<|fim▁hole|> VariantTreePrinter.__init__(self)
self.loader = loader.loader()
self.tm = TaskManager()
self.cm = ConfigManager.Get()
def show_config(self, modname):
conf = self.cm.configByName(modname)
res = "\n\tConfig:"
arguments = conf.arguments()
for argument in arguments:
res += "\n\t\tname: " + str(argument.name())
res += "\n\t\tdescription: " + str(argument.description())
if argument.inputType() == Argument.Empty:
res += "\n\t\tno input parameters"
else:
res += "\n\t\ttype: " + str(typeId.Get().typeToName(argument.type()))
res += "\n\t\trequirement: "
if argument.requirementType() == Argument.Optional:
res += "optional"
else:
res += "mandatory"
res += "\n\t\tinput parameters: "
if argument.parametersType() == Parameter.NotEditable:
res += "not editable "
else:
res += "editable "
if argument.inputType() == Argument.List:
res += "list"
else:
res += "single"
pcount = argument.parametersCount()
if pcount != 0:
parameters = argument.parameters()
res += "\n\t\tpredefined parameters: "
for parameter in parameters:
if argument.type() == typeId.Node:
res += str(parameter.value().absolute())
else:
res += parameter.toString()
pcount -= 1
if pcount != 0:
res += ", "
res += "\n"
constants = conf.constants()
if len(constants) > 0:
res += "\n\tConstant: \t"
for constant in constants:
res += "\n\t\tname: " + str(constant.name())
res += "\n\t\tdescription: " + str(constant.description())
res += "\n\t\ttype: " + str(typeId.Get().typeToName(constant.type()))
cvalues = constant.values()
cvallen = len(cvalues)
if cvallen > 0:
res += "\n\t\tvalues: "
for cvalue in cvalues:
if cvalue.type() == typeId.Node:
res += str(cvalue.value().absolute())
else:
res += cvalue.toString()
cvallen -= 1
if cvallen != 0:
res += ", "
res += "\n"
return res
def show_arg(self, args):
res = ""
if len(args):
res += "\n\n\t\tArguments: \t"
for argname in args.keys():
res += "\n\t\t\tname: " + argname
res += "\n\t\t\tparameters: "
val = args[argname]
if val.type() == typeId.List:
vlist = val.value()
vlen = len(vlist)
for item in vlist:
if item.type == typeId.Node:
res += str(val.value().absolute())
else:
res += item.toString()
vlen -= 1
if vlen != 0:
res += ", "
elif val.type() == typeId.Node:
res += str(val.value().absolute())
return res
def show_res(self, results):
res = self.fillMap(3, results, "\n\n\t\tResults:")
return res
def c_display(self):
print self.info
def getmodinfo(self, modname):
conf = self.cm.configByName(modname)
if conf == None:
return
self.lproc = self.tm.lprocessus
self.info += "\n" + modname + self.show_config(modname)
for proc in self.lproc:
if proc.mod.name == modname:
self.info += "\n\tProcessus " + str(proc.pid)
stime = datetime.fromtimestamp(proc.timestart)
self.info += "\n\t\texecution started at : " + str(stime)
if proc.timeend:
etime = datetime.fromtimestamp(proc.timeend)
self.info += "\n\t\texecution finished at : " + str(etime)
else:
etime = datetime.fromtimestamp(time.time())
delta = etime - stime
self.info += "\n\t\texecution time: " + str(delta)
self.info += self.show_arg(proc.args)
self.info += self.show_res(proc.res)
def start(self, args):
self.info = ""
if args.has_key("modules"):
modnames = args['modules'].value()
for modname in modnames:
self.getmodinfo(modname.value())
else:
self.modules = self.loader.modules
for modname in self.modules:
self.getmodinfo(modname)
class info(Module):
"""Show info on loaded drivers: configuration, arguments, results
"""
def __init__(self):
Module.__init__(self, "info", INFO)
self.tags = "builtins"
self.conf.addArgument({"name": "modules",
"description": "Display information concerning provided modules",
"input": Argument.Optional|Argument.List|typeId.String})<|fim▁end|> |
class INFO(Script, VariantTreePrinter):
def __init__(self):
Script.__init__(self, "info") |
<|file_name|>xattr.rs<|end_file_name|><|fim▁begin|>//! Extended attribute support for Darwin and Linux systems.
extern crate libc;
use std::io;
use std::path::Path;
pub const ENABLED: bool = cfg!(feature="git") && cfg!(any(target_os="macos", target_os="linux"));
pub trait FileAttributes {
fn attributes(&self) -> io::Result<Vec<Attribute>>;
fn symlink_attributes(&self) -> io::Result<Vec<Attribute>>;
}
impl FileAttributes for Path {
fn attributes(&self) -> io::Result<Vec<Attribute>> {
list_attrs(lister::Lister::new(FollowSymlinks::Yes), &self)
}
fn symlink_attributes(&self) -> io::Result<Vec<Attribute>> {
list_attrs(lister::Lister::new(FollowSymlinks::No), &self)
}
}
/// Attributes which can be passed to `Attribute::list_with_flags`
#[derive(Copy, Clone)]
pub enum FollowSymlinks {
Yes,
No
}
/// Extended attribute
#[derive(Debug, Clone)]
pub struct Attribute {
pub name: String,
pub size: usize,
}
pub fn list_attrs(lister: lister::Lister, path: &Path) -> io::Result<Vec<Attribute>> {
let c_path = match path.as_os_str().to_cstring() {
Some(cstring) => cstring,
None => return Err(io::Error::new(io::ErrorKind::Other, "Error: path somehow contained a NUL?")),
};
let mut names = Vec::new();
let bufsize = lister.listxattr_first(&c_path);
if bufsize < 0 {
return Err(io::Error::last_os_error());
}
else if bufsize > 0 {
let mut buf = vec![0u8; bufsize as usize];
let err = lister.listxattr_second(&c_path, &mut buf, bufsize);
if err < 0 {
return Err(io::Error::last_os_error());
}
if err > 0 {
// End indicies of the attribute names
// the buffer contains 0-terminates c-strings
let idx = buf.iter().enumerate().filter_map(|(i, v)|
if *v == 0 { Some(i) } else { None }
);
let mut start = 0;
for end in idx {
let c_end = end + 1; // end of the c-string (including 0)
let size = lister.getxattr(&c_path, &buf[start..c_end]);
if size > 0 {
names.push(Attribute {
name: lister.translate_attribute_name(&buf[start..end]),
size: size as usize
});
}
start = c_end;
}
}
}
Ok(names)
}
#[cfg(target_os = "macos")]
mod lister {
use std::ffi::CString;
use libc::{c_int, size_t, ssize_t, c_char, c_void, uint32_t};
use super::FollowSymlinks;
use std::ptr;
extern "C" {
fn listxattr(
path: *const c_char, namebuf: *mut c_char,
size: size_t, options: c_int
) -> ssize_t;
fn getxattr(
path: *const c_char, name: *const c_char,
value: *mut c_void, size: size_t, position: uint32_t,
options: c_int
) -> ssize_t;
}
pub struct Lister {
c_flags: c_int,
}
impl Lister {
pub fn new(do_follow: FollowSymlinks) -> Lister {
let c_flags: c_int = match do_follow {
FollowSymlinks::Yes => 0x0001,
FollowSymlinks::No => 0x0000,
};
Lister { c_flags: c_flags }
}
pub fn translate_attribute_name(&self, input: &[u8]) -> String {
use std::str::from_utf8_unchecked;
unsafe {
from_utf8_unchecked(input).into()
}
}
pub fn listxattr_first(&self, c_path: &CString) -> ssize_t {
unsafe {
listxattr(c_path.as_ptr(), ptr::null_mut(), 0, self.c_flags)
}
}
pub fn listxattr_second(&self, c_path: &CString, buf: &mut Vec<u8>, bufsize: ssize_t) -> ssize_t {
unsafe {
listxattr(
c_path.as_ptr(),
buf.as_mut_ptr() as *mut c_char,
bufsize as size_t, self.c_flags
)
}
}
pub fn getxattr(&self, c_path: &CString, buf: &[u8]) -> ssize_t {
unsafe {
getxattr(
c_path.as_ptr(),
buf.as_ptr() as *const c_char,
ptr::null_mut(), 0, 0, self.c_flags
)
}
}
}
}
#[cfg(target_os = "linux")]
mod lister {
use std::ffi::CString;
use libc::{size_t, ssize_t, c_char, c_void};
use super::FollowSymlinks;
use std::ptr;
extern "C" {
fn listxattr(
path: *const c_char, list: *mut c_char, size: size_t
) -> ssize_t;
fn llistxattr(
path: *const c_char, list: *mut c_char, size: size_t
) -> ssize_t;
fn getxattr(
path: *const c_char, name: *const c_char,
value: *mut c_void, size: size_t
) -> ssize_t;
fn lgetxattr(
path: *const c_char, name: *const c_char,
value: *mut c_void, size: size_t
) -> ssize_t;
}
pub struct Lister {
follow_symlinks: FollowSymlinks,
}
impl Lister {
pub fn new(follow_symlinks: FollowSymlinks) -> Lister {
Lister { follow_symlinks: follow_symlinks }
}
pub fn translate_attribute_name(&self, input: &[u8]) -> String {
String::from_utf8_lossy(input).into_owned()
}
pub fn listxattr_first(&self, c_path: &CString) -> ssize_t {
let listxattr = match self.follow_symlinks {
FollowSymlinks::Yes => listxattr,
FollowSymlinks::No => llistxattr,
};
<|fim▁hole|>
pub fn listxattr_second(&self, c_path: &CString, buf: &mut Vec<u8>, bufsize: ssize_t) -> ssize_t {
let listxattr = match self.follow_symlinks {
FollowSymlinks::Yes => listxattr,
FollowSymlinks::No => llistxattr,
};
unsafe {
listxattr(
c_path.as_ptr(),
buf.as_mut_ptr() as *mut c_char,
bufsize as size_t
)
}
}
pub fn getxattr(&self, c_path: &CString, buf: &[u8]) -> ssize_t {
let getxattr = match self.follow_symlinks {
FollowSymlinks::Yes => getxattr,
FollowSymlinks::No => lgetxattr,
};
unsafe {
getxattr(
c_path.as_ptr(),
buf.as_ptr() as *const c_char,
ptr::null_mut(), 0
)
}
}
}
}<|fim▁end|> | unsafe {
listxattr(c_path.as_ptr(), ptr::null_mut(), 0)
}
} |
<|file_name|>createController.js<|end_file_name|><|fim▁begin|>var app = angular.module("ethics-app");
// User create controller
app.controller("userCreateController", function($scope, $rootScope, $routeParams, $filter, $translate, $location, config, $window, $authenticationService, $userService, $universityService, $instituteService) {
/*************************************************
FUNCTIONS
*************************************************/
/**
* [redirect description]
* @param {[type]} path [description]
* @return {[type]} [description]
*/
$scope.redirect = function(path){
$location.url(path);
};
/**
* [description]
* @param {[type]} former_status [description]
* @return {[type]} [description]
*/
$scope.getGroupName = function(former_status){
if(former_status){
return $filter('translate')('FORMER_INSTITUTES');
} else {
return $filter('translate')('INSTITUTES');
}
};
/**
* [send description]
* @return {[type]} [description]
*/
$scope.send = function(){
// Validate input
if($scope.createUserForm.$invalid) {
// Update UI
$scope.createUserForm.email_address.$pristine = false;
$scope.createUserForm.title.$pristine = false;
$scope.createUserForm.first_name.$pristine = false;
$scope.createUserForm.last_name.$pristine = false;
$scope.createUserForm.institute_id.$pristine = false;
$scope.createUserForm.blocked.$pristine = false;
} else {
$scope.$parent.loading = { status: true, message: $filter('translate')('CREATING_NEW_USER') };
// Create new user
$userService.create($scope.new_user)
.then(function onSuccess(response) {
var user = response.data;
// Redirect
$scope.redirect("/users/" + user.user_id);<|fim▁hole|> .catch(function onError(response) {
$window.alert(response.data);
});
}
};
/**
* [description]
* @param {[type]} related_data [description]
* @return {[type]} [description]
*/
$scope.load = function(related_data){
// Check which kind of related data needs to be requested
switch (related_data) {
case 'universities': {
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_UNIVERSITIES') };
// Load universities
$universityService.list({
orderby: 'name.asc',
limit: null,
offset: null
})
.then(function onSuccess(response) {
$scope.universities = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
break;
}
case 'institutes': {
if($scope.university_id){
if($scope.university_id !== null){
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_INSTITUTES') };
// Load related institutes
$instituteService.listByUniversity($scope.university_id, {
orderby: 'name.asc',
limit: null,
offset: null,
former: false
})
.then(function onSuccess(response) {
$scope.institutes = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
break;
}
}
};
/*************************************************
INIT
*************************************************/
$scope.new_user = $userService.init();
$scope.authenticated_member = $authenticationService.get();
// Load universities
$scope.load('universities');
// Set default value by member
$scope.university_id = $scope.authenticated_member.university_id;
// Load related institutes
$scope.load('institutes');
// Set default value by member
$scope.new_user.institute_id = $scope.authenticated_member.institute_id;
});<|fim▁end|> | }) |
<|file_name|>resources.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-<|fim▁hole|>#
# Resources to make it easier and faster to implement and test game of life
#
# @author Mikael Wikström
# https://github.com/leakim/GameOfLifeKata
#
import pygame
class GameOfLife:
# still
BLOCK_0 = set([(0, 0), (0, 1), (1, 0), (1, 1)])
BLOCK_1 = BLOCK_0
# oscillators
THREE_0 = set([(0, 1), (0, 0), (0, 2)])
THREE_1 = set([(0, 1), (-1, 1), (1, 1)])
# spaceships (moves)
GLIDER_0 = set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 1)])
GLIDER_1 = set([(0, 1), (1, 2), (-1, 1), (1, 0), (0, 2)])
def move(state, (x, y)):
newstate = set()
for (u, v) in state:
newstate.add((x + u, y + v))
return newstate
#WINDOW_SIZE = [2*255, 2*255]
#screen = pygame.display.set_mode(WINDOW_SIZE)
def draw(screen, state, rows=25, cols=25, MARGIN=1):
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
(w, h) = screen.get_size()
width, height = w/cols, h/rows
screen.fill(BLACK)
for (x, y) in state:
pygame.draw.rect(screen, WHITE, [
(MARGIN + width) * x + MARGIN,
(MARGIN + height) * y + MARGIN,
width, height])
pygame.display.flip()<|fim▁end|> | |
<|file_name|>run_rec_mrbpr.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# =======================================================================
# This file is part of MCLRE.
#
# MCLRE 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.
#
# MCLRE 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 MCLRE. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2015 Augusto Queiroz de Macedo <[email protected]>
# =======================================================================
"""
MRBPR Runner
"""
from os import path
from argparse import ArgumentParser
import shlex
import subprocess
import multiprocessing
import logging
from run_rec_functions import read_experiment_atts
from mrbpr.mrbpr_runner import create_meta_file, run
##############################################################################
# GLOBAL VARIABLES
##############################################################################
# Define the Logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(name)s : %(message)s',
level=logging.INFO)
LOGGER = logging.getLogger('mrbpr.run_rec_mrbpr')
LOGGER.setLevel(logging.INFO)
##############################################################################
# AUXILIAR FUNCTIONS
##############################################################################
def get_mrbpr_confs():
""" Yield the MRBPR Models Configurations """
pass
##############################################################################
# MAIN
##############################################################################
if __name__ == '__main__':
# ------------------------------------------------------------------------
# Define the argument parser
PARSER = ArgumentParser(description="Script that runs the mrbpr event recommender algorithms for" \
" a given 'experiment_name' with data from a given 'region'")
PARSER.add_argument("-e", "--experiment_name", type=str, required=True,
help="The Experiment Name (e.g. recsys-15)")
PARSER.add_argument("-r", "--region", type=str, required=True,
help="The data Region (e.g. san_jose)")
PARSER.add_argument("-a", "--algorithm", type=str, required=True,
help="The algorithm name (used only to differenciate our proposed MRBPR to the others")
ARGS = PARSER.parse_args()
<|fim▁hole|>
LOGGER.info(ALGORITHM_NAME)
DATA_DIR = "data"
PARTITIONED_DATA_DIR = path.join(DATA_DIR, "partitioned_data")
PARTITIONED_REGION_DATA_DIR = path.join(PARTITIONED_DATA_DIR, REGION)
EXPERIMENT_DIR = path.join(DATA_DIR, "experiments", EXPERIMENT_NAME)
EXPERIMENT_REGION_DATA_DIR = path.join(EXPERIMENT_DIR, REGION)
# LOGGER.info('Defining the MRBPR relation weights file...')
subprocess.call(shlex.split("Rscript %s %s %s" %
(path.join("src", "recommender_execution", "mrbpr", "mrbpr_relation_weights.R"),
EXPERIMENT_NAME, ALGORITHM_NAME)))
# ------------------------------------------------------------------------
# Reading and Defining the Experiment Attributes
EXPERIMENT_ATTS = read_experiment_atts(EXPERIMENT_DIR)
PARALLEL_RUNS = multiprocessing.cpu_count() - 1
TRAIN_RELATION_NAMES = EXPERIMENT_ATTS['%s_relation_names' % ALGORITHM_NAME.lower()]
TRAIN_RELATION_FILES = ["%s_train.tsv" % name for name in TRAIN_RELATION_NAMES]
PARTITIONS = reversed(EXPERIMENT_ATTS['partitions'])
# ------------------------------------------------------------------------
# Reading and Defining the Experiment Attributes
META_FILE = path.join(EXPERIMENT_DIR, "%s_meetup.meta" % ALGORITHM_NAME.lower())
LOGGER.info('Creating the META relations file...')
create_meta_file(TRAIN_RELATION_NAMES, META_FILE, PARTITIONED_DATA_DIR)
# ------------------------------------------------------------------------
# Fixed parameters
# ------------------------------------------------------------------------
# Algorithm (0 - MRBPR)
ALGORITHM = 0
# Size of the Ranked list of events per User
RANK_SIZE = 100
# Save Parameters
SAVE_MODEL = 0
# Hyper Parameters
REGULARIZATION_PER_ENTITY = ""
REGULARIZATION_PER_RELATION = ""
RELATION_WEIGHTS_FILE = path.join(EXPERIMENT_DIR, "%s_relation_weights.txt" % ALGORITHM_NAME.lower())
# ------------------------------------------------------------------------
if ALGORITHM_NAME == "MRBPR":
LEARN_RATES = [0.1]
NUM_FACTORS = [300]
NUM_ITERATIONS = [1500]
elif ALGORITHM_NAME == "BPR-NET":
LEARN_RATES = [0.1]
NUM_FACTORS = [200]
NUM_ITERATIONS = [600]
else:
LEARN_RATES = [0.1]
NUM_FACTORS = [10]
NUM_ITERATIONS = [10]
MRBPR_BIN_PATH = path.join("src", "recommender_execution", "mrbpr", "mrbpr.bin")
LOGGER.info("Start running MRBPR Process Scheduler!")
run(PARTITIONED_REGION_DATA_DIR, EXPERIMENT_REGION_DATA_DIR,
REGION, ALGORITHM, RANK_SIZE, SAVE_MODEL, META_FILE,
REGULARIZATION_PER_ENTITY, REGULARIZATION_PER_RELATION,
RELATION_WEIGHTS_FILE, TRAIN_RELATION_FILES,
PARTITIONS, NUM_ITERATIONS, NUM_FACTORS, LEARN_RATES,
MRBPR_BIN_PATH, PARALLEL_RUNS, ALGORITHM_NAME)
LOGGER.info("DONE!")<|fim▁end|> | EXPERIMENT_NAME = ARGS.experiment_name
REGION = ARGS.region
ALGORITHM_NAME = ARGS.algorithm |
<|file_name|>SwitchPhase.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM15.IEC61970.Core.PowerSystemResource import PowerSystemResource
class SwitchPhase(PowerSystemResource):
"""Single phase of a multi-phase switch when its attributes might be different per phase.Single phase of a multi-phase switch when its attributes might be different per phase.
"""
def __init__(self, phaseSide1="C", phaseSide2="C", normalOpen=False, Switch=None, *args, **kw_args):
"""Initialises a new 'SwitchPhase' instance.
@param phaseSide1: Phase of this SwitchPhase on the “from” (Switch.Terminal.sequenceNumber=1) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
@param phaseSide2: Phase of this SwitchPhase on the “to” (Switch.Terminal.sequenceNumber=2) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
@param normalOpen: Used in cases when no Measurement for the status value is present. If the SwitchPhase has a status measurement the Discrete.normalValue is expected to match with this value.
@param Switch:
"""
#: Phase of this SwitchPhase on the “from” (Switch.Terminal.sequenceNumber=1) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
self.phaseSide1 = phaseSide1
#: Phase of this SwitchPhase on the “to” (Switch.Terminal.sequenceNumber=2) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
self.phaseSide2 = phaseSide2
#: Used in cases when no Measurement for the status value is present. If the SwitchPhase has a status measurement the Discrete.normalValue is expected to match with this value.
self.normalOpen = normalOpen
self._Switch = None
self.Switch = Switch
super(SwitchPhase, self).__init__(*args, **kw_args)
_attrs = ["phaseSide1", "phaseSide2", "normalOpen"]
_attr_types = {"phaseSide1": str, "phaseSide2": str, "normalOpen": bool}
_defaults = {"phaseSide1": "C", "phaseSide2": "C", "normalOpen": False}
_enums = {"phaseSide1": "SinglePhaseKind", "phaseSide2": "SinglePhaseKind"}
_refs = ["Switch"]
_many_refs = []
<|fim▁hole|>
return self._Switch
def setSwitch(self, value):
if self._Switch is not None:
filtered = [x for x in self.Switch.SwitchPhases if x != self]
self._Switch._SwitchPhases = filtered
self._Switch = value
if self._Switch is not None:
if self not in self._Switch._SwitchPhases:
self._Switch._SwitchPhases.append(self)
Switch = property(getSwitch, setSwitch)<|fim▁end|> | def getSwitch(self): |
<|file_name|>VisualBlock.py<|end_file_name|><|fim▁begin|>from __future__ import print_function, absolute_import
from PySide2 import QtGui,QtCore,QtWidgets
from math import *
import pickle, os, json
import learnbot_dsl.guis.EditVar as EditVar
from learnbot_dsl.learnbotCode.Block import *
from learnbot_dsl.learnbotCode.Language import getLanguage
from learnbot_dsl.learnbotCode.toQImage import *
from learnbot_dsl.learnbotCode.Parser import parserLearntBotCodeOnlyUserFuntion
from learnbot_dsl.blocksConfig import pathImgBlocks
from learnbot_dsl.learnbotCode import getAprilTextDict
class KeyPressEater(QtCore.QObject):
def eventFilter(self, obj, event):
if isinstance(event, QtGui.QMouseEvent) and event.buttons() & QtCore.Qt.RightButton:
return True
return False
def toLBotPy(inst, ntab=1, offset=0):
text = inst[0]
if inst[1]["TYPE"] in [USERFUNCTION, LIBRARY]:
text = inst[0] + "()"
else:
inst[1]["VISUALBLOCK"].startOffset = offset
if inst[1]["TYPE"] is CONTROL:
if inst[1]["VARIABLES"] is not None:
text = inst[0] + "("
for var in inst[1]["VARIABLES"]:
text += var + ", "
text = text[0:-2] + ""
text += ")"
if inst[1]["TYPE"] is FUNTION:
text = "function." + inst[0] + "("
if inst[1]["VARIABLES"] is not None:
for var in inst[1]["VARIABLES"]:
text += var + ", "
text = text[0:-2] + ""
text += ")"
elif inst[1]["TYPE"] is VARIABLE:
text = inst[0]
if inst[1]["VARIABLES"] is not None:
text += " = "
for var in inst[1]["VARIABLES"]:
text += var
if inst[1]["RIGHT"] is not None:
text += " "
text += toLBotPy(inst[1]["RIGHT"], ntab, len(text) + offset)
if inst[1]["BOTTOMIN"] is not None:
text += ":\n" + "\t" * ntab
text += toLBotPy(inst[1]["BOTTOMIN"], ntab + 1, len(text) + offset)
if inst[0] in ["while", "while True"]:
text += "\n" + "\t" * (ntab - 1) + "end"
if inst[0] == "else" or (inst[0] in ["if", "elif"] and (inst[1]["BOTTOM"] is None or (
inst[1]["BOTTOM"] is not None and inst[1]["BOTTOM"][0] not in ["elif", "else"]))):
text += "\n" + "\t" * (ntab - 1) + "end"
inst[1]["VISUALBLOCK"].endOffset = len(text)-1 + offset
if inst[1]["BOTTOM"] is not None:
text += "\n" + "\t" * (ntab - 1)
text += toLBotPy(inst[1]["BOTTOM"], ntab, len(text) + offset)
return text
def EuclideanDist(p1, p2):
p = p1 - p2
return sqrt(pow(p.x(), 2) + pow(p.y(), 2))
class VarGui(QtWidgets.QDialog, EditVar.Ui_Dialog):
def init(self):
self.setupUi(self)
def getTable(self):
return self.table
def setSlotToDeleteButton(self, fun):
self.deleteButton.clicked.connect(fun)
self.okButton.clicked.connect(self.close)
class VisualBlock(QtWidgets.QGraphicsPixmapItem, QtWidgets.QWidget):
def __init__(self, parentBlock, parent=None, scene=None):
self.startOffset = None
self.endOffset = None
self._notifications = []
self.parentBlock = parentBlock
self.__typeBlock = self.parentBlock.typeBlock
self.__type = self.parentBlock.type
self.id = self.parentBlock.id
self.connections = self.parentBlock.connections
self.highlighted = False
for c in self.connections:
c.setParent(self.parentBlock)
self.dicTrans = parentBlock.dicTrans
self.shouldUpdate = True
if len(self.dicTrans) is 0:
self.showtext = self.parentBlock.name
else:
self.showtext = self.dicTrans[getLanguage()]
QtWidgets.QGraphicsPixmapItem.__init__(self)
QtWidgets.QWidget.__init__(self)
def foo(x):
return 32
# Load Image of block
im = cv2.imread(self.parentBlock.file, cv2.IMREAD_UNCHANGED)
r, g, b, a = cv2.split(im)
rgb = cv2.merge((r, g, b))
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
h, s, v = cv2.split(hsv)
h = h + self.parentBlock.hue
s = s + 160
hsv = cv2.merge((h, s, v))
im = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
r, g, b = cv2.split(im)
self.cvImg = cv2.merge((r, g, b, a))
self.cvImg = np.require(self.cvImg, np.uint8, 'C')
# if self.parentBlock.type is VARIABLE:
# self.showtext = self.parentBlock.name + " "+ self.showtext
img = generateBlock(self.cvImg, 34, self.showtext, self.parentBlock.typeBlock, None, self.parentBlock.type,
self.parentBlock.nameControl)
qImage = toQImage(img)
# Al multiplicar por 0 obtenemos facilmente un ndarray inicializado a 0
# similar al original
try:
self.header = copy.copy(self.cvImg[0:39, 0:149])
self.foot = copy.copy(self.cvImg[69:104, 0:149])
except:
pass
self.img = QtGui.QPixmap(qImage)
self.scene = scene
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable)
self.setZValue(1)
self.setPos(self.parentBlock.pos)
self.scene.activeShouldSave()
self.updatePixmap()
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.update)
self.posmouseinItem = None
self.DialogVar = None
self.popMenu = None
self.create_dialogs()
self.sizeIn = 0
self.shouldUpdateConnections = False
def addNotification(self, notification):
tooltip = self.toolTip()
if tooltip:
tooltip += '<hr />'
tooltip += notification.simpleHtml()
self.setToolTip(tooltip)
self._notifications.append(notification)
def clearNotifications(self):
self._notifications = []
self.setToolTip('')
def notifications(self):
return self._notifications
def highlight(self):
self.highlighted = True
self.updateImg(force=True)
self.updatePixmap()
def unhighlight(self):
self.highlighted = False
self.updateImg(force=True)
self.updatePixmap()
def updatePixmap(self):
self.setPixmap(self.img)
def create_dialogs(self):
if self.DialogVar is not None:
del self.DialogVar
vars = self.parentBlock.vars
self.DialogVar = VarGui()
self.DialogVar.init()
self.DialogVar.setSlotToDeleteButton(self.delete)
self.tabVar = self.DialogVar.getTable()
self.tabVar.verticalHeader().setVisible(False)
self.tabVar.horizontalHeader().setVisible(True)
self.tabVar.setColumnCount(4)
self.tabVar.setRowCount(len(vars))
self.tableHeader = [] #QtCore.QStringList()
self.tableHeader.append(self.tr('Name'))
self.tableHeader.append(self.tr('Constant'))
self.tableHeader.append(self.tr('Set to'))
self.tableHeader.append(self.tr('Type'))
self.tabVar.setHorizontalHeaderLabels(self.tableHeader)
self.tabVar.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
# i = 0
for i, var in zip(range(len(vars)),vars):
try:
if getLanguage() in var.translate:
self.tabVar.setCellWidget(i, 0, QtWidgets.QLabel(var.translate[getLanguage()]))
else:
self.tabVar.setCellWidget(i, 0, QtWidgets.QLabel(var.name))
except:
self.tabVar.setCellWidget(i, 0, QtWidgets.QLabel(var.name))
if var.type in ["float","int", "string"]:
edit = QtWidgets.QLineEdit()
if var.type == "float":
edit.setValidator(QtGui.QDoubleValidator())
self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(self.tr('number')))
elif var.type == "int":
edit.setValidator(QtGui.QIntValidator())
self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(self.tr('number')))
else:
self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(self.tr('string')))
if var.type == "string":
edit.setText(var.defaul.replace('\"', ''))
else:
edit.setText(var.defaul)
self.tabVar.setCellWidget(i, 1, edit)
elif var.type == "boolean":
combobox = QtWidgets.QComboBox()
combobox.addItem("True")
combobox.addItem("False")
if var.defaul in ("0", "False"):
combobox.setCurrentIndex(1)
else:
combobox.setCurrentIndex(0)
self.tabVar.setCellWidget(i, 1, combobox)
self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(self.tr('boolean')))
elif var.type == "list":
values = var.translateValues[getLanguage()]
combobox = QtWidgets.QComboBox()
combobox.addItems(values)
self.tabVar.setCellWidget(i, 1, combobox)
self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(self.tr('list')))
elif var.type == "apriltext":
dictApriText = getAprilTextDict()
combobox = QtWidgets.QComboBox()
combobox.addItems([x for x in dictApriText])
self.tabVar.setCellWidget(i, 1, combobox)
self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(self.tr('apriltext')))
combobox = QtWidgets.QComboBox()
combobox.addItem(self.tr('Constant'))
self.tabVar.setCellWidget(i, 2, combobox)
# self.tabVar.setCellWidget(i,3,QtWidgets.QLabel(var.type))
# i += 1
if self.popMenu is not None:
del self.popMenu
del self.keyPressEater
self.popMenu = QtWidgets.QMenu(self)
self.keyPressEater = KeyPressEater(self.popMenu)
self.popMenu.installEventFilter(self.keyPressEater)
action1 = QtWidgets.QAction(self.tr('Edit'), self)
action1.triggered.connect(self.on_clicked_menu_edit)
self.popMenu.addAction(action1)
if self.parentBlock.name not in ["main", "when"]:
if self.parentBlock.type is USERFUNCTION and self.parentBlock.typeBlock is COMPLEXBLOCK:
action3 = QtWidgets.QAction(self.tr('Export Block'), self)
action3.triggered.connect(self.on_clicked_menu_export_block)
self.popMenu.addAction(action3)
else:
action0 = QtWidgets.QAction(self.tr('Duplicate'), self)
action0.triggered.connect(self.on_clicked_menu_duplicate)
self.popMenu.addAction(action0)
self.popMenu.addSeparator()
action2 = QtWidgets.QAction(self.tr('Delete'), self)
action2.triggered.connect(self.on_clicked_menu_delete)
# action2.installEventFilter(self.keyPressEater)
self.popMenu.addAction(action2)
def on_clicked_menu_export_block(self):
if self.parentBlock.name not in ["main", "when"] and self.parentBlock.type is USERFUNCTION and self.parentBlock.typeBlock is COMPLEXBLOCK:
self.scene.stopAllblocks()
path = QtWidgets.QFileDialog.getExistingDirectory(self, self.tr('Select Library'), self.scene.parent.libraryPath, QtWidgets.QFileDialog.ShowDirsOnly)
self.scene.startAllblocks()
ret = None
try:
os.mkdir(os.path.join(path, self.parentBlock.name))
except:
msgBox = QtWidgets.QMessageBox()
msgBox.setWindowTitle(self.tr("Warning"))
msgBox.setIcon(QtWidgets.QMessageBox.Warning)
msgBox.setText(self.tr("This module already exists"))
msgBox.setInformativeText(self.tr("Do you want to overwrite the changes?"))
msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok| QtWidgets.QMessageBox.Cancel)
msgBox.setDefaultButton(QtWidgets.QMessageBox.Ok)
ret = msgBox.exec_()
if ret is None or ret == QtWidgets.QMessageBox.Ok:
path = os.path.join(path, self.parentBlock.name)
# Save blockProject
lBInstance = self.scene.parent
with open(os.path.join(path, self.parentBlock.name + ".blockProject"), 'wb') as fichero:
dic = copy.deepcopy(lBInstance.scene.dicBlockItem)
for id in dic:
block = dic[id]
block.file = os.path.basename(block.file)
pickle.dump(
(dic, lBInstance.listNameWhens, lBInstance.listUserFunctions, lBInstance.listNameVars, lBInstance.listNameUserFunctions),
fichero, 0)
# Save config block
dictBlock = {}
dictBlock["name"] = self.parentBlock.name
dictBlock["type"] = "library"
dictBlock["shape"] = ["blockVertical"]
with open(os.path.join(path, self.parentBlock.name + ".conf"),'w') as f:
json.dump([dictBlock], f)
# Save script learnCode
inst = self.getInstructions()
code = "def " + toLBotPy(inst) + "\nend\n\n"
with open(os.path.join(path, self.parentBlock.name + ".lb"), 'w') as f:
f.write(code)
# Save script python
codePython = parserLearntBotCodeOnlyUserFuntion(code)
with open(os.path.join(path, self.parentBlock.name + ".py"), 'w') as f:
f.write(codePython)
pass
def on_clicked_menu_duplicate(self):
if self.parentBlock.name not in ["main", "when"] and not (self.parentBlock.type is USERFUNCTION and self.parentBlock.typeBlock is COMPLEXBLOCK):
self.duplicate()
self.scene.startAllblocks()
self.scene.parent.savetmpProject()
def duplicate(self, old_id=None, id=None, connection=None):
blockDuplicate = self.parentBlock.copy()
blockDuplicate.setPos(self.parentBlock.pos + QtCore.QPointF(50, 50))
self.scene.addItem(blockDuplicate, False, False, False)
id_new = blockDuplicate.id
new_connection = None
for c in blockDuplicate.connections:
if id is None and c.getType() in [TOP, LEFT]:
c.setItem(None)
c.setConnect(None)
elif old_id is not None and c.getIdItem() == old_id:
new_connection = c
c.setItem(id)
c.setConnect(connection)
elif c.getIdItem() is not None and c.getType() not in [TOP, LEFT]:
c_new, id_new2 = self.scene.getVisualItem(c.getIdItem()).duplicate(self.id, id_new, c)
c.setConnect(c_new)
c.setItem(id_new2)
return new_connection, id_new
def on_clicked_menu_edit(self):
self.scene.setIdItemSelected(None)
if self.DialogVar is not None and len(self.parentBlock.getVars())>0:
self.setCurrentParamInDialog()
self.DialogVar.open()
self.scene.setTable(self.DialogVar)
def setCurrentParamInDialog(self):
varS = self.parentBlock.getVars()
if len(varS)>0:
combo = self.tabVar.cellWidget(0, 2)
assignList = [combo.itemText(i) for i in range(combo.count())]
for cell, var in zip(range(len(varS)), varS):
if varS[cell].defaul in assignList:
index = assignList.index(varS[cell].defaul)
self.tabVar.cellWidget(cell, 2).setCurrentIndex(index)
if var.type in ["float","int", "string"]:
self.tabVar.cellWidget(cell, 1).setText("")
else:
self.tabVar.cellWidget(cell, 1).setCurrentIndex(0)
def on_clicked_menu_delete(self):
self.delete()
def start(self):
self.timer.start(5)
def stop(self):
self.timer.stop()
def activeUpdateConections(self):
self.shouldUpdateConnections = True
def getNameFuntion(self):
return self.parentBlock.name
def getIdItemBottomConnect(self):
for c in [conn for conn in self.connections if conn.getType() is BOTTOM]:
return self.scene.getVisualItem(c.getIdItem())
def getIdItemTopConnect(self):
for c in [conn for conn in self.connections if conn.getType() is TOP]:
return self.scene.getVisualItem(c.getIdItem())
def getNumSubBottom(self, n=0, size=0):
size += self.img.height() - 5
for c in [conn for conn in self.connections if conn.getType() is BOTTOM]:
if c.getConnect() is None:
return n + 1, size + 1
else:
return self.scene.getVisualItem(c.getIdItem()).getNumSubBottom(n + 1, size)
return n + 1, size + 1
def getNumSub(self, n=0):
for c in [conn for conn in self.connections if conn.getType() is BOTTOMIN and conn.getConnect() is not None]:<|fim▁hole|> return self.scene.getVisualItem(c.getIdItem()).getNumSubBottom()
return 0, 0
def getInstructionsRIGHT(self, inst=[]):
for c in [conn for conn in self.connections if conn.getType() is RIGHT and conn.getIdItem() is not None]:
inst = self.scene.getVisualItem(c.getIdItem()).getInstructions()
if len(inst) is 0:
return None
return inst
def getInstructionsBOTTOM(self, inst=[]):
for c in [conn for conn in self.connections if conn.getType() is BOTTOM and conn.getIdItem() is not None]:
inst = self.scene.getVisualItem(c.getIdItem()).getInstructions()
if len(inst) is 0:
return None
return inst
def getInstructionsBOTTOMIN(self, inst=[]):
for c in [conn for conn in self.connections if conn.getType() is BOTTOMIN and conn.getIdItem() is not None]:
inst = self.scene.getVisualItem(c.getIdItem()).getInstructions()
if len(inst) is 0:
return None
return inst
def getVars(self):
vars = []
varS = self.parentBlock.getVars()
# for cell in range(0, self.tabVar.rowCount()):
for cell, var in zip(range(len(varS)), varS):
if self.tabVar.cellWidget(cell, 2).currentText() == self.tr('Constant'):
if self.tabVar.cellWidget(cell, 3).text() == "boolean":
vars.append(self.tabVar.cellWidget(cell, 1).currentText())
elif self.tabVar.cellWidget(cell, 3).text() == "list":
vars.append('"' + var.values[self.tabVar.cellWidget(cell, 1).currentIndex()] + '"')
elif self.tabVar.cellWidget(cell, 3).text() == "apriltext":
vars.append('"' +self.tabVar.cellWidget(cell, 1).currentText() + '"')
elif self.tabVar.cellWidget(cell, 3).text() == "string":
vars.append('"'+self.tabVar.cellWidget(cell, 1).text()+'"')
else:
vars.append(self.tabVar.cellWidget(cell, 1).text())
else:
vars.append(self.tabVar.cellWidget(cell, 2).currentText())
if len(vars) is 0:
vars = None
return vars
def getInstructions(self, inst=[]):
instRight = self.getInstructionsRIGHT()
instBottom = self.getInstructionsBOTTOM()
instBottomIn = self.getInstructionsBOTTOMIN()
nameControl = self.parentBlock.nameControl
if nameControl is "":
nameControl = None
dic = {}
dic["NAMECONTROL"] = nameControl
dic["RIGHT"] = instRight
dic["BOTTOM"] = instBottom
dic["BOTTOMIN"] = instBottomIn
dic["VARIABLES"] = self.getVars()
dic["TYPE"] = self.__type
dic["VISUALBLOCK"] = self
return self.getNameFuntion(), dic
def getId(self):
return self.parentBlock.id
def updateImg(self, force=False):
if self.__typeBlock is COMPLEXBLOCK:
nSubBlock, size = self.getNumSub()
else:
size = 34
if size is 0:
size = 34
if self.sizeIn != size or self.shouldUpdate or force:
self.sizeIn = size
im = generateBlock(self.cvImg, size, self.showtext, self.__typeBlock, None, self.getVars(), self.__type,
self.parentBlock.nameControl)
if self.highlighted:
im = generate_error_block(im)
if not self.isEnabled():
r, g, b, a = cv2.split(im)
im = cv2.cvtColor(im, cv2.COLOR_RGBA2GRAY)
im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
r, g, b= cv2.split(im)
im = cv2.merge((r, g, b, a))
qImage = toQImage(im)
self.img = QtGui.QPixmap(qImage)
self.updatePixmap()
if self.sizeIn != size or self.shouldUpdate:
for c in self.connections:
if c.getType() is BOTTOM:
c.setPoint(QtCore.QPointF(c.getPoint().x(), im.shape[0] - 5))
if c.getIdItem() is not None:
self.scene.getVisualItem(c.getIdItem()).moveToPos(
self.pos() + QtCore.QPointF(0, self.img.height() - 5))
if c.getType() is RIGHT:
c.setPoint(QtCore.QPointF(im.shape[1] - 5, c.getPoint().y()))
if c.getIdItem() is not None:
self.scene.getVisualItem(c.getIdItem()).moveToPos(
self.pos() + QtCore.QPointF(self.img.width() - 5, 0))
self.shouldUpdate = False
def updateVarValues(self):
vars = self.getVars()
prev_vars = self.parentBlock.getVars()
if vars is not None:
for i in range(0, len(vars)):
if vars[i] != prev_vars[i].defaul:
self.shouldUpdate = True
self.parentBlock.updateVars(vars)
break
def updateConnections(self):
for c in [conn for conn in self.connections if conn.getConnect() is not None and EuclideanDist(conn.getPosPoint(), conn.getConnect().getPosPoint()) > 7]:
c.getConnect().setItem(None)
c.getConnect().setConnect(None)
c.setItem(None)
c.setConnect(None)
def update(self):
if len(self.dicTrans) is not 0 and self.showtext is not self.dicTrans[getLanguage()]:
#Language change
self.create_dialogs()
self.shouldUpdate = True
self.showtext = self.dicTrans[getLanguage()]
vars = self.parentBlock.vars
for i, var in zip(range(len(vars)), vars):
try:
if getLanguage() in var.translate:
self.tabVar.setCellWidget(i, 0, QtWidgets.QLabel(var.translate[getLanguage()]))
else:
self.tabVar.setCellWidget(i, 0, QtWidgets.QLabel(var.name))
if var.type == "list":
values = var.translateValues[getLanguage()]
val = self.tabVar.cellWidget(i, 1).currentIndex()
combobox = QtWidgets.QComboBox()
combobox.addItems(values)
self.tabVar.setCellWidget(i, 1, combobox)
combobox.setCurrentIndex(val)
except:
self.tabVar.setCellWidget(i, 0, QtWidgets.QLabel(var.name))
for row in range(0, self.tabVar.rowCount()):
combobox = self.tabVar.cellWidget(row, 2)
items = []
for i in reversed(range(1, combobox.count())):
items.append(combobox.itemText(i))
if combobox.itemText(i) not in self.scene.parent.listNameVars:
combobox.removeItem(i)
combobox.setCurrentIndex(0)
for var in self.scene.parent.listNameVars:
if var not in items:
combobox.addItem(var)
self.updateVarValues()
self.updateImg()
if self.shouldUpdateConnections:
self.updateConnections()
def moveToPos(self, pos, connect=False):
if self.highlighted:
self.unhighlight()
self.clearNotifications()
if connect is False and self.posmouseinItem is not None:
pos = pos - self.posmouseinItem
self.setPos(pos)
self.parentBlock.setPos(copy.deepcopy(self.pos()))
self.scene.activeShouldSave()
for c in self.connections:
if c.getType() in (TOP, LEFT) and self is self.scene.getItemSelected() and connect is not True:
if c.getIdItem() is not None:
c.getConnect().setItem(None)
c.getConnect().setConnect(None)
c.setItem(None)
c.setConnect(None)
elif c.getType() is BOTTOM:
if c.getIdItem() is not None:
self.scene.getVisualItem(c.getIdItem()).moveToPos(
self.pos() + QtCore.QPointF(0, self.img.height() - 5), connect)
elif c.getType() is BOTTOMIN:
if c.getIdItem() is not None:
self.scene.getVisualItem(c.getIdItem()).moveToPos(self.pos() + QtCore.QPointF(17, 33), connect)
elif c.getType() is RIGHT:
if c.getIdItem() is not None:
self.scene.getVisualItem(c.getIdItem()).moveToPos(
self.pos() + QtCore.QPointF(self.img.width() - 5, 0), connect)
def getLastItem(self):
for c in [conn for conn in self.connections if conn.getType() is BOTTOM]:
if c.getConnect() is None:
return c
else:
return self.scene.getVisualItem(c.getIdItem()).getLastItem()
return None
def getLastRightItem(self):
for c in [conn for conn in self.connections if conn.getType() is RIGHT]:
if c.getConnect() is None:
return c
else:
return self.scene.getVisualItem(c.getIdItem()).getLastRightItem()
return None
def moveToFront(self):
self.setZValue(1)
for c in [conn for conn in self.connections if conn.getType() in [BOTTOM, BOTTOMIN] and conn.getConnect() is not None]:
self.scene.getVisualItem(c.getIdItem()).moveToFront()
def mouseMoveEvent(self, event):
if self.isEnabled():
self.setPos(event.scenePos() - self.posmouseinItem)
self.parentBlock.setPos(self.pos())
self.scene.activeShouldSave()
def mousePressEvent(self, event):
if self.isEnabled():
if event.button() is QtCore.Qt.MouseButton.LeftButton:
self.posmouseinItem = event.scenePos() - self.pos()
self.scene.setIdItemSelected(self.id)
if self.DialogVar is not None:
self.DialogVar.close()
if event.button() is QtCore.Qt.MouseButton.RightButton:
self.popMenu.exec_(event.screenPos())
def mouseDoubleClickEvent(self, event):
if self.isEnabled():
if event.button() is QtCore.Qt.MouseButton.LeftButton:
self.scene.setIdItemSelected(None)
if self.DialogVar is not None:
self.DialogVar.open()
self.scene.setTable(self.DialogVar)
if event.button() is QtCore.Qt.MouseButton.RightButton:
pass
def mouseReleaseEvent(self, event):
if self.isEnabled():
if event.button() is QtCore.Qt.MouseButton.LeftButton:
self.posmouseinItem = None
self.scene.setIdItemSelected(None)
if event.button() is QtCore.Qt.MouseButton.RightButton:
self.posmouseinItem = None
self.scene.setIdItemSelected(None)
pass
def delete(self, savetmp=True):
self.DialogVar.close()
del self.cvImg
del self.img
del self.foot
del self.header
del self.timer
del self.DialogVar
for c in [conn for conn in self.connections if conn.getIdItem() is not None]:
if c.getType() in [BOTTOM, BOTTOMIN, RIGHT]:
self.scene.getVisualItem(c.getIdItem()).delete(savetmp=False)
else:
c.getConnect().setConnect(None)
c.getConnect().setItem(None)
if self.parentBlock.name == "when":
self.scene.parent.delWhen(self.parentBlock.nameControl)
if self.parentBlock.name == "main" and self.scene.parent.mainButton is not None:
self.scene.parent.mainButton.setEnabled(True)
self.scene.removeItem(self.id, savetmp)
del self.parentBlock
del self
def isBlockDef(self):
if self.parentBlock.name == "when":
return True
if len([conn for conn in self.connections if conn.getType() in [TOP, BOTTOM, RIGHT, LEFT]])>0:
return False
return True
def setEnabledDependentBlocks(self,enable):
self.shouldUpdate = True
self.setEnabled(enable)
for c in [conn for conn in self.connections if conn.getIdItem() is not None and conn.getType() not in [TOP, LEFT]]:
self.scene.getVisualItem(c.getIdItem()).setEnabledDependentBlocks(enable)<|fim▁end|> | |
<|file_name|>main_intents_strategy.py<|end_file_name|><|fim▁begin|>'''
Created on Nov 26, 2014
@author: Yury Zhauniarovich <y.zhalnerovich{at}gmail.com>
'''
import os, time
from interfaces.adb_interface import AdbInterface
from bboxcoverage import BBoxCoverage
from running_strategies import IntentInvocationStrategy
import smtplib
import email.utils
from email.mime.text import MIMEText
APK_DIR_SOURCES = ["", ""]
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
SENDER = ""
PASSWORD = ""
TO_EMAIL = ""
def sendMessage(subj, email_message):
msg = MIMEText(email_message)
msg['To'] = email.utils.formataddr(('Recipient', TO_EMAIL))
msg['From'] = email.utils.formataddr(('Author', SENDER))
msg['Subject'] = subj
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
try:
server.set_debuglevel(True)
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
server.login(SENDER, PASSWORD)
server.sendmail(SENDER, [TO_EMAIL], msg.as_string())
finally:
server.quit()
def getExecutionDevice():
'''
This method allows a user to select a device that is used to for further
analysis.
'''
dev_list = AdbInterface.getDeviceSerialsList()
devNum = len(dev_list)
if devNum <= 0:
print "No device has been detected! Connect your device and restart the application!"
return
if devNum == 1:
return dev_list[0]
choice = None
if devNum > 1:
print "Select the device to use for analysis:\n"
for i in xrange(0, devNum):
print "%d. %s\n" % ((i + 1), dev_list[i])
while not choice:
try:
choice = int(raw_input())
if choice not in range(1, devNum+1):
choice = None
print 'Invalid choice! Choose right number!'
except ValueError:
print 'Invalid Number! Choose right number!'
return dev_list[choice-1]
def getSubdirs(rootDir):
return [os.path.join(rootDir, name) for name in os.listdir(rootDir)
if os.path.isdir(os.path.join(rootDir, name))]
def getInstrApkInFolder(folder):
for f in os.listdir(folder):
if f.endswith("_aligned.apk"):
filepath = os.path.join(folder, f)
return filepath
return None
def runMainIntentsStrategy(adb, androidManifest, delay=10):
automaticTriggeringStrategy = IntentInvocationStrategy(adbDevice=adb, pathToAndroidManifest=androidManifest)
automaticTriggeringStrategy.run(delay=delay)
#main part
adb = AdbInterface()
device = getExecutionDevice()
if not device:
exit(1)
adb.setTargetSerial(device)
bboxcoverage = BBoxCoverage()
for apk_dir_source in APK_DIR_SOURCES:
print "\n\nStarting experiment for directory: [%s]" % apk_dir_source
result_directories = getSubdirs(apk_dir_source)
for directory in result_directories:
apk_file = getInstrApkInFolder(directory)
if apk_file:
print "Starting experiment for apk: [%s]" % apk_file
try:
bboxcoverage.initAlreadyInstrApkEnv(pathToInstrApk=apk_file, resultsDir=directory)
except:
print "Exception while initialization!"
continue
try:
bboxcoverage.installApkOnDevice()
except:
print "Exception while installation apk on device!"
bboxcoverage.uninstallPackage()
try:
bboxcoverage.installApkOnDevice()
except:
continue
package_name = bboxcoverage.getPackageName()
params = {}
params["strategy"] = "main_intents"
params["package_name"] = package_name
params["main_activity"] = bboxcoverage.androidManifest.getMainActivity()
try:
bboxcoverage.startTesting()
except:
print "Exception while startTesting!"
bboxcoverage.uninstallPackage()
continue
try:
runMainIntentsStrategy(adb=adb, androidManifest=bboxcoverage.androidManifestFile, delay=10)
except:
print "Exception while running strategy!"
bboxcoverage.uninstallPackage()
continue
try: <|fim▁hole|> bboxcoverage.uninstallPackage()
continue
time.sleep(3)
bboxcoverage.uninstallPackage()
time.sleep(5)
sendMessage("[BBoxTester]", "Experiments done for directory [%s]!" % apk_dir_source)<|fim▁end|> | bboxcoverage.stopTesting("main_intents", paramsToWrite=params)
except:
print "Exception while running strategy!" |
<|file_name|>Physics.ts<|end_file_name|><|fim▁begin|>import { Physics as EightBittrPhysics } from "eightbittr";
import { FullScreenPokemon } from "../FullScreenPokemon";
import { Direction } from "./Constants";
import { Character, Grass, Actor } from "./Actors";
/**
* Physics functions to move Actors around.
*/
export class Physics<Game extends FullScreenPokemon> extends EightBittrPhysics<Game> {
/**
* Determines the bordering direction from one Actor to another.
*
* @param actor The source Actor.
* @param other The destination Actor.
* @returns The direction from actor to other.
*/
public getDirectionBordering(actor: Actor, other: Actor): Direction | undefined {
if (Math.abs(actor.top - (other.bottom - other.tolBottom)) < 4) {
return Direction.Top;
}
if (Math.abs(actor.right - other.left) < 4) {
return Direction.Right;
}
if (Math.abs(actor.bottom - other.top) < 4) {
return Direction.Bottom;
}
if (Math.abs(actor.left - other.right) < 4) {<|fim▁hole|> }
return undefined;
}
/**
* Determines the direction from one Actor to another.
*
* @param actor The source Actor.
* @param other The destination Actor.
* @returns The direction from actor to other.
* @remarks Like getDirectionBordering, but for cases where the two Actors
* aren't necessarily touching.
*/
public getDirectionBetween(actor: Actor, other: Actor): Direction {
const dx: number = this.getMidX(other) - this.getMidX(actor);
const dy: number = this.getMidY(other) - this.getMidY(actor);
if (Math.abs(dx) > Math.abs(dy)) {
return dx > 0 ? Direction.Right : Direction.Left;
}
return dy > 0 ? Direction.Bottom : Direction.Top;
}
/**
* Checks whether one Actor is overlapping another.
*
* @param actor An in-game Actor.
* @param other An in-game Actor.
* @returns Whether actor and other are overlapping.
*/
public isActorWithinOther(actor: Actor, other: Actor): boolean {
return (
actor.top >= other.top &&
actor.right <= other.right &&
actor.bottom <= other.bottom &&
actor.left >= other.left
);
}
/**
* Determines whether a Character is visually within grass.
*
* @param actor An in-game Character.
* @param other Grass that actor might be in.
* @returns Whether actor is visually within other.
*/
public isActorWActorrass(actor: Character, other: Grass): boolean {
if (actor.right <= other.left) {
return false;
}
if (actor.left >= other.right) {
return false;
}
if (other.top > actor.top + actor.height / 2) {
return false;
}
if (other.bottom < actor.top + actor.height / 2) {
return false;
}
return true;
}
/**
* Shifts a Character according to its xvel and yvel.
*
* @param actor A Character to shift.
*/
public shiftCharacter(actor: Character): void {
if (actor.bordering[Direction.Top] && actor.yvel < 0) {
actor.yvel = 0;
}
if (actor.bordering[Direction.Right] && actor.xvel > 0) {
actor.xvel = 0;
}
if (actor.bordering[Direction.Bottom] && actor.yvel > 0) {
actor.yvel = 0;
}
if (actor.bordering[Direction.Left] && actor.xvel < 0) {
actor.xvel = 0;
}
this.shiftBoth(actor, actor.xvel, actor.yvel);
}
/**
* Snaps a moving Actor to a predictable grid position.
*
* @param actor An Actor to snap the position of.
*/
public snapToGrid(actor: Actor): void {
const grid = 32;
const x: number = (this.game.mapScreener.left + actor.left) / grid;
const y: number = (this.game.mapScreener.top + actor.top) / grid;
this.setLeft(actor, Math.round(x) * grid - this.game.mapScreener.left);
this.setTop(actor, Math.round(y) * grid - this.game.mapScreener.top);
}
}<|fim▁end|> | return Direction.Left; |
<|file_name|>shapeshift.js<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import { observer } from 'mobx-react';
import React, { Component, PropTypes } from 'react';
import { FormattedMessage } from 'react-intl';
import shapeshiftLogo from '~/../assets/images/shapeshift-logo.png';
import { Button, IdentityIcon, Portal } from '~/ui';
import { CancelIcon, DoneIcon } from '~/ui/Icons';
import AwaitingDepositStep from './AwaitingDepositStep';
import AwaitingExchangeStep from './AwaitingExchangeStep';
import CompletedStep from './CompletedStep';
import ErrorStep from './ErrorStep';
import OptionsStep from './OptionsStep';
import Store, { STAGE_COMPLETED, STAGE_OPTIONS, STAGE_WAIT_DEPOSIT, STAGE_WAIT_EXCHANGE } from './store';
import styles from './shapeshift.css';
const STAGE_TITLES = [
<FormattedMessage
id='shapeshift.title.details'
defaultMessage='details'
/>,
<FormattedMessage
id='shapeshift.title.deposit'
defaultMessage='awaiting deposit'
/>,
<FormattedMessage
id='shapeshift.title.exchange'
defaultMessage='awaiting exchange'
/>,
<FormattedMessage
id='shapeshift.title.completed'
defaultMessage='completed'
/>
];
const ERROR_TITLE = (
<FormattedMessage
id='shapeshift.title.error'
defaultMessage='exchange failed'
/>
);
@observer
export default class Shapeshift extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
}
static propTypes = {
address: PropTypes.string.isRequired,
onClose: PropTypes.func
}
store = new Store(this.props.address);
componentDidMount () {
this.store.retrieveCoins();
}
componentWillUnmount () {
this.store.unsubscribe();
}
render () {
const { error, stage } = this.store;
return (
<Portal
activeStep={ stage }
busySteps={ [
STAGE_WAIT_DEPOSIT,
STAGE_WAIT_EXCHANGE
] }
buttons={ this.renderDialogActions() }
onClose={ this.onClose }
open
steps={
error
? null
: STAGE_TITLES
}
title={
error
? ERROR_TITLE
: null
}
>
{ this.renderPage() }
</Portal>
);
}
renderDialogActions () {
const { address } = this.props;
const { coins, error, hasAcceptedTerms, stage } = this.store;
const logo = (
<a
className={ styles.shapeshift }
href='http://shapeshift.io'
key='logo'
target='_blank'
>
<img src={ shapeshiftLogo } />
</a>
);
const cancelBtn = (
<Button
icon={ <CancelIcon /> }
key='cancel'
label={
<FormattedMessage
id='shapeshift.button.cancel'
defaultMessage='Cancel'
/>
}
onClick={ this.onClose }
/>
);
if (error) {
return [
logo,
cancelBtn
];
}
switch (stage) {
case STAGE_OPTIONS:
return [
logo,
cancelBtn,
<Button
disabled={ !coins.length || !hasAcceptedTerms }
icon={
<IdentityIcon
address={ address }
button
/>
}
key='shift'
label={
<FormattedMessage
id='shapeshift.button.shift'
defaultMessage='Shift Funds'
/>
}
onClick={ this.onShift }
/>
];
case STAGE_WAIT_DEPOSIT:
case STAGE_WAIT_EXCHANGE:
return [
logo,
cancelBtn
];
case STAGE_COMPLETED:
return [
logo,
<Button
icon={ <DoneIcon /> }
key='done'
label={
<FormattedMessage
id='shapeshift.button.done'
defaultMessage='Close'
/>
}
onClick={ this.onClose }
/>
];
}
}
renderPage () {
const { error, stage } = this.store;<|fim▁hole|> return (
<ErrorStep store={ this.store } />
);
}
switch (stage) {
case STAGE_OPTIONS:
return (
<OptionsStep store={ this.store } />
);
case STAGE_WAIT_DEPOSIT:
return (
<AwaitingDepositStep store={ this.store } />
);
case STAGE_WAIT_EXCHANGE:
return (
<AwaitingExchangeStep store={ this.store } />
);
case STAGE_COMPLETED:
return (
<CompletedStep store={ this.store } />
);
}
}
onClose = () => {
this.store.setStage(STAGE_OPTIONS);
this.props.onClose && this.props.onClose();
}
onShift = () => {
return this.store.shift();
}
}<|fim▁end|> |
if (error) { |
<|file_name|>test-ae-rbm.py<|end_file_name|><|fim▁begin|>import os
from rbm import RBM
from au import AutoEncoder
import tensorflow as tf<|fim▁hole|>
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
flags.DEFINE_integer('epochs', 50, 'The number of training epochs')
flags.DEFINE_integer('batchsize', 30, 'The batch size')
flags.DEFINE_boolean('restore_rbm', False, 'Whether to restore the RBM weights or not.')
# ensure output dir exists
if not os.path.isdir('out'):
os.mkdir('out')
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
trX, teY = min_max_scale(trX, teX)
# RBMs
rbmobject1 = RBM(784, 900, ['rbmw1', 'rbvb1', 'rbmhb1'], 0.3)
rbmobject2 = RBM(900, 500, ['rbmw2', 'rbvb2', 'rbmhb2'], 0.3)
rbmobject3 = RBM(500, 250, ['rbmw3', 'rbvb3', 'rbmhb3'], 0.3)
rbmobject4 = RBM(250, 2, ['rbmw4', 'rbvb4', 'rbmhb4'], 0.3)
if FLAGS.restore_rbm:
rbmobject1.restore_weights('./out/rbmw1.chp')
rbmobject2.restore_weights('./out/rbmw2.chp')
rbmobject3.restore_weights('./out/rbmw3.chp')
rbmobject4.restore_weights('./out/rbmw4.chp')
# Autoencoder
autoencoder = AutoEncoder(784, [900, 500, 250, 2], [['rbmw1', 'rbmhb1'],
['rbmw2', 'rbmhb2'],
['rbmw3', 'rbmhb3'],
['rbmw4', 'rbmhb4']], tied_weights=False)
iterations = len(trX) / FLAGS.batchsize
# Train First RBM
print('first rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
rbmobject1.partial_fit(batch_xs)
print(rbmobject1.compute_cost(trX))
show_image("out/1rbm.jpg", rbmobject1.n_w, (28, 28), (30, 30))
rbmobject1.save_weights('./out/rbmw1.chp')
# Train Second RBM2
print('second rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
# Transform features with first rbm for second rbm
batch_xs = rbmobject1.transform(batch_xs)
rbmobject2.partial_fit(batch_xs)
print(rbmobject2.compute_cost(rbmobject1.transform(trX)))
show_image("out/2rbm.jpg", rbmobject2.n_w, (30, 30), (25, 20))
rbmobject2.save_weights('./out/rbmw2.chp')
# Train Third RBM
print('third rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
# Transform features
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
batch_xs = rbmobject1.transform(batch_xs)
batch_xs = rbmobject2.transform(batch_xs)
rbmobject3.partial_fit(batch_xs)
print(rbmobject3.compute_cost(rbmobject2.transform(rbmobject1.transform(trX))))
show_image("out/3rbm.jpg", rbmobject3.n_w, (25, 20), (25, 10))
rbmobject3.save_weights('./out/rbmw3.chp')
# Train Third RBM
print('fourth rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
# Transform features
batch_xs = rbmobject1.transform(batch_xs)
batch_xs = rbmobject2.transform(batch_xs)
batch_xs = rbmobject3.transform(batch_xs)
rbmobject4.partial_fit(batch_xs)
print(rbmobject4.compute_cost(rbmobject3.transform(rbmobject2.transform(rbmobject1.transform(trX)))))
rbmobject4.save_weights('./out/rbmw4.chp')
# Load RBM weights to Autoencoder
autoencoder.load_rbm_weights('./out/rbmw1.chp', ['rbmw1', 'rbmhb1'], 0)
autoencoder.load_rbm_weights('./out/rbmw2.chp', ['rbmw2', 'rbmhb2'], 1)
autoencoder.load_rbm_weights('./out/rbmw3.chp', ['rbmw3', 'rbmhb3'], 2)
autoencoder.load_rbm_weights('./out/rbmw4.chp', ['rbmw4', 'rbmhb4'], 3)
# Train Autoencoder
print('autoencoder')
for i in range(FLAGS.epochs):
cost = 0.0
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
cost += autoencoder.partial_fit(batch_xs)
print(cost)
autoencoder.save_weights('./out/au.chp')
autoencoder.load_weights('./out/au.chp')
fig, ax = plt.subplots()
print(autoencoder.transform(teX)[:, 0])
print(autoencoder.transform(teX)[:, 1])
plt.scatter(autoencoder.transform(teX)[:, 0], autoencoder.transform(teX)[:, 1], alpha=0.5)
plt.show()
raw_input("Press Enter to continue...")
plt.savefig('out/myfig')<|fim▁end|> | import input_data
from utilsnn import show_image, min_max_scale
import matplotlib.pyplot as plt |
<|file_name|>subtypingWithCallSignaturesA.js<|end_file_name|><|fim▁begin|>//// [subtypingWithCallSignaturesA.ts]
declare function foo3(cb: (x: number) => number): typeof cb;<|fim▁hole|>//// [subtypingWithCallSignaturesA.js]
var r5 = foo3(function (x) { return ''; });<|fim▁end|> | var r5 = foo3((x: number) => ''); // error
|
<|file_name|>test_get_role_details_action.py<|end_file_name|><|fim▁begin|>from unittest import mock
from taskplus.core.actions import GetRoleDetailsAction, GetRoleDetailsRequest
from taskplus.core.domain import UserRole
from taskplus.core.shared.response import ResponseFailure
def test_get_role_details_action():
role = mock.Mock()
role = UserRole(name='admin', id=1)
roles_repo = mock.Mock()
roles_repo.one.return_value = role
request = GetRoleDetailsRequest(role.id)
action = GetRoleDetailsAction(roles_repo)
response = action.execute(request)
assert bool(response) is True
roles_repo.one.assert_called_once_with(role.id)
assert response.value == role
def test_get_role_details_action_with_hooks():
role = mock.Mock()
role = UserRole(name='admin', id=1)
roles_repo = mock.Mock()
roles_repo.one.return_value = role
request = GetRoleDetailsRequest(role.id)
action = GetRoleDetailsAction(roles_repo)
before = mock.MagicMock()
after = mock.MagicMock()
action.add_before_execution_hook(before)
action.add_after_execution_hook(after)<|fim▁hole|>
response = action.execute(request)
assert before.called
assert after.called
assert bool(response) is True
roles_repo.one.assert_called_once_with(role.id)
assert response.value == role
def test_get_role_details_action_handles_bad_request():
role = mock.Mock()
role = UserRole(name='admin', id=1)
roles_repo = mock.Mock()
roles_repo.one.return_value = role
request = GetRoleDetailsRequest(role_id=None)
action = GetRoleDetailsAction(roles_repo)
response = action.execute(request)
assert bool(response) is False
assert not roles_repo.one.called
assert response.value == {
'type': ResponseFailure.PARAMETER_ERROR,
'message': 'role_id: is required'
}
def test_get_role_details_action_handles_generic_error():
error_message = 'Error!!!'
roles_repo = mock.Mock()
roles_repo.one.side_effect = Exception(error_message)
request = GetRoleDetailsRequest(role_id=1)
action = GetRoleDetailsAction(roles_repo)
response = action.execute(request)
assert bool(response) is False
roles_repo.one.assert_called_once_with(1)
assert response.value == {
'type': ResponseFailure.SYSTEM_ERROR,
'message': 'Exception: {}'.format(error_message)
}<|fim▁end|> | |
<|file_name|>wp-category-show.js<|end_file_name|><|fim▁begin|>/**
* Javascript file for Category Show.
* It requires jQuery.
*/
function wpcs_gen_tag() {<|fim▁hole|> // There is a need to add the id%% tag to be compatible with other versions
$("#wpcs_gen_tag").val("%%wpcs-"+$("#wpcs_term_dropdown").val()+"%%"+$("#wpcs_order_type").val()+$("#wpcs_order_by").val()+"%%id%%");
$("#wpcs_gen_tag").select();
$("#wpcs_gen_tag").focus();
}<|fim▁end|> | // Category Show searches for term_id since 0.4.1 and not term slug. |
<|file_name|>toolchain.py<|end_file_name|><|fim▁begin|># Directives using the toolchain
# documentation.
import docutils
<|fim▁hole|> app.add_object_type("ppdirective", "ppdir");
app.add_object_type("literal", "lit");<|fim▁end|> | def setup(app):
app.add_object_type("asmdirective", "asmdir");
app.add_object_type("asminstruction", "asminst");
app.add_object_type("ppexpressionop", "ppexprop"); |
<|file_name|>Updatedserver.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import logging
import os
import urllib
from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure
from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface
import cvmfsreplica.pluginsmanagement as pm
class Updatedserver(RepositoryPluginAcceptanceInterface):
def __init__(self, repository, conf):
self.log = logging.getLogger('cvmfsreplica.updatedserver')
self.repository = repository
self.conf = conf
try:
self.url = self.repository.cvmfsconf.get('CVMFS_STRATUM0')
self.reportplugins = pm.readplugins(self.repository,
'repository',
'report',
self.conf.namespace('acceptance.updatedserver.',
exclude=True)
)
except:
raise PluginConfigurationFailure('failed to initialize Updatedserver plugin')
self.log.debug('plugin Updatedserver initialized properly')
#def verify(self):
# '''
# checks if file .cvmfspublished
# was updated more recently than variable
# repository.last_published
# '''
# try:
# # FIXME
# # maybe we should try a couple of times in case of failures before failing definitely
# for line in urllib.urlopen('%s/.cvmfspublished' %self.url).readlines():
# if line.startswith('T'):
# time = int(line[1:-1])
# break
# out = time > self.repository.last_published
# if out == False:
# self._notify_failure('No new content at the server for repository %s' \
# %self.repository.repositoryname)
# return out
# except:
# self.log.warning('file %s/.cvmfspublished cannot be read. Returning False' %self.url)
# return False
def verify(self):
'''
checks if the revision number in local copy of .cvmfspublished
is different that the revision number of remote .cvmfspublished
'''
try:
# FIXME
# maybe we should try a couple of times in case of failures before failing definitely
for line in urllib.urlopen('%s/.cvmfspublished' %self.url).readlines():
if line.startswith('S'):
serverrevision = int(line[1:-1])
break<|fim▁hole|> cvmfs_upstream_storage = self.repository._get_cvmfs_upstream_storage() # FIXME, this should not be here
localfile = '%s/.cvmfspublished' %cvmfs_upstream_storage
if not os.path.isfile(localfile):
self.log.warning('local file %s does not exist. Returning True' %localfile)
return True
else:
# FIXME: too much duplicated code
for line in open(localfile):
if line.startswith('S'):
localrevision = int(line[1:-1])
break
out = (serverrevision != localrevision)
if out == False:
self._notify_failure('No new content at the server for repository %s' \
%self.repository.repositoryname)
return out
except:
self.log.warning('file %s/.cvmfspublished cannot be read. Returning False' %self.url)
return False
def _notify_failure(self, msg):
for report in self.reportplugins:
report.notifyfailure(msg)<|fim▁end|> |
# read the local revision number |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .decorators import render_to_json<|fim▁hole|><|fim▁end|> | from .helper import HeadFileUploader, ImageFactory, BaseModelManager, get_first_letter, convertjson |
<|file_name|>IEntityService.ts<|end_file_name|><|fim▁begin|> module app.shared {<|fim▁hole|> }<|fim▁end|> | export interface IEntityService<T extends IEntity> {
post : (entity : T) => ng.IPromise<T>;
} |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup
from setuptools import find_packages
setup(
name='geonition_aliases',
version='0.0.1',
author='Dariusz Walczak',
url='',
packages=find_packages(),
include_package_data=True,
package_data = {
"geoforms": [
"templates/*.html",
"templates/*.api.js",
"templates/jstranslations.txt",
"templates/help/*.html",
"templates/admin/geoforms/geoformelement/*.html",
"locale/*/LC_MESSAGES/*.po",
"locale/*/LC_MESSAGES/*.mo",
"static/js/*",
"static/css/*.css",
"static/css/images/*.png"
],
},
zip_safe=False,
install_requires=['django',<|fim▁hole|> 'django-modeltranslation'],
)<|fim▁end|> | |
<|file_name|>trans_frater_augmentation.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
<|fim▁hole|>from lib.util.memorized import memorized
from lib.graph.graph import Graph
# Calculate one transitive-fraternal-augmentation-step and
# result a tuple (newgraph, transedges, fratedges)
@memorized(['orig', 'step'])
def trans_frater_augmentation(orig, g, trans, frat, col,
nodes, step, td, ldoFunc):
fratGraph = Graph()
newTrans = {}
for v in g:
for x, y, _, in g.trans_trips(v):
newTrans[(x, y)] = step
assert (not g.adjacent(x, y)), \
"{0} {1} transitive but adjacent".format(x, y)
for x, y, _ in g.frat_trips(v):
fratGraph.add_edge(x, y)
assert (not g.adjacent(x, y)), \
"{0} {1} fraternal but adjacent".format(x, y)
for (s, t) in newTrans.keys():
g.add_arc(s, t, 1)
fratGraph.remove_edge(s, t)
# TODO: support dict to see current in-degree...
fratDigraph = ldoFunc(fratGraph)
# calculate result
trans.update(newTrans)
for s, t, _ in fratDigraph.arcs():
frat[(s, t)] = step
g.add_arc(s, t, 1)
return (g, trans, frat)
# end def<|fim▁end|> | |
<|file_name|>wrapper.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.<|fim▁hole|>// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[allow(ctypes)];
#[allow(heap_memory)];
#[allow(implicit_copies)];
#[allow(managed_heap_memory)];
#[allow(non_camel_case_types)];
#[allow(owned_heap_memory)];
#[allow(path_statement)];
#[allow(unrecognized_lint)];
#[allow(unused_imports)];
#[allow(while_true)];
#[allow(unused_variable)];
#[allow(dead_assignment)];
#[allow(unused_unsafe)];
#[allow(unused_mut)];
extern mod std;
fn print<T>(result: T) {
io::println(fmt!("%?", result));
}<|fim▁end|> | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import itertools
from django.conf import settings
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils import timezone
from schedule.feeds.ical import ICalendarFeed
from schedule.models import Calendar
class UpcomingEventsFeed(Feed):
feed_id = "upcoming"
def feed_title(self, obj):
return "Upcoming Events for %s" % obj.name
def get_object(self, request, calendar_id):
return Calendar.objects.get(pk=calendar_id)<|fim▁hole|>
def link(self, obj):
if not obj:
raise FeedDoesNotExist
return obj.get_absolute_url()
def items(self, obj):
return itertools.islice(
#obj.occurrences_after(timezone.now()),
obj.occurrences_after(timezone.localtime(timezone.now())),
getattr(settings, "FEED_LIST_LENGTH", 10),
)
def item_id(self, item):
return str(item.id)
def item_title(self, item):
return item.event.title
def item_authors(self, item):
if item.event.creator is None:
return [{"name": ""}]
return [{"name": item.event.creator.username}]
def item_updated(self, item):
return item.event.created_on
def item_content(self, item):
return "{} \n {}".format(item.event.title, item.event.description)
class CalendarICalendar(ICalendarFeed):
def items(self):
cal_id = self.args[1]
cal = Calendar.objects.get(pk=cal_id)
return cal.events.all()
def item_uid(self, item):
return str(item.id)
def item_start(self, item):
return item.start
def item_end(self, item):
return item.end
def item_summary(self, item):
return item.title
def item_created(self, item):
return item.created_on<|fim▁end|> | |
<|file_name|>PokemonRarity_pb2.py<|end_file_name|><|fim▁begin|># Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Enums/PokemonRarity.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='POGOProtos/Enums/PokemonRarity.proto',
package='POGOProtos.Enums',
syntax='proto3',
serialized_pb=_b('\n$POGOProtos/Enums/PokemonRarity.proto\x12\x10POGOProtos.Enums*6\n\rPokemonRarity\x12\n\n\x06NORMAL\x10\x00\x12\r\n\tLEGENDARY\x10\x01\x12\n\n\x06MYTHIC\x10\x02\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_POKEMONRARITY = _descriptor.EnumDescriptor(
name='PokemonRarity',
full_name='POGOProtos.Enums.PokemonRarity',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='NORMAL', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LEGENDARY', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='MYTHIC', index=2, number=2,
options=None,
type=None),
],
containing_type=None,
options=None,<|fim▁hole|>_sym_db.RegisterEnumDescriptor(_POKEMONRARITY)
PokemonRarity = enum_type_wrapper.EnumTypeWrapper(_POKEMONRARITY)
NORMAL = 0
LEGENDARY = 1
MYTHIC = 2
DESCRIPTOR.enum_types_by_name['PokemonRarity'] = _POKEMONRARITY
# @@protoc_insertion_point(module_scope)<|fim▁end|> | serialized_start=58,
serialized_end=112,
) |
<|file_name|>lecroyBaseScope.py<|end_file_name|><|fim▁begin|>"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2014 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import time
import struct
from .. import ivi
from .. import scope
from .. import scpi
from .. import extra
AcquisitionTypeMapping = {
'normal': 'norm',
'peak_detect': 'peak',
'high_resolution': 'hres',
'average': 'aver'}
VerticalCoupling = set(['ac', 'dc', 'gnd'])
InputImpedance = set([1000000, 50, 'gnd'])
# Bandwidth Limits, OFF = none, ON = 20 MHz, 200MHZ = 200 MHz
BandwidthLimit = set(['OFF', 'ON', '200MHZ'])
TriggerModes = set(['auto', 'norm', 'single', 'stop'])
TriggerTypes = set(
['drop', 'edge', 'ev', 'glit', 'ht', 'hv', 'hv2', 'il', 'intv', 'is', 'i2', 'off', 'pl', 'ps', 'p2', 'ql', 'sng',
'sq', 'sr', 'teq', 'ti', 'tl'])
TriggerCouplingMapping = {
'ac': ('ac', 0, 0),
'dc': ('dc', 0, 0),
'hf_reject': ('dc', 0, 1),
'lf_reject': ('lfr', 0, 0),
'noise_reject': ('dc', 1, 0),
'hf_reject_ac': ('ac', 0, 1),
'noise_reject_ac': ('ac', 1, 0),
'hf_noise_reject': ('dc', 1, 1),
'hf_noise_reject_ac': ('ac', 1, 1),
'lf_noise_reject': ('lfr', 1, 0)}
TVTriggerEventMapping = {'field1': 'fie1',
'field2': 'fie2',
'any_field': 'afi',
'any_line': 'alin',
'line_number': 'lfi1',
'vertical': 'vert',
'line_field1': 'lfi1',
'line_field2': 'lfi2',
'line': 'line',
'line_alternate': 'lalt',
'lvertical': 'lver'}
TVTriggerFormatMapping = {'generic': 'gen',
'ntsc': 'ntsc',
'pal': 'pal',
'palm': 'palm',
'secam': 'sec',
'p480l60hz': 'p480',
'p480': 'p480',
'p720l60hz': 'p720',
'p720': 'p720',
'p1080l24hz': 'p1080',
'p1080': 'p1080',
'p1080l25hz': 'p1080l25hz',
'p1080l50hz': 'p1080l50hz',
'p1080l60hz': 'p1080l60hz',
'i1080l50hz': 'i1080l50hz',
'i1080': 'i1080l50hz',
'i1080l60hz': 'i1080l60hz'}
PolarityMapping = {'positive': 'pos',
'negative': 'neg'}
GlitchConditionMapping = {'less_than': 'less',
'greater_than': 'gre'}
WidthConditionMapping = {'within': 'rang'}
SampleModeMapping = {'real_time': 'rtim',
'equivalent_time': 'etim'}
SlopeMapping = {
'positive': 'pos',
'negative': 'neg',
'either': 'eith',
'alternating': 'alt'}
MeasurementFunctionMapping = {
'rise_time': 'risetime',
'fall_time': 'falltime',
'frequency': 'frequency',
'period': 'period',
'voltage_rms': 'vrms display',
'voltage_peak_to_peak': 'vpp',
'voltage_max': 'vmax',
'voltage_min': 'vmin',
'voltage_high': 'vtop',
'voltage_low': 'vbase',
'voltage_average': 'vaverage display',
'width_negative': 'nwidth',
'width_positive': 'pwidth',
'duty_cycle_positive': 'dutycycle',
'amplitude': 'vamplitude',
'voltage_cycle_rms': 'vrms cycle',
'voltage_cycle_average': 'vaverage cycle',
'overshoot': 'overshoot',
'preshoot': 'preshoot',
'ratio': 'vratio',
'phase': 'phase',
'delay': 'delay'}
MeasurementFunctionMappingDigital = {
'rise_time': 'risetime',
'fall_time': 'falltime',
'frequency': 'frequency',
'period': 'period',
'width_negative': 'nwidth',
'width_positive': 'pwidth',
'duty_cycle_positive': 'dutycycle'}
ScreenshotImageFormatMapping = {
'bmp': 'bmp',
'bmp24': 'bmp',
'bmp8': 'bmpcomp',
'jpeg': 'jpeg',
'png': 'png',
'png24': 'png',
'psd': 'psd',
'tiff': 'tiff'}
TimebaseModeMapping = {
'main': 'main',
'window': 'wind',
'xy': 'xy',
'roll': 'roll'}
TimebaseReferenceMapping = {
'left': 'left',
'center': 'cent',
'right': 'righ'}
class lecroyBaseScope(scpi.common.IdnCommand, scpi.common.ErrorQuery, scpi.common.Reset,
scpi.common.SelfTest, scpi.common.Memory,
scope.Base, scope.TVTrigger,
scope.GlitchTrigger, scope.WidthTrigger, scope.AcLineTrigger,
scope.WaveformMeasurement, scope.MinMaxWaveform,
scope.ContinuousAcquisition, scope.AverageAcquisition,
scope.SampleMode, scope.AutoSetup,
extra.common.SystemSetup, extra.common.Screenshot,
ivi.Driver):
"LeCroy generic IVI oscilloscope driver"
def __init__(self, *args, **kwargs):
self.__dict__.setdefault('_instrument_id', '')
self._analog_channel_name = list()
self._analog_channel_count = 4
self._digital_channel_name = list()
self._digital_channel_count = 16
self._channel_count = self._analog_channel_count + self._digital_channel_count
self._channel_label = list()
self._channel_label_position = list()
self._channel_noise_filter = list()
self._channel_interpolation = list()
self._channel_probe_skew = list()
self._channel_invert = list()
self._channel_probe_id = list()
self._channel_bw_limit = list()
super(lecroyBaseScope, self).__init__(*args, **kwargs)
self._memory_size = 5
self._analog_channel_name = list()
self._analog_channel_count = 4
self._digital_channel_name = list()
self._digital_channel_count = 16
self._channel_count = self._analog_channel_count + self._digital_channel_count
self._bandwidth = 1e9
self._horizontal_divisions = 10
self._vertical_divisions = 8
self._timebase_mode = 'main'
self._timebase_reference = 'center'
self._timebase_position = 0.0
self._timebase_range = 1e-3
self._timebase_scale = 100e-6
self._timebase_window_position = 0.0
self._timebase_window_range = 5e-6
self._timebase_window_scale = 500e-9
self._trigger_mode = 'auto'
self._trigger_type = 'edge'
self._display_vectors = True
self._display_labels = True
self._display_grid = "single"
self._identity_description = "LeCroy generic IVI oscilloscope driver"
self._identity_identifier = ""
self._identity_revision = ""
self._identity_vendor = ""
self._identity_instrument_manufacturer = "LeCroy"
self._identity_instrument_model = ""
self._identity_instrument_firmware_revision = ""
self._identity_specification_major_version = 4
self._identity_specification_minor_version = 1
self._identity_supported_instrument_models = ['WR204MXI-A', 'WR204XI-A', 'WR104MXI-A', 'WR104XI-A', 'WR64MXI-A',
'WR64XI-A',
'WR62XI-A', 'WR44MXI-A', 'WR44XI-A']
# Turn off the command header to remove extra information from all responses
self._write("CHDR OFF")
self._add_property('channels[].bw_limit',
self._get_channel_bw_limit,
self._set_channel_bw_limit,
None,
ivi.Doc("""
Commands an internal low-pass filter. When the filter is on, the
bandwidth of the channel is limited to approximately 20 MHz.
"""))
self._add_property('channels[].invert',
self._get_channel_invert,
self._set_channel_invert,
None,
ivi.Doc("""
Selects whether or not to invert the channel.
"""))
self._add_property('channels[].label',
self._get_channel_label,
self._set_channel_label,
None,
ivi.Doc("""
Sets the channel label. Setting a channel label also adds the label to
the nonvolatile label list. Setting the label will turn it's display on.
"""))
self._add_property('channels[].label_position',
self._get_channel_label_position,
self._set_channel_label_position,
None,
ivi.Doc("""
Set the channel label positions
"""))
self._add_property('channels[].probe_skew',
self._get_channel_probe_skew,
self._set_channel_probe_skew,
None,
ivi.Doc("""
Specifies the channel-to-channel skew factor for the channel. Each analog
channel can be adjusted + or - 100 ns for a total of 200 ns difference
between channels. This can be used to compensate for differences in cable
delay. Units are seconds.
"""))
self._add_property('channels[].scale',
self._get_channel_scale,
self._set_channel_scale,
None,
ivi.Doc("""
Specifies the vertical scale, or units per division, of the channel. Units
are volts.
"""))
self._add_property('channels[].trigger_level',
self._get_channel_trigger_level,
self._set_channel_trigger_level,
None,
ivi.Doc("""
Specifies the voltage threshold for the trigger sub-system. The units are
volts. This attribute affects instrument behavior only when the Trigger
Type is set to one of the following values: Edge Trigger, Glitch Trigger,
or Width Trigger.
This attribute, along with the Trigger Slope, Trigger Source, and Trigger
Coupling attributes, defines the trigger event when the Trigger Type is
set to Edge Trigger.
"""))
# TODO: delete following if not used in LeCroy
self._add_property('timebase.mode',
self._get_timebase_mode,
self._set_timebase_mode,
None,
ivi.Doc("""
Sets the current time base. There are four time base modes:
* 'main': normal timebase
* 'window': zoomed or delayed timebase
* 'xy': channels are plotted against each other, no timebase
* 'roll': data moves continuously from left to right
"""))
self._add_property('timebase.reference',
self._get_timebase_reference,
self._set_timebase_reference,
None,
ivi.Doc("""
Sets the time reference to one division from the left side of the screen,
to the center of the screen, or to one division from the right side of the
screen. Time reference is the point on the display where the trigger point
is referenced.
Values:
* 'left'
* 'center'
* 'right'
"""))
self._add_property('timebase.position',
self._get_timebase_position,
self._set_timebase_position,
None,
ivi.Doc("""
Sets the time interval between the trigger event and the display reference
point on the screen. The display reference point is either left, right, or
center and is set with the timebase.reference property. The maximum
position value depends on the time/division settings.
"""))
self._add_property('timebase.range',
self._get_timebase_range,
self._set_timebase_range,
None,
ivi.Doc("""
Sets the full-scale horizontal time in seconds for the main window. The
range is 10 times the current time-per-division setting.
"""))
self._add_property('timebase.scale',
self._get_timebase_scale,
self._set_timebase_scale,
None,
ivi.Doc("""
Sets the horizontal scale or units per division for the main window.
"""))
self._add_property('timebase.window.position',
self._get_timebase_window_position,
self._set_timebase_window_position,
None,
ivi.Doc("""
Sets the horizontal position in the zoomed (delayed) view of the main
sweep. The main sweep range and the main sweep horizontal position
determine the range for this command. The value for this command must
keep the zoomed view window within the main sweep range.
"""))
self._add_property('timebase.window.range',
self._get_timebase_window_range,
self._set_timebase_window_range,
None,
ivi.Doc("""
Sets the fullscale horizontal time in seconds for the zoomed (delayed)
window. The range is 10 times the current zoomed view window seconds per
division setting. The main sweep range determines the range for this
command. The maximum value is one half of the timebase.range value.
"""))
self._add_property('timebase.window.scale',
self._get_timebase_window_scale,
self._set_timebase_window_scale,
None,
ivi.Doc("""
Sets the zoomed (delayed) window horizontal scale (seconds/division). The
main sweep scale determines the range for this command. The maximum value
is one half of the timebase.scale value.
"""))
self._add_property('display.vectors',
self._get_display_vectors,
self._set_display_vectors,
None,
ivi.Doc("""
When enabled, draws a line between consecutive waveform data points.
"""))
self._add_property('display.grid',
self._get_grid_mode,
self._set_grid_mode,<|fim▁hole|>
Values:
* 'single'
* 'dual'
* 'quad'
* 'octal'
* 'auto'
* 'xy'
* 'xysingle'
* 'xydual'
"""))
self._add_property('trigger.mode',
self._get_trigger_mode,
self._set_trigger_mode,
None,
ivi.Doc("""
Specifies the trigger mode of the oscilloscope.
Values:
'auto', 'norm', 'single', 'stop'
* 'auto'
* 'norm'
* 'single'
* 'stop'
"""))
self._add_method('system.fetch_setup',
self._system_fetch_setup,
ivi.Doc("""
Returns the current oscilloscope setup in the form of a binary block. The
setup can be stored in memory or written to a file and then reloaded to the
oscilloscope at a later time with system.load_setup.
"""))
self._add_method('system.load_setup',
self._system_load_setup,
ivi.Doc("""
Transfers a binary block of setup data to the scope to reload a setup
previously saved with system.fetch_setup.
"""))
self._add_method('system.display_string',
self._system_display_string,
ivi.Doc("""
Writes a string to the advisory line on the instrument display. Send None
or an empty string to clear the advisory line.
"""))
self._add_method('display.fetch_screenshot',
self._display_fetch_screenshot,
ivi.Doc("""
Captures the oscilloscope screen and transfers it in the specified format.
The display graticule is optionally inverted.
"""))
self._add_method('memory.save',
self._memory_save,
ivi.Doc("""
Stores the current state of the instrument into an internal storage
register. Use memory.recall to restore the saved state.
"""))
self._add_method('memory.recall',
self._memory_recall,
ivi.Doc("""
Recalls the state of the instrument from an internal storage register
that was previously saved with memory.save.
"""))
self._init_channels()
def initialize(self, resource=None, id_query=False, reset=False, **keywargs):
"Opens an I/O session to the instrument."
self._channel_count = self._analog_channel_count + self._digital_channel_count
super(lecroyBaseScope, self).initialize(resource, id_query, reset, **keywargs)
# interface clear
if not self._driver_operation_simulate:
self._clear()
# check ID
if id_query and not self._driver_operation_simulate:
id = self.identity.instrument_model
id_check = self._instrument_id
id_short = id[:len(id_check)]
if id_short != id_check:
raise Exception("Instrument ID mismatch, expecting %s, got %s", id_check, id_short)
# reset
if reset:
self.utility.reset()
# Modified for LeCroy, working
def _load_id_string(self):
if self._driver_operation_simulate:
self._identity_instrument_manufacturer = "Not available while simulating"
self._identity_instrument_model = "Not available while simulating"
self._identity_instrument_firmware_revision = "Not available while simulating"
else:
lst = self._ask("*IDN?").split(",")
self._identity_instrument_manufacturer = lst[0]
self._identity_instrument_model = lst[1]
self._identity_instrument_firmware_revision = lst[3]
self._set_cache_valid(True, 'identity_instrument_manufacturer')
self._set_cache_valid(True, 'identity_instrument_model')
self._set_cache_valid(True, 'identity_instrument_firmware_revision')
def _get_identity_instrument_manufacturer(self):
if self._get_cache_valid():
return self._identity_instrument_manufacturer
self._load_id_string()
return self._identity_instrument_manufacturer
def _get_identity_instrument_model(self):
if self._get_cache_valid():
return self._identity_instrument_model
self._load_id_string()
return self._identity_instrument_model
def _get_identity_instrument_firmware_revision(self):
if self._get_cache_valid():
return self._identity_instrument_firmware_revision
self._load_id_string()
return self._identity_instrument_firmware_revision
def _utility_disable(self):
pass
# TODO: Determine how to implement system:error? with LeCroy scope
def _utility_error_query(self):
error_code = 0
error_message = "No error"
if not self._driver_operation_simulate:
error_code, error_message = self._ask(":system:error?").split(',')
error_code = int(error_code)
error_message = error_message.strip(' "')
return (error_code, error_message)
def _utility_lock_object(self):
pass
# TODO: test utility reset
def _utility_reset(self):
if not self._driver_operation_simulate:
self._write("*RST")
self.driver_operation.invalidate_all_attributes()
def _utility_reset_with_defaults(self):
self._utility_reset()
# TODO: test self test, check if the time.sleep() is sufficient
def _utility_self_test(self):
code = 0
message = "Self test passed"
if not self._driver_operation_simulate:
self._write("*TST?")
# Wait for test to complete - may be adjusted if required
time.sleep(40)
code = int(self._read())
if code != 0:
message = "Self test failed"
return (code, message)
def _utility_unlock_object(self):
pass
def _init_channels(self):
try:
super(lecroyBaseScope, self)._init_channels()
except AttributeError:
pass
self._channel_name = list()
self._channel_label = list()
self._channel_label_position = list()
self._channel_noise_filter = list()
self._channel_interpolation = list()
self._channel_probe_skew = list()
self._channel_invert = list()
self._channel_probe_id = list()
self._channel_bw_limit = list()
self._channel_input_impedance = list()
self._channel_trigger_level = list()
self._analog_channel_name = list()
for i in range(self._analog_channel_count):
self._channel_name.append("C%d" % (i + 1))
self._channel_label.append("%d" % (i + 1))
self._channel_label_position.append(0)
self._channel_noise_filter.append('None')
self._channel_interpolation.append("Linear")
self._analog_channel_name.append("C%d" % (i + 1))
self._channel_probe_skew.append(0)
self._channel_invert.append(False)
self._channel_probe_id.append("NONE")
self._channel_bw_limit.append(False)
self._channel_coupling.append("NONE")
self._channel_input_impedance.append(0)
self._channel_trigger_level.append(0)
# digital channels
self._digital_channel_name = list()
if (self._digital_channel_count > 0):
for i in range(self._digital_channel_count):
self._channel_name.append("digital%d" % i)
self._channel_label.append("D%d" % i)
self._digital_channel_name.append("digital%d" % i)
for i in range(self._analog_channel_count, self._channel_count):
self._channel_input_frequency_max[i] = 1e9
self._channel_probe_attenuation[i] = 1
# self._channel_coupling[i] = 'dc'
#self._channel_input_impedance[i] = 1000000
#self._channel_coupling[i] = 'D1M'
self._channel_offset[i] = 0
self._channel_range[i] = 1
self._channel_count = self._analog_channel_count + self._digital_channel_count
self.channels._set_list(self._channel_name)
# TODO: how to implement the following on LeCroy scope?
def _system_fetch_setup(self):
if self._driver_operation_simulate:
return b''
self._write(":system:setup?")
return self._read_ieee_block()
# TODO: how to implement the following on LeCroy scope?
def _system_load_setup(self, data):
if self._driver_operation_simulate:
return
self._write_ieee_block(data, ':system:setup ')
self.driver_operation.invalidate_all_attributes()
# TODO: test display_string
def _system_display_string(self, string=None):
if string is None:
string = ""
if not self._driver_operation_simulate:
self._write("MESSAGE \"%s\"" % string)
# Modified for LeCroy, working
def _display_fetch_screenshot(self, format='png', invert=True):
if self._driver_operation_simulate:
return b''
if format not in ScreenshotImageFormatMapping:
raise ivi.ValueNotSupportedException()
format = ScreenshotImageFormatMapping[format]
if invert == False:
color = "BLACK"
elif invert == True:
color = "WHITE"
else:
color = "WHITE"
self._write(
"HCSU DEV,%s,FORMAT,PORTRAIT,BCKG,%s,DEST,\"REMOTE\",PORT,\"NET\",AREA,GRIDAREAONLY" % (str(format), color))
self._write("SCDP")
return self._read_raw()
# TODO: determine how to handle all :timebase: methods for LeCroy
def _get_timebase_mode(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
value = self._ask(":timebase:mode?").lower()
self._timebase_mode = [k for k, v in TimebaseModeMapping.items() if v == value][0]
self._set_cache_valid
return self._timebase_mode
def _set_timebase_mode(self, value):
if value not in TimebaseModeMapping:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write(":timebase:mode %s" % TimebaseModeMapping[value])
self._timebase_mode = value
self._set_cache_valid()
def _get_timebase_reference(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
value = self._ask(":timebase:reference?").lower()
self._timebase_reference = [k for k, v in TimebaseReferenceMapping.items() if v == value][0]
self._set_cache_valid
return self._timebase_reference
def _set_timebase_reference(self, value):
if value not in TimebaseReferenceMapping:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write(":timebase:reference %s" % TimebaseReferenceMapping[value])
self._timebase_reference = value
self._set_cache_valid()
def _get_timebase_position(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._timebase_position = float(self._ask(":timebase:position?"))
self._set_cache_valid()
return self._timebase_position
def _set_timebase_position(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write(":timebase:position %e" % value)
self._timebase_position = value
self._set_cache_valid()
# Modified for LeCroy, working
def _get_timebase_range(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._timebase_scale = float(self._ask("TDIV?"))
self._timebase_range = self._timebase_scale * self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_scale')
return self._timebase_range
# Modified for LeCroy, working
def _set_timebase_range(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write("TDIV %e" % (value / self._horizontal_divisions))
self._timebase_scale = value / self._horizontal_divisions
self._timebase_range = value
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_scale')
# Modified for LeCroy, working
def _get_timebase_scale(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._timebase_scale = float(self._ask("TDIV?"))
self._timebase_range = self._timebase_scale * self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_range')
return self._timebase_scale
# Modified for LeCroy, working
def _set_timebase_scale(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write("TDIV %e" % value)
self._timebase_scale = value
self._timebase_range = value * self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_range')
def _get_timebase_window_position(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._timebase_window_position = float(self._ask(":timebase:window:position?"))
self._set_cache_valid()
return self._timebase_window_position
def _set_timebase_window_position(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write(":timebase:window:position %e" % value)
self._timebase_window_position = value
self._set_cache_valid()
def _get_timebase_window_range(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._timebase_window_range = float(self._ask(":timebase:window:range?"))
self._timebase_window_scale = self._timebase_window_range / self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_window_scale')
return self._timebase_window_range
def _set_timebase_window_range(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write(":timebase:window:range %e" % value)
self._timebase_window_range = value
self._timebase_window_scale = value / self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_window_scale')
def _get_timebase_window_scale(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._timebase_window_scale = float(self._ask(":timebase:window:scale?"))
self._timebase_window_range = self._timebase_window_scale * self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_window_range')
return self._timebase_window_scale
def _set_timebase_window_scale(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write(":timebase:window:scale %e" % value)
self._timebase_window_scale = value
self._timebase_window_range = value * self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(True, 'timebase_window_range')
def _get_display_vectors(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._display_vectors = bool(int(self._ask(":display:vectors?")))
self._set_cache_valid()
return self._display_vectors
def _set_display_vectors(self, value):
value = bool(value)
if not self._driver_operation_simulate:
self._write(":display:vectors %d" % int(value))
self._display_vectors = value
self._set_cache_valid()
# Modified for LeCroy, working
def _get_grid_mode(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._display_vectors = str(self._ask("GRID?"))
self._set_cache_valid()
return self._display_vectors
# Modified for LeCroy, working
def _set_grid_mode(self, value):
if not self._driver_operation_simulate:
self._write("GRID %s" % str(value))
self._display_vectors = str(value)
self._set_cache_valid()
def _get_acquisition_start_time(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._acquisition_start_time = float(self._ask(":waveform:xorigin?"))
self._set_cache_valid()
return self._acquisition_start_time
def _set_acquisition_start_time(self, value):
value = float(value)
value = value + self._get_acquisition_time_per_record() * 5 / 10
if not self._driver_operation_simulate:
self._write(":timebase:position %e" % value)
self._acquisition_start_time = value
self._set_cache_valid()
def _get_acquisition_type(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
value = self._ask(":acquire:type?").lower()
self._acquisition_type = [k for k, v in AcquisitionTypeMapping.items() if v == value][0]
self._set_cache_valid()
return self._acquisition_type
def _set_acquisition_type(self, value):
if value not in AcquisitionTypeMapping:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write(":acquire:type %s" % AcquisitionTypeMapping[value])
self._acquisition_type = value
self._set_cache_valid()
def _get_acquisition_number_of_points_minimum(self):
return self._acquisition_number_of_points_minimum
def _set_acquisition_number_of_points_minimum(self, value):
value = int(value)
self._acquisition_number_of_points_minimum = value
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_acquisition_record_length(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._acquisition_record_length = float(self._ask("MSIZ?"))
self._set_cache_valid()
return self._acquisition_record_length
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_acquisition_time_per_record(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._acquisition_time_per_record = float(self._ask("TDIV?")) * self._horizontal_divisions
self._set_cache_valid()
return self._acquisition_time_per_record
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_acquisition_time_per_record(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write("TDIV %e" % (value / self._horizontal_divisions))
self._acquisition_time_per_record = value * self._horizontal_divisions
self._set_cache_valid()
self._set_cache_valid(False, 'acquisition_start_time')
# This method implemented differently in WRXIA, not tested with other LeCroy scope
def _get_channel_label(self, index):
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_label[index] = self._ask(":%s:label?" % self._channel_name[index]).strip('"')
self._set_cache_valid(index=index)
return self._channel_label[index]
# This method implemented differently in WRXIA, not tested with other LeCroy scope
def _set_channel_label(self, index, value):
value = str(value)
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate:
self._write(":%s:label \"%s\"" % (self._channel_name[index], value))
self._channel_label[index] = value
self._set_cache_valid(index=index)
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_channel_enabled(self, index):
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
trace = self._ask("%s:TRA?" % self._channel_name[index])
if trace == "ON":
self._channel_enabled[index] = True
elif trace == "OFF":
self._channel_enabled[index] = False
self._set_cache_valid(index=index)
return self._channel_enabled[index]
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_channel_enabled(self, index, value):
value = bool(value)
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate:
if value == False:
self._write("%s:TRA OFF" % self._channel_name[index])
elif value == True:
self._write("%s:TRA ON" % self._channel_name[index])
self._channel_enabled[index] = value
self._set_cache_valid(index=index)
# TODO: test channel.input_impedance
def _get_channel_input_impedance(self, index):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
result = str(self._ask("%s:coupling?" % self._channel_name[index])).lower().split()
result = result[1]
if result == 'a1m':
impedance = 1000000
coupling = "ac"
elif result == "a1m":
impedance = 1000000
coupling = "dc"
elif result == 'd50':
impedance = 50
coupling = "dc"
elif result == 'gnd':
impedance = 1000000
coupling = "gnd"
self._channel_input_impedance[index] = impedance
self._channel_coupling[index] = coupling
self._set_cache_valid(index=index)
return self._channel_input_impedance[index]
# TODO: test channel.input_impedance
def _set_channel_input_impedance(self, index, value):
index = ivi.get_index(self._analog_channel_name, index)
if value not in InputImpedance:
raise Exception('Invalid input impedance selection')
# Check current coupling setting to know if AC or DC
result = str(self._ask("%s:coupling?" % self._channel_name[index])).lower()
if result[0] == "a" and value == 1000000:
coupling = "a1m"
elif result[0] == "a" and value == 50:
raise Exception('Invalid impedance selection')
elif result[0] == "d" and value == 1000000:
coupling = "d1m"
elif result[0] == "d" and value == 50:
coupling = "d50"
elif result == "gnd":
if value == 50:
coupling = "d50"
elif value == 1000000:
coupling = "d1m"
else:
raise Exception('Invalid impedance selection')
if not self._driver_operation_simulate:
self._write("%s:coupling %s" % (self._channel_name[index], coupling.upper()))
self._channel_input_impedance[index] = value
self._set_cache_valid(index=index)
def _get_channel_input_frequency_max(self, index):
index = ivi.get_index(self._analog_channel_name, index)
return self._channel_input_frequency_max[index]
def _set_channel_input_frequency_max(self, index, value):
value = float(value)
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate:
self._set_channel_bw_limit(index, value < 20e6)
self._channel_input_frequency_max[index] = value
self._set_cache_valid(index=index)
# Tested, working on WRX104MXiA
def _get_channel_probe_attenuation(self, index):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_probe_attenuation[index] = int(
(self._ask("%s:attenuation?" % self._channel_name[index])))
self._set_cache_valid(index=index)
return self._channel_probe_attenuation[index]
# TODO: not working yet, can not write the correct value
def _set_channel_probe_attenuation(self, index, value):
"""
<channel> : ATTeNuation <attenuation>
<channel> :={C1,C2,C3,C4,EX,EX10}
<attenuation> : = {1, 2, 5, 10, 20, 25, 50, 100, 200, 500, 1000, 10000}
"""
index = ivi.get_index(self._analog_channel_name, index)
# value = str(value)
if not self._driver_operation_simulate:
self._write("%s:ATTN %e" % (self._channel_name[index], value))
self._channel_probe_attenuation[index] = value
self._set_cache_valid(index=index)
def _get_channel_invert(self, index):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_invert[index] = bool(int(self._ask(":%s:invert?" % self._channel_name[index])))
self._set_cache_valid(index=index)
return self._channel_invert[index]
def _set_channel_invert(self, index, value):
index = ivi.get_index(self._analog_channel_name, index)
value = bool(value)
if not self._driver_operation_simulate:
self._write(":%s:invert %e" % (self._channel_name[index], int(value)))
self._channel_invert[index] = value
self._set_cache_valid(index=index)
def _get_channel_probe_id(self, index):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_probe_id[index] = self._ask(":%s:probe:id?" % self._channel_name[index])
self._set_cache_valid(index=index)
return self._channel_probe_id[index]
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_channel_bw_limit(self, index):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
# On WRXiA bandwidth limits are read out all at one time, we need to split the list to get specified channel
limits = (self._ask("BWL?").strip()).split(',')
if self._channel_name[index] in limits:
self._channel_bw_limit[index] = limits[limits.index(self._channel_name[index]) + 1]
self._set_cache_valid(index=index)
return self._channel_bw_limit[index]
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_channel_bw_limit(self, index, value):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate:
self._write("BWL %s,%s" % (self._channel_name[index], value))
self._channel_bw_limit[index] = value
self._set_cache_valid(index=index)
# TODO: FIX COUPLING AND IMPEDANCE
def _get_channel_coupling(self, index):
index = ivi.get_index(self._analog_channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
result = self._ask("%s:coupling?" % self._channel_name[index]).lower().split()
self._channel_coupling[index] = result[1]
return self._channel_coupling[index]
# TODO: FIX COUPLING AND IMPEDANCE - split coupling from impedance to avoid errors?
def _set_channel_coupling(self, index, value):
index = ivi.get_index(self._analog_channel_name, index)
if value not in VerticalCoupling:
raise ivi.ValueNotSupportedException()
# Check current impedance setting to know if impedance is 1M, 50, or GND
result = str(self._ask("%s:coupling?" % self._channel_name[index])).lower()
if result[1:3] == "1m" or result == "gnd":
if value == "ac":
coupling = "a1m"
elif value == "dc":
coupling = "d1m"
elif result[1:3] == "50" and value == "dc":
coupling = "d50"
elif result[1:3] == "50" and value == "ac":
raise Exception('Invalid coupling selection, set correct impedance')
elif value == "gnd":
coupling = "gnd"
if not self._driver_operation_simulate:
self._write("%s:coupling %s" % (self._channel_name[index], coupling.upper()))
self._channel_coupling[index] = value
self._set_cache_valid(index=index)
# TODO: test
def _get_channel_offset(self, index):
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_offset[index] = float(self._ask("%s:offset?" % self._channel_name[index]))
self._set_cache_valid(index=index)
return self._channel_offset[index]
# TODO: test
def _set_channel_offset(self, index, value):
index = ivi.get_index(self._channel_name, index)
value = float(value)
if not self._driver_operation_simulate:
self._write("%s:offset %e" % (self._channel_name[index], value))
self._channel_offset[index] = value
self._set_cache_valid(index=index)
def _get_channel_range(self, index):
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_range[index] = float(self._ask(":%s:range?" % self._channel_name[index]))
self._channel_scale[index] = self._channel_range[index] / self._vertical_divisions
self._set_cache_valid(index=index)
self._set_cache_valid(True, "channel_scale", index)
return self._channel_range[index]
def _set_channel_range(self, index, value):
index = ivi.get_index(self._channel_name, index)
value = float(value)
if not self._driver_operation_simulate:
self._write(":%s:range %e" % (self._channel_name[index], value))
self._channel_range[index] = value
self._channel_scale[index] = value / self._vertical_divisions
self._set_cache_valid(index=index)
self._set_cache_valid(True, "channel_scale", index)
def _get_channel_scale(self, index):
index = ivi.get_index(self._channel_name, index)
if not self._driver_operation_simulate and not self._get_cache_valid(index=index):
self._channel_scale[index] = float(self._ask(":%s:scale?" % self._channel_name[index]))
self._channel_range[index] = self._channel_scale[index] * self._vertical_divisions
self._set_cache_valid(index=index)
self._set_cache_valid(True, "channel_range", index)
return self._channel_scale[index]
def _set_channel_scale(self, index, value):
index = ivi.get_index(self._channel_name, index)
value = float(value)
if not self._driver_operation_simulate:
self._write(":%s:scale %e" % (self._channel_name[index], value))
self._channel_scale[index] = value
self._channel_range[index] = value * self._vertical_divisions
self._set_cache_valid(index=index)
self._set_cache_valid(True, "channel_range", index)
def _get_measurement_status(self):
return self._measurement_status
def _get_trigger_coupling(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
cpl = self._ask(":trigger:coupling?").lower()
noise = int(self._ask(":trigger:nreject?"))
hf = int(self._ask(":trigger:hfreject?"))
for k in TriggerCouplingMapping:
if (cpl, noise, hf) == TriggerCouplingMapping[k]:
self._trigger_coupling = k
return self._trigger_coupling
def _set_trigger_coupling(self, value):
if value not in TriggerCouplingMapping:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
cpl, noise, hf = TriggerCouplingMapping[value]
self._write(":trigger:coupling %s" % cpl)
self._write(":trigger:nreject %d" % noise)
self._write(":trigger:hfreject %d" % hf)
self._trigger_coupling = value
self._set_cache_valid()
def _get_trigger_holdoff(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._trigger_holdoff = float(self._ask(":trigger:holdoff?"))
self._set_cache_valid()
return self._trigger_holdoff
def _set_trigger_holdoff(self, value):
value = float(value)
if not self._driver_operation_simulate:
self._write(":trigger:holdoff %e" % value)
self._trigger_holdoff = value
self._set_cache_valid()
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_channel_trigger_level(self, index):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._channel_trigger_level[index] = float(self._ask(("%s:TRLV?") % self._channel_name[index]).split(",")[0].split(" ")[0])
self._set_cache_valid()
return self._channel_trigger_level[index]
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_channel_trigger_level(self, index, value):
value = float(value)
if not self._driver_operation_simulate:
self._write("%s:TRLV %e" % (self._channel_name[index], value))
self._channel_trigger_level[index] = value
self._set_cache_valid()
def _get_trigger_edge_slope(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
value = self._ask(":trigger:edge:slope?").lower()
self._trigger_edge_slope = [k for k, v in SlopeMapping.items() if v == value][0]
self._set_cache_valid()
return self._trigger_edge_slope
def _set_trigger_edge_slope(self, value):
if value not in SlopeMapping:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write(":trigger:edge:slope %s" % SlopeMapping[value])
self._trigger_edge_slope = value
self._set_cache_valid()
# To only get the trigger source, the entire TRSE must be read out
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_trigger_source(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
vals = self._ask("TRSE?")
vals = vals.split(",")
#type = vals[0]
source = vals[vals.index('SR')+1]
self._trigger_source = source
self._set_cache_valid()
return self._trigger_source
# To only set the trigger source, the entire TRSE must be read out and then the new trigger source is hacked in
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_trigger_source(self, value):
value = str(value)
if value not in self._channel_name:
raise ivi.UnknownPhysicalNameException()
if not self._driver_operation_simulate:
vals = self._ask("TRSE?")
split_vals = vals.split(",")
split_vals[split_vals.index('SR')+1] = value
vals = ",".join(split_vals)
self._write("TRSE %s" % vals)
self._trigger_source = value
self._set_cache_valid()
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_trigger_mode(self, value):
value = value.lower()
if value not in TriggerModes:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write("TRMD %s" % value.lower())
self._trigger_mode = value
self._set_cache_valid()
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_trigger_mode(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
value = self._ask("TRMD?").lower()
self._trigger_mode = value
self._set_cache_valid()
return self._trigger_mode
# Modified for LeCroy, WORKING ON WR104XI-A
def _get_trigger_type(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
vals = self._ask("TRSE?")
value = vals.split(",")[0]
self._trigger_type = value.lower()
self._set_cache_valid()
return self._trigger_type
# Modified for LeCroy, WORKING ON WR104XI-A
def _set_trigger_type(self, value):
value = value.lower()
if value not in TriggerTypes:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write("TRSE %s" % value)
self._trigger_type = value
self._set_cache_valid()
def _measurement_abort(self):
pass
# def _get_trigger_tv_trigger_event(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = self._ask(":trigger:tv:mode?").lower()
# # may need processing
# self._trigger_tv_trigger_event = [k for k, v in TVTriggerEventMapping.items() if v == value][0]
# self._set_cache_valid()
# return self._trigger_tv_trigger_event
#
# def _set_trigger_tv_trigger_event(self, value):
# if value not in TVTriggerEvent:
# raise ivi.ValueNotSupportedException()
# # may need processing
# if not self._driver_operation_simulate:
# self._write(":trigger:tv:mode %s" % TVTriggerEventMapping[value])
# self._trigger_tv_trigger_event = value
# self._set_cache_valid()
#
# def _get_trigger_tv_line_number(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = int(self._ask(":trigger:tv:line?"))
# # may need processing
# self._trigger_tv_line_number = value
# self._set_cache_valid()
# return self._trigger_tv_line_number
#
# def _set_trigger_tv_line_number(self, value):
# value = int(value)
# # may need processing
# if not self._driver_operation_simulate:
# self._write(":trigger:tv:line %e" % value)
# self._trigger_tv_line_number = value
# self._set_cache_valid()
#
# def _get_trigger_tv_polarity(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = self._ask(":trigger:tv:polarity?").lower()
# self._trigger_tv_polarity = [k for k, v in PolarityMapping.items() if v == value][0]
# self._set_cache_valid()
# return self._trigger_tv_polarity
#
# def _set_trigger_tv_polarity(self, value):
# if value not in PolarityMapping:
# raise ivi.ValueNotSupportedException()
# if not self._driver_operation_simulate:
# self._write(":trigger:tv:polarity %s" % PolarityMapping[value])
# self._trigger_tv_polarity = value
# self._set_cache_valid()
#
# def _get_trigger_tv_signal_format(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = self._ask(":trigger:tv:standard?").lower()
# self._trigger_tv_signal_format = [k for k, v in TVTriggerFormatMapping.items() if v == value][0]
# self._set_cache_valid()
# return self._trigger_tv_signal_format
#
# def _set_trigger_tv_signal_format(self, value):
# if value not in TVTriggerFormatMapping:
# raise ivi.ValueNotSupportedException()
# if not self._driver_operation_simulate:
# self._write(":trigger:tv:standard %s" % TVTriggerFormatMapping[value])
# self._trigger_tv_signal_format = value
# self._set_cache_valid()
#
# def _get_trigger_glitch_condition(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = self._ask(":trigger:glitch:qualifier?").lower()
# if value in GlitchConditionMapping.values():
# self._trigger_glitch_condition = [k for k, v in GlitchConditionMapping.items() if v == value][0]
# self._set_cache_valid()
# return self._trigger_glitch_condition
#
# def _set_trigger_glitch_condition(self, value):
# if value not in GlitchConditionMapping:
# raise ivi.ValueNotSupportedException()
# if not self._driver_operation_simulate:
# self._write(":trigger:glitch:qualifier %s" % GlitchConditionMapping[value])
# self._trigger_glitch_condition = value
# self._set_cache_valid()
#
# def _get_trigger_glitch_polarity(self):
# return self._get_trigger_width_polarity()
#
# def _set_trigger_glitch_polarity(self, value):
# self._set_trigger_width_polarity(value)
#
# def _get_trigger_glitch_width(self):
# if self._get_trigger_glitch_condition() == 'greater_than':
# return self._get_trigger_width_threshold_low()
# else:
# return self._get_trigger_width_threshold_high()
#
# def _set_trigger_glitch_width(self, value):
# if self._get_trigger_glitch_condition() == 'greater_than':
# self._set_trigger_width_threshold_low(value)
# else:
# self._set_trigger_width_threshold_high(value)
#
# def _get_trigger_width_condition(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = self._ask(":trigger:glitch:qualifier?").lower()
# if value in WidthConditionMapping.values():
# self._trigger_width_condition = [k for k, v in WidthConditionMapping.items() if v == value][0]
# self._set_cache_valid()
# return self._trigger_width_condition
#
# def _set_trigger_width_condition(self, value):
# if value not in WidthConditionMapping:
# raise ivi.ValueNotSupportedException()
# if not self._driver_operation_simulate:
# self._write(":trigger:glitch:qualifier %s" % WidthConditionMapping[value])
# self._trigger_width_condition = value
# self._set_cache_valid()
#
# def _get_trigger_width_threshold_high(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# self._trigger_width_threshold_high = float(self._ask(":trigger:glitch:lessthan?"))
# self._set_cache_valid()
# return self._trigger_width_threshold_high
#
# def _set_trigger_width_threshold_high(self, value):
# value = float(value)
# if not self._driver_operation_simulate:
# self._write(":trigger:glitch:lessthan %e" % value)
# self._trigger_width_threshold_high = value
# self._set_cache_valid()
#
# def _get_trigger_width_threshold_low(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# self._trigger_width_threshold_low = float(self._ask(":trigger:glitch:greaterthan?"))
# self._set_cache_valid()
# return self._trigger_width_threshold_low
#
# def _set_trigger_width_threshold_low(self, value):
# value = float(value)
# if not self._driver_operation_simulate:
# self._write(":trigger:glitch:greaterthan %e" % value)
# self._trigger_width_threshold_low = value
# self._set_cache_valid()
#
# def _get_trigger_width_polarity(self):
# if not self._driver_operation_simulate and not self._get_cache_valid():
# value = self._ask(":trigger:glitch:polarity?").lower()
# self._trigger_width_polarity = [k for k, v in PolarityMapping.items() if v == value][0]
# self._set_cache_valid()
# return self._trigger_width_polarity
#
# def _set_trigger_width_polarity(self, value):
# if value not in Polarity:
# raise ivi.ValueNotSupportedException()
# if not self._driver_operation_simulate:
# self._write(":trigger:glitch:polarity %s" % PolarityMapping[value])
# self._trigger_width_polarity = value
# self._set_cache_valid()
#
# def _get_trigger_ac_line_slope(self):
# return self._get_trigger_edge_slope()
#
# def _set_trigger_ac_line_slope(self, value):
# self._set_trigger_edge_slope(value)
# Modified for LeCroy, WORKING ON WR104XI-A
def _measurement_fetch_waveform(self, index):
index = ivi.get_index(self._channel_name, index)
if self._driver_operation_simulate:
return list()
# Send the MSB first
# old - self._write(":waveform:byteorder msbfirst")
self._write("COMM_ORDER HI")
self._write("COMM_FORMAT DEF9,WORD,BIN")
# Read wave description and split up parts into variables
pre = self._ask("%s:INSPECT? WAVEDESC" % self._channel_name[index]).split("\r\n")
# Replace following with a more simple solution, make it < Python 2.7 compatible
temp = []
for item in pre:
temp.append(item.split(':'))
# Dict comprehension, python 2.7+
#mydict = {t[0].strip(): ["".join(elem.strip()) for elem in t[1:]] for t in temp}
#format = str(mydict["COMM_TYPE"][0])
#points = int(mydict["PNTS_PER_SCREEN"][0])
#xincrement = float(mydict["HORIZ_INTERVAL"][0])
#xorigin = float(mydict["HORIZ_OFFSET"][0])
#yincrement = float(mydict["VERTICAL_GAIN"][0])
#yorigin = float(mydict["VERTICAL_OFFSET"][0])
# Dict with lost comprehension, python 2.6+
mydict = dict([(d[0].strip(), "".join(d[1:]).strip()) for d in temp])
format = str(mydict["COMM_TYPE"])
points = int(mydict["PNTS_PER_SCREEN"])
xincrement = float(mydict["HORIZ_INTERVAL"])
xorigin = float(mydict["HORIZ_OFFSET"])
yincrement = float(mydict["VERTICAL_GAIN"])
yorigin = float(mydict["VERTICAL_OFFSET"])
# Verify that the data is in 'word' format
if format.lower() != "word":
raise ivi.UnexpectedResponseException()
# Read waveform data
self._write("%s:WAVEFORM? DAT1" % self._channel_name[index])
raw_data = raw_data = self._read_ieee_block()
# Split out points and convert to time and voltage pairs
data = list()
for i in range(points):
x = (i * xincrement) + xorigin
yval = struct.unpack(">H", raw_data[i * 2:i * 2 + 2])[0]
if yval > 32767:
yval = yval - (2 ** 16)
if yval == 0:
# hole value
y = float('nan')
else:
y = (yincrement * yval) - yorigin
data.append((x, y))
return data
def _measurement_read_waveform(self, index, maximum_time):
return self._measurement_fetch_waveform(index)
def _measurement_initiate(self):
if not self._driver_operation_simulate:
self._write(":acquire:complete 100")
self._write(":digitize")
self._set_cache_valid(False, 'trigger_continuous')
def _get_reference_level_high(self):
return self._reference_level_high
def _set_reference_level_high(self, value):
value = float(value)
if value < 5: value = 5
if value > 95: value = 95
self._reference_level_high = value
if not self._driver_operation_simulate:
self._write(":measure:define thresholds, %e, %e, %e" %
(self._reference_level_high,
self._reference_level_middle,
self._reference_level_low))
def _get_reference_level_low(self):
return self._reference_level_low
def _set_reference_level_low(self, value):
value = float(value)
if value < 5: value = 5
if value > 95: value = 95
self._reference_level_low = value
if not self._driver_operation_simulate:
self._write(":measure:define thresholds, %e, %e, %e" %
(self._reference_level_high,
self._reference_level_middle,
self._reference_level_low))
def _get_reference_level_middle(self):
return self._reference_level_middle
def _set_reference_level_middle(self, value):
value = float(value)
if value < 5: value = 5
if value > 95: value = 95
self._reference_level_middle = value
if not self._driver_operation_simulate:
self._write(":measure:define thresholds, %e, %e, %e" %
(self._reference_level_high,
self._reference_level_middle,
self._reference_level_low))
def _measurement_fetch_waveform_measurement(self, index, measurement_function, ref_channel=None):
index = ivi.get_index(self._channel_name, index)
if index < self._analog_channel_count:
if measurement_function not in MeasurementFunctionMapping:
raise ivi.ValueNotSupportedException()
func = MeasurementFunctionMapping[measurement_function]
else:
if measurement_function not in MeasurementFunctionMappingDigital:
raise ivi.ValueNotSupportedException()
func = MeasurementFunctionMappingDigital[measurement_function]
if not self._driver_operation_simulate:
l = func.split(' ')
l[0] = l[0] + '?'
if len(l) > 1:
l[-1] = l[-1] + ','
func = ' '.join(l)
query = ":measure:%s %s" % (func, self._channel_name[index])
if measurement_function in ['ratio', 'phase', 'delay']:
ref_index = ivi.get_index(self._channel_name, ref_channel)
query += ", %s" % self._channel_name[ref_index]
return float(self._ask(query))
return 0
def _measurement_read_waveform_measurement(self, index, measurement_function, maximum_time):
return self._measurement_fetch_waveform_measurement(index, measurement_function)
def _get_acquisition_number_of_envelopes(self):
return self._acquisition_number_of_envelopes
def _set_acquisition_number_of_envelopes(self, value):
self._acquisition_number_of_envelopes = value
def _measurement_fetch_waveform_min_max(self, index):
index = ivi.get_index(self._channel_name, index)
data = list()
return data
def _measurement_read_waveform_min_max(self, index, maximum_time):
return _measurement_fetch_waveform_min_max(index)
def _get_trigger_continuous(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._trigger_continuous = (int(self._ask(":oper:cond?")) & 1 << 3) != 0
self._set_cache_valid()
return self._trigger_continuous
def _set_trigger_continuous(self, value):
value = bool(value)
if not self._driver_operation_simulate:
t = 'stop'
if value: t = 'run'
self._write(":%s" % t)
self._trigger_continuous = value
self._set_cache_valid()
def _get_acquisition_number_of_averages(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
self._acquisition_number_of_averages = int(self._ask(":acquire:count?"))
self._set_cache_valid()
return self._acquisition_number_of_averages
def _set_acquisition_number_of_averages(self, value):
if value < 1 or value > 65536:
raise ivi.OutOfRangeException()
if not self._driver_operation_simulate:
self._write(":acquire:count %d" % value)
self._acquisition_number_of_averages = value
self._set_cache_valid()
def _get_acquisition_sample_mode(self):
if not self._driver_operation_simulate and not self._get_cache_valid():
value = self._ask(":acquire:mode?").lower()
self._acquisition_sample_mode = [k for k, v in SampleModeMapping.items() if v == value][0]
self._set_cache_valid()
return self._acquisition_sample_mode
def _set_acquisition_sample_mode(self, value):
if value not in SampleModeMapping:
raise ivi.ValueNotSupportedException()
if not self._driver_operation_simulate:
self._write(":acquire:mode %s" % SampleModeMapping[value])
self._acquisition_sample_mode = value
self._set_cache_valid()
# Not changed
def _measurement_auto_setup(self):
if not self._driver_operation_simulate:
self._write("ASET")
# WORKING ON WR104XI-A
def _memory_save(self, index):
index = int(index)
if index < 0 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*sav %d" % index)
# WORKING ON WR104XI-A
def _memory_recall(self, index):
index = int(index)
if index < 0 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*rcl %d" % index)
self.driver_operation.invalidate_all_attributes()<|fim▁end|> | None,
ivi.Doc("""
Sets the current grid used in the display. There are multiple grid modes. |
<|file_name|>ioport.rs<|end_file_name|><|fim▁begin|>// Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by<|fim▁hole|>// 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 Genesis. If not, see <http://www.gnu.org/licenses/>.
pub unsafe fn out<T>(port: u16, val: T) {
asm!("out $0, $1"
: // no output
: "{al}" (val), "{dx}" (port)
: // no clobber
: "volatile");
}
pub unsafe fn inb(port: u16) -> u8 {
let val: u8;
asm!("in $1, $0"
: "={al}" (val)
: "{dx}" (port)
: // no clobber
: "volatile");
val
}<|fim▁end|> | // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Genesis is distributed in the hope that it will be useful, |
<|file_name|>WsdlGeneratorPipe.java<|end_file_name|><|fim▁begin|>/*
Copyright 2016, 2020 Nationale-Nederlanden, 2020-2021 WeAreFrank!
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 nl.nn.adapterframework.pipes;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.Adapter;
import nl.nn.adapterframework.core.PipeLineSession;
import nl.nn.adapterframework.core.PipeRunException;
import nl.nn.adapterframework.core.PipeRunResult;
import nl.nn.adapterframework.doc.IbisDoc;
import nl.nn.adapterframework.http.RestListenerUtils;
import nl.nn.adapterframework.soap.WsdlGenerator;
import nl.nn.adapterframework.stream.Message;
import nl.nn.adapterframework.util.StreamUtil;
/**
* Generate WSDL of parent or specified adapter.
*
* @author Jaco de Groot
*/
public class WsdlGeneratorPipe extends FixedForwardPipe {
private String from = "parent";<|fim▁hole|> @Override
public void configure() throws ConfigurationException {
super.configure();
if (!"parent".equals(getFrom()) && !"input".equals(getFrom())) {
throw new ConfigurationException("from should either be parent or input");
}
}
@Override
public PipeRunResult doPipe(Message message, PipeLineSession session) throws PipeRunException {
String result = null;
Adapter adapter;
try {
if ("input".equals(getFrom())) {
String adapterName = message.asString();
adapter = getAdapter().getConfiguration().getIbisManager().getRegisteredAdapter(adapterName);
if (adapter == null) {
throw new PipeRunException(this, "Could not find adapter: " + adapterName);
}
} else {
adapter = getPipeLine().getAdapter();
}
} catch (IOException e) {
throw new PipeRunException(this, "Could not determine adapter name", e);
}
try {
String generationInfo = "at " + RestListenerUtils.retrieveRequestURL(session);
WsdlGenerator wsdl = new WsdlGenerator(adapter.getPipeLine(), generationInfo);
wsdl.init();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wsdl.wsdl(outputStream, null);
result = outputStream.toString(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING);
} catch (Exception e) {
throw new PipeRunException(this, "Could not generate WSDL for adapter [" + adapter.getName() + "]", e);
}
return new PipeRunResult(getSuccessForward(), result);
}
public String getFrom() {
return from;
}
@IbisDoc({"either parent (adapter of pipeline which contains this pipe) or input (name of adapter specified by input of pipe)", "parent"})
public void setFrom(String from) {
this.from = from;
}
}<|fim▁end|> | |
<|file_name|>stub_activity.rs<|end_file_name|><|fim▁begin|>// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma version(1)
// Tell which java package name the reflected files should belong to<|fim▁hole|>// Built-in header with graphics API's
#include "rs_graphics.rsh"
int root(void) {
// Clear the background color
rsgClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// Tell the runtime what the font color should be
rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
// Introuduce ourselves to the world
rsgDrawText("Hello World!", 50, 50);
// Return value tells RS roughly how often to redraw
// in this case 20 ms
return 20;
}<|fim▁end|> | #pragma rs java_package_name(android.renderscript.cts)
|
<|file_name|>ct04.cpp<|end_file_name|><|fim▁begin|>/* 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.
*
*/
#include "bladerunner/script/scene_script.h"
namespace BladeRunner {
enum kCT04Loops {
kCT04LoopInshot = 0,
kCT04LoopMainLoop = 1
};
void SceneScriptCT04::InitializeScene() {
if (Game_Flag_Query(kFlagCT03toCT04)) {
Scene_Loop_Start_Special(kSceneLoopModeLoseControl, kCT04LoopInshot, false);
Scene_Loop_Set_Default(kCT04LoopMainLoop);
Setup_Scene_Information(-150.0f, -621.3f, 357.0f, 533);
} else {
Scene_Loop_Set_Default(kCT04LoopMainLoop);
Setup_Scene_Information(-82.86f, -621.3f, 769.03f, 1020);
}
Scene_Exit_Add_2D_Exit(0, 590, 0, 639, 479, 1);
Scene_Exit_Add_2D_Exit(1, 194, 84, 320, 274, 0);
if (_vm->_cutContent) {
Scene_Exit_Add_2D_Exit(2, 0, 440, 590, 479, 2);
}
Ambient_Sounds_Add_Looping_Sound(kSfxCTRAIN1, 50, 1, 1);
Ambient_Sounds_Add_Looping_Sound(kSfxCTAMBR1, 15, -100, 1);
Ambient_Sounds_Add_Looping_Sound(kSfxCTRUNOFF, 34, 100, 1);
Ambient_Sounds_Add_Sound(kSfxSPIN2B, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0);
Ambient_Sounds_Add_Sound(kSfxSPIN3A, 10, 40, 33, 50, 0, 0, -101, -101, 0, 0);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 0, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 20, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 40, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Speech_Sound(kActorBlimpGuy, 50, 10, 260, 17, 24, -100, 100, -101, -101, 1, 1);
Ambient_Sounds_Add_Sound(kSfxTHNDER3, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0);
Ambient_Sounds_Add_Sound(kSfxTHNDER4, 10, 60, 33, 50, -100, 100, -101, -101, 0, 0);
}
void SceneScriptCT04::SceneLoaded() {
Obstacle_Object("DUMPSTER", true);
Obstacle_Object("RIGHTWALL01", true);
Obstacle_Object("BACK-BLDNG", true);
Clickable_Object("DUMPSTER");
Footstep_Sounds_Set(0, 1);
if (Game_Flag_Query(kFlagCT03toCT04)) {
Game_Flag_Reset(kFlagCT03toCT04);
}
if (Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault) {
Actor_Change_Animation_Mode(kActorTransient, 38);
}
}
bool SceneScriptCT04::MouseClick(int x, int y) {
return false;
}
bool SceneScriptCT04::ClickedOn3DObject(const char *objectName, bool a2) {
if (objectName) { // this can be only "DUMPSTER"
if (!Game_Flag_Query(kFlagCT04HomelessTalk)
&& !Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)
&& Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault
) {
Game_Flag_Set(kFlagCT04HomelessTalk);
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
if ( Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)
&& !Game_Flag_Query(kFlagCT04HomelessBodyInDumpster)
&& !Game_Flag_Query(kFlagCT04HomelessBodyFound)
&& !Game_Flag_Query(kFlagCT04HomelessBodyThrownAway)
&& Global_Variable_Query(kVariableChapter) == 1
) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -147.41f, -621.3f, 724.57f, 0, true, false, false)) {
Player_Loses_Control();
Actor_Face_Heading(kActorMcCoy, 792, false);
Actor_Put_In_Set(kActorTransient, kSetFreeSlotI);
Actor_Set_At_XYZ(kActorTransient, 0, 0, 0, 0);
Actor_Change_Animation_Mode(kActorMcCoy, 40);
Actor_Voice_Over(320, kActorVoiceOver);
Actor_Voice_Over(330, kActorVoiceOver);
Actor_Voice_Over(340, kActorVoiceOver);
Game_Flag_Set(kFlagCT04HomelessBodyInDumpster);
Game_Flag_Set(kFlagCT04HomelessBodyInDumpsterNotChecked);
}
return false;
}
if (Game_Flag_Query(kFlagCT04HomelessBodyInDumpster)) {
if (Game_Flag_Query(kFlagCT04HomelessBodyThrownAway)) {
Actor_Voice_Over(270, kActorVoiceOver);
Actor_Voice_Over(280, kActorVoiceOver);
} else if (Game_Flag_Query(kFlagCT04HomelessBodyFound)) {
Actor_Voice_Over(250, kActorVoiceOver);
Actor_Voice_Over(260, kActorVoiceOver);
} else {
Actor_Voice_Over(230, kActorVoiceOver);
Actor_Voice_Over(240, kActorVoiceOver);
Game_Flag_Reset(kFlagCT04HomelessBodyInDumpsterNotChecked);
}
return true;
}
if (!Game_Flag_Query(kFlagCT04LicensePlaceFound)) {
if (!Loop_Actor_Walk_To_Waypoint(kActorMcCoy, 75, 0, true, false)) {
Actor_Face_Heading(kActorMcCoy, 707, false);
Actor_Change_Animation_Mode(kActorMcCoy, 38);
Actor_Clue_Acquire(kActorMcCoy, kClueLicensePlate, true, -1);
Item_Pickup_Spin_Effect(kModelAnimationLicensePlate, 392, 225);
Game_Flag_Set(kFlagCT04LicensePlaceFound);
return true;
}
}
if (!Loop_Actor_Walk_To_Waypoint(kActorMcCoy, 75, 0, true, false)) {
Actor_Face_Heading(kActorMcCoy, 707, false);
Actor_Change_Animation_Mode(kActorMcCoy, 38);
Ambient_Sounds_Play_Sound(kSfxGARBAGE, 45, 30, 30, 0);
Actor_Voice_Over(1810, kActorVoiceOver);
Actor_Voice_Over(1820, kActorVoiceOver);
return true;
}
}
return false;
}
void SceneScriptCT04::dialogueWithHomeless() {
Dialogue_Menu_Clear_List();
if (Global_Variable_Query(kVariableChinyen) > 10
|| Query_Difficulty_Level() == kGameDifficultyEasy
) {
DM_Add_To_List_Never_Repeat_Once_Selected(410, 8, 4, -1); // YES
}
DM_Add_To_List_Never_Repeat_Once_Selected(420, 2, 6, 8); // NO
Dialogue_Menu_Appear(320, 240);
int answer = Dialogue_Menu_Query_Input();
Dialogue_Menu_Disappear();
switch (answer) {
case 410: // YES
Actor_Says(kActorTransient, 10, 14); // Thanks. The big man. He kind of limping.
Actor_Says(kActorTransient, 20, 14); // That way.
Actor_Modify_Friendliness_To_Other(kActorTransient, kActorMcCoy, 5);
if (Query_Difficulty_Level() != kGameDifficultyEasy) {
Global_Variable_Decrement(kVariableChinyen, 10);
}
break;
case 420: // NO
Actor_Says(kActorMcCoy, 430, 3);
Actor_Says(kActorTransient, 30, 14); // Hey, that'd work.
Actor_Modify_Friendliness_To_Other(kActorTransient, kActorMcCoy, -5);
break;
}
}
bool SceneScriptCT04::ClickedOnActor(int actorId) {
if (actorId == kActorTransient) {
if (Game_Flag_Query(kFlagCT04HomelessKilledByMcCoy)) {
if (!Loop_Actor_Walk_To_Actor(kActorMcCoy, kActorTransient, 36, true, false)) {
Actor_Voice_Over(290, kActorVoiceOver);
Actor_Voice_Over(300, kActorVoiceOver);
Actor_Voice_Over(310, kActorVoiceOver);
}
} else {
Actor_Set_Targetable(kActorTransient, false);
if (!Loop_Actor_Walk_To_Actor(kActorMcCoy, kActorTransient, 36, true, false)) {
Actor_Face_Actor(kActorMcCoy, kActorTransient, true);
if (!Game_Flag_Query(kFlagCT04HomelessTalk)) {
if (Game_Flag_Query(kFlagZubenRetired)) {
Actor_Says(kActorMcCoy, 435, kAnimationModeTalk);
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
} else {
Music_Stop(3);
Actor_Says(kActorMcCoy, 425, kAnimationModeTalk);
Actor_Says(kActorTransient, 0, 13); // Hey, maybe spare some chinyen?
dialogueWithHomeless();
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
Game_Flag_Set(kFlagCT04HomelessTalk);
} else {
Actor_Face_Actor(kActorMcCoy, kActorTransient, true);
Actor_Says(kActorMcCoy, 435, kAnimationModeTalk);
}<|fim▁hole|> return true;
}
return false;
}
bool SceneScriptCT04::ClickedOnItem(int itemId, bool a2) {
return false;
}
bool SceneScriptCT04::ClickedOnExit(int exitId) {
if (exitId == 1) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -82.86f, -621.3f, 769.03f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
if (Actor_Query_Goal_Number(kActorTransient) == kGoalTransientDefault) {
Actor_Set_Goal_Number(kActorTransient, kGoalTransientCT04Leave);
}
Game_Flag_Set(kFlagCT04toCT05);
Set_Enter(kSetCT05, kSceneCT05);
}
return true;
}
if (exitId == 0) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -187.0f, -621.3f, 437.0f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
Game_Flag_Set(kFlagCT04toCT03);
Set_Enter(kSetCT03_CT04, kSceneCT03);
}
return true;
}
if (_vm->_cutContent) {
if (exitId == 2) {
if (!Loop_Actor_Walk_To_XYZ(kActorMcCoy, -106.94f, -619.08f, 429.20f, 0, true, false, false)) {
Ambient_Sounds_Remove_All_Non_Looping_Sounds(true);
Ambient_Sounds_Remove_All_Looping_Sounds(1);
Game_Flag_Set(kFlagCT04toCT03);
Set_Enter(kSetCT03_CT04, kSceneCT03);
}
return true;
}
}
return false;
}
bool SceneScriptCT04::ClickedOn2DRegion(int region) {
return false;
}
void SceneScriptCT04::SceneFrameAdvanced(int frame) {
if (Game_Flag_Query(kFlagCT04BodyDumped)) {
Game_Flag_Reset(kFlagCT04BodyDumped);
Sound_Play(kSfxGARBAGE4, 100, 80, 80, 50);
}
}
void SceneScriptCT04::ActorChangedGoal(int actorId, int newGoal, int oldGoal, bool currentSet) {
}
void SceneScriptCT04::PlayerWalkedIn() {
}
void SceneScriptCT04::PlayerWalkedOut() {
}
void SceneScriptCT04::DialogueQueueFlushed(int a1) {
}
} // End of namespace BladeRunner<|fim▁end|> | }
} |
<|file_name|>SpellEffects.cpp<|end_file_name|><|fim▁begin|>/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Spell.h"
#include "AccountMgr.h"
#include "Battleground.h"
#include "CellImpl.h"
#include "Common.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "DatabaseEnv.h"
#include "DynamicObject.h"
#include "Formulas.h"
#include "GameObject.h"
#include "GameObjectAI.h"
#include "GossipDef.h"
#include "GridNotifiers.h"
#include "InstanceScript.h"
#include "Item.h"
#include "Language.h"
#include "Log.h"
#include "LootMgr.h"
#include "MiscPackets.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "OutdoorPvPMgr.h"
#include "PathGenerator.h"
#include "Pet.h"
#include "Player.h"
#include "ReputationMgr.h"
#ifdef ELUNA
#include "LuaEngine.h"
#endif
#include "ScriptMgr.h"
#include "SkillExtraItems.h"
#include "SharedDefines.h"
#include "SocialMgr.h"
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "SpellHistory.h"
#include "SpellMgr.h"
#include "TemporarySummon.h"
#include "Totem.h"
#include "UpdateMask.h"
#include "Unit.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
SpellEffectHandlerFn SpellEffectHandlers[TOTAL_SPELL_EFFECTS] =
{
&Spell::EffectNULL, // 0
&Spell::EffectInstaKill, // 1 SPELL_EFFECT_INSTAKILL
&Spell::EffectSchoolDMG, // 2 SPELL_EFFECT_SCHOOL_DAMAGE
&Spell::EffectDummy, // 3 SPELL_EFFECT_DUMMY
&Spell::EffectUnused, // 4 SPELL_EFFECT_PORTAL_TELEPORT unused
&Spell::EffectTeleportUnits, // 5 SPELL_EFFECT_TELEPORT_UNITS
&Spell::EffectApplyAura, // 6 SPELL_EFFECT_APPLY_AURA
&Spell::EffectEnvironmentalDMG, // 7 SPELL_EFFECT_ENVIRONMENTAL_DAMAGE
&Spell::EffectPowerDrain, // 8 SPELL_EFFECT_POWER_DRAIN
&Spell::EffectHealthLeech, // 9 SPELL_EFFECT_HEALTH_LEECH
&Spell::EffectHeal, // 10 SPELL_EFFECT_HEAL
&Spell::EffectBind, // 11 SPELL_EFFECT_BIND
&Spell::EffectNULL, // 12 SPELL_EFFECT_PORTAL
&Spell::EffectUnused, // 13 SPELL_EFFECT_RITUAL_BASE unused
&Spell::EffectUnused, // 14 SPELL_EFFECT_RITUAL_SPECIALIZE unused
&Spell::EffectUnused, // 15 SPELL_EFFECT_RITUAL_ACTIVATE_PORTAL unused
&Spell::EffectQuestComplete, // 16 SPELL_EFFECT_QUEST_COMPLETE
&Spell::EffectWeaponDmg, // 17 SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL
&Spell::EffectResurrect, // 18 SPELL_EFFECT_RESURRECT
&Spell::EffectAddExtraAttacks, // 19 SPELL_EFFECT_ADD_EXTRA_ATTACKS
&Spell::EffectUnused, // 20 SPELL_EFFECT_DODGE one spell: Dodge
&Spell::EffectUnused, // 21 SPELL_EFFECT_EVADE one spell: Evade (DND)
&Spell::EffectParry, // 22 SPELL_EFFECT_PARRY
&Spell::EffectBlock, // 23 SPELL_EFFECT_BLOCK one spell: Block
&Spell::EffectCreateItem, // 24 SPELL_EFFECT_CREATE_ITEM
&Spell::EffectUnused, // 25 SPELL_EFFECT_WEAPON
&Spell::EffectUnused, // 26 SPELL_EFFECT_DEFENSE one spell: Defense
&Spell::EffectPersistentAA, // 27 SPELL_EFFECT_PERSISTENT_AREA_AURA
&Spell::EffectSummonType, // 28 SPELL_EFFECT_SUMMON
&Spell::EffectLeap, // 29 SPELL_EFFECT_LEAP
&Spell::EffectEnergize, // 30 SPELL_EFFECT_ENERGIZE
&Spell::EffectWeaponDmg, // 31 SPELL_EFFECT_WEAPON_PERCENT_DAMAGE
&Spell::EffectTriggerMissileSpell, // 32 SPELL_EFFECT_TRIGGER_MISSILE
&Spell::EffectOpenLock, // 33 SPELL_EFFECT_OPEN_LOCK
&Spell::EffectSummonChangeItem, // 34 SPELL_EFFECT_SUMMON_CHANGE_ITEM
&Spell::EffectUnused, // 35 SPELL_EFFECT_APPLY_AREA_AURA_PARTY
&Spell::EffectLearnSpell, // 36 SPELL_EFFECT_LEARN_SPELL
&Spell::EffectUnused, // 37 SPELL_EFFECT_SPELL_DEFENSE one spell: SPELLDEFENSE (DND)
&Spell::EffectDispel, // 38 SPELL_EFFECT_DISPEL
&Spell::EffectUnused, // 39 SPELL_EFFECT_LANGUAGE
&Spell::EffectDualWield, // 40 SPELL_EFFECT_DUAL_WIELD
&Spell::EffectJump, // 41 SPELL_EFFECT_JUMP
&Spell::EffectJumpDest, // 42 SPELL_EFFECT_JUMP_DEST
&Spell::EffectTeleUnitsFaceCaster, // 43 SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER
&Spell::EffectLearnSkill, // 44 SPELL_EFFECT_SKILL_STEP
&Spell::EffectAddHonor, // 45 SPELL_EFFECT_ADD_HONOR honor/pvp related
&Spell::EffectUnused, // 46 SPELL_EFFECT_SPAWN clientside, unit appears as if it was just spawned
&Spell::EffectTradeSkill, // 47 SPELL_EFFECT_TRADE_SKILL
&Spell::EffectUnused, // 48 SPELL_EFFECT_STEALTH one spell: Base Stealth
&Spell::EffectUnused, // 49 SPELL_EFFECT_DETECT one spell: Detect
&Spell::EffectTransmitted, // 50 SPELL_EFFECT_TRANS_DOOR
&Spell::EffectUnused, // 51 SPELL_EFFECT_FORCE_CRITICAL_HIT unused
&Spell::EffectUnused, // 52 SPELL_EFFECT_GUARANTEE_HIT one spell: zzOLDCritical Shot
&Spell::EffectEnchantItemPerm, // 53 SPELL_EFFECT_ENCHANT_ITEM
&Spell::EffectEnchantItemTmp, // 54 SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY
&Spell::EffectTameCreature, // 55 SPELL_EFFECT_TAMECREATURE
&Spell::EffectSummonPet, // 56 SPELL_EFFECT_SUMMON_PET
&Spell::EffectLearnPetSpell, // 57 SPELL_EFFECT_LEARN_PET_SPELL
&Spell::EffectWeaponDmg, // 58 SPELL_EFFECT_WEAPON_DAMAGE
&Spell::EffectCreateRandomItem, // 59 SPELL_EFFECT_CREATE_RANDOM_ITEM create item base at spell specific loot
&Spell::EffectProficiency, // 60 SPELL_EFFECT_PROFICIENCY
&Spell::EffectSendEvent, // 61 SPELL_EFFECT_SEND_EVENT
&Spell::EffectPowerBurn, // 62 SPELL_EFFECT_POWER_BURN
&Spell::EffectThreat, // 63 SPELL_EFFECT_THREAT
&Spell::EffectTriggerSpell, // 64 SPELL_EFFECT_TRIGGER_SPELL
&Spell::EffectUnused, // 65 SPELL_EFFECT_APPLY_AREA_AURA_RAID
&Spell::EffectRechargeManaGem, // 66 SPELL_EFFECT_CREATE_MANA_GEM (possibly recharge it, misc - is item ID)
&Spell::EffectHealMaxHealth, // 67 SPELL_EFFECT_HEAL_MAX_HEALTH
&Spell::EffectInterruptCast, // 68 SPELL_EFFECT_INTERRUPT_CAST
&Spell::EffectDistract, // 69 SPELL_EFFECT_DISTRACT
&Spell::EffectPull, // 70 SPELL_EFFECT_PULL one spell: Distract Move
&Spell::EffectPickPocket, // 71 SPELL_EFFECT_PICKPOCKET
&Spell::EffectAddFarsight, // 72 SPELL_EFFECT_ADD_FARSIGHT
&Spell::EffectUntrainTalents, // 73 SPELL_EFFECT_UNTRAIN_TALENTS
&Spell::EffectApplyGlyph, // 74 SPELL_EFFECT_APPLY_GLYPH
&Spell::EffectHealMechanical, // 75 SPELL_EFFECT_HEAL_MECHANICAL one spell: Mechanical Patch Kit
&Spell::EffectSummonObjectWild, // 76 SPELL_EFFECT_SUMMON_OBJECT_WILD
&Spell::EffectScriptEffect, // 77 SPELL_EFFECT_SCRIPT_EFFECT
&Spell::EffectUnused, // 78 SPELL_EFFECT_ATTACK
&Spell::EffectSanctuary, // 79 SPELL_EFFECT_SANCTUARY
&Spell::EffectAddComboPoints, // 80 SPELL_EFFECT_ADD_COMBO_POINTS
&Spell::EffectUnused, // 81 SPELL_EFFECT_CREATE_HOUSE one spell: Create House (TEST)
&Spell::EffectNULL, // 82 SPELL_EFFECT_BIND_SIGHT
&Spell::EffectDuel, // 83 SPELL_EFFECT_DUEL
&Spell::EffectStuck, // 84 SPELL_EFFECT_STUCK
&Spell::EffectSummonPlayer, // 85 SPELL_EFFECT_SUMMON_PLAYER
&Spell::EffectActivateObject, // 86 SPELL_EFFECT_ACTIVATE_OBJECT
&Spell::EffectGameObjectDamage, // 87 SPELL_EFFECT_GAMEOBJECT_DAMAGE
&Spell::EffectGameObjectRepair, // 88 SPELL_EFFECT_GAMEOBJECT_REPAIR
&Spell::EffectGameObjectSetDestructionState, // 89 SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE
&Spell::EffectKillCreditPersonal, // 90 SPELL_EFFECT_KILL_CREDIT Kill credit but only for single person
&Spell::EffectUnused, // 91 SPELL_EFFECT_THREAT_ALL one spell: zzOLDBrainwash
&Spell::EffectEnchantHeldItem, // 92 SPELL_EFFECT_ENCHANT_HELD_ITEM
&Spell::EffectForceDeselect, // 93 SPELL_EFFECT_FORCE_DESELECT
&Spell::EffectSelfResurrect, // 94 SPELL_EFFECT_SELF_RESURRECT
&Spell::EffectSkinning, // 95 SPELL_EFFECT_SKINNING
&Spell::EffectCharge, // 96 SPELL_EFFECT_CHARGE
&Spell::EffectCastButtons, // 97 SPELL_EFFECT_CAST_BUTTON (totem bar since 3.2.2a)
&Spell::EffectKnockBack, // 98 SPELL_EFFECT_KNOCK_BACK
&Spell::EffectDisEnchant, // 99 SPELL_EFFECT_DISENCHANT
&Spell::EffectInebriate, //100 SPELL_EFFECT_INEBRIATE
&Spell::EffectFeedPet, //101 SPELL_EFFECT_FEED_PET
&Spell::EffectDismissPet, //102 SPELL_EFFECT_DISMISS_PET
&Spell::EffectReputation, //103 SPELL_EFFECT_REPUTATION
&Spell::EffectSummonObject, //104 SPELL_EFFECT_SUMMON_OBJECT_SLOT1
&Spell::EffectSummonObject, //105 SPELL_EFFECT_SUMMON_OBJECT_SLOT2
&Spell::EffectSummonObject, //106 SPELL_EFFECT_SUMMON_OBJECT_SLOT3
&Spell::EffectSummonObject, //107 SPELL_EFFECT_SUMMON_OBJECT_SLOT4
&Spell::EffectDispelMechanic, //108 SPELL_EFFECT_DISPEL_MECHANIC
&Spell::EffectResurrectPet, //109 SPELL_EFFECT_RESURRECT_PET
&Spell::EffectDestroyAllTotems, //110 SPELL_EFFECT_DESTROY_ALL_TOTEMS
&Spell::EffectDurabilityDamage, //111 SPELL_EFFECT_DURABILITY_DAMAGE
&Spell::EffectUnused, //112 SPELL_EFFECT_112
&Spell::EffectResurrectNew, //113 SPELL_EFFECT_RESURRECT_NEW
&Spell::EffectTaunt, //114 SPELL_EFFECT_ATTACK_ME
&Spell::EffectDurabilityDamagePCT, //115 SPELL_EFFECT_DURABILITY_DAMAGE_PCT
&Spell::EffectSkinPlayerCorpse, //116 SPELL_EFFECT_SKIN_PLAYER_CORPSE one spell: Remove Insignia, bg usage, required special corpse flags...
&Spell::EffectSpiritHeal, //117 SPELL_EFFECT_SPIRIT_HEAL one spell: Spirit Heal
&Spell::EffectSkill, //118 SPELL_EFFECT_SKILL professions and more
&Spell::EffectUnused, //119 SPELL_EFFECT_APPLY_AREA_AURA_PET
&Spell::EffectUnused, //120 SPELL_EFFECT_TELEPORT_GRAVEYARD one spell: Graveyard Teleport Test
&Spell::EffectWeaponDmg, //121 SPELL_EFFECT_NORMALIZED_WEAPON_DMG
&Spell::EffectUnused, //122 SPELL_EFFECT_122 unused
&Spell::EffectSendTaxi, //123 SPELL_EFFECT_SEND_TAXI taxi/flight related (misc value is taxi path id)
&Spell::EffectPullTowards, //124 SPELL_EFFECT_PULL_TOWARDS
&Spell::EffectModifyThreatPercent, //125 SPELL_EFFECT_MODIFY_THREAT_PERCENT
&Spell::EffectStealBeneficialBuff, //126 SPELL_EFFECT_STEAL_BENEFICIAL_BUFF spell steal effect?
&Spell::EffectProspecting, //127 SPELL_EFFECT_PROSPECTING Prospecting spell
&Spell::EffectUnused, //128 SPELL_EFFECT_APPLY_AREA_AURA_FRIEND
&Spell::EffectUnused, //129 SPELL_EFFECT_APPLY_AREA_AURA_ENEMY
&Spell::EffectRedirectThreat, //130 SPELL_EFFECT_REDIRECT_THREAT
&Spell::EffectPlaySound, //131 SPELL_EFFECT_PLAY_SOUND sound id in misc value (SoundEntries.dbc)
&Spell::EffectPlayMusic, //132 SPELL_EFFECT_PLAY_MUSIC sound id in misc value (SoundEntries.dbc)
&Spell::EffectUnlearnSpecialization, //133 SPELL_EFFECT_UNLEARN_SPECIALIZATION unlearn profession specialization
&Spell::EffectKillCredit, //134 SPELL_EFFECT_KILL_CREDIT misc value is creature entry
&Spell::EffectNULL, //135 SPELL_EFFECT_CALL_PET
&Spell::EffectHealPct, //136 SPELL_EFFECT_HEAL_PCT
&Spell::EffectEnergizePct, //137 SPELL_EFFECT_ENERGIZE_PCT
&Spell::EffectLeapBack, //138 SPELL_EFFECT_LEAP_BACK Leap back
&Spell::EffectQuestClear, //139 SPELL_EFFECT_CLEAR_QUEST Reset quest status (miscValue - quest ID)
&Spell::EffectForceCast, //140 SPELL_EFFECT_FORCE_CAST
&Spell::EffectForceCast, //141 SPELL_EFFECT_FORCE_CAST_WITH_VALUE
&Spell::EffectTriggerSpell, //142 SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE
&Spell::EffectUnused, //143 SPELL_EFFECT_APPLY_AREA_AURA_OWNER
&Spell::EffectKnockBack, //144 SPELL_EFFECT_KNOCK_BACK_DEST
&Spell::EffectPullTowardsDest, //145 SPELL_EFFECT_PULL_TOWARDS_DEST Black Hole Effect
&Spell::EffectActivateRune, //146 SPELL_EFFECT_ACTIVATE_RUNE
&Spell::EffectQuestFail, //147 SPELL_EFFECT_QUEST_FAIL quest fail
&Spell::EffectTriggerMissileSpell, //148 SPELL_EFFECT_TRIGGER_MISSILE_SPELL_WITH_VALUE
&Spell::EffectChargeDest, //149 SPELL_EFFECT_CHARGE_DEST
&Spell::EffectQuestStart, //150 SPELL_EFFECT_QUEST_START
&Spell::EffectTriggerRitualOfSummoning, //151 SPELL_EFFECT_TRIGGER_SPELL_2
&Spell::EffectSummonRaFFriend, //152 SPELL_EFFECT_SUMMON_RAF_FRIEND summon Refer-a-Friend
&Spell::EffectCreateTamedPet, //153 SPELL_EFFECT_CREATE_TAMED_PET misc value is creature entry
&Spell::EffectDiscoverTaxi, //154 SPELL_EFFECT_DISCOVER_TAXI
&Spell::EffectTitanGrip, //155 SPELL_EFFECT_TITAN_GRIP Allows you to equip two-handed axes, maces and swords in one hand, but you attack $49152s1% slower than normal.
&Spell::EffectEnchantItemPrismatic, //156 SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC
&Spell::EffectCreateItem2, //157 SPELL_EFFECT_CREATE_ITEM_2 create item or create item template and replace by some randon spell loot item
&Spell::EffectMilling, //158 SPELL_EFFECT_MILLING milling
&Spell::EffectRenamePet, //159 SPELL_EFFECT_ALLOW_RENAME_PET allow rename pet once again
&Spell::EffectForceCast, //160 SPELL_EFFECT_FORCE_CAST_2
&Spell::EffectSpecCount, //161 SPELL_EFFECT_TALENT_SPEC_COUNT second talent spec (learn/revert)
&Spell::EffectActivateSpec, //162 SPELL_EFFECT_TALENT_SPEC_SELECT activate primary/secondary spec
&Spell::EffectNULL, //163 unused
&Spell::EffectRemoveAura, //164 SPELL_EFFECT_REMOVE_AURA
};
void Spell::EffectNULL()
{
TC_LOG_DEBUG("spells", "WORLD: Spell Effect DUMMY");
}
void Spell::EffectUnused()
{
// NOT USED BY ANY SPELL OR USELESS OR IMPLEMENTED IN DIFFERENT WAY IN TRINITY
}
void Spell::EffectResurrectNew()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!m_corpseTarget && !unitTarget)
return;
Player* player = nullptr;
if (m_corpseTarget)
player = ObjectAccessor::FindPlayer(m_corpseTarget->GetOwnerGUID());
else if (unitTarget)
player = unitTarget->ToPlayer();
if (!player || player->IsAlive() || !player->IsInWorld())
return;
if (player->IsResurrectRequested()) // already have one active request
return;
uint32 health = damage;
uint32 mana = effectInfo->MiscValue;
ExecuteLogEffectResurrect(effectInfo->EffectIndex, player);
player->SetResurrectRequestData(m_caster, health, mana, 0);
SendResurrectRequest(player);
}
void Spell::EffectInstaKill()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive())
return;
if (unitTarget->GetTypeId() == TYPEID_PLAYER)
if (unitTarget->ToPlayer()->GetCommandStatus(CHEAT_GOD))
return;
if (m_caster == unitTarget) // prevent interrupt message
finish();
WorldPacket data(SMSG_SPELLINSTAKILLLOG, 8+8+4);
data << uint64(m_caster->GetGUID());
data << uint64(unitTarget->GetGUID());
data << uint32(m_spellInfo->Id);
m_caster->SendMessageToSet(&data, true);
Unit::DealDamage(GetUnitCasterForEffectHandlers(), unitTarget, unitTarget->GetHealth(), nullptr, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false);
}
void Spell::EffectEnvironmentalDMG()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive())
return;
// CalcAbsorbResist already in Player::EnvironmentalDamage
if (unitTarget->GetTypeId() == TYPEID_PLAYER)
unitTarget->ToPlayer()->EnvironmentalDamage(DAMAGE_FIRE, damage);
else
{
Unit* unitCaster = GetUnitCasterForEffectHandlers();
DamageInfo damageInfo(unitCaster, unitTarget, damage, m_spellInfo, m_spellInfo->GetSchoolMask(), SPELL_DIRECT_DAMAGE, BASE_ATTACK);
Unit::CalcAbsorbResist(damageInfo);
uint32 const absorb = damageInfo.GetAbsorb();
uint32 const resist = damageInfo.GetResist();
if (unitCaster)
unitCaster->SendSpellNonMeleeDamageLog(unitTarget, m_spellInfo->Id, damage, m_spellInfo->GetSchoolMask(), absorb, resist, false, 0, false);
}
}
void Spell::EffectSchoolDMG()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
return;
if (unitTarget && unitTarget->IsAlive())
{
bool apply_direct_bonus = true;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
// Meteor like spells (divided damage to targets)
if (m_spellInfo->HasAttribute(SPELL_ATTR0_CU_SHARE_DAMAGE))
{
uint32 count = 0;
for (auto ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit)
{
if (ihit->MissCondition != SPELL_MISS_NONE)
continue;
if (ihit->EffectMask & (1 << effectInfo->EffectIndex))
++count;
}
// divide to all targets
if (count)
damage /= count;
}
break;
}
case SPELLFAMILY_WARRIOR:
{
if (!unitCaster)
break;
// Shield Slam
if ((m_spellInfo->SpellFamilyFlags[1] & 0x200) && m_spellInfo->GetCategory() == 1209)
{
uint8 level = unitCaster->GetLevel();
uint32 block_value = unitCaster->GetShieldBlockValue(uint32(float(level) * 24.5f), uint32(float(level) * 34.5f));
damage += int32(unitCaster->ApplyEffectModifiers(m_spellInfo, effectInfo->EffectIndex, float(block_value)));
}
// Victory Rush
else if (m_spellInfo->SpellFamilyFlags[1] & 0x100)
ApplyPct(damage, unitCaster->GetTotalAttackPowerValue(BASE_ATTACK));
// Shockwave
else if (m_spellInfo->Id == 46968)
{
int32 pct = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_2));
if (pct > 0)
damage += int32(CalculatePct(unitCaster->GetTotalAttackPowerValue(BASE_ATTACK), pct));
break;
}
break;
}
case SPELLFAMILY_WARLOCK:
{
if (!unitCaster)
break;
// Incinerate Rank 1 & 2
if ((m_spellInfo->SpellFamilyFlags[1] & 0x000040) && m_spellInfo->SpellIconID == 2128)
{
// Incinerate does more dmg (dmg*0.25) if the target have Immolate debuff.
// Check aura state for speed but aura state set not only for Immolate spell
if (unitTarget->HasAuraState(AURA_STATE_CONFLAGRATE))
{
if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0))
damage += damage / 4;
}
}
// Conflagrate - consumes Immolate or Shadowflame
else if (m_spellInfo->TargetAuraState == AURA_STATE_CONFLAGRATE)
{
AuraEffect const* aura = nullptr; // found req. aura for damage calculation
Unit::AuraEffectList const& mPeriodic = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE);
for (Unit::AuraEffectList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i)
{
// for caster applied auras only
if ((*i)->GetSpellInfo()->SpellFamilyName != SPELLFAMILY_WARLOCK ||
(*i)->GetCasterGUID() != unitCaster->GetGUID())
continue;
// Immolate
if ((*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x4)
{
aura = *i; // it selected always if exist
break;
}
// Shadowflame
if ((*i)->GetSpellInfo()->SpellFamilyFlags[2] & 0x00000002)
aura = *i; // remember but wait possible Immolate as primary priority
}
// found Immolate or Shadowflame
if (aura)
{
// Calculate damage of Immolate/Shadowflame tick
int32 pdamage = aura->GetAmount();
pdamage = unitTarget->SpellDamageBonusTaken(unitCaster, aura->GetSpellInfo(), pdamage, DOT);
// And multiply by amount of ticks to get damage potential
pdamage *= aura->GetSpellInfo()->GetMaxTicks();
int32 pct_dir = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_1));
damage += CalculatePct(pdamage, pct_dir);
int32 pct_dot = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_2));
int32 const dotBasePoints = CalculatePct(pdamage, pct_dot);
ASSERT(m_spellInfo->GetMaxTicks() > 0);
m_spellValue->EffectBasePoints[EFFECT_1] = dotBasePoints / m_spellInfo->GetMaxTicks();
apply_direct_bonus = false;
// Glyph of Conflagrate
if (!unitCaster->HasAura(56235))
unitTarget->RemoveAurasDueToSpell(aura->GetId(), unitCaster->GetGUID());
break;
}
}
// Shadow Bite
else if (m_spellInfo->SpellFamilyFlags[1] & 0x400000)
{
if (unitCaster->GetTypeId() == TYPEID_UNIT && unitCaster->IsPet())
{
if (Player* owner = unitCaster->GetOwner()->ToPlayer())
{
if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 214, 0))
{
int32 bp0 = aurEff->GetId() == 54037 ? 4 : 8;
CastSpellExtraArgs args(TRIGGERED_FULL_MASK);
args.AddSpellMod(SPELLVALUE_BASE_POINT0, bp0);
unitCaster->CastSpell(nullptr, 54425, args);
}
}
}
}
break;
}
case SPELLFAMILY_PRIEST:
{
if (!unitCaster)
break;
// Improved Mind Blast (Mind Blast in shadow form bonus)
if (unitCaster->GetShapeshiftForm() == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000))
{
Unit::AuraEffectList const& ImprMindBlast = unitCaster->GetAuraEffectsByType(SPELL_AURA_ADD_FLAT_MODIFIER);
for (Unit::AuraEffectList::const_iterator i = ImprMindBlast.begin(); i != ImprMindBlast.end(); ++i)
{
if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_PRIEST &&
((*i)->GetSpellInfo()->SpellIconID == 95))
{
// Mind Trauma
int32 const chance = (*i)->GetSpellInfo()->GetEffect(EFFECT_1).CalcValue(unitCaster);
if (roll_chance_i(chance))
unitCaster->CastSpell(unitTarget, 48301, true);
break;
}
}
}
break;
}
case SPELLFAMILY_DRUID:
{
if (!unitCaster)
break;
// Ferocious Bite
if (unitCaster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->SpellFamilyFlags[0] & 0x000800000) && m_spellInfo->SpellVisual[0] == 6587)
{
// converts each extra point of energy into ($f1+$AP/410) additional damage
float ap = unitCaster->GetTotalAttackPowerValue(BASE_ATTACK);
float multiple = ap / 410 + effectInfo->DamageMultiplier;
int32 energy = -(unitCaster->ModifyPower(POWER_ENERGY, -30));
damage += int32(energy * multiple);
damage += int32(CalculatePct(unitCaster->ToPlayer()->GetComboPoints() * ap, 7));
}
// Wrath
else if (m_spellInfo->SpellFamilyFlags[0] & 0x00000001)
{
// Improved Insect Swarm
if (AuraEffect const* aurEff = unitCaster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0))
if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00200000, 0, 0))
AddPct(damage, aurEff->GetAmount());
}
break;
}
case SPELLFAMILY_ROGUE:
{
if (!unitCaster)
break;
// Envenom
if (m_spellInfo->SpellFamilyFlags[1] & 0x00000008)
{
if (Player* player = unitCaster->ToPlayer())
{
// consume from stack dozes not more that have combo-points
if (uint32 combo = player->GetComboPoints())
{
// Lookup for Deadly poison (only attacker applied)
if (AuraEffect const* aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x00010000, 0, 0, unitCaster->GetGUID()))
{
// count consumed deadly poison doses at target
bool needConsume = true;
uint32 spellId = aurEff->GetId();
uint32 doses = aurEff->GetBase()->GetStackAmount();
if (doses > combo)
doses = combo;
// Master Poisoner
Unit::AuraEffectList const& auraList = player->GetAuraEffectsByType(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK);
for (Unit::AuraEffectList::const_iterator iter = auraList.begin(); iter != auraList.end(); ++iter)
{
if ((*iter)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_ROGUE && (*iter)->GetSpellInfo()->SpellIconID == 1960)
{
uint32 chance = (*iter)->GetSpellInfo()->GetEffect(EFFECT_2).CalcValue(unitCaster);
if (chance && roll_chance_i(chance))
needConsume = false;
break;
}
}
if (needConsume)
for (uint32 i = 0; i < doses; ++i)
unitTarget->RemoveAuraFromStack(spellId, unitCaster->GetGUID());
damage *= doses;
damage += int32(player->GetTotalAttackPowerValue(BASE_ATTACK) * 0.09f * combo);
}
// Eviscerate and Envenom Bonus Damage (item set effect)
if (unitCaster->HasAura(37169))
damage += combo * 40;
}
}
}
// Eviscerate
else if (m_spellInfo->SpellFamilyFlags[0] & 0x00020000)
{
if (Player* player = unitCaster->ToPlayer())
{
if (uint32 combo = player->GetComboPoints())
{
float ap = unitCaster->GetTotalAttackPowerValue(BASE_ATTACK);
damage += std::lroundf(ap * combo * 0.07f);
// Eviscerate and Envenom Bonus Damage (item set effect)
if (unitCaster->HasAura(37169))
damage += combo*40;
}
}
}
break;
}
case SPELLFAMILY_HUNTER:
{
if (!unitCaster)
break;
//Gore
if (m_spellInfo->SpellIconID == 1578)
{
if (unitCaster->HasAura(57627)) // Charge 6 sec post-affect
damage *= 2;
}
// Steady Shot
else if (m_spellInfo->SpellFamilyFlags[1] & 0x1)
{
bool found = false;
// check dazed affect
Unit::AuraEffectList const& decSpeedList = unitTarget->GetAuraEffectsByType(SPELL_AURA_MOD_DECREASE_SPEED);
for (Unit::AuraEffectList::const_iterator iter = decSpeedList.begin(); iter != decSpeedList.end(); ++iter)
{
if ((*iter)->GetSpellInfo()->SpellIconID == 15 && (*iter)->GetSpellInfo()->Dispel == 0)
{
found = true;
break;
}
}
/// @todo should this be put on taken but not done?
if (found)
damage += m_spellInfo->GetEffect(EFFECT_1).CalcValue();
if (Player* caster = unitCaster->ToPlayer())
{
// Add Ammo and Weapon damage plus RAP * 0.1
float dmg_min = 0.f;
float dmg_max = 0.f;
for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i)
{
dmg_min += caster->GetWeaponDamageRange(RANGED_ATTACK, MINDAMAGE, i);
dmg_max += caster->GetWeaponDamageRange(RANGED_ATTACK, MAXDAMAGE, i);
}
if (dmg_max == 0.0f && dmg_min > dmg_max)
damage += int32(dmg_min);
else
damage += irand(int32(dmg_min), int32(dmg_max));
damage += int32(caster->GetAmmoDPS() * caster->GetAttackTime(RANGED_ATTACK) * 0.001f);
}
}
break;
}
case SPELLFAMILY_PALADIN:
{
if (!unitCaster)
break;
// Hammer of the Righteous
if (m_spellInfo->SpellFamilyFlags[1] & 0x00040000)
{
float minTotal = 0.f;
float maxTotal = 0.f;
float tmpMin, tmpMax;
for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i)
{
unitCaster->CalculateMinMaxDamage(BASE_ATTACK, false, false, tmpMin, tmpMax, i);
minTotal += tmpMin;
maxTotal += tmpMax;
}
float average = (minTotal + maxTotal) / 2;
// Add main hand dps * effect[2] amount
int32 count = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_2));
damage += count * int32(average * IN_MILLISECONDS) / unitCaster->GetAttackTime(BASE_ATTACK);
break;
}
// Shield of Righteousness
if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x100000)
{
uint8 level = unitCaster->GetLevel();
uint32 block_value = unitCaster->GetShieldBlockValue(uint32(float(level) * 29.5f), uint32(float(level) * 39.5f));
damage += CalculatePct(block_value, m_spellInfo->GetEffect(EFFECT_1).CalcValue());
break;
}
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
if (!unitCaster)
break;
// Blood Boil - bonus for diseased targets
if (m_spellInfo->SpellFamilyFlags[0] & 0x00040000)
{
if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0, 0x00000002, unitCaster->GetGUID()))
{
damage += m_damage / 2;
damage += int32(unitCaster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.035f);
}
}
break;
}
}
if (unitCaster && damage > 0 && apply_direct_bonus)
{
damage = unitCaster->SpellDamageBonusDone(unitTarget, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE, *effectInfo, { });
damage = unitTarget->SpellDamageBonusTaken(unitCaster, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE);
}
m_damage += damage;
}
}
void Spell::EffectDummy()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget && !gameObjTarget && !itemTarget && !m_corpseTarget)
return;
// pet auras
if (m_caster->GetTypeId() == TYPEID_PLAYER)
{
if (PetAura const* petSpell = sSpellMgr->GetPetAura(m_spellInfo->Id, effectInfo->EffectIndex))
{
m_caster->ToPlayer()->AddPetAura(petSpell);
return;
}
}
// normal DB scripted effect
TC_LOG_DEBUG("spells", "Spell ScriptStart spellid %u in EffectDummy(%u)", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
m_caster->GetMap()->ScriptsStart(sSpellScripts, uint32(m_spellInfo->Id | (effectInfo->EffectIndex << 24)), m_caster, unitTarget);
#ifdef ELUNA
if (gameObjTarget)
sEluna->OnDummyEffect(m_caster, m_spellInfo->Id, effectInfo->EffectIndex, gameObjTarget);
else if (unitTarget && unitTarget->GetTypeId() == TYPEID_UNIT)
sEluna->OnDummyEffect(m_caster, m_spellInfo->Id, effectInfo->EffectIndex, unitTarget->ToCreature());
else if (itemTarget)
sEluna->OnDummyEffect(m_caster, m_spellInfo->Id, effectInfo->EffectIndex, itemTarget);
#endif
}
void Spell::EffectTriggerSpell()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET
&& effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH)
return;
uint32 triggered_spell_id = effectInfo->TriggerSpell;
/// @todo move those to spell scripts
if (effectInfo->Effect == SPELL_EFFECT_TRIGGER_SPELL
&& effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
{
Unit* unitCaster = GetUnitCasterForEffectHandlers();
// special cases
switch (triggered_spell_id)
{
// Mirror Image
case 58832:
{
if (!unitCaster)
break;
// Glyph of Mirror Image
if (unitCaster->HasAura(63093))
unitCaster->CastSpell(nullptr, 65047, true); // Mirror Image
break;
}
// Demonic Empowerment -- succubus
case 54437:
{
unitTarget->RemoveMovementImpairingAuras(true);
unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED);
unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STUN);
// Cast Lesser Invisibility
unitTarget->CastSpell(unitTarget, 7870, true);
return;
}
// Brittle Armor - (need add max stack of 24575 Brittle Armor)
case 29284:
{
// Brittle Armor
SpellInfo const* spell = sSpellMgr->GetSpellInfo(24575);
if (!spell)
return;
for (uint32 j = 0; j < spell->StackAmount; ++j)
m_caster->CastSpell(unitTarget, spell->Id, true);
return;
}
// Mercurial Shield - (need add max stack of 26464 Mercurial Shield)
case 29286:
{
// Mercurial Shield
SpellInfo const* spell = sSpellMgr->GetSpellInfo(26464);
if (!spell)
return;
for (uint32 j = 0; j < spell->StackAmount; ++j)
m_caster->CastSpell(unitTarget, spell->Id, true);
return;
}
}
}
if (triggered_spell_id == 0)
{
TC_LOG_WARN("spells.effect.nospell", "Spell::EffectTriggerSpell: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
return;
}
// normal case
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!spellInfo)
{
TC_LOG_ERROR("spells.effect.nospell", "Spell::EffectTriggerSpell spell %u tried to trigger unknown spell %u", m_spellInfo->Id, triggered_spell_id);
return;
}
SpellCastTargets targets;
if (effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
{
if (!spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo))
return;
targets.SetUnitTarget(unitTarget);
}
else //if (effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH)
{
if (spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo) && (effectInfo->GetProvidedTargetMask() & TARGET_FLAG_UNIT_MASK))
return;
if (spellInfo->GetExplicitTargetMask() & TARGET_FLAG_DEST_LOCATION)
targets.SetDst(m_targets);
if (Unit* target = m_targets.GetUnitTarget())
targets.SetUnitTarget(target);
else
{
if (Unit* unit = m_caster->ToUnit())
targets.SetUnitTarget(unit);
else if (GameObject* go = m_caster->ToGameObject())
targets.SetGOTarget(go);
}
}
CastSpellExtraArgs args(m_originalCasterGUID);
// set basepoints for trigger with value effect
if (effectInfo->Effect == SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE)
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), damage);
// original caster guid only for GO cast
m_caster->CastSpell(targets, spellInfo->Id, args);
}
void Spell::EffectTriggerMissileSpell()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET
&& effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
uint32 triggered_spell_id = effectInfo->TriggerSpell;
if (triggered_spell_id == 0)
{
TC_LOG_WARN("spells.effect.nospell", "Spell::EffectTriggerMissileSpell: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
return;
}
// normal case
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!spellInfo)
{
TC_LOG_ERROR("spells.effect.nospell", "Spell::EffectTriggerMissileSpell spell %u tried to trigger unknown spell %u.", m_spellInfo->Id, triggered_spell_id);
return;
}
SpellCastTargets targets;
if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET)
{
if (!spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo))
return;
targets.SetUnitTarget(unitTarget);
}
else //if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT)
{
if (spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo) && (effectInfo->GetProvidedTargetMask() & TARGET_FLAG_UNIT_MASK))
return;
if (spellInfo->GetExplicitTargetMask() & TARGET_FLAG_DEST_LOCATION)
targets.SetDst(m_targets);
if (Unit* unit = m_caster->ToUnit())
targets.SetUnitTarget(unit);
else if (GameObject* go = m_caster->ToGameObject())
targets.SetGOTarget(go);
}
CastSpellExtraArgs args(m_originalCasterGUID);
// set basepoints for trigger with value effect
if (effectInfo->Effect == SPELL_EFFECT_TRIGGER_MISSILE_SPELL_WITH_VALUE)
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), damage);
// original caster guid only for GO cast
m_caster->CastSpell(targets, spellInfo->Id, args);
}
void Spell::EffectForceCast()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
uint32 triggered_spell_id = effectInfo->TriggerSpell;
if (triggered_spell_id == 0)
{
TC_LOG_WARN("spells.effect.nospell", "Spell::EffectForceCast: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
return;
}
// normal case
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!spellInfo)
{
TC_LOG_ERROR("spells.effect.nospell", "Spell::EffectForceCast of spell %u: triggering unknown spell id %i.", m_spellInfo->Id, triggered_spell_id);
return;
}
if (effectInfo->Effect == SPELL_EFFECT_FORCE_CAST && damage)
{
switch (m_spellInfo->Id)
{
case 52588: // Skeletal Gryphon Escape
case 48598: // Ride Flamebringer Cue
unitTarget->RemoveAura(damage);
break;
case 52463: // Hide In Mine Car
case 52349: // Overtake
{
CastSpellExtraArgs args(m_originalCasterGUID);
args.AddSpellMod(SPELLVALUE_BASE_POINT0, damage);
unitTarget->CastSpell(unitTarget, spellInfo->Id, args);
return;
}
}
}
switch (spellInfo->Id)
{
case 72298: // Malleable Goo Summon
unitTarget->CastSpell(unitTarget, spellInfo->Id, m_originalCasterGUID);
return;
}
CastSpellExtraArgs args(TRIGGERED_FULL_MASK);
if (effectInfo->Effect == SPELL_EFFECT_FORCE_CAST_WITH_VALUE)
for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i)
args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), damage);
unitTarget->CastSpell(m_caster, spellInfo->Id, args);
}
void Spell::EffectTriggerRitualOfSummoning()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
uint32 triggered_spell_id = effectInfo->TriggerSpell;
if (triggered_spell_id == 0)
{
TC_LOG_WARN("spells.effect.nospell", "Spell::EffectTriggerRitualOfSummoning: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
return;
}
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id);
if (!spellInfo)
{
TC_LOG_ERROR("spells.effect.nospell", "EffectTriggerRitualOfSummoning of spell %u: triggering unknown spell id %i.", m_spellInfo->Id, triggered_spell_id);
return;
}
finish();
m_caster->CastSpell(nullptr, spellInfo->Id, false);
}
void Spell::CalculateJumpSpeeds(SpellEffectInfo const& spellEffectInfo, float dist, float& speedXY, float& speedZ)
{
Unit* unitCaster = GetUnitCasterForEffectHandlers();
ASSERT(unitCaster);
float runSpeed = unitCaster->IsControlledByPlayer() ? playerBaseMoveSpeed[MOVE_RUN] : baseMoveSpeed[MOVE_RUN];
if (Creature* creature = unitCaster->ToCreature())
runSpeed *= creature->GetCreatureTemplate()->speed_run;
float multiplier = spellEffectInfo.ValueMultiplier;
if (multiplier <= 0.0f)
multiplier = 1.0f;
speedXY = std::min(runSpeed * 3.0f * multiplier, std::max(28.0f, unitCaster->GetSpeed(MOVE_RUN) * 4.0f));
float duration = dist / speedXY;
float durationSqr = duration * duration;
float minHeight = spellEffectInfo.MiscValue ? spellEffectInfo.MiscValue / 10.0f : 0.5f; // Lower bound is blizzlike
float maxHeight = spellEffectInfo.MiscValueB ? spellEffectInfo.MiscValueB / 10.0f : 1000.0f; // Upper bound is unknown
float height;
if (durationSqr < minHeight * 8 / Movement::gravity)
height = minHeight;
else if (durationSqr > maxHeight * 8 / Movement::gravity)
height = maxHeight;
else
height = Movement::gravity * durationSqr / 8;
speedZ = std::sqrt(2 * Movement::gravity * height);
}
void Spell::EffectJump()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (unitCaster->IsInFlight())
return;
if (!unitTarget)
return;
float speedXY, speedZ;
CalculateJumpSpeeds(*effectInfo, unitCaster->GetExactDist2d(unitTarget), speedXY, speedZ);
unitCaster->GetMotionMaster()->MoveJump(*unitTarget, speedXY, speedZ, EVENT_JUMP, false);
}
void Spell::EffectJumpDest()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (unitCaster->IsInFlight())
return;
if (!m_targets.HasDst())
return;
float speedXY, speedZ;
CalculateJumpSpeeds(*effectInfo, unitCaster->GetExactDist2d(destTarget), speedXY, speedZ);
unitCaster->GetMotionMaster()->MoveJump(*destTarget, speedXY, speedZ, EVENT_JUMP, !m_targets.GetObjectTargetGUID().IsEmpty());
}
void Spell::EffectTeleportUnits()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->IsInFlight())
return;
// If not exist data for dest location - return
if (!m_targets.HasDst())
{
TC_LOG_ERROR("spells", "Spell::EffectTeleportUnits - does not have a destination for spellId %u.", m_spellInfo->Id);
return;
}
// Init dest coordinates
WorldLocation targetDest(*destTarget);
if (targetDest.GetMapId() == MAPID_INVALID)
targetDest.m_mapId = unitTarget->GetMapId();
if (!targetDest.GetOrientation() && m_targets.GetUnitTarget())
targetDest.SetOrientation(m_targets.GetUnitTarget()->GetOrientation());
if (targetDest.GetMapId() == unitTarget->GetMapId())
unitTarget->NearTeleportTo(targetDest, unitTarget == m_caster);
else if (unitTarget->GetTypeId() == TYPEID_PLAYER)
unitTarget->ToPlayer()->TeleportTo(targetDest, unitTarget == m_caster ? TELE_TO_SPELL : 0);
else
{
TC_LOG_ERROR("spells", "Spell::EffectTeleportUnits - spellId %u attempted to teleport creature to a different map.", m_spellInfo->Id);
return;
}
}
void Spell::EffectApplyAura()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!_spellAura || !unitTarget)
return;
// register target/effect on aura
AuraApplication* aurApp = _spellAura->GetApplicationOfTarget(unitTarget->GetGUID());
if (!aurApp)
aurApp = unitTarget->_CreateAuraApplication(_spellAura, 1 << effectInfo->EffectIndex);
else
aurApp->UpdateApplyEffectMask(aurApp->GetEffectsToApply() | 1 << effectInfo->EffectIndex);
}
void Spell::EffectUnlearnSpecialization()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
uint32 spellToUnlearn = effectInfo->TriggerSpell;
player->RemoveSpell(spellToUnlearn);
TC_LOG_DEBUG("spells", "Spell: Player %s has unlearned spell %u from Npc %s", player->GetGUID().ToString().c_str(), spellToUnlearn, m_caster->GetGUID().ToString().c_str());
}
void Spell::EffectPowerDrain()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS))
return;
Powers powerType = Powers(effectInfo->MiscValue);
if (!unitTarget || !unitTarget->IsAlive() || unitTarget->GetPowerType() != powerType || damage < 0)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
// add spell damage bonus
if (unitCaster)
{
damage = unitCaster->SpellDamageBonusDone(unitTarget, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE, *effectInfo, { });
damage = unitTarget->SpellDamageBonusTaken(unitCaster, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE);
}
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
int32 power = damage;
if (powerType == POWER_MANA)
power -= unitTarget->GetSpellCritDamageReduction(power);
int32 newDamage = -(unitTarget->ModifyPower(powerType, -int32(power)));
// Don't restore from self drain
float gainMultiplier = 0.f;
if (unitCaster && unitCaster != unitTarget)
{
gainMultiplier = effectInfo->CalcValueMultiplier(unitCaster, this);
int32 const gain = int32(newDamage * gainMultiplier);
unitCaster->EnergizeBySpell(unitCaster, m_spellInfo, gain, powerType);
}
ExecuteLogEffectTakeTargetPower(effectInfo->EffectIndex, unitTarget, powerType, newDamage, gainMultiplier);
}
void Spell::EffectSendEvent()
{
// we do not handle a flag dropping or clicking on flag in battleground by sendevent system
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET
&& effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
WorldObject* target = nullptr;
// call events for object target if present
if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET)
{
if (unitTarget)
target = unitTarget;
else if (gameObjTarget)
target = gameObjTarget;
else if (m_corpseTarget)
target = m_corpseTarget;
}
else // if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT)
{
// let's prevent executing effect handler twice in case when spell effect is capable of targeting an object
// this check was requested by scripters, but it has some downsides:
// now it's impossible to script (using sEventScripts) a cast which misses all targets
// or to have an ability to script the moment spell hits dest (in a case when there are object targets present)
if (effectInfo->GetProvidedTargetMask() & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_GAMEOBJECT_MASK))
return;
// some spells have no target entries in dbc and they use focus target
if (focusObject)
target = focusObject;
/// @todo there should be a possibility to pass dest target to event script
}
TC_LOG_DEBUG("spells", "Spell ScriptStart %u for spellid %u in EffectSendEvent ", effectInfo->MiscValue, m_spellInfo->Id);
if (ZoneScript* zoneScript = m_caster->GetZoneScript())
zoneScript->ProcessEvent(target, effectInfo->MiscValue);
else if (InstanceScript* instanceScript = m_caster->GetInstanceScript()) // needed in case Player is the caster
instanceScript->ProcessEvent(target, effectInfo->MiscValue);
m_caster->GetMap()->ScriptsStart(sEventScripts, effectInfo->MiscValue, m_caster, target);
}
void Spell::EffectPowerBurn()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS))
return;
Powers powerType = Powers(effectInfo->MiscValue);
if (!unitTarget || !unitTarget->IsAlive() || unitTarget->GetPowerType() != powerType || damage < 0)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
// burn x% of target's mana, up to maximum of 2x% of caster's mana (Mana Burn)
///@todo: move this to scripts
if (unitCaster && m_spellInfo->Id == 8129)
{
int32 maxDamage = int32(CalculatePct(unitCaster->GetMaxPower(powerType), damage * 2));
damage = int32(CalculatePct(unitTarget->GetMaxPower(powerType), damage));
damage = std::min(damage, maxDamage);
}
int32 power = damage;
// resilience reduce mana draining effect at spell crit damage reduction (added in 2.4)
if (powerType == POWER_MANA)
power -= unitTarget->GetSpellCritDamageReduction(power);
int32 newDamage = -(unitTarget->ModifyPower(powerType, -power));
// NO - Not a typo - EffectPowerBurn uses effect value multiplier - not effect damage multiplier
float dmgMultiplier = effectInfo->CalcValueMultiplier(unitCaster, this);
// add log data before multiplication (need power amount, not damage)
ExecuteLogEffectTakeTargetPower(effectInfo->EffectIndex, unitTarget, powerType, newDamage, 0.0f);
newDamage = int32(newDamage * dmgMultiplier);
m_damage += newDamage;
}
void Spell::EffectHeal()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive() || damage < 0)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
// Skip if m_originalCaster not available
if (!unitCaster)
return;
int32 addhealth = damage;
// Vessel of the Naaru (Vial of the Sunwell trinket)
///@todo: move this to scripts
if (m_spellInfo->Id == 45064)
{
// Amount of heal - depends from stacked Holy Energy
int32 damageAmount = 0;
if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(45062, 0))
{
damageAmount += aurEff->GetAmount();
unitCaster->RemoveAurasDueToSpell(45062);
}
addhealth += damageAmount;
}
// Swiftmend - consumes Regrowth or Rejuvenation
else if (m_spellInfo->TargetAuraState == AURA_STATE_SWIFTMEND && unitTarget->HasAuraState(AURA_STATE_SWIFTMEND, m_spellInfo, unitCaster))
{
Unit::AuraEffectList const& RejorRegr = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL);
// find most short by duration
AuraEffect* targetAura = nullptr;
for (Unit::AuraEffectList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i)
{
if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID
&& (*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x50)
{
if (!targetAura || (*i)->GetBase()->GetDuration() < targetAura->GetBase()->GetDuration())
targetAura = *i;
}
}
if (!targetAura)
{
TC_LOG_ERROR("spells", "Target (%s) has the aurastate AURA_STATE_SWIFTMEND, but no matching aura.", unitTarget->GetGUID().ToString().c_str());
return;
}
int32 tickheal = targetAura->GetAmount();
unitTarget->SpellHealingBonusTaken(unitCaster, targetAura->GetSpellInfo(), tickheal, DOT);
int32 tickcount = 0;
// Rejuvenation
if (targetAura->GetSpellInfo()->SpellFamilyFlags[0] & 0x10)
tickcount = 4;
// Regrowth
else // if (targetAura->GetSpellInfo()->SpellFamilyFlags[0] & 0x40)
tickcount = 6;
addhealth += tickheal * tickcount;
// Glyph of Swiftmend
if (!unitCaster->HasAura(54824))
unitTarget->RemoveAura(targetAura->GetId(), targetAura->GetCasterGUID());
}
// Death Pact - return pct of max health to caster
else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] & 0x00080000)
addhealth = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, int32(unitCaster->CountPctFromMaxHealth(damage)), HEAL, *effectInfo, { });
else
addhealth = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, addhealth, HEAL, *effectInfo, { });
addhealth = unitTarget->SpellHealingBonusTaken(unitCaster, m_spellInfo, addhealth, HEAL);
// Remove Grievious bite if fully healed
if (unitTarget->HasAura(48920) && (unitTarget->GetHealth() + addhealth >= unitTarget->GetMaxHealth()))
unitTarget->RemoveAura(48920);
m_healing += addhealth;
}
void Spell::EffectHealPct()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive() || damage < 0)
return;
uint32 heal = unitTarget->CountPctFromMaxHealth(damage);
if (Unit* unitCaster = GetUnitCasterForEffectHandlers())
{
heal = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, heal, HEAL, *effectInfo, { });
heal = unitTarget->SpellHealingBonusTaken(unitCaster, m_spellInfo, heal, HEAL);
}
m_healing += heal;
}
void Spell::EffectHealMechanical()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive() || damage < 0)
return;
uint32 heal = damage;
if (Unit* unitCaster = GetUnitCasterForEffectHandlers())
{
heal = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, heal, HEAL, *effectInfo, { });
heal = unitTarget->SpellHealingBonusTaken(unitCaster, m_spellInfo, heal, HEAL);
}
m_healing += heal;
}
void Spell::EffectHealthLeech()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive() || damage < 0)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (unitCaster)
{
damage = unitCaster->SpellDamageBonusDone(unitTarget, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE, *effectInfo, { });
damage = unitTarget->SpellDamageBonusTaken(unitCaster, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE);
}
TC_LOG_DEBUG("spells", "HealthLeech :%i", damage);
float healMultiplier = effectInfo->CalcValueMultiplier(unitCaster, this);
m_damage += damage;
DamageInfo damageInfo(unitCaster, unitTarget, damage, m_spellInfo, m_spellInfo->GetSchoolMask(), SPELL_DIRECT_DAMAGE, BASE_ATTACK);
Unit::CalcAbsorbResist(damageInfo);
uint32 const absorb = damageInfo.GetAbsorb();
damage -= absorb;
// get max possible damage, don't count overkill for heal
uint32 healthGain = uint32(-unitTarget->GetHealthGain(-damage) * healMultiplier);
if (unitCaster && unitCaster->IsAlive())
{
healthGain = unitCaster->SpellHealingBonusDone(unitCaster, m_spellInfo, healthGain, HEAL, *effectInfo, { });
healthGain = unitCaster->SpellHealingBonusTaken(unitCaster, m_spellInfo, healthGain, HEAL);
HealInfo healInfo(unitCaster, unitCaster, healthGain, m_spellInfo, m_spellSchoolMask);
unitCaster->HealBySpell(healInfo);
}
}
void Spell::DoCreateItem(uint32 itemId)
{
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
uint32 newitemid = itemId;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(newitemid);
if (!pProto)
{
player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr);
return;
}
// bg reward have some special in code work
uint32 bgType = 0;
switch (m_spellInfo->Id)
{
case SPELL_AV_MARK_WINNER:
case SPELL_AV_MARK_LOSER:
bgType = BATTLEGROUND_AV;
break;
case SPELL_WS_MARK_WINNER:
case SPELL_WS_MARK_LOSER:
bgType = BATTLEGROUND_WS;
break;
case SPELL_AB_MARK_WINNER:
case SPELL_AB_MARK_LOSER:
bgType = BATTLEGROUND_AB;
break;
default:
break;
}
uint32 num_to_add = damage;
if (num_to_add < 1)
num_to_add = 1;
if (num_to_add > pProto->GetMaxStackSize())
num_to_add = pProto->GetMaxStackSize();
/* == gem perfection handling == */
// the chance of getting a perfect result
float perfectCreateChance = 0.0f;
// the resulting perfect item if successful
uint32 perfectItemType = itemId;
// get perfection capability and chance
if (CanCreatePerfectItem(player, m_spellInfo->Id, perfectCreateChance, perfectItemType))
if (roll_chance_f(perfectCreateChance)) // if the roll succeeds...
newitemid = perfectItemType; // the perfect item replaces the regular one
/* == gem perfection handling over == */
/* == profession specialization handling == */
// init items_count to 1, since 1 item will be created regardless of specialization
int items_count=1;
// the chance to create additional items
float additionalCreateChance=0.0f;
// the maximum number of created additional items
uint8 additionalMaxNum=0;
// get the chance and maximum number for creating extra items
if (CanCreateExtraItems(player, m_spellInfo->Id, additionalCreateChance, additionalMaxNum))
// roll with this chance till we roll not to create or we create the max num
while (roll_chance_f(additionalCreateChance) && items_count <= additionalMaxNum)
++items_count;
// really will be created more items
num_to_add *= items_count;
/* == profession specialization handling over == */
// can the player store the new item?
ItemPosCountVec dest;
uint32 no_space = 0;
InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, newitemid, num_to_add, &no_space);
if (msg != EQUIP_ERR_OK)
{
// convert to possible store amount
if (msg == EQUIP_ERR_INVENTORY_FULL || msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS)
num_to_add -= no_space;
else
{
// if not created by another reason from full inventory or unique items amount limitation
player->SendEquipError(msg, nullptr, nullptr, newitemid);
return;
}
}
if (num_to_add)
{
// create the new item and store it
Item* pItem = player->StoreNewItem(dest, newitemid, true, GenerateItemRandomPropertyId(newitemid));
// was it successful? return error if not
if (!pItem)
{
player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr);
return;
}
// set the "Crafted by ..." property of the item
if (pItem->GetTemplate()->HasSignature())
pItem->SetGuidValue(ITEM_FIELD_CREATOR, player->GetGUID());
// send info to the client
player->SendNewItem(pItem, num_to_add, true, bgType == 0);
// we succeeded in creating at least one item, so a levelup is possible
if (bgType == 0)
player->UpdateCraftSkill(m_spellInfo->Id);
}
/*
// for battleground marks send by mail if not add all expected
if (no_space > 0 && bgType)
{
if (Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(BattlegroundTypeId(bgType)))
bg->SendRewardMarkByMail(player, newitemid, no_space);
}
*/
}
void Spell::EffectCreateItem()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
DoCreateItem(effectInfo->ItemType);
ExecuteLogEffectCreateItem(effectInfo->EffectIndex, effectInfo->ItemType);
}
void Spell::EffectCreateItem2()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
// Pick a random item from spell_loot_template
if (m_spellInfo->IsLootCrafting())
{
player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell, false, true);
player->UpdateCraftSkill(m_spellInfo->Id);
}
else // If there's no random loot entries for this spell, pick the item associated with this spell
{
uint32 item_id = effectInfo->ItemType;
if (item_id)
DoCreateItem(item_id);
}
/// @todo ExecuteLogEffectCreateItem(effectInfo->EffectIndex, effectInfo->ItemType);
}
void Spell::EffectCreateRandomItem()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
// create some random items
player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell);
/// @todo ExecuteLogEffectCreateItem(effectInfo->EffectIndex, effectInfo->ItemType);
}
void Spell::EffectPersistentAA()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
// only handle at last effect
for (size_t i = effectInfo->EffectIndex + 1; i < m_spellInfo->GetEffects().size(); ++i)
if (m_spellInfo->GetEffect(SpellEffIndex(i)).IsEffect(SPELL_EFFECT_PERSISTENT_AREA_AURA))
return;
ASSERT(!_dynObjAura);
float radius = effectInfo->CalcRadius(unitCaster);
// Caster not in world, might be spell triggered from aura removal
if (!unitCaster->IsInWorld())
return;
DynamicObject* dynObj = new DynamicObject(false);
if (!dynObj->CreateDynamicObject(unitCaster->GetMap()->GenerateLowGuid<HighGuid::DynamicObject>(), unitCaster, m_spellInfo->Id, *destTarget, radius, DYNAMIC_OBJECT_AREA_SPELL))
{
delete dynObj;
return;
}
AuraCreateInfo createInfo(m_spellInfo, MAX_EFFECT_MASK, dynObj);
createInfo
.SetCaster(unitCaster)
.SetBaseAmount(m_spellValue->EffectBasePoints);
if (Aura* aura = Aura::TryCreate(createInfo))
{
_dynObjAura = aura->ToDynObjAura();
_dynObjAura->_RegisterForTargets();
}
else
return;
ASSERT(_dynObjAura->GetDynobjOwner());
_dynObjAura->_ApplyEffectForTargets(effectInfo->EffectIndex);
}
void Spell::EffectEnergize()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster || !unitTarget)
return;
if (!unitTarget->IsAlive())
return;
if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS))
return;
Powers power = Powers(effectInfo->MiscValue);
if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetPowerType() != power && m_spellInfo->SpellFamilyName != SPELLFAMILY_POTION
&& !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER))
return;
if (unitTarget->GetMaxPower(power) == 0)
return;
// Some level depends spells
///@todo: move this to scripts
int32 level_multiplier = 0;
int32 level_diff = 0;
switch (m_spellInfo->Id)
{
case 9512: // Restore Energy
level_diff = unitCaster->GetLevel() - 40;
level_multiplier = 2;
break;
case 24571: // Blood Fury
level_diff = unitCaster->GetLevel() - 60;
level_multiplier = 10;
break;
case 24532: // Burst of Energy
level_diff = unitCaster->GetLevel() - 60;
level_multiplier = 4;
break;
case 31930: // Judgements of the Wise
case 63375: // Improved Stormstrike
case 68082: // Glyph of Seal of Command
damage = int32(CalculatePct(unitTarget->GetCreateMana(), damage));
break;
case 48542: // Revitalize
damage = int32(CalculatePct(unitTarget->GetMaxPower(power), damage));
break;
case 67490: // Runic Mana Injector (mana gain increased by 25% for engineers - 3.2.0 patch change)
{
if (Player* player = unitCaster->ToPlayer())
if (player->HasSkill(SKILL_ENGINEERING))
AddPct(damage, 25);
break;
}
case 71132: // Glyph of Shadow Word: Pain
damage = int32(CalculatePct(unitTarget->GetCreateMana(), 1)); // set 1 as value, missing in dbc
break;
default:
break;
}
if (level_diff > 0)
damage -= level_multiplier * level_diff;
if (damage < 0)
return;
unitCaster->EnergizeBySpell(unitTarget, m_spellInfo, damage, power);
}
void Spell::EffectEnergizePct()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster || !unitTarget)
return;
if (!unitTarget->IsAlive())
return;
if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS))
return;
Powers power = Powers(effectInfo->MiscValue);
if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetPowerType() != power && !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER))
return;
uint32 maxPower = unitTarget->GetMaxPower(power);
if (!maxPower)
return;
uint32 const gain = CalculatePct(maxPower, damage);
unitCaster->EnergizeBySpell(unitTarget, m_spellInfo, gain, power);
}
void Spell::SendLoot(ObjectGuid guid, LootType loottype)
{
Player* player = m_caster->ToPlayer();
if (!player)
return;
if (gameObjTarget)
{
// Players shouldn't be able to loot gameobjects that are currently despawned
if (!gameObjTarget->isSpawned() && !player->IsGameMaster())
{
TC_LOG_ERROR("entities.player.cheat", "Possible hacking attempt: Player %s %s tried to loot a gameobject %s which is on respawn timer without being in GM mode!",
player->GetName().c_str(), player->GetGUID().ToString().c_str(), gameObjTarget->GetGUID().ToString().c_str());
return;
}
// special case, already has GossipHello inside so return and avoid calling twice
if (gameObjTarget->GetGoType() == GAMEOBJECT_TYPE_GOOBER)
{
gameObjTarget->Use(player);
return;
}
player->PlayerTalkClass->ClearMenus();
#ifdef ELUNA
if (sEluna->OnGossipHello(player, gameObjTarget))
return;
if (sEluna->OnGameObjectUse(player, gameObjTarget))
return;
#endif
if (gameObjTarget->AI()->OnGossipHello(player))
return;
switch (gameObjTarget->GetGoType())
{
case GAMEOBJECT_TYPE_DOOR:
case GAMEOBJECT_TYPE_BUTTON:
gameObjTarget->UseDoorOrButton(0, false, player);
return;
case GAMEOBJECT_TYPE_QUESTGIVER:
player->PrepareGossipMenu(gameObjTarget, gameObjTarget->GetGOInfo()->questgiver.gossipID, true);
player->SendPreparedGossip(gameObjTarget);
return;
case GAMEOBJECT_TYPE_SPELL_FOCUS:
// triggering linked GO
if (uint32 trapEntry = gameObjTarget->GetGOInfo()->spellFocus.linkedTrapId)
gameObjTarget->TriggeringLinkedGameObject(trapEntry, player);
return;
case GAMEOBJECT_TYPE_CHEST:
/// @todo possible must be moved to loot release (in different from linked triggering)
if (gameObjTarget->GetGOInfo()->chest.eventId)
{
TC_LOG_DEBUG("spells", "Chest ScriptStart id %u for GO %u", gameObjTarget->GetGOInfo()->chest.eventId, gameObjTarget->GetSpawnId());
player->GetMap()->ScriptsStart(sEventScripts, gameObjTarget->GetGOInfo()->chest.eventId, player, gameObjTarget);
}
// triggering linked GO
if (uint32 trapEntry = gameObjTarget->GetGOInfo()->chest.linkedTrapId)
gameObjTarget->TriggeringLinkedGameObject(trapEntry, player);
// Don't return, let loots been taken
break;
default:
break;
}
}
// Send loot
player->SendLoot(guid, loottype);
}
void Spell::EffectOpenLock()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
{
TC_LOG_DEBUG("spells", "WORLD: Open Lock - No Player Caster!");
return;
}
Player* player = m_caster->ToPlayer();
uint32 lockId = 0;
ObjectGuid guid;
// Get lockId
if (gameObjTarget)
{
GameObjectTemplate const* goInfo = gameObjTarget->GetGOInfo();
if (goInfo->CannotBeUsedUnderImmunity() && m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE))
return;
// Arathi Basin banner opening. /// @todo Verify correctness of this check
if ((goInfo->type == GAMEOBJECT_TYPE_BUTTON && goInfo->button.noDamageImmune) ||
(goInfo->type == GAMEOBJECT_TYPE_GOOBER && goInfo->goober.losOK))
{
//CanUseBattlegroundObject() already called in CheckCast()
// in battleground check
if (Battleground* bg = player->GetBattleground())
{
bg->EventPlayerClickedOnFlag(player, gameObjTarget);
return;
}
}
else if (goInfo->type == GAMEOBJECT_TYPE_FLAGSTAND)
{
//CanUseBattlegroundObject() already called in CheckCast()
// in battleground check
if (Battleground* bg = player->GetBattleground())
{
if (bg->GetTypeID(true) == BATTLEGROUND_EY)
bg->EventPlayerClickedOnFlag(player, gameObjTarget);
return;
}
}
else if (m_spellInfo->Id == 1842 && gameObjTarget->GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && gameObjTarget->GetOwner())
{
gameObjTarget->SetLootState(GO_JUST_DEACTIVATED);
return;
}
/// @todo Add script for spell 41920 - Filling, becouse server it freze when use this spell
// handle outdoor pvp object opening, return true if go was registered for handling
// these objects must have been spawned by outdoorpvp!
else if (gameObjTarget->GetGOInfo()->type == GAMEOBJECT_TYPE_GOOBER && sOutdoorPvPMgr->HandleOpenGo(player, gameObjTarget))
return;
lockId = goInfo->GetLockId();
guid = gameObjTarget->GetGUID();
}
else if (itemTarget)
{
lockId = itemTarget->GetTemplate()->LockID;
guid = itemTarget->GetGUID();
}
else
{
TC_LOG_DEBUG("spells", "WORLD: Open Lock - No GameObject/Item Target!");
return;
}
SkillType skillId = SKILL_NONE;
int32 reqSkillValue = 0;
int32 skillValue;
SpellCastResult res = CanOpenLock(*effectInfo, lockId, skillId, reqSkillValue, skillValue);
if (res != SPELL_CAST_OK)
{
SendCastResult(res);
return;
}
if (gameObjTarget)
SendLoot(guid, LOOT_SKINNING);
else if (itemTarget)
{
itemTarget->SetFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_UNLOCKED);
itemTarget->SetState(ITEM_CHANGED, itemTarget->GetOwner());
}
// not allow use skill grow at item base open
if (!m_CastItem && skillId != SKILL_NONE)
{
// update skill if really known
if (uint32 pureSkillValue = player->GetPureSkillValue(skillId))
{
if (gameObjTarget)
{
// Allow one skill-up until respawned
if (!gameObjTarget->IsInSkillupList(player->GetGUID().GetCounter()) &&
player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue))
gameObjTarget->AddToSkillupList(player->GetGUID().GetCounter());
}
else if (itemTarget)
{
// Do one skill-up
player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue);
}
}
}
ExecuteLogEffectOpenLock(effectInfo->EffectIndex, gameObjTarget ? (Object*)gameObjTarget : (Object*)itemTarget);
}
void Spell::EffectSummonChangeItem()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = m_caster->ToPlayer();
// applied only to using item
if (!m_CastItem)
return;
// ... only to item in own inventory/bank/equip_slot
if (m_CastItem->GetOwnerGUID() != player->GetGUID())
return;
uint32 newitemid = effectInfo->ItemType;
if (!newitemid)
return;
uint16 pos = m_CastItem->GetPos();
Item* pNewItem = Item::CreateItem(newitemid, 1, player);
if (!pNewItem)
return;
for (uint8 j = PERM_ENCHANTMENT_SLOT; j <= TEMP_ENCHANTMENT_SLOT; ++j)
if (m_CastItem->GetEnchantmentId(EnchantmentSlot(j)))
pNewItem->SetEnchantment(EnchantmentSlot(j), m_CastItem->GetEnchantmentId(EnchantmentSlot(j)), m_CastItem->GetEnchantmentDuration(EnchantmentSlot(j)), m_CastItem->GetEnchantmentCharges(EnchantmentSlot(j)));
if (m_CastItem->GetUInt32Value(ITEM_FIELD_DURABILITY) < m_CastItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY))
{
double lossPercent = 1 - m_CastItem->GetUInt32Value(ITEM_FIELD_DURABILITY) / double(m_CastItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY));
player->DurabilityLoss(pNewItem, lossPercent);
}
if (player->IsInventoryPos(pos))
{
ItemPosCountVec dest;
InventoryResult msg = player->CanStoreItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true);
if (msg == EQUIP_ERR_OK)
{
player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true);
// prevent crash at access and unexpected charges counting with item update queue corrupt
if (m_CastItem == m_targets.GetItemTarget())
m_targets.SetItemTarget(nullptr);
m_CastItem = nullptr;
m_castItemGUID.Clear();
m_castItemEntry = 0;
player->StoreItem(dest, pNewItem, true);
player->SendNewItem(pNewItem, 1, true, false);
player->ItemAddedQuestCheck(newitemid, 1);
return;
}
}
else if (player->IsBankPos(pos))
{
ItemPosCountVec dest;
if (player->CanBankItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true) == EQUIP_ERR_OK)
{
player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true);
// prevent crash at access and unexpected charges counting with item update queue corrupt
if (m_CastItem == m_targets.GetItemTarget())
m_targets.SetItemTarget(nullptr);
m_CastItem = nullptr;
m_castItemGUID.Clear();
m_castItemEntry = 0;
player->BankItem(dest, pNewItem, true);
return;
}
}
else if (player->IsEquipmentPos(pos))
{
uint16 dest;
player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true);
InventoryResult msg = player->CanEquipItem(m_CastItem->GetSlot(), dest, pNewItem, true);
if (msg == EQUIP_ERR_OK || msg == EQUIP_ERR_CANT_DO_RIGHT_NOW)
{
if (msg == EQUIP_ERR_CANT_DO_RIGHT_NOW) dest = EQUIPMENT_SLOT_MAINHAND;
// prevent crash at access and unexpected charges counting with item update queue corrupt
if (m_CastItem == m_targets.GetItemTarget())
m_targets.SetItemTarget(nullptr);
m_CastItem = nullptr;
m_castItemGUID.Clear();
m_castItemEntry = 0;
player->EquipItem(dest, pNewItem, true);
player->AutoUnequipOffhandIfNeed();
player->SendNewItem(pNewItem, 1, true, false);
player->ItemAddedQuestCheck(newitemid, 1);
return;
}
}
// fail
delete pNewItem;
}
void Spell::EffectProficiency()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* p_target = m_caster->ToPlayer();
uint32 subClassMask = m_spellInfo->EquippedItemSubClassMask;
if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && !(p_target->GetWeaponProficiency() & subClassMask))
{
p_target->AddWeaponProficiency(subClassMask);
p_target->SendProficiency(ITEM_CLASS_WEAPON, p_target->GetWeaponProficiency());
}
if (m_spellInfo->EquippedItemClass == ITEM_CLASS_ARMOR && !(p_target->GetArmorProficiency() & subClassMask))
{
p_target->AddArmorProficiency(subClassMask);
p_target->SendProficiency(ITEM_CLASS_ARMOR, p_target->GetArmorProficiency());
}
}
void Spell::EffectSummonType()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
uint32 entry = effectInfo->MiscValue;
if (!entry)
return;
SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(effectInfo->MiscValueB);
if (!properties)
{
TC_LOG_ERROR("spells", "EffectSummonType: Unhandled summon type %u.", effectInfo->MiscValueB);
return;
}
WorldObject* caster = m_caster;
if (m_originalCaster)
caster = m_originalCaster;
bool personalSpawn = (properties->Flags & SUMMON_PROP_FLAG_PERSONAL_SPAWN) != 0;
int32 duration = m_spellInfo->GetDuration();
if (Player* modOwner = caster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
Unit* unitCaster = GetUnitCasterForEffectHandlers();
TempSummon* summon = nullptr;
// determine how many units should be summoned
uint32 numSummons;
// some spells need to summon many units, for those spells number of summons is stored in effect value
// however so far noone found a generic check to find all of those (there's no related data in summonproperties.dbc
// and in spell attributes, possibly we need to add a table for those)
// so here's a list of MiscValueB values, which is currently most generic check
switch (properties->ID)
{
case 64:
case 61:
case 1101:
case 66:
case 648:
case 2301:
case 1061:
case 1261:
case 629:
case 181:
case 715:
case 1562:
case 833:
case 1161:
case 713:
numSummons = (damage > 0) ? damage : 1;
break;
default:
numSummons = 1;
break;
}
switch (properties->Control)
{
case SUMMON_CATEGORY_WILD:
case SUMMON_CATEGORY_ALLY:
case SUMMON_CATEGORY_UNK:
{
if (properties->Flags & 512)
{
SummonGuardian(*effectInfo, entry, properties, numSummons);
break;
}
switch (properties->Title)
{
case SUMMON_TYPE_PET:
case SUMMON_TYPE_GUARDIAN:
case SUMMON_TYPE_GUARDIAN2:
case SUMMON_TYPE_MINION:
SummonGuardian(*effectInfo, entry, properties, numSummons);
break;
// Summons a vehicle, but doesn't force anyone to enter it (see SUMMON_CATEGORY_VEHICLE)
case SUMMON_TYPE_VEHICLE:
case SUMMON_TYPE_VEHICLE2:
{
if (!unitCaster)
return;
summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id);
break;
}
case SUMMON_TYPE_LIGHTWELL:
case SUMMON_TYPE_TOTEM:
{
if (!unitCaster)
return;
summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id, 0, personalSpawn);
if (!summon || !summon->IsTotem())
return;
// Mana Tide Totem
if (m_spellInfo->Id == 16190)
damage = unitCaster->CountPctFromMaxHealth(10);
if (damage) // if not spell info, DB values used
{
summon->SetMaxHealth(damage);
summon->SetHealth(damage);
}
break;
}
case SUMMON_TYPE_MINIPET:
{
if (!unitCaster)
return;
summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id, 0, personalSpawn);
if (!summon || !summon->HasUnitTypeMask(UNIT_MASK_MINION))
return;
summon->SelectLevel(); // some summoned creaters have different from 1 DB data for level/hp
summon->SetUInt32Value(UNIT_NPC_FLAGS, summon->GetCreatureTemplate()->npcflag);
summon->SetImmuneToAll(true);
break;
}
default:
{
float radius = effectInfo->CalcRadius();
TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN;
for (uint32 count = 0; count < numSummons; ++count)
{
Position pos;
if (count == 0)
pos = *destTarget;
else
// randomize position for multiple summons
pos = caster->GetRandomPoint(*destTarget, radius);
summon = caster->SummonCreature(entry, pos, summonType, Milliseconds(duration), 0, m_spellInfo->Id, personalSpawn);
if (!summon)
continue;
if (properties->Control == SUMMON_CATEGORY_ALLY)
{
summon->SetOwnerGUID(caster->GetGUID());
summon->SetFaction(caster->GetFaction());
}
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, summon);
}
return;
}
}
break;
}
case SUMMON_CATEGORY_PET:
SummonGuardian(*effectInfo, entry, properties, numSummons);
break;
case SUMMON_CATEGORY_PUPPET:
{
if (!unitCaster)
return;
summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id, 0, personalSpawn);
break;
}
case SUMMON_CATEGORY_VEHICLE:
{
if (!unitCaster)
return;
// Summoning spells (usually triggered by npc_spellclick) that spawn a vehicle and that cause the clicker
// to cast a ride vehicle spell on the summoned unit.
summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id);
if (!summon || !summon->IsVehicle())
return;
// The spell that this effect will trigger. It has SPELL_AURA_CONTROL_VEHICLE
uint32 spellId = VEHICLE_SPELL_RIDE_HARDCODED;
int32 basePoints = effectInfo->CalcValue();
if (basePoints > MAX_VEHICLE_SEATS)
{
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(basePoints);
if (spellInfo && spellInfo->HasAura(SPELL_AURA_CONTROL_VEHICLE))
spellId = spellInfo->Id;
}
CastSpellExtraArgs args(TRIGGERED_FULL_MASK);
// if we have small value, it indicates seat position
if (basePoints > 0 && basePoints < MAX_VEHICLE_SEATS)
args.AddSpellMod(SPELLVALUE_BASE_POINT0, basePoints);
unitCaster->CastSpell(summon, spellId, args);
uint32 faction = properties->Faction;
if (!faction)
faction = unitCaster->GetFaction();
summon->SetFaction(faction);
break;
}
}
if (summon)
{
summon->SetCreatorGUID(caster->GetGUID());
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, summon);
}
}
void Spell::EffectLearnSpell()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (unitTarget->GetTypeId() != TYPEID_PLAYER)
{
if (unitTarget->ToPet())
EffectLearnPetSpell();
return;
}
Player* player = unitTarget->ToPlayer();
uint32 spellToLearn = (m_spellInfo->Id == 483 || m_spellInfo->Id == 55884) ? damage : effectInfo->TriggerSpell;
player->LearnSpell(spellToLearn, false);
TC_LOG_DEBUG("spells", "Spell: Player %s has learned spell %u from Npc %s", player->GetGUID().ToString().c_str(), spellToLearn, m_caster->GetGUID().ToString().c_str());
}
void Spell::EffectDispel()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
// Create dispel mask by dispel type
uint32 dispel_type = effectInfo->MiscValue;
uint32 dispelMask = SpellInfo::GetDispelMask(DispelType(dispel_type));
DispelChargesList dispelList;
unitTarget->GetDispellableAuraList(m_caster, dispelMask, dispelList, targetMissInfo == SPELL_MISS_REFLECT);
if (dispelList.empty())
return;
size_t remaining = dispelList.size();
// Ok if exist some buffs for dispel try dispel it
uint32 failCount = 0;
DispelChargesList successList;
successList.reserve(damage);
WorldPacket dataFail(SMSG_DISPEL_FAILED, 8 + 8 + 4 + 4 + damage * 4);
// dispel N = damage buffs (or while exist buffs for dispel)
for (int32 count = 0; count < damage && remaining > 0;)
{
// Random select buff for dispel
auto itr = dispelList.begin();
std::advance(itr, urand(0, remaining - 1));
if (itr->RollDispel())
{
auto successItr = std::find_if(successList.begin(), successList.end(), [&itr](DispelableAura& dispelAura) -> bool
{
if (dispelAura.GetAura()->GetId() == itr->GetAura()->GetId() && dispelAura.GetAura()->GetCaster() == itr->GetAura()->GetCaster())
return true;
return false;
});
if (successItr == successList.end())
successList.emplace_back(itr->GetAura(), 0, 1);
else
successItr->IncrementCharges();
if (!itr->DecrementCharge())
{
--remaining;
std::swap(*itr, dispelList[remaining]);
}
}
else
{
if (!failCount)
{
// Failed to dispell
dataFail << uint64(m_caster->GetGUID()); // Caster GUID
dataFail << uint64(unitTarget->GetGUID()); // Victim GUID
dataFail << uint32(m_spellInfo->Id); // dispel spell id
}
++failCount;
dataFail << uint32(itr->GetAura()->GetId()); // Spell Id
}
++count;
}
if (failCount)
m_caster->SendMessageToSet(&dataFail, true);
if (successList.empty())
return;
WorldPacket dataSuccess(SMSG_SPELLDISPELLOG, 8 + 8 + 4 + 1 + 4 + successList.size() * 5);
// Send packet header
dataSuccess << unitTarget->GetPackGUID(); // Victim GUID
dataSuccess << m_caster->GetPackGUID(); // Caster GUID
dataSuccess << uint32(m_spellInfo->Id); // dispel spell id
dataSuccess << uint8(0); // not used
dataSuccess << uint32(successList.size()); // count
for (DispelChargesList::iterator itr = successList.begin(); itr != successList.end(); ++itr)
{
// Send dispelled spell info
dataSuccess << uint32(itr->GetAura()->GetId()); // Spell Id
dataSuccess << uint8(0); // 0 - dispelled !=0 cleansed
unitTarget->RemoveAurasDueToSpellByDispel(itr->GetAura()->GetId(), m_spellInfo->Id, itr->GetAura()->GetCasterGUID(), m_caster, itr->GetDispelCharges());
}
m_caster->SendMessageToSet(&dataSuccess, true);
// On success dispel
// Devour Magic
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->GetCategory() == SPELLCATEGORY_DEVOUR_MAGIC)
{
CastSpellExtraArgs args(TRIGGERED_FULL_MASK);
args.AddSpellMod(SPELLVALUE_BASE_POINT0, m_spellInfo->GetEffect(EFFECT_1).CalcValue());
m_caster->CastSpell(m_caster, 19658, args);
// Glyph of Felhunter
if (Unit* owner = m_caster->GetOwner())
if (owner->GetAura(56249))
owner->CastSpell(owner, 19658, args);
}
}
void Spell::EffectDualWield()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
unitTarget->SetCanDualWield(true);
}
void Spell::EffectPull()
{
/// @todo create a proper pull towards distract spell center for distract
EffectNULL();
}
void Spell::EffectDistract()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
// Check for possible target
if (!unitTarget || unitTarget->IsEngaged())
return;
// target must be OK to do this
if (unitTarget->HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING))
return;
unitTarget->GetMotionMaster()->MoveDistract(damage * IN_MILLISECONDS, unitTarget->GetAbsoluteAngle(destTarget));
}
void Spell::EffectPickPocket()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
// victim must be creature and attackable
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->IsFriendlyTo(unitTarget))
return;
// victim have to be alive and humanoid or undead
if (unitTarget->IsAlive() && (unitTarget->GetCreatureTypeMask() &CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) != 0)
m_caster->ToPlayer()->SendLoot(unitTarget->GetGUID(), LOOT_PICKPOCKETING);
}
void Spell::EffectAddFarsight()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
float radius = effectInfo->CalcRadius();
int32 duration = m_spellInfo->GetDuration();
// Caster not in world, might be spell triggered from aura removal
if (!player->IsInWorld())
return;
DynamicObject* dynObj = new DynamicObject(true);
if (!dynObj->CreateDynamicObject(player->GetMap()->GenerateLowGuid<HighGuid::DynamicObject>(), player, m_spellInfo->Id, *destTarget, radius, DYNAMIC_OBJECT_FARSIGHT_FOCUS))
{
delete dynObj;
return;
}
dynObj->SetDuration(duration);
dynObj->SetCasterViewpoint();
}
void Spell::EffectUntrainTalents()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || m_caster->GetTypeId() == TYPEID_PLAYER)
return;
if (ObjectGuid guid = m_caster->GetGUID()) // the trainer is the caster
unitTarget->ToPlayer()->SendTalentWipeConfirm(guid);
}
void Spell::EffectTeleUnitsFaceCaster()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (unitTarget->IsInFlight())
return;
if (m_targets.HasDst())
unitTarget->NearTeleportTo(destTarget->GetPositionX(), destTarget->GetPositionY(), destTarget->GetPositionZ(), destTarget->GetAbsoluteAngle(m_caster), unitTarget == m_caster);
}
void Spell::EffectLearnSkill()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
if (damage < 0)
return;
uint32 skillid = effectInfo->MiscValue;
SkillRaceClassInfoEntry const* rcEntry = GetSkillRaceClassInfo(skillid, unitTarget->GetRace(), unitTarget->GetClass());
if (!rcEntry)
return;
SkillTiersEntry const* tier = sSkillTiersStore.LookupEntry(rcEntry->SkillTierID);
if (!tier)
return;
uint16 skillval = unitTarget->ToPlayer()->GetPureSkillValue(skillid);
unitTarget->ToPlayer()->SetSkill(skillid, effectInfo->CalcValue(), std::max<uint16>(skillval, 1), tier->Value[damage - 1]);
}
void Spell::EffectAddHonor()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
// not scale value for item based reward (/10 value expected)
if (m_CastItem)
{
unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage/10);
TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %d honor points (item %u) for player %s", m_spellInfo->Id, damage/10, m_CastItem->GetEntry(), unitTarget->ToPlayer()->GetGUID().ToString().c_str());
return;
}
// do not allow to add too many honor for player (50 * 21) = 1040 at level 70, or (50 * 31) = 1550 at level 80
if (damage <= 50)
{
uint32 honor_reward = Trinity::Honor::hk_honor_at_level(unitTarget->GetLevel(), float(damage));
unitTarget->ToPlayer()->RewardHonor(nullptr, 1, honor_reward);
TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %u honor points (scale) to player %s", m_spellInfo->Id, honor_reward, unitTarget->ToPlayer()->GetGUID().ToString().c_str());
}
else
{
//maybe we have correct honor_gain in damage already
unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage);
TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %u honor points (non scale) for player %s", m_spellInfo->Id, damage, unitTarget->ToPlayer()->GetGUID().ToString().c_str());
}
}
void Spell::EffectTradeSkill()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
// uint32 skillid = effectInfo->MiscValue;
// uint16 skillmax = unitTarget->ToPlayer()->(skillid);
// m_caster->ToPlayer()->SetSkill(skillid, skillval?skillval:1, skillmax+75);
}
void Spell::EffectEnchantItemPerm()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!itemTarget)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
// Handle vellums
if (itemTarget->IsWeaponVellum() || itemTarget->IsArmorVellum())
{
// destroy one vellum from stack
uint32 count = 1;
player->DestroyItemCount(itemTarget, count, true);
unitTarget = player;
// and add a scroll
DoCreateItem(effectInfo->ItemType);
itemTarget = nullptr;
m_targets.SetItemTarget(nullptr);
}
else
{
// do not increase skill if vellum used
if (!(m_CastItem && m_CastItem->GetTemplate()->HasFlag(ITEM_FLAG_NO_REAGENT_COST)))
player->UpdateCraftSkill(m_spellInfo->Id);
uint32 enchant_id = effectInfo->MiscValue;
if (!enchant_id)
return;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return;
// item can be in trade slot and have owner diff. from caster
Player* item_owner = itemTarget->GetOwner();
if (!item_owner)
return;
if (item_owner != player && player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE))
{
sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) enchanting(perm): %s (Entry: %d) for player: %s (Account: %u)",
player->GetName().c_str(), player->GetSession()->GetAccountId(),
itemTarget->GetTemplate()->Name1.c_str(), itemTarget->GetEntry(),
item_owner->GetName().c_str(), item_owner->GetSession()->GetAccountId());
}
// remove old enchanting before applying new if equipped
item_owner->ApplyEnchantment(itemTarget, PERM_ENCHANTMENT_SLOT, false);
itemTarget->SetEnchantment(PERM_ENCHANTMENT_SLOT, enchant_id, 0, 0, m_caster->GetGUID());
// add new enchanting if equipped
item_owner->ApplyEnchantment(itemTarget, PERM_ENCHANTMENT_SLOT, true);
item_owner->RemoveTradeableItem(itemTarget);
itemTarget->ClearSoulboundTradeable(item_owner);
}
}
void Spell::EffectEnchantItemPrismatic()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!itemTarget)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
uint32 enchantId = effectInfo->MiscValue;
if (!enchantId)
return;
SpellItemEnchantmentEntry const* enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId);
if (!enchant)
return;
// support only enchantings with add socket in this slot
{
bool add_socket = false;
for (uint8 i = 0; i < MAX_ITEM_ENCHANTMENT_EFFECTS; ++i)
{
if (enchant->Effect[i] == ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET)
{
add_socket = true;
break;
}
}
if (!add_socket)
{
TC_LOG_ERROR("spells", "Spell::EffectEnchantItemPrismatic: attempt to apply the enchant spell %u with SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC (%u), but without ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET (%u), not supported yet.",
m_spellInfo->Id, SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC, ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET);
return;
}
}
// item can be in trade slot and have owner diff. from caster
Player* item_owner = itemTarget->GetOwner();
if (!item_owner)
return;
if (item_owner != player && player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE))
{
sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) enchanting(perm): %s (Entry: %d) for player: %s (Account: %u)",
player->GetName().c_str(), player->GetSession()->GetAccountId(),
itemTarget->GetTemplate()->Name1.c_str(), itemTarget->GetEntry(),
item_owner->GetName().c_str(), item_owner->GetSession()->GetAccountId());
}
// remove old enchanting before applying new if equipped
item_owner->ApplyEnchantment(itemTarget, PRISMATIC_ENCHANTMENT_SLOT, false);
itemTarget->SetEnchantment(PRISMATIC_ENCHANTMENT_SLOT, enchantId, 0, 0, m_caster->GetGUID());
// add new enchanting if equipped
item_owner->ApplyEnchantment(itemTarget, PRISMATIC_ENCHANTMENT_SLOT, true);
item_owner->RemoveTradeableItem(itemTarget);
itemTarget->ClearSoulboundTradeable(item_owner);
}
void Spell::EffectEnchantItemTmp()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
// Rockbiter Weapon apply to both weapon
if (!itemTarget)
return;
if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & 0x400000)
{
uint32 spell_id = 0;
// enchanting spell selected by calculated damage-per-sec stored in Effect[1] base value
// Note: damage calculated (correctly) with rounding int32(float(v)) but
// RW enchantments applied damage int32(float(v)+0.5), this create 0..1 difference sometime
switch (damage)
{
// Rank 1
case 2: spell_id = 36744; break; // 0% [ 7% == 2, 14% == 2, 20% == 2]
// Rank 2
case 4: spell_id = 36753; break; // 0% [ 7% == 4, 14% == 4]
case 5: spell_id = 36751; break; // 20%
// Rank 3
case 6: spell_id = 36754; break; // 0% [ 7% == 6, 14% == 6]
case 7: spell_id = 36755; break; // 20%
// Rank 4
case 9: spell_id = 36761; break; // 0% [ 7% == 6]
case 10: spell_id = 36758; break; // 14%
case 11: spell_id = 36760; break; // 20%
default:
TC_LOG_ERROR("spells", "Spell::EffectEnchantItemTmp: Damage %u not handled in S'RW.", damage);
return;
}
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
if (!spellInfo)
{
TC_LOG_ERROR("spells", "Spell::EffectEnchantItemTmp: unknown spell id %i", spell_id);
return;
}
for (int j = BASE_ATTACK; j <= OFF_ATTACK; ++j)
{
if (Item* item = player->GetWeaponForAttack(WeaponAttackType(j)))
{
if (item->IsFitToSpellRequirements(m_spellInfo))
{
Spell* spell = new Spell(m_caster, spellInfo, TRIGGERED_FULL_MASK);
SpellCastTargets targets;
targets.SetItemTarget(item);
spell->prepare(targets);
}
}
}
return;
}
uint32 enchant_id = effectInfo->MiscValue;
if (!enchant_id)
{
TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) has enchanting id 0.", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
return;
}
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
{
TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) has a non-existing enchanting id %u ", m_spellInfo->Id, uint32(effectInfo->EffectIndex), enchant_id);
return;
}
// select enchantment duration
uint32 duration;
// rogue family enchantments exception by duration
if (m_spellInfo->Id == 38615)
duration = 1800; // 30 mins
// other rogue family enchantments always 1 hour (some have spell damage=0, but some have wrong data in EffBasePoints)
else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE)
duration = 3600; // 1 hour
// shaman family enchantments
else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN)
duration = 1800; // 30 mins
// other cases with this SpellVisual already selected
else if (m_spellInfo->SpellVisual[0] == 215)
duration = 1800; // 30 mins
// some fishing pole bonuses except Glow Worm which lasts full hour
else if (m_spellInfo->SpellVisual[0] == 563 && m_spellInfo->Id != 64401)
duration = 600; // 10 mins
// shaman rockbiter enchantments
else if (m_spellInfo->SpellVisual[0] == 0)
duration = 1800; // 30 mins
else if (m_spellInfo->Id == 29702)
duration = 300; // 5 mins
else if (m_spellInfo->Id == 37360)
duration = 300; // 5 mins
// default case
else
duration = 3600; // 1 hour
// item can be in trade slot and have owner diff. from caster
Player* item_owner = itemTarget->GetOwner();
if (!item_owner)
return;
if (item_owner != player && player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE))
{
sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) enchanting(temp): %s (Entry: %d) for player: %s (Account: %u)",
player->GetName().c_str(), player->GetSession()->GetAccountId(),
itemTarget->GetTemplate()->Name1.c_str(), itemTarget->GetEntry(),
item_owner->GetName().c_str(), item_owner->GetSession()->GetAccountId());
}
// remove old enchanting before applying new if equipped
item_owner->ApplyEnchantment(itemTarget, TEMP_ENCHANTMENT_SLOT, false);
itemTarget->SetEnchantment(TEMP_ENCHANTMENT_SLOT, enchant_id, duration * 1000, 0, m_caster->GetGUID());
// add new enchanting if equipped
item_owner->ApplyEnchantment(itemTarget, TEMP_ENCHANTMENT_SLOT, true);
}
void Spell::EffectTameCreature()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster || unitCaster->GetPetGUID())
return;
if (!unitTarget)
return;
if (unitTarget->GetTypeId() != TYPEID_UNIT)
return;
Creature* creatureTarget = unitTarget->ToCreature();
if (creatureTarget->IsPet())
return;
if (unitCaster->GetClass() != CLASS_HUNTER)
return;
// cast finish successfully
//SendChannelUpdate(0);
finish();
Pet* pet = unitCaster->CreateTamedPetFrom(creatureTarget, m_spellInfo->Id);
if (!pet) // in very specific state like near world end/etc.
return;
// "kill" original creature
creatureTarget->DespawnOrUnsummon();
uint8 level = (creatureTarget->GetLevel() < (unitCaster->GetLevel() - 5)) ? (unitCaster->GetLevel() - 5) : creatureTarget->GetLevel();
// prepare visual effect for levelup
pet->SetUInt32Value(UNIT_FIELD_LEVEL, level - 1);
// add to world
pet->GetMap()->AddToMap(pet->ToCreature());
// visual effect for levelup
pet->SetUInt32Value(UNIT_FIELD_LEVEL, level);
// caster have pet now
unitCaster->SetMinion(pet, true);
pet->InitTalentForLevel();
if (unitCaster->GetTypeId() == TYPEID_PLAYER)
{
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
unitCaster->ToPlayer()->PetSpellInitialize();
}
}
void Spell::EffectSummonPet()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Player* owner = nullptr;
if (Unit* unitCaster = GetUnitCasterForEffectHandlers())
{
owner = unitCaster->ToPlayer();
if (!owner && unitCaster->IsTotem())
owner = unitCaster->GetCharmerOrOwnerPlayerOrPlayerItself();
}
uint32 petentry = effectInfo->MiscValue;
if (!owner)
{
SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(67);
if (properties)
SummonGuardian(*effectInfo, petentry, properties, 1);
return;
}
Pet* OldSummon = owner->GetPet();
// if pet requested type already exist
if (OldSummon)
{
if (petentry == 0 || OldSummon->GetEntry() == petentry)
{
// pet in corpse state can't be summoned
if (OldSummon->isDead())
return;
ASSERT(OldSummon->GetMap() == owner->GetMap());
//OldSummon->GetMap()->Remove(OldSummon->ToCreature(), false);
float px, py, pz;
owner->GetClosePoint(px, py, pz, OldSummon->GetCombatReach());
OldSummon->NearTeleportTo(px, py, pz, OldSummon->GetOrientation());
//OldSummon->Relocate(px, py, pz, OldSummon->GetOrientation());
//OldSummon->SetMap(owner->GetMap());
//owner->GetMap()->Add(OldSummon->ToCreature());
if (OldSummon->getPetType() == SUMMON_PET)
{
OldSummon->SetHealth(OldSummon->GetMaxHealth());
OldSummon->SetPower(OldSummon->GetPowerType(), OldSummon->GetMaxPower(OldSummon->GetPowerType()));
OldSummon->GetSpellHistory()->ResetAllCooldowns();
}
if (owner->GetTypeId() == TYPEID_PLAYER && OldSummon->isControlled())
owner->ToPlayer()->PetSpellInitialize();
return;
}
if (owner->GetTypeId() == TYPEID_PLAYER)
owner->ToPlayer()->RemovePet(OldSummon, PET_SAVE_NOT_IN_SLOT, false);
else
return;
}
float x, y, z;
owner->GetClosePoint(x, y, z, owner->GetCombatReach());
Pet* pet = owner->SummonPet(petentry, x, y, z, owner->GetOrientation(), SUMMON_PET, 0);
if (!pet)
return;
if (m_caster->GetTypeId() == TYPEID_UNIT)
{
if (m_caster->ToCreature()->IsTotem())
pet->SetReactState(REACT_AGGRESSIVE);
else
pet->SetReactState(REACT_DEFENSIVE);
}
pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id);
// generate new name for summon pet
std::string new_name = sObjectMgr->GeneratePetName(petentry);
if (!new_name.empty())
pet->SetName(new_name);
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pet);
}
void Spell::EffectLearnPetSpell()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (unitTarget->ToPlayer())
{
EffectLearnSpell();
return;
}
Pet* pet = unitTarget->ToPet();
if (!pet)
return;
SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(effectInfo->TriggerSpell);
if (!learn_spellproto)
return;
pet->learnSpell(learn_spellproto->Id);
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
pet->GetOwner()->PetSpellInitialize();
}
void Spell::EffectTaunt()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
// this effect use before aura Taunt apply for prevent taunt already attacking target
// for spell as marked "non effective at already attacking target"
if (!unitTarget || unitTarget->IsTotem())
{
SendCastResult(SPELL_FAILED_DONT_REPORT);
return;
}
// Hand of Reckoning can hit some entities that can't have a threat list (including players' pets)
if (m_spellInfo->Id == 62124)
if (unitTarget->GetTypeId() != TYPEID_PLAYER && unitTarget->GetTarget() != unitCaster->GetGUID())
unitCaster->CastSpell(unitTarget, 67485, true);
if (!unitTarget->CanHaveThreatList())
{
SendCastResult(SPELL_FAILED_DONT_REPORT);
return;
}
ThreatManager& mgr = unitTarget->GetThreatManager();
if (mgr.GetCurrentVictim() == unitCaster)
{
SendCastResult(SPELL_FAILED_DONT_REPORT);
return;
}
if (!mgr.IsThreatListEmpty())
// Set threat equal to highest threat currently on target
mgr.MatchUnitThreatToHighestThreat(unitCaster);
}
void Spell::EffectWeaponDmg()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (!unitTarget || !unitTarget->IsAlive())
return;
// multiple weapon dmg effect workaround
// execute only the last weapon damage
// and handle all effects at once
for (size_t j = effectInfo->EffectIndex + 1; j < m_spellInfo->GetEffects().size(); ++j)
{
switch (m_spellInfo->GetEffect(SpellEffIndex(j)).Effect)
{
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
return; // we must calculate only at last weapon effect
default:
break;
}
}
// some spell specific modifiers
float totalDamagePercentMod = 1.0f; // applied to final bonus+weapon damage
int32 fixed_bonus = 0;
int32 spell_bonus = 0; // bonus specific for spell
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_WARRIOR:
{
// Devastate (player ones)
if (m_spellInfo->SpellFamilyFlags[1] & 0x40)
{
unitCaster->CastSpell(unitTarget, 58567, true);
// 58388 - Glyph of Devastate dummy aura.
if (unitCaster->HasAura(58388))
unitCaster->CastSpell(unitTarget, 58567, true);
if (Aura* aur = unitTarget->GetAura(58567, unitCaster->GetGUID()))
fixed_bonus += (aur->GetStackAmount() - 1) * CalculateDamage(m_spellInfo->GetEffect(EFFECT_2)); // subtract 1 so fixed bonus is not applied twice
}
else if (m_spellInfo->SpellFamilyFlags[0] & 0x8000000) // Mocking Blow
{
if (unitTarget->IsImmunedToSpellEffect(m_spellInfo, m_spellInfo->GetEffect(EFFECT_1), unitCaster) || unitTarget->GetTypeId() == TYPEID_PLAYER)
{
m_damage = 0;
return;
}
}
break;
}
case SPELLFAMILY_ROGUE:
{
// Fan of Knives, Hemorrhage, Ghostly Strike
if ((m_spellInfo->SpellFamilyFlags[1] & 0x40000)
|| (m_spellInfo->SpellFamilyFlags[0] & 0x6000000))
{
// Hemorrhage
if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000)
AddComboPointGain(unitTarget, 1);
// 50% more damage with daggers
if (unitCaster->GetTypeId() == TYPEID_PLAYER)
if (Item* item = unitCaster->ToPlayer()->GetWeaponForAttack(m_attackType, true))
if (item->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER)
totalDamagePercentMod *= 1.5f;
}
// Mutilate (for each hand)
else if (m_spellInfo->SpellFamilyFlags[1] & 0x6)
{
bool found = false;
// fast check
if (unitTarget->HasAuraState(AURA_STATE_DEADLY_POISON, m_spellInfo, unitCaster))
found = true;
// full aura scan
else
{
Unit::AuraApplicationMap const& auras = unitTarget->GetAppliedAuras();
for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
if (itr->second->GetBase()->GetSpellInfo()->Dispel == DISPEL_POISON)
{
found = true;
break;
}
}
}
if (found)
totalDamagePercentMod *= 1.2f; // 120% if poisoned
}
break;
}
case SPELLFAMILY_PALADIN:
{
// Seal of Command Unleashed
if (m_spellInfo->Id == 20467)
{
spell_bonus += int32(0.08f * unitCaster->GetTotalAttackPowerValue(BASE_ATTACK));
spell_bonus += int32(0.13f * unitCaster->SpellBaseDamageBonusDone(m_spellInfo->GetSchoolMask()));
}
break;
}
case SPELLFAMILY_SHAMAN:
{
// Skyshatter Harness item set bonus
// Stormstrike
if (AuraEffect* aurEff = unitCaster->IsScriptOverriden(m_spellInfo, 5634))
unitCaster->CastSpell(nullptr, 38430, aurEff);
break;
}
case SPELLFAMILY_DRUID:
{
// Mangle (Cat): CP
if (m_spellInfo->SpellFamilyFlags[1] & 0x400)
AddComboPointGain(unitTarget, 1);
// Shred, Maul - Rend and Tear
else if (m_spellInfo->SpellFamilyFlags[0] & 0x00008800 && unitTarget->HasAuraState(AURA_STATE_BLEEDING))
{
if (AuraEffect const* rendAndTear = unitCaster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 0))
AddPct(totalDamagePercentMod, rendAndTear->GetAmount());
}
break;
}
case SPELLFAMILY_HUNTER:
{
// Kill Shot - bonus damage from Ranged Attack Power
if (m_spellInfo->SpellFamilyFlags[1] & 0x800000)
spell_bonus += int32(0.4f * unitCaster->GetTotalAttackPowerValue(RANGED_ATTACK));
break;
}
case SPELLFAMILY_DEATHKNIGHT:
{
// Plague Strike
if (m_spellInfo->SpellFamilyFlags[0] & 0x1)
{
// Glyph of Plague Strike
if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(58657, EFFECT_0))
AddPct(totalDamagePercentMod, aurEff->GetAmount());
break;
}
// Blood Strike
if (m_spellInfo->SpellFamilyFlags[0] & 0x400000)
{
float bonusPct = m_spellInfo->GetEffect(EFFECT_2).CalcValue() * unitTarget->GetDiseasesByCaster(unitCaster->GetGUID()) / 2.0f;
// Death Knight T8 Melee 4P Bonus
if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(64736, EFFECT_0))
AddPct(bonusPct, aurEff->GetAmount());
AddPct(totalDamagePercentMod, bonusPct);
// Glyph of Blood Strike
if (unitCaster->GetAuraEffect(59332, EFFECT_0))
if (unitTarget->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED))
AddPct(totalDamagePercentMod, 20);
break;
}
// Death Strike
if (m_spellInfo->SpellFamilyFlags[0] & 0x10)
{
// Glyph of Death Strike
if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(59336, EFFECT_0))
if (uint32 runic = std::min<uint32>(unitCaster->GetPower(POWER_RUNIC_POWER), aurEff->GetSpellInfo()->GetEffect(EFFECT_1).CalcValue()))
AddPct(totalDamagePercentMod, runic);
break;
}
// Obliterate (12.5% more damage per disease)
if (m_spellInfo->SpellFamilyFlags[1] & 0x20000)
{
bool consumeDiseases = true;
// Annihilation
if (AuraEffect const* aurEff = unitCaster->GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2710, EFFECT_0))
// Do not consume diseases if roll sucesses
if (roll_chance_i(aurEff->GetAmount()))
consumeDiseases = false;
float bonusPct = m_spellInfo->GetEffect(EFFECT_2).CalcValue() * unitTarget->GetDiseasesByCaster(unitCaster->GetGUID(), consumeDiseases) / 2.0f;
// Death Knight T8 Melee 4P Bonus
if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(64736, EFFECT_0))
AddPct(bonusPct, aurEff->GetAmount());
AddPct(totalDamagePercentMod, bonusPct);
break;
}
// Blood-Caked Strike - Blood-Caked Blade
if (m_spellInfo->SpellIconID == 1736)
{
AddPct(totalDamagePercentMod, unitTarget->GetDiseasesByCaster(unitCaster->GetGUID()) * 50.0f);
break;
}
// Heart Strike
if (m_spellInfo->SpellFamilyFlags[0] & 0x1000000)
{
float bonusPct = m_spellInfo->GetEffect(EFFECT_2).CalcValue() * unitTarget->GetDiseasesByCaster(unitCaster->GetGUID());
// Death Knight T8 Melee 4P Bonus
if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(64736, EFFECT_0))
AddPct(bonusPct, aurEff->GetAmount());<|fim▁hole|>
AddPct(totalDamagePercentMod, bonusPct);
break;
}
break;
}
}
bool normalized = false;
float weaponDamagePercentMod = 1.0f;
for (SpellEffectInfo const& spellEffectInfo : m_spellInfo->GetEffects())
{
switch (spellEffectInfo.Effect)
{
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
fixed_bonus += CalculateDamage(spellEffectInfo);
break;
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
fixed_bonus += CalculateDamage(spellEffectInfo);
normalized = true;
break;
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
ApplyPct(weaponDamagePercentMod, CalculateDamage(spellEffectInfo));
break;
default:
break; // not weapon damage effect, just skip
}
}
// if (addPctMods) { percent mods are added in Unit::CalculateDamage } else { percent mods are added in Unit::MeleeDamageBonusDone }
// this distinction is neccessary to properly inform the client about his autoattack damage values from Script_UnitDamage
bool const addPctMods = !m_spellInfo->HasAttribute(SPELL_ATTR6_LIMIT_PCT_DAMAGE_MODS) && (m_spellSchoolMask & SPELL_SCHOOL_MASK_NORMAL);
if (addPctMods)
{
UnitMods unitMod;
switch (m_attackType)
{
default:
case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
}
float weapon_total_pct = unitCaster->GetPctModifierValue(unitMod, TOTAL_PCT);
if (fixed_bonus)
fixed_bonus = int32(fixed_bonus * weapon_total_pct);
if (spell_bonus)
spell_bonus = int32(spell_bonus * weapon_total_pct);
}
int32 weaponDamage = unitCaster->CalculateDamage(m_attackType, normalized, addPctMods);
// Sequence is important
for (SpellEffectInfo const& spellEffectInfo : m_spellInfo->GetEffects())
{
// We assume that a spell have at most one fixed_bonus
// and at most one weaponDamagePercentMod
switch (spellEffectInfo.Effect)
{
case SPELL_EFFECT_WEAPON_DAMAGE:
case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL:
case SPELL_EFFECT_NORMALIZED_WEAPON_DMG:
weaponDamage += fixed_bonus;
break;
case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE:
weaponDamage = int32(weaponDamage * weaponDamagePercentMod);
break;
default:
break; // not weapon damage effect, just skip
}
}
weaponDamage += spell_bonus;
weaponDamage = int32(weaponDamage * totalDamagePercentMod);
// apply spellmod to Done damage
if (Player* modOwner = unitCaster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DAMAGE, weaponDamage);
// prevent negative damage
weaponDamage = std::max(weaponDamage, 0);
// Add melee damage bonuses (also check for negative)
weaponDamage = unitCaster->MeleeDamageBonusDone(unitTarget, weaponDamage, m_attackType, m_spellInfo);
m_damage += unitTarget->MeleeDamageBonusTaken(unitCaster, weaponDamage, m_attackType, m_spellInfo);
}
void Spell::EffectThreat()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster || !unitCaster->IsAlive())
return;
if (!unitTarget)
return;
if (!unitTarget->CanHaveThreatList())
return;
unitTarget->GetThreatManager().AddThreat(unitCaster, float(damage), m_spellInfo, true);
}
void Spell::EffectHealMaxHealth()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (!unitTarget || !unitTarget->IsAlive())
return;
int32 addhealth = 0;
// damage == 0 - heal for caster max health
if (damage == 0)
addhealth = unitCaster->GetMaxHealth();
else
addhealth = unitTarget->GetMaxHealth() - unitTarget->GetHealth();
m_healing += addhealth;
}
void Spell::EffectInterruptCast()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive())
return;
/// @todo not all spells that used this effect apply cooldown at school spells
// also exist case: apply cooldown to interrupted cast only and to all spells
// there is no CURRENT_AUTOREPEAT_SPELL spells that can be interrupted
for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_AUTOREPEAT_SPELL; ++i)
{
if (Spell* spell = unitTarget->GetCurrentSpell(CurrentSpellTypes(i)))
{
SpellInfo const* curSpellInfo = spell->m_spellInfo;
// check if we can interrupt spell
if ((spell->getState() == SPELL_STATE_CASTING
|| (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastTime() > 0.0f))
&& curSpellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE
&& ((i == CURRENT_GENERIC_SPELL && curSpellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT)
|| (i == CURRENT_CHANNELED_SPELL && curSpellInfo->ChannelInterruptFlags & CHANNEL_INTERRUPT_FLAG_INTERRUPT)))
{
if (Unit* unitCaster = GetUnitCasterForEffectHandlers())
{
int32 duration = m_spellInfo->GetDuration();
unitTarget->GetSpellHistory()->LockSpellSchool(curSpellInfo->GetSchoolMask(), unitTarget->ModSpellDuration(m_spellInfo, unitTarget, duration, false, 1 << effectInfo->EffectIndex));
if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC)
Unit::ProcSkillsAndAuras(unitCaster, unitTarget, PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG, PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG,
PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_HIT, PROC_HIT_INTERRUPT, nullptr, nullptr, nullptr);
else if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE)
Unit::ProcSkillsAndAuras(unitCaster, unitTarget, PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS, PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS,
PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_HIT, PROC_HIT_INTERRUPT, nullptr, nullptr, nullptr);
}
ExecuteLogEffectInterruptCast(effectInfo->EffectIndex, unitTarget, curSpellInfo->Id);
unitTarget->InterruptSpell(CurrentSpellTypes(i), false);
}
}
}
}
void Spell::EffectSummonObjectWild()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
uint32 gameobject_id = effectInfo->MiscValue;
GameObject* pGameObj = new GameObject();
WorldObject* target = focusObject;
if (!target)
target = m_caster;
float x, y, z;
if (m_targets.HasDst())
destTarget->GetPosition(x, y, z);
else
m_caster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS);
Map* map = target->GetMap();
QuaternionData rot = QuaternionData::fromEulerAnglesZYX(target->GetOrientation(), 0.f, 0.f);
if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, map, m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), rot, 255, GO_STATE_READY))
{
delete pGameObj;
return;
}
int32 duration = m_spellInfo->GetDuration();
pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0);
pGameObj->SetSpellId(m_spellInfo->Id);
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pGameObj);
// Wild object not have owner and check clickable by players
map->AddToMap(pGameObj);
if (pGameObj->GetGoType() == GAMEOBJECT_TYPE_FLAGDROP)
if (Player* player = m_caster->ToPlayer())
if (Battleground* bg = player->GetBattleground())
bg->SetDroppedFlagGUID(pGameObj->GetGUID(), player->GetTeam() == ALLIANCE ? TEAM_HORDE: TEAM_ALLIANCE);
if (GameObject* linkedTrap = pGameObj->GetLinkedTrap())
{
linkedTrap->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0);
linkedTrap->SetSpellId(m_spellInfo->Id);
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, linkedTrap);
}
}
void Spell::EffectScriptEffect()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
/// @todo we must implement hunter pet summon at login there (spell 6962)
/// @todo: move this to scripts
switch (m_spellInfo->SpellFamilyName)
{
case SPELLFAMILY_GENERIC:
{
switch (m_spellInfo->Id)
{
// Shadow Flame (All script effects, not just end ones to prevent player from dodging the last triggered spell)
case 22539:
case 22972:
case 22975:
case 22976:
case 22977:
case 22978:
case 22979:
case 22980:
case 22981:
case 22982:
case 22983:
case 22984:
case 22985:
{
if (!unitTarget || !unitTarget->IsAlive())
return;
// Onyxia Scale Cloak
if (unitTarget->HasAura(22683))
return;
// Shadow Flame
m_caster->CastSpell(unitTarget, 22682, true);
return;
}
// Mug Transformation
case 41931:
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
uint8 bag = 19;
uint8 slot = 0;
Item* item = nullptr;
while (bag) // 256 = 0 due to var type
{
item = m_caster->ToPlayer()->GetItemByPos(bag, slot);
if (item && item->GetEntry() == 38587)
break;
++slot;
if (slot == 39)
{
slot = 0;
++bag;
}
}
if (bag)
{
if (m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount() == 1) m_caster->ToPlayer()->RemoveItem(bag, slot, true);
else m_caster->ToPlayer()->GetItemByPos(bag, slot)->SetCount(m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount()-1);
// Spell 42518 (Braufest - Gratisprobe des Braufest herstellen)
m_caster->CastSpell(m_caster, 42518, true);
return;
}
break;
}
// Brutallus - Burn
case 45141:
case 45151:
{
//Workaround for Range ... should be global for every ScriptEffect
float radius = effectInfo->CalcRadius();
if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetDistance(m_caster) >= radius && !unitTarget->HasAura(46394) && unitTarget != m_caster)
unitTarget->CastSpell(unitTarget, 46394, true);
break;
}
// Summon Ghouls On Scarlet Crusade
case 51904:
{
if (!m_targets.HasDst())
return;
float x, y, z;
float radius = effectInfo->CalcRadius();
for (uint8 i = 0; i < 15; ++i)
{
m_caster->GetRandomPoint(*destTarget, radius, x, y, z);
m_caster->CastSpell({x, y, z}, 54522, true);
}
break;
}
case 52173: // Coyote Spirit Despawn
case 60243: // Blood Parrot Despawn
if (unitTarget->GetTypeId() == TYPEID_UNIT && unitTarget->IsSummon())
unitTarget->ToTempSummon()->UnSummon();
return;
case 57347: // Retrieving (Wintergrasp RP-GG pickup spell)
{
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToCreature()->DespawnOrUnsummon();
return;
}
case 57349: // Drop RP-GG (Wintergrasp RP-GG at death drop spell)
{
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
// Delete item from inventory at death
m_caster->ToPlayer()->DestroyItemCount(damage, 5, true);
return;
}
case 62482: // Grab Crate
{
if (!unitCaster)
return;
if (unitTarget)
{
if (Unit* seat = unitCaster->GetVehicleBase())
{
if (Unit* parent = seat->GetVehicleBase())
{
/// @todo a hack, range = 11, should after some time cast, otherwise too far
unitCaster->CastSpell(parent, 62496, true);
unitTarget->CastSpell(parent, m_spellInfo->GetEffect(EFFECT_0).CalcValue());
}
}
}
return;
}
}
break;
}
}
// normal DB scripted effect
TC_LOG_DEBUG("spells", "Spell ScriptStart spellid %u in EffectScriptEffect(%u)", m_spellInfo->Id, uint32(effectInfo->EffectIndex));
m_caster->GetMap()->ScriptsStart(sSpellScripts, uint32(m_spellInfo->Id | (effectInfo->EffectIndex << 24)), m_caster, unitTarget);
}
void Spell::EffectSanctuary()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (unitTarget->GetTypeId() == TYPEID_PLAYER && !unitTarget->GetMap()->IsDungeon())
{
// stop all pve combat for players outside dungeons, suppress pvp combat
unitTarget->CombatStop(false, false);
}
else
{
// in dungeons (or for nonplayers), reset this unit on all enemies' threat lists
for (auto const& pair : unitTarget->GetThreatManager().GetThreatenedByMeList())
pair.second->ScaleThreat(0.0f);
}
// makes spells cast before this time fizzle
unitTarget->m_lastSanctuaryTime = GameTime::GetGameTimeMS();
}
void Spell::EffectAddComboPoints()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (damage <= 0)
return;
AddComboPointGain(unitTarget, damage);
}
void Spell::EffectDuel()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || m_caster->GetTypeId() != TYPEID_PLAYER || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* caster = m_caster->ToPlayer();
Player* target = unitTarget->ToPlayer();
// caster or target already have requested duel
if (caster->duel || target->duel || !target->GetSocial() || target->GetSocial()->HasIgnore(caster->GetGUID()))
return;
// Players can only fight a duel in zones with this flag
AreaTableEntry const* casterAreaEntry = sAreaTableStore.LookupEntry(caster->GetAreaId());
if (casterAreaEntry && !(casterAreaEntry->Flags & AREA_FLAG_ALLOW_DUELS))
{
SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here
return;
}
AreaTableEntry const* targetAreaEntry = sAreaTableStore.LookupEntry(target->GetAreaId());
if (targetAreaEntry && !(targetAreaEntry->Flags & AREA_FLAG_ALLOW_DUELS))
{
SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here
return;
}
//CREATE DUEL FLAG OBJECT
GameObject* pGameObj = new GameObject;
uint32 gameobject_id = effectInfo->MiscValue;
Position const pos =
{
caster->GetPositionX() + (unitTarget->GetPositionX() - caster->GetPositionX()) / 2,
caster->GetPositionY() + (unitTarget->GetPositionY() - caster->GetPositionY()) / 2,
caster->GetPositionZ(),
caster->GetOrientation()
};
Map* map = caster->GetMap();
QuaternionData rot = QuaternionData::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f);
if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, map, caster->GetPhaseMask(), pos, rot, 0, GO_STATE_READY))
{
delete pGameObj;
return;
}
pGameObj->SetFaction(caster->GetFaction());
pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, caster->GetLevel() + 1);
int32 duration = m_spellInfo->GetDuration();
pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0);
pGameObj->SetSpellId(m_spellInfo->Id);
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pGameObj);
caster->AddGameObject(pGameObj);
map->AddToMap(pGameObj);
//END
// Send request
WorldPacket data(SMSG_DUEL_REQUESTED, 8 + 8);
data << uint64(pGameObj->GetGUID());
data << uint64(caster->GetGUID());
caster->SendDirectMessage(&data);
target->SendDirectMessage(&data);
// create duel-info
bool isMounted = (GetSpellInfo()->Id == 62875);
caster->duel = std::make_unique<DuelInfo>(target, caster, isMounted);
target->duel = std::make_unique<DuelInfo>(caster, caster, isMounted);
caster->SetGuidValue(PLAYER_DUEL_ARBITER, pGameObj->GetGUID());
target->SetGuidValue(PLAYER_DUEL_ARBITER, pGameObj->GetGUID());
sScriptMgr->OnPlayerDuelRequest(target, caster);
}
void Spell::EffectStuck()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (!sWorld->getBoolConfig(CONFIG_CAST_UNSTUCK))
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
TC_LOG_DEBUG("spells", "Spell Effect: Stuck");
TC_LOG_DEBUG("spells", "Player %s %s used the auto-unstuck feature at map %u (%f, %f, %f).", player->GetName().c_str(), player->GetGUID().ToString().c_str(), player->GetMapId(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ());
if (player->IsInFlight())
return;
// if player is dead - teleport to graveyard
if (!player->IsAlive())
{
if (player->HasAuraType(SPELL_AURA_PREVENT_RESURRECTION))
return;
// player is in corpse
if (!player->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
player->BuildPlayerRepop();
player->RepopAtGraveyard();
return;
}
// no hearthstone in bag or on cooldown
Item* hearthStone = player->GetItemByEntry(6948 /*Hearthstone*/);
if (!hearthStone || player->GetSpellHistory()->HasCooldown(8690 /*Spell Hearthstone*/))
{
float o = rand_norm() * 2 * M_PI;
Position pos = *player;
player->MovePositionToFirstCollision(pos, 5.0f, o);
player->NearTeleportTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), player->GetOrientation());
return;
}
// we have hearthstone not on cooldown, just use it
player->CastSpell(player, 8690, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD));
}
void Spell::EffectSummonPlayer()
{
// workaround - this effect should not use target map
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToPlayer()->SendSummonRequestFrom(unitCaster);
}
void Spell::EffectActivateObject()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!gameObjTarget)
return;
GameObjectActions action = GameObjectActions(effectInfo->MiscValue);
gameObjTarget->ActivateObject(action, m_caster, m_spellInfo->Id, int32(effectInfo->EffectIndex));
}
void Spell::EffectApplyGlyph()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_glyphIndex >= MAX_GLYPH_SLOT_INDEX)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
// glyph sockets level requirement
uint8 minLevel = 0;
switch (m_glyphIndex)
{
case 0:
case 1: minLevel = 15; break;
case 2: minLevel = 50; break;
case 3: minLevel = 30; break;
case 4: minLevel = 70; break;
case 5: minLevel = 80; break;
}
if (minLevel && player->GetLevel() < minLevel)
{
SendCastResult(SPELL_FAILED_GLYPH_SOCKET_LOCKED);
return;
}
// apply new one
if (uint32 glyph = effectInfo->MiscValue)
{
if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(player->GetGlyphSlot(m_glyphIndex)))
{
if (gp->GlyphSlotFlags != gs->Type)
{
SendCastResult(SPELL_FAILED_INVALID_GLYPH);
return; // glyph slot mismatch
}
}
// remove old glyph
if (uint32 oldglyph = player->GetGlyph(m_glyphIndex))
{
if (GlyphPropertiesEntry const* old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph))
{
player->RemoveAurasDueToSpell(old_gp->SpellID);
player->SetGlyph(m_glyphIndex, 0);
}
}
player->CastSpell(player, gp->SpellID, true);
player->SetGlyph(m_glyphIndex, glyph);
player->SendTalentsInfoData(false);
}
}
}
void Spell::EffectEnchantHeldItem()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
// this is only item spell effect applied to main-hand weapon of target player (players in area)
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* item_owner = unitTarget->ToPlayer();
Item* item = item_owner->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
if (!item)
return;
// must be equipped
if (!item->IsEquipped())
return;
if (effectInfo->MiscValue)
{
uint32 enchant_id = effectInfo->MiscValue;
int32 duration = m_spellInfo->GetDuration(); // Try duration index first ..
if (!duration)
duration = damage;//+1; // Base points after ..
if (!duration)
duration = 10 * IN_MILLISECONDS; // 10 seconds for enchants which don't have listed duration
if (m_spellInfo->Id == 14792) // Venomhide Poison
duration = 5 * MINUTE * IN_MILLISECONDS;
SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return;
// Always go to temp enchantment slot
EnchantmentSlot slot = TEMP_ENCHANTMENT_SLOT;
// Enchantment will not be applied if a different one already exists
if (item->GetEnchantmentId(slot) && item->GetEnchantmentId(slot) != enchant_id)
return;
// Apply the temporary enchantment
item->SetEnchantment(slot, enchant_id, duration, 0, m_caster->GetGUID());
item_owner->ApplyEnchantment(item, slot, true);
}
}
void Spell::EffectDisEnchant()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!itemTarget || !itemTarget->GetTemplate()->DisenchantID)
return;
if (Player* caster = m_caster->ToPlayer())
{
caster->UpdateCraftSkill(m_spellInfo->Id);
caster->SendLoot(itemTarget->GetGUID(), LOOT_DISENCHANTING);
}
// item will be removed at disenchanting end
}
void Spell::EffectInebriate()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
uint8 currentDrunk = player->GetDrunkValue();
uint8 drunkMod = damage;
if (currentDrunk + drunkMod > 100)
{
currentDrunk = 100;
if (rand_chance() < 25.0f)
player->CastSpell(player, 67468, false); // Drunken Vomit
}
else
currentDrunk += drunkMod;
player->SetDrunkValue(currentDrunk, m_CastItem ? m_CastItem->GetEntry() : 0);
}
void Spell::EffectFeedPet()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
Item* foodItem = itemTarget;
if (!foodItem)
return;
Pet* pet = player->GetPet();
if (!pet)
return;
if (!pet->IsAlive())
return;
int32 benefit = pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel);
if (benefit <= 0)
return;
ExecuteLogEffectDestroyItem(effectInfo->EffectIndex, foodItem->GetEntry());
uint32 count = 1;
player->DestroyItemCount(foodItem, count, true);
/// @todo fix crash when a spell has two effects, both pointed at the same item target
CastSpellExtraArgs args(TRIGGERED_FULL_MASK);
args.AddSpellMod(SPELLVALUE_BASE_POINT0, benefit);
m_caster->CastSpell(pet, effectInfo->TriggerSpell, args);
}
void Spell::EffectDismissPet()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsPet())
return;
Pet* pet = unitTarget->ToPet();
ExecuteLogEffectUnsummonObject(effectInfo->EffectIndex, pet);
pet->Remove(PET_SAVE_NOT_IN_SLOT);
}
void Spell::EffectSummonObject()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
uint32 go_id = effectInfo->MiscValue;
uint8 slot = effectInfo->Effect - SPELL_EFFECT_SUMMON_OBJECT_SLOT1;
if (ObjectGuid guid = unitCaster->m_ObjectSlot[slot])
{
if (GameObject* obj = unitCaster->GetMap()->GetGameObject(guid))
{
// Recast case - null spell id to make auras not be removed on object remove from world
if (m_spellInfo->Id == obj->GetSpellId())
obj->SetSpellId(0);
unitCaster->RemoveGameObject(obj, true);
}
unitCaster->m_ObjectSlot[slot].Clear();
}
GameObject* go = new GameObject();
float x, y, z;
// If dest location if present
if (m_targets.HasDst())
destTarget->GetPosition(x, y, z);
// Summon in random point all other units if location present
else
unitCaster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS);
Map* map = unitCaster->GetMap();
QuaternionData rot = QuaternionData::fromEulerAnglesZYX(unitCaster->GetOrientation(), 0.f, 0.f);
if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), go_id, map, unitCaster->GetPhaseMask(), Position(x, y, z, unitCaster->GetOrientation()), rot, 255, GO_STATE_READY))
{
delete go;
return;
}
go->SetFaction(unitCaster->GetFaction());
go->SetUInt32Value(GAMEOBJECT_LEVEL, unitCaster->GetLevel());
int32 duration = m_spellInfo->GetDuration();
go->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0);
go->SetSpellId(m_spellInfo->Id);
unitCaster->AddGameObject(go);
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, go);
map->AddToMap(go);
unitCaster->m_ObjectSlot[slot] = go->GetGUID();
}
void Spell::EffectResurrect()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!m_corpseTarget && !unitTarget)
return;
Player* player = nullptr;
if (m_corpseTarget)
player = ObjectAccessor::FindPlayer(m_corpseTarget->GetOwnerGUID());
else if (unitTarget)
player = unitTarget->ToPlayer();
if (!player || player->IsAlive() || !player->IsInWorld())
return;
if (player->IsResurrectRequested()) // already have one active request
return;
uint32 health = player->CountPctFromMaxHealth(damage);
uint32 mana = CalculatePct(player->GetMaxPower(POWER_MANA), damage);
ExecuteLogEffectResurrect(effectInfo->EffectIndex, player);
player->SetResurrectRequestData(m_caster, health, mana, 0);
SendResurrectRequest(player);
}
void Spell::EffectAddExtraAttacks()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || !unitTarget->IsAlive())
return;
unitTarget->AddExtraAttacks(damage);
ExecuteLogEffectExtraAttacks(effectInfo->EffectIndex, unitTarget, damage);
}
void Spell::EffectParry()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetCanParry(true);
}
void Spell::EffectBlock()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetCanBlock(true);
}
void Spell::EffectLeap()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->IsInFlight())
return;
if (!m_targets.HasDst())
return;
Position pos = destTarget->GetPosition();
unitTarget->NearTeleportTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), unitTarget == m_caster);
}
void Spell::EffectReputation()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
int32 repChange = damage;
uint32 factionId = effectInfo->MiscValue;
FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionId);
if (!factionEntry)
return;
repChange = player->CalculateReputationGain(REPUTATION_SOURCE_SPELL, 0, repChange, factionId);
player->GetReputationMgr().ModifyReputation(factionEntry, repChange);
}
void Spell::EffectQuestComplete()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
uint32 questId = effectInfo->MiscValue;
if (questId)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
if (!quest)
return;
uint16 logSlot = player->FindQuestSlot(questId);
if (logSlot < MAX_QUEST_LOG_SIZE)
player->AreaExploredOrEventHappens(questId);
else if (quest->HasFlag(QUEST_FLAGS_TRACKING)) // Check if the quest is used as a serverside flag.
player->SetRewardedQuest(questId); // If so, set status to rewarded without broadcasting it to client.
}
}
void Spell::EffectForceDeselect()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
float dist = unitCaster->GetVisibilityRange();
// clear focus
WorldPacket data(SMSG_BREAK_TARGET, unitCaster->GetPackGUID().size());
data << unitCaster->GetPackGUID();
Trinity::MessageDistDelivererToHostile notifierBreak(unitCaster, &data, dist);
Cell::VisitWorldObjects(unitCaster, notifierBreak, dist);
// and selection
data.Initialize(SMSG_CLEAR_TARGET, 8);
data << uint64(unitCaster->GetGUID());
Trinity::MessageDistDelivererToHostile notifierClear(unitCaster, &data, dist);
Cell::VisitWorldObjects(unitCaster, notifierClear, dist);
// we should also force pets to remove us from current target
Unit::AttackerSet attackerSet;
for (Unit::AttackerSet::const_iterator itr = unitCaster->getAttackers().begin(); itr != unitCaster->getAttackers().end(); ++itr)
if ((*itr)->GetTypeId() == TYPEID_UNIT && !(*itr)->CanHaveThreatList())
attackerSet.insert(*itr);
for (Unit::AttackerSet::const_iterator itr = attackerSet.begin(); itr != attackerSet.end(); ++itr)
(*itr)->AttackStop();
}
void Spell::EffectSelfResurrect()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Player* player = m_caster->ToPlayer();
if (!player || !player->IsInWorld() || player->IsAlive())
return;
uint32 health = 0;
uint32 mana = 0;
// flat case
if (damage < 0)
{
health = uint32(-damage);
mana = effectInfo->MiscValue;
}
// percent case
else
{
health = player->CountPctFromMaxHealth(damage);
if (player->GetMaxPower(POWER_MANA) > 0)
mana = CalculatePct(player->GetMaxPower(POWER_MANA), damage);
}
player->ResurrectPlayer(0.0f);
player->SetHealth(health);
player->SetPower(POWER_MANA, mana);
player->SetPower(POWER_RAGE, 0);
player->SetPower(POWER_ENERGY, player->GetMaxPower(POWER_ENERGY));
player->SpawnCorpseBones();
}
void Spell::EffectSkinning()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (unitTarget->GetTypeId() != TYPEID_UNIT)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
Creature* creature = unitTarget->ToCreature();
int32 targetLevel = creature->GetLevel();
uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill();
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
player->SendLoot(creature->GetGUID(), LOOT_SKINNING);
int32 const reqValue = targetLevel < 10 ? 0 : (targetLevel < 20 ? (targetLevel - 10) * 10 : targetLevel * 5);
int32 const skillValue = player->GetPureSkillValue(skill);
// Double chances for elites
player->UpdateGatherSkill(skill, skillValue, reqValue, creature->isElite() ? 2 : 1);
}
void Spell::EffectCharge()
{
if (!unitTarget)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
{
// charge changes fall time
if (unitCaster->GetTypeId() == TYPEID_PLAYER)
unitCaster->ToPlayer()->SetFallInformation(0, unitCaster->GetPositionZ());
float speed = G3D::fuzzyGt(m_spellInfo->Speed, 0.0f) ? m_spellInfo->Speed : SPEED_CHARGE;
// Spell is not using explicit target - no generated path
if (!m_preGeneratedPath)
{
//unitTarget->GetContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ);
Position pos = unitTarget->GetFirstCollisionPosition(unitTarget->GetCombatReach(), unitTarget->GetRelativeAngle(m_caster));
unitCaster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speed);
}
else
unitCaster->GetMotionMaster()->MoveCharge(*m_preGeneratedPath, speed);
}
if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET)
{
// not all charge effects used in negative spells
if (!m_spellInfo->IsPositive() && m_caster->GetTypeId() == TYPEID_PLAYER)
unitCaster->Attack(unitTarget, true);
}
}
void Spell::EffectChargeDest()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (m_targets.HasDst())
{
Position pos = destTarget->GetPosition();
if (!unitCaster->IsWithinLOS(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()))
{
float angle = unitCaster->GetRelativeAngle(pos.GetPositionX(), pos.GetPositionY());
float dist = unitCaster->GetDistance(pos);
pos = unitCaster->GetFirstCollisionPosition(dist, angle);
}
unitCaster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ);
}
}
void Spell::EffectKnockBack()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (m_caster->GetAffectingPlayer())
if (Creature* creatureTarget = unitTarget->ToCreature())
if (creatureTarget->isWorldBoss() || creatureTarget->IsDungeonBoss())
return;
// Spells with SPELL_EFFECT_KNOCK_BACK (like Thunderstorm) can't knockback target if target has ROOT/STUN
if (unitTarget->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED))
return;
// Instantly interrupt non melee spells being cast
if (unitTarget->IsNonMeleeSpellCast(true))
unitTarget->InterruptNonMeleeSpells(true);
float ratio = 0.1f;
float speedxy = float(effectInfo->MiscValue) * ratio;
float speedz = float(damage) * ratio;
if (speedxy < 0.01f && speedz < 0.01f)
return;
float x, y;
if (effectInfo->Effect == SPELL_EFFECT_KNOCK_BACK_DEST)
{
if (m_targets.HasDst())
destTarget->GetPosition(x, y);
else
return;
}
else //if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_KNOCK_BACK)
m_caster->GetPosition(x, y);
unitTarget->KnockbackFrom(x, y, speedxy, speedz);
}
void Spell::EffectLeapBack()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET)
return;
if (!unitTarget)
return;
float speedxy = effectInfo->MiscValue / 10.f;
float speedz = damage/ 10.f;
//1891: Disengage
unitTarget->JumpTo(speedxy, speedz, m_spellInfo->SpellIconID != 1891);
// changes fall time
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetFallInformation(0, m_caster->GetPositionZ());
}
void Spell::EffectQuestClear()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
uint32 quest_id = effectInfo->MiscValue;
Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
if (!quest)
return;
// Player has never done this quest
if (player->GetQuestStatus(quest_id) == QUEST_STATUS_NONE)
return;
// remove all quest entries for 'entry' from quest log
for (uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot)
{
uint32 logQuest = player->GetQuestSlotQuestId(slot);
if (logQuest == quest_id)
{
player->SetQuestSlot(slot, 0);
// we ignore unequippable quest items in this case, it's still be equipped
player->TakeQuestSourceItem(logQuest, false);
if (quest->HasFlag(QUEST_FLAGS_FLAGS_PVP))
{
player->pvpInfo.IsHostile = player->pvpInfo.IsInHostileArea || player->HasPvPForcingQuest();
player->UpdatePvPState();
}
}
}
player->RemoveActiveQuest(quest_id, false);
player->RemoveRewardedQuest(quest_id);
sScriptMgr->OnQuestStatusChange(player, quest_id);
}
void Spell::EffectSendTaxi()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToPlayer()->ActivateTaxiPathTo(effectInfo->MiscValue, m_spellInfo->Id);
}
void Spell::EffectPullTowards()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
Position pos = m_caster->GetFirstCollisionPosition(m_caster->GetCombatReach(), m_caster->GetRelativeAngle(unitTarget));
// This is a blizzlike mistake: this should be 2D distance according to projectile motion formulas, but Blizzard erroneously used 3D distance.
float distXY = unitTarget->GetExactDist(pos);
// Avoid division by 0
if (distXY < 0.001)
return;
float distZ = pos.GetPositionZ() - unitTarget->GetPositionZ();
float speedXY = effectInfo->MiscValue ? effectInfo->MiscValue / 10.0f : 30.0f;
float speedZ = (2 * speedXY * speedXY * distZ + Movement::gravity * distXY * distXY) / (2 * speedXY * distXY);
if (!std::isfinite(speedZ))
{
TC_LOG_ERROR("spells", "Spell %u with SPELL_EFFECT_PULL_TOWARDS called with invalid speedZ. %s", m_spellInfo->Id, GetDebugInfo().c_str());
return;
}
unitTarget->JumpTo(speedXY, speedZ, true, pos);
}
void Spell::EffectPullTowardsDest()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
if (!m_targets.HasDst())
{
TC_LOG_ERROR("spells", "Spell %u with SPELL_EFFECT_PULL_TOWARDS_DEST has no dest target", m_spellInfo->Id);
return;
}
Position const* pos = m_targets.GetDstPos();
// This is a blizzlike mistake: this should be 2D distance according to projectile motion formulas, but Blizzard erroneously used 3D distance
float distXY = unitTarget->GetExactDist(pos);
// Avoid division by 0
if (distXY < 0.001)
return;
float distZ = pos->GetPositionZ() - unitTarget->GetPositionZ();
float speedXY = effectInfo->MiscValue ? effectInfo->MiscValue / 10.0f : 30.0f;
float speedZ = (2 * speedXY * speedXY * distZ + Movement::gravity * distXY * distXY) / (2 * speedXY * distXY);
if (!std::isfinite(speedZ))
{
TC_LOG_ERROR("spells", "Spell %u with SPELL_EFFECT_PULL_TOWARDS_DEST called with invalid speedZ. %s", m_spellInfo->Id, GetDebugInfo().c_str());
return;
}
unitTarget->JumpTo(speedXY, speedZ, true, *pos);
}
void Spell::EffectDispelMechanic()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
uint32 mechanic = effectInfo->MiscValue;
DispelList dispel_list;
Unit::AuraMap const& auras = unitTarget->GetOwnedAuras();
for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
Aura* aura = itr->second;
if (!aura->GetApplicationOfTarget(unitTarget->GetGUID()))
continue;
if (roll_chance_i(aura->CalcDispelChance(unitTarget, !unitTarget->IsFriendlyTo(m_caster))))
if ((aura->GetSpellInfo()->GetAllEffectsMechanicMask() & (1 << mechanic)))
dispel_list.emplace_back(aura->GetId(), aura->GetCasterGUID());
}
for (auto itr = dispel_list.begin(); itr != dispel_list.end(); ++itr)
unitTarget->RemoveAura(itr->first, itr->second, 0, AURA_REMOVE_BY_ENEMY_SPELL);
}
void Spell::EffectResurrectPet()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (damage < 0)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
// Maybe player dismissed dead pet or pet despawned?
bool hadPet = true;
if (!player->GetPet())
{
// Position passed to SummonPet is irrelevant with current implementation,
// pet will be relocated without using these coords in Pet::LoadPetFromDB
player->SummonPet(0, 0.0f, 0.0f, 0.0f, 0.0f, SUMMON_PET, 0);
hadPet = false;
}
// TODO: Better to fail Hunter's "Revive Pet" at cast instead of here when casting ends
Pet* pet = player->GetPet(); // Attempt to get current pet
if (!pet || pet->IsAlive())
return;
// If player did have a pet before reviving, teleport it
if (hadPet)
{
// Reposition the pet's corpse before reviving so as not to grab aggro
// We can use a different, more accurate version of GetClosePoint() since we have a pet
float x, y, z; // Will be used later to reposition the pet if we have one
player->GetClosePoint(x, y, z, pet->GetCombatReach(), PET_FOLLOW_DIST, pet->GetFollowAngle());
pet->NearTeleportTo(x, y, z, player->GetOrientation());
pet->Relocate(x, y, z, player->GetOrientation()); // This is needed so SaveStayPosition() will get the proper coords.
}
pet->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE);
pet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
pet->setDeathState(ALIVE);
pet->ClearUnitState(UNIT_STATE_ALL_ERASABLE);
pet->SetHealth(pet->CountPctFromMaxHealth(damage));
// Reset things for when the AI to takes over
CharmInfo *ci = pet->GetCharmInfo();
if (ci)
{
// In case the pet was at stay, we don't want it running back
ci->SaveStayPosition();
ci->SetIsAtStay(ci->HasCommandState(COMMAND_STAY));
ci->SetIsFollowing(false);
ci->SetIsCommandAttack(false);
ci->SetIsCommandFollow(false);
ci->SetIsReturning(false);
}
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
}
void Spell::EffectDestroyAllTotems()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
int32 mana = 0;
for (uint8 slot = SUMMON_SLOT_TOTEM_FIRE; slot < MAX_TOTEM_SLOT; ++slot)
{
if (!unitCaster->m_SummonSlot[slot])
continue;
Creature* totem = unitCaster->GetMap()->GetCreature(unitCaster->m_SummonSlot[slot]);
if (totem && totem->IsTotem())
{
uint32 spell_id = totem->GetUInt32Value(UNIT_CREATED_BY_SPELL);
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
if (spellInfo)
{
mana += spellInfo->ManaCost;
mana += int32(CalculatePct(unitCaster->GetCreateMana(), spellInfo->ManaCostPercentage));
}
totem->ToTotem()->UnSummon();
}
}
ApplyPct(mana, damage);
if (mana)
{
CastSpellExtraArgs args(TRIGGERED_FULL_MASK);
args.AddSpellMod(SPELLVALUE_BASE_POINT0, mana);
unitCaster->CastSpell(unitCaster, 39104, args);
}
}
void Spell::EffectDurabilityDamage()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
int32 slot = effectInfo->MiscValue;
// -1 means all player equipped items and -2 all items
if (slot < 0)
{
unitTarget->ToPlayer()->DurabilityPointsLossAll(damage, (slot < -1));
ExecuteLogEffectDurabilityDamage(effectInfo->EffectIndex, unitTarget, -1, -1);
return;
}
// invalid slot value
if (slot >= INVENTORY_SLOT_BAG_END)
return;
if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
{
unitTarget->ToPlayer()->DurabilityPointsLoss(item, damage);
ExecuteLogEffectDurabilityDamage(effectInfo->EffectIndex, unitTarget, item->GetEntry(), slot);
}
}
void Spell::EffectDurabilityDamagePCT()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
int32 slot = effectInfo->MiscValue;
// FIXME: some spells effects have value -1/-2
// Possibly its mean -1 all player equipped items and -2 all items
if (slot < 0)
{
unitTarget->ToPlayer()->DurabilityLossAll(float(damage) / 100.0f, (slot < -1));
return;
}
// invalid slot value
if (slot >= INVENTORY_SLOT_BAG_END)
return;
if (damage <= 0)
return;
if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
unitTarget->ToPlayer()->DurabilityLoss(item, float(damage) / 100.0f);
}
void Spell::EffectModifyThreatPercent()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster || !unitTarget)
return;
unitTarget->GetThreatManager().ModifyThreatByPercent(unitCaster, damage);
}
void Spell::EffectTransmitted()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
uint32 name_id = effectInfo->MiscValue;
GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(name_id);
if (!goinfo)
{
TC_LOG_ERROR("sql.sql", "Gameobject (Entry: %u) does not exist and is not created by spell (ID: %u) cast.", name_id, m_spellInfo->Id);
return;
}
float fx, fy, fz;
if (m_targets.HasDst())
destTarget->GetPosition(fx, fy, fz);
//FIXME: this can be better check for most objects but still hack
else if (effectInfo->HasRadius() && m_spellInfo->Speed == 0)
{
float dis = effectInfo->CalcRadius(unitCaster);
unitCaster->GetClosePoint(fx, fy, fz, DEFAULT_PLAYER_BOUNDING_RADIUS, dis);
}
else
{
//GO is always friendly to it's creator, get range for friends
float min_dis = m_spellInfo->GetMinRange(true);
float max_dis = m_spellInfo->GetMaxRange(true);
float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis;
unitCaster->GetClosePoint(fx, fy, fz, DEFAULT_PLAYER_BOUNDING_RADIUS, dis);
}
Map* cMap = unitCaster->GetMap();
// if gameobject is summoning object, it should be spawned right on caster's position
if (goinfo->type == GAMEOBJECT_TYPE_SUMMONING_RITUAL)
unitCaster->GetPosition(fx, fy, fz);
GameObject* pGameObj = new GameObject;
Position pos = { fx, fy, fz, unitCaster->GetOrientation() };
QuaternionData rot = QuaternionData::fromEulerAnglesZYX(unitCaster->GetOrientation(), 0.f, 0.f);
if (!pGameObj->Create(cMap->GenerateLowGuid<HighGuid::GameObject>(), name_id, cMap, unitCaster->GetPhaseMask(), pos, rot, 255, GO_STATE_READY))
{
delete pGameObj;
return;
}
int32 duration = m_spellInfo->GetDuration();
switch (goinfo->type)
{
case GAMEOBJECT_TYPE_FISHINGNODE:
{
unitCaster->SetChannelObjectGuid(pGameObj->GetGUID());
unitCaster->AddGameObject(pGameObj); // will removed at spell cancel
// end time of range when possible catch fish (FISHING_BOBBER_READY_TIME..GetDuration(m_spellInfo))
// start time == fish-FISHING_BOBBER_READY_TIME (0..GetDuration(m_spellInfo)-FISHING_BOBBER_READY_TIME)
int32 lastSec = 0;
switch (urand(0, 2))
{
case 0: lastSec = 3; break;
case 1: lastSec = 7; break;
case 2: lastSec = 13; break;
}
// Duration of the fishing bobber can't be higher than the Fishing channeling duration
duration = std::min(duration, duration - lastSec*IN_MILLISECONDS + FISHING_BOBBER_READY_TIME*IN_MILLISECONDS);
break;
}
case GAMEOBJECT_TYPE_SUMMONING_RITUAL:
{
if (unitCaster->GetTypeId() == TYPEID_PLAYER)
{
pGameObj->AddUniqueUse(unitCaster->ToPlayer());
unitCaster->AddGameObject(pGameObj); // will be removed at spell cancel
}
break;
}
case GAMEOBJECT_TYPE_DUEL_ARBITER: // 52991
unitCaster->AddGameObject(pGameObj);
break;
case GAMEOBJECT_TYPE_FISHINGHOLE:
case GAMEOBJECT_TYPE_CHEST:
default:
break;
}
pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0);
pGameObj->SetOwnerGUID(unitCaster->GetGUID());
//pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, unitCaster->GetLevel());
pGameObj->SetSpellId(m_spellInfo->Id);
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pGameObj);
TC_LOG_DEBUG("spells", "AddObject at SpellEfects.cpp EffectTransmitted");
//unitCaster->AddGameObject(pGameObj);
//m_ObjToDel.push_back(pGameObj);
cMap->AddToMap(pGameObj);
if (GameObject* linkedTrap = pGameObj->GetLinkedTrap())
{
linkedTrap->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0);
//linkedTrap->SetUInt32Value(GAMEOBJECT_LEVEL, unitCaster->GetLevel());
linkedTrap->SetSpellId(m_spellInfo->Id);
linkedTrap->SetOwnerGUID(unitCaster->GetGUID());
ExecuteLogEffectSummonObject(effectInfo->EffectIndex, linkedTrap);
}
}
void Spell::EffectProspecting()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
if (!itemTarget || !itemTarget->GetTemplate()->HasFlag(ITEM_FLAG_IS_PROSPECTABLE))
return;
if (itemTarget->GetCount() < 5)
return;
if (sWorld->getBoolConfig(CONFIG_SKILL_PROSPECTING))
{
uint32 SkillValue = player->GetPureSkillValue(SKILL_JEWELCRAFTING);
uint32 reqSkillValue = itemTarget->GetTemplate()->RequiredSkillRank;
player->UpdateGatherSkill(SKILL_JEWELCRAFTING, SkillValue, reqSkillValue);
}
player->SendLoot(itemTarget->GetGUID(), LOOT_PROSPECTING);
}
void Spell::EffectMilling()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
if (!itemTarget || !itemTarget->GetTemplate()->HasFlag(ITEM_FLAG_IS_MILLABLE))
return;
if (itemTarget->GetCount() < 5)
return;
if (sWorld->getBoolConfig(CONFIG_SKILL_MILLING))
{
uint32 SkillValue = player->GetPureSkillValue(SKILL_INSCRIPTION);
uint32 reqSkillValue = itemTarget->GetTemplate()->RequiredSkillRank;
player->UpdateGatherSkill(SKILL_INSCRIPTION, SkillValue, reqSkillValue);
}
player->SendLoot(itemTarget->GetGUID(), LOOT_MILLING);
}
void Spell::EffectSkill()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
TC_LOG_DEBUG("spells", "WORLD: SkillEFFECT");
}
/* There is currently no need for this effect. We handle it in Battleground.cpp
If we would handle the resurrection here, the spiritguide would instantly disappear as the
player revives, and so we wouldn't see the spirit heal visual effect on the npc.
This is why we use a half sec delay between the visual effect and the resurrection itself */
void Spell::EffectSpiritHeal()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
/*
if (unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
if (!unitTarget->IsInWorld())
return;
//m_spellInfo->Effects[i].BasePoints; == 99 (percent?)
//unitTarget->ToPlayer()->setResurrect(m_caster->GetGUID(), unitTarget->GetPositionX(), unitTarget->GetPositionY(), unitTarget->GetPositionZ(), unitTarget->GetMaxHealth(), unitTarget->GetMaxPower(POWER_MANA));
unitTarget->ToPlayer()->ResurrectPlayer(1.0f);
unitTarget->ToPlayer()->SpawnCorpseBones();
*/
}
// remove insignia spell effect
void Spell::EffectSkinPlayerCorpse()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
TC_LOG_DEBUG("spells", "Effect: SkinPlayerCorpse");
Player* player = m_caster->ToPlayer();
Player* target = nullptr;
if (unitTarget)
target = unitTarget->ToPlayer();
else if (m_corpseTarget)
target = ObjectAccessor::FindPlayer(m_corpseTarget->GetOwnerGUID());
if (!player || !target || target->IsAlive())
return;
target->RemovedInsignia(player);
}
void Spell::EffectStealBeneficialBuff()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
TC_LOG_DEBUG("spells", "Effect: StealBeneficialBuff");
if (!unitTarget || unitTarget == m_caster) // can't steal from self
return;
DispelChargesList stealList;
// Create dispel mask by dispel type
uint32 dispelMask = SpellInfo::GetDispelMask(DispelType(effectInfo->MiscValue));
Unit::AuraMap const& auras = unitTarget->GetOwnedAuras();
for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
{
Aura* aura = itr->second;
AuraApplication const* aurApp = aura->GetApplicationOfTarget(unitTarget->GetGUID());
if (!aurApp)
continue;
if ((aura->GetSpellInfo()->GetDispelMask()) & dispelMask)
{
// Need check for passive? this
if (!aurApp->IsPositive() || aura->IsPassive() || aura->GetSpellInfo()->HasAttribute(SPELL_ATTR4_NOT_STEALABLE))
continue;
// 2.4.3 Patch Notes: "Dispel effects will no longer attempt to remove effects that have 100% dispel resistance."
int32 chance = aura->CalcDispelChance(unitTarget, !unitTarget->IsFriendlyTo(m_caster));
if (!chance)
continue;
// The charges / stack amounts don't count towards the total number of auras that can be dispelled.
// Ie: A dispel on a target with 5 stacks of Winters Chill and a Polymorph has 1 / (1 + 1) -> 50% chance to dispell
// Polymorph instead of 1 / (5 + 1) -> 16%.
bool dispelCharges = aura->GetSpellInfo()->HasAttribute(SPELL_ATTR7_DISPEL_CHARGES);
uint8 charges = dispelCharges ? aura->GetCharges() : aura->GetStackAmount();
if (charges > 0)
stealList.emplace_back(aura, chance, charges);
}
}
if (stealList.empty())
return;
size_t remaining = stealList.size();
// Ok if exist some buffs for dispel try dispel it
uint32 failCount = 0;
DispelList successList;
successList.reserve(damage);
WorldPacket dataFail(SMSG_DISPEL_FAILED, 8 + 8 + 4 + 4 + damage * 4);
// dispel N = damage buffs (or while exist buffs for dispel)
for (int32 count = 0; count < damage && remaining > 0;)
{
// Random select buff for dispel
DispelChargesList::iterator itr = stealList.begin();
std::advance(itr, urand(0, remaining - 1));
if (itr->RollDispel())
{
successList.emplace_back(itr->GetAura()->GetId(), itr->GetAura()->GetCasterGUID());
if (!itr->DecrementCharge())
{
--remaining;
std::swap(*itr, stealList[remaining]);
}
}
else
{
if (!failCount)
{
// Failed to dispell
dataFail << uint64(m_caster->GetGUID()); // Caster GUID
dataFail << uint64(unitTarget->GetGUID()); // Victim GUID
dataFail << uint32(m_spellInfo->Id); // dispel spell id
}
++failCount;
dataFail << uint32(itr->GetAura()->GetId()); // Spell Id
}
++count;
}
if (failCount)
m_caster->SendMessageToSet(&dataFail, true);
if (successList.empty())
return;
WorldPacket dataSuccess(SMSG_SPELLSTEALLOG, 8 + 8 + 4 + 1 + 4 + damage * 5);
dataSuccess << unitTarget->GetPackGUID(); // Victim GUID
dataSuccess << m_caster->GetPackGUID(); // Caster GUID
dataSuccess << uint32(m_spellInfo->Id); // dispel spell id
dataSuccess << uint8(0); // not used
dataSuccess << uint32(successList.size()); // count
for (auto itr = successList.begin(); itr != successList.end(); ++itr)
{
dataSuccess << uint32(itr->first); // Spell Id
dataSuccess << uint8(0); // 0 - steals !=0 transfers
unitTarget->RemoveAurasDueToSpellBySteal(itr->first, itr->second, m_caster);
}
m_caster->SendMessageToSet(&dataSuccess, true);
}
void Spell::EffectKillCreditPersonal()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToPlayer()->KilledMonsterCredit(effectInfo->MiscValue);
}
void Spell::EffectKillCredit()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
int32 creatureEntry = effectInfo->MiscValue;
if (!creatureEntry)
{
if (m_spellInfo->Id == 42793) // Burn Body
creatureEntry = 24008; // Fallen Combatant
}
if (creatureEntry)
unitTarget->ToPlayer()->RewardPlayerAndGroupAtEvent(creatureEntry, unitTarget);
}
void Spell::EffectQuestFail()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToPlayer()->FailQuest(effectInfo->MiscValue);
}
void Spell::EffectQuestStart()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
Player* player = unitTarget->ToPlayer();
if (!player)
return;
if (Quest const* quest = sObjectMgr->GetQuestTemplate(effectInfo->MiscValue))
{
if (!player->CanTakeQuest(quest, false))
return;
if (quest->IsAutoAccept() && player->CanAddQuest(quest, false))
player->AddQuestAndCheckCompletion(quest, player);
player->PlayerTalkClass->SendQuestGiverQuestDetails(quest, player->GetGUID(), true);
}
}
void Spell::EffectActivateRune()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = m_caster->ToPlayer();
if (player->GetClass() != CLASS_DEATH_KNIGHT)
return;
// needed later
m_runesState = m_caster->ToPlayer()->GetRunesState();
uint32 count = damage;
if (count == 0)
count = 1;
for (uint32 j = 0; j < MAX_RUNES && count > 0; ++j)
{
if (player->GetRuneCooldown(j) && player->GetCurrentRune(j) == RuneType(effectInfo->MiscValue))
{
player->SetRuneCooldown(j, 0);
--count;
}
}
// Empower rune weapon
if (m_spellInfo->Id == 47568)
{
// Need to do this just once
if (effectInfo->EffectIndex != EFFECT_0)
return;
for (uint32 i = 0; i < MAX_RUNES; ++i)
{
if (player->GetRuneCooldown(i) && (player->GetBaseRune(i) == RUNE_FROST))
player->SetRuneCooldown(i, 0);
}
}
}
void Spell::EffectCreateTamedPet()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER || unitTarget->GetPetGUID() || unitTarget->GetClass() != CLASS_HUNTER)
return;
uint32 creatureEntry = effectInfo->MiscValue;
Pet* pet = unitTarget->CreateTamedPetFrom(creatureEntry, m_spellInfo->Id);
if (!pet)
return;
// add to world
pet->GetMap()->AddToMap(pet->ToCreature());
// unitTarget has pet now
unitTarget->SetMinion(pet, true);
pet->InitTalentForLevel();
if (unitTarget->GetTypeId() == TYPEID_PLAYER)
{
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
unitTarget->ToPlayer()->PetSpellInitialize();
}
}
void Spell::EffectDiscoverTaxi()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
uint32 nodeid = effectInfo->MiscValue;
if (sTaxiNodesStore.LookupEntry(nodeid))
unitTarget->ToPlayer()->GetSession()->SendDiscoverNewTaxiNode(nodeid);
}
void Spell::EffectTitanGrip()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
if (m_caster->GetTypeId() == TYPEID_PLAYER)
m_caster->ToPlayer()->SetCanTitanGrip(true, effectInfo->MiscValue);
}
void Spell::EffectRedirectThreat()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (unitTarget)
unitCaster->GetThreatManager().RegisterRedirectThreat(m_spellInfo->Id, unitTarget->GetGUID(), uint32(damage));
}
void Spell::EffectGameObjectDamage()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!gameObjTarget)
return;
FactionTemplateEntry const* casterFaction = m_caster->GetFactionTemplateEntry();
FactionTemplateEntry const* targetFaction = sFactionTemplateStore.LookupEntry(gameObjTarget->GetFaction());
// Do not allow to damage GO's of friendly factions (ie: Wintergrasp Walls/Ulduar Storm Beacons)
if (!targetFaction || (casterFaction && !casterFaction->IsFriendlyTo(*targetFaction)))
gameObjTarget->ModifyHealth(-damage, m_caster, GetSpellInfo()->Id);
}
void Spell::EffectGameObjectRepair()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!gameObjTarget)
return;
gameObjTarget->ModifyHealth(damage, m_caster);
}
void Spell::EffectGameObjectSetDestructionState()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!gameObjTarget)
return;
gameObjTarget->SetDestructibleState(GameObjectDestructibleState(effectInfo->MiscValue), m_caster, true);
}
void Spell::SummonGuardian(SpellEffectInfo const& spellEffectInfo, uint32 entry, SummonPropertiesEntry const* properties, uint32 numGuardians)
{
Unit* unitCaster = GetUnitCasterForEffectHandlers();
if (!unitCaster)
return;
if (unitCaster->IsTotem())
unitCaster = unitCaster->ToTotem()->GetOwner();
// in another case summon new
uint8 level = unitCaster->GetLevel();
// level of pet summoned using engineering item based at engineering skill level
if (m_CastItem && unitCaster->GetTypeId() == TYPEID_PLAYER)
if (ItemTemplate const* proto = m_CastItem->GetTemplate())
if (proto->RequiredSkill == SKILL_ENGINEERING)
if (uint16 skill202 = unitCaster->ToPlayer()->GetSkillValue(SKILL_ENGINEERING))
level = skill202 / 5;
float radius = 5.0f;
int32 duration = m_spellInfo->GetDuration();
if (Player* modOwner = unitCaster->GetSpellModOwner())
modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration);
//TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN;
Map* map = unitCaster->GetMap();
for (uint32 count = 0; count < numGuardians; ++count)
{
Position pos;
if (count == 0)
pos = *destTarget;
else
// randomize position for multiple summons
pos = unitCaster->GetRandomPoint(*destTarget, radius);
TempSummon* summon = map->SummonCreature(entry, pos, properties, duration, unitCaster, m_spellInfo->Id);
if (!summon)
return;
if (summon->HasUnitTypeMask(UNIT_MASK_GUARDIAN))
((Guardian*)summon)->InitStatsForLevel(level);
if (properties && properties->Control == SUMMON_CATEGORY_ALLY)
summon->SetFaction(unitCaster->GetFaction());
if (summon->HasUnitTypeMask(UNIT_MASK_MINION) && m_targets.HasDst())
((Minion*)summon)->SetFollowAngle(unitCaster->GetAbsoluteAngle(summon));
if (summon->GetEntry() == 27893)
{
if (uint32 weapon = unitCaster->GetUInt32Value(PLAYER_VISIBLE_ITEM_16_ENTRYID))
{
summon->SetDisplayId(11686); // modelid2
summon->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, weapon);
}
else
summon->SetDisplayId(1126); // modelid1
}
ExecuteLogEffectSummonObject(spellEffectInfo.EffectIndex, summon);
}
}
void Spell::EffectRenamePet()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT ||
!unitTarget->IsPet() || ((Pet*)unitTarget)->getPetType() != HUNTER_PET)
return;
unitTarget->SetByteFlag(UNIT_FIELD_BYTES_2, UNIT_BYTES_2_OFFSET_PET_FLAGS, UNIT_CAN_BE_RENAMED);
}
void Spell::EffectPlayMusic()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
uint32 soundid = effectInfo->MiscValue;
if (!sSoundEntriesStore.LookupEntry(soundid))
{
TC_LOG_ERROR("spells", "EffectPlayMusic: Sound (Id: %u) does not exist in spell %u.", soundid, m_spellInfo->Id);
return;
}
unitTarget->ToPlayer()->SendDirectMessage(WorldPackets::Misc::PlayMusic(soundid).Write());
}
void Spell::EffectSpecCount()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToPlayer()->UpdateSpecCount(damage);
}
void Spell::EffectActivateSpec()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
unitTarget->ToPlayer()->ActivateSpec(damage-1); // damage is 1 or 2, spec is 0 or 1
}
void Spell::EffectPlaySound()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
Player* player = unitTarget->ToPlayer();
if (!player)
return;
switch (m_spellInfo->Id)
{
case 58730: // Restricted Flight Area
case 58600: // Restricted Flight Area
player->GetSession()->SendNotification(LANG_ZONE_NOFLYZONE);
break;
default:
break;
}
uint32 soundId = effectInfo->MiscValue;
if (!sSoundEntriesStore.LookupEntry(soundId))
{
TC_LOG_ERROR("spells", "EffectPlaySound: Sound (Id: %u) does not exist in spell %u.", soundId, m_spellInfo->Id);
return;
}
player->PlayDirectSound(soundId, player);
}
void Spell::EffectRemoveAura()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget)
return;
// there may be need of specifying casterguid of removed auras
unitTarget->RemoveAurasDueToSpell(effectInfo->TriggerSpell);
}
void Spell::EffectCastButtons()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
uint32 button_id = effectInfo->MiscValue + 132;
uint32 n_buttons = effectInfo->MiscValueB;
for (; n_buttons; --n_buttons, ++button_id)
{
ActionButton const* ab = player->GetActionButton(button_id);
if (!ab || ab->GetType() != ACTION_BUTTON_SPELL)
continue;
//! Action button data is unverified when it's set so it can be "hacked"
//! to contain invalid spells, so filter here.
uint32 spell_id = ab->GetAction();
if (!spell_id)
continue;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
if (!spellInfo)
continue;
if (!player->HasSpell(spell_id) || player->GetSpellHistory()->HasCooldown(spell_id))
continue;
if (!spellInfo->HasAttribute(SPELL_ATTR7_SUMMON_PLAYER_TOTEM))
continue;
uint32 cost = spellInfo->CalcPowerCost(player, spellInfo->GetSchoolMask());
if (player->GetPower(POWER_MANA) < cost)
continue;
TriggerCastFlags triggerFlags = TriggerCastFlags(TRIGGERED_IGNORE_GCD | TRIGGERED_IGNORE_CAST_IN_PROGRESS | TRIGGERED_CAST_DIRECTLY);
player->CastSpell(player, spell_id, triggerFlags);
}
}
void Spell::EffectRechargeManaGem()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = m_caster->ToPlayer();
if (!player)
return;
uint32 item_id = effectInfo->ItemType;
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id);
if (!pProto)
{
player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr);
return;
}
if (Item* pItem = player->GetItemByEntry(item_id))
{
for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x)
pItem->SetSpellCharges(x, pProto->Spells[x].SpellCharges);
pItem->SetState(ITEM_CHANGED, player);
}
}
void Spell::EffectBind()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
Player* player = unitTarget->ToPlayer();
WorldLocation homeLoc;
uint32 areaId = player->GetAreaId();
if (effectInfo->MiscValue)
areaId = effectInfo->MiscValue;
if (m_targets.HasDst())
homeLoc.WorldRelocate(*destTarget);
else
homeLoc = player->GetWorldLocation();
player->SetHomebind(homeLoc, areaId);
player->SendBindPointUpdate();
TC_LOG_DEBUG("spells", "EffectBind: New homebind X: %f, Y: %f, Z: %f, MapId: %u, AreaId: %u",
homeLoc.GetPositionX(), homeLoc.GetPositionY(), homeLoc.GetPositionZ(), homeLoc.GetMapId(), areaId);
// zone update
WorldPackets::Misc::PlayerBound packet(m_caster->GetGUID(), areaId);
player->SendDirectMessage(packet.Write());
}
void Spell::EffectSummonRaFFriend()
{
if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET)
return;
if (m_caster->GetTypeId() != TYPEID_PLAYER || !unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER)
return;
m_caster->CastSpell(unitTarget, effectInfo->TriggerSpell, true);
}<|fim▁end|> | |
<|file_name|>helper.rs<|end_file_name|><|fim▁begin|>// This file provides a const function that is unstably const forever.
#![feature(staged_api)]
#![stable(feature = "1", since = "1.0.0")]
#[stable(feature = "1", since = "1.0.0")]
#[rustc_const_unstable(feature = "foo", issue = "none")]<|fim▁hole|>pub const fn unstably_const_fn() {}<|fim▁end|> | |
<|file_name|>gantry-totop.js<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> * @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
eval(function(p,a,c,k,e,r){e=function(c){return c.toString(a)};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3.0(\'j\',1(){2 a=f.d(\'c-9\');8(a){2 b=6 5.4(3);a.7(\'g\',\'h\').0(\'i\',1(e){e.k();b.l()})}});',22,22,'addEvent|function|var|window|Scroll|Fx|new|setStyle|if|totop|||gantry|id||document|outline|none|click|domready|stop|toTop'.split('|'),0,{}))<|fim▁end|> | * @version $Id: gantry-totop.js 58623 2012-12-15 22:01:32Z btowles $ |
<|file_name|>testCombined.py<|end_file_name|><|fim▁begin|>from __future__ import print_function
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem.PyMol import MolViewer
from rdkit.Chem.Subshape import SubshapeBuilder,SubshapeObjects,SubshapeAligner
from rdkit.six.moves import cPickle
import copy
m1 = Chem.MolFromMolFile('test_data/square1.mol')
m2 = Chem.MolFromMolFile('test_data/square2.mol')
b = SubshapeBuilder.SubshapeBuilder()
b.gridDims=(10.,10.,5)
b.gridSpacing=0.4
b.winRad=2.0
if 1:
print('m1:')
s1 = b.GenerateSubshapeShape(m1)
cPickle.dump(s1,file('test_data/square1.shp.pkl','wb+'))
print('m2:')
s2 = b.GenerateSubshapeShape(m2)
cPickle.dump(s2,file('test_data/square2.shp.pkl','wb+'))
ns1 = b.CombineSubshapes(s1,s2)
b.GenerateSubshapeSkeleton(ns1)
cPickle.dump(ns1,file('test_data/combined.shp.pkl','wb+'))
else:
s1 = cPickle.load(file('test_data/square1.shp.pkl','rb'))
s2 = cPickle.load(file('test_data/square2.shp.pkl','rb'))
#ns1 = cPickle.load(file('test_data/combined.shp.pkl','rb'))
ns1=cPickle.load(file('test_data/combined.shp.pkl','rb'))
v = MolViewer()
SubshapeObjects.DisplaySubshape(v,s1,'shape1')
SubshapeObjects.DisplaySubshape(v,ns1,'ns1')
#SubshapeObjects.DisplaySubshape(v,s2,'shape2')
a = SubshapeAligner.SubshapeAligner()
pruneStats={}
algs =a.GetSubshapeAlignments(None,ns1,m1,s1,b,pruneStats=pruneStats)<|fim▁hole|>from rdkit import Geometry
fName = tempfile.mktemp('.grd')
Geometry.WriteGridToFile(ns1.coarseGrid.grid,fName)
v.server.loadSurface(fName,'coarse','',2.5)
os.unlink(fName)
fName = tempfile.mktemp('.grd')
Geometry.WriteGridToFile(ns1.medGrid.grid,fName)
v.server.loadSurface(fName,'med','',2.5)
os.unlink(fName)<|fim▁end|> | print(len(algs))
print(pruneStats)
import os,tempfile |
<|file_name|>fileBased.spec.js<|end_file_name|><|fim▁begin|>var loadJsons = require('../lib/loadJsons');
describe("Get a recursive directory load of JSONs", function() {
var data;
beforeEach(function(done) {
if(data) done();
else {
loadJsons("./specs")(function(d) {
data = d;
done();
});
}
});
it("Should return right number of jsons", function() {
expect(data.length).toBe(6);
});
<|fim▁hole|> it("Should have a @type field on all objects", function() {
data.forEach(function(d) {
expect(d['@type']).toBeDefined();
});
});
});<|fim▁end|> | |
<|file_name|>split_check.rs<|end_file_name|><|fim▁begin|>// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::path::Path;
use std::sync::mpsc::{self, sync_channel};
use std::sync::Arc;
use std::time::Duration;
use engine_rocks::raw::DB;
use engine_rocks::Compat;
use raftstore::coprocessor::{
config::{Config, SplitCheckConfigManager},
CoprocessorHost,
};
use raftstore::store::{SplitCheckRunner as Runner, SplitCheckTask as Task};
use tikv::config::{ConfigController, Module, TiKvConfig};
use tikv_util::worker::{LazyWorker, Scheduler, Worker};
fn tmp_engine<P: AsRef<Path>>(path: P) -> Arc<DB> {
Arc::new(
engine_rocks::raw_util::new_engine(
path.as_ref().to_str().unwrap(),
None,
&["split-check-config"],
None,
)
.unwrap(),
)
}
fn setup(cfg: TiKvConfig, engine: Arc<DB>) -> (ConfigController, LazyWorker<Task>) {
let (router, _) = sync_channel(1);
let runner = Runner::new(
engine.c().clone(),
router.clone(),
CoprocessorHost::new(router),
cfg.coprocessor.clone(),
);
let share_worker = Worker::new("split-check-config");
let mut worker = share_worker.lazy_build("split-check-config");
worker.start(runner);
let cfg_controller = ConfigController::new(cfg);
cfg_controller.register(
Module::Coprocessor,
Box::new(SplitCheckConfigManager(worker.scheduler())),
);
(cfg_controller, worker)
}
fn validate<F>(scheduler: &Scheduler<Task>, f: F)
where
F: FnOnce(&Config) + Send + 'static,
{
let (tx, rx) = mpsc::channel();
scheduler
.schedule(Task::Validate(Box::new(move |cfg: &Config| {
f(cfg);
tx.send(()).unwrap();
})))
.unwrap();
rx.recv_timeout(Duration::from_secs(1)).unwrap();
}
#[test]
fn test_update_split_check_config() {
let (mut cfg, _dir) = TiKvConfig::with_tmp().unwrap();
cfg.validate().unwrap();
let engine = tmp_engine(&cfg.storage.data_dir);
let (cfg_controller, mut worker) = setup(cfg.clone(), engine);
let scheduler = worker.scheduler();
let cop_config = cfg.coprocessor.clone();
// update of other module's config should not effect split check config
cfg_controller
.update_config("raftstore.raft-log-gc-threshold", "2000")
.unwrap();
validate(&scheduler, move |cfg: &Config| {
assert_eq!(cfg, &cop_config);
});
let change = {
let mut m = std::collections::HashMap::new();
m.insert(
"coprocessor.split_region_on_table".to_owned(),
"true".to_owned(),
);<|fim▁hole|> m.insert(
"coprocessor.region_split_keys".to_owned(),
"12345".to_owned(),
);
m
};
cfg_controller.update(change).unwrap();
// config should be updated
let cop_config = {
let mut cop_config = cfg.coprocessor;
cop_config.split_region_on_table = true;
cop_config.batch_split_limit = 123;
cop_config.region_split_keys = 12345;
cop_config
};
validate(&scheduler, move |cfg: &Config| {
assert_eq!(cfg, &cop_config);
});
worker.stop();
}<|fim▁end|> | m.insert("coprocessor.batch_split_limit".to_owned(), "123".to_owned()); |
<|file_name|>baseline_picdata.py<|end_file_name|><|fim▁begin|>import sys
import os
#For baseline and redundacy-detecion to prepare message size picture
def MessageSize(typePrefix, directory):
wf = open("%(typePrefix)s-msgsize.data"%vars(), "w")
wf.write("#Suggest Filename: %(typePrefix)s-message.data\n#Data for drawing message overall size in different Amount/Redundancy\n"%vars())
wf.write("#row: amount(10000, 20000, 30000, 40000, 50000)\n#col: redundancy(1, 2, 3, 4, 5)\n")
wf.write('#amount\tRedundancy 1\tRedundancy 2\tRedundancy 3\tRedundancy 4\tRedundancy 5\n')
num = 100 # may subject to change by the simulation node number
for amount in [10000,20000,30000,40000,50000]:
wf.write(str(amount) + " ")
for redundancy in [1,2,3,4,5]:
file = open("%(directory)s%(typePrefix)s_da%(amount)s_r%(redundancy)s_overhead.data"%vars())
for line in file:
if line[0] != "#":
numbers = line.split(' ')
wf.write(numbers[7]+" ")
wf.write("\n")
file.close()
def RecvToSendRatio(typePrefix, directory):
writefile = open("%(typePrefix)s-rsratio-nonce.data"%vars(), "w")
writefile.write("#Suggest Filename: %(typePrefix)s-rsratio.data\n#Data for drawing each package in different Amount/Redundancy\n"%vars())
writefile.write("#MPM100 ratio MPM200 ratio MPM300 ratio MPM400 ratio MPM500 ratio MPM600 ratio NoLimit ratio\n")
writefile.write("0 0 0 0 0 0 0 0 0 0 \n")
backofftime = 2.5 # may subject to change by the data amount wanted to observe
da=50000
msgcount = {}
ratiotemp = {}
ratio = {}
for redundancy in [1,2,3,4,5]:
msgcount[redundancy] = {}
for logcontent in ['SI','SD']:
file = open("%(directory)s%(typePrefix)s_da%(da)s_r%(redundancy)s_%(logcontent)s.data"%vars())
for line in file:
if line[0:2] == logcontent:
info = line.split(' ')
for x in info:
if x[0:2] == "Ho":
nonce = x.split(':')[1]
if msgcount[redundancy].has_key(nonce):
msgcount[redundancy][nonce]["s"] += 1
else:
msgcount[redundancy][nonce] = {}
msgcount[redundancy][nonce]["s"] = 1
msgcount[redundancy][nonce]["r"] = 0
msgcount[redundancy][nonce]["rs"] = 0
for logcontent in ['RI','DRD']:
file = open("%(directory)s%(typePrefix)s_da%(da)s_r%(redundancy)s_%(logcontent)s.data"%vars())
for line in file:
if line[0:2] == logcontent or line[0:3] == logcontent:
info = line.split(' ')
for x in info:
if x[0:2] == "Ho":
nonce = x.split(':')[1]
if(msgcount[redundancy].has_key(nonce)):
msgcount[redundancy][nonce]["r"] += 1
else:
print logcontent, redundancy, nonce
for nonce in msgcount[redundancy]:
msgcount[redundancy][nonce]['rs'] = float(msgcount[redundancy][nonce]['r']) / float(msgcount[redundancy][nonce]['s'])
msg = sorted(msgcount[redundancy].iteritems(), key=lambda s: s[1]['rs'])
for x in range(len(msg)):
ratiotemp[msg[x][1]["rs"]] = float(x+1) / len(msg);
ratio[redundancy] = sorted(ratiotemp.iteritems())
ratiotemp.clear()
length = max(len(ratio[1]),len(ratio[2]),len(ratio[3]),len(ratio[4]),len(ratio[5]))
for j in range(length):
for i in [1,2,3,4,5]:
if(len(ratio[i])<=j):
writefile.write("null null")
else:
writefile.write(str(ratio[i][j][0])+" "+str(ratio[i][j][1])+ " ")
writefile.write("\n")
def RecvToSendRatioHopnonce(typePrefix, directory):
writefile = open("%(typePrefix)s-rsratio-hopnonce.data"%vars())
writefile.write("#Suggest Filename: %(typePrefix)s-rsratio.data\n#Data for drawing each package in different Amount/Redundancy\n"%vars())
writefile.write("#MPM100 ratio MPM200 ratio MPM300 ratio MPM400 ratio MPM500 ratio MPM600 ratio NoLimit ratio\n")
writefile.write("0 0 0 0 0 0 0 0 0 0 0 0 0 0\n")
backofftime = 2.5 # may subject to change by the data amount wanted to observe
msgcount = {}
ratiotemp = {}
ratio = {}
for mms in [100,200,300,400,500,600,-1]:
msgcount[mms] = {}
for logcontent in ['SI','SD']:
file = open("%(directory)s%(typePrefix)s_mb%(backofftime)s_mms%(mms)s_%(logcontent)s.data"%vars())
for line in file:
if line[0:2] == logcontent:
info = line.split(' ')
for x in info:
if x[0:2] == "Ho":
nonce = x.split(':')[1]
if msgcount[mms].has_key(nonce):
msgcount[mms][nonce]["s"] += 1
else:
msgcount[mms][nonce] = {}
msgcount[mms][nonce]["s"] = 1
msgcount[mms][nonce]["r"] = 0
msgcount[mms][nonce]["rs"] = 0
for logcontent in ['RI','DRD']:
file = open("%(directory)s%(typePrefix)s_mb%(backofftime)s_mms%(mms)s_%(logcontent)s.data"%vars())
for line in file:
if line[0:2] == logcontent or line[0:3] == logcontent:
info = line.split(' ')
for x in info:
if x[0:2] == "Ho":
nonce = x.split(':')[1]
if(msgcount[mms].has_key(nonce)):
msgcount[mms][nonce]["r"] += 1
else:
print logcontent, mms, nonce
for nonce in msgcount[mms]:
msgcount[mms][nonce]['rs'] = float(msgcount[mms][nonce]['r']) / float(msgcount[mms][nonce]['s'])
msg = sorted(msgcount[mms].iteritems(), key=lambda s: s[1]['rs'])
for x in range(len(msg)):
ratiotemp[msg[x][1]["rs"]] = float(x+1) / len(msg);
ratio[mms] = sorted(ratiotemp.iteritems())
ratiotemp.clear()
length = max(len(ratio[100]),len(ratio[200]),len(ratio[300]),len(ratio[400]),len(ratio[500]),len(ratio[-1]))
for j in range(length):
for i in [100,200,300,400,500,600,-1]:
if(len(ratio[i])<=j):
writefile.write("null null")
else:
writefile.write(str(ratio[i][j][0])+" "+str(ratio[i][j][1]))
writefile.write("\n")
#Get recall and latency
def RecallAndLatency(typePrefix, directory):
recallf = open("./%(typePrefix)s-recall.data"%vars(), "w")
latencyf = open("./%(typePrefix)s-latency.data"%vars(), "w")
recallf.write("#Data for recall of the %(typePrefix)s\n"%vars())
latencyf.write("#Data for latency of the %(typePrefix)s\n"%vars())
recallf.write("# row: max_backoff(0 0.5 1 1.5 2 2.5 3)\n")
recallf.write("# col: max_message_size(-1, 200, 400, 600, 800, 1000)\n")
recallf.write("#MaxBackoff No Limits 100 200 300 400 500\n")
latencyf.write("# row: max_backoff(0 0.5 1 1.5 2 2.5 3)\n")
latencyf.write("# col: max_message_size(-1, 200, 400, 600, 800, 1000)\n")
latencyf.write("#MaxBackoff No Limits 100 200 300 400 500\n")
for amount in [10000,20000,30000,40000,50000]:
recallf.write(str(amount)+" ")
<|fim▁hole|> latencyf.write(str(amount)+" ")
for redundancy in [1,2,3,4,5]:
file = open("%(directory)s%(typePrefix)s_da%(amount)s_r%(redundancy)s_0.data"%vars())
line = file.readlines()[-1].split()
recallf.write(str(float(line[1])/amount)+" ")
latencyf.write(line[0]+" ")
file.close()
recallf.write("\n")
latencyf.write("\n")
recallf.close()
latencyf.close()
# os.system("gnuplot collision-avoidance-recall.gp")
# os.system("gnuplot collision-avoidance-latency.gp")
def RSRHeatmap(typePrefix, directory):
amount = 50000
redundancy = 1
sendList = []
recvList = []
ratiolist = []
for i in xrange(100):
sendList.append([])
recvList.append([])
ratiolist.append(0)
for logcontent in ['SI','SD']:
file = open("%(directory)s%(typePrefix)s_da%(amount)s_r%(redundancy)s_%(logcontent)s.data"%vars())
for line in file:
if(line[0:2] == logcontent):
info = line.split(" ")
hopnonce = 0
for x in info:
if x[0:2] == "Ho":
hopnonce = int(x.split(":")[1])
if hopnonce != 0:
sendList[int(info[1])].append(hopnonce)
file.close()
for logcontent in ['RI','DRD']:
file = open("%(directory)s%(typePrefix)s_da%(amount)s_r%(redundancy)s_%(logcontent)s.data"%vars())
for line in file:
if(line[0:2] == logcontent or line[0:3] == logcontent):
info = line.split(" ")
hopnonce = 0
for x in info:
if x[0:2] == "Ho":
hopnonce = int(x.split(":")[1])
if hopnonce != 0:
recvList[int(info[1])].append(hopnonce)
file.close()
for i in xrange(100):
for x in sendList[i]:
recv = 0
for ki in [-11,-10,-9,-1,1,9,10,11]:
if (i+ki >99 or i+ki<0):
continue
elif(i %10 == 0 and (ki == -1 or ki == -11 or ki == 9)):
continue
elif(i % 10 == 9 and (ki == 1 or ki == 11 or ki == -9)):
continue
recv += recvList[i+ki].count(x)
ratiolist[i] += recv
ratiolist[i] /= float(len(sendList[i]))
writefile = open("./%(typePrefix)s-heatmap.data"%vars(), "w")
writefile.write("#Data for receive send ratio on each ndoe of the %(typePrefix)s\n"%vars())
for i in xrange(10):
for j in xrange(10):
writefile.write(str(ratiolist[i*10 + j])+"\t")
writefile.write("\n")
writefile.close()
# os.system("gnuplot collision-avoidance-heatmap.gp")
#MessageSize("baseline", "F:\\Data_baseline\\")
#MessageSize("redundancy_detection", "F:\\Data_redundancy\\")
#RecvToSendRatio("collision_avoidance", "/home/theodore/pecns3/")
#RecallAndLatency("collision_avoidance", "/home/theodore/pecns3/")
#RecvToSendRatioHopnonce("collision_avoidance", "/home/theodore/pecns3/")
#ReceivedConsumer("baseline", "F:\\Data_baseline\\", 44)
#RSRHeatmap("collision_avoidance", "/home/theodore/pecns3/")
#main
if len(sys.argv) <=1:
print "This python program is the automatic processing for the data log of the ns3 simulator of the pec. \nThis particular for the collision avoidance.\n"
print "Useage: choose the function by the first parameter."
print "a. Receive send ratio of each message."
print "b. Receive send ratio of each message by hop."
print "c. Receive send ratio heatmap for each node by each message hop."
print "d. Recall and latency."
print "e. Message overall size"
print "Put this file into the same directory of the data files. Then run \"python\" + filename + chiose to get the picture direcely."
else:
if sys.argv[1] == "a":
RecvToSendRatio("baseline", "./")
elif sys.argv[1] == "b":
RecvToSendRatioHopnonce("baseline", "./")
elif sys.argv[1] == "c":
RSRHeatmap("baseline", "./")
elif sys.argv[1] == "d":
RecallAndLatency("baseline", "./")
elif sys.argv[1] == "e":
MessageSize("baseline", "./")<|fim▁end|> | |
<|file_name|>stefan.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#Author: Stefan Toman
if __name__ == '__main__':
n = int(input())
a = set(map(int, input().split()))
m = int(input())
b = set(map(int, input().split()))
print(len(a-b))<|fim▁end|> | #!/usr/bin/env python3
|
<|file_name|>main.js<|end_file_name|><|fim▁begin|>/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
*
* Google CDN, Latest jQuery
* To use the default WordPress version of jQuery, go to lib/config.php and
* remove or comment out: add_theme_support('jquery-cdn');
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};<|fim▁hole|> $(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
$(document).ready(function(){
$("#sidebar-home ul li").addClass( "col-md-3 col-sm-6" );
$("#sidebar-home div").addClass( "clearfix" );
});<|fim▁end|> |
// Load Events |
<|file_name|>state_test.go<|end_file_name|><|fim▁begin|>package models
import (
"testing"
"time"
)
func TestSetServiceState(t *testing.T) {
err := SetServiceState("testState", time.Now().UTC(), 1)
if err != nil {
t.Error(err)
return
}
}<|fim▁hole|>func TestSetServiceStateByDays(t *testing.T) {
err := SetServiceStateByDays("testStateDays", 0, 1)
if err != nil {
t.Error(err)
return
}
}
func TestGetServiceState(t *testing.T) {
_, i, err := GetServiceState("testState")
if err != nil {
t.Error(err)
return
}
if i != 1 {
t.Error("testState incorrect")
return
}
_, i, err = GetServiceState("testStateDays")
if err != nil {
t.Error(err)
return
}
if i != 1 {
t.Error("testStateDays incorrect")
return
}
}<|fim▁end|> | |
<|file_name|>InitialDirContext.java<|end_file_name|><|fim▁begin|>/*===========================================================================
* Licensed Materials - Property of IBM
* "Restricted Materials of IBM"
*
* IBM SDK, Java(tm) Technology Edition, v8
* (C) Copyright IBM Corp. 1999, 2009. All Rights Reserved
*
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
*===========================================================================
*/
/*
* Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.naming.directory;
import java.util.Hashtable;
import javax.naming.spi.NamingManager;
import javax.naming.*;
/**
* This class is the starting context for performing
* directory operations. The documentation in the class description
* of InitialContext (including those for synchronization) apply here.
*
*
* @author Rosanna Lee
* @author Scott Seligman
*
* @see javax.naming.InitialContext
* @since 1.3
*/
public class InitialDirContext extends InitialContext implements DirContext {
/**
* Constructs an initial DirContext with the option of not
* initializing it. This may be used by a constructor in
* a subclass when the value of the environment parameter
* is not yet known at the time the <tt>InitialDirContext</tt>
* constructor is called. The subclass's constructor will
* call this constructor, compute the value of the environment,
* and then call <tt>init()</tt> before returning.
*
* @param lazy
* true means do not initialize the initial DirContext; false
* is equivalent to calling <tt>new InitialDirContext()</tt>
* @throws NamingException if a naming exception is encountered
*
* @see InitialContext#init(Hashtable)
* @since 1.3
*/
protected InitialDirContext(boolean lazy) throws NamingException {
super(lazy);
}
/**
* Constructs an initial DirContext.
* No environment properties are supplied.
* Equivalent to <tt>new InitialDirContext(null)</tt>.
*
* @throws NamingException if a naming exception is encountered
*
* @see #InitialDirContext(Hashtable)
*/
public InitialDirContext() throws NamingException {
super();
}
/**
* Constructs an initial DirContext using the supplied environment.
* Environment properties are discussed in the
* <tt>javax.naming.InitialContext</tt> class description.
*
* <p> This constructor will not modify <tt>environment</tt>
* or save a reference to it, but may save a clone.
* Caller should not modify mutable keys and values in
* <tt>environment</tt> after it has been passed to the constructor.
*
* @param environment
* environment used to create the initial DirContext.
* Null indicates an empty environment.
*
* @throws NamingException if a naming exception is encountered
*/
public InitialDirContext(Hashtable<?,?> environment)
throws NamingException
{
super(environment);
}
private DirContext getURLOrDefaultInitDirCtx(String name)
throws NamingException {
Context answer = getURLOrDefaultInitCtx(name);
if (!(answer instanceof DirContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of DirContext");
}
}
return (DirContext)answer;
}
private DirContext getURLOrDefaultInitDirCtx(Name name)
throws NamingException {
Context answer = getURLOrDefaultInitCtx(name);
if (!(answer instanceof DirContext)) {
if (answer == null) {
throw new NoInitialContextException();
} else {
throw new NotContextException(
"Not an instance of DirContext");
}
}
return (DirContext)answer;
}
// DirContext methods
// Most Javadoc is deferred to the DirContext interface.
public Attributes getAttributes(String name)
throws NamingException {
return getAttributes(name, null);
}
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds);<|fim▁hole|> return getAttributes(name, null);
}
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getAttributes(name, attrIds);
}
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mod_op, attrs);
}
public void modifyAttributes(String name, ModificationItem[] mods)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods);
}
public void modifyAttributes(Name name, ModificationItem[] mods)
throws NamingException {
getURLOrDefaultInitDirCtx(name).modifyAttributes(name, mods);
}
public void bind(String name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs);
}
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).bind(name, obj, attrs);
}
public void rebind(String name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs);
}
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException {
getURLOrDefaultInitDirCtx(name).rebind(name, obj, attrs);
}
public DirContext createSubcontext(String name, Attributes attrs)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs);
}
public DirContext createSubcontext(Name name, Attributes attrs)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).createSubcontext(name, attrs);
}
public DirContext getSchema(String name) throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchema(name);
}
public DirContext getSchema(Name name) throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchema(name);
}
public DirContext getSchemaClassDefinition(String name)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name);
}
public DirContext getSchemaClassDefinition(Name name)
throws NamingException {
return getURLOrDefaultInitDirCtx(name).getSchemaClassDefinition(name);
}
// -------------------- search operations
public NamingEnumeration<SearchResult>
search(String name, Attributes matchingAttributes)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult>
search(Name name, Attributes matchingAttributes)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, matchingAttributes);
}
public NamingEnumeration<SearchResult>
search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name,
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult>
search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name,
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult>
search(String name,
String filter,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filter, cons);
}
public NamingEnumeration<SearchResult>
search(Name name,
String filter,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filter, cons);
}
public NamingEnumeration<SearchResult>
search(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filterExpr,
filterArgs, cons);
}
public NamingEnumeration<SearchResult>
search(Name name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException
{
return getURLOrDefaultInitDirCtx(name).search(name, filterExpr,
filterArgs, cons);
}
}<|fim▁end|> | }
public Attributes getAttributes(Name name)
throws NamingException { |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Composer models of Kinova robots."""
<|fim▁hole|><|fim▁end|> | from dm_control.entities.manipulators.kinova.jaco_arm import JacoArm
from dm_control.entities.manipulators.kinova.jaco_hand import JacoHand |
<|file_name|>models.go<|end_file_name|><|fim▁begin|>package managedservices
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"encoding/json"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/Azure/go-autorest/tracing"
"github.com/gofrs/uuid"
"net/http"
)
// The package's fully qualified name.
const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/managedservices/mgmt/2019-04-01/managedservices"
// Authorization authorization tuple containing principal Id (of user/service principal/security group) and
// role definition id.
type Authorization struct {
// PrincipalID - Principal Id of the security group/service principal/user that would be assigned permissions to the projected subscription
PrincipalID *string `json:"principalId,omitempty"`
// PrincipalIDDisplayName - Display name of the principal Id.
PrincipalIDDisplayName *string `json:"principalIdDisplayName,omitempty"`
// RoleDefinitionID - The role definition identifier. This role will define all the permissions that the security group/service principal/user must have on the projected subscription. This role cannot be an owner role.
RoleDefinitionID *string `json:"roleDefinitionId,omitempty"`
// DelegatedRoleDefinitionIds - The delegatedRoleDefinitionIds field is required when the roleDefinitionId refers to the User Access Administrator Role. It is the list of role definition ids which define all the permissions that the user in the authorization can assign to other security groups/service principals/users.
DelegatedRoleDefinitionIds *[]uuid.UUID `json:"delegatedRoleDefinitionIds,omitempty"`
}
// ErrorDefinition error response indicates Azure Resource Manager is not able to process the incoming
// request. The reason is provided in the error message.
type ErrorDefinition struct {
// Code - Error code.
Code *string `json:"code,omitempty"`
// Message - Error message indicating why the operation failed.
Message *string `json:"message,omitempty"`
// Details - Internal error details.
Details *[]ErrorDefinition `json:"details,omitempty"`
}
// ErrorResponse error response.
type ErrorResponse struct {
// Error - The error details.
Error *ErrorDefinition `json:"error,omitempty"`
}
// Operation object that describes a single Microsoft.ManagedServices operation.
type Operation struct {
// Name - READ-ONLY; Operation name: {provider}/{resource}/{operation}
Name *string `json:"name,omitempty"`
// Display - READ-ONLY; The object that represents the operation.
Display *OperationDisplay `json:"display,omitempty"`
}
// MarshalJSON is the custom marshaler for Operation.
func (o Operation) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// OperationDisplay the object that represents the operation.
type OperationDisplay struct {
// Provider - Service provider: Microsoft.ManagedServices
Provider *string `json:"provider,omitempty"`
// Resource - Resource on which the operation is performed: Registration definition, registration assignment etc.
Resource *string `json:"resource,omitempty"`
// Operation - Operation type: Read, write, delete, etc.
Operation *string `json:"operation,omitempty"`
// Description - Description of the operation.
Description *string `json:"description,omitempty"`
}
// OperationList list of the operations.
type OperationList struct {
autorest.Response `json:"-"`
// Value - READ-ONLY; List of Microsoft.ManagedServices operations.
Value *[]Operation `json:"value,omitempty"`
}
// MarshalJSON is the custom marshaler for OperationList.
func (ol OperationList) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// Plan plan details for the managed services.
type Plan struct {
// Name - The plan name.
Name *string `json:"name,omitempty"`
// Publisher - The publisher ID.
Publisher *string `json:"publisher,omitempty"`
// Product - The product code.
Product *string `json:"product,omitempty"`
// Version - The plan's version.
Version *string `json:"version,omitempty"`
}
// RegistrationAssignment registration assignment.
type RegistrationAssignment struct {
autorest.Response `json:"-"`
// Properties - Properties of a registration assignment.
Properties *RegistrationAssignmentProperties `json:"properties,omitempty"`
// ID - READ-ONLY; The fully qualified path of the registration assignment.
ID *string `json:"id,omitempty"`
// Type - READ-ONLY; Type of the resource.
Type *string `json:"type,omitempty"`
// Name - READ-ONLY; Name of the registration assignment.
Name *string `json:"name,omitempty"`
}
// MarshalJSON is the custom marshaler for RegistrationAssignment.
func (ra RegistrationAssignment) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if ra.Properties != nil {
objectMap["properties"] = ra.Properties
}
return json.Marshal(objectMap)
}
// RegistrationAssignmentList list of registration assignments.
type RegistrationAssignmentList struct {
autorest.Response `json:"-"`
// Value - READ-ONLY; List of registration assignments.
Value *[]RegistrationAssignment `json:"value,omitempty"`
// NextLink - READ-ONLY; Link to next page of registration assignments.
NextLink *string `json:"nextLink,omitempty"`
}
// MarshalJSON is the custom marshaler for RegistrationAssignmentList.
func (ral RegistrationAssignmentList) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// RegistrationAssignmentListIterator provides access to a complete listing of RegistrationAssignment
// values.
type RegistrationAssignmentListIterator struct {
i int
page RegistrationAssignmentListPage
}
// NextWithContext advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *RegistrationAssignmentListIterator) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentListIterator.NextWithContext")
defer func() {
sc := -1
if iter.Response().Response.Response != nil {
sc = iter.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err = iter.page.NextWithContext(ctx)
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *RegistrationAssignmentListIterator) Next() error {
return iter.NextWithContext(context.Background())
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter RegistrationAssignmentListIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter RegistrationAssignmentListIterator) Response() RegistrationAssignmentList {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter RegistrationAssignmentListIterator) Value() RegistrationAssignment {
if !iter.page.NotDone() {
return RegistrationAssignment{}
}
return iter.page.Values()[iter.i]
}
// Creates a new instance of the RegistrationAssignmentListIterator type.
func NewRegistrationAssignmentListIterator(page RegistrationAssignmentListPage) RegistrationAssignmentListIterator {
return RegistrationAssignmentListIterator{page: page}
}
// IsEmpty returns true if the ListResult contains no values.
func (ral RegistrationAssignmentList) IsEmpty() bool {
return ral.Value == nil || len(*ral.Value) == 0
}
// hasNextLink returns true if the NextLink is not empty.
func (ral RegistrationAssignmentList) hasNextLink() bool {
return ral.NextLink != nil && len(*ral.NextLink) != 0
}
// registrationAssignmentListPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (ral RegistrationAssignmentList) registrationAssignmentListPreparer(ctx context.Context) (*http.Request, error) {
if !ral.hasNextLink() {
return nil, nil
}
return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(ral.NextLink)))
}
// RegistrationAssignmentListPage contains a page of RegistrationAssignment values.
type RegistrationAssignmentListPage struct {
fn func(context.Context, RegistrationAssignmentList) (RegistrationAssignmentList, error)
ral RegistrationAssignmentList
}
// NextWithContext advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *RegistrationAssignmentListPage) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationAssignmentListPage.NextWithContext")
defer func() {
sc := -1
if page.Response().Response.Response != nil {
sc = page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
for {
next, err := page.fn(ctx, page.ral)
if err != nil {
return err
}
page.ral = next
if !next.hasNextLink() || !next.IsEmpty() {
break
}
}
return nil
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *RegistrationAssignmentListPage) Next() error {
return page.NextWithContext(context.Background())
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page RegistrationAssignmentListPage) NotDone() bool {
return !page.ral.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page RegistrationAssignmentListPage) Response() RegistrationAssignmentList {
return page.ral
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page RegistrationAssignmentListPage) Values() []RegistrationAssignment {
if page.ral.IsEmpty() {
return nil
}
return *page.ral.Value
}
// Creates a new instance of the RegistrationAssignmentListPage type.
func NewRegistrationAssignmentListPage(cur RegistrationAssignmentList, getNextPage func(context.Context, RegistrationAssignmentList) (RegistrationAssignmentList, error)) RegistrationAssignmentListPage {
return RegistrationAssignmentListPage{
fn: getNextPage,
ral: cur,
}
}
// RegistrationAssignmentProperties properties of a registration assignment.
type RegistrationAssignmentProperties struct {
// RegistrationDefinitionID - Fully qualified path of the registration definition.
RegistrationDefinitionID *string `json:"registrationDefinitionId,omitempty"`
// ProvisioningState - READ-ONLY; Current state of the registration assignment. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating'
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
// RegistrationDefinition - READ-ONLY; Registration definition inside registration assignment.
RegistrationDefinition *RegistrationAssignmentPropertiesRegistrationDefinition `json:"registrationDefinition,omitempty"`
}
// MarshalJSON is the custom marshaler for RegistrationAssignmentProperties.
func (rap RegistrationAssignmentProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rap.RegistrationDefinitionID != nil {
objectMap["registrationDefinitionId"] = rap.RegistrationDefinitionID
}
return json.Marshal(objectMap)
}
// RegistrationAssignmentPropertiesRegistrationDefinition registration definition inside registration
// assignment.
type RegistrationAssignmentPropertiesRegistrationDefinition struct {
// Properties - Properties of registration definition inside registration assignment.
Properties *RegistrationAssignmentPropertiesRegistrationDefinitionProperties `json:"properties,omitempty"`
// Plan - Plan details for the managed services.
Plan *Plan `json:"plan,omitempty"`
// ID - READ-ONLY; Fully qualified path of the registration definition.
ID *string `json:"id,omitempty"`
// Type - READ-ONLY; Type of the resource (Microsoft.ManagedServices/registrationDefinitions).
Type *string `json:"type,omitempty"`
// Name - READ-ONLY; Name of the registration definition.
Name *string `json:"name,omitempty"`
}
// MarshalJSON is the custom marshaler for RegistrationAssignmentPropertiesRegistrationDefinition.
func (rapD RegistrationAssignmentPropertiesRegistrationDefinition) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rapD.Properties != nil {
objectMap["properties"] = rapD.Properties
}
if rapD.Plan != nil {
objectMap["plan"] = rapD.Plan
}
return json.Marshal(objectMap)
}
// RegistrationAssignmentPropertiesRegistrationDefinitionProperties properties of registration definition
// inside registration assignment.
type RegistrationAssignmentPropertiesRegistrationDefinitionProperties struct {
// Description - Description of the registration definition.
Description *string `json:"description,omitempty"`
// Authorizations - Authorization tuple containing principal id of the user/security group or service principal and id of the build-in role.
Authorizations *[]Authorization `json:"authorizations,omitempty"`
// RegistrationDefinitionName - Name of the registration definition.
RegistrationDefinitionName *string `json:"registrationDefinitionName,omitempty"`
// ProvisioningState - Current state of the registration definition. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating'
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
// ManageeTenantID - Id of the home tenant.
ManageeTenantID *string `json:"manageeTenantId,omitempty"`
// ManageeTenantName - Name of the home tenant.
ManageeTenantName *string `json:"manageeTenantName,omitempty"`
// ManagedByTenantID - Id of the managedBy tenant.
ManagedByTenantID *string `json:"managedByTenantId,omitempty"`
// ManagedByTenantName - Name of the managedBy tenant.
ManagedByTenantName *string `json:"managedByTenantName,omitempty"`
}
// RegistrationAssignmentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of
// a long-running operation.
type RegistrationAssignmentsCreateOrUpdateFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(RegistrationAssignmentsClient) (RegistrationAssignment, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *RegistrationAssignmentsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for RegistrationAssignmentsCreateOrUpdateFuture.Result.
func (future *RegistrationAssignmentsCreateOrUpdateFuture) result(client RegistrationAssignmentsClient) (ra RegistrationAssignment, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
ra.Response.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("managedservices.RegistrationAssignmentsCreateOrUpdateFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if ra.Response.Response, err = future.GetResult(sender); err == nil && ra.Response.Response.StatusCode != http.StatusNoContent {
ra, err = client.CreateOrUpdateResponder(ra.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsCreateOrUpdateFuture", "Result", ra.Response.Response, "Failure responding to request")
}
}
return
}
// RegistrationAssignmentsDeleteFuture an abstraction for monitoring and retrieving the results of a
// long-running operation.
type RegistrationAssignmentsDeleteFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(RegistrationAssignmentsClient) (autorest.Response, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *RegistrationAssignmentsDeleteFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for RegistrationAssignmentsDeleteFuture.Result.
func (future *RegistrationAssignmentsDeleteFuture) result(client RegistrationAssignmentsClient) (ar autorest.Response, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "managedservices.RegistrationAssignmentsDeleteFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
ar.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("managedservices.RegistrationAssignmentsDeleteFuture")
return
}
ar.Response = future.Response()
return
}
// RegistrationDefinition registration definition.
type RegistrationDefinition struct {
autorest.Response `json:"-"`
// Properties - Properties of a registration definition.
Properties *RegistrationDefinitionProperties `json:"properties,omitempty"`
// Plan - Plan details for the managed services.
Plan *Plan `json:"plan,omitempty"`
// ID - READ-ONLY; Fully qualified path of the registration definition.
ID *string `json:"id,omitempty"`
// Type - READ-ONLY; Type of the resource.
Type *string `json:"type,omitempty"`
// Name - READ-ONLY; Name of the registration definition.
Name *string `json:"name,omitempty"`
}
// MarshalJSON is the custom marshaler for RegistrationDefinition.
func (rd RegistrationDefinition) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rd.Properties != nil {
objectMap["properties"] = rd.Properties
}
if rd.Plan != nil {
objectMap["plan"] = rd.Plan
}
return json.Marshal(objectMap)
}
// RegistrationDefinitionList list of registration definitions.
type RegistrationDefinitionList struct {
autorest.Response `json:"-"`
// Value - READ-ONLY; List of registration definitions.
Value *[]RegistrationDefinition `json:"value,omitempty"`
// NextLink - READ-ONLY; Link to next page of registration definitions.
NextLink *string `json:"nextLink,omitempty"`
}
// MarshalJSON is the custom marshaler for RegistrationDefinitionList.
func (rdl RegistrationDefinitionList) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
return json.Marshal(objectMap)
}
// RegistrationDefinitionListIterator provides access to a complete listing of RegistrationDefinition
// values.
type RegistrationDefinitionListIterator struct {
i int
page RegistrationDefinitionListPage
}
// NextWithContext advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
func (iter *RegistrationDefinitionListIterator) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionListIterator.NextWithContext")
defer func() {
sc := -1
if iter.Response().Response.Response != nil {
sc = iter.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
iter.i++
if iter.i < len(iter.page.Values()) {
return nil
}
err = iter.page.NextWithContext(ctx)
if err != nil {
iter.i--
return err
}
iter.i = 0
return nil
}
// Next advances to the next value. If there was an error making
// the request the iterator does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (iter *RegistrationDefinitionListIterator) Next() error {
return iter.NextWithContext(context.Background())
}
// NotDone returns true if the enumeration should be started or is not yet complete.
func (iter RegistrationDefinitionListIterator) NotDone() bool {
return iter.page.NotDone() && iter.i < len(iter.page.Values())
}
// Response returns the raw server response from the last page request.
func (iter RegistrationDefinitionListIterator) Response() RegistrationDefinitionList {
return iter.page.Response()
}
// Value returns the current value or a zero-initialized value if the
// iterator has advanced beyond the end of the collection.
func (iter RegistrationDefinitionListIterator) Value() RegistrationDefinition {
if !iter.page.NotDone() {
return RegistrationDefinition{}
}
return iter.page.Values()[iter.i]
}
// Creates a new instance of the RegistrationDefinitionListIterator type.
func NewRegistrationDefinitionListIterator(page RegistrationDefinitionListPage) RegistrationDefinitionListIterator {
return RegistrationDefinitionListIterator{page: page}
}
// IsEmpty returns true if the ListResult contains no values.
func (rdl RegistrationDefinitionList) IsEmpty() bool {
return rdl.Value == nil || len(*rdl.Value) == 0
}
// hasNextLink returns true if the NextLink is not empty.
func (rdl RegistrationDefinitionList) hasNextLink() bool {
return rdl.NextLink != nil && len(*rdl.NextLink) != 0
}
// registrationDefinitionListPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist.
func (rdl RegistrationDefinitionList) registrationDefinitionListPreparer(ctx context.Context) (*http.Request, error) {
if !rdl.hasNextLink() {
return nil, nil
}
return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(rdl.NextLink)))
}
// RegistrationDefinitionListPage contains a page of RegistrationDefinition values.
type RegistrationDefinitionListPage struct {
fn func(context.Context, RegistrationDefinitionList) (RegistrationDefinitionList, error)
rdl RegistrationDefinitionList
}
// NextWithContext advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
func (page *RegistrationDefinitionListPage) NextWithContext(ctx context.Context) (err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/RegistrationDefinitionListPage.NextWithContext")
defer func() {
sc := -1
if page.Response().Response.Response != nil {
sc = page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
for {
next, err := page.fn(ctx, page.rdl)
if err != nil {
return err
}
page.rdl = next
if !next.hasNextLink() || !next.IsEmpty() {
break
}
}
return nil
}
// Next advances to the next page of values. If there was an error making
// the request the page does not advance and the error is returned.
// Deprecated: Use NextWithContext() instead.
func (page *RegistrationDefinitionListPage) Next() error {
return page.NextWithContext(context.Background())
}
// NotDone returns true if the page enumeration should be started or is not yet complete.
func (page RegistrationDefinitionListPage) NotDone() bool {
return !page.rdl.IsEmpty()
}
// Response returns the raw server response from the last page request.
func (page RegistrationDefinitionListPage) Response() RegistrationDefinitionList {
return page.rdl
}
// Values returns the slice of values for the current page or nil if there are no values.
func (page RegistrationDefinitionListPage) Values() []RegistrationDefinition {
if page.rdl.IsEmpty() {
return nil
}
return *page.rdl.Value
}
// Creates a new instance of the RegistrationDefinitionListPage type.
func NewRegistrationDefinitionListPage(cur RegistrationDefinitionList, getNextPage func(context.Context, RegistrationDefinitionList) (RegistrationDefinitionList, error)) RegistrationDefinitionListPage {
return RegistrationDefinitionListPage{
fn: getNextPage,
rdl: cur,
}
}
// RegistrationDefinitionProperties properties of a registration definition.
type RegistrationDefinitionProperties struct {
// Description - Description of the registration definition.
Description *string `json:"description,omitempty"`
// Authorizations - Authorization tuple containing principal id of the user/security group or service principal and id of the build-in role.
Authorizations *[]Authorization `json:"authorizations,omitempty"`
// RegistrationDefinitionName - Name of the registration definition.
RegistrationDefinitionName *string `json:"registrationDefinitionName,omitempty"`
// ManagedByTenantID - Id of the managedBy tenant.
ManagedByTenantID *string `json:"managedByTenantId,omitempty"`
// ProvisioningState - READ-ONLY; Current state of the registration definition. Possible values include: 'NotSpecified', 'Accepted', 'Running', 'Ready', 'Creating', 'Created', 'Deleting', 'Deleted', 'Canceled', 'Failed', 'Succeeded', 'Updating'
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
// ManagedByTenantName - READ-ONLY; Name of the managedBy tenant.
ManagedByTenantName *string `json:"managedByTenantName,omitempty"`<|fim▁hole|>// MarshalJSON is the custom marshaler for RegistrationDefinitionProperties.
func (rdp RegistrationDefinitionProperties) MarshalJSON() ([]byte, error) {
objectMap := make(map[string]interface{})
if rdp.Description != nil {
objectMap["description"] = rdp.Description
}
if rdp.Authorizations != nil {
objectMap["authorizations"] = rdp.Authorizations
}
if rdp.RegistrationDefinitionName != nil {
objectMap["registrationDefinitionName"] = rdp.RegistrationDefinitionName
}
if rdp.ManagedByTenantID != nil {
objectMap["managedByTenantId"] = rdp.ManagedByTenantID
}
return json.Marshal(objectMap)
}
// RegistrationDefinitionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of
// a long-running operation.
type RegistrationDefinitionsCreateOrUpdateFuture struct {
azure.FutureAPI
// Result returns the result of the asynchronous operation.
// If the operation has not completed it will return an error.
Result func(RegistrationDefinitionsClient) (RegistrationDefinition, error)
}
// UnmarshalJSON is the custom unmarshaller for CreateFuture.
func (future *RegistrationDefinitionsCreateOrUpdateFuture) UnmarshalJSON(body []byte) error {
var azFuture azure.Future
if err := json.Unmarshal(body, &azFuture); err != nil {
return err
}
future.FutureAPI = &azFuture
future.Result = future.result
return nil
}
// result is the default implementation for RegistrationDefinitionsCreateOrUpdateFuture.Result.
func (future *RegistrationDefinitionsCreateOrUpdateFuture) result(client RegistrationDefinitionsClient) (rd RegistrationDefinition, err error) {
var done bool
done, err = future.DoneWithContext(context.Background(), client)
if err != nil {
err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure")
return
}
if !done {
rd.Response.Response = future.Response()
err = azure.NewAsyncOpIncompleteError("managedservices.RegistrationDefinitionsCreateOrUpdateFuture")
return
}
sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if rd.Response.Response, err = future.GetResult(sender); err == nil && rd.Response.Response.StatusCode != http.StatusNoContent {
rd, err = client.CreateOrUpdateResponder(rd.Response.Response)
if err != nil {
err = autorest.NewErrorWithError(err, "managedservices.RegistrationDefinitionsCreateOrUpdateFuture", "Result", rd.Response.Response, "Failure responding to request")
}
}
return
}<|fim▁end|> | }
|
<|file_name|>111815001.py<|end_file_name|><|fim▁begin|>import random
import math
import sympy
from sympy import latex, fraction, Symbol, Rational
localid =11181500100000
letter=["a","b","c","d"]
n=[0,0,0,0,0,0]
m=[0,0,0,0,0]
f = open("111815001.tex","w") #opens file with name of "test.txt"
for x in range(0, 1000):
localid = localid +1
writewrong=["\correctchoice{\(","\wrongchoice{\(","\wrongchoice{\(","\wrongchoice{\("]
for count in range (0,5):
n[count]=random.randint(-20, 20)
m[1]=n[4]-n[2]
m[2]=n[3]-n[1]
m[3]=n[2]-n[1]
m[4]=n[4]-n[3]
if n[2]==n[4]:
letter[0]='undefined'
letter[2]=latex(Rational(-m[3],m[2]))
letter[3]=latex(Rational(-m[4],m[3]))
letter[1]=latex(Rational(m[4],m[3]))
else:
letter[0]=latex(Rational(m[1],m[2]))
letter[1]=latex(Rational(-m[1],m[2]))
letter[2]=latex(Rational(-m[2],m[1]))
letter[3]=latex(Rational(m[2],m[1]))<|fim▁hole|> letter[2]=latex(Rational(m[4],m[3]))
elif zz==3:
letter[3]=latex(Rational(m[4],m[3]))
n[5]=random.randint(0,10)
if n[2]==n[4]:
letter[0]='undefined'
elif n[5]==8:
zz=random.randint(1,3)
letter[zz]='undefined'
if(len(letter)==4):
for z in range (0, 4):
writewrong[z]=writewrong[z]+str(letter[z])
random.shuffle(writewrong)
f.write("\n\n\n")
f.write("\\element{slope}{")
f.write("\n")
f.write("\\begin{question}{")
f.write(str(localid))
f.write("}")
f.write("\n")
f.write("Find the slope using points: (")
f.write(str(n[1]))
f.write(",")
f.write(str(n[2]))
f.write(") and (")
f.write(str(n[3]))
f.write(",")
f.write(str(n[4]))
f.write("):")
f.write("\n")
f.write("\\begin{choiceshoriz}")
f.write("\n")
for y in range(0, 4):
f.write("\n")
f.write(writewrong[y])
f.write("\)}")
f.write("\n")
f.write("\\end{choiceshoriz}")
f.write("\n")
f.write("\\end{question}")
f.write("\n")
f.write("}")
f.close()<|fim▁end|> | zz=random.randint(1,6)
if zz==1:
letter[1]=latex(Rational(m[4],m[3]))
elif zz==2: |
<|file_name|>UDPScanThread.java<|end_file_name|><|fim▁begin|>package com.ks.net;
import java.io.IOException;
import java.net.DatagramPacket;<|fim▁hole|>
import com.ks.activitys.IndexActivity.IndexHandler;
import com.ks.net.enums.MessageEnums;
public class UDPScanThread extends Thread {
private static final int UDPPORT = 9999;
private ArrayList<String> servers;
private DatagramSocket dgSocket = null;
private IndexHandler handler;
public UDPScanThread(ArrayList<String> servers, IndexHandler handler) {
this.servers = servers;
this.handler = handler;
}
public void stopUDP() {
this.interrupt();
if (dgSocket != null) {
dgSocket.close();
dgSocket = null;
}
}
@Override
public void run() {
super.run();
try {
dgSocket = new DatagramSocket();
dgSocket.setSoTimeout(500);
byte b[] = (MessageEnums.UDPSCANMESSAGE + MessageEnums.NETSEPARATOR + android.os.Build.BRAND + "_"
+ android.os.Build.MODEL).getBytes();
DatagramPacket dgPacket = null;
dgPacket = new DatagramPacket(b, b.length, InetAddress.getByName("255.255.255.255"), UDPPORT);
dgSocket.send(dgPacket);
} catch (IOException e3) {
handler.sendEmptyMessage(NUMCODES.NETSTATE.UDPSCANFAIL.getValue());
e3.printStackTrace();
if (dgSocket != null)
dgSocket.close();
return;
}
long start = System.nanoTime();
/** scan for 5 seconds */
while (!isInterrupted() && (System.nanoTime() - start) / 1000000 < 1500) {
byte data[] = new byte[512];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
dgSocket.receive(packet);
String rec = new String(packet.getData(), packet.getOffset(), packet.getLength());
System.out.println(rec);
String[] msgGet = rec.split(MessageEnums.NETSEPARATOR);
if (msgGet != null && msgGet.length == 3 && msgGet[0].equalsIgnoreCase(MessageEnums.UDPSCANRETURN)) {
if (msgGet[1].trim().length() == 0) {
msgGet[1] = "Unknown";
}
String server = msgGet[1] + MessageEnums.UDPSEPARATOR + packet.getAddress().toString().substring(1)
+ ":" + msgGet[2];
servers.add(server);
}
} catch (SocketTimeoutException ex) {
ex.printStackTrace();
continue;
} catch (IOException e) {
e.printStackTrace();
//handler.sendEmptyMessage(NUMCODES.NETSTATE.UDPSCANFAIL.getValue());
if (dgSocket != null)
dgSocket.close();
return;
}
}
if (dgSocket != null) {
dgSocket.close();
}
if (!isInterrupted()) {
handler.sendEmptyMessage(NUMCODES.NETSTATE.UDPSCANOK.getValue());
}
}
}<|fim▁end|> | import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList; |
<|file_name|>widget.ts<|end_file_name|><|fim▁begin|>import {WidgetConfig} from '../shared/widget-config';
import {WidgetService} from '../shared/widget.service';
export class Widget {
title: string;
updateInterval: number = 1000;
widgetConfig: WidgetConfig;
titleUrl: string;
description: string;
constructor(private widgetService: WidgetService) {
}
getTitle(): string {
return this.title;
}
initWidget(widgetConfig: WidgetConfig) {
this.widgetConfig = widgetConfig;
this.title = widgetConfig.title;<|fim▁hole|>
triggerUpdate() {
setInterval(() => {
this.updateWidgetData();
}, this.updateInterval);
}
updateWidgetData() {
this.widgetService.getWidgetData(this.widgetConfig).subscribe(
widgetData => {
if (widgetData.length > 0) {
this.updateData(widgetData);
}
},
error => console.error(error)
);
}
updateData(data: any) {
// log backend errors
for (const sourceData of data) {
if ((sourceData.data || {}).errors) {
sourceData.data.errors.forEach(error => console.error(error));
}
}
// custom logic is implemented by widgets
}
}<|fim▁end|> | this.titleUrl = widgetConfig.titleUrl;
this.description = widgetConfig.description;
this.triggerUpdate();
} |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, url
from .views import MediaLibraryAPIView, MediaLibraryItemView, AddShelfRelationAPIView
<|fim▁hole|>urlpatterns = patterns('',
url(r'^(?P<type>(audio|video|image))/$', MediaLibraryAPIView.as_view(), name='medialibrary'),
url(r'^(?P<pk>\d+)/$', MediaLibraryItemView.as_view(), name='medialibrary-shelf'),
url(r'^(?P<pk>\d+)/add/$', AddShelfRelationAPIView.as_view(), name='medialibrary-shelf-add-relation')
)<|fim▁end|> | |
<|file_name|>msg-ctrl.js<|end_file_name|><|fim▁begin|>define(['./module'], function (controllers) {
'use strict';<|fim▁hole|>});<|fim▁end|> | controllers.controller('msg_ctrl', [function ($scope) {}]); |
<|file_name|>OverviewPanelItem.js<|end_file_name|><|fim▁begin|>///
// Dependencies
///
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import isString from 'lodash/isString';
import * as types from './types';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ExpanderButton from '../elements/ExpanderButton';
import Icon from '../elements/Icon';
import Scrollable from '../elements/Scrollable';
import * as actions from './actions';
import * as formsActions from '../forms/actions';
///
// View
///
class OverviewPanelItemView extends Component {
///
// Construction / Hooks
///
constructor(props) {
super(props);
this.onToggle = this.onToggle.bind(this);<|fim▁hole|> this.onShowForm = this.onShowForm.bind(this);
}
///
// Event handling
///
onToggle() {
this.props.toggleItem(this.props.name);
}
onSelect() {
this.props.selectItem(this.props.name);
}
onShowForm() {
this.props.clearForm(this.props.name);
this.props.showForm(this.props.name);
}
///
// Rendering
///
renderIcon(icon) {
if(! icon) return '';
if(isString(icon)) {
icon = (
<Icon name={icon} />
);
}
return (
<div className="item-icon">
{icon}
</div>
);
}
render() {
const isSelected = this.props.selected === this.props.name;
const isExpanded = isSelected || this.props.overview.getIn(
['panels', this.props.name, 'isExpanded']
);
const itemClassName = classNames('overview-panel-item', {
selected: isSelected,
expanded: isExpanded,
});
return (
<div className={itemClassName}>
<div className="item-header">
<ExpanderButton
expanded={isExpanded}
disabled={isSelected}
onClick={this.onToggle}
/>
<h4
className="item-title"
onClick={this.onSelect}
>
{this.renderIcon(this.props.icon)}
{this.props.title}
</h4>
<Button
className="add-button"
onClick={this.onShowForm}
>
<Icon name="plus" />
</Button>
</div>
<Panel
collapsible expanded={isExpanded}
className="item-content"
>
{this.props.notifications}
<Scrollable>
{this.props.children}
</Scrollable>
</Panel>
</div>
);
}
}
OverviewPanelItemView.propTypes = {
name: PropTypes.string.isRequired,
icon: PropTypes.node,
title: PropTypes.node.isRequired,
selected: PropTypes.string,
notifications: PropTypes.node,
overview: types.Overview.isRequired,
toggleItem: PropTypes.func.isRequired,
selectItem: PropTypes.func.isRequired,
clearForm: PropTypes.func.isRequired,
showForm: PropTypes.func.isRequired,
children: PropTypes.node,
};
export { OverviewPanelItemView };
///
// Container
///
function mapStateToProps(state) {
return {
selected: state.getIn(['overview', 'root', 'selected']),
overview: state.get('overview'),
};
}
function mapDispatchToProps(dispatch) {
return {
toggleItem: (name) => dispatch(actions.toggleItem(name)),
selectItem: (name) => dispatch(actions.selectItem(name)),
clearForm: (name) => dispatch(formsActions.clearForm(name)),
showForm: (name) => dispatch(formsActions.showForm(name)),
};
}
const connector = connect(
mapStateToProps,
mapDispatchToProps
);
export default connector(OverviewPanelItemView);<|fim▁end|> | this.onSelect = this.onSelect.bind(this); |
<|file_name|>csv_converter.py<|end_file_name|><|fim▁begin|># Copyright 2005-2010 Wesabe, 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.
#
# ofxtools.CsvConverter - translate CSV files into OFX files.
#
import datetime
import dateutil.parser
import ofx
import ofxtools
import re
import sys
import xml.sax.saxutils as sax
from decimal import *
from ofx.builder import *
class CsvConverter:
def __init__(self, qif, colspec=None, fid="UNKNOWN", org="UNKNOWN",
bankid="UNKNOWN", accttype="UNKNOWN", acctid="UNKNOWN",
balance="UNKNOWN", curdef=None, lang="ENG", dayfirst=False,
debug=False):
self.qif = qif
self.colspec = colspec
self.fid = fid
self.org = org
self.bankid = bankid
self.accttype = accttype
self.acctid = acctid
self.balance = balance
self.curdef = curdef
self.lang = lang
self.debug = debug
self.dayfirst = dayfirst
self.parsed_csv = None
# FIXME: Move this to one of the OFX generation classes (Document or Response).
self.txns_by_date = {}
if self.debug: sys.stderr.write("Parsing document.\n")
parser = ofxtools.QifParser() # debug=debug)
self.parsed_qif = parser.parse(self.qif)
if self.debug: sys.stderr.write("Cleaning transactions.\n")
# We do a two-pass conversion in order to check the dates of all
# transactions in the statement, and convert all the dates using
# the same date format. The first pass does nothing but look
# at dates; the second actually applies the date conversion and
# all other conversions, and extracts information needed for
# the final output (like date range).
txn_list = self._extract_txn_list(self.parsed_qif)
self._guess_formats(txn_list)
self._clean_txn_list(txn_list)
def _extract_txn_list(self, qif):
stmt_obj = qif.asDict()["QifStatement"]
if self.accttype == "UNKNOWN":
if "BankTransactions" in stmt_obj:
self.accttype = "CHECKING"
elif "CreditCardTransactions" in stmt_obj:
self.accttype = "CREDITCARD"<|fim▁hole|> for txn in stmt:
txn_list.append(txn)
if len(txn_list) == 0:
raise ValueError("Found no transactions to convert " +
"in the QIF source.")
else:
return txn_list
#
# Date methods
#
def _guess_formats(self, txn_list):
# Go through the transactions one at a time, and try to parse the date
# field and currency format. If we check the date format and find a
# transaction where the first number must be the day (that is, the first
# number is in the range 13..31), then set the state of the converter to
# use dayfirst for all transaction cleanups. This is a guess because the
# method will only work for UK dates if the statement contains a day in
# the 13..31 range. (We could also test whether a date appears out of
# order, or whether the jumps between transactions are especially long,
# if this guessing method doesn't work reliably.)
for txn_obj in txn_list:
txn = txn_obj.asDict()
txn_date = txn.get("Date", "UNKNOWN")
txn_currency = txn.get("Currency", "UNKNOWN")
# Look for date format.
parsed_date = self._parse_date(txn_date)
self._check_date_format(parsed_date)
def _parse_date(self, txn_date, dayfirst=False):
def _check_date_format(self, parsed_date):
# If we *ever* find a date that parses as dayfirst, treat
# *all* transactions in this statement as dayfirst.
if parsed_date is not None and parsed_date != "UNKNOWN" and parsed_date.microsecond == 3:
self.dayfirst = True
#
# Cleanup methods
#
def _clean_txn_list(self, txn_list):
for txn_obj in txn_list:
try:
txn = self._clean_txn(txn_obj)
txn_date = txn["Date"]
txn_date_list = self.txns_by_date.get(txn_date, [])
txn_date_list.append(txn)
self.txns_by_date[txn_date] = txn_date_list
except ValueError:
# The _clean_txn method will sometimes find transactions
# that are inherently unclean and are unable to be purified.
# In these cases it will reject the transaction by throwing
# a ValueError, which signals us not to store the transaction.
if self.debug: sys.stderr.write("Skipping transaction '%s'." %
str(txn_obj.asDict()))
# Sort the dates (in YYYYMMDD format) and choose the lowest
# date as our start date, and the highest date as our end
# date.
date_list = self.txns_by_date.keys()
date_list.sort()
self.start_date = date_list[0]
self.end_date = date_list[-1]
def _clean_txn(self, txn_obj):
# This is sort of the brute-force method of the converter. It
# looks at the data we get from the bank and tries as hard as
# possible to make best-effort guesses about what the OFX 2.0
# standard values for the transaction should be. There's a
# reasonable amount of guesswork in here -- some of it wise,
# maybe some of it not. If the cleanup method determines that
# the txn_obj shouldn't be in the data, it will return None.
# Otherwise, it will return a transaction cleaned to the best
# of our abilities.
txn = txn_obj.asDict()
self._clean_txn_date(txn)
self._clean_txn_amount(txn)
self._clean_txn_number(txn)
self._clean_txn_type(txn)
self._clean_txn_payee(txn)
return txn
def _clean_txn_date(self, txn):
txn_date = txn.get("Date", "UNKNOWN").strip()
if txn_date != "UNKNOWN":
parsed_date = self._parse_date(txn_date, dayfirst=self.dayfirst)
txn["Date"] = parsed_date.strftime("%Y%m%d")
else:
txn["Date"] = "UNKNOWN"
def _clean_txn_amount(self, txn):
txn_amount = txn.get("Amount", "00.00")
txn_amount2 = txn.get("Amount2", "00.00")
# Home Depot Credit Card seems to send two transaction records for each
# transaction. They're out of order (that is, the second record is not
# directly after the first, nor even necessarily after it at all), and
# the second one *sometimes* appears to be a memo field on the first one
# (e.g., a credit card payment will show up with an amount and date, and
# then the next transaction will have the same date and a payee that
# reads, "Thank you for your payment!"), and *sometimes* is the real
# payee (e.g., the first will say "Home Depot" and the second will say
# "Seasonal/Garden"). One of the two transaction records will have a
# transaction amount of "-", and the other will have the real
# transaction amount. Ideally, we would pull out the memo and attach it
# to the right transaction, but unless the two transactions are the only
# transactions on that date, there doesn't seem to be a good clue (order
# in statement, amount, etc.) as to how to associate them. So, instead,
# we're returning None, which means this transaction should be removed
# from the statement and not displayed to the user. The result is that
# for Home Depot cards, sometimes we lose the memo (which isn't that big
# a deal), and sometimes we make the memo into the payee (which sucks).
if txn_amount == "-" or txn_amount == " ":
raise ValueError("Transaction amount is undefined.")
# Some QIF sources put the amount in Amount2 instead, for unknown
# reasons. Here we ignore Amount2 unless Amount is unknown.
if txn_amount == "00.00":
txn_amount = txn_amount2
# Okay, now strip out whitespace padding.
txn_amount = txn_amount.strip()
# Some QIF files have dollar signs in the amount. Hey, why not?
txn_amount = txn_amount.replace('$', '', 1)
# Some QIF sources put three digits after the decimal, and the Ruby
# code thinks that means we're in Europe. So.....let's deal with
# that now.
try:
txn_amount = str(Decimal(txn_amount).quantize(Decimal('.01')))
except:
# Just keep truckin'.
pass
txn["Amount"] = txn_amount
def _clean_txn_number(self, txn):
txn_number = txn.get("Number", "UNKNOWN").strip()
# Clean up bad check number behavior
all_digits = re.compile("\d+")
if txn_number == "N/A":
# Get rid of brain-dead Chase check number "N/A"s
del txn["Number"]
elif txn_number.startswith("XXXX-XXXX-XXXX"):
# Home Depot credit cards throw THE CREDIT CARD NUMBER
# into the check number field. Oy! At least they mask
# the first twelve digits, so we know they're insane.
del txn["Number"]
elif txn_number != "UNKNOWN" and self.accttype == "CREDITCARD":
# Several other credit card companies (MBNA, CapitalOne)
# seem to use the number field as a transaction ID. Get
# rid of this.
del txn["Number"]
elif txn_number == "0000000000" and self.accttype != "CREDITCARD":
# There's some bank that puts "N0000000000" in every non-check
# transaction. (They do use normal check numbers for checks.)
del txn["Number"]
elif txn_number != "UNKNOWN" and all_digits.search(txn_number):
# Washington Mutual doesn't indicate a CHECK transaction
# when a check number is present.
txn["Type"] = "CHECK"
def _clean_txn_type(self, txn):
txn_type = "UNKNOWN"
txn_amount = txn.get("Amount", "UNKNOWN")
txn_payee = txn.get("Payee", "UNKNOWN")
txn_memo = txn.get("Memo", "UNKNOWN")
txn_number = txn.get("Number", "UNKNOWN")
txn_sign = self._txn_sign(txn_amount)
# Try to figure out the transaction type from the Payee or
# Memo field.
for typestr in self.txn_types.keys():
if txn_number == typestr:
# US Bank sends "DEBIT" or "CREDIT" as a check number
# on credit card transactions.
txn["Type"] = self.txn_types[typestr]
del txn["Number"]
break
elif txn_payee.startswith(typestr + "/") or \
txn_memo.startswith(typestr + "/") or \
txn_memo == typestr or txn_payee == typestr:
if typestr == "ACH" and txn_sign == "credit":
txn["Type"] = "DIRECTDEP"
elif typestr == "ACH" and txn_sign == "debit":
txn["Type"] = "DIRECTDEBIT"
else:
txn["Type"] = self.txn_types[typestr]
break
def _clean_txn_payee(self, txn):
txn_payee = txn.get("Payee", "UNKNOWN")
txn_memo = txn.get("Memo", "UNKNOWN")
txn_number = txn.get("Number", "UNKNOWN")
txn_type = txn.get("Type", "UNKNOWN")
txn_amount = txn.get("Amount", "UNKNOWN")
txn_sign = self._txn_sign(txn_amount)
# Try to fill in the payee field with some meaningful value.
if txn_payee == "UNKNOWN":
if txn_number != "UNKNOWN" and (self.accttype == "CHECKING" or
self.accttype == "SAVINGS"):
txn["Payee"] = "Check #%s" % txn_number
txn["Type"] = "CHECK"
elif txn_type == "INT" and txn_sign == "debit":
txn["Payee"] = "Interest paid"
elif txn_type == "INT" and txn_sign == "credit":
txn["Payee"] = "Interest earned"
elif txn_type == "ATM" and txn_sign == "debit":
txn["Payee"] = "ATM Withdrawal"
elif txn_type == "ATM" and txn_sign == "credit":
txn["Payee"] = "ATM Deposit"
elif txn_type == "POS" and txn_sign == "debit":
txn["Payee"] = "Point of Sale Payment"
elif txn_type == "POS" and txn_sign == "credit":
txn["Payee"] = "Point of Sale Credit"
elif txn_memo != "UNKNOWN":
txn["Payee"] = txn_memo
# Down here, we have no payee, no memo, no check number,
# and no type. Who knows what this stuff is.
elif txn_type == "UNKNOWN" and txn_sign == "debit":
txn["Payee"] = "Other Debit"
txn["Type"] = "DEBIT"
elif txn_type == "UNKNOWN" and txn_sign == "credit":
txn["Payee"] = "Other Credit"
txn["Type"] = "CREDIT"
# Make sure the transaction type has some valid value.
if not txn.has_key("Type") and txn_sign == "debit":
txn["Type"] = "DEBIT"
elif not txn.has_key("Type") and txn_sign == "credit":
txn["Type"] = "CREDIT"
def _txn_sign(self, txn_amount):
# Is this a credit or a debit?
if txn_amount.startswith("-"):
return "debit"
else:
return "credit"
#
# Conversion methods
#
def to_ofx102(self):
if self.debug: sys.stderr.write("Making OFX/1.02.\n")
return DOCUMENT(self._ofx_header(),
OFX(self._ofx_signon(),
self._ofx_stmt()))
def to_xml(self):
ofx102 = self.to_ofx102()
if self.debug:
sys.stderr.write(ofx102 + "\n")
sys.stderr.write("Parsing OFX/1.02.\n")
response = ofx.Response(ofx102) #, debug=self.debug)
if self.debug: sys.stderr.write("Making OFX/2.0.\n")
if self.dayfirst:
date_format = "DD/MM/YY"
else:
date_format = "MM/DD/YY"
xml = response.as_xml(original_format="QIF", date_format=date_format)
return xml<|fim▁end|> |
txn_list = []
for stmt in stmt_obj: |
<|file_name|>element.js<|end_file_name|><|fim▁begin|>/**
* The DOM Element unit handling
*
* Copyright (C) 2008-2011 Nikolay Nemshilov
*/
var Element = RightJS.Element = new Class(Wrapper, {
/**
* constructor
*
* NOTE: this constructor will dynamically typecast
* the wrappers depending on the element tag-name
*
* @param String element tag name or an HTMLElement instance
* @param Object options
* @return Element element
*/
initialize: function(element, options) {
Element_initialize(this, element, options);
}
}, Element_Klass),
Element_wrappers = Element.Wrappers = {},
elements_cache = {},
/**
* bulds dom-elements
*
* @param String element tag name
* @param Object options
* @return HTMLElement
*/
make_element = function (tag, options) {
return (tag in elements_cache ? elements_cache[tag] : (
elements_cache[tag] = document.createElement(tag)
)).cloneNode(false);
};
//
// IE 6,7,8 (not 9!) browsers have a bug with checkbox and radio input elements
// it doesn't place the 'checked' property correctly, plus there are some issues
// with clonned SELECT objects, so we are replaceing the elements maker in here
//
if (IE8_OR_LESS) {<|fim▁hole|> '" type="'+ options.type +'"'+
(options.checked ? ' checked' : '') + ' />';
delete(options.name);
delete(options.type);
}
return document.createElement(tag);
};
}
/**
* Basic element's constructor
*
* @param Element wrapper instance
* @param mixed raw dom element of a string tag name
* @param Object options
* @return void
*/
function Element_initialize(inst, element, options) {
if (typeof element === 'string') {
inst._ = make_element(element, options);
if (options !== undefined) {
for (var key in options) {
switch (key) {
case 'id': inst._.id = options[key]; break;
case 'html': inst._.innerHTML = options[key]; break;
case 'class': inst._.className = options[key]; break;
case 'on': inst.on(options[key]); break;
default: inst.set(key, options[key]);
}
}
}
} else {
inst._ = element;
}
}<|fim▁end|> | make_element = function(tag, options) {
if (options !== undefined && (tag === 'input' || tag === 'button')) {
tag = '<'+ tag +' name="'+ options.name + |
<|file_name|>ask.js<|end_file_name|><|fim▁begin|>//you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate input
function configureParams() {
var nameRequest = event["body-json"];
hash.update(event["context"]["source-ip"]);
var hashedIpAddress = hash.digest('hex');
var blocking_string = hashedIpAddress;
var session_expiry = 3600;
if (nameRequest.vname) {
var v1ValidationFilter = /^The ([a-z]|[A-Z])+ ([a-z]|[A-Z])+ of ([a-z]|[A-Z]|[0-9]|-| )+([a-z]|[A-Z]|[0-9])$/i;
if (v1ValidationFilter.test(nameRequest.vname)) {
var vname_components = [];
var vname_version = 'v1';
var vnameMacroParts = nameRequest.vname.split(' of ');
var vnameCity = vnameMacroParts[1];
var vnameColorAndAnimal = vnameMacroParts[0];
var vnameMicroParts = vnameColorAndAnimal.split(' ');
var vnameColor = vnameMicroParts[1];
var vnameAnimal = vnameMicroParts[2];
vname_components = [vnameColor, vnameAnimal, vnameCity];
}
else {
context.done(null, { "error": "vname doesn't match current versions" });
return null;
}
/* SAMPLE DATA, uncomment if you want to use it
vname_version = 'v1';
vname_components = ['brown','bear','Chicago'];
blocking_string = 0383176601762cf74cb95607034b9c7712a431325074396e073d7eb4e5206edc; //just a hash of the user's IP address, you could use a cookie or deviceId as well
session_expiry = 600; // 10 minute connection
*/
sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry);
}
else {
return null;
}
return null;
}
function sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry) {
var payload = { "vname_version": vname_version, "vname_components": vname_components, "blocking_string": blocking_string, "session_expiry_sec": session_expiry };
payload = JSON.stringify(payload);
console.log(payload);
const options = {
hostname: 'api.voicesignin.com',
port: 443,
path: '/ask',
method: 'POST',
headers: {
'Content-Type': 'application/json',
//********************************************************************
'Authorization': '' // add your API key here
//********************************************************************
}
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
// console.log('data:',res.data);
var rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {<|fim▁hole|> if (requestResponse.request_id !== undefined) {
context.done(null, requestResponse);
return null;
}
else {
context.done(null, { "error": "invalid request" });
return null;
}
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(payload);
req.end();
}
};<|fim▁end|> |
var requestResponse = JSON.parse(rawData);
console.log('reqresp: ' + JSON.stringify(requestResponse)); |
<|file_name|>Stixai.py<|end_file_name|><|fim▁begin|>import random
class ai:
def __init__(self, actions, responses):
self.IN = actions
self.OUT = responses
def get_act(self, action, valres):
if action in self.IN:
mList = {}
for response in self.OUT:
if self.IN[self.OUT.index(response)] == action and not response in mList:
mList[response] = 1
elif response in mList:
mList[response] += 1
print mList
keys = []
vals = []
for v in sorted(mList.values(), reverse = True):
for k in mList.keys():
if mList[k] == v:
keys.append(k)
vals.append(v)
print keys
print vals
try:
resp = keys[valres]
except:
resp = random.choice(self.OUT)
else:
resp = random.choice(self.OUT)
<|fim▁hole|> self.IN = ins
self.OUT = outs
def test():
stix = ai(['attack', 'retreat', 'eat', 'attack', 'attack'], ['run', 'cheer', 'share lunch', 'fall', 'run'])
print stix.get_act('attack', 0)
#test()<|fim▁end|> | return resp
def update(ins, outs):
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Combines sequences of arithmetic or logical instructions into single instructions.
//! For every instruction, try to combine one of its operands into itself. This
//! transforms linear data-dependency chains into trees.
use analysis::analyzer::{
Action, Analyzer, AnalyzerInfo, AnalyzerKind, AnalyzerResult, Change, FuncAnalyzer,
};
use frontend::radeco_containers::RadecoFunction;
use middle::ir::MOpcode;
use middle::ssa::ssa_traits::*;
use middle::ssa::ssastorage::SSAStorage;
use either::*;
use std::any::Any;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
mod combine_rules;
type SSAValue = <SSAStorage as SSA>::ValueRef;
/// Represents binary operations that are effectively unary because one of the
/// operands is constant. In other words, represents curried binary operations.
/// e.g. `(|x| 7 & x)`, `(|x| x + 3)`, etc.
#[derive(Clone)]
pub struct CombinableOpInfo(MOpcode, CombinableOpConstInfo);
#[derive(Clone, Debug)]
pub enum CombinableOpConstInfo {
/// no const, like in `(|x| !x)`
Unary,
/// const is on the left, like in `(|x| 3 - x)`
Left(u64),
/// const is on the right, like in `(|x| x - 3)`
Right(u64),
}
use self::CombinableOpConstInfo as COCI;
#[derive(Debug)]
pub struct CombineChange {
/// Index of the node to combine.
node: SSAValue,
/// Left: The node and one of its args were combined. The tuple contains: the
/// structure of the combined node (if the node is a no-op then `None` is present)
/// and the index of the non-const operand of the combined node.
/// Right: The node and its args were combined into a constant value.
res: Either<(Option<CombinableOpInfo>, SSAValue), u64>,
}
impl Change for CombineChange {
fn as_any(&self) -> &dyn Any {
self
}
}
enum CombErr {
/// The op-info is not combinable.
NoComb,
<|fim▁hole|> /// An abort request was raised.
Abort,
}
const NAME: &str = "combiner";
const REQUIRES: &[AnalyzerKind] = &[];
pub const INFO: AnalyzerInfo = AnalyzerInfo {
name: NAME,
kind: AnalyzerKind::Combiner,
requires: REQUIRES,
uses_policy: true,
};
#[derive(Debug)]
pub struct Combiner {
/// Nodes that could potentially be combined into another
combine_candidates: HashMap<SSAValue, (SSAValue, CombinableOpInfo)>,
}
impl Combiner {
pub fn new() -> Self {
Combiner {
combine_candidates: HashMap::new(),
}
}
/// Returns `Some(new_node)` if one of `cur_node`'s operands can be combined
/// into `cur_node`, resulting in `new_node`; or, if `cur_node` could be
/// simplified, resulting in `new_node`. In both cases `Action::Apply` was returned
/// by the policy function.
/// Returns `Err(CombErr::NoComb)` if no simplification can occur.
/// Returns `Err(CombErr::Skip)` if the policy function returned `Action::Skip`.
/// Returns `Err(CombErr::Abort)` if the policy function returned `Action::Abort`.
fn visit_node<T: FnMut(Box<Change>) -> Action>(
&mut self,
cur_node: SSAValue,
ssa: &mut SSAStorage,
policy: &mut T,
) -> Result<SSAValue, CombErr> {
// bail if non-combinable
let extracted = extract_opinfo(cur_node, ssa).ok_or(CombErr::NoComb)?;
match extracted {
Left((sub_node, cur_opinfo, cur_vt)) => {
radeco_trace!(
"trying to combine ({:?} = {:?} {:?})",
cur_node,
sub_node,
cur_opinfo
);
let opt_new_node =
self.make_combined_node(cur_node, &cur_opinfo, cur_vt, sub_node, ssa, policy);
match opt_new_node {
Ok(Left((new_node, new_sub_node, new_opinfo))) => {
radeco_trace!(
" {:?} ==> ({:?} = {:?} {:?})",
cur_node,
new_node,
new_sub_node,
new_opinfo
);
self.combine_candidates
.insert(new_node, (new_sub_node, new_opinfo));
Ok(new_node)
}
Ok(Right(new_node)) => {
radeco_trace!(" {:?} ==> no-op", cur_node);
Ok(new_node)
}
Err(comb_err) => {
if let CombErr::NoComb = comb_err {
// no change; still add to `combine_candidates`
self.combine_candidates
.insert(cur_node, (sub_node, cur_opinfo));
}
Err(comb_err)
}
}
}
Right(c_val) => {
let action = policy(Box::new(CombineChange {
node: cur_node,
res: Right(c_val),
}));
match action {
Action::Apply => {
// combined to constant
radeco_trace!("{:?} = {:#x}", cur_node, c_val);
let c_node = ssa.insert_const(c_val, None).ok_or(CombErr::NoComb)?;
Ok(c_node)
}
Action::Skip => Err(CombErr::Skip),
Action::Abort => Err(CombErr::Abort),
}
}
}
}
/// Returns `Left(new_node, new_sub_node, new_opinfo)` if `cur_opinfo`
/// combined with an operand or if `cur_opinfo` was simplified.
/// Returns `Right(new_node)` if `cur_opinfo` canceled with an
/// operand to make a no-op or was originally a no-op.
/// Returns `Err(CombErr::NoComb)` if no combination or simplification exists.
/// Returns `Err(CombErr::Skip)` if the policy function returned `Action::Skip`.
/// Returns `Err(CombErr::Abort)` if the policy funcion returned `Action::Abort`.
fn make_combined_node<T: FnMut(Box<Change>) -> Action>(
&self,
cur_node: SSAValue,
cur_opinfo: &CombinableOpInfo,
cur_vt: ValueInfo,
sub_node: SSAValue,
ssa: &mut SSAStorage,
policy: &mut T,
) -> Result<Either<(SSAValue, SSAValue, CombinableOpInfo), SSAValue>, CombErr> {
let (new_opinfo, new_sub_node) = self
.combine_opinfo(cur_opinfo, sub_node)
.map(|(oi, sn)| (Cow::Owned(oi), sn))
.unwrap_or((Cow::Borrowed(cur_opinfo), sub_node));
// simplify
match simplify_opinfo(&new_opinfo) {
Some(Some(simpl_new_opinfo)) => {
let action = policy(Box::new(CombineChange {
node: cur_node,
res: Left((Some(simpl_new_opinfo.clone()), new_sub_node)),
}));
match action {
Action::Apply => {
radeco_trace!(
" simplified ({:?}) into ({:?})",
new_opinfo,
simpl_new_opinfo
);
// make the new node
let new_node =
make_opinfo_node(cur_vt, simpl_new_opinfo.clone(), new_sub_node, ssa)
.ok_or(CombErr::NoComb)?;
Ok(Left((new_node, new_sub_node, simpl_new_opinfo)))
}
Action::Skip => Err(CombErr::Skip),
Action::Abort => Err(CombErr::Abort),
}
}
Some(None) => {
let action = policy(Box::new(CombineChange {
node: cur_node,
res: Left((None, new_sub_node)),
}));
match action {
Action::Apply => {
radeco_trace!(" simplified ({:?}) into no-op", new_opinfo);
Ok(Right(new_sub_node))
}
Action::Skip => Err(CombErr::Skip),
Action::Abort => Err(CombErr::Abort),
}
}
None => {
// no simplification
match new_opinfo {
Cow::Borrowed(_) => Err(CombErr::NoComb),
Cow::Owned(new_opinfo) => {
let action = policy(Box::new(CombineChange {
node: cur_node,
res: Left((Some(new_opinfo.clone()), new_sub_node)),
}));
match action {
Action::Apply => {
// combined, but no further simplification
let new_node =
make_opinfo_node(cur_vt, new_opinfo.clone(), new_sub_node, ssa)
.ok_or(CombErr::NoComb)?;
Ok(Left((new_node, new_sub_node, new_opinfo)))
}
Action::Skip => Err(CombErr::Skip),
Action::Abort => Err(CombErr::Abort),
}
}
}
}
}
}
/// Tries to combine `sub_node` into `cur_opinfo`.
/// Returns `None` if no combination exists.
fn combine_opinfo(
&self,
cur_opinfo: &CombinableOpInfo,
sub_node: SSAValue,
) -> Option<(CombinableOpInfo, SSAValue)> {
let &(sub_sub_node, ref sub_opinfo) = self.combine_candidates.get(&sub_node)?;
let new_opinfo = combine_rules::combine_opinfo(cur_opinfo, sub_opinfo)?;
radeco_trace!(
" combined ({:?} {:?}) into ({:?})",
sub_opinfo,
cur_opinfo,
new_opinfo
);
Some((new_opinfo, sub_sub_node))
}
}
impl Analyzer for Combiner {
fn info(&self) -> &'static AnalyzerInfo {
&INFO
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl FuncAnalyzer for Combiner {
fn analyze<T: FnMut(Box<Change>) -> Action>(
&mut self,
func: &mut RadecoFunction,
policy: Option<T>,
) -> Option<Box<AnalyzerResult>> {
let ssa = func.ssa_mut();
let mut policy = policy.expect("A policy function must be provided");
for node in ssa.inorder_walk() {
let res = self.visit_node(node, ssa, &mut policy);
if let Ok(repl_node) = res {
let blk = ssa.block_for(node).unwrap();
let addr = ssa.address(node).unwrap();
ssa.replace_value(node, repl_node);
if !ssa.is_constant(repl_node) && ssa.address(repl_node).is_none() {
ssa.insert_into_block(repl_node, blk, addr);
}
}
if let Err(CombErr::Abort) = res {
return None;
}
}
None
}
}
/// Creates an SSA node from the given `CombinableOpInfo`.
/// Returns `None` on SSA error.
fn make_opinfo_node(
vt: ValueInfo,
opinfo: CombinableOpInfo,
sub_node: SSAValue,
ssa: &mut SSAStorage,
) -> Option<SSAValue> {
let ret = ssa.insert_op(opinfo.0, vt, None)?;
match opinfo.1 {
COCI::Unary => {
ssa.op_use(ret, 0, sub_node);
}
COCI::Left(new_c) => {
let new_cnode = ssa.insert_const(new_c, None)?;
ssa.op_use(ret, 0, new_cnode);
ssa.op_use(ret, 1, sub_node);
}
COCI::Right(new_c) => {
let new_cnode = ssa.insert_const(new_c, None)?;
ssa.op_use(ret, 0, sub_node);
ssa.op_use(ret, 1, new_cnode);
}
};
Some(ret)
}
/// Returns an equivalent `CombinableOpInfo`, but "simpler" in some sence.
/// Currently, this converts `OpAdd`s or `OpSub`s with "negative" constants into
/// equivalent operations with positive constants.
/// Returns `Some(None)` if `info` is a no-op.
/// Returns `None` if no simplification exists.
fn simplify_opinfo(info: &CombinableOpInfo) -> Option<Option<CombinableOpInfo>> {
use self::CombinableOpConstInfo as COCI;
use self::CombinableOpInfo as COI;
use middle::ir::MOpcode::*;
match info {
COI(OpAdd, COCI::Left(0))
| COI(OpAdd, COCI::Right(0))
| COI(OpSub, COCI::Right(0))
| COI(OpAnd, COCI::Left(0xFFFFFFFFFFFFFFFF))
| COI(OpAnd, COCI::Right(0xFFFFFFFFFFFFFFFF))
| COI(OpOr, COCI::Left(0))
| COI(OpOr, COCI::Right(0))
| COI(OpXor, COCI::Left(0))
| COI(OpXor, COCI::Right(0)) => Some(None),
COI(OpAdd, COCI::Left(c)) | COI(OpAdd, COCI::Right(c)) if *c > u64::max_value() / 2 => {
let c = OpSub.eval_binop(0, *c).unwrap();
Some(Some(COI(OpSub, COCI::Right(c))))
}
COI(OpSub, COCI::Right(c)) if *c > u64::max_value() / 2 => {
let c = OpSub.eval_binop(0, *c).unwrap();
Some(Some(COI(OpAdd, COCI::Left(c))))
}
_ => None,
}
}
/// Returns `Some(Left(_))` if `cur_node` has exactly one non-const operand.
/// Returns `Some(Right(_))` if `cur_node` has all const operands.
/// Returns `None` if `cur_node` is non-combinable.
fn extract_opinfo(
cur_node: SSAValue,
ssa: &SSAStorage,
) -> Option<Either<(SSAValue, CombinableOpInfo, ValueInfo), u64>> {
// bail if non-`NodeType::Op`
let (cur_opcode, cur_vt) = extract_opcode(cur_node, ssa)?;
let cur_operands = ssa.operands_of(cur_node);
match cur_operands.as_slice() {
&[sub_node] => {
let cur_opinfo = CombinableOpInfo(cur_opcode, COCI::Unary);
Some(Left((sub_node, cur_opinfo, cur_vt)))
}
&[sub_node1, sub_node2] => {
match (ssa.constant(sub_node1), ssa.constant(sub_node2)) {
(Some(c1), Some(c2)) => {
// this is const_prop's job, but we can do this here too
// bail if `cur_opcode` is non-evalable, since that also
// implies it's non-combinable
let res_val = cur_opcode.eval_binop(c1, c2)?;
Some(Right(res_val))
}
(None, Some(c)) => {
let cur_opinfo = CombinableOpInfo(cur_opcode, COCI::Right(c));
Some(Left((sub_node1, cur_opinfo, cur_vt)))
}
(Some(c), None) => {
let cur_opinfo = CombinableOpInfo(cur_opcode, COCI::Left(c));
Some(Left((sub_node2, cur_opinfo, cur_vt)))
}
(None, None) => None,
}
}
_ => None,
}
}
fn extract_opcode(node: SSAValue, ssa: &SSAStorage) -> Option<(MOpcode, ValueInfo)> {
if let NodeData {
vt,
nt: NodeType::Op(opcode),
} = ssa.node_data(node).ok()?
{
Some((opcode, vt))
} else {
None
}
}
impl fmt::Debug for CombinableOpInfo {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.1 {
COCI::Unary => fmt.write_fmt(format_args!("-> ({:?} .)", self.0)),
COCI::Left(c) => fmt.write_fmt(format_args!("-> ({:#x} {:?} .)", c, self.0)),
COCI::Right(c) => fmt.write_fmt(format_args!("-> (. {:?} {:#x})", self.0, c)),
}
}
}<|fim▁end|> | /// Skip this substitution.
Skip,
|
<|file_name|>ribi_create_tally_test.cpp<|end_file_name|><|fim▁begin|>#include "ribi_create_tally.h"
#include <iostream>
#include <fstream>
// Boost.Test does not play well with -Weffc++
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#include <boost/test/unit_test.hpp>
using namespace ribi;
BOOST_AUTO_TEST_CASE(test_ribi_create_tally)
{
{
const std::vector<std::string> v = {};
const std::map<std::string, int> expected = {};
const auto result = ::create_tally(v);
BOOST_CHECK(result == expected);
}
{
const std::vector<std::string> v = { "A" };
const std::map<std::string, int> expected = { {"A", 1} };
const auto result = ::create_tally(v);
BOOST_CHECK(result == expected);
}
{
const std::vector<std::string> v = { "A", "A" };
const std::map<std::string, int> expected = { {"A", 2} };
const auto result = ::create_tally(v);<|fim▁hole|> const std::map<std::string, int> expected = { {"A", 1}, { "B", 1} };
const auto result = ::create_tally(v);
BOOST_CHECK(result == expected);
}
{
const std::vector<std::string> v = { "A", "A", "B" };
const std::map<std::string, int> expected = { {"A", 2}, {"B", 1} };
const auto result = ::create_tally(v);
BOOST_CHECK(result == expected);
}
{
const std::vector<std::string> v = { "B", "A", "A" };
const std::map<std::string, int> expected = { {"A", 2}, {"B", 1} };
const auto result = ::create_tally(v);
BOOST_CHECK(result == expected);
}
}
#pragma GCC diagnostic pop<|fim▁end|> | BOOST_CHECK(result == expected);
}
{
const std::vector<std::string> v = { "A", "B" }; |
<|file_name|>q14.py<|end_file_name|><|fim▁begin|>"""
问题描述:给定一个正数数组arr,其中所有的值都为整数,以下是最小不可组成和的概念:
1)把arr每个子集内的所有元素加起来会出现很多值,其中最小的记为min,最大的记为max.
2)在区间[min,max]上,如果有数不可以被arr某一个子集相加得到,那么其中最小的那个数是
arr的最小不可组成和.
3)在区间[min,max]上,如果所有的数都可以被arr的某一个子集相加得到,那么max+1是arr
的最小不可组成和.
请写函数返回正数数组arr的最小不可组成和.
举例:
arr=[3, 2, 5],子集{2}相加产生2为min,子集{3, 2, 5}相加产生10为max.在区间[2, 10]
上,4、6和9不能被任何子集相加得到,其中4是arr的最小不可组成和.
arr=[1,2,4]。子集{1}相加产生1为min,子集{1,2,4}相加产生7为max。在区间[1,7]上,任何
数都可以被子集相加得到,所以8是arr的最小不可组成和.
进阶题目:
如果已知正数数组arr中肯定有1这个数,是否能更快地得到最小不可组成和?
"""
import sys
class UnformedSum:
@classmethod
def unformed_sum(cls, arr):
if not arr:
return 1
my_set = set()
cls.process(arr, 0, 0, my_set)
min_value = sys.maxsize
for i in arr:
min_value = min([min_value, i])
i = min_value
while True:
if i not in my_set:
return i
i += 1
@classmethod
def process(cls, arr, index, cur_sum, cur_set):
if index == len(arr):<|fim▁hole|> cls.process(arr, index+1, cur_sum, cur_set)
@classmethod
def unformed_sum_dp(cls, arr):
if not arr:
return 1
max_sum = sum(arr)
min_value = min(arr)
dp = [False for _ in range(max_sum+1)]
dp[0] = True
for i in arr:
dp[i] = True
for i in range(len(arr)):
for j in range(arr[i]+1, max_sum-arr[i]+1):
if dp[j] is True:
dp[j+arr[i]] = True
for i in range(min_value, len(dp)):
if not dp[i]:
return i
return max_sum+1
@classmethod
def unformed_sum_contined_1(cls, arr):
if not arr:
return 1
sorted_arr = sorted(arr)
sum_val = 0
for i in range(len(sorted_arr)):
if sum_val + 1 < sorted_arr[i]:
return sum_val + 1
sum_val += arr[i]
return sum_val + 1
if __name__ == '__main__':
print(UnformedSum.unformed_sum_dp([3, 2, 5]))
print(UnformedSum.unformed_sum_dp([1, 2, 4]))
print(UnformedSum.unformed_sum_contined_1([1, 2, 4]))<|fim▁end|> | cur_set.add(cur_sum)
return
cls.process(arr, index+1, cur_sum+arr[index], cur_set) |
<|file_name|>docente-model.js<|end_file_name|><|fim▁begin|>define(['backbone', 'underscore'], function (Backbone, _) {
return Backbone.Model.extend({<|fim▁hole|> defaults: {
persona: {
personaPnombre: '',
personaSnombre: '',
personaApaterno: '',
personaAmaterno: '',
dni: ''
}
},
validate: function (attrs, options) {
console.log('persona', attrs.persona);
if (_.isUndefined(attrs.persona)) {
return {
field: 'persona',
error: 'Debe definir una persona'
};
}
if (_.isUndefined(attrs.persona.personaDni) || _.isEmpty(attrs.persona.personaDni.trim()) || attrs.persona.personaDni.trim().length != 8) {
return {
field: 'persona-personaDni',
error: 'El dni es un campo obligatorio y debe tener 8 caracteres.'
};
}
if (_.isUndefined(attrs.persona.personaPnombre) || _.isEmpty(attrs.persona.personaPnombre.trim())) {
return {
field: 'persona-personaPnombre',
error: 'El primer nombre es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaApaterno) || _.isEmpty(attrs.persona.personaApaterno.trim())) {
return {
field: 'persona-personaApaterno',
error: 'El apellido paterno es un campo obligatorio.'
};
}
if (_.isUndefined(attrs.persona.personaAmaterno) || _.isEmpty(attrs.persona.personaAmaterno.trim())) {
return {
field: 'persona-personaAmaterno',
error: 'El apellido materno es un campo obligatorio.'
};
}
}
});
});<|fim▁end|> | idAttribute: 'username', |
<|file_name|>bot.cpp<|end_file_name|><|fim▁begin|>/*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2012 <copyright holder> <email>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bot.h"
#include "../communication/boost/concept_check.hpp"
Bot::Bot() {
position.x = 20;
position.y = 20;
color = al_map_rgb(255, 0, 0);
AI = true;
init();
}
Bot::Bot(slm::vec2 p):position(p) {
color = al_map_rgb(255, 0, 0);
AI = true;
init();
}
Bot::Bot(slm::vec2 p, ALLEGRO_COLOR c):position(p),color(c) {
AI = true;
init();
}
void Bot::init() {
currentPath = -1;
orientation = 0;
velocity = slm::vec2(0,0);
rotation = 0;
sterring = new Sterring(slm::vec2(0,0), 0);
health = 100;
ammo = 50;
dead = false;
}
Bot::~Bot() {}
void Bot::render() {
ostringstream ss;
if(health > 0) {
ss << "h:" << health << " a:" << ammo;
al_draw_filled_circle(position.x, position.y, 20, color);
al_draw_filled_circle(nearestNode->position.x, nearestNode->position.y, 5, al_map_rgb(160, 160, 0));
al_draw_text(font, al_map_rgb(0, 0, 0), position.x, position.y - 30, ALLEGRO_ALIGN_CENTRE, ss.str().c_str());
Pathfinding::getInstance().drawPath(currentPath);
} else {
ss << "DEAD";
al_draw_filled_circle(position.x, position.y, 20, al_map_rgb(150,150,150));
al_draw_text(font, al_map_rgb(0, 0, 0), position.x, position.y - 30, ALLEGRO_ALIGN_CENTRE, ss.str().c_str());
}
}
void Bot::setMap(AIMap* m) {
map = m;
}
void Bot::setPosition(slm::vec2 p) {
position = p;
}
void Bot::setSterring(Sterring *s)
{
sterring = s;
}
void Bot::findNearestNode() {
if(dead) return;
float minDist = map->size.x*map->size.y;
for(int i = 0; i < map->graphNodes.size(); i++) {
float dist = slm::distance(position, map->graphNodes[i]->position);
if(dist < minDist) {
minDist = dist;<|fim▁hole|> }
}
}
void Bot::getSterring()
{
sterring = Pathfinding::getInstance().getSterring(position, currentPath);
}
void Bot::updatePosition(float time) {
if(dead) return;
if(AI) getSterring();
position += velocity * time;
orientation += rotation * time;
velocity += sterring->linear * time;
// let player be faster
if(AI) velocity = slm::clamp(velocity, slm::vec2(-MAX_SPEED,-MAX_SPEED), slm::vec2(MAX_SPEED,MAX_SPEED));
else velocity = slm::clamp(velocity, slm::vec2(-2*MAX_SPEED,-2*MAX_SPEED), slm::vec2(2*MAX_SPEED,2*MAX_SPEED));
rotation += sterring->angular * time;
if(slm::length(sterring->linear) == 0) {
velocity *= (1.0 - FRICTION*time);
if(slm::length(velocity) < (MAX_SPEED*0.5)) velocity = slm::vec2(0,0);
}
updateNearestNode();
}
void Bot::updateNearestNode() {
float minDist = slm::distance(position, nearestNode->position);
if(minDist > 2*map->distance) {
findNearestNode();
return;
}
AIMap_Node* newNearest = nearestNode;
for(int i = 0; i < nearestNode->neighbours.size(); i++) {
float tmpDist = slm::distance(position, nearestNode->neighbours[i]->position);
if(tmpDist < minDist) {
minDist = tmpDist;
newNearest = nearestNode->neighbours[i];
}
}
nearestNode = newNearest;
}
AIMap_Node* Bot::getNearestNode()
{
return nearestNode;
}
void Bot::setFollow(Followable* f)
{
followed = f;
}<|fim▁end|> | nearestNode = map->graphNodes[i]; |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
<|fim▁hole|>setup(name='my_project',
version='0.1.0',
packages=['my_project'],
entry_points={
'console_scripts': [
'my_project = crawler.__main__:main'
]
},
install_requires='requests'
)<|fim▁end|> | from setuptools import setup
|
<|file_name|>HotelRepository.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stt.data.jpa.service;
import com.stt.data.jpa.domain.City;
import com.stt.data.jpa.domain.Hotel;
import com.stt.data.jpa.domain.HotelSummary;
import com.stt.data.jpa.domain.RatingCount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import java.util.List;
interface HotelRepository extends Repository<Hotel, Long> {
<|fim▁hole|> Page<HotelSummary> findByCity(City city, Pageable pageable);
@Query("select r.rating as rating, count(r) as count "
+ "from Review r where r.hotel = ?1 group by r.rating order by r.rating DESC")
List<RatingCount> findRatingCounts(Hotel hotel);
}<|fim▁end|> | Hotel findByCityAndName(City city, String name);
@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
+ "from Hotel h left outer join h.reviews r where h.city = ?1 group by h") |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# scikit-survival documentation build configuration file
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from datetime import datetime
import inspect
import os
from pathlib import Path
import re
import sys
from nbconvert.preprocessors import Preprocessor
import nbsphinx
from setuptools_scm import get_version
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
# https://docs.readthedocs.io/en/latest/faq.html?highlight=environ#how-do-i-change-behavior-for-read-the-docs
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
if on_rtd:
sys.path.insert(0, os.path.abspath(os.path.pardir))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.8'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.extlinks',
'sphinx.ext.linkcode',
'sphinx.ext.mathjax',
'sphinx.ext.napoleon',
'nbsphinx',
]
autosummary_generate = True
autodoc_default_options = {
'members': None,
'inherited-members': None,
}
# Napoleon settings
napoleon_google_docstring = False
napoleon_include_init_with_doc = False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'scikit-survival'
current_year = datetime.utcnow().year
copyright = f'2015-{current_year}, Sebastian Pölsterl and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
if on_rtd:
release = get_version(root='..', relative_to=__file__)
else:
import sksurv
release = sksurv.__version__
# The short X.Y.Z version.
version = '.'.join(release.split('.')[:3])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# The default language to highlight source code in.
highlight_language = 'none'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '**/README.*', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.<|fim▁hole|># If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
# pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
nbsphinx_execute = 'never'
nbsphinx_prolog = r"""
{% set docname = "doc/" + env.doc2path(env.docname, base=None) %}
{% set notebook = env.doc2path(env.docname, base=None)|replace("user_guide/", "notebooks/") %}
{% set branch = 'master' if 'dev' in env.config.release else 'v{}'.format(env.config.release) %}
.. raw:: html
<div class="admonition note" style="line-height: 150%;">
This page was generated from
<a class="reference external" href="https://github.com/sebp/scikit-survival/blob/{{ branch|e }}/{{ docname|e }}">{{ docname|e }}</a>.<br/>
Interactive online version:
<span style="white-space: nowrap;"><a href="https://mybinder.org/v2/gh/sebp/scikit-survival/{{ branch|e }}?urlpath=lab/tree/{{ notebook|e }}"><img alt="Binder badge" src="https://mybinder.org/badge_logo.svg" style="vertical-align:text-bottom"></a>.</span>
</div>
"""
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'pydata_sphinx_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"github_url": "https://github.com/sebp/scikit-survival",
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "scikit-survival {0}".format(version)
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
html_css_files = ['custom.css']
html_js_files = ['buttons.js']
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
extlinks = {
'issue': ('https://github.com/sebp/scikit-survival/issues/%s', '#'),
}
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
Adapted from scipy.
"""
import sksurv
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.split('.'):
try:
obj = getattr(obj, part)
except AttributeError:
return None
try:
fn = inspect.getsourcefile(obj)
except TypeError:
fn = None
if fn is None and hasattr(obj, '__module__'):
fn = inspect.getsourcefile(sys.modules[obj.__module__])
if fn is None:
return None
try:
source, lineno = inspect.getsourcelines(obj)
except ValueError:
lineno = None
if lineno:
linespec = '#L%d-L%d' % (lineno, lineno + len(source) - 1)
else:
linespec = ''
startdir = Path(sksurv.__file__).parent.parent.absolute()
if not fn.startswith(str(startdir)): # not in sksurv
return None
fn = '/'.join(Path(fn).relative_to(startdir).parts)
if fn.startswith('sksurv/'):
m = re.match(r'^.*dev[0-9]+\+g([a-f0-9]+)$', release)
if m:
branch = m.group(1)
elif 'dev' in release:
branch = 'master'
else:
branch = 'v{}'.format(release)
return 'https://github.com/sebp/scikit-survival/blob/{branch}/{filename}{linespec}'.format(
branch=branch,
filename=fn,
linespec=linespec
)
else:
return None
class RTDUrlPreprocessor(Preprocessor):
"""Convert URLs to RTD in notebook to relative urls."""
URL_PATTERN = re.compile(
r'\(https://scikit-survival\.readthedocs\.io/.+?/.+?/([-._a-zA-Z0-9/]+)/(.+?)\.html.*?\)'
)
DOC_DIR = Path(__file__).parent
def preprocess_cell(self, cell, resources, index):
# path of notebook directory, relative to conf.py
nb_path = Path(resources['metadata']['path']).relative_to(self.DOC_DIR)
to_root = [os.pardir] * len(nb_path.parts)
if cell.cell_type == 'markdown':
text = cell.source
replace = []
for match in self.URL_PATTERN.finditer(text):
path = to_root[:]
path.append(match.group(1))
rel_url = "/".join(path)
filename = match.group(2)
replace.append((match.group(0), '({}/{}.rst)'.format(rel_url, filename)))
for s, r in replace:
text = text.replace(s, r)
cell.source = text
return cell, resources
return cell, resources
def _from_notebook_node(self, nb, resources, **kwargs):
filters = [RTDUrlPreprocessor(), ]
for f in filters:
nb, resources = f.preprocess(nb, resources=resources)
return nbsphinx_from_notebook_node(self, nb, resources=resources, **kwargs)
# see https://github.com/spatialaudio/nbsphinx/issues/305#issuecomment-506748814-permalink
nbsphinx_from_notebook_node = nbsphinx.Exporter.from_notebook_node
nbsphinx.Exporter.from_notebook_node = _from_notebook_node
# ------------------------
# Mock dependencies on RTD
# ------------------------
if on_rtd:
MOCK_MODULES = [
# external dependencies
'ecos',
'joblib',
'numexpr',
'numpy',
'osqp',
'pandas',
'pandas.api.types',
'scipy',
'scipy.integrate',
'scipy.io.arff',
'scipy.linalg',
'scipy.optimize',
'scipy.sparse',
'scipy.special',
'scipy.stats',
'sklearn',
'sklearn.base',
'sklearn.dummy',
'sklearn.ensemble',
'sklearn.ensemble._base',
'sklearn.ensemble._forest',
'sklearn.ensemble._gb',
'sklearn.ensemble._gb_losses',
'sklearn.ensemble._gradient_boosting',
'sklearn.ensemble.base',
'sklearn.ensemble.forest',
'sklearn.ensemble.gradient_boosting',
'sklearn.exceptions',
'sklearn.externals.joblib',
'sklearn.linear_model',
'sklearn.metrics',
'sklearn.metrics.pairwise',
'sklearn.model_selection',
'sklearn.pipeline',
'sklearn.preprocessing',
'sklearn.svm',
'sklearn.tree',
'sklearn.tree._classes',
'sklearn.tree._splitter',
'sklearn.tree._tree',
'sklearn.tree.tree',
'sklearn.utils',
'sklearn.utils._joblib',
'sklearn.utils.extmath',
'sklearn.utils.fixes',
'sklearn.utils.metaestimators',
'sklearn.utils.validation',
# our C modules
'sksurv.bintrees._binarytrees',
'sksurv.ensemble._coxph_loss',
'sksurv.kernels._clinical_kernel',
'sksurv.linear_model._coxnet',
'sksurv.svm._minlip',
'sksurv.svm._prsvm',
'sksurv.tree._criterion']
from unittest.mock import Mock
class MockModule(Mock):
"""mock imports"""
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
elif name[0] == name[0].upper() and name[0] != "_":
# Not very good, we assume Uppercase names are classes...
mocktype = type(name, (), {})
mocktype.__module__ = __name__
return mocktype
else:
return MockModule()
sys.modules.update((mod_name, MockModule()) for mod_name in MOCK_MODULES)
else:
from sklearn.ensemble._gb import BaseGradientBoosting
# Remove inherited API doc to avoid sphinx's duplicate object description error
BaseGradientBoosting.feature_importances_.__doc__ = None<|fim▁end|> | #add_function_parentheses = True
|
<|file_name|>common.py<|end_file_name|><|fim▁begin|>import os
from typing import Dict, List, Union
OptionalJSON = Union[List, Dict, float, int, str, bool, None]
def ensure_dir_exists(directory):
if not os.path.exists(directory):
os.mkdir(directory)
def get_dir(directory: str) -> str:
"""
Return a string which contains the complete path to the input directory<|fim▁hole|> Current directory structure:
PATinderBot
src
img
like
match
nope
json
data
:param directory: string of the directory to search for
:return: string with the complete path to the searched for directory
"""
current_dir = os.path.dirname(__file__)
project_dir = os.path.join(current_dir, '..')
result = os.path.join(project_dir, directory)
ensure_dir_exists(result)
return result<|fim▁end|> | |
<|file_name|>oauth.js.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for JavaScript software for implementing an OAuth consumer
// Project: https://code.google.com/p/oauth/
// Definitions by: NOBUOKA Yu <https://github.com/nobuoka>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare namespace OAuth {
/** An Array of name-value pairs [[name, value], [name2, value2]]. */
type ParameterList = [string, string][];
/** A map {name: value, name2: value2}. */
type ParameterMap = { [name: string]: string; };
type ParameterListOrMap = ParameterList|ParameterMap;
/**
* An OAuth message is represented as an object like this:
* { method: "GET", action: "http://server.com/path", parameters: ... }
*/
interface Message {
action: string;
method: string;
parameters: ParameterListOrMap;
}
/**
* SignatureMethod expects an accessor object to be like this:
* {tokenSecret: "lakjsdflkj...", consumerSecret: "QOUEWRI..", accessorSecret: "xcmvzc..."}
* The accessorSecret property is optional.
*/
interface Accessor {
consumerKey: string;
consumerSecret: string;
accessorSecret?: string;
token: string;
tokenSecret: string;
}
/**
* Encode text value according to OAuth Percent Encoding.
* @see {@link https://tools.ietf.org/html/rfc5849#section-3.6}
* @param s Target text value.
*/
function percentEncode(s: string): string;
/**
* Encode text values according to OAuth Percent Encoding.<|fim▁hole|> * @param s Target text values.
*/
function percentEncode(s: string[]): string;
/**
* Decode percent-encoded value.
* @see {@link https://tools.ietf.org/html/rfc5849#section-3.6}
* @param s Target percent-encoded value.
*/
function decodePercent(s: string): string;
/**
* Convert the given parameters to an Array of name-value pairs.
*/
function getParameterList(parameters: ParameterListOrMap): ParameterList;
/**
* Convert the given parameters to an Array of name-value pairs.
*/
function getParameterList(parameters: string): ParameterList;
/**
* Convert the given parameters to a map from name to value.
*/
function getParameterMap(parameters: ParameterListOrMap): ParameterMap;
/**
* Convert the given parameters to a map from name to value.
*/
function getParameterMap(parameters: string): ParameterMap;
function getParameter(parameters: ParameterListOrMap, name: string): string;
function getParameter(parameters: string, name: string): string;
function formEncode(parameters: ParameterListOrMap): string;
function decodeForm(form: string): ParameterList;
function setParameter(message: Message, name: string, value: string): void;
function setParameters(message: Message, parameters: ParameterListOrMap): void;
function setParameters(message: Message, parameters: string): void;
/**
* Fill in parameters to help construct a request message.
* This function doesn't fill in every parameter.
* @param message Target request message.
* @param accessor Accessor object. The accessorSecret property is optional.
*/
function completeRequest(message: Message, accessor: Accessor): void;
function setTimestampAndNonce(message: Message): void;
/**
* Add specified parameters into URL as query parameters.
* @param url URL that parameters added into.
* @param parameters Parameters added into URL.
* @return New URL string.
*/
function addToURL(url: string, parameters: ParameterListOrMap): string;
/** Construct the value of the Authorization header for an HTTP request. */
function getAuthorizationHeader(realm: string, parameters: ParameterListOrMap): string;
function getAuthorizationHeader(realm: string, parameters: string): string;
/** Correct the time using a parameter from the URL from which the last script was loaded. */
function correctTimestampFromSrc(parameterName?: string): void;
/** Generate timestamps starting with the given value. */
function correctTimestamp(timestamp: number): void;
/** The difference between the correct time and my clock. */
var timeCorrectionMsec: number;
function timestamp(): number;
function nonce(length: number): string;
interface Uri {
source: string;
protocol: string;
authority: string;
userInfo: string;
user: string;
password: string;
host: string;
port: string;
relative: string;
path: string;
directory: string;
file: string;
query: string;
anchor: string;
}
interface SignatureMethodStatic {
sign(message: Message, accessor: Accessor): void;
/** Instantiate a SignatureMethod for the given method name. */
newMethod(name: string, accessor: Accessor): SignatureMethod;
/** A map from signature method name to constructor. */
REGISTERED: { [name: string]: { new (): SignatureMethod }; };
/**
* Subsequently, the given constructor will be used for the named methods.
* The constructor will be called with no parameters.
* The resulting object should usually implement getSignature(baseString).
* You can easily define such a constructor by calling makeSubclass method.
*/
registerMethodClass(names: string[], classConstructor: { new(): SignatureMethod }): void;
/**
* Create a subclass of OAuth.SignatureMethod, with the given getSignature function.
* @param getSignatureFunction
*/
makeSubclass(getSignatureFunction: (baseString: string) => string): { new(): SignatureMethod };
/**
* Generate a signature base string from a Message object.
* @see {@link https://tools.ietf.org/html/rfc5849#section-3.4.1}
* @param message Source of the signature base string.
*/
getBaseString(message: Message): string;
normalizeUrl(url: string): string;
parseUri(str: string): Uri;
normalizeParameters(parameters: ParameterListOrMap): string;
}
interface SignatureMethod {
getSignature(baseString: string): string;
key: string;
/** Add a signature to the message. */
sign(message: Message): string;
/** Set the key string for signing. */
initialize(name: string, accessor: Accessor): void;
}
var SignatureMethod: SignatureMethodStatic;
}<|fim▁end|> | * Encoded values are joined with an ampersand character (&) in between them.
* @see {@link https://tools.ietf.org/html/rfc5849#section-3.6} |
<|file_name|>jquery.inputmask.numeric.extensions-2.5.0.js<|end_file_name|><|fim▁begin|>/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - 2014 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 2.5.0
Optional extensions on the jquery.inputmask base
*/
(function ($) {
//number aliases
$.extend($.inputmask.defaults.aliases, {
'decimal': {
mask: "~",
placeholder: "",
repeat: "*",
greedy: false,
numericInput: false,<|fim▁hole|> groupSize: 3,
autoGroup: false,
allowPlus: true,
allowMinus: true,
//todo
integerDigits: "*", //number of integerDigits
defaultValue: "",
prefix: "",
suffix: "",
//todo
getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { //custom getMaskLength to take the groupSeparator into account
var calculatedLength = buffer.length;
if (!greedy) {
if (repeat == "*") {
calculatedLength = currentBuffer.length + 1;
} else if (repeat > 1) {
calculatedLength += (buffer.length * (repeat - 1));
}
}
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint);
var currentBufferStr = currentBuffer.join(''), strippedBufferStr = currentBufferStr.replace(new RegExp(escapedGroupSeparator, "g"), "").replace(new RegExp(escapedRadixPoint), ""),
groupOffset = currentBufferStr.length - strippedBufferStr.length;
return calculatedLength + groupOffset;
},
postFormat: function (buffer, pos, reformatOnly, opts) {
if (opts.groupSeparator == "") return pos;
var cbuf = buffer.slice(),
radixPos = $.inArray(opts.radixPoint, buffer);
if (!reformatOnly) {
cbuf.splice(pos, 0, "?"); //set position indicator
}
var bufVal = cbuf.join('');
if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), '');
var radixSplit = bufVal.split(opts.radixPoint);
bufVal = radixSplit[0];
var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})');
while (reg.test(bufVal)) {
bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2');
bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
}
if (radixSplit.length > 1)
bufVal += opts.radixPoint + radixSplit[1];
}
buffer.length = bufVal.length; //align the length
for (var i = 0, l = bufVal.length; i < l; i++) {
buffer[i] = bufVal.charAt(i);
}
var newPos = $.inArray("?", buffer);
if (!reformatOnly) buffer.splice(newPos, 1);
return reformatOnly ? pos : newPos;
},
regex: {
number: function (opts) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint);
var digitExpression = isNaN(opts.digits) ? opts.digits : '{0,' + opts.digits + '}';
var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : "";
return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)(" + escapedRadixPoint + "\\d" + digitExpression + ")?$");
}
},
onKeyDown: function (e, buffer, opts) {
var $input = $(this), input = this;
if (e.keyCode == opts.keyCode.TAB) {
var radixPosition = $.inArray(opts.radixPoint, buffer);
if (radixPosition != -1) {
var masksets = $input.data('_inputmask')['masksets'];
var activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex'];
for (var i = 1; i <= opts.digits && i < opts.getMaskLength(masksets[activeMasksetIndex]["_buffer"], masksets[activeMasksetIndex]["greedy"], masksets[activeMasksetIndex]["repeat"], buffer, opts) ; i++) {
if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == "") buffer[radixPosition + i] = "0";
}
input._valueSet(buffer.join(''));
}
} else if (e.keyCode == opts.keyCode.DELETE || e.keyCode == opts.keyCode.BACKSPACE) {
opts.postFormat(buffer, 0, true, opts);
input._valueSet(buffer.join(''));
return true;
}
},
definitions: {
'~': { //real number
validator: function (chrs, buffer, pos, strict, opts) {
if (chrs == "") return false;
if (!strict && pos <= 1 && buffer[0] === '0' && new RegExp("[\\d-]").test(chrs) && buffer.join('').length == 1) { //handle first char
buffer[0] = "";
return { "pos": 0 };
}
var cbuf = strict ? buffer.slice(0, pos) : buffer.slice();
cbuf.splice(pos, 0, chrs);
var bufferStr = cbuf.join('');
//strip groupseparator
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
bufferStr = bufferStr.replace(new RegExp(escapedGroupSeparator, "g"), '');
var isValid = opts.regex.number(opts).test(bufferStr);
if (!isValid) {
//let's help the regex a bit
bufferStr += "0";
isValid = opts.regex.number(opts).test(bufferStr);
if (!isValid) {
//make a valid group
var lastGroupSeparator = bufferStr.lastIndexOf(opts.groupSeparator);
for (var i = bufferStr.length - lastGroupSeparator; i <= 3; i++) {
bufferStr += "0";
}
isValid = opts.regex.number(opts).test(bufferStr);
if (!isValid && !strict) {
if (chrs == opts.radixPoint) {
isValid = opts.regex.number(opts).test("0" + bufferStr + "0");
if (isValid) {
buffer[pos] = "0";
pos++;
return { "pos": pos };
}
}
}
}
}
if (isValid != false && !strict && chrs != opts.radixPoint) {
var newPos = opts.postFormat(buffer, pos, false, opts);
return { "pos": newPos };
}
return isValid;
},
cardinality: 1,
prevalidator: null
}
},
insertMode: true,
autoUnmask: false
},
'integer': {
regex: {
number: function (opts) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : "";
return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)$");
}
},
alias: "decimal"
}
});
})(jQuery);<|fim▁end|> | isNumeric: true,
digits: "*", //number of fractionalDigits
groupSeparator: "",//",", // | "."
radixPoint: ".", |
<|file_name|>outlier_cleaner.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import math
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
"""
### your code goes here
data = []
for i in xrange(len(ages)):
data.append((ages[i], net_worths[i], _error(predictions[i], net_worths[i])))
sorted_data = sorted(data, key = lambda x: x[2])
<|fim▁hole|>
length = int(0.9 * len(sorted_data))
return sorted_data[0:length]
def _error(expected, actual):
return math.pow(actual - expected, 2)<|fim▁end|> | print sorted_data |
<|file_name|>pastetext.js<|end_file_name|><|fim▁begin|>/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.dialog.add( 'pastetext', function( editor )
{
return {
title : editor.lang.pasteText.title,
minWidth : CKEDITOR.env.ie && CKEDITOR.env.quirks ? 368 : 350,
minHeight : 240,
onShow : function(){ this.setupContent(); },
onOk : function(){ this.commitContent(); },
contents :
[
{
label : editor.lang.common.generalTab,
id : 'general',
elements :
[
{
type : 'html',
id : 'pasteMsg',
html : '<div style="white-space:normal;width:340px;">' + editor.lang.clipboard.pasteMsg + '</div>'
},
{
<|fim▁hole|> id : 'content',
className : 'cke_pastetext',
onLoad : function()
{
var label = this.getDialog().getContentElement( 'general', 'pasteMsg' ).getElement(),
input = this.getElement().getElementsByTag( 'textarea' ).getItem( 0 );
input.setAttribute( 'aria-labelledby', label.$.id );
input.setStyle( 'direction', editor.config.contentsLangDirection );
},
focus : function()
{
this.getElement().focus();
},
setup : function()
{
this.setValue( '' );
},
commit : function()
{
var value = this.getValue();
setTimeout( function()
{
editor.fire( 'paste', { 'text' : value } );
}, 0 );
}
}
]
}
]
};
});
})();<|fim▁end|> | type : 'textarea',
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>import numpy as np
import time
import matplotlib.pyplot as plt
from AndorSpectrometer import Spectrometer
spec = Spectrometer(start_cooler=False,init_shutter=True)
#time.sleep(30)
spec.SetCentreWavelength(650)
spec.SetSlitWidth(100)
# spec.SetImageofSlit()
# slit = spec.TakeImageofSlit()
#
#
spec.SetSingleTrack()
spec.SetExposureTime(5.0)
d = spec.TakeSingleTrack()
spec.SetExposureTime(1)
d2 = spec.TakeSingleTrack()
#
# spec.SetFullImage()
# img = spec.TakeFullImage()
#<|fim▁hole|>#
# print(d.shape)
plt.plot(spec.GetWavelength(),d)
plt.show()
plt.plot(spec.GetWavelength(),d2)
plt.show()
# plt.imshow(img)
# plt.show()
#
# plt.imshow(slit)
# plt.show()<|fim▁end|> | |
<|file_name|>base.js<|end_file_name|><|fim▁begin|>if(!Hummingbird) { var Hummingbird = {}; }
Hummingbird.Base = function() {};
Hummingbird.Base.prototype = {
validMessageCount: 0,
messageRate: 20,
initialize: function() {
this.averageLog = [];
this.setFilter();
this.registerHandler();
},
registerHandler: function() {
this.socket.registerHandler(this.onData, this);
},
onMessage: function(message) {
console.log("Base class says: " + JSON.stringify(message));
},
onData: function(fullData) {
var average;
var message = this.extract(fullData);
if(typeof(message) != "undefined") {
this.validMessageCount += 1;
// Calculate the average over N seconds if the averageOver option is set
if(this.options.averageOver) { average = this.addToAverage(message); }
if((!this.options.every) || (this.validMessageCount % this.options.every == 0)) {<|fim▁hole|> },
extract: function(data) {
if(typeof(data) == "undefined") { return; }
var obj = data;
for(var i = 0, len = this.filter.length; i < len; i++) {
obj = obj[this.filter[i]];
if(typeof(obj) == "undefined") { return; }
}
return obj;
},
setFilter: function() {
// TODO: extend this (and extract) to support multiple filters
var obj = this.options.data;
this.filter = [];
while(typeof(obj) == "object") {
for(var i in obj) {
this.filter.push(i);
obj = obj[i];
break;
}
}
},
addToAverage: function(newValue) {
var averageCount = this.options.averageOver * this.messageRate;
this.averageLog.push(newValue);
if(this.averageLog.length > averageCount) {
this.averageLog.shift();
}
},
average: function() {
if(this.averageLog.length == 0) { return 0; }
return this.averageLog.sum() * 1.0 / this.averageLog.length * this.messageRate;
}
};<|fim▁end|> | this.onMessage(message, this.average());
}
} |
<|file_name|>test_acl.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import os
from swift3.test.functional import Swift3FunctionalTestCase
from swift3.test.functional.s3_test_client import Connection, \
get_tester2_connection<|fim▁hole|>
class TestSwift3Acl(Swift3FunctionalTestCase):
def setUp(self):
super(TestSwift3Acl, self).setUp()
self.bucket = 'bucket'
self.obj = 'object'
self.conn.make_request('PUT', self.bucket)
self.conn2 = get_tester2_connection()
def test_acl(self):
self.conn.make_request('PUT', self.bucket, self.obj)
query = 'acl'
# PUT Bucket ACL
headers = {'x-amz-acl': 'public-read'}
status, headers, body = \
self.conn.make_request('PUT', self.bucket, headers=headers,
query=query)
self.assertEqual(status, 200)
self.assertCommonResponseHeaders(headers)
self.assertEqual(headers['content-length'], '0')
# GET Bucket ACL
status, headers, body = \
self.conn.make_request('GET', self.bucket, query=query)
self.assertEqual(status, 200)
self.assertCommonResponseHeaders(headers)
# TODO: Fix the response that last-modified must be in the response.
# self.assertTrue(headers['last-modified'] is not None)
self.assertEqual(headers['content-length'], str(len(body)))
self.assertTrue(headers['content-type'] is not None)
elem = fromstring(body, 'AccessControlPolicy')
owner = elem.find('Owner')
self.assertEqual(owner.find('ID').text, self.conn.user_id)
self.assertEqual(owner.find('DisplayName').text, self.conn.user_id)
acl = elem.find('AccessControlList')
self.assertTrue(acl.find('Grant') is not None)
# GET Object ACL
status, headers, body = \
self.conn.make_request('GET', self.bucket, self.obj, query=query)
self.assertEqual(status, 200)
self.assertCommonResponseHeaders(headers)
# TODO: Fix the response that last-modified must be in the response.
# self.assertTrue(headers['last-modified'] is not None)
self.assertEqual(headers['content-length'], str(len(body)))
self.assertTrue(headers['content-type'] is not None)
elem = fromstring(body, 'AccessControlPolicy')
owner = elem.find('Owner')
self.assertEqual(owner.find('ID').text, self.conn.user_id)
self.assertEqual(owner.find('DisplayName').text, self.conn.user_id)
acl = elem.find('AccessControlList')
self.assertTrue(acl.find('Grant') is not None)
def test_put_bucket_acl_error(self):
req_headers = {'x-amz-acl': 'public-read'}
aws_error_conn = Connection(aws_secret_key='invalid')
status, headers, body = \
aws_error_conn.make_request('PUT', self.bucket,
headers=req_headers, query='acl')
self.assertEqual(get_error_code(body), 'SignatureDoesNotMatch')
status, headers, body = \
self.conn.make_request('PUT', 'nothing',
headers=req_headers, query='acl')
self.assertEqual(get_error_code(body), 'NoSuchBucket')
status, headers, body = \
self.conn2.make_request('PUT', self.bucket,
headers=req_headers, query='acl')
self.assertEqual(get_error_code(body), 'AccessDenied')
def test_get_bucket_acl_error(self):
aws_error_conn = Connection(aws_secret_key='invalid')
status, headers, body = \
aws_error_conn.make_request('GET', self.bucket, query='acl')
self.assertEqual(get_error_code(body), 'SignatureDoesNotMatch')
status, headers, body = \
self.conn.make_request('GET', 'nothing', query='acl')
self.assertEqual(get_error_code(body), 'NoSuchBucket')
status, headers, body = \
self.conn2.make_request('GET', self.bucket, query='acl')
self.assertEqual(get_error_code(body), 'AccessDenied')
def test_get_object_acl_error(self):
self.conn.make_request('PUT', self.bucket, self.obj)
aws_error_conn = Connection(aws_secret_key='invalid')
status, headers, body = \
aws_error_conn.make_request('GET', self.bucket, self.obj,
query='acl')
self.assertEqual(get_error_code(body), 'SignatureDoesNotMatch')
status, headers, body = \
self.conn.make_request('GET', self.bucket, 'nothing', query='acl')
self.assertEqual(get_error_code(body), 'NoSuchKey')
status, headers, body = \
self.conn2.make_request('GET', self.bucket, self.obj, query='acl')
self.assertEqual(get_error_code(body), 'AccessDenied')
@unittest.skipIf(os.environ['AUTH'] == 'tempauth',
'v4 is supported only in keystone')
class TestSwift3AclSigV4(TestSwift3Acl):
@classmethod
def setUpClass(cls):
os.environ['S3_USE_SIGV4'] = "True"
@classmethod
def tearDownClass(cls):
del os.environ['S3_USE_SIGV4']
if __name__ == '__main__':
unittest.main()<|fim▁end|> | from swift3.test.functional.utils import get_error_code
from swift3.etree import fromstring |
<|file_name|>response.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>> response = nexmo.send_sms(frm, to, txt)
>>> print response.total_price
0.15
>>> print response.remaining_balance
1.00
>>> print response.message_count:
3
>>> for message in response.messages:
... print message.message_id, message.message_price
00000124 0.05
00000125 0.05
00000126 0.05
The class only handles successfull responses, since errors raise
exceptions in the :class:`~Nexmo` class.
"""
def __init__(self, json_data):
self.messages = [NexmoMessage(data) for data in json_data['messages']]<|fim▁hole|>
class NexmoMessage(object):
"""A wrapper to manipulate a single `message` entry in a Nexmo response.
When a text messages is sent in several parts, Nexmo will return a status
for each and everyone of them.
The class does nothing more than simply wrapping the json data for easy
access.
"""
def __init__(self, json_data):
data = {
'to': json_data['to'],
'message_id': json_data['message-id'],
'status': int(json_data['status']),
'remaining_balance': D(json_data['remaining-balance']),
'message_price': D(json_data['message-price']),
'network': json_data['network']
}
self.__dict__.update(data)<|fim▁end|> | self.message_count = len(self.messages)
self.total_price = sum(msg.message_price for msg in self.messages)
self.remaining_balance = min(msg.remaining_balance for msg in self.messages) |
<|file_name|>ValidConfig.ts<|end_file_name|><|fim▁begin|>/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Config} from '@jest/types';
import {replacePathSepForRegex} from 'jest-regex-util';
import {multipleValidOptions} from 'jest-validate';
import {NODE_MODULES} from './constants';
const NODE_MODULES_REGEXP = replacePathSepForRegex(NODE_MODULES);
const initialOptions: Config.InitialOptions = {
automock: false,
bail: multipleValidOptions(false, 0),
browser: false,
cache: true,
cacheDirectory: '/tmp/user/jest',
changedFilesWithAncestor: false,
changedSince: 'master',
clearMocks: false,
collectCoverage: true,
collectCoverageFrom: ['src', '!public'],
collectCoverageOnlyFrom: {
'<rootDir>/this-directory-is-covered/Covered.js': true,
},
coverageDirectory: 'coverage',
coveragePathIgnorePatterns: [NODE_MODULES_REGEXP],
coverageReporters: ['json', 'text', 'lcov', 'clover'],
coverageThreshold: {
global: {
branches: 50,
functions: 100,
lines: 100,
statements: 100,
},
},
dependencyExtractor: '<rootDir>/dependencyExtractor.js',
displayName: multipleValidOptions('test-config', {
color: 'blue',
name: 'test-config',
} as const),
errorOnDeprecated: false,
expand: false,
extraGlobals: [],
filter: '<rootDir>/filter.js',
forceCoverageMatch: ['**/*.t.js'],
forceExit: false,
globalSetup: 'setup.js',
globalTeardown: 'teardown.js',
globals: {__DEV__: true},
haste: {
computeSha1: true,
defaultPlatform: 'ios',
hasteImplModulePath: '<rootDir>/haste_impl.js',
platforms: ['ios', 'android'],
providesModuleNodeModules: ['react', 'react-native'],
throwOnModuleCollision: false,
},
json: false,
lastCommit: false,
logHeapUsage: true,
maxConcurrency: 5,
maxWorkers: '50%',
moduleDirectories: ['node_modules'],
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'],
moduleLoader: '<rootDir>',
moduleNameMapper: {
'^React$': '<rootDir>/node_modules/react',
},
modulePathIgnorePatterns: ['<rootDir>/build/'],
modulePaths: ['/shared/vendor/modules'],
name: 'string',
noStackTrace: false,
notify: false,
notifyMode: 'failure-change',
onlyChanged: false,
preset: 'react-native',
prettierPath: '<rootDir>/node_modules/prettier',
projects: ['project-a', 'project-b/'],
reporters: [
'default',
'custom-reporter-1',
['custom-reporter-2', {configValue: true}],
],
resetMocks: false,
resetModules: false,
resolver: '<rootDir>/resolver.js',
restoreMocks: false,
rootDir: '/',
roots: ['<rootDir>'],
runTestsByPath: false,
runner: 'jest-runner',
setupFiles: ['<rootDir>/setup.js'],
setupFilesAfterEnv: ['<rootDir>/testSetupFile.js'],
silent: true,
skipFilter: false,
skipNodeResolution: false,
snapshotResolver: '<rootDir>/snapshotResolver.js',
snapshotSerializers: ['my-serializer-module'],
testEnvironment: 'jest-environment-jsdom',
testEnvironmentOptions: {userAgent: 'Agent/007'},
testFailureExitCode: 1,
testLocationInResults: false,
testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],
testNamePattern: 'test signature',
testPathIgnorePatterns: [NODE_MODULES_REGEXP],
testRegex: multipleValidOptions(
'(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
['/__tests__/\\.test\\.[jt]sx?$', '/__tests__/\\.spec\\.[jt]sx?$'],
),
testResultsProcessor: 'processor-node-module',
testRunner: 'jasmine2',
testSequencer: '@jest/test-sequencer',
testTimeout: 5000,
testURL: 'http://localhost',
timers: 'real',
transform: {
'^.+\\.js$': '<rootDir>/preprocessor.js',
},
transformIgnorePatterns: [NODE_MODULES_REGEXP],
unmockedModulePathPatterns: ['mock'],
updateSnapshot: true,
useStderr: false,
verbose: false,
watch: false,
watchPathIgnorePatterns: ['<rootDir>/e2e/'],
watchPlugins: [
'path/to/yourWatchPlugin',
[
'jest-watch-typeahead/filename',
{
key: 'k',
prompt: 'do something with my custom prompt',
},
],
],
watchman: true,
};<|fim▁hole|><|fim▁end|> |
export default initialOptions; |
<|file_name|>c006.cpp<|end_file_name|><|fim▁begin|>#include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
int sum=1080;
while(cin>>a>>b>>c>>d)
{
if(a==0&&b==0&&c==0&&d==0)
break;
if(a>b)
{
sum=(a-b)*9+sum;
}
else if(a<b)
<|fim▁hole|> {
sum=((40-b)+a)*9+sum;
}
if(c>b)
{
sum=(c-b)*9+sum;
}
else if(c<b)
{
sum=((40-b)+c)*9+sum;
}
if(c>d)
{
sum=(c-d)*9+sum;
}
else if(c<d)
{
sum=((40-d)+c)*9+sum;
}
cout<<sum<<endl;
sum=1080;
}
return 0;
}<|fim▁end|> | |
<|file_name|>sshkey.go<|end_file_name|><|fim▁begin|>package util
import (
"crypto"
"io"
"golang.org/x/crypto/ssh"
)
func SignatureFormatFromSigningOptionAndCA(opt string, ca ssh.PublicKey) string {
switch {
case ca != nil && ca.Type() == ssh.KeyAlgoED25519:
return ssh.KeyAlgoED25519
case ca != nil && ca.Type() == ssh.KeyAlgoRSA && opt == "":
return ssh.SigAlgoRSA
default:
return opt
}
}
type ExtendedAgentSigner interface {
ssh.Signer
SignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error)<|fim▁hole|>
type ExtendedAgentSignerWrapper struct {
Opts crypto.SignerOpts
Signer ExtendedAgentSigner
}
func (e *ExtendedAgentSignerWrapper) PublicKey() ssh.PublicKey {
return e.Signer.PublicKey()
}
func (e *ExtendedAgentSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
return e.Signer.SignWithOpts(rand, data, e.Opts)
}
type AlgorithmSignerWrapper struct {
Algorithm string
Signer ssh.AlgorithmSigner
}
func (a *AlgorithmSignerWrapper) PublicKey() ssh.PublicKey {
return a.Signer.PublicKey()
}
func (a *AlgorithmSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
return a.Signer.SignWithAlgorithm(rand, data, a.Algorithm)
}<|fim▁end|> | } |
<|file_name|>decomp.py<|end_file_name|><|fim▁begin|>"""
PySAR
Polarimetric SAR decomposition
Contents
--------
decomp_fd(hhhh,vvvv,hvhv,hhvv,numthrd=None) : Freeman-Durden 3-component decomposition
"""
from __future__ import print_function, division
import sys,os
import numpy as np
###===========================================================================================
def decomp_fd(hhhh,vvvv,hvhv,hhvv,null=None,numthrd=None,maxthrd=8):
"""
Freeman-Durden 3-component decomposition
Parameters
----------
hhhh : ndarray
horizontally polarized power
vvvv : ndarray
vertically polarized power
hvhv : ndarray
cross-polarized power
hhvv : ndarray
co-polarized cross product (complex-valued)
null : float or None
null value to exclude from decomposition
numthrd : int or None
number of pthreads; None sets numthrd based on the data array size [None]
maxthrd : int or None
maximum allowable numthrd [8]
Returns
-------
ps : ndarray
surface-scattered power
pd : ndarray
double-bounce power
pv : ndarray
volume-scattered power
Notes
-----
* arrays are returned with the same type as hhhh data
Reference
---------
1. Freeman, A. and Durden, S., "A three-component scattering model for polarimetric SAR data", *IEEE Trans. Geosci. Remote Sensing*, vol. 36, no. 3, pp. 963-973, May 1998.
"""
from pysar.polsar._decomp_modc import free_durden
if not numthrd:
numthrd = np.max([len(hhhh)//1e5, 1])
if numthrd > maxthrd: numthrd = maxthrd
elif numthrd < 1:
raise ValueError('numthrd must be >= 1')
if null:
nullmask = np.abs(hhhh-null) < 1.e-7
nullmask += np.abs(vvvv-null) < 1.e-7
nullmask += np.abs(hvhv-null) < 1.e-7
nullmask += np.abs(hhvv-null) < 1.e-7
hhvv[nullmask] = 0.
hhhhtype = None
if hhhh.dtype != np.float32:
hhhhtype = hhhh.dtype
hhhh = hhhh.astype(np.float32)
vvvv = vvvv.astype(np.float32)
hvhv = hvhv.astype(np.float32)
hhvv = hhvv.astype(np.complex64)
if not all({2-x for x in [hhhh.ndim, vvvv.ndim, hvhv.ndim, hhvv.ndim]}):
hhhh, vvvv = hhhh.flatten(), vvvv.flatten()
hvhv, hhvv = hvhv.flatten(), hhvv.flatten()
P = free_durden(hhhh, vvvv, hvhv, hhvv, numthrd)
if hhhhtype: P = P.astype(hhhhtype)
P = P.reshape(3,-1)
if null: P[0,nullmask], P[1,nullmask], P[2,nullmask] = null, null, null
return P[0,:], P[1,:], P[2,:]
###---------------------------------------------------------------------------------
def decomp_haa(hhhh,vvvv,hvhv,hhhv,hhvv,hvvv,matform='C',null=None,numthrd=None,maxthrd=8):
"""
Cloude-Pottier H/A/alpha polarimetric decomposition
Parameters
----------
hhhh : ndarray
horizontal co-polarized power (or 0.5|HH + VV|^2 if matform = 'T')
vvvv : ndarray
vertical co-polarized power (or 0.5|HH - VV|^2 if matform = 'T')
hvhv : ndarray
cross-polarized power (2|HV|^2 for matform = 'T')
hhhv : ndarray
HH.HV* cross-product (or 0.5(HH+VV)(HH-VV)* for matform = 'T')
hhvv : ndarray
HH.VV* cross-product (or HV(HH+VV)* for matform = 'T')
hvvv : ndarray
HV.VV* cross-product (or HV(HH-VV)* for matform = 'T')
matform : str {'C' or 'T'}
form of input matrix entries: 'C' for covariance matrix and
'T' for coherency matrix ['C'] (see ref. 1)
null : float or None
null value to exclude from decomposition
numthrd : int or None
number of pthreads; None sets numthrd based on the data array size [None]
maxthrd : int or None
maximum allowable numthrd [8]
Returns
-------
H : ndarray
entropy (H = -(p1*log_3(p1) + p2*log_3(p2) + p3*log_3(p3))
where pi = lam_i/(hhhh+vvvv+hvhv)) and lam is an eigenvalue
A : ndarray
anisotropy (A = (lam_2-lam_3)/(lam_2+lam_3) --> lam_1 >= lam_2 >= lam_3
alpha : ndarray
alpha angle in degrees (see ref. 1)
Notes
-----
* arrays are returned with the same type as hhhh data
* if covariance matrix form is used, do not multiply entries by any constants
Reference<|fim▁hole|> 1. Cloude, S. and Pottier, E., "An entropy based classification scheme for land applications of polarimetric SAR", *IEEE Trans. Geosci. Remote Sensing*, vol. 35, no. 1, pp. 68-78, Jan. 1997.
"""
from pysar.polsar._decomp_modc import cloude_pot
if matform == 'C' or matform == 'c':
mtf = 1
elif matform == 'T' or matform == 't':
mtf = 0
else:
raise ValueError("matform must be 'C' or 'T'")
if not numthrd:
numthrd = np.max([len(hhhh)//1e5, 1])
if numthrd > maxthrd: numthrd = maxthrd
elif numthrd < 1:
raise ValueError('numthrd must be >= 1')
if null:
nullmask = np.abs(hhhh-null) < 1.e-7
nullmask += np.abs(vvvv-null) < 1.e-7
nullmask += np.abs(hvhv-null) < 1.e-7
nullmask += np.abs(hhhv-null) < 1.e-7
nullmask += np.abs(hhvv-null) < 1.e-7
nullmask += np.abs(hvvv-null) < 1.e-7
hhhh[nullmask], vvvv[nullmask] = 0., 0.
hvhv[nullmask] = 0.
hhhhtype = None
if hhhh.dtype != np.float32:
hhhhtype = hhhh.dtype
hhhh = hhhh.astype(np.float32)
vvvv = vvvv.astype(np.float32)
hvhv = hvhv.astype(np.float32)
hhhv = hhhv.astype(np.complex64)
hhvv = hhvv.astype(np.complex64)
hvvv = hvvv.astype(np.complex64)
if not all({2-x for x in [hhhh.ndim, vvvv.ndim, hvhv.ndim, hhhv.ndim, hhvv.ndim, hvvv.ndim]}):
hhhh, vvvv = hhhh.flatten(), vvvv.flatten()
hvhv, hhvv = hvhv.flatten(), hhvv.flatten()
hhhv, hvvv = hhhv.flatten(), hvvv.flatten()
P = cloude_pot(hhhh, vvvv, hvhv, hhhv, hhvv, hvvv, mtf, numthrd)
if hhhhtype: P = P.astype(hhhhtype)
P = P.reshape(3,-1)
if null: P[0,nullmask], P[1,nullmask], P[2,nullmask] = null, null, null
return P[0,:], P[1,:], P[2,:]
def decomp_cp(hhhh,vvvv,hvhv,hhhv,hhvv,hvvv,matform='C',null=None,numthrd=None,maxthrd=8):
__doc__ = decomp_haa.__doc__
return decomp_haa(hhhh=hhhh,vvvv=vvvv,hvhv=hvhv,hhhv=hhhv,hhvv=hhvv,hvvv=hvvv,
matform=matform,null=null,numthrd=numthrd,maxthrd=maxthrd)<|fim▁end|> | --------- |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2019 Canonical Ltd
#
# 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.
<|fim▁hole|>from charms_openstack.plugins.adapters import (
CephRelationAdapter,
)
from charms_openstack.plugins.classes import (
BaseOpenStackCephCharm,
CephCharm,
PolicydOverridePlugin,
)
from charms_openstack.plugins.trilio import (
TrilioVaultCharm,
TrilioVaultSubordinateCharm,
TrilioVaultCharmGhostAction,
)
__all__ = (
"BaseOpenStackCephCharm",
"CephCharm",
"CephRelationAdapter",
"PolicydOverridePlugin",
"TrilioVaultCharm",
"TrilioVaultSubordinateCharm",
"TrilioVaultCharmGhostAction",
)<|fim▁end|> | # Pull in helpers that 'charms_openstack.plugins' will export |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#[doc = r" Value read from the register"]
pub struct R {
bits: u32,<|fim▁hole|>}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CNT {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct CNTR {
bits: u16,
}
impl CNTR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _CNTW<'a> {
w: &'a mut W,
}
impl<'a> _CNTW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u16) -> &'a mut W {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:15 - counter value"]
#[inline(always)]
pub fn cnt(&self) -> CNTR {
let bits = {
const MASK: u16 = 65535;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u16
};
CNTR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:15 - counter value"]
#[inline(always)]
pub fn cnt(&mut self) -> _CNTW {
_CNTW { w: self }
}
}<|fim▁end|> | |
<|file_name|>procfs_net_test.go<|end_file_name|><|fim▁begin|>/*
Copyright 2017 Gravitational, 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.
*/
package monitoring
import (
"net"
"github.com/gravitational/satellite/lib/test"
"github.com/prometheus/procfs"
. "gopkg.in/check.v1"
)
type S struct{}
var _ = Suite(&S{})
func (_ *S) TestParseSocketFile(c *C) {
err := parseSocketFile("fixtures/tcp", func(string) error {
return nil
})
c.Assert(err, IsNil)
}
func (_ *S) TestGetTCPSockets(c *C) {
sockets, err := getTCPSocketsFromPath("fixtures/tcp")
c.Assert(err, IsNil)
c.Assert(sockets, Not(IsNil))
<|fim▁hole|>
func (_ *S) TestGetUDPSockets(c *C) {
sockets, err := getUDPSocketsFromPath("fixtures/udp")
c.Assert(err, IsNil)
c.Assert(sockets, Not(IsNil))
sockets, err = getUDPSocketsFromPath("fixtures/udp6")
c.Assert(err, IsNil)
c.Assert(sockets, Not(IsNil))
}
func (_ *S) TestGetUnixSockets(c *C) {
sockets, err := getUnixSocketsFromPath("fixtures/unix")
c.Assert(err, IsNil)
c.Assert(sockets, Not(IsNil))
}
func (_ *S) TestTCPSocketFromLine(c *C) {
// setup / exercise
sock, err := newTCPSocketFromLine(" 13: 6408A8C0:D370 03AD7489:01BB 01 00000000:00000000 02:00000998 00000000 1000 0 4128613 2 ffff8cea5ed24080 56 4 30 10 -1")
// verify
c.Assert(err, IsNil)
c.Assert(sock, test.DeepCompare, &tcpSocket{
LocalAddress: tcpAddr("192.168.8.100:54128", c),
RemoteAddress: tcpAddr("137.116.173.3:443", c),
State: Established,
UID: 1000,
Inode: 4128613,
})
// setup / exercise
sock, err = newTCPSocketFromLine(" 1: 00000000000000000000000000000000:0016 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 4118579 1 ffff8ceb27309800 100 0 0 10 0")
// verify
c.Assert(err, IsNil)
c.Assert(sock, test.DeepCompare, &tcpSocket{
LocalAddress: tcpAddr("[::]:22", c),
RemoteAddress: tcpAddr("[::]:0", c),
State: Listen,
Inode: 4118579,
})
}
func (_ *S) TestUDPSocketFromLine(c *C) {
// setup / exercise
sock, err := newUDPSocketFromLine(" 6620: 6408A8C0:A44D BDDCC2AD:01BB 01 00000000:00000000 00:00000000 00000000 1000 0 4216043 2 ffff8cec9b9c2440 0")
// verify
c.Assert(err, IsNil)
c.Assert(sock, test.DeepCompare, &udpSocket{
LocalAddress: udpAddr("192.168.8.100:42061", c),
RemoteAddress: udpAddr("173.194.220.189:443", c),
State: 1,
UID: 1000,
Inode: 4216043,
RefCount: 2,
})
// setup / exercise
sock, err = newUDPSocketFromLine(" 2680: 00000000000000000000000000000000:14E9 00000000000000000000000000000000:0000 07 00000000:00000000 00:00000000 00000000 1000 0 4361657 2 ffff8ceb2722a580 0")
// verify
c.Assert(err, IsNil)
c.Assert(sock, test.DeepCompare, &udpSocket{
LocalAddress: udpAddr("[::]:5353", c),
RemoteAddress: udpAddr("[::]:0", c),
State: 7,
UID: 1000,
Inode: 4361657,
RefCount: 2,
})
}
func (_ *S) TestUnixSocketFromLine(c *C) {
// setup / exercise
sock, err := newUnixSocketFromLine("ffff8cec77d65000: 00000003 00000000 00000000 0001 03 4116864")
// verify
c.Assert(err, IsNil)
c.Assert(sock, test.DeepCompare, &unixSocket{
Type: 1,
State: 3,
Inode: 4116864,
RefCount: 3,
})
// setup / exercise
sock, err = newUnixSocketFromLine("ffff8cec9ca9c400: 00000003 00000000 00000000 0001 03 11188 /run/systemd/journal/stdout")
c.Assert(err, IsNil)
c.Assert(sock, test.DeepCompare, &unixSocket{
Path: "/run/systemd/journal/stdout",
Type: 1,
State: 3,
Inode: 11188,
RefCount: 3,
})
}
func (_ *S) TestDoesNotFailForNonExistingStacks(c *C) {
fetchTCP := func() ([]socket, error) {
return getTCPSocketsFromPath("non-existing/tcp")
}
fetchUDP := func() ([]socket, error) {
return getUDPSocketsFromPath("non-existing/udp")
}
fetchProcs := func() (procfs.Procs, error) {
return nil, nil
}
procs, err := getPorts(fetchProcs, fetchTCP, fetchUDP)
c.Assert(err, IsNil)
c.Assert(procs, DeepEquals, []process(nil))
}
func tcpAddr(addrS string, c *C) net.TCPAddr {
addr, err := net.ResolveTCPAddr("tcp", addrS)
c.Assert(err, IsNil)
ipv4 := addr.IP.To4()
if ipv4 != nil {
addr.IP = ipv4
}
return *addr
}
func udpAddr(addrS string, c *C) net.UDPAddr {
addr, err := net.ResolveUDPAddr("udp", addrS)
c.Assert(err, IsNil)
ipv4 := addr.IP.To4()
if ipv4 != nil {
addr.IP = ipv4
}
return *addr
}<|fim▁end|> | sockets, err = getTCPSocketsFromPath("fixtures/tcp6")
c.Assert(err, IsNil)
c.Assert(sockets, Not(IsNil))
} |
<|file_name|>entity.js<|end_file_name|><|fim▁begin|>'use strict';
var _ = require('lodash');
var Q = require('q');
var util = require('util');
var should = require('./utils/should');
var descriptors = require('./utils/descriptors');
var Attribute = require('./attribute');
var AssertionResult = require('./assertion-result');
var PropertyAssertion = require('./assertions/property-assertion');
var StateAssertion = require('./assertions/state-assertion');
var tinto = {};
tinto.Entity = function Entity() {
this._properties = {};
this._states = {};
/**
* @name tinto.Entity#should
* @type {tinto.Assertion}
*/
/**
* @name tinto.Entity#should
* @function
* @param {...tinto.Assertion} assertions
*/
Object.defineProperty(this, 'should', {
get: should
});
};
/**
* @param {string} state
* @returns {function() : Promise.<tinto.AssertionResult>}
*/
tinto.Entity.prototype.is = function(state) {
var self = this;
if (!this._states[state]) {
throw new Error(util.format('Unsupported state "%s"', state));
}
return function() {
return self._states[state].call(self).then(function(result) {
return new AssertionResult(result);
});
};
};
/**
* @param {string} property
* @param {*} expected
* @returns {function() : Promise.<tinto.AssertionResult>}
*/
tinto.Entity.prototype.has = function(property, expected) {
if (typeof property === 'number') {
return hasCount.call(this, expected, property);
} else {
return hasValue.call(this, property, expected);
}
};
/**
* @param {string} name
* @param {function} [matcher]
* @param {Array.<*>} [args]
*/
tinto.Entity.prototype.state = function(name, matcher, args) {
this._states[name] = wrap(matcher, args);
StateAssertion.register(name);
};
/**
* @param {Object.<string, function>} mappings
*/
tinto.Entity.prototype.states = function() {
processMappings.call(this, 'state', arguments);
};
/**
* @param {string} name
* @param {function} [matcher]
* @param {Array.<*>} [args]
*/
tinto.Entity.prototype.property = function(name, matcher, args) {
this._properties[name] = wrap(matcher, args);
PropertyAssertion.register(name);
this.getter(name, function() {
return new Attribute(this, name, matcher.call(this));
});
};
/**
* @param {Object.<string, function>} mappings
*/
tinto.Entity.prototype.properties = function() {
processMappings.call(this, 'property', arguments);
};
/**
* @param {string} prop
* @param {function()} func
*/
tinto.Entity.prototype.getter = function(prop, func) {
Object.defineProperty(this, prop, {
get: func,
enumerable: true,
configurable: true
});
};
/**
* @param {Object} props
*/
tinto.Entity.prototype.getters = function(props) {
_.forIn(descriptors(props), function(descriptor, prop) {
if (descriptor.enumerable) {
if (descriptor.get) {
this.getter(prop, descriptor.get);
} else if (descriptor.value && typeof descriptor.value === 'function') {
this.getter(prop, descriptor.value);
}
}
}, this);
};
/**
* @private
* @param {function()} matcher
* @param {Array.<*>} args
* @returns {Function}
*/
function wrap(matcher, args) {
return function() {
return Q.when(args ? matcher.apply(this, args) : matcher.call(this));
};
}
/**
* @private
* @param {string} property
* @param {*} value
* @returns {function() : Promise.<tinto.AssertionResult>}
*/
function hasValue(property, value) {
var self = this;
if (!this._properties[property]) {
throw new Error(util.format('Unsupported property "%s"', property));
}
return function() {
return self._properties[property].call(self).then(function(actual) {
return new AssertionResult(_.isEqual(value, actual), value, actual);
});
};
}
/**
* @private
* @param {string} property
* @param {Number} count
* @returns {function() : Promise.<tinto.AssertionResult>}
*/
function hasCount(property, count) {
var collection = this[property];
if (collection.count === undefined || typeof collection.count !== 'function') {
throw new Error('Count assertions can only be applied to collections');
}
return function() {
return Q.resolve(collection.count()).then(function(length) {
return new AssertionResult(count === length, count, length);
});
};
}
/**
* @private
* @param {string} type
* @param {Array.<string|Object>} mappings
*/
function processMappings(type, mappings) {
var self = this;
mappings = Array.prototype.slice.call(mappings, 0);
mappings.forEach(function(mapping) {
if (typeof mapping === 'string') {
self[type](mapping);
} else {<|fim▁hole|> self[type](name, matcher);
}, self);
}
});
}
module.exports = tinto.Entity;<|fim▁end|> | _.forEach(mapping, function(matcher, name) { |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright (C) 2015, Alberto Corona <[email protected]>
// All rights reserved. This file is part of core-utils, distributed under the
// GPL v3 license. For full terms please see the LICENSE file.
#![crate_type = "lib"]
#![feature(path_relative_from,exit_status)]
extern crate term;
use std::io::prelude::Write;
use std::process;
use std::env;
use std::path::{PathBuf,Path};
pub enum Status {
Ok,
Error,
OptError,
ArgError,
}
pub fn exit(status: Status) {
process::exit(status as i32);
}
pub fn set_exit_status(status: Status) {
env::set_exit_status(status as i32);
}
pub fn path_err(status: Status, mesg: String, item: PathBuf) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n",item.display(), mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn err(prog: &str, status: Status, mesg: String) {
match term::stdout() {
Some(mut term) => {
term.fg(term::color::RED).unwrap();
(write!(term, "{}: {}\n", prog, mesg)).unwrap();
term.reset().unwrap();
exit(status);
}
None => {},
};
}
pub fn copyright(prog: &str, vers: &str, yr: &str, auth: Vec<&str>) {
print!("{} (core-utils) {}\n\
Copyright (C) {} core-utils developers\n\
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\n", prog, vers, yr);
print!("Written by ");
for pers in auth.iter() {
print!("{} ", pers);
}
print!("\n");
}
pub fn prog_try(prog: &str) {<|fim▁hole|> set_exit_status(Status::ArgError);
}
pub trait PathMod {
fn last_component(&self) -> PathBuf;
fn first_component(&self) -> PathBuf;
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf;
}
impl PathMod for PathBuf {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}
impl PathMod for Path {
fn last_component(&self) -> PathBuf {
let last = match self.components().last() {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return last;
}
fn first_component(&self) -> PathBuf {
let first = match self.components().nth(0) {
Some(s) => { PathBuf::from(s.as_os_str()) },
None => { PathBuf::new() },
};
return first;
}
fn rel_to(&self, rel_from: &PathBuf) -> PathBuf {
self.relative_from(&rel_from).unwrap_or(&PathBuf::new()).to_path_buf()
}
}<|fim▁end|> | println!("{}: Missing arguments\n\
Try '{} --help' for more information", prog, prog); |
<|file_name|>index.spec.js<|end_file_name|><|fim▁begin|>const {suite} = require('suitape');
const snakeobj = require('./../index');
suite('snakeobj object', (test) => {
test('Returns same as input if input is not an object', (assert) => {
[1, 'hola', true, new Date()].forEach(input => {
const out = snakeobj(input);<|fim▁hole|> });
test('Snakeizes single property object', (assert) => {
const input = {lastName: 'last_name'};
const out = snakeobj(input);
Object.keys(out).forEach(key => assert('equal', key, out[key]));
});
test('Snakeizes multiple property object', (assert) => {
const input = {lastName: 'last_name', name: 'name', isFullName: 'is_full_name'};
const out = snakeobj(input);
Object.keys(out).forEach(key => assert('equal', key, out[key]));
});
test('Snakeizes nested objects', (assert) => {
const input = {person: {lastName: 'doe', job: {jobTitle: 'programmer'}}};
const out = snakeobj(input);
assert('equal', out.person.last_name, 'doe');
assert('equal', out.person.job.job_title, 'programmer');
});
test('Snakeizes nested in arrays objects', (assert) => {
const input = {persons: [{lastName: 'doe', job: {jobTitle: 'programmer'}}]};
const out = snakeobj(input);
assert('equal', out.persons[0].last_name, 'doe');
assert('equal', out.persons[0].job.job_title, 'programmer');
});
test('Snakeizes double nested in arrays objects', (assert) => {
const elem = {itemsInArray: [{item: 1}, {item: 2}]};
const elems = [Object.assign({}, elem), Object.assign({}, elem)];
const out = snakeobj({elems});
assert('equal', out.elems[0].items_in_array[0].item, 1);
assert('equal', out.elems[0].items_in_array[1].item, 2);
assert('equal', out.elems[1].items_in_array[0].item, 1);
assert('equal', out.elems[1].items_in_array[1].item, 2);
});
test('Snakeizes nested dot notation objects', (assert) => {
const input = {'person.lastName': 'doe'};
const out = snakeobj(input);
assert('equal', out['person.last_name'], 'doe');
});
test('Snakeizes all but excented keys', (assert) => {
const date = new Date();
const input = {person: {birthDate: {'$gt': date}}};
const out = snakeobj(input, ['$gt']);
assert('equal', out.person.birth_date['$gt'], date);
});
test('Snakeizes all but nested in arrays excented keys', (assert) => {
const date = new Date();
const input = {persons: [{birthDate: {$gt: date}}, {birthDate: {$lt: date}}]};
const out = snakeobj(input, ['$gt', '$lt']);
assert('equal', out.persons[0].birth_date['$gt'], date);
assert('equal', out.persons[1].birth_date['$lt'], date);
});
test('Snakeizes arrays', (assert) => {
const input = [{fooBar: 'baz'}, {hogeKage: 'piyo'}];
const out = snakeobj(input);
assert('equal', out[0].foo_bar, 'baz');
assert('equal', out[1].hoge_kage, 'piyo');
});
});<|fim▁end|> | assert('equal', out, input);
}); |
<|file_name|>types.ts<|end_file_name|><|fim▁begin|>/* Copyright (c) Ben Robert Mewburn
* Licensed under the ISC Licence.
*/
'use strict';
import { Range } from 'vscode-languageserver-types';
export interface Predicate<T> {
(t: T): boolean;
}
export interface DebugLogger {
debug(message: string): void;
}
export interface EventHandler<T> {
(t: T): void;
}
export interface Unsubscribe {
(): void;
}
export class Event<T> {
private _subscribed: EventHandler<T>[];
constructor() {
this._subscribed = [];
}
subscribe(handler: EventHandler<T>): Unsubscribe {
this._subscribed.push(handler);
let index = this._subscribed.length - 1;
let subscribed = this._subscribed;
return () => {
subscribed.splice(index, 1);
};
}
trigger(args: T) {
let handler: EventHandler<T>;
for (let n = 0; n < this._subscribed.length; ++n) {
handler = this._subscribed[n];
handler(args);
}
}
}
export interface HashedLocation {
uriHash: number;
range: Range;
}
export namespace HashedLocation {
export function create(uriHash: number, range: Range) {
return <HashedLocation>{
uriHash: uriHash,
range: range
};
}
}
export interface TreeLike {
[index: string]: any,
children?: TreeLike[]
}
export class TreeTraverser<T extends TreeLike> {
protected _spine: T[];
constructor(spine: T[]) {
this._spine = spine.slice(0);
}
get spine() {
return this._spine.slice(0);
}
get node() {
return this._spine.length ? this._spine[this._spine.length - 1] : null;
}
traverse(visitor: TreeVisitor<T>) {
this._traverse(this.node, visitor, this._spine.slice(0));
}
filter(predicate: Predicate<T>) {
let visitor = new FilterVisitor<T>(predicate);
this.traverse(visitor);
return visitor.array;
}
toArray() {
let visitor = new ToArrayVisitor<T>();
this.traverse(visitor);
return visitor.array;
}
count() {
let visitor = new CountVisitor<T>();
this.traverse(visitor);
return visitor.count;
}
depth() {
return this._spine.length - 1;
}
up(n: number) {
let steps = Math.max(this._spine.length - 1, n);
this._spine = this._spine.slice(0, this._spine.length - steps);
}
find(predicate: Predicate<T>) {
let visitor = new FindVisitor<T>(predicate);
this.traverse(visitor);
if (visitor.found) {
this._spine = visitor.found;
return this.node;
}
return null;
}
child(predicate: Predicate<T>) {
let parent = this.node;
if (!parent || !parent.children) {
return null;
}
for (let n = 0; n < parent.children.length; ++n) {
if (predicate(<T>parent.children[n])) {
this._spine.push(<T>parent.children[n]);
return this.node;
}
}
return null;
}
nthChild(n: number) {
let parent = this.node;
if (!parent || !parent.children || n < 0 || n > parent.children.length - 1) {
return undefined;
}
this._spine.push(<T>parent.children[n]);
return this.node;
}
childCount() {
let node = this.node;
return node && node.children ? node.children.length : 0;
}
prevSibling() {
if (this._spine.length < 2) {
return null;
}
let parent = this._spine[this._spine.length - 2];
let childIndex = parent.children.indexOf(this.node);
if (childIndex > 0) {
this._spine.pop();
this._spine.push(<T>parent.children[childIndex - 1]);
return this.node;
} else {
return null;
}
}
nextSibling() {
if (this._spine.length < 2) {
return null;
}
let parent = this._spine[this._spine.length - 2];
let childIndex = parent.children.indexOf(this.node);
if (childIndex < parent.children.length - 1) {
this._spine.pop();
this._spine.push(<T>parent.children[childIndex + 1]);
return this.node;
} else {
return null;
}
}
ancestor(predicate: Predicate<T>) {
for (let n = this._spine.length - 2; n >= 0; --n) {
if (predicate(this._spine[n])) {
this._spine = this._spine.slice(0, n + 1);
return this.node;
}
}
return undefined;
}<|fim▁hole|> this._spine.pop();
return this.node;
}
return null;
}
clone() {
return new TreeTraverser(this._spine);
}
private _traverse(treeNode: T, visitor: TreeVisitor<T>, spine: T[]) {
if (visitor.haltTraverse) {
return;
}
let descend = true;
if (visitor.preorder) {
descend = visitor.preorder(treeNode, spine);
if (visitor.haltTraverse) {
return;
}
}
if (treeNode.children && descend) {
spine.push(treeNode);
for (let n = 0, l = treeNode.children.length; n < l; ++n) {
this._traverse(<T>treeNode.children[n], visitor, spine);
if (visitor.haltTraverse) {
return;
}
}
spine.pop();
}
if (visitor.postorder) {
visitor.postorder(treeNode, spine);
}
}
}
export interface Traversable<T extends TreeLike> {
traverse(visitor: TreeVisitor<T>): TreeVisitor<T>;
}
export interface TreeVisitor<T extends TreeLike> {
/**
* True will halt traverse immediately.
* No further functions will be called.
*/
haltTraverse?: boolean;
/**
* Return value determines whether to descend into child nodes
*/
preorder?(node: T, spine: T[]): boolean;
postorder?(node: T, spine: T[]): void;
}
class FilterVisitor<T> implements TreeVisitor<T>{
private _predicate: Predicate<T>;
private _array: T[];
constructor(predicate: Predicate<T>) {
this._predicate = predicate;
this._array = [];
}
get array() {
return this._array;
}
preorder(node: T, spine: T[]) {
if (this._predicate(node)) {
this._array.push(node);
}
return true;
}
}
class FindVisitor<T> implements TreeVisitor<T> {
private _predicate: Predicate<T>;
private _found: T[];
haltTraverse: boolean;
constructor(predicate: Predicate<T>) {
this._predicate = predicate;
this.haltTraverse = false;
}
get found() {
return this._found;
}
preorder(node: T, spine: T[]) {
if (this._predicate(node)) {
this._found = spine.slice(0);
this._found.push(node);
this.haltTraverse = true;
return false;
}
return true;
}
}
export class Debounce<T> {
private _handler: (e: T) => void;
private _lastEvent: T;
private _timer: number | NodeJS.Timer;
constructor(handler: (e: T) => void, public wait: number) {
this._handler = handler;
this.wait = wait;
}
clear = () => {
clearTimeout(<any>this._timer);
this._timer = null;
this._lastEvent = null;
}
handle(event: T) {
this.clear();
this._lastEvent = event;
let that = this;
let handler = this._handler;
let clear = this.clear;
let later = () => {
handler.apply(that, [event]);
clear();
};
this._timer = setTimeout(later, this.wait);
}
flush() {
if (!this._timer) {
return;
}
let event = this._lastEvent;
this.clear();
this._handler.apply(this, [event]);
}
}
export class ToArrayVisitor<T> implements TreeVisitor<T> {
private _array: T[];
constructor() {
this._array = [];
}
get array() {
return this._array;
}
preorder(t: T, spine: T[]) {
this._array.push(t);
return true;
}
}
export class CountVisitor<T> implements TreeVisitor<T> {
private _count: number
constructor() {
this._count = 0;
}
get count() {
return this._count;
}
preorder(t: T, spine: T[]) {
++this._count;
return true;
}
}
export class MultiVisitor<T> implements TreeVisitor<T> {
protected _visitors: [TreeVisitor<T>, TreeLike][];
haltTraverse = false;
constructor(visitors: TreeVisitor<T>[]) {
this._visitors = [];
for (let n = 0; n < visitors.length; ++n) {
this.add(visitors[n]);
}
}
add(v: TreeVisitor<T>) {
this._visitors.push([v, null]);
}
preorder(node: T, spine: T[]) {
let v: [TreeVisitor<T>, TreeLike];
let descend: boolean;
for (let n = 0; n < this._visitors.length; ++n) {
v = this._visitors[n];
if (!v[1] && v[0].preorder && !v[0].preorder(node, spine)) {
v[1] = node;
}
if (v[0].haltTraverse) {
this.haltTraverse = true;
break;
}
}
return true;
}
postorder(node: T, spine: T[]) {
let v: [TreeVisitor<T>, TreeLike];
for (let n = 0; n < this._visitors.length; ++n) {
v = this._visitors[n];
if (v[1] === node) {
v[1] = null;
}
if (!v[1] && v[0].postorder) {
v[0].postorder(node, spine);
}
if (v[0].haltTraverse) {
this.haltTraverse = true;
break;
}
}
}
}
export class BinarySearch<T> {
private _sortedArray: T[];
constructor(sortedArray: T[]) {
this._sortedArray = sortedArray;
}
find(compare: (n: T) => number) {
let result = this.search(compare);
return result.isExactMatch ? this._sortedArray[result.rank] : null;
}
rank(compare: (n: T) => number) {
return this.search(compare).rank;
}
range(compareLower: (n: T) => number, compareUpper: (n:T) => number) {
let rankLower = this.rank(compareLower);
return this._sortedArray.slice(rankLower, this.search(compareUpper, rankLower).rank);
}
search(compare: (n: T) => number, offset?: number): BinarySearchResult {
let left = offset ? offset : 0;
let right = this._sortedArray.length - 1;
let mid = 0;
let compareResult = 0;
let searchResult: BinarySearchResult;
while (true) {
if (left > right) {
searchResult = { rank: left, isExactMatch: false };
break;
}
mid = Math.floor((left + right) / 2);
compareResult = compare(this._sortedArray[mid]);
if (compareResult < 0) {
left = mid + 1;
} else if (compareResult > 0) {
right = mid - 1;
} else {
searchResult = { rank: mid, isExactMatch: true };
break;
}
}
return searchResult;
}
}
export interface BinarySearchResult {
rank: number;
isExactMatch: boolean
}
export interface NameIndexNode<T> {
key: string;
items: T[];
}
export type KeysDelegate<T> = (t: T) => string[];
export class NameIndex<T> {
private _keysDelegate: KeysDelegate<T>;
private _nodeArray: NameIndexNode<T>[];
private _binarySearch: BinarySearch<NameIndexNode<T>>;
private _collator: Intl.Collator;
constructor(keysDelegate: KeysDelegate<T>) {
this._keysDelegate = keysDelegate;
this._nodeArray = [];
this._binarySearch = new BinarySearch<NameIndexNode<T>>(this._nodeArray);
this._collator = new Intl.Collator('en');
}
add(item: T) {
let suffixes = this._keysDelegate(item);
let node: NameIndexNode<T>;
for (let n = 0; n < suffixes.length; ++n) {
node = this._nodeFind(suffixes[n]);
if (node) {
node.items.push(item);
} else {
this._insertNode({ key: suffixes[n], items: [item] });
}
}
}
addMany(items: T[]) {
for (let n = 0; n < items.length; ++n) {
this.add(items[n]);
}
}
remove(item: T) {
let suffixes = this._keysDelegate(item);
let node: NameIndexNode<T>;
let i: number;
for (let n = 0; n < suffixes.length; ++n) {
node = this._nodeFind(suffixes[n]);
if (!node) {
continue;
}
i = node.items.indexOf(item);
if (i > -1) {
node.items.splice(i, 1);
/* uneccessary? save a lookup and splice
if (!node.items.length) {
this._deleteNode(node);
}
*/
}
}
}
removeMany(items: T[]) {
for (let n = 0; n < items.length; ++n) {
this.remove(items[n]);
}
}
/**
* Matches all items that are prefixed with text
* @param text
*/
match(text: string) {
text = text.toLowerCase();
let nodes = this._nodeMatch(text);
let matches: T[] = [];
for (let n = 0; n < nodes.length; ++n) {
Array.prototype.push.apply(matches, nodes[n].items);
}
return Array.from(new Set<T>(matches));
}
*matchIterator(text: string) {
text = text.toLowerCase();
const nodes = this._nodeMatch(text);
const matches = new Set<T>();
let node: NameIndexNode<T>;
for (let n = 0, l = nodes.length; n < l; ++n) {
node = nodes[n];
for (let k = 0, i = node.items.length; k < i; ++k) {
yield node.items[k];
}
}
}
/**
* Finds all items that match (case insensitive) text exactly
* @param text
*/
find(text: string) {
let node = this._nodeFind(text.toLowerCase());
return node ? node.items.slice(0) : [];
}
toJSON() {
return this._nodeArray;
}
fromJSON(data: NameIndexNode<T>[]) {
this._nodeArray = data;
this._binarySearch = new BinarySearch<NameIndexNode<T>>(this._nodeArray);
}
private _nodeMatch(lcText: string) {
let collator = this._collator;
let compareLowerFn = (n: NameIndexNode<T>) => {
return collator.compare(n.key, lcText);
};
let compareUpperFn = (n: NameIndexNode<T>) => {
return n.key.slice(0, lcText.length) === lcText ? -1 : 1;
}
return this._binarySearch.range(compareLowerFn, compareUpperFn);
}
private _nodeFind(lcText: string) {
let collator = this._collator;
let compareFn = (n: NameIndexNode<T>) => {
return collator.compare(n.key, lcText);
}
return this._binarySearch.find(compareFn);
}
private _insertNode(node: NameIndexNode<T>) {
let collator = this._collator;
let rank = this._binarySearch.rank((n) => {
return collator.compare(n.key, node.key);
});
this._nodeArray.splice(rank, 0, node);
}
private _deleteNode(node: NameIndexNode<T>) {
let collator = this._collator;
let rank = this._binarySearch.rank((n) => {
return collator.compare(n.key, node.key);
});
if (this._nodeArray[rank] === node) {
this._nodeArray.splice(rank, 1);
}
}
}
export type Comparer<T> = (a: T, b: T) => number;
export class SortedList<T> {
protected _items: T[];
protected _search: BinarySearch<T>;
constructor(protected compareFn: Comparer<T>, items?: T[]) {
this._items = items || [];
this._search = new BinarySearch<T>(this._items);
}
get length() {
return this._items.length;
}
get items() {
return this._items;
}
add(item: T) {
let cmpFn = this._createCompareClosure(item, this.compareFn);
let result = this._search.search(cmpFn);
if (result.isExactMatch) {
throw new Error(`Duplicate key ${JSON.stringify(item)}`);
}
this._items.splice(result.rank, 0, item);
}
remove(compareFn: (t: T) => number) {
let result = this._search.search(compareFn);
if (result.isExactMatch) {
return this._items.splice(result.rank, 1).shift();
}
return undefined;
}
find(compareFn: (t: T) => number) {
return this._search.find(compareFn);
}
private _createCompareClosure(item: T, cmpFn: (a: T, b: T) => number) {
return (t: T): number => {
return cmpFn(t, item);
}
}
}<|fim▁end|> |
parent() {
if (this._spine.length > 1) { |
<|file_name|>feed.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import logging<|fim▁hole|>import types
import dateutil.parser
import feedparser
import pytz
import http
from html_sanitizer import HTMLSanitizer
def getFeed(url):
current_feed = []
content = http.get(url)
feed = feedparser.parse(content) # even if content is None feedparser returns object with empty entries list
for item in feed.entries:
parsed = FeedParser.parse(item)
current_feed.append(parsed)
logging.info("Downloaded %d posts." % len(current_feed))
return current_feed
def filterExistingFeeds(feeds, latest_feed):
filtered = []
if feeds is not None and len(feeds) > 0:
if latest_feed is not None:
for feed in feeds:
logging.info("Comparing downloaded and latest feed date - (%s, %s)" % (feed["published"], latest_feed))
if feed["published"] is not None and feed["published"] > latest_feed:
filtered.append(feed)
else:
filtered = feeds
logging.info("After filtering there is %d posts to store." % len(filtered))
return filtered
class FeedParser():
@staticmethod
def parse(item):
link = FeedParser._getFirstOf(item, ["link", "id"])
title = FeedParser._getFirstOf(item, ["title"])
summary = FeedParser._getFirstOf(item, ["summary"])
published = FeedParser._getFirstOf(item, ["published", "updated"])
categories = FeedParser._getFirstOf(item, ["tags"])
# for everyone using BlogEngine.NET (this item contains last betag:tag item for single feed item)
betag = FeedParser._getFirstOf(item, ["betag"])
categories_names = FeedParser._getNames(categories)
categories_names.append(FeedParser._encode(betag))
datetime_published = DateParser.parse(published)
sanitized_summary = HTMLSanitizer.sanitize_and_parse(summary)
return {
"link": link,
"published": datetime_published,
"title": FeedParser._encode(title),
"summary": sanitized_summary,
"categories": categories_names
}
@staticmethod
def _getFirstOf(feed_entry, attributes):
if attributes is not None:
for attr in attributes:
if hasattr(feed_entry, attr):
return feed_entry[attr]
@staticmethod
def _encode(value_to_encode):
if type(value_to_encode) is types.UnicodeType:
return value_to_encode.encode("UTF-8")
return value_to_encode
@staticmethod
def _getNames(categories):
result = []
if categories is not None:
for category in categories:
if "term" in category.keys():
result.append(FeedParser._encode(category["term"]))
return result
class DateParser():
@staticmethod
def parse(date):
try:
result = dateutil.parser.parse(date).astimezone(tz=pytz.UTC).replace(tzinfo=None)
except ValueError:
try:
result = dateutil.parser.parse(date, parserinfo=DateParser.PolishParserInfo()) \
.astimezone(tz=pytz.UTC) \
.replace(tzinfo=None)
except ValueError as e:
logging.error("Unknown date string format. Provided date: %s" % date.encode("utf-8"))
raise
return result
class PolishParserInfo(dateutil.parser.parserinfo):
MONTHS = [(u'Sty', u'Styczeń'), (u'Lut', u'Luty'), (u'Mar', u'Marzec'), (u'Kwi', u'Kwiecień'), (u'Maj', u'Maj'),
(u'Cze', u'Czerwiec'), (u'Lip', u'Lipiec'), (u'Sie', u'Sierpień'), (u'Wrz', u'Wrzesień'),
(u'Paź', u'Październik'), (u'Lis', u'Listopad'), (u'Gru', u'Grudzień')]
WEEKDAYS = [(u'Pn', u'Pon', u'Poniedziałek'), (u'Wt', u'Wto', u'Wtorek'), (u'Śr', u'Śro', u'Środa'),
(u'Cz', u'Czw', u'Czwartek'), (u'Pt', u'Pią', u'Piątek'), (u'So', u'Sob', u'Sobota'),
(u'N', u'Nd', u'Nie', u'Niedziela')]
# By default this method checks if name has length greater or equal 3
# and I need to override this method because weekday abbreviations in Poland might have one letter like 'N' (Sunday)
def weekday(self, name):
if len(name) >= 1:
try:
return self._weekdays[name.lower()]
except KeyError:
pass
return None<|fim▁end|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.