prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>test_models.py<|end_file_name|><|fim▁begin|>from django.test import TestCase from httmock import HTTMock from jenkinsapi.jenkins import Jenkins from jenkins.models import Build, JobType from .helpers import mock_url from .factories import BuildFactory, JenkinsServerFactory class JenkinsServerTest(TestCase): <|fim▁hole|> JenkinsServer.get_client should return a Jenkins client configured appropriately. """ server = JenkinsServerFactory.create() mock_request = mock_url( r"\/api\/python$", "fixture1") with HTTMock(mock_request): client = server.get_client() self.assertIsInstance(client, Jenkins) class BuildTest(TestCase): def test_ordering(self): """Builds should be ordered in reverse build order by default.""" builds = BuildFactory.create_batch(5) build_numbers = sorted([x.number for x in builds], reverse=True) self.assertEqual( build_numbers, list(Build.objects.all().values_list("number", flat=True))) class JobTypeTest(TestCase): def test_instantiation(self): """We can create JobTypes.""" JobType.objects.create( name="my-test", config_xml="testing xml")<|fim▁end|>
def test_get_client(self): """
<|file_name|>merge.py<|end_file_name|><|fim▁begin|># Copyright 2015 The TensorFlow 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 # limitations under the License. # ============================================================================== # pylint: disable=not-callable # pylint: disable=redefined-builtin """Layers can merge several input tensors into a single output tensor. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.python.keras import backend as K from tensorflow.contrib.keras.python.keras.engine.topology import Layer from tensorflow.python.framework import tensor_shape class _Merge(Layer): """Generic merge layer for elementwise merge functions. Used to implement `Sum`, `Average`, etc. Arguments: **kwargs: standard layer keyword arguments. """ def __init__(self, **kwargs): super(_Merge, self).__init__(**kwargs) self.supports_masking = True def _merge_function(self, inputs): raise NotImplementedError def _compute_elemwise_op_output_shape(self, shape1, shape2): """Computes the shape of the resultant of an elementwise operation. Arguments: shape1: tuple or None. Shape of the first tensor shape2: tuple or None. Shape of the second tensor Returns: expected output shape when an element-wise operation is carried out on 2 tensors with shapes shape1 and shape2. tuple or None. Raises: ValueError: if shape1 and shape2 are not compatible for element-wise operations. """ if None in [shape1, shape2]: return None elif len(shape1) < len(shape2): return self._compute_elemwise_op_output_shape(shape2, shape1) elif not shape2: return shape1 output_shape = list(shape1[:-len(shape2)]) for i, j in zip(shape1[-len(shape2):], shape2): if i is None or j is None: output_shape.append(None) elif i == 1: output_shape.append(j) elif j == 1: output_shape.append(i) else: if i != j: raise ValueError('Operands could not be broadcast ' 'together with shapes ' + str(shape1) + ' ' + str(shape2)) output_shape.append(i) return tuple(output_shape) def build(self, input_shape): # Used purely for shape validation. if not isinstance(input_shape, list): raise ValueError('A merge layer should be called ' 'on a list of inputs.') if len(input_shape) < 2: raise ValueError('A merge layer should be called ' 'on a list of at least 2 inputs. ' 'Got ' + str(len(input_shape)) + ' inputs.') input_shape = [tensor_shape.TensorShape(s).as_list() for s in input_shape] batch_sizes = [s[0] for s in input_shape if s is not None] batch_sizes = set(batch_sizes) batch_sizes -= set([None]) if len(batch_sizes) > 1: raise ValueError('Can not merge tensors with different ' 'batch sizes. Got tensors with shapes : ' + str(input_shape)) if input_shape[0] is None: output_shape = None else: output_shape = input_shape[0][1:] for i in range(1, len(input_shape)): if input_shape[i] is None: shape = None else: shape = input_shape[i][1:] output_shape = self._compute_elemwise_op_output_shape(output_shape, shape) # If the inputs have different ranks, we have to reshape them # to make them broadcastable. if None not in input_shape and len(set(map(len, input_shape))) == 1: self._reshape_required = False else: self._reshape_required = True self.built = True def call(self, inputs): if self._reshape_required: reshaped_inputs = [] input_ndims = list(map(K.ndim, inputs)) if None not in input_ndims: # If ranks of all inputs are available, # we simply expand each of them at axis=1 # until all of them have the same rank. max_ndim = max(input_ndims) for x in inputs: x_ndim = K.ndim(x) for _ in range(max_ndim - x_ndim): x = K.expand_dims(x, 1) reshaped_inputs.append(x) return self._merge_function(reshaped_inputs) else: # Transpose all inputs so that batch size is the last dimension. # (batch_size, dim1, dim2, ... ) -> (dim1, dim2, ... , batch_size) transposed = False for x in inputs: x_ndim = K.ndim(x) if x_ndim is None: x_shape = K.shape(x) batch_size = x_shape[0] new_shape = K.concatenate([x_shape[1:], K.expand_dims(batch_size)]) x_transposed = K.reshape(x, K.stack([batch_size, K.prod(x_shape[1:])])) x_transposed = K.permute_dimensions(x_transposed, (1, 0)) x_transposed = K.reshape(x_transposed, new_shape) reshaped_inputs.append(x_transposed) transposed = True elif x_ndim > 1: dims = list(range(1, x_ndim)) + [0] reshaped_inputs.append(K.permute_dimensions(x, dims)) transposed = True else: # We don't transpose inputs if they are 1D vectors or scalars. reshaped_inputs.append(x) y = self._merge_function(reshaped_inputs) y_ndim = K.ndim(y) if transposed: # If inputs have been transposed, we have to transpose the output too. if y_ndim is None: y_shape = K.shape(y) y_ndim = K.shape(y_shape)[0] batch_size = y_shape[y_ndim - 1] new_shape = K.concatenate( [K.expand_dims(batch_size), y_shape[:y_ndim - 1]]) y = K.reshape(y, (-1, batch_size)) y = K.permute_dimensions(y, (1, 0)) y = K.reshape(y, new_shape) elif y_ndim > 1: dims = [y_ndim - 1] + list(range(y_ndim - 1)) y = K.permute_dimensions(y, dims) return y else: return self._merge_function(inputs) def compute_output_shape(self, input_shape): if input_shape[0] is None: output_shape = None else: output_shape = input_shape[0][1:] for i in range(1, len(input_shape)): if input_shape[i] is None: shape = None else: shape = input_shape[i][1:] output_shape = self._compute_elemwise_op_output_shape(output_shape, shape) batch_sizes = [s[0] for s in input_shape if s is not None] batch_sizes = set(batch_sizes)<|fim▁hole|> else: output_shape = (None,) + output_shape return output_shape def compute_mask(self, inputs, mask=None): if mask is None: return None if not isinstance(mask, list): raise ValueError('`mask` should be a list.') if not isinstance(inputs, list): raise ValueError('`inputs` should be a list.') if len(mask) != len(inputs): raise ValueError('The lists `inputs` and `mask` ' 'should have the same length.') if all([m is None for m in mask]): return None masks = [K.expand_dims(m, 0) for m in mask if m is not None] return K.all(K.concatenate(masks, axis=0), axis=0, keepdims=False) class Add(_Merge): """Layer that adds a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). """ def _merge_function(self, inputs): output = inputs[0] for i in range(1, len(inputs)): output += inputs[i] return output class Multiply(_Merge): """Layer that multiplies (element-wise) a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). """ def _merge_function(self, inputs): output = inputs[0] for i in range(1, len(inputs)): output *= inputs[i] return output class Average(_Merge): """Layer that averages a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). """ def _merge_function(self, inputs): output = inputs[0] for i in range(1, len(inputs)): output += inputs[i] return output / len(inputs) class Maximum(_Merge): """Layer that computes the maximum (element-wise) a list of inputs. It takes as input a list of tensors, all of the same shape, and returns a single tensor (also of the same shape). """ def _merge_function(self, inputs): output = inputs[0] for i in range(1, len(inputs)): output = K.maximum(output, inputs[i]) return output class Concatenate(_Merge): """Layer that concatenates a list of inputs. It takes as input a list of tensors, all of the same shape expect for the concatenation axis, and returns a single tensor, the concatenation of all inputs. Arguments: axis: Axis along which to concatenate. **kwargs: standard layer keyword arguments. """ def __init__(self, axis=-1, **kwargs): super(Concatenate, self).__init__(**kwargs) self.axis = axis self.supports_masking = True def build(self, input_shape): # Used purely for shape validation. if not isinstance(input_shape, list): raise ValueError('`Concatenate` layer should be called ' 'on a list of inputs') if all([shape is None for shape in input_shape]): return reduced_inputs_shapes = [ tensor_shape.TensorShape(shape).as_list() for shape in input_shape ] shape_set = set() for i in range(len(reduced_inputs_shapes)): del reduced_inputs_shapes[i][self.axis] shape_set.add(tuple(reduced_inputs_shapes[i])) if len(shape_set) > 1: raise ValueError('`Concatenate` layer requires ' 'inputs with matching shapes ' 'except for the concat axis. ' 'Got inputs shapes: %s' % (input_shape)) self.built = True def call(self, inputs): if not isinstance(inputs, list): raise ValueError('A `Concatenate` layer should be called ' 'on a list of inputs.') return K.concatenate(inputs, axis=self.axis) def _compute_output_shape(self, input_shape): if not isinstance(input_shape, list): raise ValueError('A `Concatenate` layer should be called ' 'on a list of inputs.') input_shapes = input_shape output_shape = tensor_shape.TensorShape(input_shapes[0]).as_list() for shape in input_shapes[1:]: shape = tensor_shape.TensorShape(shape).as_list() if output_shape[self.axis] is None or shape[self.axis] is None: output_shape[self.axis] = None break output_shape[self.axis] += shape[self.axis] return tensor_shape.TensorShape(output_shape) def compute_mask(self, inputs, mask=None): if mask is None: return None if not isinstance(mask, list): raise ValueError('`mask` should be a list.') if not isinstance(inputs, list): raise ValueError('`inputs` should be a list.') if len(mask) != len(inputs): raise ValueError('The lists `inputs` and `mask` ' 'should have the same length.') if all([m is None for m in mask]): return None # Make a list of masks while making sure # the dimensionality of each mask # is the same as the corresponding input. masks = [] for input_i, mask_i in zip(inputs, mask): if mask_i is None: # Input is unmasked. Append all 1s to masks, # but cast it to bool first masks.append(K.cast(K.ones_like(input_i), 'bool')) elif K.ndim(mask_i) < K.ndim(input_i): # Mask is smaller than the input, expand it masks.append(K.expand_dims(mask_i)) else: masks.append(mask_i) concatenated = K.concatenate(masks, axis=self.axis) return K.all(concatenated, axis=-1, keepdims=False) def get_config(self): config = { 'axis': self.axis, } base_config = super(Concatenate, self).get_config() return dict(list(base_config.items()) + list(config.items())) class Dot(_Merge): """Layer that computes a dot product between samples in two tensors. E.g. if applied to two tensors `a` and `b` of shape `(batch_size, n)`, the output will be a tensor of shape `(batch_size, 1)` where each entry `i` will be the dot product between `a[i]` and `b[i]`. Arguments: axes: Integer or tuple of integers, axis or axes along which to take the dot product. normalize: Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then the output of the dot product is the cosine proximity between the two samples. **kwargs: Standard layer keyword arguments. """ def __init__(self, axes, normalize=False, **kwargs): super(Dot, self).__init__(**kwargs) if not isinstance(axes, int): if not isinstance(axes, (list, tuple)): raise TypeError('Invalid type for `axes` - ' 'should be a list or an int.') if len(axes) != 2: raise ValueError('Invalid format for `axes` - ' 'should contain two elements.') if not isinstance(axes[0], int) or not isinstance(axes[1], int): raise ValueError('Invalid format for `axes` - ' 'list elements should be "int".') self.axes = axes self.normalize = normalize self.supports_masking = True def build(self, input_shape): # Used purely for shape validation. if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `Dot` layer should be called ' 'on a list of 2 inputs.') shape1 = tensor_shape.TensorShape(input_shape[0]).as_list() shape2 = tensor_shape.TensorShape(input_shape[1]).as_list() if shape1 is None or shape2 is None: return if isinstance(self.axes, int): if self.axes < 0: axes = [self.axes % len(shape1), self.axes % len(shape2)] else: axes = [self.axes] * 2 else: axes = self.axes if shape1[axes[0]] != shape2[axes[1]]: raise ValueError('Dimension incompatibility ' '%s != %s. ' % (shape1[axes[0]], shape2[axes[1]]) + 'Layer shapes: %s, %s' % (shape1, shape2)) self.built = True def call(self, inputs): x1 = inputs[0] x2 = inputs[1] if isinstance(self.axes, int): if self.axes < 0: axes = [self.axes % K.ndim(x1), self.axes % K.ndim(x2)] else: axes = [self.axes] * 2 else: axes = [] for i in range(len(self.axes)): if self.axes[i] < 0: axes.append(self.axes[i] % K.ndim(inputs[i])) else: axes.append(self.axes[i]) if self.normalize: x1 = K.l2_normalize(x1, axis=axes[0]) x2 = K.l2_normalize(x2, axis=axes[1]) output = K.batch_dot(x1, x2, axes) return output def _compute_output_shape(self, input_shape): if not isinstance(input_shape, list) or len(input_shape) != 2: raise ValueError('A `Dot` layer should be called ' 'on a list of 2 inputs.') shape1 = tensor_shape.TensorShape(input_shape[0]).as_list() shape2 = tensor_shape.TensorShape(input_shape[1]).as_list() if isinstance(self.axes, int): if self.axes < 0: axes = [self.axes % len(shape1), self.axes % len(shape2)] else: axes = [self.axes] * 2 else: axes = self.axes shape1.pop(axes[0]) shape2.pop(axes[1]) shape2.pop(0) output_shape = shape1 + shape2 if len(output_shape) == 1: output_shape += [1] return tensor_shape.TensorShape(output_shape) def compute_mask(self, inputs, mask=None): return None def get_config(self): config = { 'axes': self.axes, 'normalize': self.normalize, } base_config = super(Dot, self).get_config() return dict(list(base_config.items()) + list(config.items())) def add(inputs, **kwargs): """Functional interface to the `Add` layer. Arguments: inputs: A list of input tensors (at least 2). **kwargs: Standard layer keyword arguments. Returns: A tensor, the sum of the inputs. """ return Add(**kwargs)(inputs) def multiply(inputs, **kwargs): """Functional interface to the `Multiply` layer. Arguments: inputs: A list of input tensors (at least 2). **kwargs: Standard layer keyword arguments. Returns: A tensor, the element-wise product of the inputs. """ return Multiply(**kwargs)(inputs) def average(inputs, **kwargs): """Functional interface to the `Average` layer. Arguments: inputs: A list of input tensors (at least 2). **kwargs: Standard layer keyword arguments. Returns: A tensor, the average of the inputs. """ return Average(**kwargs)(inputs) def maximum(inputs, **kwargs): """Functional interface to the `Maximum` layer. Arguments: inputs: A list of input tensors (at least 2). **kwargs: Standard layer keyword arguments. Returns: A tensor, the element-wise maximum of the inputs. """ return Maximum(**kwargs)(inputs) def concatenate(inputs, axis=-1, **kwargs): """Functional interface to the `Concatenate` layer. Arguments: inputs: A list of input tensors (at least 2). axis: Concatenation axis. **kwargs: Standard layer keyword arguments. Returns: A tensor, the concatenation of the inputs alongside axis `axis`. """ return Concatenate(axis=axis, **kwargs)(inputs) def dot(inputs, axes, normalize=False, **kwargs): """Functional interface to the `Dot` layer. Arguments: inputs: A list of input tensors (at least 2). axes: Integer or tuple of integers, axis or axes along which to take the dot product. normalize: Whether to L2-normalize samples along the dot product axis before taking the dot product. If set to True, then the output of the dot product is the cosine proximity between the two samples. **kwargs: Standard layer keyword arguments. Returns: A tensor, the dot product of the samples from the inputs. """ return Dot(axes=axes, normalize=normalize, **kwargs)(inputs)<|fim▁end|>
batch_sizes -= set([None]) if len(batch_sizes) == 1: output_shape = (list(batch_sizes)[0],) + output_shape
<|file_name|>XmlSerializer.cpp<|end_file_name|><|fim▁begin|>#include "XmlSerializer.h" namespace dnc { namespace Xml { XmlSerializer::XmlSerializer() {} XmlSerializer::~XmlSerializer() {} std::string XmlSerializer::ToString() { return std::string("System.Xml.XmlSerializer"); } std::string XmlSerializer::GetTypeString() { return std::string("XmlSerializer"); } String XmlSerializer::ToXml(Serializable* obj, Collections::Generic::List<unsigned long long>& _childPtrs) { unsigned long long hash = 0; String res; size_t len; //Serializable* seri = nullptr; /*if(std::is_same<T, Serializable*>::value) { seri = (Serializable*) obj; } else { seri = static_cast<Serializable*>(&obj); }*/ len = obj->AttrLen(); res = "<" + obj->Name() + " ID=\"" + obj->getHashCode() + "\">"; for(size_t i = 0; i < len; i++) {<|fim▁hole|> // Get Values String attrName = t.AttributeName(); Object& val = t.Member(); // Check Serializable Serializable* child = dynamic_cast<Serializable*>(&val); if(child == nullptr) { // Just serialize res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">"; res += val.ToString(); res += "</" + attrName + ">"; } else { // Is Serializable hash = child->getHashCode(); if(_childPtrs.Contains(hash)) { // Just add a reference res += "<" + attrName + " ref=\"" + hash + "\"/>"; } else { // Call serialize _childPtrs.Add(hash); res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">"; res += ToXml(child, _childPtrs); res += "</" + attrName + ">"; } } } res += "</" + obj->Name() + ">\r\n"; return res; } } }<|fim▁end|>
SerializableAttribute& t = obj->Attribute(i);
<|file_name|>remove.py<|end_file_name|><|fim▁begin|>import json import csv teamfolder = "teamdata/out/" with open('combined.json', 'r') as jsonfile: data = json.load(jsonfile) for yeardata in data: year = yeardata['year'] print "" print "NEW YEAR " + str(year) for team in yeardata['teams']: teamname = team['team'] print "Doing team " + teamname team['info'] = { "PTS/G": team['info']['PTS/G'], "FG%": team['info']['FG%']} team['opponent'] = { "PTS/G": team['opponent']['PTS/G']} team['misc'] = {"Attendance": team['misc']['Attendance'], "Age": team['misc']['Age'], "ORtg": team['misc']['ORtg'], "DRtg": team['misc']['DRtg']}<|fim▁hole|> if player['advanced']['G'] > 5: del player['pergame'] del player['perminute'] player['perposs'] = { "ORtg": player['perposs']['ORtg'], "DRtg": player['perposs']['DRtg'] } player['totals'] = { "Age": player['totals']['Age'], "eFG%" : player['totals']['eFG%'] } player['advanced'] = { "PER": player['advanced']['PER'] } totalper += player['advanced']['PER'] newplayers.append(player) team['players'] = newplayers team['totalper'] = totalper with open('removed.json', 'w') as outjsonfile: json.dump(data, outjsonfile, indent=4)<|fim▁end|>
newplayers = [] totalper = 0 for player in team['players']:
<|file_name|>import-to-mongodb.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys import pymongo import json print "import crawled json file into mongodb 'newspapers' database." if len(sys.argv) < 3: print "input as [collection] [json_file]" exit(1) connection = pymongo.Connection("localhost", 27017) news_database = connection.newspapers news_collection = news_database[sys.argv[1]] json_file_name = sys.argv[2] try: with open(json_file_name, mode='r') as json_file: items = json.loads(json_file.read())<|fim▁hole|> for item in items: news_collection.save(item) print len(items), " items saved to mongodb."<|fim▁end|>
json_file.close() except Exception, e: raise e
<|file_name|>IntegerSmallIntTest.java<|end_file_name|><|fim▁begin|>/* The MIT License (MIT) Copyright (c) 2014 Manni Wood 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. */ package com.manniwood.cl4pg.v1.test.types; import com.manniwood.cl4pg.v1.datasourceadapters.DataSourceAdapter; import com.manniwood.cl4pg.v1.PgSession; import com.manniwood.cl4pg.v1.datasourceadapters.PgSimpleDataSourceAdapter; import com.manniwood.cl4pg.v1.commands.DDL; import com.manniwood.cl4pg.v1.commands.Insert; import com.manniwood.cl4pg.v1.commands.Select; import com.manniwood.cl4pg.v1.resultsethandlers.GuessScalarListHandler; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Please note that these tests must be run serially, and not all at once. * Although they depend as little as possible on state in the database, it is * very convenient to have them all use the same db session; so they are all run * one after the other so that they don't all trip over each other. * * @author mwood * */ public class IntegerSmallIntTest { private PgSession pgSession; private DataSourceAdapter adapter; @BeforeClass public void init() { adapter = PgSimpleDataSourceAdapter.buildFromDefaultConfFile(); pgSession = adapter.getSession(); pgSession.run(DDL.config().sql("create temporary table test(col smallint)").done()); pgSession.commit(); } @AfterClass public void tearDown() { pgSession.close(); adapter.close(); } /** * Truncate the users table before each test. */ @BeforeMethod public void truncateTable() { pgSession.run(DDL.config().sql("truncate table test").done()); pgSession.commit(); } @Test(priority = 1) public void testValue() { Integer expected = 3; pgSession.run(Insert.usingVariadicArgs() .sql("insert into test (col) values (#{java.lang.Integer})") .args(expected) .done()); pgSession.commit(); GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>(); pgSession.run(Select.<Integer> usingVariadicArgs() .sql("select col from test limit 1") .resultSetHandler(handler) .done()); pgSession.rollback(); Integer actual = handler.getList().get(0); Assert.assertEquals(actual, expected, "scalars must match"); } @Test(priority = 2) public void testNull() { Integer expected = null; pgSession.run(Insert.usingVariadicArgs() .sql("insert into test (col) values (#{java.lang.Integer})") .args(expected) .done()); pgSession.commit(); GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>(); pgSession.run(Select.<Integer> usingVariadicArgs() .sql("select col from test limit 1") .resultSetHandler(handler) .done()); pgSession.rollback(); Integer actual = handler.getList().get(0); Assert.assertEquals(actual, expected, "scalars must match"); } @Test(priority = 3) public void testSpecialValue1() { Integer expected = 32767; pgSession.run(Insert.usingVariadicArgs() .sql("insert into test (col) values (#{java.lang.Integer})") .args(expected) .done()); pgSession.commit(); GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>(); pgSession.run(Select.<Integer> usingVariadicArgs() .sql("select col from test limit 1") .resultSetHandler(handler) .done()); pgSession.rollback(); Integer actual = handler.getList().get(0); <|fim▁hole|> @Test(priority = 4) public void testSpecialValu21() { Integer expected = -32768; pgSession.run(Insert.usingVariadicArgs() .sql("insert into test (col) values (#{java.lang.Integer})") .args(expected) .done()); pgSession.commit(); GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>(); pgSession.run(Select.<Integer> usingVariadicArgs() .sql("select col from test limit 1") .resultSetHandler(handler) .done()); pgSession.rollback(); Integer actual = handler.getList().get(0); Assert.assertEquals(actual, expected, "scalars must match"); } }<|fim▁end|>
Assert.assertEquals(actual, expected, "scalars must match"); }
<|file_name|>setting_helpers.cpp<|end_file_name|><|fim▁begin|>/* Neutrino-GUI - DBoxII-Project Copyright (C) 2001 Steffen Hehn 'McClean' Homepage: http://dbox.cyberphoria.org/ Kommentar: Diese GUI wurde von Grund auf neu programmiert und sollte nun vom Aufbau und auch den Ausbaumoeglichkeiten gut aussehen. Neutrino basiert auf der Client-Server Idee, diese GUI ist also von der direkten DBox- Steuerung getrennt. Diese wird dann von Daemons uebernommen. License: GPL This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <system/setting_helpers.h> #include "configure_network.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <iomanip> #include <sstream> #include <netinet/in.h> #include <fcntl.h> #include <signal.h> #include <libnet.h> #include <linux/if.h> #include <sys/time.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/ioctl.h> #include <config.h> #include <global.h> #include <neutrino.h> #include <gui/widget/stringinput.h> #include <gui/infoclock.h> #include <driver/volume.h> #include <system/helpers.h> // obsolete #include <gui/streaminfo.h> #include <gui/widget/messagebox.h> #include <gui/widget/hintbox.h> #include <gui/plugins.h> #include <daemonc/remotecontrol.h> #include <xmlinterface.h> #include <audio.h> #include <video.h> #include <dmx.h> #include <cs_api.h> #include <pwrmngr.h> #include <libdvbsub/dvbsub.h> #include <libtuxtxt/teletext.h> #include <zapit/satconfig.h> #include <zapit/zapit.h> extern CPlugins * g_PluginList; /* neutrino.cpp */ extern CRemoteControl * g_RemoteControl; /* neutrino.cpp */ extern cVideo *videoDecoder; extern cAudio *audioDecoder; extern cDemux *videoDemux; extern cDemux *audioDemux; extern cDemux *pcrDemux; extern CHintBox *reloadhintBox; extern "C" int pinghost( const char *hostname ); COnOffNotifier::COnOffNotifier(int OffValue) { offValue = OffValue; } bool COnOffNotifier::changeNotify(const neutrino_locale_t, void *Data) { bool active = (*(int*)(Data) != offValue); for (std::vector<CMenuItem*>::iterator it = toDisable.begin(); it != toDisable.end(); it++) (*it)->setActive(active); return false; } void COnOffNotifier::addItem(CMenuItem* menuItem) { toDisable.push_back(menuItem); } bool CSectionsdConfigNotifier::changeNotify(const neutrino_locale_t, void *) { CNeutrinoApp::getInstance()->SendSectionsdConfig(); return false; } bool CTouchFileNotifier::changeNotify(const neutrino_locale_t, void * data) { if ((*(int *)data) != 0) { FILE * fd = fopen(filename, "w"); if (fd) fclose(fd); else return false; } else remove(filename); return true; } void CColorSetupNotifier::setPalette() { CFrameBuffer *frameBuffer = CFrameBuffer::getInstance(); //setting colors-.. frameBuffer->paletteGenFade(COL_MENUHEAD, convertSetupColor2RGB(g_settings.menu_Head_red, g_settings.menu_Head_green, g_settings.menu_Head_blue), convertSetupColor2RGB(g_settings.menu_Head_Text_red, g_settings.menu_Head_Text_green, g_settings.menu_Head_Text_blue), 8, convertSetupAlpha2Alpha( g_settings.menu_Head_alpha ) ); frameBuffer->paletteGenFade(COL_MENUCONTENT, convertSetupColor2RGB(g_settings.menu_Content_red, g_settings.menu_Content_green, g_settings.menu_Content_blue), convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), 8, convertSetupAlpha2Alpha(g_settings.menu_Content_alpha) ); frameBuffer->paletteGenFade(COL_MENUCONTENTDARK, convertSetupColor2RGB(int(g_settings.menu_Content_red*0.6), int(g_settings.menu_Content_green*0.6), int(g_settings.menu_Content_blue*0.6)), convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), 8, convertSetupAlpha2Alpha(g_settings.menu_Content_alpha) ); frameBuffer->paletteGenFade(COL_MENUCONTENTSELECTED, convertSetupColor2RGB(g_settings.menu_Content_Selected_red, g_settings.menu_Content_Selected_green, g_settings.menu_Content_Selected_blue), convertSetupColor2RGB(g_settings.menu_Content_Selected_Text_red, g_settings.menu_Content_Selected_Text_green, g_settings.menu_Content_Selected_Text_blue), 8, convertSetupAlpha2Alpha(g_settings.menu_Content_Selected_alpha) ); frameBuffer->paletteGenFade(COL_MENUCONTENTINACTIVE, convertSetupColor2RGB(g_settings.menu_Content_inactive_red, g_settings.menu_Content_inactive_green, g_settings.menu_Content_inactive_blue), convertSetupColor2RGB(g_settings.menu_Content_inactive_Text_red, g_settings.menu_Content_inactive_Text_green, g_settings.menu_Content_inactive_Text_blue), 8, convertSetupAlpha2Alpha(g_settings.menu_Content_inactive_alpha) ); frameBuffer->paletteGenFade(COL_INFOBAR, convertSetupColor2RGB(g_settings.infobar_red, g_settings.infobar_green, g_settings.infobar_blue), convertSetupColor2RGB(g_settings.infobar_Text_red, g_settings.infobar_Text_green, g_settings.infobar_Text_blue), 8, convertSetupAlpha2Alpha(g_settings.infobar_alpha) ); frameBuffer->paletteGenFade(COL_INFOBAR_SHADOW, convertSetupColor2RGB(int(g_settings.infobar_red*0.4), int(g_settings.infobar_green*0.4), int(g_settings.infobar_blue*0.4)), convertSetupColor2RGB(g_settings.infobar_Text_red, g_settings.infobar_Text_green, g_settings.infobar_Text_blue), 8, convertSetupAlpha2Alpha(g_settings.infobar_alpha) ); frameBuffer->paletteGenFade(COL_COLORED_EVENTS_INFOBAR, convertSetupColor2RGB(g_settings.infobar_red, g_settings.infobar_green, g_settings.infobar_blue), convertSetupColor2RGB(g_settings.colored_events_red, g_settings.colored_events_green, g_settings.colored_events_blue), 8, convertSetupAlpha2Alpha(g_settings.infobar_alpha) ); frameBuffer->paletteGenFade(COL_COLORED_EVENTS_CHANNELLIST, convertSetupColor2RGB(int(g_settings.menu_Content_red*0.6), int(g_settings.menu_Content_green*0.6), int(g_settings.menu_Content_blue*0.6)), convertSetupColor2RGB(g_settings.colored_events_red, g_settings.colored_events_green, g_settings.colored_events_blue), 8, convertSetupAlpha2Alpha(g_settings.infobar_alpha) ); // ##### TEXT COLORS ##### // COL_COLORED_EVENTS_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 0, convertSetupColor2RGB(g_settings.colored_events_red, g_settings.colored_events_green, g_settings.colored_events_blue), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_INFOBAR_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 1, convertSetupColor2RGB(g_settings.infobar_Text_red, g_settings.infobar_Text_green, g_settings.infobar_Text_blue), convertSetupAlpha2Alpha(g_settings.infobar_alpha)); // COL_INFOBAR_SHADOW_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 2, convertSetupColor2RGB(int(g_settings.infobar_Text_red*0.6), int(g_settings.infobar_Text_green*0.6), int(g_settings.infobar_Text_blue*0.6)), convertSetupAlpha2Alpha(g_settings.infobar_alpha)); // COL_MENUHEAD_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 3, convertSetupColor2RGB(g_settings.menu_Head_Text_red, g_settings.menu_Head_Text_green, g_settings.menu_Head_Text_blue), convertSetupAlpha2Alpha(g_settings.menu_Head_alpha)); // COL_MENUCONTENT_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 4, convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENT_TEXT_PLUS_1 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 5, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), -16), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENT_TEXT_PLUS_2 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 6, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), -32), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENT_TEXT_PLUS_3 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 7, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), -48), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENTDARK_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 8, convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENTDARK_TEXT_PLUS_1 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 9, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), -52), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENTDARK_TEXT_PLUS_2 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 10, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Text_red, g_settings.menu_Content_Text_green, g_settings.menu_Content_Text_blue), -60), convertSetupAlpha2Alpha(g_settings.menu_Content_alpha)); // COL_MENUCONTENTSELECTED_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 11, convertSetupColor2RGB(g_settings.menu_Content_Selected_Text_red, g_settings.menu_Content_Selected_Text_green, g_settings.menu_Content_Selected_Text_blue), convertSetupAlpha2Alpha(g_settings.menu_Content_Selected_alpha)); // COL_MENUCONTENTSELECTED_TEXT_PLUS_1 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 12, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Selected_Text_red, g_settings.menu_Content_Selected_Text_green, g_settings.menu_Content_Selected_Text_blue), -16), convertSetupAlpha2Alpha(g_settings.menu_Content_Selected_alpha)); // COL_MENUCONTENTSELECTED_TEXT_PLUS_2 frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 13, changeBrightnessRGBRel(convertSetupColor2RGB(g_settings.menu_Content_Selected_Text_red, g_settings.menu_Content_Selected_Text_green, g_settings.menu_Content_Selected_Text_blue), -32), convertSetupAlpha2Alpha(g_settings.menu_Content_Selected_alpha)); // COL_MENUCONTENTINACTIVE_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 14, convertSetupColor2RGB(g_settings.menu_Content_inactive_Text_red, g_settings.menu_Content_inactive_Text_green, g_settings.menu_Content_inactive_Text_blue), convertSetupAlpha2Alpha(g_settings.menu_Content_inactive_alpha)); // COL_INFOCLOCK_TEXT frameBuffer->paletteSetColor(COL_NEUTRINO_TEXT + 15, convertSetupColor2RGB(g_settings.clock_Digit_red, g_settings.clock_Digit_green, g_settings.clock_Digit_blue), convertSetupAlpha2Alpha(g_settings.clock_Digit_alpha)); frameBuffer->paletteSet(); } bool CColorSetupNotifier::changeNotify(const neutrino_locale_t, void *) { setPalette(); return false; } bool CAudioSetupNotifier::changeNotify(const neutrino_locale_t OptionName, void *) { //printf("notify: %d\n", OptionName); #if 0 //FIXME to do ? manual audio delay if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_PCMOFFSET)) { } #endif if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_ANALOG_MODE)) { g_Zapit->setAudioMode(g_settings.audio_AnalogMode); } else if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_ANALOG_OUT)) { audioDecoder->EnableAnalogOut(g_settings.analog_out ? true : false); } else if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_HDMI_DD)) { audioDecoder->SetHdmiDD((HDMI_ENCODED_MODE) g_settings.hdmi_dd); } else if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_SPDIF_DD)) { audioDecoder->SetSpdifDD(g_settings.spdif_dd ? true : false); } else if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_AVSYNC)) { videoDecoder->SetSyncMode((AVSYNC_TYPE)g_settings.avsync); audioDecoder->SetSyncMode((AVSYNC_TYPE)g_settings.avsync); videoDemux->SetSyncMode((AVSYNC_TYPE)g_settings.avsync); audioDemux->SetSyncMode((AVSYNC_TYPE)g_settings.avsync); pcrDemux->SetSyncMode((AVSYNC_TYPE)g_settings.avsync); } else if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIOMENU_CLOCKREC)) { //.Clock recovery enable/disable // FIXME add code here. } else if (ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIO_SRS_ALGO) || ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIO_SRS_NMGR) || ARE_LOCALES_EQUAL(OptionName, LOCALE_AUDIO_SRS_VOLUME)) { audioDecoder->SetSRS(g_settings.srs_enable, g_settings.srs_nmgr_enable, g_settings.srs_algo, g_settings.srs_ref_volume); } return false; } // used in ./gui/osd_setup.cpp: bool CFontSizeNotifier::changeNotify(const neutrino_locale_t, void *) { CHintBox hintBox(LOCALE_MESSAGEBOX_INFO, g_Locale->getText(LOCALE_FONTSIZE_HINT)); // UTF-8 hintBox.paint(); CNeutrinoApp::getInstance()->SetupFonts(CNeutrinoFonts::FONTSETUP_NEUTRINO_FONT); hintBox.hide(); /* recalculate infoclock/muteicon/volumebar */ CVolumeHelper::getInstance()->refresh(); return true; } int CSubtitleChangeExec::exec(CMenuTarget* /*parent*/, const std::string & actionKey) { printf("CSubtitleChangeExec::exec: action %s\n", actionKey.c_str()); if(actionKey == "off") { tuxtx_stop_subtitle(); dvbsub_stop(); return menu_return::RETURN_EXIT; } if(!strncmp(actionKey.c_str(), "DVB", 3)) { char const * pidptr = strchr(actionKey.c_str(), ':'); int pid = atoi(pidptr+1); tuxtx_stop_subtitle(); dvbsub_pause(); dvbsub_start(pid); } else { char const * ptr = strchr(actionKey.c_str(), ':'); ptr++; int pid = atoi(ptr); ptr = strchr(ptr, ':'); ptr++; int page = strtol(ptr, NULL, 16); ptr = strchr(ptr, ':'); ptr++; printf("CSubtitleChangeExec::exec: TTX, pid %x page %x lang %s\n", pid, page, ptr); tuxtx_stop_subtitle(); tuxtx_set_pid(pid, page, ptr); dvbsub_stop(); tuxtx_main(g_RCInput->getFileHandle(), pid, page); } return menu_return::RETURN_EXIT; } int CNVODChangeExec::exec(CMenuTarget* parent, const std::string & actionKey) { // printf("CNVODChangeExec exec: %s\n", actionKey.c_str()); unsigned sel= atoi(actionKey.c_str()); g_RemoteControl->setSubChannel(sel); parent->hide(); g_InfoViewer->showSubchan(); return menu_return::RETURN_EXIT; } int CStreamFeaturesChangeExec::exec(CMenuTarget* parent, const std::string & actionKey) { //printf("CStreamFeaturesChangeExec exec: %s\n", actionKey.c_str()); int sel= atoi(actionKey.c_str()); if(parent != NULL) parent->hide(); // -- obsolete (rasc 2004-06-10) // if (sel==-1) // { // CStreamInfo StreamInfo; // StreamInfo.exec(NULL, ""); // } else if(actionKey == "teletext") { g_RCInput->postMsg(CRCInput::RC_timeout, 0); g_RCInput->postMsg(CRCInput::RC_text, 0); #if 0 g_RCInput->clearRCMsg(); tuxtx_main(g_RCInput->getFileHandle(), frameBuffer->getFrameBufferPointer(), g_RemoteControl->current_PIDs.PIDs.vtxtpid); frameBuffer->paintBackground(); if(!g_settings.cacheTXT) tuxtxt_stop(); g_RCInput->clearRCMsg(); #endif } else if (sel>=0) {<|fim▁hole|>} int CMoviePluginChangeExec::exec(CMenuTarget* parent, const std::string & actionKey) { int sel= atoi(actionKey.c_str()); parent->hide(); if (sel>=0) { g_settings.movieplayer_plugin=g_PluginList->getName(sel); } return menu_return::RETURN_EXIT; } int COnekeyPluginChangeExec::exec(CMenuTarget* parent, const std::string & actionKey) { int sel= atoi(actionKey.c_str()); parent->hide(); if (sel>=0) { g_settings.onekey_plugin=g_PluginList->getName(sel); } return menu_return::RETURN_EXIT; } long CNetAdapter::mac_addr_sys ( u_char *addr) //only for function getMacAddr() { struct ifreq ifr; struct ifreq *IFR; struct ifconf ifc; char buf[1024]; int s, i; int ok = 0; s = socket(AF_INET, SOCK_DGRAM, 0); if (s==-1) { return -1; } ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; ioctl(s, SIOCGIFCONF, &ifc); IFR = ifc.ifc_req; for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) { strcpy(ifr.ifr_name, IFR->ifr_name); if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) { if (! (ifr.ifr_flags & IFF_LOOPBACK)) { if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) { ok = 1; break; } } } } close(s); if (ok) { memmove(addr, ifr.ifr_hwaddr.sa_data, 6); } else { return -1; } return 0; } std::string CNetAdapter::getMacAddr(void) { long stat; u_char addr[6]; stat = mac_addr_sys( addr); if (0 == stat) { std::stringstream mac_tmp; for(int i=0;i<6;++i) mac_tmp<<std::hex<<std::setfill('0')<<std::setw(2)<<(int)addr[i]<<':'; return mac_tmp.str().substr(0,17); } else { printf("[neutrino] eth-id not detected...\n"); return ""; } } bool CTZChangeNotifier::changeNotify(const neutrino_locale_t, void * Data) { bool found = false; std::string name, zone; printf("CTZChangeNotifier::changeNotify: %s\n", (char *) Data); xmlDocPtr parser = parseXmlFile("/etc/timezone.xml"); if (parser != NULL) { xmlNodePtr search = xmlDocGetRootElement(parser)->xmlChildrenNode; while (search) { if (!strcmp(xmlGetName(search), "zone")) { name = xmlGetAttribute(search, "name"); if(g_settings.timezone == name) { zone = xmlGetAttribute(search, "zone"); found = true; break; } } search = search->xmlNextNode; } xmlFreeDoc(parser); } if(found) { printf("Timezone: %s -> %s\n", name.c_str(), zone.c_str()); std::string cmd = "cp /usr/share/zoneinfo/" + zone + " /etc/localtime"; printf("exec %s\n", cmd.c_str()); my_system(3,"/bin/sh", "-c", cmd.c_str()); #if 0 cmd = ":" + zone; setenv("TZ", cmd.c_str(), 1); #endif tzset(); } return false; } extern Zapit_config zapitCfg; int CDataResetNotifier::exec(CMenuTarget* /*parent*/, const std::string& actionKey) { bool delete_all = (actionKey == "all"); bool delete_chan = (actionKey == "channels") || delete_all; bool delete_set = (actionKey == "settings") || delete_all; bool delete_removed = (actionKey == "delete_removed"); neutrino_locale_t msg = delete_all ? LOCALE_RESET_ALL : delete_chan ? LOCALE_RESET_CHANNELS : LOCALE_RESET_SETTINGS; int ret = menu_return::RETURN_REPAINT; /* no need to confirm if we only remove deleted channels */ if (!delete_removed) { int result = ShowMsg(msg, g_Locale->getText(LOCALE_RESET_CONFIRM), CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo); if (result != CMessageBox::mbrYes) return true; } if(delete_all) { my_system(3, "/bin/sh", "-c", "rm -f " CONFIGDIR "/zapit/*.conf"); CServiceManager::getInstance()->SatelliteList().clear(); CZapit::getInstance()->LoadSettings(); CZapit::getInstance()->GetConfig(zapitCfg); g_RCInput->postMsg( NeutrinoMessages::REBOOT, 0); ret = menu_return::RETURN_EXIT_ALL; } if(delete_set) { unlink(NEUTRINO_SETTINGS_FILE); //unlink(NEUTRINO_SCAN_SETTINGS_FILE); CNeutrinoApp::getInstance()->loadSetup(NEUTRINO_SETTINGS_FILE); CNeutrinoApp::getInstance()->saveSetup(NEUTRINO_SETTINGS_FILE); //CNeutrinoApp::getInstance()->loadColors(NEUTRINO_SETTINGS_FILE); CNeutrinoApp::getInstance()->SetupFonts(); CColorSetupNotifier::setPalette(); CVFD::getInstance()->setlcdparameter(); CFrameBuffer::getInstance()->Clear(); } if(delete_chan) { my_system(3, "/bin/sh", "-c", "rm -f " CONFIGDIR "/zapit/*.xml"); g_Zapit->reinitChannels(); } if (delete_removed) { if (reloadhintBox) reloadhintBox->paint(); CServiceManager::getInstance()->SaveServices(true, false, true); if (reloadhintBox) reloadhintBox->hide(); /* reinitChannels also triggers a reloadhintbox */ g_Zapit->reinitChannels(); } return ret; } void CFanControlNotifier::setSpeed(unsigned int speed) { printf("FAN Speed %d\n", speed); #ifndef BOXMODEL_APOLLO int cfd = open("/dev/cs_control", O_RDONLY); if(cfd < 0) { perror("Cannot open /dev/cs_control"); return; } if (ioctl(cfd, IOC_CONTROL_PWM_SPEED, speed) < 0) perror("IOC_CONTROL_PWM_SPEED"); close(cfd); #endif } bool CFanControlNotifier::changeNotify(const neutrino_locale_t, void * data) { unsigned int speed = * (int *) data; setSpeed(speed); return false; } bool CCpuFreqNotifier::changeNotify(const neutrino_locale_t, void * data) { extern cCpuFreqManager * cpuFreq; int freq = * (int *) data; printf("CCpuFreqNotifier: %d Mhz\n", freq); freq *= 1000*1000; cpuFreq->SetCpuFreq(freq); return false; } extern CMenuOptionChooser::keyval_ext VIDEOMENU_VIDEOMODE_OPTIONS[]; bool CAutoModeNotifier::changeNotify(const neutrino_locale_t /*OptionName*/, void * /* data */) { int i; int modes[VIDEO_STD_MAX+1]; memset(modes, 0, sizeof(int)*VIDEO_STD_MAX+1); for(i = 0; i < VIDEOMENU_VIDEOMODE_OPTION_COUNT; i++) { modes[VIDEOMENU_VIDEOMODE_OPTIONS[i].key] = g_settings.enabled_video_modes[i]; } videoDecoder->SetAutoModes(modes); return false; }<|fim▁end|>
g_PluginList->startPlugin(sel,0); } return menu_return::RETURN_EXIT;
<|file_name|>[email protected]<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="sr@latin" version="2.1"> <context> <name>AlongsidePage</name> <message> <location filename="../src/modules/partition/gui/AlongsidePage.cpp" line="77"/> <source>Choose partition to shrink:</source> <translation>Odaberite particiju koju želite smanjiti:</translation> </message> <message> <location filename="../src/modules/partition/gui/AlongsidePage.cpp" line="78"/> <source>Allocate drive space by dragging the divider below:</source> <translation>Izdvojite prostor na disku tako što ćete povući graničnik ispod:</translation> </message> <message> <location filename="../src/modules/partition/gui/AlongsidePage.cpp" line="121"/> <source>With this operation, the partition &lt;strong&gt;%1&lt;/strong&gt; which contains %4 will be shrunk to %2MB and a new %3MB partition will be created for %5.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/AlongsidePage.cpp" line="198"/> <source>An EFI system partition cannot be found anywhere on this system. Please go back and use manual partitioning to set up %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/AlongsidePage.cpp" line="208"/> <source>The EFI system partition at %1 will be used for starting %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/AlongsidePage.cpp" line="218"/> <source>EFI system partition:</source> <translation type="unfinished"/> </message> </context> <context> <name>BootInfoWidget</name> <message> <location filename="../src/modules/partition/gui/BootInfoWidget.cpp" line="61"/> <source>The &lt;strong&gt;boot environment&lt;/strong&gt; of this system.&lt;br&gt;&lt;br&gt;Older x86 systems only support &lt;strong&gt;BIOS&lt;/strong&gt;.&lt;br&gt;Modern systems usually use &lt;strong&gt;EFI&lt;/strong&gt;, but may also show up as BIOS if started in compatibility mode.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/BootInfoWidget.cpp" line="75"/> <source>This system was started with an &lt;strong&gt;EFI&lt;/strong&gt; boot environment.&lt;br&gt;&lt;br&gt;To configure startup from an EFI environment, this installer must deploy a boot loader application, like &lt;strong&gt;GRUB&lt;/strong&gt; or &lt;strong&gt;systemd-boot&lt;/strong&gt; on an &lt;strong&gt;EFI System Partition&lt;/strong&gt;. This is automatic, unless you choose manual partitioning, in which case you must choose it or create it on your own.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/BootInfoWidget.cpp" line="87"/> <source>This system was started with a &lt;strong&gt;BIOS&lt;/strong&gt; boot environment.&lt;br&gt;&lt;br&gt;To configure startup from a BIOS environment, this installer must install a boot loader, like &lt;strong&gt;GRUB&lt;/strong&gt;, either at the beginning of a partition or on the &lt;strong&gt;Master Boot Record&lt;/strong&gt; near the beginning of the partition table (preferred). This is automatic, unless you choose manual partitioning, in which case you must set it up on your own.</source> <translation type="unfinished"/> </message> </context> <context> <name>BootLoaderModel</name> <message> <location filename="../src/modules/partition/core/BootLoaderModel.cpp" line="59"/> <source>Master Boot Record of %1</source> <translation>Master Boot Record na %1</translation> </message> <message> <location filename="../src/modules/partition/core/BootLoaderModel.cpp" line="76"/> <source>Boot Partition</source> <translation>Particija za pokretanje sistema</translation> </message> <message> <location filename="../src/modules/partition/core/BootLoaderModel.cpp" line="81"/> <source>System Partition</source> <translation>Sistemska particija</translation> </message> <message> <location filename="../src/modules/partition/core/BootLoaderModel.cpp" line="111"/> <source>Do not install a boot loader</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/BootLoaderModel.cpp" line="125"/> <source>%1 (%2)</source> <translation type="unfinished"/> </message> </context> <context> <name>Calamares::DebugWindow</name> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="24"/> <source>GlobalStorage</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="34"/> <source>JobQueue</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="44"/> <source>Modules</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="57"/> <source>Type:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="64"/> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="78"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="71"/> <source>Interface:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.ui" line="93"/> <source>Tools</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/utils/DebugWindow.cpp" line="182"/> <source>Debug information</source> <translation type="unfinished"/> </message> </context> <context> <name>Calamares::ExecutionViewStep</name> <message> <location filename="../src/libcalamaresui/ExecutionViewStep.cpp" line="77"/> <source>Install</source> <translation type="unfinished"/> </message> </context> <context> <name>Calamares::JobThread</name> <message> <location filename="../src/libcalamares/JobQueue.cpp" line="89"/> <source>Done</source> <translation>Gotovo</translation> </message> </context> <context> <name>Calamares::ProcessJob</name> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="51"/> <source>Run command %1 %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="60"/> <source>Running command %1 %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="89"/> <source>External command crashed</source> <translation>Izvršavanje eksterne komande nije uspjelo</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="90"/> <source>Command %1 crashed. Output: %2</source> <translation>Izvršavanje komande %1 nije uspjelo. Povratna poruka: %2</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="95"/> <source>External command failed to start</source> <translation>Pokretanje komande nije uspjelo</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="96"/> <source>Command %1 failed to start.</source> <translation>Neuspješno pokretanje komande %1.</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="100"/> <source>Internal error when starting command</source> <translation>Interna greška kod pokretanja komande</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="101"/> <source>Bad parameters for process job call.</source> <translation>Pogrešni parametri kod poziva funkcije u procesu.</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="104"/> <source>External command failed to finish</source> <translation>Izvršavanje eksterne komande nije dovršeno</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="105"/> <source>Command %1 failed to finish in %2s. Output: %3</source> <translation>Izvršavanje komande %1 nije dovršeno u %2s. Povratna poruka: %3</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="111"/> <source>External command finished with errors</source> <translation>Greška u izvršavanju eksterne komande</translation> </message> <message> <location filename="../src/libcalamares/ProcessJob.cpp" line="112"/> <source>Command %1 finished with exit code %2. Output: %3</source> <translation>Greška u izvršavanju komande %1, izlazni kod: %2. Povratna poruka: %3</translation> </message> </context> <context> <name>Calamares::PythonJob</name> <message> <location filename="../src/libcalamares/PythonJob.cpp" line="250"/> <source>Running %1 operation.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamares/PythonJob.cpp" line="263"/> <source>Bad working directory path</source> <translation>Neispravna putanja do radne datoteke</translation> </message> <message> <location filename="../src/libcalamares/PythonJob.cpp" line="264"/> <source>Working directory %1 for python job %2 is not readable.</source> <translation>Nemoguće pročitati radnu datoteku %1 za funkciju %2 u Python-u.</translation> </message> <message> <location filename="../src/libcalamares/PythonJob.cpp" line="274"/> <source>Bad main script file</source> <translation>Neispravan glavna datoteka za skriptu</translation> </message> <message> <location filename="../src/libcalamares/PythonJob.cpp" line="275"/> <source>Main script file %1 for python job %2 is not readable.</source> <translation>Glavna datoteka za skriptu %1 za Python funkciju %2 se ne može pročitati.</translation> </message> <message> <location filename="../src/libcalamares/PythonJob.cpp" line="320"/> <source>Boost.Python error in job &quot;%1&quot;.</source> <translation>Boost.Python greška u funkciji %1</translation> </message> </context> <context> <name>Calamares::ViewManager</name> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="65"/> <source>&amp;Back</source> <translation>&amp;Nazad</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="66"/> <source>&amp;Next</source> <translation>&amp;Dalje</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="67"/> <location filename="../src/libcalamaresui/ViewManager.cpp" line="295"/> <source>&amp;Cancel</source> <translation>&amp;Prekini</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="90"/> <source>Cancel installation?</source> <translation>Prekini instalaciju?</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="91"/> <source>Do you really want to cancel the current install process? The installer will quit and all changes will be lost.</source> <translation>Da li stvarno želite prekinuti trenutni proces instalacije? Instaler će se zatvoriti i sve promjene će biti izgubljene.</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="224"/> <source>Continue with setup?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="225"/> <source>The %1 installer is about to make changes to your disk in order to install %2.&lt;br/&gt;&lt;strong&gt;You will not be able to undo these changes.&lt;/strong&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="232"/> <source>&amp;Install now</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="233"/> <source>Go &amp;back</source> <translation type="unfinished"/> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="264"/> <source>&amp;Quit</source> <translation>&amp;Zatvori</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="170"/> <source>Error</source> <translation>Greška</translation> </message> <message> <location filename="../src/libcalamaresui/ViewManager.cpp" line="171"/> <source>Installation Failed</source> <translation>Neuspješna instalacija</translation> </message> </context> <context> <name>CalamaresPython::Helper</name> <message> <location filename="../src/libcalamares/PythonHelper.cpp" line="263"/> <source>Unknown exception type</source> <translation>Nepoznat tip izuzetka</translation> </message> <message> <location filename="../src/libcalamares/PythonHelper.cpp" line="276"/> <source>unparseable Python error</source> <translation>unparseable Python error</translation> </message> <message> <location filename="../src/libcalamares/PythonHelper.cpp" line="292"/> <source>unparseable Python traceback</source> <translation>unparseable Python traceback</translation> </message> <message> <location filename="../src/libcalamares/PythonHelper.cpp" line="296"/> <source>Unfetchable Python error.</source> <translation>Unfetchable Python error.</translation> </message> </context> <context> <name>CalamaresWindow</name> <message> <location filename="../src/calamares/CalamaresWindow.cpp" line="44"/> <source>%1 Installer</source> <translation>%1 Instaler</translation> </message> <message> <location filename="../src/calamares/CalamaresWindow.cpp" line="98"/> <source>Show debug information</source> <translation type="unfinished"/> </message> </context> <context> <name>CheckFileSystemJob</name> <message> <location filename="../src/modules/partition/jobs/CheckFileSystemJob.cpp" line="39"/> <source>Checking file system on partition %1.</source> <translation>Provjeravam fajl sistem na particiji %1.</translation> </message> <message> <location filename="../src/modules/partition/jobs/CheckFileSystemJob.cpp" line="77"/> <source>The file system check on partition %1 failed.</source> <translation>Provjera fajl sistema na particiji %1 nije uspjela.</translation> </message> </context> <context> <name>CheckerWidget</name> <message> <location filename="../src/modules/welcome/checker/CheckerWidget.cpp" line="95"/> <source>This computer does not satisfy the minimum requirements for installing %1.&lt;br/&gt;Installation cannot continue. &lt;a href=&quot;#details&quot;&gt;Details...&lt;/a&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/CheckerWidget.cpp" line="113"/> <source>This computer does not satisfy some of the recommended requirements for installing %1.&lt;br/&gt;Installation can continue, but some features might be disabled.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/CheckerWidget.cpp" line="142"/> <source>This program will ask you some questions and set up %2 on your computer.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/CheckerWidget.cpp" line="166"/> <source>For best results, please ensure that this computer:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/CheckerWidget.cpp" line="194"/> <source>System requirements</source> <translation type="unfinished"/> </message> </context> <context> <name>ChoicePage</name> <message> <location filename="../src/modules/partition/gui/ChoicePage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="127"/> <source>After:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="240"/> <source>&lt;strong&gt;Manual partitioning&lt;/strong&gt;&lt;br/&gt;You can create or resize partitions yourself.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="981"/> <source>Boot loader location:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="923"/> <source>%1 will be shrunk to %2MB and a new %3MB partition will be created for %4.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="125"/> <source>Select storage de&amp;vice:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="126"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="905"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="952"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1032"/> <source>Current:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="782"/> <source>Reuse %1 as home partition for %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="906"/> <source>&lt;strong&gt;Select a partition to shrink, then drag the bottom bar to resize&lt;/strong&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1023"/> <source>&lt;strong&gt;Select a partition to install on&lt;/strong&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1079"/> <source>An EFI system partition cannot be found anywhere on this system. Please go back and use manual partitioning to set up %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1089"/> <source>The EFI system partition at %1 will be used for starting %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1098"/> <source>EFI system partition:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1183"/> <source>This storage device does not seem to have an operating system on it. What would you like to do?&lt;br/&gt;You will be able to review and confirm your choices before any change is made to the storage device.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1188"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1228"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1252"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1290"/> <source>&lt;strong&gt;Erase disk&lt;/strong&gt;&lt;br/&gt;This will &lt;font color=&quot;red&quot;&gt;delete&lt;/font&gt; all data currently present on the selected storage device.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1217"/> <source>This storage device has %1 on it. What would you like to do?&lt;br/&gt;You will be able to review and confirm your choices before any change is made to the storage device.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1192"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1223"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1247"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1285"/> <source>&lt;strong&gt;Install alongside&lt;/strong&gt;&lt;br/&gt;The installer will shrink a partition to make room for %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1197"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1233"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1256"/> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1294"/> <source>&lt;strong&gt;Replace a partition&lt;/strong&gt;&lt;br/&gt;Replaces a partition with %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1242"/> <source>This storage device already has an operating system on it. What would you like to do?&lt;br/&gt;You will be able to review and confirm your choices before any change is made to the storage device.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ChoicePage.cpp" line="1280"/> <source>This storage device has multiple operating systems on it. What would you like to do?&lt;br/&gt;You will be able to review and confirm your choices before any change is made to the storage device.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClearMountsJob</name> <message> <location filename="../src/modules/partition/jobs/ClearMountsJob.cpp" line="45"/> <source>Clear mounts for partitioning operations on %1</source> <translation>Skini tačke montiranja za operacije nad particijama na %1</translation> </message> <message> <location filename="../src/modules/partition/jobs/ClearMountsJob.cpp" line="53"/> <source>Clearing mounts for partitioning operations on %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ClearMountsJob.cpp" line="190"/> <source>Cleared all mounts for %1</source> <translation>Sve tačke montiranja na %1 skinute</translation> </message> </context> <context> <name>ClearTempMountsJob</name> <message> <location filename="../src/modules/partition/jobs/ClearTempMountsJob.cpp" line="40"/> <source>Clear all temporary mounts.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ClearTempMountsJob.cpp" line="47"/> <source>Clearing all temporary mounts.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ClearTempMountsJob.cpp" line="58"/> <source>Cannot get list of temporary mounts.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ClearTempMountsJob.cpp" line="97"/> <source>Cleared all temporary mounts.</source> <translation type="unfinished"/> </message> </context> <context> <name>CreatePartitionDialog</name> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="14"/> <source>Create a Partition</source> <translation>Kreiraj particiju</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="55"/> <source>Partition &amp;Type:</source> <translation>&amp;Tip particije</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="67"/> <source>&amp;Primary</source> <translation>&amp;Primarna</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="77"/> <source>E&amp;xtended</source> <translation>P&amp;roširena</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="119"/> <source>Fi&amp;le System:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="178"/> <source>Flags:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="151"/> <source>&amp;Mount Point:</source> <translation>Tačka &amp;montiranja:</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="38"/> <source>Si&amp;ze:</source> <translation>Veli&amp;čina</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.ui" line="48"/> <source> MB</source> <translation> MB</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.cpp" line="65"/> <source>En&amp;crypt</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.cpp" line="161"/> <source>Logical</source> <translation>Logička</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.cpp" line="166"/> <source>Primary</source> <translation>Primarna</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.cpp" line="183"/> <source>GPT</source> <translation>GPT</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionDialog.cpp" line="268"/> <source>Mountpoint already in use. Please select another one.</source> <translation type="unfinished"/> </message> </context> <context> <name>CreatePartitionJob</name> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="48"/> <source>Create new %2MB partition on %4 (%3) with file system %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="59"/> <source>Create new &lt;strong&gt;%2MB&lt;/strong&gt; partition on &lt;strong&gt;%4&lt;/strong&gt; (%3) with file system &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="71"/> <source>Creating new %1 partition on %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="83"/> <source>The installer failed to create partition on disk &apos;%1&apos;.</source> <translation>Instaler nije uspeo napraviti particiju na disku &apos;%1&apos;.</translation> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="92"/> <source>Could not open device &apos;%1&apos;.</source> <translation>Nemoguće otvoriti uređaj &apos;%1&apos;.</translation> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="102"/> <source>Could not open partition table.</source> <translation>Nemoguće otvoriti tabelu particija.</translation> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="126"/> <source>The installer failed to create file system on partition %1.</source> <translation>Instaler ne može napraviti fajl sistem na particiji %1.</translation> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionJob.cpp" line="134"/> <source>The installer failed to update partition table on disk &apos;%1&apos;.</source> <translation>Instaler ne može promjeniti tabelu particija na disku &apos;%1&apos;.</translation> </message> </context> <context> <name>CreatePartitionTableDialog</name> <message> <location filename="../src/modules/partition/gui/CreatePartitionTableDialog.ui" line="20"/> <source>Create Partition Table</source> <translation>Napravi novu tabelu particija</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionTableDialog.ui" line="39"/> <source>Creating a new partition table will delete all existing data on the disk.</source> <translation>Kreiranje nove tabele particija će obrisati sve podatke na disku.</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionTableDialog.ui" line="65"/> <source>What kind of partition table do you want to create?</source> <translation>Kakvu tabelu particija želite da napravite?</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionTableDialog.ui" line="72"/> <source>Master Boot Record (MBR)</source> <translation>Master Boot Record (MBR)</translation> </message> <message> <location filename="../src/modules/partition/gui/CreatePartitionTableDialog.ui" line="82"/> <source>GUID Partition Table (GPT)</source> <translation>GUID Partition Table (GPT)</translation> </message> </context> <context> <name>CreatePartitionTableJob</name> <message> <location filename="../src/modules/partition/jobs/CreatePartitionTableJob.cpp" line="49"/> <source>Create new %1 partition table on %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionTableJob.cpp" line="56"/> <source>Create new &lt;strong&gt;%1&lt;/strong&gt; partition table on &lt;strong&gt;%2&lt;/strong&gt; (%3).</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionTableJob.cpp" line="66"/> <source>Creating new %1 partition table on %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionTableJob.cpp" line="76"/> <source>The installer failed to create a partition table on %1.</source> <translation>Instaler nije uspjeo da napravi tabelu particija na %1.</translation> </message> <message> <location filename="../src/modules/partition/jobs/CreatePartitionTableJob.cpp" line="84"/> <source>Could not open device %1.</source> <translation>Nemoguće otvoriti uređaj %1.</translation> </message> </context> <context> <name>CreateUserJob</name> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="50"/> <source>Create user %1</source> <translation>Napravi korisnika %1</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="57"/> <source>Create user &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="64"/> <source>Creating user %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="80"/> <source>Sudoers dir is not writable.</source> <translation>Nemoguće mijenjati fajlove u sudoers direktorijumu</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="84"/> <source>Cannot create sudoers file for writing.</source> <translation>Nemoguće napraviti sudoers fajl</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="92"/> <source>Cannot chmod sudoers file.</source> <translation>Nemoguće uraditi chmod nad sudoers fajlom.</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="98"/> <source>Cannot open groups file for reading.</source> <translation>Nemoguće otvoriti groups fajl</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="160"/> <source>Cannot create user %1.</source> <translation>Nemoguće napraviti korisnika %1.</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="162"/> <source>useradd terminated with error code %1.</source> <translation>Komanda useradd prekinuta sa kodom greške %1</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="171"/> <source>Cannot add user %1 to groups: %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="174"/> <source>usermod terminated with error code %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="184"/> <source>Cannot set home directory ownership for user %1.</source> <translation>Nemoguće postaviti vlasništvo nad početnim direktorijumom za korisnika %1.</translation> </message> <message> <location filename="../src/modules/users/CreateUserJob.cpp" line="186"/> <source>chown terminated with error code %1.</source> <translation>Komanda chown prekinuta sa kodom greške %1.</translation> </message> </context> <context> <name>DeletePartitionJob</name> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="42"/> <source>Delete partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="50"/> <source>Delete partition &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="58"/> <source>Deleting partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="67"/> <source>The installer failed to delete partition %1.</source> <translation>Instaler nije uspjeo obrisati particiju %1.</translation> </message> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="73"/> <source>Partition (%1) and device (%2) do not match.</source> <translation>Particija (%1) i uređaj (%2) se ne slažu.</translation> </message> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="85"/> <source>Could not open device %1.</source> <translation>Nemoguće otvoriti uređaj %1.</translation> </message> <message> <location filename="../src/modules/partition/jobs/DeletePartitionJob.cpp" line="94"/> <source>Could not open partition table.</source> <translation>Nemoguće otvoriti tabelu particija.</translation> </message> </context> <context> <name>DeviceInfoWidget</name> <message> <location filename="../src/modules/partition/gui/DeviceInfoWidget.cpp" line="63"/> <source>The type of &lt;strong&gt;partition table&lt;/strong&gt; on the selected storage device.&lt;br&gt;&lt;br&gt;The only way to change the partition table type is to erase and recreate the partition table from scratch, which destroys all data on the storage device.&lt;br&gt;This installer will keep the current partition table unless you explicitly choose otherwise.&lt;br&gt;If unsure, on modern systems GPT is preferred.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/DeviceInfoWidget.cpp" line="107"/> <source>This device has a &lt;strong&gt;%1&lt;/strong&gt; partition table.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/DeviceInfoWidget.cpp" line="114"/> <source>This is a &lt;strong&gt;loop&lt;/strong&gt; device.&lt;br&gt;&lt;br&gt;It is a pseudo-device with no partition table that makes a file accessible as a block device. This kind of setup usually only contains a single filesystem.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/DeviceInfoWidget.cpp" line="121"/> <source>This installer &lt;strong&gt;cannot detect a partition table&lt;/strong&gt; on the selected storage device.&lt;br&gt;&lt;br&gt;The device either has no partition table, or the partition table is corrupted or of an unknown type.&lt;br&gt;This installer can create a new partition table for you, either automatically, or through the manual partitioning page.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/DeviceInfoWidget.cpp" line="131"/> <source>&lt;br&gt;&lt;br&gt;This is the recommended partition table type for modern systems which start from an &lt;strong&gt;EFI&lt;/strong&gt; boot environment.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/DeviceInfoWidget.cpp" line="137"/> <source>&lt;br&gt;&lt;br&gt;This partition table type is only advisable on older systems which start from a &lt;strong&gt;BIOS&lt;/strong&gt; boot environment. GPT is recommended in most other cases.&lt;br&gt;&lt;br&gt;&lt;strong&gt;Warning:&lt;/strong&gt; the MBR partition table is an obsolete MS-DOS era standard.&lt;br&gt;Only 4 &lt;em&gt;primary&lt;/em&gt; partitions may be created, and of those 4, one can be an &lt;em&gt;extended&lt;/em&gt; partition, which may in turn contain many &lt;em&gt;logical&lt;/em&gt; partitions.</source> <translation type="unfinished"/> </message> </context> <context> <name>DeviceModel</name> <message> <location filename="../src/modules/partition/core/DeviceModel.cpp" line="80"/> <source>%1 - %2 (%3)</source> <translation>%1 - %2 (%3)</translation> </message> </context> <context> <name>DracutLuksCfgJob</name> <message> <location filename="../src/modules/dracutlukscfg/DracutLuksCfgJob.cpp" line="131"/> <source>Write LUKS configuration for Dracut to %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/dracutlukscfg/DracutLuksCfgJob.cpp" line="133"/> <source>Skip writing LUKS configuration for Dracut: &quot;/&quot; partition is not encrypted</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/dracutlukscfg/DracutLuksCfgJob.cpp" line="149"/> <source>Failed to open %1</source> <translation type="unfinished"/> </message> </context> <context> <name>DummyCppJob</name> <message> <location filename="../src/modules/dummycpp/DummyCppJob.cpp" line="46"/> <source>Dummy C++ Job</source> <translation type="unfinished"/> </message> </context> <context> <name>EditExistingPartitionDialog</name> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="20"/> <source>Edit Existing Partition</source> <translation>Promjeni postojeću particiju:</translation> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="50"/> <source>Content:</source> <translation>Sadržaj:</translation> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="60"/> <source>&amp;Keep</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="70"/> <source>Format</source> <translation>Formatiraj</translation> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="89"/> <source>Warning: Formatting the partition will erase all existing data.</source> <translation>Upozorenje: Formatiranje particije će obrisati sve podatke.</translation> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="99"/> <source>&amp;Mount Point:</source> <translation>Tačka za &amp;montiranje:</translation> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="119"/> <source>Si&amp;ze:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="132"/> <source>Fi&amp;le System:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.ui" line="145"/> <source>Flags:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EditExistingPartitionDialog.cpp" line="306"/> <source>Mountpoint already in use. Please select another one.</source> <translation type="unfinished"/> </message> </context> <context> <name>EncryptWidget</name> <message> <location filename="../src/modules/partition/gui/EncryptWidget.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EncryptWidget.ui" line="32"/> <source>En&amp;crypt system</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EncryptWidget.ui" line="42"/> <source>Passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EncryptWidget.ui" line="52"/> <source>Confirm passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/EncryptWidget.cpp" line="150"/> <source>Please enter the same passphrase in both boxes.</source> <translation type="unfinished"/> </message> </context> <context> <name>FillGlobalStorageJob</name> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="123"/> <source>Set partition information</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="147"/> <source>Install %1 on &lt;strong&gt;new&lt;/strong&gt; %2 system partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="152"/> <source>Set up &lt;strong&gt;new&lt;/strong&gt; %2 partition with mount point &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="160"/> <source>Install %2 on %3 system partition &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="166"/> <source>Set up %3 partition &lt;strong&gt;%1&lt;/strong&gt; with mount point &lt;strong&gt;%2&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="178"/> <source>Install boot loader on &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FillGlobalStorageJob.cpp" line="188"/> <source>Setting up mount points.</source> <translation type="unfinished"/> </message> </context> <context> <name>FinishedPage</name> <message> <location filename="../src/modules/finished/FinishedPage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/finished/FinishedPage.ui" line="77"/> <source>&amp;Restart now</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/finished/FinishedPage.cpp" line="50"/> <source>&lt;h1&gt;All done.&lt;/h1&gt;&lt;br/&gt;%1 has been installed on your computer.&lt;br/&gt;You may now restart into your new system, or continue using the %2 Live environment.</source> <translation type="unfinished"/> </message> </context> <context> <name>FinishedViewStep</name> <message> <location filename="../src/modules/finished/FinishedViewStep.cpp" line="43"/> <source>Finish</source> <translation type="unfinished"/> </message> </context> <context> <name>FormatPartitionJob</name> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="49"/> <source>Format partition %1 (file system: %2, size: %3 MB) on %4.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="60"/> <source>Format &lt;strong&gt;%3MB&lt;/strong&gt; partition &lt;strong&gt;%1&lt;/strong&gt; with file system &lt;strong&gt;%2&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="71"/> <source>Formatting partition %1 with file system %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="83"/> <source>The installer failed to format partition %1 on disk &apos;%2&apos;.</source> <translation>Instaler nije uspeo formatirati particiju %1 na disku &apos;%2&apos;.</translation> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="91"/> <source>Could not open device &apos;%1&apos;.</source> <translation>Ne mogu otvoriti uređaj &apos;%1&apos;.</translation> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="100"/> <source>Could not open partition table.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="124"/> <source>The installer failed to create file system on partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/FormatPartitionJob.cpp" line="133"/> <source>The installer failed to update partition table on disk &apos;%1&apos;.</source> <translation type="unfinished"/> </message> </context> <context> <name>InteractiveTerminalPage</name> <message> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="69"/> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="84"/> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="96"/> <source>Konsole not installed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="70"/> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="85"/> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="97"/> <source>Please install the kde konsole and try again!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/interactiveterminal/InteractiveTerminalPage.cpp" line="122"/> <source>Executing script: &amp;nbsp;&lt;code&gt;%1&lt;/code&gt;</source> <translation type="unfinished"/> </message> </context> <context> <name>InteractiveTerminalViewStep</name> <message> <location filename="../src/modules/interactiveterminal/InteractiveTerminalViewStep.cpp" line="45"/> <source>Script</source> <translation type="unfinished"/> </message> </context> <context> <name>KeyboardPage</name> <message> <location filename="../src/modules/keyboard/KeyboardPage.cpp" line="193"/> <source>Set keyboard model to %1.&lt;br/&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/KeyboardPage.cpp" line="195"/> <source>Set keyboard layout to %1/%2.</source> <translation type="unfinished"/> </message> </context> <context> <name>KeyboardViewStep</name> <message> <location filename="../src/modules/keyboard/KeyboardViewStep.cpp" line="50"/> <source>Keyboard</source> <translation>Tastatura</translation> </message> </context> <context> <name>LCLocaleDialog</name> <message> <location filename="../src/modules/locale/LCLocaleDialog.cpp" line="33"/> <source>System locale setting</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/LCLocaleDialog.cpp" line="40"/> <source>The system locale setting affects the language and character set for some command line user interface elements.&lt;br/&gt;The current setting is &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> </context> <context> <name>LicensePage</name> <message> <location filename="../src/modules/license/LicensePage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="88"/> <source>I accept the terms and conditions above.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="115"/> <source>&lt;h1&gt;License Agreement&lt;/h1&gt;This setup procedure will install proprietary software that is subject to licensing terms.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="118"/> <source>Please review the End User License Agreements (EULAs) above.&lt;br/&gt;If you do not agree with the terms, the setup procedure cannot continue.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="124"/> <source>&lt;h1&gt;License Agreement&lt;/h1&gt;This setup procedure can install proprietary software that is subject to licensing terms in order to provide additional features and enhance the user experience.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="129"/> <source>Please review the End User License Agreements (EULAs) above.&lt;br/&gt;If you do not agree with the terms, proprietary software will not be installed, and open source alternatives will be used instead.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="159"/> <source>&lt;strong&gt;%1 driver&lt;/strong&gt;&lt;br/&gt;by %2</source> <extracomment>%1 is an untranslatable product name, example: Creative Audigy driver</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="166"/> <source>&lt;strong&gt;%1 graphics driver&lt;/strong&gt;&lt;br/&gt;&lt;font color=&quot;Grey&quot;&gt;by %2&lt;/font&gt;</source> <extracomment>%1 is usually a vendor name, example: Nvidia graphics driver</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="172"/> <source>&lt;strong&gt;%1 browser plugin&lt;/strong&gt;&lt;br/&gt;&lt;font color=&quot;Grey&quot;&gt;by %2&lt;/font&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="178"/> <source>&lt;strong&gt;%1 codec&lt;/strong&gt;&lt;br/&gt;&lt;font color=&quot;Grey&quot;&gt;by %2&lt;/font&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="184"/> <source>&lt;strong&gt;%1 package&lt;/strong&gt;&lt;br/&gt;&lt;font color=&quot;Grey&quot;&gt;by %2&lt;/font&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="190"/> <source>&lt;strong&gt;%1&lt;/strong&gt;&lt;br/&gt;&lt;font color=&quot;Grey&quot;&gt;by %2&lt;/font&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/license/LicensePage.cpp" line="202"/> <source>&lt;a href=&quot;%1&quot;&gt;view license agreement&lt;/a&gt;</source> <translation type="unfinished"/> </message> </context> <context> <name>LicenseViewStep</name> <message> <location filename="../src/modules/license/LicenseViewStep.cpp" line="51"/> <source>License</source> <translation type="unfinished"/> </message> </context> <context> <name>LocalePage</name> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="174"/> <location filename="../src/modules/locale/LocalePage.cpp" line="237"/> <source>The system language will be set to %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="206"/> <location filename="../src/modules/locale/LocalePage.cpp" line="240"/> <source>The numbers and dates locale will be set to %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="216"/> <source>Region:</source> <translation>Regija:</translation> </message> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="217"/> <source>Zone:</source> <translation>Zona:</translation> </message> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="221"/> <location filename="../src/modules/locale/LocalePage.cpp" line="222"/> <source>&amp;Change...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="390"/> <source>Set timezone to %1/%2.&lt;br/&gt;</source> <translation>Postavi vremensku zonu na %1/%2.&lt;br/&gt;</translation> </message> <message> <location filename="../src/modules/locale/LocalePage.cpp" line="465"/> <source>%1 (%2)</source> <extracomment>Language (Country)</extracomment> <translation type="unfinished"/> </message> </context> <context> <name>LocaleViewStep</name> <message> <location filename="../src/modules/locale/LocaleViewStep.cpp" line="52"/> <source>Loading location data...</source> <translation>Očitavam podatke o lokaciji...</translation> </message> <message> <location filename="../src/modules/locale/LocaleViewStep.cpp" line="160"/> <source>Location</source> <translation>Lokacija</translation> </message> </context> <context> <name>MoveFileSystemJob</name> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="66"/> <source>Move file system of partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="80"/> <source>Could not open file system on partition %1 for moving.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="86"/> <source>Could not create target for moving file system on partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="95"/> <source>Moving of partition %1 failed, changes have been rolled back.</source> <translation>Premještanje particije %1 nije uspjelo, promjene su poništene.</translation> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="101"/> <source>Moving of partition %1 failed. Roll back of the changes have failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="113"/> <source>Updating boot sector after the moving of partition %1 failed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="127"/> <source>The logical sector sizes in the source and target for copying are not the same. This is currently unsupported.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="197"/> <source>Source and target for copying do not overlap: Rollback is not required.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="221"/> <location filename="../src/modules/partition/jobs/MoveFileSystemJob.cpp" line="229"/> <source>Could not open device %1 to rollback copying.</source> <translation type="unfinished"/> </message> </context> <context> <name>NetInstallPage</name> <message> <location filename="../src/modules/netinstall/NetInstallPage.cpp" line="71"/> <source>Name</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/netinstall/NetInstallPage.cpp" line="72"/> <source>Description</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/netinstall/NetInstallPage.cpp" line="81"/> <source>Network Installation. (Disabled: Unable to fetch package lists, check your network connection)</source> <translation type="unfinished"/> </message> </context> <context> <name>NetInstallViewStep</name> <message> <location filename="../src/modules/netinstall/NetInstallViewStep.cpp" line="51"/> <source>Package selection</source> <translation type="unfinished"/> </message> </context> <context> <name>Page_Keyboard</name> <message> <location filename="../src/modules/keyboard/KeyboardPage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/KeyboardPage.ui" line="70"/> <source>Keyboard Model:</source> <translation>Model tastature:</translation> </message> <message> <location filename="../src/modules/keyboard/KeyboardPage.ui" line="131"/> <source>Type here to test your keyboard</source> <translation>Test tastature</translation> </message> </context> <context> <name>Page_UserSetup</name> <message> <location filename="../src/modules/users/page_usersetup.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="36"/> <source>What is your name?</source> <translation>Kako se zovete?</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="117"/> <source>What name do you want to use to log in?</source> <translation>Koje ime želite koristiti da se prijavite?</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="197"/> <location filename="../src/modules/users/page_usersetup.ui" line="306"/> <location filename="../src/modules/users/page_usersetup.ui" line="437"/> <location filename="../src/modules/users/page_usersetup.ui" line="582"/> <source>font-weight: normal</source> <translation>font-weight: normal</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="200"/> <source>&lt;small&gt;If more than one person will use this computer, you can set up multiple accounts after installation.&lt;/small&gt;</source> <translation>&lt;small&gt;Ako će više osoba koristiti ovaj računar, možete postaviti više korisničkih naloga nakon instalacije.&lt;/small&gt;</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="335"/> <source>Choose a password to keep your account safe.</source> <translation>Odaberite lozinku da biste zaštitili Vaš korisnički nalog.</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="440"/> <source>&lt;small&gt;Enter the same password twice, so that it can be checked for typing errors. A good password will contain a mixture of letters, numbers and punctuation, should be at least eight characters long, and should be changed at regular intervals.&lt;/small&gt;</source> <translation>&lt;small&gt;Upišite istu lozinku dvaput, da ne bi došlo do greške kod kucanja. Dobra lozinka se sastoji od mešavine slova, brojeva i interpunkcijskih znakova; trebala bi biti duga bar osam znakova, i trebalo bi da ju menjate redovno&lt;/small&gt;</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="226"/> <source>What is the name of this computer?</source> <translation>Kako želite nazvati ovaj računar?</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="309"/> <source>&lt;small&gt;This name will be used if you make the computer visible to others on a network.&lt;/small&gt;</source> <translation>&lt;small&gt;Ovo ime će biti vidljivo drugim računarima na mreži&lt;/small&gt;</translation> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="450"/> <source>Log in automatically without asking for the password.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="457"/> <source>Use the same password for the administrator account.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="480"/> <source>Choose a password for the administrator account.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/page_usersetup.ui" line="585"/> <source>&lt;small&gt;Enter the same password twice, so that it can be checked for typing errors.&lt;/small&gt;</source> <translation>&lt;small&gt;Unesite istu lozinku dvaput, da ne bi došlp do greške kod kucanja&lt;/small&gt;</translation> </message> </context> <context> <name>PartitionLabelsView</name> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="191"/> <source>Root</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="194"/> <source>Home</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="196"/> <source>Boot</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="199"/> <source>EFI system</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="201"/> <source>Swap</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="203"/> <source>New partition for %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="205"/> <source>New partition</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="222"/> <source>%1 %2</source> <translation type="unfinished"/> </message> </context> <context> <name>PartitionModel</name> <message> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="137"/> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="169"/> <source>Free Space</source> <translation>Slobodan prostor</translation> </message> <message> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="141"/> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="173"/> <source>New partition</source> <translation>Nova particija</translation> </message> <message> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="257"/> <source>Name</source> <translation>Naziv</translation> </message> <message> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="259"/> <source>File System</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="261"/> <source>Mount Point</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/PartitionModel.cpp" line="263"/> <source>Size</source> <translation>Veličina</translation> </message> </context> <context> <name>PartitionPage</name> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="22"/> <source>Storage de&amp;vice:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="51"/> <source>&amp;Revert All Changes</source> <translation>&amp;Vrati sve promjene</translation> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="87"/> <source>New Partition &amp;Table</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="107"/> <source>&amp;Create</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="114"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="121"/> <source>&amp;Delete</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.ui" line="148"/> <source>Install boot &amp;loader on:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionPage.cpp" line="160"/> <source>Are you sure you want to create a new partition table on %1?</source> <translation type="unfinished"/> </message> </context> <context> <name>PartitionViewStep</name> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="70"/> <source>Gathering system information...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="121"/> <source>Partitions</source> <translation>Particije</translation> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="158"/> <source>Install %1 &lt;strong&gt;alongside&lt;/strong&gt; another operating system.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="163"/> <source>&lt;strong&gt;Erase&lt;/strong&gt; disk and install %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="168"/> <source>&lt;strong&gt;Replace&lt;/strong&gt; a partition with %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="173"/> <source>&lt;strong&gt;Manual&lt;/strong&gt; partitioning.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="186"/> <source>Install %1 &lt;strong&gt;alongside&lt;/strong&gt; another operating system on disk &lt;strong&gt;%2&lt;/strong&gt; (%3).</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="193"/> <source>&lt;strong&gt;Erase&lt;/strong&gt; disk &lt;strong&gt;%2&lt;/strong&gt; (%3) and install %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="200"/> <source>&lt;strong&gt;Replace&lt;/strong&gt; a partition on disk &lt;strong&gt;%2&lt;/strong&gt; (%3) with %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="207"/> <source>&lt;strong&gt;Manual&lt;/strong&gt; partitioning on disk &lt;strong&gt;%1&lt;/strong&gt; (%2).</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="215"/> <source>Disk &lt;strong&gt;%1&lt;/strong&gt; (%2)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="243"/> <source>Current:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="261"/> <source>After:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="405"/> <source>No EFI system partition configured</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="406"/> <source>An EFI system partition is necessary to start %1.&lt;br/&gt;&lt;br/&gt;To configure an EFI system partition, go back and select or create a FAT32 filesystem with the &lt;strong&gt;esp&lt;/strong&gt; flag enabled and mount point &lt;strong&gt;%2&lt;/strong&gt;.&lt;br/&gt;&lt;br/&gt;You can continue without setting up an EFI system partition but your system may fail to start.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="420"/> <source>EFI system partition flag not set</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="421"/> <source>An EFI system partition is necessary to start %1.&lt;br/&gt;&lt;br/&gt;A partition was configured with mount point &lt;strong&gt;%2&lt;/strong&gt; but its &lt;strong&gt;esp&lt;/strong&gt; flag is not set.&lt;br/&gt;To set the flag, go back and edit the partition.&lt;br/&gt;&lt;br/&gt;You can continue without setting the flag but your system may fail to start.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="456"/> <source>Boot partition not encrypted</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionViewStep.cpp" line="457"/> <source>A separate boot partition was set up together with an encrypted root partition, but the boot partition is not encrypted.&lt;br/&gt;&lt;br/&gt;There are security concerns with this kind of setup, because important system files are kept on an unencrypted partition.&lt;br/&gt;You may continue if you wish, but filesystem unlocking will happen later during system startup.&lt;br/&gt;To encrypt the boot partition, go back and recreate it, selecting &lt;strong&gt;Encrypt&lt;/strong&gt; in the partition creation window.</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../src/modules/keyboard/keyboardwidget/keyboardglobal.cpp" line="82"/> <source>Default Keyboard Model</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/keyboardwidget/keyboardglobal.cpp" line="127"/> <location filename="../src/modules/keyboard/keyboardwidget/keyboardglobal.cpp" line="163"/> <source>Default</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/KPMHelpers.cpp" line="201"/> <source>unknown</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/KPMHelpers.cpp" line="203"/> <source>extended</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/KPMHelpers.cpp" line="205"/> <source>unformatted</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/core/KPMHelpers.cpp" line="207"/> <source>swap</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/PartitionLabelsView.cpp" line="49"/> <source>Unpartitioned space or unknown partition table</source> <translation type="unfinished"/> </message> </context> <context> <name>ReplaceWidget</name> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="134"/> <source>Select where to install %1.&lt;br/&gt;&lt;font color=&quot;red&quot;&gt;Warning: &lt;/font&gt;this will delete all files on the selected partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="161"/> <source>The selected item does not appear to be a valid partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="169"/> <source>%1 cannot be installed on empty space. Please select an existing partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="180"/> <source>%1 cannot be installed on an extended partition. Please select an existing primary or logical partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="191"/> <source>%1 cannot be installed on this partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="198"/> <source>Data partition (%1)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="215"/> <source>Unknown system partition (%1)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="220"/> <source>%1 system partition (%2)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="231"/> <source>&lt;strong&gt;%4&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;The partition %1 is too small for %2. Please select a partition with capacity at least %3 GiB.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="255"/> <source>&lt;strong&gt;%2&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;An EFI system partition cannot be found anywhere on this system. Please go back and use manual partitioning to set up %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="267"/> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="286"/> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="311"/> <source>&lt;strong&gt;%3&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;%1 will be installed on %2.&lt;br/&gt;&lt;font color=&quot;red&quot;&gt;Warning: &lt;/font&gt;all data on partition %2 will be lost.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="277"/> <source>The EFI system partition at %1 will be used for starting %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ReplaceWidget.cpp" line="295"/> <source>EFI system partition:</source> <translation type="unfinished"/> </message> </context> <context> <name>RequirementsChecker</name> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="61"/> <source>Gathering system information...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="102"/> <source>has at least %1 GB available drive space</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="104"/> <source>There is not enough drive space. At least %1 GB is required.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="112"/> <source>has at least %1 GB working memory</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="114"/> <source>The system does not have enough working memory. At least %1 GB is required.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="122"/> <source>is plugged in to a power source</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="123"/> <source>The system is not plugged in to a power source.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="130"/> <source>is connected to the Internet</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="131"/> <source>The system is not connected to the Internet.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/checker/RequirementsChecker.cpp" line="139"/> <source>The installer is not running with administrator rights.</source> <translation type="unfinished"/> </message> </context> <context> <name>ResizeFileSystemJob</name> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="76"/> <source>Resize file system on partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="91"/> <source>Parted failed to resize filesystem.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="101"/> <source>Failed to resize filesystem.</source> <translation type="unfinished"/> </message> </context> <context> <name>ResizePartitionJob</name> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="187"/> <source>Resize partition %1.</source> <translation>Promjeni veličinu particije %1.</translation> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="194"/> <source>Resize &lt;strong&gt;%2MB&lt;/strong&gt; partition &lt;strong&gt;%1&lt;/strong&gt; to &lt;strong&gt;%3MB&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="205"/> <source>Resizing %2MB partition %1 to %3MB.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="232"/> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="298"/> <source>The installer failed to resize partition %1 on disk &apos;%2&apos;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="237"/> <source>Could not open device &apos;%1&apos;.</source> <translation type="unfinished"/> </message> </context> <context> <name>ScanningDialog</name> <message> <location filename="../src/modules/partition/gui/ScanningDialog.cpp" line="83"/> <source>Scanning storage devices...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/gui/ScanningDialog.cpp" line="84"/> <source>Partitioning</source> <translation type="unfinished"/> </message> </context> <context> <name>SetHostNameJob</name> <message> <location filename="../src/modules/users/SetHostNameJob.cpp" line="37"/> <source>Set hostname %1</source> <translation>Postavi ime računara %1</translation> </message> <message> <location filename="../src/modules/users/SetHostNameJob.cpp" line="44"/> <source>Set hostname &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetHostNameJob.cpp" line="51"/> <source>Setting hostname %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetHostNameJob.cpp" line="61"/> <location filename="../src/modules/users/SetHostNameJob.cpp" line="68"/> <source>Internal Error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetHostNameJob.cpp" line="75"/> <location filename="../src/modules/users/SetHostNameJob.cpp" line="86"/> <source>Cannot write hostname to target system</source> <translation type="unfinished"/> </message> </context> <context> <name>SetKeyboardLayoutJob</name> <message> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="59"/> <source>Set keyboard model to %1, layout to %2-%3</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="320"/> <source>Failed to write keyboard configuration for the virtual console.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="321"/> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="325"/> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="331"/> <source>Failed to write to %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="324"/> <source>Failed to write keyboard configuration for X11.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/keyboard/SetKeyboardLayoutJob.cpp" line="330"/><|fim▁hole|><context> <name>SetPartFlagsJob</name> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="48"/> <source>Set flags on partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="51"/> <source>Set flags on %1MB %2 partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="55"/> <source>Set flags on new partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="66"/> <source>Clear flags on partition &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="70"/> <source>Clear flags on %1MB &lt;strong&gt;%2&lt;/strong&gt; partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="74"/> <source>Clear flags on new partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="78"/> <source>Flag partition &lt;strong&gt;%1&lt;/strong&gt; as &lt;strong&gt;%2&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="84"/> <source>Flag %1MB &lt;strong&gt;%2&lt;/strong&gt; partition as &lt;strong&gt;%3&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="90"/> <source>Flag new partition as &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="102"/> <source>Clearing flags on partition &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="106"/> <source>Clearing flags on %1MB &lt;strong&gt;%2&lt;/strong&gt; partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="110"/> <source>Clearing flags on new partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="114"/> <source>Setting flags &lt;strong&gt;%2&lt;/strong&gt; on partition &lt;strong&gt;%1&lt;/strong&gt;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="120"/> <source>Setting flags &lt;strong&gt;%3&lt;/strong&gt; on %1MB &lt;strong&gt;%2&lt;/strong&gt; partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="126"/> <source>Setting flags &lt;strong&gt;%1&lt;/strong&gt; on new partition.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="140"/> <source>The installer failed to set flags on partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="148"/> <source>Could not open device &apos;%1&apos;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="157"/> <source>Could not open partition table on device &apos;%1&apos;.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/SetPartitionFlagsJob.cpp" line="169"/> <source>Could not find partition &apos;%1&apos;.</source> <translation type="unfinished"/> </message> </context> <context> <name>SetPartGeometryJob</name> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="144"/> <source>Update geometry of partition %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/partition/jobs/ResizePartitionJob.cpp" line="156"/> <source>Failed to change the geometry of the partition.</source> <translation type="unfinished"/> </message> </context> <context> <name>SetPasswordJob</name> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="42"/> <source>Set password for user %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="49"/> <source>Setting password for user %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="59"/> <source>Bad destination system path.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="60"/> <source>rootMountPoint is %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="70"/> <source>Cannot disable root account.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="71"/> <source>passwd terminated with error code %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="87"/> <source>Cannot set password for user %1.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/SetPasswordJob.cpp" line="89"/> <source>usermod terminated with error code %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>SetTimezoneJob</name> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="43"/> <source>Set timezone to %1/%2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="71"/> <source>Cannot access selected timezone path.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="72"/> <source>Bad path: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="86"/> <source>Cannot set timezone.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="87"/> <source>Link creation failed, target: %1; link name: %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="96"/> <source>Cannot set timezone,</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/locale/SetTimezoneJob.cpp" line="97"/> <source>Cannot open /etc/timezone for writing</source> <translation type="unfinished"/> </message> </context> <context> <name>SummaryPage</name> <message> <location filename="../src/modules/summary/SummaryPage.cpp" line="46"/> <source>This is an overview of what will happen once you start the install procedure.</source> <translation type="unfinished"/> </message> </context> <context> <name>SummaryViewStep</name> <message> <location filename="../src/modules/summary/SummaryViewStep.cpp" line="43"/> <source>Summary</source> <translation>Izveštaj</translation> </message> </context> <context> <name>UsersPage</name> <message> <location filename="../src/modules/users/UsersPage.cpp" line="275"/> <source>Your username is too long.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/UsersPage.cpp" line="285"/> <source>Your username contains invalid characters. Only lowercase letters and numbers are allowed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/UsersPage.cpp" line="329"/> <source>Your hostname is too short.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/UsersPage.cpp" line="340"/> <source>Your hostname is too long.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/UsersPage.cpp" line="351"/> <source>Your hostname contains invalid characters. Only letters, numbers and dashes are allowed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/users/UsersPage.cpp" line="382"/> <location filename="../src/modules/users/UsersPage.cpp" line="415"/> <source>Your passwords do not match!</source> <translation>Vaše lozinke se ne poklapaju</translation> </message> </context> <context> <name>UsersViewStep</name> <message> <location filename="../src/modules/users/UsersViewStep.cpp" line="48"/> <source>Users</source> <translation>Korisnici</translation> </message> </context> <context> <name>WelcomePage</name> <message> <location filename="../src/modules/welcome/WelcomePage.ui" line="14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.ui" line="75"/> <source>&amp;Language:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.ui" line="176"/> <source>&amp;Release notes</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.ui" line="166"/> <source>&amp;Known issues</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.ui" line="156"/> <source>&amp;Support</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.ui" line="146"/> <source>&amp;About</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.cpp" line="56"/> <source>&lt;h1&gt;Welcome to the %1 installer.&lt;/h1&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.cpp" line="70"/> <source>About %1 installer</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.cpp" line="72"/> <source>&lt;h1&gt;%1&lt;/h1&gt;&lt;br/&gt;&lt;strong&gt;%2&lt;br/&gt;for %3&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;Copyright 2014-2017 Teo Mrnjavac &amp;lt;[email protected]&amp;gt;&lt;br/&gt;Thanks to: Anke Boersma, Aurélien Gâteau, Kevin Kofler, Lisa Vitolo, Philip Müller, Pier Luigi Fiorini, Rohan Garg and the &lt;a href=&quot;https://www.transifex.com/calamares/calamares/&quot;&gt;Calamares translators team&lt;/a&gt;.&lt;br/&gt;&lt;br/&gt;&lt;a href=&quot;http://calamares.io/&quot;&gt;Calamares&lt;/a&gt; development is sponsored by &lt;br/&gt;&lt;a href=&quot;http://www.blue-systems.com/&quot;&gt;Blue Systems&lt;/a&gt; - Liberating Software.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/modules/welcome/WelcomePage.cpp" line="196"/> <source>%1 support</source> <translation type="unfinished"/> </message> </context> <context> <name>WelcomeViewStep</name> <message> <location filename="../src/modules/welcome/WelcomeViewStep.cpp" line="51"/> <source>Welcome</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<source>Failed to write keyboard configuration to existing /etc/default directory.</source> <translation type="unfinished"/> </message> </context>
<|file_name|>GpioPinPwm.java<|end_file_name|><|fim▁begin|>package com.pi4j.io.gpio; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : GpioPinPwm.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2015 Pi4J * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * Gpio input pin interface. This interface is extension of {@link GpioPin} interface * with reading pwm values. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ @SuppressWarnings("unused")<|fim▁hole|>}<|fim▁end|>
public interface GpioPinPwm extends GpioPin { int getPwm();
<|file_name|>IAccount.java<|end_file_name|><|fim▁begin|>package com.dgex.offspring.nxtCore.service; import java.util.List; import nxt.Account; import nxt.Alias; import nxt.Block; import nxt.Transaction; import com.dgex.offspring.nxtCore.core.TransactionHelper.IteratorAsList; public interface IAccount { public Account getNative(); public Long getId(); public String getStringId(); public long getBalance(); public long getUnconfirmedBalance(); public long getAssetBalance(Long assetId); public long getUnconfirmedAssetBalance(Long assetId); public String getPrivateKey(); public byte[] getPublicKey(); public List<ITransaction> getTransactions(); public List<Transaction> getNativeTransactions(); <|fim▁hole|> public List<IAlias> getAliases(); public List<IMessage> getMessages(); public List<IAsset> getIssuedAssets(); public int getForgedFee(); public boolean startForging(); public boolean stopForging(); public boolean isForging(); public boolean isReadOnly(); IteratorAsList getUserTransactions(); }<|fim▁end|>
public List<Alias> getNativeAliases(); public List<Block> getForgedBlocks();
<|file_name|>transport-browser.ts<|end_file_name|><|fim▁begin|>/* * Copyright 2015 Mozilla 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. */ module RtmpJs.Browser { var DEFAULT_RTMP_PORT = 1935; var COMBINE_RTMPT_DATA = true; var TCPSocket = (<any>navigator).mozTCPSocket; export class RtmpTransport extends BaseTransport { host: string; port: number; ssl: boolean; constructor(connectionSettings) { super(); if (typeof connectionSettings === 'string') { connectionSettings = {host: connectionSettings}; } this.host = connectionSettings.host || 'localhost'; this.port = connectionSettings.port || DEFAULT_RTMP_PORT; this.ssl = !!connectionSettings.ssl || false; } connect(properties, args?) { if (!TCPSocket) { throw new Error('Your browser does not support socket communication.\n' + 'Currenly only Firefox with enabled mozTCPSocket is allowed (see README.md).'); } var channel = this._initChannel(properties, args); var writeQueue = [], socketError = false; var createRtmpSocket = (<any>window).createRtmpSocket; var socket = createRtmpSocket ? createRtmpSocket({host: this.host, port: this.port, ssl: this.ssl}) : TCPSocket.open(this.host, this.port, { useSecureTransport: this.ssl, binaryType: 'arraybuffer' }); var sendData = function (data) { return socket.send(data.buffer, data.byteOffset, data.byteLength); }; socket.onopen = function (e) { channel.ondata = function (data) { var buf = new Uint8Array(data); writeQueue.push(buf); if (writeQueue.length > 1) { return; } release || console.log('Bytes written: ' + buf.length); if (sendData(buf)) { writeQueue.shift(); } }; channel.onclose = function () { socket.close(); }; channel.start(); }; socket.ondrain = function (e) { writeQueue.shift(); release || console.log('Write completed'); while (writeQueue.length > 0) { release || console.log('Bytes written: ' + writeQueue[0].length); if (!sendData(writeQueue[0])) { break; } writeQueue.shift(); } }; socket.onclose = function (e) { channel.stop(socketError); }; socket.onerror = function (e) { socketError = true; console.error('socket error: ' + e.data); }; socket.ondata = function (e) { release || console.log('Bytes read: ' + e.data.byteLength); channel.push(new Uint8Array(e.data)); }; } } /* * RtmptTransport uses systemXHR to send HTTP requests. * See https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#XMLHttpRequest%28%29 and * https://github.com/mozilla-b2g/gaia/blob/master/apps/email/README.md#running-in-firefox * * Spec at http://red5.electroteque.org/dev/doc/html/rtmpt.html */ export class RtmptTransport extends BaseTransport { baseUrl: string; stopped: boolean; sessionId: string; requestId: number; data: Uint8Array[]; constructor(connectionSettings) { super(); var host = connectionSettings.host || 'localhost'; var url = (connectionSettings.ssl ? 'https' : 'http') + '://' + host; if (connectionSettings.port) { url += ':' + connectionSettings.port; } this.baseUrl = url; this.stopped = false; this.sessionId = null; this.requestId = 0; this.data = []; } connect(properties, args?) { var channel = this._initChannel(properties, args); channel.ondata = function (data) { release || console.log('Bytes written: ' + data.length); this.data.push(new Uint8Array(data)); }.bind(this); channel.onclose = function () { this.stopped = true; }.bind(this); post(this.baseUrl + '/fcs/ident2', null, function (data, status) { if (status !== 404) { throw new Error('Unexpected response: ' + status); } post(this.baseUrl + '/open/1', null, function (data, status) { this.sessionId = String.fromCharCode.apply(null, data).slice(0, -1); // - '\n' console.log('session id: ' + this.sessionId); this.tick(); channel.start(); }.bind(this)); }.bind(this)); } tick() { var continueSend = function (data, status) { if (status !== 200) { throw new Error('Invalid HTTP status'); } var idle = data[0]; if (data.length > 1) { this.channel.push(data.subarray(1)); } setTimeout(this.tick.bind(this), idle * 16); }.bind(this); if (this.stopped) { post(this.baseUrl + '/close/2', null, function () { // do nothing }); return; } if (this.data.length > 0) { var data; if (COMBINE_RTMPT_DATA) { var length = 0; this.data.forEach(function (i) { length += i.length; }); var pos = 0; data = new Uint8Array(length); this.data.forEach(function (i) { data.set(i, pos); pos += i.length; }); this.data.length = 0; } else { data = this.data.shift(); } post(this.baseUrl + '/send/' + this.sessionId + '/' + (this.requestId++), data, continueSend); } else { post(this.baseUrl + '/idle/' + this.sessionId + '/' + (this.requestId++), null, continueSend); } } } var emptyPostData = new Uint8Array([0]); function post(path, data, onload) { data || (data = emptyPostData); var createRtmpXHR = (<any>window).createRtmpXHR; var xhr = createRtmpXHR ? createRtmpXHR() : new (<any>XMLHttpRequest)({mozSystem: true}); xhr.open('POST', path, true); xhr.responseType = 'arraybuffer'; xhr.setRequestHeader('Content-Type', 'application/x-fcs'); xhr.onload = function (e) {<|fim▁hole|> xhr.onerror = function (e) { console.log('error'); throw new Error('HTTP error'); }; xhr.send(data); } }<|fim▁end|>
onload(new Uint8Array(xhr.response), xhr.status); };
<|file_name|>rpc.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015-2017 winapi-rs developers // Licensed under the Apache License, Version 2.0<|fim▁hole|>// except according to those terms. // Master include file for RPC applications. pub type I_RPC_HANDLE = *mut ::c_void; pub type RPC_STATUS = ::c_long;<|fim▁end|>
// <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. // All files in the project carrying such notice may not be copied, modified, or distributed
<|file_name|>project_test1.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # Copyright 2002 Dave Abrahams # Copyright 2002, 2003, 2004 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) from BoostBuild import Tester import os t = Tester("--build-system=project-test1", boost_build_path='', pass_toolset=0) # This test does no modifications, so run in in the invocation dir os.chdir(t.original_workdir)<|fim▁hole|> expected_output1="""Project Roots: """ expected_output2="""'%(root-dir-prefix)sdir2': Module for project-root is 'project-root<%(root-dir-prefix)sdir2>' Projects: '/cool-library': * Parent project: (none) * Requirements: <include>/home/ghost/build/boost-cvs * Default build: * Source location: %(root-dir-prefix)sdir2 * Projects to build: """ expected_output3="""'%(root-dir)s': Module for project-root is 'project-root<%(root-dir)s>' Projects: '/boost-build-test-project-1': * Parent project: (none) * Requirements: <include>/home/ghost/local/include <threading>multi * Default build: * Source location: %(root-dir)s * Projects to build: dir dir2 '/boost-build-test-project-1/dir': * Parent project: %(root-dir)s * Requirements: <include>/home/ghost/local/include <threading>multi * Default build: <variant>release * Source location: %(root-dir-prefix)sdir/src * Projects to build: """ # Test that correct project structure is created when jam is invoked # outside of the source tree. expected = (expected_output1 + expected_output2 + expected_output3) % \ {"root-dir": "project-test1", "root-dir-prefix": "project-test1/" } t.run_build_system(stdout=expected) # Test that correct project structure is created when jam is invoked # at the top of the source tree. expected = (expected_output1 + expected_output3 + expected_output2) % \ {"root-dir": ".", "root-dir-prefix": "" } os.chdir("project-test1") t.run_build_system(stdout=expected) t.cleanup()<|fim▁end|>
<|file_name|>external_tools.py<|end_file_name|><|fim▁begin|>from restclients.canvas import Canvas #from restclients.models.canvas import ExternalTool class ExternalTools(Canvas): def get_external_tools_in_account(self, account_id): """<|fim▁hole|> Return external tools for the passed canvas account id. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index """ url = "/api/v1/accounts/%s/external_tools" % account_id external_tools = [] for data in self._get_resource(url): external_tools.append(self._external_tool_from_json(data)) return external_tools def get_external_tools_in_account_by_sis_id(self, sis_id): """ Return external tools for given account sis id. """ return self.get_external_tools_in_account(self._sis_id(sis_id, "account")) def get_external_tools_in_course(self, course_id): """ Return external tools for the passed canvas course id. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index """ url = "/api/v1/courses/%s/external_tools" % course_id external_tools = [] for data in self._get_resource(url): external_tools.append(self._external_tool_from_json(data)) return external_tools def get_external_tools_in_course_by_sis_id(self, sis_id): """ Return external tools for given course sis id. """ return self.get_external_tools_in_course(self._sis_id(sis_id, "course")) def _external_tool_from_json(self, data): return data<|fim▁end|>
<|file_name|>cli.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2015, 2016 CERN. # # Zenodo 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. # # Zenodo 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 Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """CLI for Zenodo fixtures.""" from __future__ import absolute_import, print_function import json from os.path import dirname, join import click from flask.cli import with_appcontext from invenio_communities.utils import initialize_communities_bucket from sqlalchemy.orm.exc import NoResultFound from .communities import loadcommunities from .files import loaddemofiles, loadlocation from .grants import loadfp6funders, loadfp6grants from .licenses import loadlicenses, matchlicenses from .oai import loadoaisets from .pages import loadpages from .records import loaddemorecords @click.group() def fixtures(): """Command for loading fixture data.""" @fixtures.command() @with_appcontext def init(): """Load basic data.""" loadpages() loadlocation() loadoaisets() initialize_communities_bucket() @fixtures.command('loadpages') @click.option('--force', '-f', is_flag=True, default=False) @with_appcontext def loadpages_cli(force): """Load pages.""" loadpages(force=force) click.secho('Created pages', fg='green') @fixtures.command('loadlocation') @with_appcontext<|fim▁hole|> loc = loadlocation() click.secho('Created location {0}'.format(loc.uri), fg='green') @fixtures.command('loadoaisets') @with_appcontext def loadoaisets_cli(): """Load OAI-PMH sets.""" sets_count = loadoaisets() click.secho('Created {0} OAI-PMH sets'.format(len(sets_count)), fg='green') @fixtures.command('loadfp6grants') @with_appcontext def loadfp6grants_cli(): """Load one-off grants.""" loadfp6grants() @fixtures.command('loadfp6funders') @with_appcontext def loadfp6funders_cli(): """Load one-off funders.""" loadfp6funders() @fixtures.command('loaddemorecords') @with_appcontext def loaddemorecords_cli(): """Load demo records.""" click.echo('Loading demo data...') with open(join(dirname(__file__), 'data/records.json'), 'r') as fp: data = json.load(fp) click.echo('Sending tasks to queue...') with click.progressbar(data) as records: loaddemorecords(records) click.echo("1. Start Celery:") click.echo(" celery worker -A zenodo.celery -l INFO") click.echo("2. After tasks have been processed start reindexing:") click.echo(" zenodo migration recordsrun") click.echo(" zenodo migration reindex recid") click.echo(" zenodo index run -d -c 4") @fixtures.command('loaddemofiles') @click.argument('source', type=click.Path(exists=True, dir_okay=False, resolve_path=True)) @with_appcontext def loaddemofiles_cli(source): """Load demo files.""" loaddemofiles(source) @fixtures.command('loadlicenses') @with_appcontext def loadlicenses_cli(): """Load Zenodo licenses.""" loadlicenses() @fixtures.command('matchlicenses') @click.argument('legacy_source', type=click.Path(exists=True, dir_okay=False, resolve_path=True)) @click.argument('od_source', type=click.Path(exists=True, dir_okay=False, resolve_path=True)) @click.argument('destination', type=click.Path(exists=False, dir_okay=False)) def matchlicenses_cli(legacy_source, od_source, destination): """Match legacy Zenodo licenses with OpenDefinition.org licenses.""" matchlicenses(legacy_source, od_source, destination) @fixtures.command('loadcommunities') @click.argument('owner_email') @with_appcontext def loadcommunities_cli(owner_email): """Load Zenodo communities.""" try: loadcommunities(owner_email) except NoResultFound: click.echo("Error: Provided owner email does not exist.")<|fim▁end|>
def loadlocation_cli(): """Load data store location."""
<|file_name|>routes.rs<|end_file_name|><|fim▁begin|>//! # Request handlers //! //! Iron's [`router`]() will accept a function closure that takes //! a mutable `Request` and returns an `IronResult<Response>`. //! The application specifies two handlers: //! //! - `get_person` handles `GET /person/:id`, and will get a `Person` //! from Redis and return them as json. //! - `post_person` handles `POST /person/:id`, and will update a //! `Person` in Redis with a new name. use serde_json; use redis::{self, Commands}; use iron::prelude::*; use iron::status; use router::Router; use errors::*; use model::*; /// Get a person by id. /// /// This handler takes an id from the query parameters and gets /// the corresponding person, or returns a `HTTP 404`. pub fn get_person(req: &mut Request) -> IronResult<Response> { let id = get_id(&req)?; let conn = get_conn()?; let person_data = get_person_data(conn, &id)?; Ok(Response::with((status::Ok, person_data))) } #[derive(Deserialize)] struct PostPersonCommand { pub name: String, } /// Post a new person value for an id. /// /// This handler takes an id and `PostPersonCommand` and adds or updates /// that person's data. /// /// The body of the request should look something like: /// /// ```json /// { "name": "Some Name" } /// ``` pub fn post_person(req: &mut Request) -> IronResult<Response> { let id = get_id(&req)?;<|fim▁hole|> let person = make_person(req, id)?; set_person_data(conn, person)?; Ok(Response::with(status::Ok)) } /// Get an `Id` from the request url params. fn get_id(req: &Request) -> Result<Id> { req.extensions .get::<Router>() .unwrap() .find("id") .unwrap_or("") .try_into() } /// Get a new Redis connection. fn get_conn() -> Result<redis::Connection> { let client = redis::Client::open("redis://127.0.0.1/")?; client.get_connection().map_err(|e| e.into()) } /// Get the data for a `Person` from Redis. fn get_person_data(conn: redis::Connection, id: &Id) -> Result<String> { let person_data: Option<String> = conn.get(id.as_ref())?; person_data.ok_or(Error::from(ErrorKind::PersonNotFound)) } /// Set the data for a `Person` in Redis. fn set_person_data(conn: redis::Connection, person: Person) -> Result<()> { let person_data = serde_json::to_string(&person)?; conn.set(person.id.as_ref(), person_data)?; Ok(()) } /// Get a person from the request body with an id. fn make_person(req: &mut Request, id: Id) -> Result<Person> { let cmd: PostPersonCommand = serde_json::from_reader(&mut req.body)?; Ok(Person { id: id, name: cmd.name, }) }<|fim▁end|>
let conn = get_conn()?;
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|>import sys # widgets class Button: """ Represents button Keyword arguments: text -- button text | str onclick -- function invoked after pressing the button | function: Button -> void Attributes: wide -- makes the button wide """ def __new__(cls, text=None, onclick=None): return object.__new__(sys.modules['aui.widgets'].Button) def __init__(self, text, onclick=None): self.wide = self def destroy(self): """Destroys the button""" pass class Checkbox: """ Represents checkbox in UI Keyword arguments: text -- checkbox text | str selected -- whether the checkbox is selected on init | boolean onchange -- function invoked after toggling the checkbox | function: Checkbox -> void """ def __new__(cls, text=None, selected=False, onchange=None, *args): return object.__new__(sys.modules['aui.widgets'].Checkbox) def __init__(self, text, selected=False, onchange=None): pass def destroy(self): """Destroys the checkbox""" pass class Input: """ Represents input field in UI Keyword arguments: value -- default value | str (default: "") onenter -- function called after the return key is pressed | function: Input -> void Attributes: wide -- makes the input wide """ def __new__(cls, value="", onenter=None, *args): return object.__new__(sys.modules['aui.widgets'].Input) def __init__(self, value="", onenter=None): self.wide = self def destroy(self): """Destroys the input field""" pass class Label: """ Represents label in UI Keyword arguments: text -- label text | str<|fim▁hole|> """ def __new__(cls, text=None, *args): return object.__new__(sys.modules['aui.widgets'].Label) def __init__(self, text): pass def destroy(self): """Destroys the label""" pass class Text: """ Represents multiline input field in UI Keyword arguments: text -- widget text | str (default: "") """ def __new__(cls, text=None, *args): return object.__new__(sys.modules['aui.widgets'].Text) def __init__(self, text=""): pass def destroy(self): """Destroys the text field""" pass # containers class Vertical: """ Represents vertical container in UI Arguments: *children -- children elements of the container """ def __new__(cls, *args): return object.__new__(sys.modules['aui.widgets'].Vertical) def append(self, child): """ Appends widget to the vertical container Keyword arguments: child -- the widget to be placed into the container """ pass def create(self, parent, align=None): """ Creates vertical container and assigns it to its parent Keyword arguments: parent -- parent of the element to be put into align -- alignment of the element in container tk.constants.(TOP/RIGHT/BOTTOM/LEFT) """ pass def destroy(self): """Destroys the vertical container""" pass class Horizontal: """ Represents horizontal container in UI Arguments: *children -- children elements of the container """ def __new__(cls, *args): return object.__new__(sys.modules['aui.widgets'].Horizontal) def append(self, child): """ Appends widget to the horizontal container Keyword arguments: child -- the widget to be placed into the container """ pass def create(self, parent, align=None): """ Creates horizontal container and assigns it to its parent Keyword arguments: parent -- parent of the element to be put into align -- alignment of the element in container tk.constants.(TOP/RIGHT/BOTTOM/LEFT) """ pass def destroy(self): """Destroys the horizontal container""" pass<|fim▁end|>
<|file_name|>cookies.ts<|end_file_name|><|fim▁begin|>/** * @module * Cookies support. */ import { getHeader, setHeader, } from './headers'; /** * Returns true if `name` is a valid cookie name according to RFC-6265 */ export function isValidName(name: string): boolean { // Any CHAR (Octets 0-127) except CTLs or separators if (name.length <= 0) { return false; } for (let i = 0; i < name.length; i++) { const c = name.charCodeAt(i); const fail = (c >= 0 && c <= 32) || c === 34 || c === 40 || c === 41 || c === 44 || c === 47 || c === 58 || c === 59 || (c >= 60 && c <= 64) || c === 91 || c === 92 || c === 93 || c === 123 || c === 125 || c === 127; if (fail) { return false; } } return true; } /** * Returns true if `value` is a valid cookie value according to RFC-6265 */ export function isValidValue(value: string): boolean { for (let i = 0; i < value.length; i++) { if (!isValidValueChar(value.charCodeAt(i))) { return false; } } return true; } function isValidValueChar(c: number): boolean { return c === 0x21 || (c >= 0x23 && c <= 0x2b) || (c >= 0x2d && c <= 0x3a) || (c >= 0x3c && c <= 0x5b) || (c >= 0x5d && c <= 0x7e); } /** * Extracts cookie from cookie header value. */ export function extract(cookieHeader: string, name: string): string | undefined { const STATE_MATCH = 0; const STATE_FIND_END = 1; const STATE_SKIP_SPACES = 2; const STATE_NOM_END = 3; if (!isValidName(name)) { throw new TypeError(`invalid cookie name: ${name}`); } name = `${name}=`; let i: number, j: number, state = STATE_SKIP_SPACES; for (i = 0, j = 0; i < cookieHeader.length;) { const c = cookieHeader.charCodeAt(i); switch (state) { case STATE_MATCH: // assert: j < name.length since name.length > 0 if (c !== name.charCodeAt(j)) { state = STATE_FIND_END; j = 0; } else { i++; j++; if (j === name.length) { state = STATE_NOM_END; j = i; } } break; case STATE_FIND_END: if (c === 59 /* ; */) { state = STATE_SKIP_SPACES; } i++; break; case STATE_SKIP_SPACES: if (c !== 32 /* SP */) { state = STATE_MATCH; } else { i++; } break; case STATE_NOM_END: if (c === 59 /* ; */) { return cookieHeader.substring(j, i); } else if (!isValidValueChar(c)) { return; } else { i++; } break; default: throw new Error('unknown state'); } } return state === STATE_NOM_END ? cookieHeader.substring(j, i) : undefined; } type CookieOptions = { path?: string; expires?: Date; domain?: string; httpOnly?: boolean; sameSite?: 'strict' | 'lax'; secure?: boolean; /** * In milliseconds. */ maxAge?: number; }; export function stringify(name: string, value: string, options?: CookieOptions): string { if (!options) { options = {}; } if (!isValidName(name)) { throw new TypeError(`invalid cookie name: ${name}`); } if (!isValidValue(value)) { throw new TypeError(`invalid cookie value: ${value}`); } const expires = options.maxAge ? new Date(Date.now() + options.maxAge) : options.expires; <|fim▁hole|> header += `; path=${options.path}`; } if (expires) { header += `; expires=${expires.toUTCString()}`; } if (options.domain) { header += `; domain=${options.domain}`; } if (options.sameSite) { header += `; samesite=${options.sameSite}`; } if (options.secure) { header += '; secure'; } if (options.httpOnly) { header += '; httponly'; } return header; } type GetCookieRequest = { headers: {[key: string]: string | string[] | undefined}; }; export function getCookie(req: GetCookieRequest, name: string): string | undefined { const cookieHeader = req.headers['cookie']; if (typeof cookieHeader !== 'string') { return; } return extract(cookieHeader, name); } type SetCookieResponse = { headers: Map<string, string[]>; }; export function setCookie(resp: SetCookieResponse, name: string, value: string, options?: CookieOptions): void { const cookieHeaders = getHeader(resp, 'Set-Cookie') .filter(header => header.startsWith(`${name}=`)); cookieHeaders.push(stringify(name, value, options)); setHeader(resp, 'Set-Cookie', cookieHeaders); }<|fim▁end|>
let header = `${name}=${value}`; if (options.path) {
<|file_name|>PipelineRunNode.js<|end_file_name|><|fim▁begin|>/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import PipelineRunNodeedges from './PipelineRunNodeedges'; /** * The PipelineRunNode model module. * @module model/PipelineRunNode * @version 1.1.2-pre.0 */ class PipelineRunNode { /** * Constructs a new <code>PipelineRunNode</code>. * @alias module:model/PipelineRunNode */ constructor() { PipelineRunNode.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PipelineRunNode</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PipelineRunNode} obj Optional instance to populate. * @return {module:model/PipelineRunNode} The populated <code>PipelineRunNode</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PipelineRunNode(); if (data.hasOwnProperty('_class')) { obj['_class'] = ApiClient.convertToType(data['_class'], 'String'); } if (data.hasOwnProperty('displayName')) { obj['displayName'] = ApiClient.convertToType(data['displayName'], 'String'); } if (data.hasOwnProperty('durationInMillis')) { obj['durationInMillis'] = ApiClient.convertToType(data['durationInMillis'], 'Number'); } if (data.hasOwnProperty('edges')) { obj['edges'] = ApiClient.convertToType(data['edges'], [PipelineRunNodeedges]); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('result')) { obj['result'] = ApiClient.convertToType(data['result'], 'String'); } if (data.hasOwnProperty('startTime')) { obj['startTime'] = ApiClient.convertToType(data['startTime'], 'String'); } if (data.hasOwnProperty('state')) { obj['state'] = ApiClient.convertToType(data['state'], 'String'); } } return obj; } } /** * @member {String} _class */ PipelineRunNode.prototype['_class'] = undefined; /** * @member {String} displayName */ PipelineRunNode.prototype['displayName'] = undefined; /** * @member {Number} durationInMillis */ PipelineRunNode.prototype['durationInMillis'] = undefined;<|fim▁hole|> /** * @member {Array.<module:model/PipelineRunNodeedges>} edges */ PipelineRunNode.prototype['edges'] = undefined; /** * @member {String} id */ PipelineRunNode.prototype['id'] = undefined; /** * @member {String} result */ PipelineRunNode.prototype['result'] = undefined; /** * @member {String} startTime */ PipelineRunNode.prototype['startTime'] = undefined; /** * @member {String} state */ PipelineRunNode.prototype['state'] = undefined; export default PipelineRunNode;<|fim▁end|>
<|file_name|>mpl1.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals import sys import os import random import matplotlib # Make sure that we are using QT5 matplotlib.use('Qt5Agg') from PyQt5 import QtCore, QtWidgets from numpy import arange, sin, pi from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure progname = os.path.basename(sys.argv[0]) progversion = "0.1" class MyMplCanvas(FigureCanvas): """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) self.compute_initial_figure() FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def compute_initial_figure(self): pass class MyStaticMplCanvas(MyMplCanvas): """Simple canvas with a sine plot.""" def compute_initial_figure(self): t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.axes.plot(t, s) class MyDynamicMplCanvas(MyMplCanvas): """A canvas that updates itself every second with a new plot.""" def __init__(self, *args, **kwargs): MyMplCanvas.__init__(self, *args, **kwargs) timer = QtCore.QTimer(self) timer.timeout.connect(self.update_figure) timer.start(1000) def compute_initial_figure(self): self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r') def update_figure(self): # Build a list of 4 random integers between 0 and 10 (both inclusive) l = [random.randint(0, 10) for i in range(4)] self.axes.cla() self.axes.plot([0, 1, 2, 3], l, 'r') self.draw() class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("application main window") self.file_menu = QtWidgets.QMenu('&File', self) self.file_menu.addAction('&Quit', self.fileQuit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q) self.menuBar().addMenu(self.file_menu)<|fim▁hole|> self.menuBar().addMenu(self.help_menu) self.help_menu.addAction('&About', self.about) self.main_widget = QtWidgets.QWidget(self) l = QtWidgets.QVBoxLayout(self.main_widget) sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100) dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100) l.addWidget(sc) l.addWidget(dc) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) self.statusBar().showMessage("All hail matplotlib!", 2000) def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit() def about(self): QtWidgets.QMessageBox.about(self, "About", """embedding_in_qt5.py example Copyright 2005 Florent Rougon, 2006 Darren Dale, 2015 Jens H Nielsen This program is a simple example of a Qt5 application embedding matplotlib canvases. It may be used and modified with no restriction; raw copies as well as modified versions may be distributed without limitation. This is modified from the embedding in qt4 example to show the difference between qt4 and qt5""" ) qApp = QtWidgets.QApplication(sys.argv) aw = ApplicationWindow() aw.setWindowTitle("%s" % progname) aw.show() sys.exit(qApp.exec_()) # qApp.exec_()<|fim▁end|>
self.help_menu = QtWidgets.QMenu('&Help', self) self.menuBar().addSeparator()
<|file_name|>HealthColors.js<|end_file_name|><|fim▁begin|>/* My Profile link: https://app.roll20.net/users/262130/dxwarlock GIT link: https://github.com/dxwarlock/Roll20/blob/master/Public/HeathColors Roll20Link: https://app.roll20.net/forum/post/4630083/script-aura-slash-tint-healthcolor Last Updated 2/27/2017 */ /*global createObj getAttrByName spawnFxWithDefinition getObj state playerIsGM sendChat _ findObjs log on*/ var HealthColors = HealthColors || (function() { 'use strict'; var version = '1.2.0', ScriptName = "HealthColors", schemaVersion = '1.0.3', Updated = "Feb 27 2017", /*-------- ON TOKEN UPDATE --------*/ handleToken = function(obj, prev) { var ColorOn = state.HealthColors.auraColorOn; var bar = state.HealthColors.auraBar; var tint = state.HealthColors.auraTint; var onPerc = state.HealthColors.auraPerc; var dead = state.HealthColors.auraDead; if (obj.get("represents") !== "" || (obj.get("represents") == "" && state.HealthColors.OneOff == true)) { if (ColorOn !== true) return; //Check Toggle //ATTRIBUTE CHECK------------ var oCharacter = getObj('character', obj.get("_represents")); if (oCharacter !== undefined) { //SET BLOOD ATTRIB------------ if (getAttrByName(oCharacter.id, 'BLOODCOLOR') === undefined) CreateAttrib(oCharacter, 'BLOODCOLOR', 'DEFAULT'); var Blood = findObjs({name: 'BLOODCOLOR',_type: "attribute",characterid: oCharacter.id}, {caseInsensitive: true})[0]; var UseBlood = Blood.get("current"); UseBlood = UseBlood.toString().toUpperCase(); //SET DISABLED AURA/TINT ATTRIB------------ if (getAttrByName(oCharacter.id, 'USECOLOR') === undefined) CreateAttrib(oCharacter, 'USECOLOR', 'YES'); var UseAuraAtt = findObjs({name: "USECOLOR",_type: "attribute",characterid: oCharacter.id}, {caseInsensitive: true})[0]; var UseAura = UseAuraAtt.get("current"); UseAura = UseAura.toString().toUpperCase(); //DISABLE OR ENABLE AURA/TINT ON TOKEN------------ if (UseAura != "YES" && UseAura != "NO") { UseAuraAtt.set('current', "YES"); var name = oCharacter.get('name'); GMW(name + ": USECOLOR NOT SET TO YES or NO, SETTING TO YES"); } UseAura = UseAuraAtt.get("current").toUpperCase(); if (UseAura == "NO") return; } //CHECK BARS------------ if (obj.get(bar + "_max") === "" || obj.get(bar + "_value") === "") return; var maxValue = parseInt(obj.get(bar + "_max"), 10); var curValue = parseInt(obj.get(bar + "_value"), 10); var prevValue = prev[bar + "_value"]; if (isNaN(maxValue) && isNaN(curValue)) return; //CALC PERCENTAGE------------ var perc = Math.round((curValue / maxValue) * 100); var percReal = Math.min(100, perc); //PERCENTAGE OFF------------ if (percReal > onPerc) { SetAuraNone(obj); return; } //SET DEAD------------ if (curValue <= 0 && dead === true) { obj.set("status_dead", true); SetAuraNone(obj); if (state.HealthColors.auraDeadFX !== "None") PlayDeath(state.HealthColors.auraDeadFX); return; } else if (dead === true) obj.set("status_dead", false); //CHECK MONSTER OR PLAYER------------ var type = (oCharacter === undefined || oCharacter.get("controlledby") === "") ? 'Monster' : 'Player'; //IF PLAYER------------ var GM = '', PC = ''; var markerColor = PercentToRGB(Math.min(100, percReal)); var pColor = '#ffffff'; if (type == 'Player') { if (state.HealthColors.PCAura === false) return; var cBy = oCharacter.get('controlledby'); var player = getObj('player', cBy); pColor = '#000000'; if (player !== undefined) pColor = player.get('color'); GM = state.HealthColors.GM_PCNames; if (GM != 'Off') { GM = (GM == "Yes") ? true : false; obj.set({'showname': GM}); } PC = state.HealthColors.PCNames; if (PC != 'Off') { PC = (PC == "Yes") ? true : false; obj.set({'showplayers_name': PC}); } } //IF MONSTER------------ if (type == 'Monster') { if (state.HealthColors.NPCAura === false) return; GM = state.HealthColors.GM_NPCNames; if (GM != 'Off') { GM = (GM == "Yes") ? true : false; obj.set({'showname': GM}); } PC = state.HealthColors.NPCNames; if (PC != 'Off') { PC = (PC == "Yes") ? true : false; obj.set({'showplayers_name': PC}); } } //SET AURA|TINT------------ if (tint === true) obj.set({'tint_color': markerColor,}); else { TokenSet(obj, state.HealthColors.AuraSize, markerColor, pColor); } //SPURT FX------------ if (state.HealthColors.FX == true && obj.get("layer") == "objects" && UseBlood !== "OFF") { if (curValue == prevValue || prevValue == "") return; var amount = Math.abs(curValue - prevValue); var HitSizeCalc = Math.min((amount / maxValue) * 4, 1); var HitSize = Math.max(HitSizeCalc, 0.2) * (_.random(60, 100) / 100); var HealColor = HEXtoRGB(state.HealthColors.HealFX); var HurtColor = HEXtoRGB(state.HealthColors.HurtFX); if (UseBlood !== "DEFAULT") HurtColor = HEXtoRGB(UseBlood); var size = obj.get("height"); var multi = size / 70; var StartColor; var EndColor; var HITS; if (curValue > prevValue && prevValue !== "") { StartColor = HealColor; EndColor = [255, 255, 255, 0]; HITS = Heal(HitSize, multi, StartColor, EndColor, size); } else { StartColor = HurtColor; EndColor = [0, 0, 0, 0]; HITS = Hurt(HitSize, multi, StartColor, EndColor, size); } spawnFxWithDefinition(obj.get("left"), obj.get("top"), HITS, obj.get("_pageid")); } } }, /*-------- CHAT MESSAGES --------*/ handleInput = function(msg) { var msgFormula = msg.content.split(/\s+/); var command = msgFormula[0].toUpperCase(); if (msg.type == "api" && command.indexOf("!AURA") !== -1) { if (!playerIsGM(msg.playerid)) { sendChat('HealthColors', "/w " + msg.who + " you must be a GM to use this command!"); return; } else { var option = msgFormula[1]; if (option === undefined) { aurahelp(); return; } switch (msgFormula[1].toUpperCase()) { case "ON": state.HealthColors.auraColorOn = !state.HealthColors.auraColorOn; aurahelp(); break; case "BAR": state.HealthColors.auraBar = "bar" + msgFormula[2]; aurahelp(); break; case "TINT": state.HealthColors.auraTint = !state.HealthColors.auraTint; aurahelp(); break; case "PERC": state.HealthColors.auraPerc = parseInt(msgFormula[2], 10); aurahelp(); break; case "PC": state.HealthColors.PCAura = !state.HealthColors.PCAura; aurahelp(); break; case "NPC": state.HealthColors.NPCAura = !state.HealthColors.NPCAura; aurahelp(); break; case "GMNPC": state.HealthColors.GM_NPCNames = msgFormula[2]; aurahelp(); break; case "GMPC": state.HealthColors.GM_PCNames = msgFormula[2]; aurahelp(); break; case "PCNPC": state.HealthColors.NPCNames = msgFormula[2]; aurahelp(); break; case "PCPC": state.HealthColors.PCNames = msgFormula[2]; aurahelp();<|fim▁hole|> break; case "DEAD": state.HealthColors.auraDead = !state.HealthColors.auraDead; aurahelp(); break; case "DEADFX": state.HealthColors.auraDeadFX = msgFormula[2]; aurahelp(); break; case "SIZE": state.HealthColors.AuraSize = parseFloat(msgFormula[2]); aurahelp(); break; case "ONEOFF": state.HealthColors.OneOff = !state.HealthColors.OneOff; aurahelp(); break; case "FX": state.HealthColors.FX = !state.HealthColors.FX; aurahelp(); break; case "HEAL": var UPPER = msgFormula[2]; UPPER = UPPER.toUpperCase(); state.HealthColors.HealFX = UPPER; aurahelp(); break; case "HURT": var UPPER = msgFormula[2]; UPPER = UPPER.toUpperCase(); state.HealthColors.HurtFX = UPPER; aurahelp(); break; default: return; } } } }, /*-------- FUNCTIONS --------*/ //HURT FX---------- Hurt = function(HitSize, multi, StartColor, EndColor, size) { var FX = { "maxParticles": 150, "duration": 70 * HitSize, "size": size / 10 * HitSize, "sizeRandom": 3, "lifeSpan": 25, "lifeSpanRandom": 5, "speed": multi * 8, "speedRandom": multi * 3, "gravity": { "x": multi * 0.01, "y": multi * 0.65 }, "angle": 270, "angleRandom": 25, "emissionRate": 100 * HitSize, "startColour": StartColor, "endColour": EndColor, }; return FX; }, //HEAL FX---------- Heal = function(HitSize, multi, StartColor, EndColor, size) { var FX = { "maxParticles": 150, "duration": 50 * HitSize, "size": size / 10 * HitSize, "sizeRandom": 15 * HitSize, "lifeSpan": multi * 50, "lifeSpanRandom": 30, "speed": multi * 0.5, "speedRandom": multi / 2 * 1.1, "angle": 0, "angleRandom": 180, "emissionRate": 1000, "startColour": StartColor, "endColour": EndColor, }; return FX; }, //WHISPER GM------------ GMW = function(text) { sendChat('HealthColors', "/w GM <br><b> " + text + "</b>"); }, //DEATH SOUND------------ PlayDeath = function(trackname) { var track = findObjs({type: 'jukeboxtrack',title: trackname})[0]; if (track) { track.set('playing', false); track.set('softstop', false); track.set('volume', 50); track.set('playing', true); } else { log("No track found"); } }, //CREATE USECOLOR ATTR------------ CreateAttrib = function(oCharacter, attrib, value) { log("Creating "+ attrib); createObj("attribute", {name: attrib,current: value,characterid: oCharacter.id}); }, //SET TOKEN COLORS------------ TokenSet = function(obj, sizeSet, markerColor, pColor) { var Pageon = getObj("page", obj.get("_pageid")); var scale = Pageon.get("scale_number") / 10; obj.set({ 'aura1_radius': sizeSet * scale * 1.8, 'aura2_radius': sizeSet * scale * 0.1, 'aura1_color': markerColor, 'aura2_color': pColor, 'showplayers_aura1': true, 'showplayers_aura2': true, }); }, //HELP MENU------------ aurahelp = function() { var img = "background-image: -webkit-linear-gradient(-45deg, #a7c7dc 0%,#85b2d3 100%);"; var tshadow = "-1px -1px #000, 1px -1px #000, -1px 1px #000, 1px 1px #000 , 2px 2px #222;"; var style = 'style="padding-top: 1px; text-align:center; font-size: 9pt; width: 45px; height: 14px; border: 1px solid black; margin: 1px; background-color: #6FAEC7;border-radius: 4px; box-shadow: 1px 1px 1px #707070;'; var off = "#A84D4D"; var disable = "#D6D6D6"; var HR = "<hr style='background-color: #000000; margin: 5px; border-width:0;color: #000000;height: 1px;'/>"; var FX = state.HealthColors.auraDeadFX.substring(0, 4); sendChat('HealthColors', "/w GM <b><br>" + '<div style="border-radius: 8px 8px 8px 8px; padding: 5px; font-size: 9pt; text-shadow: ' + tshadow + '; box-shadow: 3px 3px 1px #707070; '+img+' color:#FFF; border:2px solid black; text-align:right; vertical-align:middle;">' + '<u>HealthColors Version: ' + version + '</u><br>' + //-- HR + //-- 'Is On: <a ' + style + 'background-color:' + (state.HealthColors.auraColorOn !== true ? off : "") + ';" href="!aura on">' + (state.HealthColors.auraColorOn !== true ? "No" : "Yes") + '</a><br>' + //-- 'Bar: <a ' + style + '" href="!aura bar ?{Bar|1|2|3}">' + state.HealthColors.auraBar + '</a><br>' + //-- 'Use Tint: <a ' + style + 'background-color:' + (state.HealthColors.auraTint !== true ? off : "") + ';" href="!aura tint">' + (state.HealthColors.auraTint !== true ? "No" : "Yes") + '</a><br>' + //-- 'Percentage: <a ' + style + '" href="!aura perc ?{Percent?|100}">' + state.HealthColors.auraPerc + '</a><br>' + //-- 'Show on PC: <a ' + style + 'background-color:' + (state.HealthColors.PCAura !== true ? off : "") + ';" href="!aura pc">' + (state.HealthColors.PCAura !== true ? "No" : "Yes") + '</a><br>' + //-- 'Show on NPC: <a ' + style + 'background-color:' + (state.HealthColors.NPCAura !== true ? off : "") + ';" href="!aura npc">' + (state.HealthColors.NPCAura !== true ? "No" : "Yes") + '</a><br>' + //-- 'Show Dead: <a ' + style + 'background-color:' + (state.HealthColors.auraDead !== true ? off : "") + ';" href="!aura dead">' + (state.HealthColors.auraDead !== true ? "No" : "Yes") + '</a><br>' + //-- 'DeathSFX: <a ' + style + '" href="!aura deadfx ?{Sound Name?|None}">' + FX + '</a><br>' + //-- HR + //-- 'GM Sees all NPC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.GM_NPCNames, off, disable) + ';" href="!aura gmnpc ?{Setting|Yes|No|Off}">' + state.HealthColors.GM_NPCNames + '</a><br>' + //--- 'GM Sees all PC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.GM_PCNames, off, disable) + ';" href="!aura gmpc ?{Setting|Yes|No|Off}">' + state.HealthColors.GM_PCNames + '</a><br>' + //-- HR + //-- 'PC Sees all NPC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.NPCNames, off, disable) + ';" href="!aura pcnpc ?{Setting|Yes|No|Off}">' + state.HealthColors.NPCNames + '</a><br>' + //-- 'PC Sees all PC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.PCNames, off, disable) + ';" href="!aura pcpc ?{Setting|Yes|No|Off}">' + state.HealthColors.PCNames + '</a><br>' + //-- HR + //-- 'Aura Size: <a ' + style + '" href="!aura size ?{Size?|0.7}">' + state.HealthColors.AuraSize + '</a><br>' + //-- 'One Offs: <a ' + style + 'background-color:' + (state.HealthColors.OneOff !== true ? off : "") + ';" href="!aura ONEOFF">' + (state.HealthColors.OneOff !== true ? "No" : "Yes") + '</a><br>' + //-- 'FX: <a ' + style + 'background-color:' + (state.HealthColors.FX !== true ? off : "") + ';" href="!aura FX">' + (state.HealthColors.FX !== true ? "No" : "Yes") + '</a><br>' + //-- 'HealFX Color: <a ' + style + 'background-color:#' + state.HealthColors.HealFX + ';""href="!aura HEAL ?{Color?|00FF00}">' + state.HealthColors.HealFX + '</a><br>' + //-- 'HurtFX Color: <a ' + style + 'background-color:#' + state.HealthColors.HurtFX + ';""href="!aura HURT ?{Color?|FF0000}">' + state.HealthColors.HurtFX + '</a><br>' + //-- HR + //-- '</div>'); }, //OFF BUTTON COLORS------------ ButtonColor = function(state, off, disable) { var color; if (state == "No") color = off; if (state == "Off") color = disable; return color; }, //REMOVE ALL------------ SetAuraNone = function(obj) { var tint = state.HealthColors.auraTint; if (tint === true) { obj.set({'tint_color': "transparent",}); } else { obj.set({ 'aura1_color': "", 'aura2_color': "", }); } }, //PERC TO RGB------------ PercentToRGB = function(percent) { if (percent === 100) percent = 99; var r, g, b; if (percent < 50) { g = Math.floor(255 * (percent / 50)); r = 255; } else { g = 255; r = Math.floor(255 * ((50 - percent % 50) / 50)); } b = 0; var Gradient = rgbToHex(r, g, b); return Gradient; }, //RGB TO HEX------------ rgbToHex = function(r, g, b) { var Color = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); return Color; }, //HEX TO RGB------------ HEXtoRGB = function(hex) { let parts = hex.match(/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/); if (parts) { let rgb = _.chain(parts) .rest() .map((d) => parseInt(d, 16)) .value(); rgb.push(1.0); return rgb; } return [0, 0, 0, 1.0]; }, //CHECK INSTALL & SET STATE------------ checkInstall = function() { log('<' + ScriptName + ' v' + version + ' Ready [Updated: '+ Updated+']>'); if (!_.has(state, 'HealthColors') || state.HealthColors.schemaVersion !== schemaVersion) { log('<' + ScriptName + ' Updating Schema to v' + schemaVersion + '>'); state.HealthColors = { schemaVersion: schemaVersion }; state.HealthColors.version = version; } if (_.isUndefined(state.HealthColors.auraColorOn)) state.HealthColors.auraColorOn = true; //global on or off if (_.isUndefined(state.HealthColors.auraBar)) state.HealthColors.auraBar = "bar1"; //bar to use if (_.isUndefined(state.HealthColors.PCAura)) state.HealthColors.PCAura = true; //show players Health? if (_.isUndefined(state.HealthColors.NPCAura)) state.HealthColors.NPCAura = true; //show NPC Health? if (_.isUndefined(state.HealthColors.auraTint)) state.HealthColors.auraTint = false; //use tint instead? if (_.isUndefined(state.HealthColors.auraPerc)) state.HealthColors.auraPerc = 100; //precent to start showing if (_.isUndefined(state.HealthColors.auraDead)) state.HealthColors.auraDead = true; //show dead X status if (_.isUndefined(state.HealthColors.auraDeadFX)) state.HealthColors.auraDeadFX = 'None'; //Sound FX Name if (_.isUndefined(state.HealthColors.GM_NPCNames)) state.HealthColors.GM_NPCNames = "Yes"; //show GM NPC names? if (_.isUndefined(state.HealthColors.NPCNames)) state.HealthColors.NPCNames = "Yes"; //show players NPC Names? if (_.isUndefined(state.HealthColors.GM_PCNames)) state.HealthColors.GM_PCNames = "Yes"; //show GM PC names? if (_.isUndefined(state.HealthColors.PCNames)) state.HealthColors.PCNames = "Yes"; //show players PC Names? if (_.isUndefined(state.HealthColors.AuraSize)) state.HealthColors.AuraSize = 0.7; //set aura size? if (_.isUndefined(state.HealthColors.FX)) state.HealthColors.FX = true; //set FX ON/OFF? if (_.isUndefined(state.HealthColors.HealFX)) state.HealthColors.HealFX = "00FF00"; //set FX HEAL COLOR if (_.isUndefined(state.HealthColors.HurtFX)) state.HealthColors.HurtFX = "FF0000"; //set FX HURT COLOR? }, registerEventHandlers = function() { on('chat:message', handleInput); on("change:token", handleToken); }; /*------------- RETURN OUTSIDE FUNCTIONS -----------*/ return { CheckInstall: checkInstall, RegisterEventHandlers: registerEventHandlers }; }()); //On Ready on('ready', function() { 'use strict'; HealthColors.CheckInstall(); HealthColors.RegisterEventHandlers(); });<|fim▁end|>
<|file_name|>future.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 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. /*! * A type representing values that may be computed concurrently and * operations for working with them. * * # Example * * ```rust * use std::sync::Future; * # fn fib(n: uint) -> uint {42}; * # fn make_a_sandwich() {}; * let mut delayed_fib = Future::spawn(proc() { fib(5000) }); * make_a_sandwich(); * println!("fib(5000) = {}", delayed_fib.get()) * ``` */ #![allow(missing_doc)] use core::prelude::*; use core::mem::replace; use comm::{Receiver, channel}; use task::spawn; /// A type encapsulating the result of a computation which may not be complete pub struct Future<A> { state: FutureState<A>, } enum FutureState<A> { Pending(proc():Send -> A), Evaluating, Forced(A) } /// Methods on the `future` type impl<A:Clone> Future<A> { pub fn get(&mut self) -> A { //! Get the value of the future. (*(self.get_ref())).clone() } } impl<A> Future<A> { /// Gets the value from this future, forcing evaluation. pub fn unwrap(mut self) -> A { self.get_ref(); let state = replace(&mut self.state, Evaluating); match state { Forced(v) => v, _ => fail!( "Logic error." ), } } pub fn get_ref<'a>(&'a mut self) -> &'a A { /*! * Executes the future's closure and then returns a reference * to the result. The reference lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => fail!("Recursive forcing of future!"), Pending(_) => { match replace(&mut self.state, Evaluating) { Forced(_) | Evaluating => fail!("Logic error."), Pending(f) => { self.state = Forced(f()); self.get_ref() } } } } } pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: proc():Send -> A) -> Future<A> { /*! * Create a future from a function. * * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ Future {state: Pending(f)} } } impl<A:Send> Future<A> { pub fn from_receiver(rx: Receiver<A>) -> Future<A> { /*! * Create a future from a port * * The first time that the value is requested the task will block * waiting for the result to be received on the port. */ Future::from_fn(proc() { rx.recv() }) } pub fn spawn(blk: proc():Send -> A) -> Future<A> { /*! * Create a future from a unique closure. * * The closure will be run in a new task and its result used as the * value of the future. */ let (tx, rx) = channel(); spawn(proc() { // Don't fail if the other end has hung up let _ = tx.send_opt(blk()); }); Future::from_receiver(rx) } } #[cfg(test)] mod test { use prelude::*; use sync::Future; use task; use comm::{channel, Sender}; #[test] fn test_from_value() { let mut f = Future::from_value("snail".to_string()); assert_eq!(f.get(), "snail".to_string()); } #[test] fn test_from_receiver() { let (tx, rx) = channel(); tx.send("whale".to_string()); let mut f = Future::from_receiver(rx); assert_eq!(f.get(), "whale".to_string());<|fim▁hole|> fn test_from_fn() { let mut f = Future::from_fn(proc() "brail".to_string()); assert_eq!(f.get(), "brail".to_string()); } #[test] fn test_interface_get() { let mut f = Future::from_value("fail".to_string()); assert_eq!(f.get(), "fail".to_string()); } #[test] fn test_interface_unwrap() { let f = Future::from_value("fail".to_string()); assert_eq!(f.unwrap(), "fail".to_string()); } #[test] fn test_get_ref_method() { let mut f = Future::from_value(22i); assert_eq!(*f.get_ref(), 22); } #[test] fn test_spawn() { let mut f = Future::spawn(proc() "bale".to_string()); assert_eq!(f.get(), "bale".to_string()); } #[test] #[should_fail] fn test_futurefail() { let mut f = Future::spawn(proc() fail!()); let _x: String = f.get(); } #[test] fn test_sendable_future() { let expected = "schlorf"; let (tx, rx) = channel(); let f = Future::spawn(proc() { expected }); task::spawn(proc() { let mut f = f; tx.send(f.get()); }); assert_eq!(rx.recv(), expected); } #[test] fn test_dropped_future_doesnt_fail() { struct Bomb(Sender<bool>); local_data_key!(LOCAL: Bomb) impl Drop for Bomb { fn drop(&mut self) { let Bomb(ref tx) = *self; tx.send(task::failing()); } } // Spawn a future, but drop it immediately. When we receive the result // later on, we should never view the task as having failed. let (tx, rx) = channel(); drop(Future::spawn(proc() { LOCAL.replace(Some(Bomb(tx))); })); // Make sure the future didn't fail the task. assert!(!rx.recv()); } }<|fim▁end|>
} #[test]
<|file_name|>borrowck-move-out-of-vec-tail.rs<|end_file_name|><|fim▁begin|>// Test that we do not permit moves from &[] matched by a vec pattern. struct Foo { string: ~str } pub fn main() { let x = [ Foo { string: ~"foo" }, Foo { string: ~"bar" }, Foo { string: ~"baz" } ]; match x { [_, ..tail] => { match tail { [Foo { string: a }, Foo { string: b }] => { //~^ ERROR cannot move out of dereference of & pointer //~^^ ERROR cannot move out of dereference of & pointer } _ => { ::std::util::unreachable(); } } let z = copy tail[0]; info!(fmt!("%?", z)); } _ => { ::std::util::unreachable(); }<|fim▁hole|>}<|fim▁end|>
}
<|file_name|>config.py<|end_file_name|><|fim▁begin|>import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SECRET_KEY = os.getenv('APP_SECRET_KEY', '') # db config DB_PORT = os.getenv('DB_PORT', '') DB_HOST = os.getenv('DB_HOST', '') DB_ROLE = os.getenv('DB_ROLE', '') # TODO: abstract auth stuff to kubernetes manifests DB_PASSWORD = os.getenv('DB_PASSWORD', '') DB_NAME = os.getenv('DB_NAME', '') SQLALCHEMY_DATABASE_URI = 'postgresql://{}:{}@{}:{}/{}'.format( DB_ROLE, DB_PASSWORD, DB_HOST, str(DB_PORT), DB_NAME) class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True<|fim▁hole|>class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True<|fim▁end|>
<|file_name|>handy.js<|end_file_name|><|fim▁begin|>'use strict'; var handyJS = {}; 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; handyJS.ajax = {}; handyJS.ajax.request = function (options) { var self = this; var blankFun = function blankFun() {}; self.xhr = new XMLHttpRequest(); if (options.method === undefined) {<|fim▁hole|> } if (options.async === undefined) { options.async = true; } if (!options.data) { options.segments = null; } else if (!Array.isArray(options.data)) { throw Error('Option.data must be an Array.'); } else if (options.data.length === 0) { options.segments = null; } else { //detect the form to send data. if (options.method === 'POST') { options.data.forEach(function (segment) { if (segment === null) { throw Error('Do not send null variable.'); } else if ((typeof segment === 'undefined' ? 'undefined' : _typeof(segment)) === 'object') { for (var key in segment) { if (segment.hasOwnProperty(key)) { if (segment[key] === undefined) { continue; } if (segment[key] instanceof Blob) { if (options.enctype === undefined) { options.enctype = 'FORMDATA'; break; } if (options.enctype.toUpperCase() !== 'FORMDATA') { throw Error('You have to set dataForm to \'FormData\'' + ' because you about to send file, or just ignore this property.'); } } if (options.enctype === undefined) { options.enctype = 'URLENCODE'; } } } } else { throw Error('You have to use {key: value} structure to send data.'); } }); } else { options.enctype = 'URLINLINE'; } } //transform some type of value var transformValue = function transformValue(value) { if (value === null) { return ''; } if (value === undefined) { return ''; } switch (typeof value === 'undefined' ? 'undefined' : _typeof(value)) { case 'object': if (value instanceof Blob) { return value; } else { return JSON.stringify(value); } break; case 'string': return value; default: return value; } }; //encode uri string //Copied from MDN, if wrong, pls info me. var encodeUriStr = function encodeUriStr(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16); }); }; //add event handler. These handlers must added before open method. //set blank functions options.onProgress = options.onProgress || blankFun; options.onComplete = options.onComplete || blankFun; options.onFailed = options.onFailed || blankFun; options.onCanceled = options.onCanceled || blankFun; options.onLoadEnd = options.onLoadEnd || blankFun; self.xhr.addEventListener('progress', options.onProgress); self.xhr.addEventListener('load', options.onComplete); self.xhr.addEventListener('error', options.onFailed); self.xhr.addEventListener('abort', options.onCanceled); self.xhr.addEventListener('loadend', options.onLoadEnd); self.xhr.open(options.method, options.url, options.async, options.user, options.password); //digest the data decided by encode type //header setting must be done here switch (options.enctype.toUpperCase()) { case 'FORMDATA': console.log('Encode data as FormData type.'); options.segments = new FormData(); options.data.forEach(function (segment) { if (segment.fileName) { for (var key in segment) { if (segment.hasOwnProperty(key)) { if (key !== 'fileName') { options.segments.append(key, segment[key], segment.fileName); } } } } else { for (var _key in segment) { if (segment.hasOwnProperty(_key)) { options.segments.append(_key, transformValue(segment[_key])); } } } }); break; case 'URLINLINE': console.log('Encode data as url inline type.'); options.segments = null; options.data.forEach(function (segment, index) { for (var key in segment) { if (segment.hasOwnProperty(key)) { var value = encodeUriStr(transformValue(segment[key])); if (index === 0) { options.url = options.url + '?' + value; } else { options.url = options.url + '&' + value; } } } }); break; case 'URLENCODE': console.log('Encode data as url encode type.'); self.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); options.segments = ''; options.data.forEach(function (segment, index) { for (var key in segment) { if (segment.hasOwnProperty(key)) { var value = encodeUriStr(transformValue(segment[key])); if (index === 0) { options.segments = options.segments + key + '=' + value; } else { options.segments = options.segments + '&' + key + '=' + value; } } } }); break; } self.xhr.send(options.segments); }; handyJS.ajax.post = function (url, data, cb) { var self = this; self.request({ method: 'POST', url: url, data: data, onComplete: function onComplete() { //get response content types var contentType = handyJS.string.removeWhitespace(this.getResponseHeader('content-type').toLowerCase()).split(';'); //callback with probably variables. if (contentType.indexOf('application/json') === -1) { cb(this.responseText); } else { cb(JSON.parse(this.responseText)); } } }); }; 'use strict'; //All bout file manipulate handyJS.file = {}; // sources: // http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript handyJS.file.getExtension = function (fileName) { return fileName.slice((Math.max(0, fileName.lastIndexOf('.')) || Infinity) + 1); }; //usage: changeFileName('ding.js', 'dong'); => dong.js handyJS.file.changeName = function (originalName, newName) { var extension = this.getExtension(originalName); return newName + '.' + extension; }; 'use strict'; handyJS.string = {}; //remove whitespace, tab and new line handyJS.string.removeAllSpace = function (string) { return string.replace(/\s/g, ''); }; //only remove whitespace handyJS.string.removeWhitespace = function (string) { return string.replace(/ /g, ''); }; "use strict";<|fim▁end|>
options.method = 'GET'; } else { options.method = options.method.toUpperCase();
<|file_name|>plugin_suite_test.go<|end_file_name|><|fim▁begin|>package plugin_test import ( "path/filepath" "code.cloudfoundry.org/cli/utils/testhelpers/pluginbuilder" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega"<|fim▁hole|>) func TestPlugin(t *testing.T) { RegisterFailHandler(Fail) pluginbuilder.BuildTestBinary(filepath.Join("..", "fixtures", "plugins"), "test_1") RunSpecs(t, "Plugin Suite") }<|fim▁end|>
"testing"
<|file_name|>protractor.conf.js<|end_file_name|><|fim▁begin|>// conf.js exports.config = { seleniumServerJar: "./node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar", specs: ["test/e2e/*.scenarios.coffee"], baseUrl: "http://localhost:3000", capabilities: { "browserName": "chrome"<|fim▁hole|> }, framework: "mocha" }<|fim▁end|>
<|file_name|>data.js<|end_file_name|><|fim▁begin|>vde.App.controller('DataCtrl', function($scope, $rootScope, $http, timeline, Vis, vg, d3) { $scope.dMdl = { src: {}, formats: ['json', 'csv', 'tsv'], parsings: ['string', 'number', 'boolean', 'date'] }; $scope.finishedLoading = function() { var src = $scope.dMdl.src; src.format.parse = {}; if(vg.isArray(src.values)) { for(var k in src.values[0]) src.format.parse[k] = vg.isNumber(src.values[0][k]) ? 'number' : 'string'; } $scope.dMdl.isLoading = false; $scope.dMdl.hasLoaded = true; $scope.dMdl.isObj = !vg.isArray(src.values); $scope.dMdl.properties = vg.keys(src.values); }; $scope.loadValues = function() { var src = $scope.dMdl.src, req = vg.duplicate(src); if($scope.dMdl.from == 'url') { req.url = 'proxy.php?url=' + encodeURIComponent(req.url); $scope.dMdl.isLoading = true; var dataModel = vg.parse.data([req], function() { $scope.$apply(function() { src.values = dataModel.load[src.name]; $scope.finishedLoading(); }); }); } else { var type = $scope.dMdl.src.format.type;<|fim▁hole|> } else { $scope.dMdl.src.values = d3[type].parse($scope.dMdl.values); $scope.finishedLoading(); } } }; $scope.add = function() { var src = $scope.dMdl.src; for(var p in src.format.parse) if(src.format.parse[p] == 'string') delete src.format.parse[p]; Vis._data[src.name] = vg.duplicate(src); delete Vis._data[src.name].$$hashKey; // AngularJS pollution $rootScope.activePipeline.source = src.name; $scope.dMdl.src = {}; $rootScope.newData = false; timeline.save(); }; $scope.cancel = function() { $rootScope.newData = false; $scope.dMdl.src = {}; $scope.dMdl.isLoading = false; $scope.dMdl.hasLoaded = false; }; });<|fim▁end|>
if(type == 'json') { $scope.dMdl.src.values = JSON.parse($scope.dMdl.values); $scope.finishedLoading();
<|file_name|>file_util.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import os import base64 from random import choice def random_file_from_dir(relative_path):<|fim▁hole|>def abs_path_to_file(relative_path): # print os.getcwd() return os.path.abspath(os.path.join(os.getcwd(), relative_path)) def encode_base64(abs_path): print "abs_path", abs_path with open(abs_path, 'rb') as f: return base64.b64encode(f.read())<|fim▁end|>
random_file = choice(os.listdir(os.path.join(os.getcwd(), relative_path))) return abs_path_to_file(os.path.join(relative_path, random_file))
<|file_name|>Maze.py<|end_file_name|><|fim▁begin|># Copyright 2010 by Dana Larose # This file is part of crashRun. # crashRun 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. # crashRun 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 crashRun. If not, see <http://www.gnu.org/licenses/>. from random import choice from .DisjointSet import DSNode from .DisjointSet import union from .DisjointSet import find from .DisjointSet import split_sets from .Terrain import TerrainFactory from .Terrain import CYBERSPACE_WALL from .Terrain import CYBERSPACE_FLOOR class Maze(object): def __init__(self, length, width): self.length = length self.width = width if self.width % 2 == 0: self.width -= 1 if self.length % 2 == 0: self.length -= 1 self.map = [] self.__tf = TerrainFactory() self.__ds_nodes = [] self.__wall = self.__tf.get_terrain_tile(CYBERSPACE_WALL) self.__floor = self.__tf.get_terrain_tile(CYBERSPACE_FLOOR) self.__gen_initial_map() def __gen_initial_map(self): for r in range(self.length): if r % 2 == 0: self.map.append([self.__wall] * self.width) else: _row = [] _ds_row = [] for c in range(self.width): if c % 2 == 0: _row.append(self.__wall) else: _row.append(self.__floor) _ds_row.append(DSNode((r,c))) self.__ds_nodes.append(_ds_row) self.map.append(_row) def in_bounds(self, row, col): return row >= 0 and row < self.length and col >= 0 and col < self.width def __get_candidate(self, node): _candidates = [] _nr = node.value[0] _nc = node.value[1] if self.in_bounds(_nr - 2, _nc) and self.map[_nr-1][_nc].get_type() == CYBERSPACE_WALL: _c_node = self.__ds_nodes[_nr//2-1][_nc//2] if find(_c_node) != find(node): _candidates.append((_c_node, _nr-1, _nc)) if self.in_bounds(_nr + 2, _nc) and self.map[_nr+1][_nc].get_type() == CYBERSPACE_WALL: _c_node = self.__ds_nodes[_nr//2+1][_nc//2] if find(_c_node) != find(node): _candidates.append((_c_node, _nr+1, _nc)) if self.in_bounds(_nr, _nc - 2) and self.map[_nr][_nc-1].get_type() == CYBERSPACE_WALL: _c_node = self.__ds_nodes[_nr//2][_nc//2-1] if find(_c_node) != find(node): _candidates.append((_c_node, _nr, _nc-1)) if self.in_bounds(_nr, _nc + 2) and self.map[_nr][_nc+1].get_type() == CYBERSPACE_WALL: _c_node = self.__ds_nodes[_nr//2][_nc//2+1] if find(_c_node) != find(node): _candidates.append((_c_node, _nr, _nc+1)) if len(_candidates) > 0: return choice(_candidates)<|fim▁hole|> for _row in self.__ds_nodes: for _node in _row: _merge = self.__get_candidate(_node) if _merge != None: union(_node, _merge[0]) self.map[_merge[1]][_merge[2]] = self.__floor return self.map def print_map(self): for r in range(self.length): row = '' for c in range(self.width): ch = self.map[r][c].get_ch() row += ' ' if ch == '.' else ch print(row)<|fim▁end|>
else: return None def gen_map(self):
<|file_name|>prelude.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 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. //! The I/O Prelude //! //! The purpose of this module is to alleviate imports of many common I/O traits //! by adding a glob import to the top of I/O heavy modules: //! //! ``` //! # #![allow(unused_imports)] //! use std::io::prelude::*; //! ``` #![stable(feature = "rust1", since = "1.0.0")] <|fim▁hole|>pub use fs::PathExt;<|fim▁end|>
pub use super::{Read, Write, BufRead, Seek};
<|file_name|>ec2.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Amazon EC2, Eucalyptus, Nimbus and Outscale drivers. """ import re import sys import base64 import copy import warnings try: from lxml import etree as ET except ImportError: from xml.etree import ElementTree as ET from libcloud.utils.py3 import b, basestring, ensure_string from libcloud.utils.xml import fixxpath, findtext, findattr, findall from libcloud.utils.publickey import get_pubkey_ssh2_fingerprint from libcloud.utils.publickey import get_pubkey_comment from libcloud.utils.iso8601 import parse_date from libcloud.common.aws import AWSBaseResponse, SignedAWSConnection from libcloud.common.types import (InvalidCredsError, MalformedResponseError, LibcloudError) from libcloud.compute.providers import Provider from libcloud.compute.base import Node, NodeDriver, NodeLocation, NodeSize from libcloud.compute.base import NodeImage, StorageVolume, VolumeSnapshot from libcloud.compute.base import KeyPair from libcloud.compute.types import NodeState, KeyPairDoesNotExistError __all__ = [ 'API_VERSION', 'NAMESPACE', 'INSTANCE_TYPES', 'OUTSCALE_INSTANCE_TYPES', 'OUTSCALE_SAS_REGION_DETAILS', 'OUTSCALE_INC_REGION_DETAILS', 'DEFAULT_EUCA_API_VERSION', 'EUCA_NAMESPACE', 'EC2NodeDriver', 'BaseEC2NodeDriver', 'NimbusNodeDriver', 'EucNodeDriver', 'OutscaleSASNodeDriver', 'OutscaleINCNodeDriver', 'EC2NodeLocation', 'EC2ReservedNode', 'EC2SecurityGroup', 'EC2PlacementGroup', 'EC2Network', 'EC2NetworkSubnet', 'EC2NetworkInterface', 'EC2RouteTable', 'EC2Route', 'EC2SubnetAssociation', 'ExEC2AvailabilityZone', 'IdempotentParamError' ] API_VERSION = '2013-10-15' NAMESPACE = 'http://ec2.amazonaws.com/doc/%s/' % (API_VERSION) # Eucalyptus Constants DEFAULT_EUCA_API_VERSION = '3.3.0' EUCA_NAMESPACE = 'http://msgs.eucalyptus.com/%s' % (DEFAULT_EUCA_API_VERSION) """ Sizes must be hardcoded, because Amazon doesn't provide an API to fetch them. From http://aws.amazon.com/ec2/instance-types/ """ INSTANCE_TYPES = { 't1.micro': { 'id': 't1.micro', 'name': 'Micro Instance', 'ram': 613, 'disk': 15, 'bandwidth': None }, 'm1.small': { 'id': 'm1.small', 'name': 'Small Instance', 'ram': 1740, 'disk': 160, 'bandwidth': None }, 'm1.medium': { 'id': 'm1.medium', 'name': 'Medium Instance', 'ram': 3700, 'disk': 410, 'bandwidth': None }, 'm1.large': { 'id': 'm1.large', 'name': 'Large Instance', 'ram': 7680, 'disk': 850, 'bandwidth': None }, 'm1.xlarge': { 'id': 'm1.xlarge', 'name': 'Extra Large Instance', 'ram': 15360, 'disk': 1690, 'bandwidth': None }, 'c1.medium': { 'id': 'c1.medium', 'name': 'High-CPU Medium Instance', 'ram': 1740, 'disk': 350, 'bandwidth': None }, 'c1.xlarge': { 'id': 'c1.xlarge', 'name': 'High-CPU Extra Large Instance', 'ram': 7680, 'disk': 1690, 'bandwidth': None }, 'm2.xlarge': { 'id': 'm2.xlarge', 'name': 'High-Memory Extra Large Instance', 'ram': 17510, 'disk': 420, 'bandwidth': None }, 'm2.2xlarge': { 'id': 'm2.2xlarge', 'name': 'High-Memory Double Extra Large Instance', 'ram': 35021, 'disk': 850, 'bandwidth': None }, 'm2.4xlarge': { 'id': 'm2.4xlarge', 'name': 'High-Memory Quadruple Extra Large Instance', 'ram': 70042, 'disk': 1690, 'bandwidth': None }, 'm3.medium': { 'id': 'm3.medium', 'name': 'Medium Instance', 'ram': 3840, 'disk': 4000, 'bandwidth': None }, 'm3.large': { 'id': 'm3.large', 'name': 'Large Instance', 'ram': 7168, 'disk': 32000, 'bandwidth': None }, 'm3.xlarge': { 'id': 'm3.xlarge', 'name': 'Extra Large Instance', 'ram': 15360, 'disk': 80000, 'bandwidth': None }, 'm3.2xlarge': { 'id': 'm3.2xlarge', 'name': 'Double Extra Large Instance', 'ram': 30720, 'disk': 160000, 'bandwidth': None }, 'cg1.4xlarge': { 'id': 'cg1.4xlarge', 'name': 'Cluster GPU Quadruple Extra Large Instance', 'ram': 22528, 'disk': 1690, 'bandwidth': None }, 'g2.2xlarge': { 'id': 'g2.2xlarge', 'name': 'Cluster GPU G2 Double Extra Large Instance', 'ram': 15000, 'disk': 60, 'bandwidth': None, }, 'cc1.4xlarge': { 'id': 'cc1.4xlarge', 'name': 'Cluster Compute Quadruple Extra Large Instance', 'ram': 23552, 'disk': 1690, 'bandwidth': None }, 'cc2.8xlarge': { 'id': 'cc2.8xlarge', 'name': 'Cluster Compute Eight Extra Large Instance', 'ram': 63488, 'disk': 3370, 'bandwidth': None }, # c3 instances have 2 SSDs of the specified disk size 'c3.large': { 'id': 'c3.large', 'name': 'Compute Optimized Large Instance', 'ram': 3750, 'disk': 32, # x2 'bandwidth': None }, 'c3.xlarge': { 'id': 'c3.xlarge', 'name': 'Compute Optimized Extra Large Instance', 'ram': 7500, 'disk': 80, # x2 'bandwidth': None }, 'c3.2xlarge': { 'id': 'c3.2xlarge', 'name': 'Compute Optimized Double Extra Large Instance', 'ram': 15000, 'disk': 160, # x2 'bandwidth': None }, 'c3.4xlarge': { 'id': 'c3.4xlarge', 'name': 'Compute Optimized Quadruple Extra Large Instance', 'ram': 30000, 'disk': 320, # x2 'bandwidth': None }, 'c3.8xlarge': { 'id': 'c3.8xlarge', 'name': 'Compute Optimized Eight Extra Large Instance', 'ram': 60000, 'disk': 640, # x2 'bandwidth': None }, 'cr1.8xlarge': { 'id': 'cr1.8xlarge', 'name': 'High Memory Cluster Eight Extra Large', 'ram': 244000, 'disk': 240, 'bandwidth': None }, 'hs1.4xlarge': { 'id': 'hs1.4xlarge', 'name': 'High Storage Quadruple Extra Large Instance', 'ram': 61952, 'disk': 2048, 'bandwidth': None }, 'hs1.8xlarge': { 'id': 'hs1.8xlarge', 'name': 'High Storage Eight Extra Large Instance', 'ram': 119808, 'disk': 48000, 'bandwidth': None }, # i2 instances have up to eight SSD drives 'i2.xlarge': { 'id': 'i2.xlarge', 'name': 'High Storage Optimized Extra Large Instance', 'ram': 31232, 'disk': 800, 'bandwidth': None }, 'i2.2xlarge': { 'id': 'i2.2xlarge', 'name': 'High Storage Optimized Double Extra Large Instance', 'ram': 62464, 'disk': 1600, 'bandwidth': None }, 'i2.4xlarge': { 'id': 'i2.4xlarge', 'name': 'High Storage Optimized Quadruple Large Instance', 'ram': 124928, 'disk': 3200, 'bandwidth': None }, 'i2.8xlarge': { 'id': 'i2.8xlarge', 'name': 'High Storage Optimized Eight Extra Large Instance', 'ram': 249856, 'disk': 6400, 'bandwidth': None }, # 1x SSD 'r3.large': { 'id': 'r3.large', 'name': 'Memory Optimized Large instance', 'ram': 15000, 'disk': 32, 'bandwidth': None }, 'r3.xlarge': { 'id': 'r3.xlarge', 'name': 'Memory Optimized Extra Large instance', 'ram': 30500, 'disk': 80, 'bandwidth': None }, 'r3.2xlarge': { 'id': 'r3.2xlarge', 'name': 'Memory Optimized Double Extra Large instance', 'ram': 61000, 'disk': 160, 'bandwidth': None }, 'r3.4xlarge': { 'id': 'r3.4xlarge', 'name': 'Memory Optimized Quadruple Extra Large instance', 'ram': 122000, 'disk': 320, 'bandwidth': None }, 'r3.8xlarge': { 'id': 'r3.8xlarge', 'name': 'Memory Optimized Eight Extra Large instance', 'ram': 244000, 'disk': 320, # x2 'bandwidth': None }, 't2.micro': { 'id': 't2.micro', 'name': 'Burstable Performance Micro Instance', 'ram': 1024, 'disk': 0, # EBS Only 'bandwidth': None, 'extra': { 'cpu': 1 } }, # Burstable Performance General Purpose 't2.small': { 'id': 't2.small', 'name': 'Burstable Performance Small Instance', 'ram': 2048, 'disk': 0, # EBS Only 'bandwidth': None, 'extra': { 'cpu': 11 } }, 't2.medium': { 'id': 't2.medium', 'name': 'Burstable Performance Medium Instance', 'ram': 4028, 'disk': 0, # EBS Only 'bandwidth': None, 'extra': { 'cpu': 2 } } } REGION_DETAILS = { # US East (Northern Virginia) Region 'us-east-1': { 'endpoint': 'ec2.us-east-1.amazonaws.com', 'api_name': 'ec2_us_east', 'country': 'USA', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'cc2.8xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'cg1.4xlarge', 'g2.2xlarge', 'cr1.8xlarge', 'hs1.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # US West (Northern California) Region 'us-west-1': { 'endpoint': 'ec2.us-west-1.amazonaws.com', 'api_name': 'ec2_us_west', 'country': 'USA', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'g2.2xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # US West (Oregon) Region 'us-west-2': { 'endpoint': 'ec2.us-west-2.amazonaws.com', 'api_name': 'ec2_us_west_oregon', 'country': 'US', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'g2.2xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'hs1.8xlarge', 'cc2.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # EU (Ireland) Region 'eu-west-1': { 'endpoint': 'ec2.eu-west-1.amazonaws.com', 'api_name': 'ec2_eu_west', 'country': 'Ireland', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'g2.2xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'hs1.8xlarge', 'cc2.8xlarge', 'i2.xlarge', 'i2.2xlarge',<|fim▁hole|> 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # Asia Pacific (Singapore) Region 'ap-southeast-1': { 'endpoint': 'ec2.ap-southeast-1.amazonaws.com', 'api_name': 'ec2_ap_southeast', 'country': 'Singapore', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'hs1.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # Asia Pacific (Tokyo) Region 'ap-northeast-1': { 'endpoint': 'ec2.ap-northeast-1.amazonaws.com', 'api_name': 'ec2_ap_northeast', 'country': 'Japan', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'g2.2xlarge', 'c1.xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'hs1.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # South America (Sao Paulo) Region 'sa-east-1': { 'endpoint': 'ec2.sa-east-1.amazonaws.com', 'api_name': 'ec2_sa_east', 'country': 'Brazil', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 't2.micro', 't2.small', 't2.medium' ] }, # Asia Pacific (Sydney) Region 'ap-southeast-2': { 'endpoint': 'ec2.ap-southeast-2.amazonaws.com', 'api_name': 'ec2_ap_southeast_2', 'country': 'Australia', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'hs1.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, 'us-gov-west-1': { 'endpoint': 'ec2.us-gov-west-1.amazonaws.com', 'api_name': 'ec2_us_govwest', 'country': 'US', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge', 'c1.medium', 'c1.xlarge', 'g2.2xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge', 'hs1.4xlarge', 'hs1.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge', 'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge', 't2.micro', 't2.small', 't2.medium' ] }, 'nimbus': { # Nimbus clouds have 3 EC2-style instance types but their particular # RAM allocations are configured by the admin 'country': 'custom', 'instance_types': [ 'm1.small', 'm1.large', 'm1.xlarge' ] } } """ Sizes must be hardcoded because Outscale doesn't provide an API to fetch them. Outscale cloud instances share some names with EC2 but have different specifications so declare them in another constant. """ OUTSCALE_INSTANCE_TYPES = { 't1.micro': { 'id': 't1.micro', 'name': 'Micro Instance', 'ram': 615, 'disk': 0, 'bandwidth': None }, 'm1.small': { 'id': 'm1.small', 'name': 'Standard Small Instance', 'ram': 1740, 'disk': 150, 'bandwidth': None }, 'm1.medium': { 'id': 'm1.medium', 'name': 'Standard Medium Instance', 'ram': 3840, 'disk': 420, 'bandwidth': None }, 'm1.large': { 'id': 'm1.large', 'name': 'Standard Large Instance', 'ram': 7680, 'disk': 840, 'bandwidth': None }, 'm1.xlarge': { 'id': 'm1.xlarge', 'name': 'Standard Extra Large Instance', 'ram': 15360, 'disk': 1680, 'bandwidth': None }, 'c1.medium': { 'id': 'c1.medium', 'name': 'Compute Optimized Medium Instance', 'ram': 1740, 'disk': 340, 'bandwidth': None }, 'c1.xlarge': { 'id': 'c1.xlarge', 'name': 'Compute Optimized Extra Large Instance', 'ram': 7168, 'disk': 1680, 'bandwidth': None }, 'c3.large': { 'id': 'c3.large', 'name': 'Compute Optimized Large Instance', 'ram': 3840, 'disk': 32, 'bandwidth': None }, 'c3.xlarge': { 'id': 'c3.xlarge', 'name': 'Compute Optimized Extra Large Instance', 'ram': 7168, 'disk': 80, 'bandwidth': None }, 'c3.2xlarge': { 'id': 'c3.2xlarge', 'name': 'Compute Optimized Double Extra Large Instance', 'ram': 15359, 'disk': 160, 'bandwidth': None }, 'c3.4xlarge': { 'id': 'c3.4xlarge', 'name': 'Compute Optimized Quadruple Extra Large Instance', 'ram': 30720, 'disk': 320, 'bandwidth': None }, 'c3.8xlarge': { 'id': 'c3.8xlarge', 'name': 'Compute Optimized Eight Extra Large Instance', 'ram': 61440, 'disk': 640, 'bandwidth': None }, 'm2.xlarge': { 'id': 'm2.xlarge', 'name': 'High Memory Extra Large Instance', 'ram': 17510, 'disk': 420, 'bandwidth': None }, 'm2.2xlarge': { 'id': 'm2.2xlarge', 'name': 'High Memory Double Extra Large Instance', 'ram': 35020, 'disk': 840, 'bandwidth': None }, 'm2.4xlarge': { 'id': 'm2.4xlarge', 'name': 'High Memory Quadruple Extra Large Instance', 'ram': 70042, 'disk': 1680, 'bandwidth': None }, 'nv1.small': { 'id': 'nv1.small', 'name': 'GPU Small Instance', 'ram': 1739, 'disk': 150, 'bandwidth': None }, 'nv1.medium': { 'id': 'nv1.medium', 'name': 'GPU Medium Instance', 'ram': 3839, 'disk': 420, 'bandwidth': None }, 'nv1.large': { 'id': 'nv1.large', 'name': 'GPU Large Instance', 'ram': 7679, 'disk': 840, 'bandwidth': None }, 'nv1.xlarge': { 'id': 'nv1.xlarge', 'name': 'GPU Extra Large Instance', 'ram': 15358, 'disk': 1680, 'bandwidth': None }, 'g2.2xlarge': { 'id': 'g2.2xlarge', 'name': 'GPU Double Extra Large Instance', 'ram': 15360, 'disk': 60, 'bandwidth': None }, 'cc1.4xlarge': { 'id': 'cc1.4xlarge', 'name': 'Cluster Compute Quadruple Extra Large Instance', 'ram': 24576, 'disk': 1680, 'bandwidth': None }, 'cc2.8xlarge': { 'id': 'cc2.8xlarge', 'name': 'Cluster Compute Eight Extra Large Instance', 'ram': 65536, 'disk': 3360, 'bandwidth': None }, 'hi1.xlarge': { 'id': 'hi1.xlarge', 'name': 'High Storage Extra Large Instance', 'ram': 15361, 'disk': 1680, 'bandwidth': None }, 'm3.xlarge': { 'id': 'm3.xlarge', 'name': 'High Storage Optimized Extra Large Instance', 'ram': 15357, 'disk': 0, 'bandwidth': None }, 'm3.2xlarge': { 'id': 'm3.2xlarge', 'name': 'High Storage Optimized Double Extra Large Instance', 'ram': 30720, 'disk': 0, 'bandwidth': None }, 'm3s.xlarge': { 'id': 'm3s.xlarge', 'name': 'High Storage Optimized Extra Large Instance', 'ram': 15359, 'disk': 0, 'bandwidth': None }, 'm3s.2xlarge': { 'id': 'm3s.2xlarge', 'name': 'High Storage Optimized Double Extra Large Instance', 'ram': 30719, 'disk': 0, 'bandwidth': None }, 'cr1.8xlarge': { 'id': 'cr1.8xlarge', 'name': 'Memory Optimized Eight Extra Large Instance', 'ram': 249855, 'disk': 240, 'bandwidth': None }, 'os1.2xlarge': { 'id': 'os1.2xlarge', 'name': 'Memory Optimized, High Storage, Passthrough NIC Double Extra ' 'Large Instance', 'ram': 65536, 'disk': 60, 'bandwidth': None }, 'os1.4xlarge': { 'id': 'os1.4xlarge', 'name': 'Memory Optimized, High Storage, Passthrough NIC Quadruple Ext' 'ra Large Instance', 'ram': 131072, 'disk': 120, 'bandwidth': None }, 'os1.8xlarge': { 'id': 'os1.8xlarge', 'name': 'Memory Optimized, High Storage, Passthrough NIC Eight Extra L' 'arge Instance', 'ram': 249856, 'disk': 500, 'bandwidth': None }, 'oc1.4xlarge': { 'id': 'oc1.4xlarge', 'name': 'Outscale Quadruple Extra Large Instance', 'ram': 24575, 'disk': 1680, 'bandwidth': None }, 'oc2.8xlarge': { 'id': 'oc2.8xlarge', 'name': 'Outscale Eight Extra Large Instance', 'ram': 65535, 'disk': 3360, 'bandwidth': None } } """ The function manipulating Outscale cloud regions will be overridden because Outscale instances types are in a separate dict so also declare Outscale cloud regions in some other constants. """ OUTSCALE_SAS_REGION_DETAILS = { 'eu-west-3': { 'endpoint': 'api-ppd.outscale.com', 'api_name': 'osc_sas_eu_west_3', 'country': 'FRANCE', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'nv1.small', 'nv1.medium', 'nv1.large', 'nv1.xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'm3.xlarge', 'm3.2xlarge', 'cr1.8xlarge', 'os1.8xlarge' ] }, 'eu-west-1': { 'endpoint': 'api.eu-west-1.outscale.com', 'api_name': 'osc_sas_eu_west_1', 'country': 'FRANCE', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'nv1.small', 'nv1.medium', 'nv1.large', 'nv1.xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'm3.xlarge', 'm3.2xlarge', 'cr1.8xlarge', 'os1.8xlarge' ] }, 'us-east-1': { 'endpoint': 'api.us-east-1.outscale.com', 'api_name': 'osc_sas_us_east_1', 'country': 'USA', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'nv1.small', 'nv1.medium', 'nv1.large', 'nv1.xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'm3.xlarge', 'm3.2xlarge', 'cr1.8xlarge', 'os1.8xlarge' ] } } OUTSCALE_INC_REGION_DETAILS = { 'eu-west-1': { 'endpoint': 'api.eu-west-1.outscale.com', 'api_name': 'osc_inc_eu_west_1', 'country': 'FRANCE', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'nv1.small', 'nv1.medium', 'nv1.large', 'nv1.xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'm3.xlarge', 'm3.2xlarge', 'cr1.8xlarge', 'os1.8xlarge' ] }, 'eu-west-3': { 'endpoint': 'api-ppd.outscale.com', 'api_name': 'osc_inc_eu_west_3', 'country': 'FRANCE', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'nv1.small', 'nv1.medium', 'nv1.large', 'nv1.xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'm3.xlarge', 'm3.2xlarge', 'cr1.8xlarge', 'os1.8xlarge' ] }, 'us-east-1': { 'endpoint': 'api.us-east-1.outscale.com', 'api_name': 'osc_inc_us_east_1', 'country': 'USA', 'instance_types': [ 't1.micro', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'nv1.small', 'nv1.medium', 'nv1.large', 'nv1.xlarge', 'cc1.4xlarge', 'cc2.8xlarge', 'm3.xlarge', 'm3.2xlarge', 'cr1.8xlarge', 'os1.8xlarge' ] } } """ Define the extra dictionary for specific resources """ RESOURCE_EXTRA_ATTRIBUTES_MAP = { 'ebs_volume': { 'snapshot_id': { 'xpath': 'ebs/snapshotId', 'transform_func': str }, 'volume_id': { 'xpath': 'ebs/volumeId', 'transform_func': str }, 'volume_size': { 'xpath': 'ebs/volumeSize', 'transform_func': int }, 'delete': { 'xpath': 'ebs/deleteOnTermination', 'transform_func': str }, 'volume_type': { 'xpath': 'ebs/volumeType', 'transform_func': str }, 'iops': { 'xpath': 'ebs/iops', 'transform_func': int } }, 'elastic_ip': { 'allocation_id': { 'xpath': 'allocationId', 'transform_func': str, }, 'association_id': { 'xpath': 'associationId', 'transform_func': str, }, 'interface_id': { 'xpath': 'networkInterfaceId', 'transform_func': str, }, 'owner_id': { 'xpath': 'networkInterfaceOwnerId', 'transform_func': str, }, 'private_ip': { 'xpath': 'privateIp', 'transform_func': str, } }, 'image': { 'state': { 'xpath': 'imageState', 'transform_func': str }, 'owner_id': { 'xpath': 'imageOwnerId', 'transform_func': str }, 'owner_alias': { 'xpath': 'imageOwnerAlias', 'transform_func': str }, 'is_public': { 'xpath': 'isPublic', 'transform_func': str }, 'architecture': { 'xpath': 'architecture', 'transform_func': str }, 'image_type': { 'xpath': 'imageType', 'transform_func': str }, 'image_location': { 'xpath': 'imageLocation', 'transform_func': str }, 'platform': { 'xpath': 'platform', 'transform_func': str }, 'description': { 'xpath': 'description', 'transform_func': str }, 'root_device_type': { 'xpath': 'rootDeviceType', 'transform_func': str }, 'virtualization_type': { 'xpath': 'virtualizationType', 'transform_func': str }, 'hypervisor': { 'xpath': 'hypervisor', 'transform_func': str }, 'kernel_id': { 'xpath': 'kernelId', 'transform_func': str }, 'ramdisk_id': { 'xpath': 'ramdiskId', 'transform_func': str } }, 'network': { 'state': { 'xpath': 'state', 'transform_func': str }, 'dhcp_options_id': { 'xpath': 'dhcpOptionsId', 'transform_func': str }, 'instance_tenancy': { 'xpath': 'instanceTenancy', 'transform_func': str }, 'is_default': { 'xpath': 'isDefault', 'transform_func': str } }, 'network_interface': { 'subnet_id': { 'xpath': 'subnetId', 'transform_func': str }, 'vpc_id': { 'xpath': 'vpcId', 'transform_func': str }, 'zone': { 'xpath': 'availabilityZone', 'transform_func': str }, 'description': { 'xpath': 'description', 'transform_func': str }, 'owner_id': { 'xpath': 'ownerId', 'transform_func': str }, 'mac_address': { 'xpath': 'macAddress', 'transform_func': str }, 'private_dns_name': { 'xpath': 'privateIpAddressesSet/privateDnsName', 'transform_func': str }, 'source_dest_check': { 'xpath': 'sourceDestCheck', 'transform_func': str } }, 'network_interface_attachment': { 'attachment_id': { 'xpath': 'attachment/attachmentId', 'transform_func': str }, 'instance_id': { 'xpath': 'attachment/instanceId', 'transform_func': str }, 'owner_id': { 'xpath': 'attachment/instanceOwnerId', 'transform_func': str }, 'device_index': { 'xpath': 'attachment/deviceIndex', 'transform_func': int }, 'status': { 'xpath': 'attachment/status', 'transform_func': str }, 'attach_time': { 'xpath': 'attachment/attachTime', 'transform_func': parse_date }, 'delete': { 'xpath': 'attachment/deleteOnTermination', 'transform_func': str } }, 'node': { 'availability': { 'xpath': 'placement/availabilityZone', 'transform_func': str }, 'architecture': { 'xpath': 'architecture', 'transform_func': str }, 'client_token': { 'xpath': 'clientToken', 'transform_func': str }, 'dns_name': { 'xpath': 'dnsName', 'transform_func': str }, 'hypervisor': { 'xpath': 'hypervisor', 'transform_func': str }, 'iam_profile': { 'xpath': 'iamInstanceProfile/id', 'transform_func': str }, 'image_id': { 'xpath': 'imageId', 'transform_func': str }, 'instance_id': { 'xpath': 'instanceId', 'transform_func': str }, 'instance_lifecycle': { 'xpath': 'instanceLifecycle', 'transform_func': str }, 'instance_tenancy': { 'xpath': 'placement/tenancy', 'transform_func': str }, 'instance_type': { 'xpath': 'instanceType', 'transform_func': str }, 'key_name': { 'xpath': 'keyName', 'transform_func': str }, 'launch_index': { 'xpath': 'amiLaunchIndex', 'transform_func': int }, 'launch_time': { 'xpath': 'launchTime', 'transform_func': str }, 'kernel_id': { 'xpath': 'kernelId', 'transform_func': str }, 'monitoring': { 'xpath': 'monitoring/state', 'transform_func': str }, 'platform': { 'xpath': 'platform', 'transform_func': str }, 'private_dns': { 'xpath': 'privateDnsName', 'transform_func': str }, 'ramdisk_id': { 'xpath': 'ramdiskId', 'transform_func': str }, 'root_device_type': { 'xpath': 'rootDeviceType', 'transform_func': str }, 'root_device_name': { 'xpath': 'rootDeviceName', 'transform_func': str }, 'reason': { 'xpath': 'reason', 'transform_func': str }, 'source_dest_check': { 'xpath': 'sourceDestCheck', 'transform_func': str }, 'status': { 'xpath': 'instanceState/name', 'transform_func': str }, 'subnet_id': { 'xpath': 'subnetId', 'transform_func': str }, 'virtualization_type': { 'xpath': 'virtualizationType', 'transform_func': str }, 'ebs_optimized': { 'xpath': 'ebsOptimized', 'transform_func': str }, 'vpc_id': { 'xpath': 'vpcId', 'transform_func': str } }, 'reserved_node': { 'instance_type': { 'xpath': 'instanceType', 'transform_func': str }, 'availability': { 'xpath': 'availabilityZone', 'transform_func': str }, 'start': { 'xpath': 'start', 'transform_func': str }, 'duration': { 'xpath': 'duration', 'transform_func': int }, 'usage_price': { 'xpath': 'usagePrice', 'transform_func': float }, 'fixed_price': { 'xpath': 'fixedPrice', 'transform_func': float }, 'instance_count': { 'xpath': 'instanceCount', 'transform_func': int }, 'description': { 'xpath': 'productDescription', 'transform_func': str }, 'instance_tenancy': { 'xpath': 'instanceTenancy', 'transform_func': str }, 'currency_code': { 'xpath': 'currencyCode', 'transform_func': str }, 'offering_type': { 'xpath': 'offeringType', 'transform_func': str } }, 'security_group': { 'vpc_id': { 'xpath': 'vpcId', 'transform_func': str }, 'description': { 'xpath': 'groupDescription', 'transform_func': str }, 'owner_id': { 'xpath': 'ownerId', 'transform_func': str } }, 'snapshot': { 'volume_id': { 'xpath': 'volumeId', 'transform_func': str }, 'state': { 'xpath': 'status', 'transform_func': str }, 'description': { 'xpath': 'description', 'transform_func': str }, 'progress': { 'xpath': 'progress', 'transform_func': str }, 'start_time': { 'xpath': 'startTime', 'transform_func': parse_date } }, 'subnet': { 'cidr_block': { 'xpath': 'cidrBlock', 'transform_func': str }, 'available_ips': { 'xpath': 'availableIpAddressCount', 'transform_func': int }, 'zone': { 'xpath': 'availabilityZone', 'transform_func': str }, 'vpc_id': { 'xpath': 'vpcId', 'transform_func': str } }, 'volume': { 'device': { 'xpath': 'attachmentSet/item/device', 'transform_func': str }, 'snapshot_id': { 'xpath': 'snapshotId', 'transform_func': lambda v: str(v) or None }, 'iops': { 'xpath': 'iops', 'transform_func': int }, 'zone': { 'xpath': 'availabilityZone', 'transform_func': str }, 'create_time': { 'xpath': 'createTime', 'transform_func': parse_date }, 'state': { 'xpath': 'status', 'transform_func': str }, 'attach_time': { 'xpath': 'attachmentSet/item/attachTime', 'transform_func': parse_date }, 'attachment_status': { 'xpath': 'attachmentSet/item/status', 'transform_func': str }, 'instance_id': { 'xpath': 'attachmentSet/item/instanceId', 'transform_func': str }, 'delete': { 'xpath': 'attachmentSet/item/deleteOnTermination', 'transform_func': str } }, 'route_table': { 'vpc_id': { 'xpath': 'vpcId', 'transform_func': str } } } VALID_EC2_REGIONS = REGION_DETAILS.keys() VALID_EC2_REGIONS = [r for r in VALID_EC2_REGIONS if r != 'nimbus'] class EC2NodeLocation(NodeLocation): def __init__(self, id, name, country, driver, availability_zone): super(EC2NodeLocation, self).__init__(id, name, country, driver) self.availability_zone = availability_zone def __repr__(self): return (('<EC2NodeLocation: id=%s, name=%s, country=%s, ' 'availability_zone=%s driver=%s>') % (self.id, self.name, self.country, self.availability_zone, self.driver.name)) class EC2Response(AWSBaseResponse): """ EC2 specific response parsing and error handling. """ def parse_error(self): err_list = [] # Okay, so for Eucalyptus, you can get a 403, with no body, # if you are using the wrong user/password. msg = "Failure: 403 Forbidden" if self.status == 403 and self.body[:len(msg)] == msg: raise InvalidCredsError(msg) try: body = ET.XML(self.body) except: raise MalformedResponseError("Failed to parse XML", body=self.body, driver=EC2NodeDriver) for err in body.findall('Errors/Error'): code, message = err.getchildren() err_list.append('%s: %s' % (code.text, message.text)) if code.text == 'InvalidClientTokenId': raise InvalidCredsError(err_list[-1]) if code.text == 'SignatureDoesNotMatch': raise InvalidCredsError(err_list[-1]) if code.text == 'AuthFailure': raise InvalidCredsError(err_list[-1]) if code.text == 'OptInRequired': raise InvalidCredsError(err_list[-1]) if code.text == 'IdempotentParameterMismatch': raise IdempotentParamError(err_list[-1]) if code.text == 'InvalidKeyPair.NotFound': # TODO: Use connection context instead match = re.match(r'.*\'(.+?)\'.*', message.text) if match: name = match.groups()[0] else: name = None raise KeyPairDoesNotExistError(name=name, driver=self.connection.driver) return '\n'.join(err_list) class EC2Connection(SignedAWSConnection): """ Represents a single connection to the EC2 Endpoint. """ version = API_VERSION host = REGION_DETAILS['us-east-1']['endpoint'] responseCls = EC2Response class ExEC2AvailabilityZone(object): """ Extension class which stores information about an EC2 availability zone. Note: This class is EC2 specific. """ def __init__(self, name, zone_state, region_name): self.name = name self.zone_state = zone_state self.region_name = region_name def __repr__(self): return (('<ExEC2AvailabilityZone: name=%s, zone_state=%s, ' 'region_name=%s>') % (self.name, self.zone_state, self.region_name)) class EC2ReservedNode(Node): """ Class which stores information about EC2 reserved instances/nodes Inherits from Node and passes in None for name and private/public IPs Note: This class is EC2 specific. """ def __init__(self, id, state, driver, size=None, image=None, extra=None): super(EC2ReservedNode, self).__init__(id=id, name=None, state=state, public_ips=None, private_ips=None, driver=driver, extra=extra) def __repr__(self): return (('<EC2ReservedNode: id=%s>') % (self.id)) class EC2SecurityGroup(object): """ Represents information about a Security group Note: This class is EC2 specific. """ def __init__(self, id, name, ingress_rules, egress_rules, extra=None): self.id = id self.name = name self.ingress_rules = ingress_rules self.egress_rules = egress_rules self.extra = extra or {} def __repr__(self): return (('<EC2SecurityGroup: id=%s, name=%s') % (self.id, self.name)) class EC2PlacementGroup(object): """ Represents information about a Placement Grous Note: This class is EC2 specific. """ def __init__(self, name, state, strategy='cluster', extra=None): self.name = name self.strategy = strategy self.extra = extra or {} def __repr__(self): return '<EC2PlacementGroup: name=%s, state=%s>' % (self.name, self.strategy) class EC2Network(object): """ Represents information about a VPC (Virtual Private Cloud) network Note: This class is EC2 specific. """ def __init__(self, id, name, cidr_block, extra=None): self.id = id self.name = name self.cidr_block = cidr_block self.extra = extra or {} def __repr__(self): return (('<EC2Network: id=%s, name=%s') % (self.id, self.name)) class EC2NetworkSubnet(object): """ Represents information about a VPC (Virtual Private Cloud) subnet Note: This class is EC2 specific. """ def __init__(self, id, name, state, extra=None): self.id = id self.name = name self.state = state self.extra = extra or {} def __repr__(self): return (('<EC2NetworkSubnet: id=%s, name=%s') % (self.id, self.name)) class EC2NetworkInterface(object): """ Represents information about a VPC network interface Note: This class is EC2 specific. The state parameter denotes the current status of the interface. Valid values for state are attaching, attached, detaching and detached. """ def __init__(self, id, name, state, extra=None): self.id = id self.name = name self.state = state self.extra = extra or {} def __repr__(self): return (('<EC2NetworkInterface: id=%s, name=%s') % (self.id, self.name)) class ElasticIP(object): """ Represents information about an elastic IP address :param ip: The elastic IP address :type ip: ``str`` :param domain: The domain that the IP resides in (EC2-Classic/VPC). EC2 classic is represented with standard and VPC is represented with vpc. :type domain: ``str`` :param instance_id: The identifier of the instance which currently has the IP associated. :type instance_id: ``str`` Note: This class is used to support both EC2 and VPC IPs. For VPC specific attributes are stored in the extra dict to make promotion to the base API easier. """ def __init__(self, ip, domain, instance_id, extra=None): self.ip = ip self.domain = domain self.instance_id = instance_id self.extra = extra or {} def __repr__(self): return (('<ElasticIP: ip=%s, domain=%s, instance_id=%s>') % (self.ip, self.domain, self.instance_id)) class VPCInternetGateway(object): """ Class which stores information about VPC Internet Gateways. Note: This class is VPC specific. """ def __init__(self, id, name, vpc_id, state, driver, extra=None): self.id = id self.name = name self.vpc_id = vpc_id self.state = state self.extra = extra or {} def __repr__(self): return (('<VPCInternetGateway: id=%s>') % (self.id)) class EC2RouteTable(object): """ Class which stores information about VPC Route Tables. Note: This class is VPC specific. """ def __init__(self, id, name, routes, subnet_associations, propagating_gateway_ids, extra=None): """ :param id: The ID of the route table. :type id: ``str`` :param name: The name of the route table. :type name: ``str`` :param routes: A list of routes in the route table. :type routes: ``list`` of :class:`EC2Route` :param subnet_associations: A list of associations between the route table and one or more subnets. :type subnet_associations: ``list`` of :class:`EC2SubnetAssociation` :param propagating_gateway_ids: The list of IDs of any virtual private gateways propagating the routes. :type propagating_gateway_ids: ``list`` """ self.id = id self.name = name self.routes = routes self.subnet_associations = subnet_associations self.propagating_gateway_ids = propagating_gateway_ids self.extra = extra or {} def __repr__(self): return (('<EC2RouteTable: id=%s>') % (self.id)) class EC2Route(object): """ Class which stores information about a Route. Note: This class is VPC specific. """ def __init__(self, cidr, gateway_id, instance_id, owner_id, interface_id, state, origin, vpc_peering_connection_id): """ :param cidr: The CIDR block used for the destination match. :type cidr: ``str`` :param gateway_id: The ID of a gateway attached to the VPC. :type gateway_id: ``str`` :param instance_id: The ID of a NAT instance in the VPC. :type instance_id: ``str`` :param owner_id: The AWS account ID of the owner of the instance. :type owner_id: ``str`` :param interface_id: The ID of the network interface. :type interface_id: ``str`` :param state: The state of the route (active | blackhole). :type state: ``str`` :param origin: Describes how the route was created. :type origin: ``str`` :param vpc_peering_connection_id: The ID of the VPC peering connection. :type vpc_peering_connection_id: ``str`` """ self.cidr = cidr self.gateway_id = gateway_id self.instance_id = instance_id self.owner_id = owner_id self.interface_id = interface_id self.state = state self.origin = origin self.vpc_peering_connection_id = vpc_peering_connection_id def __repr__(self): return (('<EC2Route: cidr=%s>') % (self.cidr)) class EC2SubnetAssociation(object): """ Class which stores information about Route Table associated with a given Subnet in a VPC Note: This class is VPC specific. """ def __init__(self, id, route_table_id, subnet_id, main=False): """ :param id: The ID of the subnet association in the VPC. :type id: ``str`` :param route_table_id: The ID of a route table in the VPC. :type route_table_id: ``str`` :param subnet_id: The ID of a subnet in the VPC. :type subnet_id: ``str`` :param main: If true, means this is a main VPC route table. :type main: ``bool`` """ self.id = id self.route_table_id = route_table_id self.subnet_id = subnet_id self.main = main def __repr__(self): return (('<EC2SubnetAssociation: id=%s>') % (self.id)) class BaseEC2NodeDriver(NodeDriver): """ Base Amazon EC2 node driver. Used for main EC2 and other derivate driver classes to inherit from it. """ connectionCls = EC2Connection features = {'create_node': ['ssh_key']} path = '/' NODE_STATE_MAP = { 'pending': NodeState.PENDING, 'running': NodeState.RUNNING, 'shutting-down': NodeState.UNKNOWN, 'terminated': NodeState.TERMINATED } def list_nodes(self, ex_node_ids=None, ex_filters=None): """ List all nodes Ex_node_ids parameter is used to filter the list of nodes that should be returned. Only the nodes with the corresponding node ids will be returned. :param ex_node_ids: List of ``node.id`` :type ex_node_ids: ``list`` of ``str`` :param ex_filters: The filters so that the response includes information for only certain nodes. :type ex_filters: ``dict`` :rtype: ``list`` of :class:`Node` """ params = {'Action': 'DescribeInstances'} if ex_node_ids: params.update(self._pathlist('InstanceId', ex_node_ids)) if ex_filters: params.update(self._build_filters(ex_filters)) elem = self.connection.request(self.path, params=params).object nodes = [] for rs in findall(element=elem, xpath='reservationSet/item', namespace=NAMESPACE): nodes += self._to_nodes(rs, 'instancesSet/item') nodes_elastic_ips_mappings = self.ex_describe_addresses(nodes) for node in nodes: ips = nodes_elastic_ips_mappings[node.id] node.public_ips.extend(ips) return nodes def list_sizes(self, location=None): available_types = REGION_DETAILS[self.region_name]['instance_types'] sizes = [] for instance_type in available_types: attributes = INSTANCE_TYPES[instance_type] attributes = copy.deepcopy(attributes) price = self._get_size_price(size_id=instance_type) attributes.update({'price': price}) sizes.append(NodeSize(driver=self, **attributes)) return sizes def list_images(self, location=None, ex_image_ids=None, ex_owner=None, ex_executableby=None, ex_filters=None): """ List all images @inherits: :class:`NodeDriver.list_images` Ex_image_ids parameter is used to filter the list of images that should be returned. Only the images with the corresponding image ids will be returned. Ex_owner parameter is used to filter the list of images that should be returned. Only the images with the corresponding owner will be returned. Valid values: amazon|aws-marketplace|self|all|aws id Ex_executableby parameter describes images for which the specified user has explicit launch permissions. The user can be an AWS account ID, self to return images for which the sender of the request has explicit launch permissions, or all to return images with public launch permissions. Valid values: all|self|aws id Ex_filters parameter is used to filter the list of images that should be returned. Only images matchind the filter will be returned. :param ex_image_ids: List of ``NodeImage.id`` :type ex_image_ids: ``list`` of ``str`` :param ex_owner: Owner name :type ex_owner: ``str`` :param ex_executableby: Executable by :type ex_executableby: ``str`` :param ex_filters: Filter by :type ex_filters: ``dict`` :rtype: ``list`` of :class:`NodeImage` """ params = {'Action': 'DescribeImages'} if ex_owner: params.update({'Owner.1': ex_owner}) if ex_executableby: params.update({'ExecutableBy.1': ex_executableby}) if ex_image_ids: for index, image_id in enumerate(ex_image_ids): index += 1 params.update({'ImageId.%s' % (index): image_id}) if ex_filters: params.update(self._build_filters(ex_filters)) images = self._to_images( self.connection.request(self.path, params=params).object ) return images def get_image(self, image_id): """ Get an image based on an image_id :param image_id: Image identifier :type image_id: ``str`` :return: A NodeImage object :rtype: :class:`NodeImage` """ images = self.list_images(ex_image_ids=[image_id]) image = images[0] return image def list_locations(self): locations = [] for index, availability_zone in \ enumerate(self.ex_list_availability_zones()): locations.append(EC2NodeLocation( index, availability_zone.name, self.country, self, availability_zone) ) return locations def list_volumes(self, node=None): params = { 'Action': 'DescribeVolumes', } if node: filters = {'attachment.instance-id': node.id} params.update(self._build_filters(filters)) response = self.connection.request(self.path, params=params).object volumes = [self._to_volume(el) for el in response.findall( fixxpath(xpath='volumeSet/item', namespace=NAMESPACE)) ] return volumes def create_node(self, **kwargs): """ Create a new EC2 node. Reference: http://bit.ly/8ZyPSy [docs.amazonwebservices.com] @inherits: :class:`NodeDriver.create_node` :keyword ex_keyname: The name of the key pair :type ex_keyname: ``str`` :keyword ex_userdata: User data :type ex_userdata: ``str`` :keyword ex_security_groups: A list of names of security groups to assign to the node. :type ex_security_groups: ``list`` :keyword ex_security_group_ids: A list of ids of security groups to assign to the node.[for VPC nodes only] :type ex_security_group_ids: ``list`` :keyword ex_metadata: Key/Value metadata to associate with a node :type ex_metadata: ``dict`` :keyword ex_mincount: Minimum number of instances to launch :type ex_mincount: ``int`` :keyword ex_maxcount: Maximum number of instances to launch :type ex_maxcount: ``int`` :keyword ex_clienttoken: Unique identifier to ensure idempotency :type ex_clienttoken: ``str`` :keyword ex_blockdevicemappings: ``list`` of ``dict`` block device mappings. :type ex_blockdevicemappings: ``list`` of ``dict`` :keyword ex_iamprofile: Name or ARN of IAM profile :type ex_iamprofile: ``str`` :keyword ex_ebs_optimized: EBS-Optimized if True :type ex_ebs_optimized: ``bool`` :keyword ex_subnet: The subnet to launch the instance into. :type ex_subnet: :class:`.EC2Subnet` :keyword ex_placement_group: The name of the placement group to launch the instance into. :type ex_placement_group: ``str`` """ image = kwargs["image"] size = kwargs["size"] params = { 'Action': 'RunInstances', 'ImageId': image.id, 'MinCount': str(kwargs.get('ex_mincount', '1')), 'MaxCount': str(kwargs.get('ex_maxcount', '1')), 'InstanceType': size.id } if 'ex_security_groups' in kwargs and 'ex_securitygroup' in kwargs: raise ValueError('You can only supply ex_security_groups or' ' ex_securitygroup') # ex_securitygroup is here for backward compatibility ex_security_groups = kwargs.get('ex_security_groups', None) ex_securitygroup = kwargs.get('ex_securitygroup', None) security_groups = ex_security_groups or ex_securitygroup if security_groups: if not isinstance(security_groups, (tuple, list)): security_groups = [security_groups] for sig in range(len(security_groups)): params['SecurityGroup.%d' % (sig + 1,)] =\ security_groups[sig] if 'ex_security_group_ids' in kwargs and 'ex_subnet' not in kwargs: raise ValueError('You can only supply ex_security_group_ids' ' combinated with ex_subnet') security_group_ids = kwargs.get('ex_security_group_ids', None) if security_group_ids: if not isinstance(security_group_ids, (tuple, list)): security_group_ids = [security_group_ids] for sig in range(len(security_group_ids)): params['SecurityGroupId.%d' % (sig + 1,)] =\ security_group_ids[sig] if 'location' in kwargs: availability_zone = getattr(kwargs['location'], 'availability_zone', None) if availability_zone: if availability_zone.region_name != self.region_name: raise AttributeError('Invalid availability zone: %s' % (availability_zone.name)) params['Placement.AvailabilityZone'] = availability_zone.name if 'auth' in kwargs and 'ex_keyname' in kwargs: raise AttributeError('Cannot specify auth and ex_keyname together') if 'auth' in kwargs: auth = self._get_and_check_auth(kwargs['auth']) key = self.ex_find_or_import_keypair_by_key_material(auth.pubkey) params['KeyName'] = key['keyName'] if 'ex_keyname' in kwargs: params['KeyName'] = kwargs['ex_keyname'] if 'ex_userdata' in kwargs: params['UserData'] = base64.b64encode(b(kwargs['ex_userdata']))\ .decode('utf-8') if 'ex_clienttoken' in kwargs: params['ClientToken'] = kwargs['ex_clienttoken'] if 'ex_blockdevicemappings' in kwargs: params.update(self._get_block_device_mapping_params( kwargs['ex_blockdevicemappings'])) if 'ex_iamprofile' in kwargs: if not isinstance(kwargs['ex_iamprofile'], basestring): raise AttributeError('ex_iamprofile not string') if kwargs['ex_iamprofile'].startswith('arn:aws:iam:'): params['IamInstanceProfile.Arn'] = kwargs['ex_iamprofile'] else: params['IamInstanceProfile.Name'] = kwargs['ex_iamprofile'] if 'ex_ebs_optimized' in kwargs: params['EbsOptimized'] = kwargs['ex_ebs_optimized'] if 'ex_subnet' in kwargs: params['SubnetId'] = kwargs['ex_subnet'].id if 'ex_placement_group' in kwargs and kwargs['ex_placement_group']: params['Placement.GroupName'] = kwargs['ex_placement_group'] object = self.connection.request(self.path, params=params).object nodes = self._to_nodes(object, 'instancesSet/item') for node in nodes: tags = {'Name': kwargs['name']} if 'ex_metadata' in kwargs: tags.update(kwargs['ex_metadata']) try: self.ex_create_tags(resource=node, tags=tags) except Exception: continue node.name = kwargs['name'] node.extra.update({'tags': tags}) if len(nodes) == 1: return nodes[0] else: return nodes def reboot_node(self, node): params = {'Action': 'RebootInstances'} params.update(self._pathlist('InstanceId', [node.id])) res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def destroy_node(self, node): params = {'Action': 'TerminateInstances'} params.update(self._pathlist('InstanceId', [node.id])) res = self.connection.request(self.path, params=params).object return self._get_terminate_boolean(res) def create_volume(self, size, name, location=None, snapshot=None, ex_volume_type='standard', ex_iops=None): """ Create a new volume. :param size: Size of volume in gigabytes (required) :type size: ``int`` :param name: Name of the volume to be created :type name: ``str`` :param location: Which data center to create a volume in. If empty, undefined behavior will be selected. (optional) :type location: :class:`.NodeLocation` :param snapshot: Snapshot from which to create the new volume. (optional) :type snapshot: :class:`.VolumeSnapshot` :param location: Datacenter in which to create a volume in. :type location: :class:`.ExEC2AvailabilityZone` :param ex_volume_type: Type of volume to create. :type ex_volume_type: ``str`` :param iops: The number of I/O operations per second (IOPS) that the volume supports. Only used if ex_volume_type is io1. :type iops: ``int`` :return: The newly created volume. :rtype: :class:`StorageVolume` """ valid_volume_types = ['standard', 'io1', 'gp2'] params = { 'Action': 'CreateVolume', 'Size': str(size)} if ex_volume_type and ex_volume_type not in valid_volume_types: raise ValueError('Invalid volume type specified: %s' % (ex_volume_type)) if snapshot: params['SnapshotId'] = snapshot.id if location is not None: params['AvailabilityZone'] = location.availability_zone.name if ex_volume_type: params['VolumeType'] = ex_volume_type if ex_volume_type == 'io1' and ex_iops: params['Iops'] = ex_iops volume = self._to_volume( self.connection.request(self.path, params=params).object, name=name) if self.ex_create_tags(volume, {'Name': name}): volume.extra['tags']['Name'] = name return volume def attach_volume(self, node, volume, device): params = { 'Action': 'AttachVolume', 'VolumeId': volume.id, 'InstanceId': node.id, 'Device': device} self.connection.request(self.path, params=params) return True def detach_volume(self, volume): params = { 'Action': 'DetachVolume', 'VolumeId': volume.id} self.connection.request(self.path, params=params) return True def destroy_volume(self, volume): params = { 'Action': 'DeleteVolume', 'VolumeId': volume.id} response = self.connection.request(self.path, params=params).object return self._get_boolean(response) def create_volume_snapshot(self, volume, name=None): """ Create snapshot from volume :param volume: Instance of ``StorageVolume`` :type volume: ``StorageVolume`` :param name: Name of snapshot :type name: ``str`` :rtype: :class:`VolumeSnapshot` """ params = { 'Action': 'CreateSnapshot', 'VolumeId': volume.id, } if name: params.update({ 'Description': name, }) response = self.connection.request(self.path, params=params).object snapshot = self._to_snapshot(response, name) if name and self.ex_create_tags(snapshot, {'Name': name}): snapshot.extra['tags']['Name'] = name return snapshot def list_volume_snapshots(self, volume): return [snapshot for snapshot in self.list_snapshots(owner='self') if snapshot.extra["volume_id"] == volume.id] def list_snapshots(self, snapshot=None, owner=None): """ Describe all snapshots. :param snapshot: If provided, only return snapshot information for the provided snapshot. :param owner: Owner for snapshot: self|amazon|ID :type owner: ``str`` :rtype: ``list`` of :class:`VolumeSnapshot` """ params = { 'Action': 'DescribeSnapshots', } if snapshot: params.update({ 'SnapshotId.1': snapshot.id, }) if owner: params.update({ 'Owner.1': owner, }) response = self.connection.request(self.path, params=params).object snapshots = self._to_snapshots(response) return snapshots def destroy_volume_snapshot(self, snapshot): params = { 'Action': 'DeleteSnapshot', 'SnapshotId': snapshot.id } response = self.connection.request(self.path, params=params).object return self._get_boolean(response) # Key pair management methods def list_key_pairs(self): params = { 'Action': 'DescribeKeyPairs' } response = self.connection.request(self.path, params=params) elems = findall(element=response.object, xpath='keySet/item', namespace=NAMESPACE) key_pairs = self._to_key_pairs(elems=elems) return key_pairs def get_key_pair(self, name): params = { 'Action': 'DescribeKeyPairs', 'KeyName': name } response = self.connection.request(self.path, params=params) elems = findall(element=response.object, xpath='keySet/item', namespace=NAMESPACE) key_pair = self._to_key_pairs(elems=elems)[0] return key_pair def create_key_pair(self, name): params = { 'Action': 'CreateKeyPair', 'KeyName': name } response = self.connection.request(self.path, params=params) elem = response.object key_pair = self._to_key_pair(elem=elem) return key_pair def import_key_pair_from_string(self, name, key_material): base64key = ensure_string(base64.b64encode(b(key_material))) params = { 'Action': 'ImportKeyPair', 'KeyName': name, 'PublicKeyMaterial': base64key } response = self.connection.request(self.path, params=params) elem = response.object key_pair = self._to_key_pair(elem=elem) return key_pair def delete_key_pair(self, key_pair): params = { 'Action': 'DeleteKeyPair', 'KeyName': key_pair.name } res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def copy_image(self, image, source_region, name=None, description=None): """ Copy an Amazon Machine Image from the specified source region to the current region. @inherits: :class:`NodeDriver.copy_image` :param source_region: The region where the image resides :type source_region: ``str`` :param image: Instance of class NodeImage :type image: :class:`NodeImage` :param name: The name of the new image :type name: ``str`` :param description: The description of the new image :type description: ``str`` :return: Instance of class ``NodeImage`` :rtype: :class:`NodeImage` """ params = {'Action': 'CopyImage', 'SourceRegion': source_region, 'SourceImageId': image.id} if name is not None: params['Name'] = name if description is not None: params['Description'] = description image = self._to_image( self.connection.request(self.path, params=params).object) return image def create_image(self, node, name, description=None, reboot=False, block_device_mapping=None): """ Create an Amazon Machine Image based off of an EBS-backed instance. @inherits: :class:`NodeDriver.create_image` :param node: Instance of ``Node`` :type node: :class: `Node` :param name: The name for the new image :type name: ``str`` :param block_device_mapping: A dictionary of the disk layout An example of this dict is included below. :type block_device_mapping: ``list`` of ``dict`` :param reboot: Whether or not to shutdown the instance before creation. Amazon calls this NoReboot and sets it to false by default to ensure a clean image. :type reboot: ``bool`` :param description: An optional description for the new image :type description: ``str`` An example block device mapping dictionary is included: mapping = [{'VirtualName': None, 'Ebs': {'VolumeSize': 10, 'VolumeType': 'standard', 'DeleteOnTermination': 'true'}, 'DeviceName': '/dev/sda1'}] :return: Instance of class ``NodeImage`` :rtype: :class:`NodeImage` """ params = {'Action': 'CreateImage', 'InstanceId': node.id, 'Name': name, 'NoReboot': not reboot} if description is not None: params['Description'] = description if block_device_mapping is not None: params.update(self._get_block_device_mapping_params( block_device_mapping)) image = self._to_image( self.connection.request(self.path, params=params).object) return image def delete_image(self, image): """ Deletes an image at Amazon given a NodeImage object @inherits: :class:`NodeDriver.delete_image` :param image: Instance of ``NodeImage`` :type image: :class: `NodeImage` :rtype: ``bool`` """ params = {'Action': 'DeregisterImage', 'ImageId': image.id} response = self.connection.request(self.path, params=params).object return self._get_boolean(response) def ex_create_placement_group(self, name): """ Creates new Placement Group :param name: Name for new placement Group :type name: ``str`` :rtype: ``bool`` """ params = {'Action': 'CreatePlacementGroup', 'Strategy': 'cluster', 'GroupName': name} response = self.connection.request(self.path, params=params).object return self._get_boolean(response) def ex_delete_placement_group(self, name): """ Deletes Placement Group :param name: Placement Group name :type name: ``str`` :rtype: ``bool`` """ params = {'Action': 'DeletePlacementGroup', 'GroupName': name} response = self.connection.request(self.path, params=params).object return self._get_boolean(response) def ex_list_placement_groups(self, names=None): """ List Placement Groups :param names: Placement Group names :type names: ``list`` of ``str`` :rtype: ``list`` of :class:`.EC2PlacementGroup` """ names = names or [] params = {'Action': 'DescribePlacementGroups'} for index, name in enumerate(names): params['GroupName.%s' % index + 1] = name response = self.connection.request(self.path, params=params).object return self._to_placement_groups(response) def ex_register_image(self, name, description=None, architecture=None, image_location=None, root_device_name=None, block_device_mapping=None, kernel_id=None, ramdisk_id=None, virtualization_type=None): """ Registers an Amazon Machine Image based off of an EBS-backed instance. Can also be used to create images from snapshots. More information can be found at http://goo.gl/hqZq0a. :param name: The name for the AMI being registered :type name: ``str`` :param description: The description of the AMI (optional) :type description: ``str`` :param architecture: The architecture of the AMI (i386/x86_64) (optional) :type architecture: ``str`` :param image_location: The location of the AMI within Amazon S3 Required if registering an instance store-backed AMI :type image_location: ``str`` :param root_device_name: The device name for the root device Required if registering an EBS-backed AMI :type root_device_name: ``str`` :param block_device_mapping: A dictionary of the disk layout (optional) :type block_device_mapping: ``dict`` :param kernel_id: Kernel id for AMI (optional) :type kernel_id: ``str`` :param ramdisk_id: RAM disk for AMI (optional) :type ramdisk_id: ``str`` :param virtualization_type: The type of virtualization for the AMI you are registering, paravirt or hvm (optional) :type virtualization_type: ``str`` :rtype: :class:`NodeImage` """ params = {'Action': 'RegisterImage', 'Name': name} if description is not None: params['Description'] = description if architecture is not None: params['Architecture'] = architecture if image_location is not None: params['ImageLocation'] = image_location if root_device_name is not None: params['RootDeviceName'] = root_device_name if block_device_mapping is not None: params.update(self._get_block_device_mapping_params( block_device_mapping)) if kernel_id is not None: params['KernelId'] = kernel_id if ramdisk_id is not None: params['RamDiskId'] = ramdisk_id if virtualization_type is not None: params['VirtualizationType'] = virtualization_type image = self._to_image( self.connection.request(self.path, params=params).object ) return image def ex_list_networks(self, network_ids=None, filters=None): """ Return a list of :class:`EC2Network` objects for the current region. :param network_ids: Return only networks matching the provided network IDs. If not specified, a list of all the networks in the corresponding region is returned. :type network_ids: ``list`` :param filters: The filters so that the response includes information for only certain networks. :type filters: ``dict`` :rtype: ``list`` of :class:`EC2Network` """ params = {'Action': 'DescribeVpcs'} if network_ids: params.update(self._pathlist('VpcId', network_ids)) if filters: params.update(self._build_filters(filters)) return self._to_networks( self.connection.request(self.path, params=params).object ) def ex_create_network(self, cidr_block, name=None, instance_tenancy='default'): """ Create a network/VPC :param cidr_block: The CIDR block assigned to the network :type cidr_block: ``str`` :param name: An optional name for the network :type name: ``str`` :param instance_tenancy: The allowed tenancy of instances launched into the VPC. Valid values: default/dedicated :type instance_tenancy: ``str`` :return: Dictionary of network properties :rtype: ``dict`` """ params = {'Action': 'CreateVpc', 'CidrBlock': cidr_block, 'InstanceTenancy': instance_tenancy} response = self.connection.request(self.path, params=params).object element = response.findall(fixxpath(xpath='vpc', namespace=NAMESPACE))[0] network = self._to_network(element, name) if name and self.ex_create_tags(network, {'Name': name}): network.extra['tags']['Name'] = name return network def ex_delete_network(self, vpc): """ Deletes a network/VPC. :param vpc: VPC to delete. :type vpc: :class:`.EC2Network` :rtype: ``bool`` """ params = {'Action': 'DeleteVpc', 'VpcId': vpc.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_list_subnets(self, subnet_ids=None, filters=None): """ Return a list of :class:`EC2NetworkSubnet` objects for the current region. :param subnet_ids: Return only subnets matching the provided subnet IDs. If not specified, a list of all the subnets in the corresponding region is returned. :type subnet_ids: ``list`` :param filters: The filters so that the response includes information for only certain subnets. :type filters: ``dict`` :rtype: ``list`` of :class:`EC2NetworkSubnet` """ params = {'Action': 'DescribeSubnets'} if subnet_ids: params.update(self._pathlist('SubnetId', subnet_ids)) if filters: params.update(self._build_filters(filters)) return self._to_subnets( self.connection.request(self.path, params=params).object ) def ex_create_subnet(self, vpc_id, cidr_block, availability_zone, name=None): """ Create a network subnet within a VPC :param vpc_id: The ID of the VPC that the subnet should be associated with :type vpc_id: ``str`` :param cidr_block: The CIDR block assigned to the subnet :type cidr_block: ``str`` :param availability_zone: The availability zone where the subnet should reside :type availability_zone: ``str`` :param name: An optional name for the network :type name: ``str`` :rtype: :class: `EC2NetworkSubnet` """ params = {'Action': 'CreateSubnet', 'VpcId': vpc_id, 'CidrBlock': cidr_block, 'AvailabilityZone': availability_zone} response = self.connection.request(self.path, params=params).object element = response.findall(fixxpath(xpath='subnet', namespace=NAMESPACE))[0] subnet = self._to_subnet(element, name) if name and self.ex_create_tags(subnet, {'Name': name}): subnet.extra['tags']['Name'] = name return subnet def ex_delete_subnet(self, subnet): """ Deletes a VPC subnet. :param subnet: The subnet to delete :type subnet: :class:`.EC2NetworkSubnet` :rtype: ``bool`` """ params = {'Action': 'DeleteSubnet', 'SubnetId': subnet.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_list_security_groups(self): """ List existing Security Groups. @note: This is a non-standard extension API, and only works for EC2. :rtype: ``list`` of ``str`` """ params = {'Action': 'DescribeSecurityGroups'} response = self.connection.request(self.path, params=params).object groups = [] for group in findall(element=response, xpath='securityGroupInfo/item', namespace=NAMESPACE): name = findtext(element=group, xpath='groupName', namespace=NAMESPACE) groups.append(name) return groups def ex_get_security_groups(self, group_ids=None, group_names=None, filters=None): """ Return a list of :class:`EC2SecurityGroup` objects for the current region. :param group_ids: Return only groups matching the provided group IDs. :type group_ids: ``list`` :param group_names: Return only groups matching the provided group names. :type group_ids: ``list`` :param filters: The filters so that the response includes information for only specific security groups. :type filters: ``dict`` :rtype: ``list`` of :class:`EC2SecurityGroup` """ params = {'Action': 'DescribeSecurityGroups'} if group_ids: params.update(self._pathlist('GroupId', group_ids)) if group_names: for name_idx, group_name in enumerate(group_names): name_idx += 1 # We want 1-based indexes name_key = 'GroupName.%s' % (name_idx) params[name_key] = group_name if filters: params.update(self._build_filters(filters)) response = self.connection.request(self.path, params=params) return self._to_security_groups(response.object) def ex_create_security_group(self, name, description, vpc_id=None): """ Creates a new Security Group in EC2-Classic or a targeted VPC. :param name: The name of the security group to Create. This must be unique. :type name: ``str`` :param description: Human readable description of a Security Group. :type description: ``str`` :param vpc_id: Optional identifier for VPC networks :type vpc_id: ``str`` :rtype: ``dict`` """ params = {'Action': 'CreateSecurityGroup', 'GroupName': name, 'GroupDescription': description} if vpc_id is not None: params['VpcId'] = vpc_id response = self.connection.request(self.path, params=params).object group_id = findattr(element=response, xpath='groupId', namespace=NAMESPACE) return { 'group_id': group_id } def ex_delete_security_group_by_id(self, group_id): """ Deletes a new Security Group using the group id. :param group_id: The ID of the security group :type group_id: ``str`` :rtype: ``bool`` """ params = {'Action': 'DeleteSecurityGroup', 'GroupId': group_id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_delete_security_group_by_name(self, group_name): """ Deletes a new Security Group using the group name. :param group_name: The name of the security group :type group_name: ``str`` :rtype: ``bool`` """ params = {'Action': 'DeleteSecurityGroup', 'GroupName': group_name} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_delete_security_group(self, name): """ Wrapper method which calls ex_delete_security_group_by_name. :param name: The name of the security group :type name: ``str`` :rtype: ``bool`` """ return self.ex_delete_security_group_by_name(name) def ex_authorize_security_group(self, name, from_port, to_port, cidr_ip, protocol='tcp'): """ Edit a Security Group to allow specific traffic. @note: This is a non-standard extension API, and only works for EC2. :param name: The name of the security group to edit :type name: ``str`` :param from_port: The beginning of the port range to open :type from_port: ``str`` :param to_port: The end of the port range to open :type to_port: ``str`` :param cidr_ip: The ip to allow traffic for. :type cidr_ip: ``str`` :param protocol: tcp/udp/icmp :type protocol: ``str`` :rtype: ``bool`` """ params = {'Action': 'AuthorizeSecurityGroupIngress', 'GroupName': name, 'IpProtocol': protocol, 'FromPort': str(from_port), 'ToPort': str(to_port), 'CidrIp': cidr_ip} try: res = self.connection.request( self.path, params=params.copy()).object return self._get_boolean(res) except Exception: e = sys.exc_info()[1] if e.args[0].find('InvalidPermission.Duplicate') == -1: raise e def ex_authorize_security_group_ingress(self, id, from_port, to_port, cidr_ips=None, group_pairs=None, protocol='tcp'): """ Edit a Security Group to allow specific ingress traffic using CIDR blocks or either a group ID, group name or user ID (account). :param id: The id of the security group to edit :type id: ``str`` :param from_port: The beginning of the port range to open :type from_port: ``int`` :param to_port: The end of the port range to open :type to_port: ``int`` :param cidr_ips: The list of ip ranges to allow traffic for. :type cidr_ips: ``list`` :param group_pairs: Source user/group pairs to allow traffic for. More info can be found at http://goo.gl/stBHJF EC2 Classic Example: To allow access from any system associated with the default group on account 1234567890 [{'group_name': 'default', 'user_id': '1234567890'}] VPC Example: Allow access from any system associated with security group sg-47ad482e on your own account [{'group_id': ' sg-47ad482e'}] :type group_pairs: ``list`` of ``dict`` :param protocol: tcp/udp/icmp :type protocol: ``str`` :rtype: ``bool`` """ params = self._get_common_security_group_params(id, protocol, from_port, to_port, cidr_ips, group_pairs) params["Action"] = 'AuthorizeSecurityGroupIngress' res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_authorize_security_group_egress(self, id, from_port, to_port, cidr_ips, group_pairs=None, protocol='tcp'): """ Edit a Security Group to allow specific egress traffic using CIDR blocks or either a group ID, group name or user ID (account). This call is not supported for EC2 classic and only works for VPC groups. :param id: The id of the security group to edit :type id: ``str`` :param from_port: The beginning of the port range to open :type from_port: ``int`` :param to_port: The end of the port range to open :type to_port: ``int`` :param cidr_ips: The list of ip ranges to allow traffic for. :type cidr_ips: ``list`` :param group_pairs: Source user/group pairs to allow traffic for. More info can be found at http://goo.gl/stBHJF EC2 Classic Example: To allow access from any system associated with the default group on account 1234567890 [{'group_name': 'default', 'user_id': '1234567890'}] VPC Example: Allow access from any system associated with security group sg-47ad482e on your own account [{'group_id': ' sg-47ad482e'}] :type group_pairs: ``list`` of ``dict`` :param protocol: tcp/udp/icmp :type protocol: ``str`` :rtype: ``bool`` """ params = self._get_common_security_group_params(id, protocol, from_port, to_port, cidr_ips, group_pairs) params["Action"] = 'AuthorizeSecurityGroupEgress' res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_revoke_security_group_ingress(self, id, from_port, to_port, cidr_ips=None, group_pairs=None, protocol='tcp'): """ Edit a Security Group to revoke specific ingress traffic using CIDR blocks or either a group ID, group name or user ID (account). :param id: The id of the security group to edit :type id: ``str`` :param from_port: The beginning of the port range to open :type from_port: ``int`` :param to_port: The end of the port range to open :type to_port: ``int`` :param cidr_ips: The list of ip ranges to allow traffic for. :type cidr_ips: ``list`` :param group_pairs: Source user/group pairs to allow traffic for. More info can be found at http://goo.gl/stBHJF EC2 Classic Example: To allow access from any system associated with the default group on account 1234567890 [{'group_name': 'default', 'user_id': '1234567890'}] VPC Example: Allow access from any system associated with security group sg-47ad482e on your own account [{'group_id': ' sg-47ad482e'}] :type group_pairs: ``list`` of ``dict`` :param protocol: tcp/udp/icmp :type protocol: ``str`` :rtype: ``bool`` """ params = self._get_common_security_group_params(id, protocol, from_port, to_port, cidr_ips, group_pairs) params["Action"] = 'RevokeSecurityGroupIngress' res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_revoke_security_group_egress(self, id, from_port, to_port, cidr_ips=None, group_pairs=None, protocol='tcp'): """ Edit a Security Group to revoke specific egress traffic using CIDR blocks or either a group ID, group name or user ID (account). This call is not supported for EC2 classic and only works for VPC groups. :param id: The id of the security group to edit :type id: ``str`` :param from_port: The beginning of the port range to open :type from_port: ``int`` :param to_port: The end of the port range to open :type to_port: ``int`` :param cidr_ips: The list of ip ranges to allow traffic for. :type cidr_ips: ``list`` :param group_pairs: Source user/group pairs to allow traffic for. More info can be found at http://goo.gl/stBHJF EC2 Classic Example: To allow access from any system associated with the default group on account 1234567890 [{'group_name': 'default', 'user_id': '1234567890'}] VPC Example: Allow access from any system associated with security group sg-47ad482e on your own account [{'group_id': ' sg-47ad482e'}] :type group_pairs: ``list`` of ``dict`` :param protocol: tcp/udp/icmp :type protocol: ``str`` :rtype: ``bool`` """ params = self._get_common_security_group_params(id, protocol, from_port, to_port, cidr_ips, group_pairs) params['Action'] = 'RevokeSecurityGroupEgress' res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_authorize_security_group_permissive(self, name): """ Edit a Security Group to allow all traffic. @note: This is a non-standard extension API, and only works for EC2. :param name: The name of the security group to edit :type name: ``str`` :rtype: ``list`` of ``str`` """ results = [] params = {'Action': 'AuthorizeSecurityGroupIngress', 'GroupName': name, 'IpProtocol': 'tcp', 'FromPort': '0', 'ToPort': '65535', 'CidrIp': '0.0.0.0/0'} try: results.append( self.connection.request(self.path, params=params.copy()).object ) except Exception: e = sys.exc_info()[1] if e.args[0].find("InvalidPermission.Duplicate") == -1: raise e params['IpProtocol'] = 'udp' try: results.append( self.connection.request(self.path, params=params.copy()).object ) except Exception: e = sys.exc_info()[1] if e.args[0].find("InvalidPermission.Duplicate") == -1: raise e params.update({'IpProtocol': 'icmp', 'FromPort': '-1', 'ToPort': '-1'}) try: results.append( self.connection.request(self.path, params=params.copy()).object ) except Exception: e = sys.exc_info()[1] if e.args[0].find("InvalidPermission.Duplicate") == -1: raise e return results def ex_list_availability_zones(self, only_available=True): """ Return a list of :class:`ExEC2AvailabilityZone` objects for the current region. Note: This is an extension method and is only available for EC2 driver. :keyword only_available: If true, return only availability zones with state 'available' :type only_available: ``str`` :rtype: ``list`` of :class:`ExEC2AvailabilityZone` """ params = {'Action': 'DescribeAvailabilityZones'} filters = {'region-name': self.region_name} if only_available: filters['state'] = 'available' params.update(self._build_filters(filters)) result = self.connection.request(self.path, params=params.copy()).object availability_zones = [] for element in findall(element=result, xpath='availabilityZoneInfo/item', namespace=NAMESPACE): name = findtext(element=element, xpath='zoneName', namespace=NAMESPACE) zone_state = findtext(element=element, xpath='zoneState', namespace=NAMESPACE) region_name = findtext(element=element, xpath='regionName', namespace=NAMESPACE) availability_zone = ExEC2AvailabilityZone( name=name, zone_state=zone_state, region_name=region_name ) availability_zones.append(availability_zone) return availability_zones def ex_describe_tags(self, resource): """ Return a dictionary of tags for a resource (e.g. Node or StorageVolume). :param resource: resource which should be used :type resource: any resource class, such as :class:`Node,` :class:`StorageVolume,` or :class:NodeImage` :return: dict Node tags :rtype: ``dict`` """ params = {'Action': 'DescribeTags'} filters = { 'resource-id': resource.id } params.update(self._build_filters(filters)) result = self.connection.request(self.path, params=params).object return self._get_resource_tags(result) def ex_create_tags(self, resource, tags): """ Create tags for a resource (Node or StorageVolume). :param resource: Resource to be tagged :type resource: :class:`Node` or :class:`StorageVolume` :param tags: A dictionary or other mapping of strings to strings, associating tag names with tag values. :type tags: ``dict`` :rtype: ``bool`` """ if not tags: return params = {'Action': 'CreateTags', 'ResourceId.0': resource.id} for i, key in enumerate(tags): params['Tag.%d.Key' % i] = key params['Tag.%d.Value' % i] = tags[key] res = self.connection.request(self.path, params=params.copy()).object return self._get_boolean(res) def ex_delete_tags(self, resource, tags): """ Delete tags from a resource. :param resource: Resource to be tagged :type resource: :class:`Node` or :class:`StorageVolume` :param tags: A dictionary or other mapping of strings to strings, specifying the tag names and tag values to be deleted. :type tags: ``dict`` :rtype: ``bool`` """ if not tags: return params = {'Action': 'DeleteTags', 'ResourceId.0': resource.id} for i, key in enumerate(tags): params['Tag.%d.Key' % i] = key params['Tag.%d.Value' % i] = tags[key] res = self.connection.request(self.path, params=params.copy()).object return self._get_boolean(res) def ex_get_metadata_for_node(self, node): """ Return the metadata associated with the node. :param node: Node instance :type node: :class:`Node` :return: A dictionary or other mapping of strings to strings, associating tag names with tag values. :rtype tags: ``dict`` """ return node.extra['tags'] def ex_allocate_address(self, domain='standard'): """ Allocate a new Elastic IP address for EC2 classic or VPC :param domain: The domain to allocate the new address in (standard/vpc) :type domain: ``str`` :return: Instance of ElasticIP :rtype: :class:`ElasticIP` """ params = {'Action': 'AllocateAddress'} if domain == 'vpc': params['Domain'] = domain response = self.connection.request(self.path, params=params).object return self._to_address(response, only_associated=False) def ex_release_address(self, elastic_ip, domain=None): """ Release an Elastic IP address using the IP (EC2-Classic) or using the allocation ID (VPC) :param elastic_ip: Elastic IP instance :type elastic_ip: :class:`ElasticIP` :param domain: The domain where the IP resides (vpc only) :type domain: ``str`` :return: True on success, False otherwise. :rtype: ``bool`` """ params = {'Action': 'ReleaseAddress'} if domain is not None and domain != 'vpc': raise AttributeError('Domain can only be set to vpc') if domain is None: params['PublicIp'] = elastic_ip.ip else: params['AllocationId'] = elastic_ip.extra['allocation_id'] response = self.connection.request(self.path, params=params).object return self._get_boolean(response) def ex_describe_all_addresses(self, only_associated=False): """ Return all the Elastic IP addresses for this account optionally, return only addresses associated with nodes :param only_associated: If true, return only those addresses that are associated with an instance. :type only_associated: ``bool`` :return: List of ElasticIP instances. :rtype: ``list`` of :class:`ElasticIP` """ params = {'Action': 'DescribeAddresses'} response = self.connection.request(self.path, params=params).object # We will send our only_associated boolean over to # shape how the return data is sent back return self._to_addresses(response, only_associated) def ex_associate_address_with_node(self, node, elastic_ip, domain=None): """ Associate an Elastic IP address with a particular node. :param node: Node instance :type node: :class:`Node` :param elastic_ip: Elastic IP instance :type elastic_ip: :class:`ElasticIP` :param domain: The domain where the IP resides (vpc only) :type domain: ``str`` :return: A string representation of the association ID which is required for VPC disassociation. EC2/standard addresses return None :rtype: ``None`` or ``str`` """ params = {'Action': 'AssociateAddress', 'InstanceId': node.id} if domain is not None and domain != 'vpc': raise AttributeError('Domain can only be set to vpc') if domain is None: params.update({'PublicIp': elastic_ip.ip}) else: params.update({'AllocationId': elastic_ip.extra['allocation_id']}) response = self.connection.request(self.path, params=params).object association_id = findtext(element=response, xpath='associationId', namespace=NAMESPACE) return association_id def ex_associate_addresses(self, node, elastic_ip, domain=None): """ Note: This method has been deprecated in favor of the ex_associate_address_with_node method. """ return self.ex_associate_address_with_node(node=node, elastic_ip=elastic_ip, domain=domain) def ex_disassociate_address(self, elastic_ip, domain=None): """ Disassociate an Elastic IP address using the IP (EC2-Classic) or the association ID (VPC) :param elastic_ip: ElasticIP instance :type elastic_ip: :class:`ElasticIP` :param domain: The domain where the IP resides (vpc only) :type domain: ``str`` :return: True on success, False otherwise. :rtype: ``bool`` """ params = {'Action': 'DisassociateAddress'} if domain is not None and domain != 'vpc': raise AttributeError('Domain can only be set to vpc') if domain is None: params['PublicIp'] = elastic_ip.ip else: params['AssociationId'] = elastic_ip.extra['association_id'] res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_describe_addresses(self, nodes): """ Return Elastic IP addresses for all the nodes in the provided list. :param nodes: List of :class:`Node` instances :type nodes: ``list`` of :class:`Node` :return: Dictionary where a key is a node ID and the value is a list with the Elastic IP addresses associated with this node. :rtype: ``dict`` """ if not nodes: return {} params = {'Action': 'DescribeAddresses'} if len(nodes) == 1: self._add_instance_filter(params, nodes[0]) result = self.connection.request(self.path, params=params).object node_instance_ids = [node.id for node in nodes] nodes_elastic_ip_mappings = {} # We will set only_associated to True so that we only get back # IPs which are associated with instances only_associated = True for node_id in node_instance_ids: nodes_elastic_ip_mappings.setdefault(node_id, []) for addr in self._to_addresses(result, only_associated): instance_id = addr.instance_id if node_id == instance_id: nodes_elastic_ip_mappings[instance_id].append( addr.ip) return nodes_elastic_ip_mappings def ex_describe_addresses_for_node(self, node): """ Return a list of Elastic IP addresses associated with this node. :param node: Node instance :type node: :class:`Node` :return: list Elastic IP addresses attached to this node. :rtype: ``list`` of ``str`` """ node_elastic_ips = self.ex_describe_addresses([node]) return node_elastic_ips[node.id] # Network interface management methods def ex_list_network_interfaces(self): """ Return all network interfaces :return: List of EC2NetworkInterface instances :rtype: ``list`` of :class `EC2NetworkInterface` """ params = {'Action': 'DescribeNetworkInterfaces'} return self._to_interfaces( self.connection.request(self.path, params=params).object ) def ex_create_network_interface(self, subnet, name=None, description=None, private_ip_address=None): """ Create a network interface within a VPC subnet. :param subnet: EC2NetworkSubnet instance :type subnet: :class:`EC2NetworkSubnet` :param name: Optional name of the interface :type name: ``str`` :param description: Optional description of the network interface :type description: ``str`` :param private_ip_address: Optional address to assign as the primary private IP address of the interface. If one is not provided then Amazon will automatically auto-assign an available IP. EC2 allows assignment of multiple IPs, but this will be the primary. :type private_ip_address: ``str`` :return: EC2NetworkInterface instance :rtype: :class `EC2NetworkInterface` """ params = {'Action': 'CreateNetworkInterface', 'SubnetId': subnet.id} if description: params['Description'] = description if private_ip_address: params['PrivateIpAddress'] = private_ip_address response = self.connection.request(self.path, params=params).object element = response.findall(fixxpath(xpath='networkInterface', namespace=NAMESPACE))[0] interface = self._to_interface(element, name) if name and self.ex_create_tags(interface, {'Name': name}): interface.extra['tags']['Name'] = name return interface def ex_delete_network_interface(self, network_interface): """ Deletes a network interface. :param network_interface: EC2NetworkInterface instance :type network_interface: :class:`EC2NetworkInterface` :rtype: ``bool`` """ params = {'Action': 'DeleteNetworkInterface', 'NetworkInterfaceId': network_interface.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_attach_network_interface_to_node(self, network_interface, node, device_index): """ Attach a network interface to an instance. :param network_interface: EC2NetworkInterface instance :type network_interface: :class:`EC2NetworkInterface` :param node: Node instance :type node: :class:`Node` :param device_index: The interface device index :type device_index: ``int`` :return: String representation of the attachment id. This is required to detach the interface. :rtype: ``str`` """ params = {'Action': 'AttachNetworkInterface', 'NetworkInterfaceId': network_interface.id, 'InstanceId': node.id, 'DeviceIndex': device_index} response = self.connection.request(self.path, params=params).object attachment_id = findattr(element=response, xpath='attachmentId', namespace=NAMESPACE) return attachment_id def ex_detach_network_interface(self, attachment_id, force=False): """ Detach a network interface from an instance. :param attachment_id: The attachment ID associated with the interface :type attachment_id: ``str`` :param force: Forces the detachment. :type force: ``bool`` :return: ``True`` on successful detachment, ``False`` otherwise. :rtype: ``bool`` """ params = {'Action': 'DetachNetworkInterface', 'AttachmentId': attachment_id} if force: params['Force'] = True res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_modify_instance_attribute(self, node, attributes): """ Modify node attributes. A list of valid attributes can be found at http://goo.gl/gxcj8 :param node: Node instance :type node: :class:`Node` :param attributes: Dictionary with node attributes :type attributes: ``dict`` :return: True on success, False otherwise. :rtype: ``bool`` """ attributes = attributes or {} attributes.update({'InstanceId': node.id}) params = {'Action': 'ModifyInstanceAttribute'} params.update(attributes) res = self.connection.request(self.path, params=params.copy()).object return self._get_boolean(res) def ex_modify_image_attribute(self, image, attributes): """ Modify image attributes. :param image: NodeImage instance :type image: :class:`NodeImage` :param attributes: Dictionary with node attributes :type attributes: ``dict`` :return: True on success, False otherwise. :rtype: ``bool`` """ attributes = attributes or {} attributes.update({'ImageId': image.id}) params = {'Action': 'ModifyImageAttribute'} params.update(attributes) res = self.connection.request(self.path, params=params.copy()).object return self._get_boolean(res) def ex_change_node_size(self, node, new_size): """ Change the node size. Note: Node must be turned of before changing the size. :param node: Node instance :type node: :class:`Node` :param new_size: NodeSize intance :type new_size: :class:`NodeSize` :return: True on success, False otherwise. :rtype: ``bool`` """ if 'instancetype' in node.extra: current_instance_type = node.extra['instancetype'] if current_instance_type == new_size.id: raise ValueError('New instance size is the same as' + 'the current one') attributes = {'InstanceType.Value': new_size.id} return self.ex_modify_instance_attribute(node, attributes) def ex_start_node(self, node): """ Start the node by passing in the node object, does not work with instance store backed instances :param node: Node which should be used :type node: :class:`Node` :rtype: ``bool`` """ params = {'Action': 'StartInstances'} params.update(self._pathlist('InstanceId', [node.id])) res = self.connection.request(self.path, params=params).object return self._get_state_boolean(res) def ex_stop_node(self, node): """ Stop the node by passing in the node object, does not work with instance store backed instances :param node: Node which should be used :type node: :class:`Node` :rtype: ``bool`` """ params = {'Action': 'StopInstances'} params.update(self._pathlist('InstanceId', [node.id])) res = self.connection.request(self.path, params=params).object return self._get_state_boolean(res) def ex_get_console_output(self, node): """ Get console output for the node. :param node: Node which should be used :type node: :class:`Node` :return: Dictionary with the following keys: - instance_id (``str``) - timestamp (``datetime.datetime``) - ts of the last output - output (``str``) - console output :rtype: ``dict`` """ params = { 'Action': 'GetConsoleOutput', 'InstanceId': node.id } response = self.connection.request(self.path, params=params).object timestamp = findattr(element=response, xpath='timestamp', namespace=NAMESPACE) encoded_string = findattr(element=response, xpath='output', namespace=NAMESPACE) timestamp = parse_date(timestamp) if encoded_string: output = base64.b64decode(b(encoded_string)).decode('utf-8') else: # No console output output = None return {'instance_id': node.id, 'timestamp': timestamp, 'output': output} def ex_list_reserved_nodes(self): """ List all reserved instances/nodes which can be purchased from Amazon for one or three year terms. Reservations are made at a region level and reduce the hourly charge for instances. More information can be found at http://goo.gl/ulXCC7. :rtype: ``list`` of :class:`.EC2ReservedNode` """ params = {'Action': 'DescribeReservedInstances'} response = self.connection.request(self.path, params=params).object return self._to_reserved_nodes(response, 'reservedInstancesSet/item') # Account specific methods def ex_get_limits(self): """ Retrieve account resource limits. :rtype: ``dict`` """ attributes = ['max-instances', 'max-elastic-ips', 'vpc-max-elastic-ips'] params = {} params['Action'] = 'DescribeAccountAttributes' for index, attribute in enumerate(attributes): params['AttributeName.%s' % (index)] = attribute response = self.connection.request(self.path, params=params) data = response.object elems = data.findall(fixxpath(xpath='accountAttributeSet/item', namespace=NAMESPACE)) result = {'resource': {}} for elem in elems: name = findtext(element=elem, xpath='attributeName', namespace=NAMESPACE) value = findtext(element=elem, xpath='attributeValueSet/item/attributeValue', namespace=NAMESPACE) result['resource'][name] = int(value) return result # Deprecated extension methods def ex_list_keypairs(self): """ Lists all the keypair names and fingerprints. :rtype: ``list`` of ``dict`` """ warnings.warn('This method has been deprecated in favor of ' 'list_key_pairs method') key_pairs = self.list_key_pairs() result = [] for key_pair in key_pairs: item = { 'keyName': key_pair.name, 'keyFingerprint': key_pair.fingerprint, } result.append(item) return result def ex_describe_all_keypairs(self): """ Return names for all the available key pairs. @note: This is a non-standard extension API, and only works for EC2. :rtype: ``list`` of ``str`` """ names = [key_pair.name for key_pair in self.list_key_pairs()] return names def ex_describe_keypairs(self, name): """ Here for backward compatibility. """ return self.ex_describe_keypair(name=name) def ex_describe_keypair(self, name): """ Describes a keypair by name. @note: This is a non-standard extension API, and only works for EC2. :param name: The name of the keypair to describe. :type name: ``str`` :rtype: ``dict`` """ params = { 'Action': 'DescribeKeyPairs', 'KeyName.1': name } response = self.connection.request(self.path, params=params).object key_name = findattr(element=response, xpath='keySet/item/keyName', namespace=NAMESPACE) fingerprint = findattr(element=response, xpath='keySet/item/keyFingerprint', namespace=NAMESPACE).strip() return { 'keyName': key_name, 'keyFingerprint': fingerprint } def ex_create_keypair(self, name): """ Creates a new keypair @note: This is a non-standard extension API, and only works for EC2. :param name: The name of the keypair to Create. This must be unique, otherwise an InvalidKeyPair.Duplicate exception is raised. :type name: ``str`` :rtype: ``dict`` """ warnings.warn('This method has been deprecated in favor of ' 'create_key_pair method') key_pair = self.create_key_pair(name=name) result = { 'keyMaterial': key_pair.private_key, 'keyFingerprint': key_pair.fingerprint } return result def ex_delete_keypair(self, keypair): """ Delete a key pair by name. @note: This is a non-standard extension API, and only works with EC2. :param keypair: The name of the keypair to delete. :type keypair: ``str`` :rtype: ``bool`` """ warnings.warn('This method has been deprecated in favor of ' 'delete_key_pair method') keypair = KeyPair(name=keypair, public_key=None, fingerprint=None, driver=self) return self.delete_key_pair(keypair) def ex_import_keypair_from_string(self, name, key_material): """ imports a new public key where the public key is passed in as a string @note: This is a non-standard extension API, and only works for EC2. :param name: The name of the public key to import. This must be unique, otherwise an InvalidKeyPair.Duplicate exception is raised. :type name: ``str`` :param key_material: The contents of a public key file. :type key_material: ``str`` :rtype: ``dict`` """ warnings.warn('This method has been deprecated in favor of ' 'import_key_pair_from_string method') key_pair = self.import_key_pair_from_string(name=name, key_material=key_material) result = { 'keyName': key_pair.name, 'keyFingerprint': key_pair.fingerprint } return result def ex_import_keypair(self, name, keyfile): """ imports a new public key where the public key is passed via a filename @note: This is a non-standard extension API, and only works for EC2. :param name: The name of the public key to import. This must be unique, otherwise an InvalidKeyPair.Duplicate exception is raised. :type name: ``str`` :param keyfile: The filename with path of the public key to import. :type keyfile: ``str`` :rtype: ``dict`` """ warnings.warn('This method has been deprecated in favor of ' 'import_key_pair_from_file method') key_pair = self.import_key_pair_from_file(name=name, key_file_path=keyfile) result = { 'keyName': key_pair.name, 'keyFingerprint': key_pair.fingerprint } return result def ex_find_or_import_keypair_by_key_material(self, pubkey): """ Given a public key, look it up in the EC2 KeyPair database. If it exists, return any information we have about it. Otherwise, create it. Keys that are created are named based on their comment and fingerprint. :rtype: ``dict`` """ key_fingerprint = get_pubkey_ssh2_fingerprint(pubkey) key_comment = get_pubkey_comment(pubkey, default='unnamed') key_name = '%s-%s' % (key_comment, key_fingerprint) key_pairs = self.list_key_pairs() key_pairs = [key_pair for key_pair in key_pairs if key_pair.fingerprint == key_fingerprint] if len(key_pairs) >= 1: key_pair = key_pairs[0] result = { 'keyName': key_pair.name, 'keyFingerprint': key_pair.fingerprint } else: result = self.ex_import_keypair_from_string(key_name, pubkey) return result def ex_list_internet_gateways(self, gateway_ids=None, filters=None): """ Describes available Internet gateways and whether or not they are attached to a VPC. These are required for VPC nodes to communicate over the Internet. :param gateway_ids: Return only intenet gateways matching the provided internet gateway IDs. If not specified, a list of all the internet gateways in the corresponding region is returned. :type gateway_ids: ``list`` :param filters: The filters so that the response includes information for only certain gateways. :type filters: ``dict`` :rtype: ``list`` of :class:`.VPCInternetGateway` """ params = {'Action': 'DescribeInternetGateways'} if gateway_ids: params.update(self._pathlist('InternetGatewayId', gateway_ids)) if filters: params.update(self._build_filters(filters)) response = self.connection.request(self.path, params=params).object return self._to_internet_gateways(response, 'internetGatewaySet/item') def ex_create_internet_gateway(self, name=None): """ Delete a VPC Internet gateway :rtype: ``bool`` """ params = {'Action': 'CreateInternetGateway'} resp = self.connection.request(self.path, params=params).object element = resp.findall(fixxpath(xpath='internetGateway', namespace=NAMESPACE)) gateway = self._to_internet_gateway(element[0], name) if name and self.ex_create_tags(gateway, {'Name': name}): gateway.extra['tags']['Name'] = name return gateway def ex_delete_internet_gateway(self, gateway): """ Delete a VPC Internet gateway :param gateway: The gateway to delete :type gateway: :class:`.VPCInternetGateway` :rtype: ``bool`` """ params = {'Action': 'DeleteInternetGateway', 'InternetGatewayId': gateway.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_attach_internet_gateway(self, gateway, network): """ Attach an Internet gateway to a VPC :param gateway: The gateway to attach :type gateway: :class:`.VPCInternetGateway` :param network: The VPC network to attach to :type network: :class:`.EC2Network` :rtype: ``bool`` """ params = {'Action': 'AttachInternetGateway', 'InternetGatewayId': gateway.id, 'VpcId': network.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_detach_internet_gateway(self, gateway, network): """ Detach an Internet gateway from a VPC :param gateway: The gateway to detach :type gateway: :class:`.VPCInternetGateway` :param network: The VPC network to detach from :type network: :class:`.EC2Network` :rtype: ``bool`` """ params = {'Action': 'DetachInternetGateway', 'InternetGatewayId': gateway.id, 'VpcId': network.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_list_route_tables(self, route_table_ids=None, filters=None): """ Describes one or more of a VPC's route tables. These are used to determine where network traffic is directed. :param route_table_ids: Return only route tables matching the provided route table IDs. If not specified, a list of all the route tables in the corresponding region is returned. :type route_table_ids: ``list`` :param filters: The filters so that the response includes information for only certain route tables. :type filters: ``dict`` :rtype: ``list`` of :class:`.EC2RouteTable` """ params = {'Action': 'DescribeRouteTables'} if route_table_ids: params.update(self._pathlist('RouteTableId', route_table_ids)) if filters: params.update(self._build_filters(filters)) response = self.connection.request(self.path, params=params) return self._to_route_tables(response.object) def ex_create_route_table(self, network, name=None): """ Create a route table within a VPC. :param vpc_id: The VPC that the subnet should be created in. :type vpc_id: :class:`.EC2Network` :rtype: :class: `.EC2RouteTable` """ params = {'Action': 'CreateRouteTable', 'VpcId': network.id} response = self.connection.request(self.path, params=params).object element = response.findall(fixxpath(xpath='routeTable', namespace=NAMESPACE))[0] route_table = self._to_route_table(element, name=name) if name and self.ex_create_tags(route_table, {'Name': name}): route_table.extra['tags']['Name'] = name return route_table def ex_delete_route_table(self, route_table): """ Deletes a VPC route table. :param route_table: The route table to delete. :type route_table: :class:`.EC2RouteTable` :rtype: ``bool`` """ params = {'Action': 'DeleteRouteTable', 'RouteTableId': route_table.id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_associate_route_table(self, route_table, subnet): """ Associates a route table with a subnet within a VPC. Note: A route table can be associated with multiple subnets. :param route_table: The route table to associate. :type route_table: :class:`.EC2RouteTable` :param subnet: The subnet to associate with. :type subnet: :class:`.EC2Subnet` :return: Route table association ID. :rtype: ``str`` """ params = {'Action': 'AssociateRouteTable', 'RouteTableId': route_table.id, 'SubnetId': subnet.id} result = self.connection.request(self.path, params=params).object association_id = findtext(element=result, xpath='associationId', namespace=NAMESPACE) return association_id def ex_dissociate_route_table(self, subnet_association): """ Dissociates a subnet from a route table. :param subnet_association: The subnet association object or subnet association ID. :type subnet_association: :class:`.EC2SubnetAssociation` or ``str`` :rtype: ``bool`` """ if isinstance(subnet_association, EC2SubnetAssociation): subnet_association_id = subnet_association.id else: subnet_association_id = subnet_association params = {'Action': 'DisassociateRouteTable', 'AssociationId': subnet_association_id} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_replace_route_table_association(self, subnet_association, route_table): """ Changes the route table associated with a given subnet in a VPC. Note: This method can be used to change which table is the main route table in the VPC (Specify the main route table's association ID and the route table to be the new main route table). :param subnet_association: The subnet association object or subnet association ID. :type subnet_association: :class:`.EC2SubnetAssociation` or ``str`` :param route_table: The new route table to associate. :type route_table: :class:`.EC2RouteTable` :return: New route table association ID. :rtype: ``str`` """ if isinstance(subnet_association, EC2SubnetAssociation): subnet_association_id = subnet_association.id else: subnet_association_id = subnet_association params = {'Action': 'ReplaceRouteTableAssociation', 'AssociationId': subnet_association_id, 'RouteTableId': route_table.id} result = self.connection.request(self.path, params=params).object new_association_id = findtext(element=result, xpath='newAssociationId', namespace=NAMESPACE) return new_association_id def ex_create_route(self, route_table, cidr, internet_gateway=None, node=None, network_interface=None, vpc_peering_connection=None): """ Creates a route entry in the route table. :param route_table: The route table to create the route in. :type route_table: :class:`.EC2RouteTable` :param cidr: The CIDR block used for the destination match. :type cidr: ``str`` :param internet_gateway: The internet gateway to route traffic through. :type internet_gateway: :class:`.VPCInternetGateway` :param node: The NAT instance to route traffic through. :type node: :class:`Node` :param network_interface: The network interface of the node to route traffic through. :type network_interface: :class:`.EC2NetworkInterface` :param vpc_peering_connection: The VPC peering connection. :type vpc_peering_connection: :class:`.VPCPeeringConnection` :rtype: ``bool`` Note: You must specify one of the following: internet_gateway, node, network_interface, vpc_peering_connection. """ params = {'Action': 'CreateRoute', 'RouteTableId': route_table.id, 'DestinationCidrBlock': cidr} if internet_gateway: params['GatewayId'] = internet_gateway.id if node: params['InstanceId'] = node.id if network_interface: params['NetworkInterfaceId'] = network_interface.id if vpc_peering_connection: params['VpcPeeringConnectionId'] = vpc_peering_connection.id res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_delete_route(self, route_table, cidr): """ Deletes a route entry from the route table. :param route_table: The route table to delete the route from. :type route_table: :class:`.EC2RouteTable` :param cidr: The CIDR block used for the destination match. :type cidr: ``str`` :rtype: ``bool`` """ params = {'Action': 'DeleteRoute', 'RouteTableId': route_table.id, 'DestinationCidrBlock': cidr} res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def ex_replace_route(self, route_table, cidr, internet_gateway=None, node=None, network_interface=None, vpc_peering_connection=None): """ Replaces an existing route entry within a route table in a VPC. :param route_table: The route table to replace the route in. :type route_table: :class:`.EC2RouteTable` :param cidr: The CIDR block used for the destination match. :type cidr: ``str`` :param internet_gateway: The new internet gateway to route traffic through. :type internet_gateway: :class:`.VPCInternetGateway` :param node: The new NAT instance to route traffic through. :type node: :class:`Node` :param network_interface: The new network interface of the node to route traffic through. :type network_interface: :class:`.EC2NetworkInterface` :param vpc_peering_connection: The new VPC peering connection. :type vpc_peering_connection: :class:`.VPCPeeringConnection` :rtype: ``bool`` Note: You must specify one of the following: internet_gateway, node, network_interface, vpc_peering_connection. """ params = {'Action': 'ReplaceRoute', 'RouteTableId': route_table.id, 'DestinationCidrBlock': cidr} if internet_gateway: params['GatewayId'] = internet_gateway.id if node: params['InstanceId'] = node.id if network_interface: params['NetworkInterfaceId'] = network_interface.id if vpc_peering_connection: params['VpcPeeringConnectionId'] = vpc_peering_connection.id res = self.connection.request(self.path, params=params).object return self._get_boolean(res) def _to_nodes(self, object, xpath): return [self._to_node(el) for el in object.findall(fixxpath(xpath=xpath, namespace=NAMESPACE))] def _to_node(self, element): try: state = self.NODE_STATE_MAP[findattr(element=element, xpath="instanceState/name", namespace=NAMESPACE) ] except KeyError: state = NodeState.UNKNOWN instance_id = findtext(element=element, xpath='instanceId', namespace=NAMESPACE) public_ip = findtext(element=element, xpath='ipAddress', namespace=NAMESPACE) public_ips = [public_ip] if public_ip else [] private_ip = findtext(element=element, xpath='privateIpAddress', namespace=NAMESPACE) private_ips = [private_ip] if private_ip else [] product_codes = [] for p in findall(element=element, xpath="productCodesSet/item/productCode", namespace=NAMESPACE): product_codes.append(p) # Get our tags tags = self._get_resource_tags(element) name = tags.get('Name', instance_id) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['node']) # Add additional properties to our extra dictionary extra['block_device_mapping'] = self._to_device_mappings(element) extra['groups'] = self._get_security_groups(element) extra['network_interfaces'] = self._to_interfaces(element) extra['product_codes'] = product_codes extra['tags'] = tags return Node(id=instance_id, name=name, state=state, public_ips=public_ips, private_ips=private_ips, driver=self.connection.driver, extra=extra) def _to_images(self, object): return [self._to_image(el) for el in object.findall( fixxpath(xpath='imagesSet/item', namespace=NAMESPACE)) ] def _to_image(self, element): id = findtext(element=element, xpath='imageId', namespace=NAMESPACE) name = findtext(element=element, xpath='name', namespace=NAMESPACE) # Build block device mapping block_device_mapping = self._to_device_mappings(element) # Get our tags tags = self._get_resource_tags(element) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['image']) # Add our tags and block device mapping extra['tags'] = tags extra['block_device_mapping'] = block_device_mapping return NodeImage(id=id, name=name, driver=self, extra=extra) def _to_volume(self, element, name=None): """ Parse the XML element and return a StorageVolume object. :param name: An optional name for the volume. If not provided then either tag with a key "Name" or volume ID will be used (which ever is available first in that order). :type name: ``str`` :rtype: :class:`StorageVolume` """ volId = findtext(element=element, xpath='volumeId', namespace=NAMESPACE) size = findtext(element=element, xpath='size', namespace=NAMESPACE) # Get our tags tags = self._get_resource_tags(element) # If name was not passed into the method then # fall back then use the volume id name = name if name else tags.get('Name', volId) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['volume']) extra['tags'] = tags return StorageVolume(id=volId, name=name, size=int(size), driver=self, extra=extra) def _to_snapshots(self, response): return [self._to_snapshot(el) for el in response.findall( fixxpath(xpath='snapshotSet/item', namespace=NAMESPACE)) ] def _to_snapshot(self, element, name=None): snapId = findtext(element=element, xpath='snapshotId', namespace=NAMESPACE) size = findtext(element=element, xpath='volumeSize', namespace=NAMESPACE) created = parse_date(findtext(element=element, xpath='startTime', namespace=NAMESPACE)) # Get our tags tags = self._get_resource_tags(element) # If name was not passed into the method then # fall back then use the snapshot id name = name if name else tags.get('Name', snapId) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['snapshot']) # Add tags and name to the extra dict extra['tags'] = tags extra['name'] = name return VolumeSnapshot(snapId, size=int(size), driver=self, extra=extra, created=created) def _to_key_pairs(self, elems): key_pairs = [self._to_key_pair(elem=elem) for elem in elems] return key_pairs def _to_key_pair(self, elem): name = findtext(element=elem, xpath='keyName', namespace=NAMESPACE) fingerprint = findtext(element=elem, xpath='keyFingerprint', namespace=NAMESPACE).strip() private_key = findtext(element=elem, xpath='keyMaterial', namespace=NAMESPACE) key_pair = KeyPair(name=name, public_key=None, fingerprint=fingerprint, private_key=private_key, driver=self) return key_pair def _to_security_groups(self, response): return [self._to_security_group(el) for el in response.findall( fixxpath(xpath='securityGroupInfo/item', namespace=NAMESPACE)) ] def _to_security_group(self, element): # security group id sg_id = findtext(element=element, xpath='groupId', namespace=NAMESPACE) # security group name name = findtext(element=element, xpath='groupName', namespace=NAMESPACE) # Get our tags tags = self._get_resource_tags(element) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['security_group']) # Add tags to the extra dict extra['tags'] = tags # Get ingress rules ingress_rules = self._to_security_group_rules( element, 'ipPermissions/item' ) # Get egress rules egress_rules = self._to_security_group_rules( element, 'ipPermissionsEgress/item' ) return EC2SecurityGroup(sg_id, name, ingress_rules, egress_rules, extra=extra) def _to_security_group_rules(self, element, xpath): return [self._to_security_group_rule(el) for el in element.findall( fixxpath(xpath=xpath, namespace=NAMESPACE)) ] def _to_security_group_rule(self, element): """ Parse the XML element and return a SecurityGroup object. :rtype: :class:`EC2SecurityGroup` """ rule = {} rule['protocol'] = findtext(element=element, xpath='ipProtocol', namespace=NAMESPACE) rule['from_port'] = findtext(element=element, xpath='fromPort', namespace=NAMESPACE) rule['to_port'] = findtext(element=element, xpath='toPort', namespace=NAMESPACE) # get security groups elements = element.findall(fixxpath( xpath='groups/item', namespace=NAMESPACE )) rule['group_pairs'] = [] for element in elements: item = { 'user_id': findtext( element=element, xpath='userId', namespace=NAMESPACE), 'group_id': findtext( element=element, xpath='groupId', namespace=NAMESPACE), 'group_name': findtext( element=element, xpath='groupName', namespace=NAMESPACE) } rule['group_pairs'].append(item) # get ip ranges elements = element.findall(fixxpath( xpath='ipRanges/item', namespace=NAMESPACE )) rule['cidr_ips'] = [ findtext( element=element, xpath='cidrIp', namespace=NAMESPACE ) for element in elements] return rule def _to_networks(self, response): return [self._to_network(el) for el in response.findall( fixxpath(xpath='vpcSet/item', namespace=NAMESPACE)) ] def _to_network(self, element, name=None): # Get the network id vpc_id = findtext(element=element, xpath='vpcId', namespace=NAMESPACE) # Get our tags tags = self._get_resource_tags(element) # Set our name if the Name key/value if available # If we don't get anything back then use the vpc_id name = name if name else tags.get('Name', vpc_id) cidr_block = findtext(element=element, xpath='cidrBlock', namespace=NAMESPACE) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['network']) # Add tags to the extra dict extra['tags'] = tags return EC2Network(vpc_id, name, cidr_block, extra=extra) def _to_addresses(self, response, only_associated): """ Builds a list of dictionaries containing elastic IP properties. :param only_associated: If true, return only those addresses that are associated with an instance. If false, return all addresses. :type only_associated: ``bool`` :rtype: ``list`` of :class:`ElasticIP` """ addresses = [] for el in response.findall(fixxpath(xpath='addressesSet/item', namespace=NAMESPACE)): addr = self._to_address(el, only_associated) if addr is not None: addresses.append(addr) return addresses def _to_address(self, element, only_associated): instance_id = findtext(element=element, xpath='instanceId', namespace=NAMESPACE) public_ip = findtext(element=element, xpath='publicIp', namespace=NAMESPACE) domain = findtext(element=element, xpath='domain', namespace=NAMESPACE) # Build our extra dict extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['elastic_ip']) # Return NoneType if only associated IPs are requested if only_associated and not instance_id: return None return ElasticIP(public_ip, domain, instance_id, extra=extra) def _to_placement_groups(self, response): return [self._to_placement_group(el) for el in response.findall( fixxpath(xpath='placementGroupSet/item', namespace=NAMESPACE))] def _to_placement_group(self, element): name = findtext(element=element, xpath='groupName', namespace=NAMESPACE) state = findtext(element=element, xpath='state', namespace=NAMESPACE) strategy = findtext(element=element, xpath='strategy', namespace=NAMESPACE) return EC2PlacementGroup(name, state, strategy) def _to_subnets(self, response): return [self._to_subnet(el) for el in response.findall( fixxpath(xpath='subnetSet/item', namespace=NAMESPACE)) ] def _to_subnet(self, element, name=None): # Get the subnet ID subnet_id = findtext(element=element, xpath='subnetId', namespace=NAMESPACE) # Get our tags tags = self._get_resource_tags(element) # If we don't get anything back then use the subnet_id name = name if name else tags.get('Name', subnet_id) state = findtext(element=element, xpath='state', namespace=NAMESPACE) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['subnet']) # Also include our tags extra['tags'] = tags return EC2NetworkSubnet(subnet_id, name, state, extra=extra) def _to_interfaces(self, response): return [self._to_interface(el) for el in response.findall( fixxpath(xpath='networkInterfaceSet/item', namespace=NAMESPACE)) ] def _to_interface(self, element, name=None): """ Parse the XML element and return an EC2NetworkInterface object. :param name: An optional name for the interface. If not provided then either tag with a key "Name" or the interface ID will be used (whichever is available first in that order). :type name: ``str`` :rtype: :class: `EC2NetworkInterface` """ interface_id = findtext(element=element, xpath='networkInterfaceId', namespace=NAMESPACE) state = findtext(element=element, xpath='status', namespace=NAMESPACE) # Get tags tags = self._get_resource_tags(element) name = name if name else tags.get('Name', interface_id) # Build security groups groups = self._get_security_groups(element) # Build private IPs priv_ips = [] for item in findall(element=element, xpath='privateIpAddressesSet/item', namespace=NAMESPACE): priv_ips.append({'private_ip': findtext(element=item, xpath='privateIpAddress', namespace=NAMESPACE), 'private_dns': findtext(element=item, xpath='privateDnsName', namespace=NAMESPACE), 'primary': findtext(element=item, xpath='primary', namespace=NAMESPACE)}) # Build our attachment dictionary which we will add into extra later attributes_map = \ RESOURCE_EXTRA_ATTRIBUTES_MAP['network_interface_attachment'] attachment = self._get_extra_dict(element, attributes_map) # Build our extra dict attributes_map = RESOURCE_EXTRA_ATTRIBUTES_MAP['network_interface'] extra = self._get_extra_dict(element, attributes_map) # Include our previously built items as well extra['tags'] = tags extra['attachment'] = attachment extra['private_ips'] = priv_ips extra['groups'] = groups return EC2NetworkInterface(interface_id, name, state, extra=extra) def _to_reserved_nodes(self, object, xpath): return [self._to_reserved_node(el) for el in object.findall(fixxpath(xpath=xpath, namespace=NAMESPACE))] def _to_reserved_node(self, element): """ Build an EC2ReservedNode object using the reserved instance properties. Information on these properties can be found at http://goo.gl/ulXCC7. """ # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['reserved_node']) try: size = [size for size in self.list_sizes() if size.id == extra['instance_type']][0] except IndexError: size = None return EC2ReservedNode(id=findtext(element=element, xpath='reservedInstancesId', namespace=NAMESPACE), state=findattr(element=element, xpath='state', namespace=NAMESPACE), driver=self, size=size, extra=extra) def _to_device_mappings(self, object): return [self._to_device_mapping(el) for el in object.findall( fixxpath(xpath='blockDeviceMapping/item', namespace=NAMESPACE)) ] def _to_device_mapping(self, element): """ Parse the XML element and return a dictionary of device properties. Additional information can be found at http://goo.gl/GjWYBf. @note: EBS volumes do not have a virtual name. Only ephemeral disks use this property. :rtype: ``dict`` """ mapping = {} mapping['device_name'] = findattr(element=element, xpath='deviceName', namespace=NAMESPACE) mapping['virtual_name'] = findattr(element=element, xpath='virtualName', namespace=NAMESPACE) # If virtual name does not exist then this is an EBS volume. # Build the EBS dictionary leveraging the _get_extra_dict method. if mapping['virtual_name'] is None: mapping['ebs'] = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['ebs_volume']) return mapping def _to_internet_gateways(self, object, xpath): return [self._to_internet_gateway(el) for el in object.findall(fixxpath(xpath=xpath, namespace=NAMESPACE))] def _to_internet_gateway(self, element, name=None): id = findtext(element=element, xpath='internetGatewayId', namespace=NAMESPACE) vpc_id = findtext(element=element, xpath='attachmentSet/item/vpcId', namespace=NAMESPACE) state = findtext(element=element, xpath='attachmentSet/item/state', namespace=NAMESPACE) # If there's no attachment state, let's # set it to available if not state: state = 'available' # Get our tags tags = self._get_resource_tags(element) # If name was not passed into the method then # fall back then use the gateway id name = name if name else tags.get('Name', id) return VPCInternetGateway(id=id, name=name, vpc_id=vpc_id, state=state, driver=self.connection.driver, extra={'tags': tags}) def _to_route_tables(self, response): return [self._to_route_table(el) for el in response.findall( fixxpath(xpath='routeTableSet/item', namespace=NAMESPACE)) ] def _to_route_table(self, element, name=None): # route table id route_table_id = findtext(element=element, xpath='routeTableId', namespace=NAMESPACE) # Get our tags tags = self._get_resource_tags(element) # Get our extra dictionary extra = self._get_extra_dict( element, RESOURCE_EXTRA_ATTRIBUTES_MAP['route_table']) # Add tags to the extra dict extra['tags'] = tags # Get routes routes = self._to_routes(element, 'routeSet/item') # Get subnet associations subnet_associations = self._to_subnet_associations( element, 'associationSet/item') # Get propagating routes virtual private gateways (VGW) IDs propagating_gateway_ids = [] for el in element.findall(fixxpath(xpath='propagatingVgwSet/item', namespace=NAMESPACE)): propagating_gateway_ids.append(findtext(element=el, xpath='gatewayId', namespace=NAMESPACE)) name = name if name else tags.get('Name', id) return EC2RouteTable(route_table_id, name, routes, subnet_associations, propagating_gateway_ids, extra=extra) def _to_routes(self, element, xpath): return [self._to_route(el) for el in element.findall( fixxpath(xpath=xpath, namespace=NAMESPACE)) ] def _to_route(self, element): """ Parse the XML element and return a route object :rtype: :class: `EC2Route` """ destination_cidr = findtext(element=element, xpath='destinationCidrBlock', namespace=NAMESPACE) gateway_id = findtext(element=element, xpath='gatewayId', namespace=NAMESPACE) instance_id = findtext(element=element, xpath='instanceId', namespace=NAMESPACE) owner_id = findtext(element=element, xpath='instanceOwnerId', namespace=NAMESPACE) interface_id = findtext(element=element, xpath='networkInterfaceId', namespace=NAMESPACE) state = findtext(element=element, xpath='state', namespace=NAMESPACE) origin = findtext(element=element, xpath='origin', namespace=NAMESPACE) vpc_peering_connection_id = findtext(element=element, xpath='vpcPeeringConnectionId', namespace=NAMESPACE) return EC2Route(destination_cidr, gateway_id, instance_id, owner_id, interface_id, state, origin, vpc_peering_connection_id) def _to_subnet_associations(self, element, xpath): return [self._to_subnet_association(el) for el in element.findall( fixxpath(xpath=xpath, namespace=NAMESPACE)) ] def _to_subnet_association(self, element): """ Parse the XML element and return a route table association object :rtype: :class: `EC2SubnetAssociation` """ association_id = findtext(element=element, xpath='routeTableAssociationId', namespace=NAMESPACE) route_table_id = findtext(element=element, xpath='routeTableId', namespace=NAMESPACE) subnet_id = findtext(element=element, xpath='subnetId', namespace=NAMESPACE) main = findtext(element=element, xpath='main', namespace=NAMESPACE) main = True if main else False return EC2SubnetAssociation(association_id, route_table_id, subnet_id, main) def _pathlist(self, key, arr): """ Converts a key and an array of values into AWS query param format. """ params = {} i = 0 for value in arr: i += 1 params['%s.%s' % (key, i)] = value return params def _get_boolean(self, element): tag = '{%s}%s' % (NAMESPACE, 'return') return element.findtext(tag) == 'true' def _get_terminate_boolean(self, element): status = element.findtext(".//{%s}%s" % (NAMESPACE, 'name')) return any([term_status == status for term_status in ('shutting-down', 'terminated')]) def _add_instance_filter(self, params, node): """ Add instance filter to the provided params dictionary. """ filters = {'instance-id': node.id} params.update(self._build_filters(filters)) return params def _get_state_boolean(self, element): """ Checks for the instances's state """ state = findall(element=element, xpath='instancesSet/item/currentState/name', namespace=NAMESPACE)[0].text return state in ('stopping', 'pending', 'starting') def _get_extra_dict(self, element, mapping): """ Extract attributes from the element based on rules provided in the mapping dictionary. :param element: Element to parse the values from. :type element: xml.etree.ElementTree.Element. :param mapping: Dictionary with the extra layout :type node: :class:`Node` :rtype: ``dict`` """ extra = {} for attribute, values in mapping.items(): transform_func = values['transform_func'] value = findattr(element=element, xpath=values['xpath'], namespace=NAMESPACE) if value is not None: extra[attribute] = transform_func(value) else: extra[attribute] = None return extra def _get_resource_tags(self, element): """ Parse tags from the provided element and return a dictionary with key/value pairs. :rtype: ``dict`` """ tags = {} # Get our tag set by parsing the element tag_set = findall(element=element, xpath='tagSet/item', namespace=NAMESPACE) for tag in tag_set: key = findtext(element=tag, xpath='key', namespace=NAMESPACE) value = findtext(element=tag, xpath='value', namespace=NAMESPACE) tags[key] = value return tags def _get_block_device_mapping_params(self, block_device_mapping): """ Return a list of dictionaries with query parameters for a valid block device mapping. :param mapping: List of dictionaries with the drive layout :type mapping: ``list`` or ``dict`` :return: Dictionary representation of the drive mapping :rtype: ``dict`` """ if not isinstance(block_device_mapping, (list, tuple)): raise AttributeError( 'block_device_mapping not list or tuple') params = {} for idx, mapping in enumerate(block_device_mapping): idx += 1 # We want 1-based indexes if not isinstance(mapping, dict): raise AttributeError( 'mapping %s in block_device_mapping ' 'not a dict' % mapping) for k, v in mapping.items(): if not isinstance(v, dict): params['BlockDeviceMapping.%d.%s' % (idx, k)] = str(v) else: for key, value in v.items(): params['BlockDeviceMapping.%d.%s.%s' % (idx, k, key)] = str(value) return params def _get_common_security_group_params(self, group_id, protocol, from_port, to_port, cidr_ips, group_pairs): """ Return a dictionary with common query parameters which are used when operating on security groups. :rtype: ``dict`` """ params = {'GroupId': group_id, 'IpPermissions.1.IpProtocol': protocol, 'IpPermissions.1.FromPort': from_port, 'IpPermissions.1.ToPort': to_port} if cidr_ips is not None: ip_ranges = {} for index, cidr_ip in enumerate(cidr_ips): index += 1 ip_ranges['IpPermissions.1.IpRanges.%s.CidrIp' % (index)] = cidr_ip params.update(ip_ranges) if group_pairs is not None: user_groups = {} for index, group_pair in enumerate(group_pairs): index += 1 if 'group_id' in group_pair.keys(): user_groups['IpPermissions.1.Groups.%s.GroupId' % (index)] = group_pair['group_id'] if 'group_name' in group_pair.keys(): user_groups['IpPermissions.1.Groups.%s.GroupName' % (index)] = group_pair['group_name'] if 'user_id' in group_pair.keys(): user_groups['IpPermissions.1.Groups.%s.UserId' % (index)] = group_pair['user_id'] params.update(user_groups) return params def _get_security_groups(self, element): """ Parse security groups from the provided element and return a list of security groups with the id ane name key/value pairs. :rtype: ``list`` of ``dict`` """ groups = [] for item in findall(element=element, xpath='groupSet/item', namespace=NAMESPACE): groups.append({ 'group_id': findtext(element=item, xpath='groupId', namespace=NAMESPACE), 'group_name': findtext(element=item, xpath='groupName', namespace=NAMESPACE) }) return groups def _build_filters(self, filters): """ Return a dictionary with filter query parameters which are used when listing networks, security groups, etc. :param filters: Dict of filter names and filter values :type filters: ``dict`` :rtype: ``dict`` """ filter_entries = {} for filter_idx, filter_data in enumerate(filters.items()): filter_idx += 1 # We want 1-based indexes filter_name, filter_values = filter_data filter_key = 'Filter.%s.Name' % (filter_idx) filter_entries[filter_key] = filter_name if isinstance(filter_values, list): for value_idx, value in enumerate(filter_values): value_idx += 1 # We want 1-based indexes value_key = 'Filter.%s.Value.%s' % (filter_idx, value_idx) filter_entries[value_key] = value else: value_key = 'Filter.%s.Value.1' % (filter_idx) filter_entries[value_key] = filter_values return filter_entries class EC2NodeDriver(BaseEC2NodeDriver): """ Amazon EC2 node driver. """ connectionCls = EC2Connection type = Provider.EC2 name = 'Amazon EC2' website = 'http://aws.amazon.com/ec2/' path = '/' NODE_STATE_MAP = { 'pending': NodeState.PENDING, 'running': NodeState.RUNNING, 'shutting-down': NodeState.UNKNOWN, 'terminated': NodeState.TERMINATED, 'stopped': NodeState.STOPPED } def __init__(self, key, secret=None, secure=True, host=None, port=None, region='us-east-1', **kwargs): if hasattr(self, '_region'): region = self._region if region not in VALID_EC2_REGIONS: raise ValueError('Invalid region: %s' % (region)) details = REGION_DETAILS[region] self.region_name = region self.api_name = details['api_name'] self.country = details['country'] host = host or details['endpoint'] super(EC2NodeDriver, self).__init__(key=key, secret=secret, secure=secure, host=host, port=port, **kwargs) class IdempotentParamError(LibcloudError): """ Request used the same client token as a previous, but non-identical request. """ def __str__(self): return repr(self.value) class EC2EUNodeDriver(EC2NodeDriver): """ Driver class for EC2 in the Western Europe Region. """ name = 'Amazon EC2 (eu-west-1)' _region = 'eu-west-1' class EC2USWestNodeDriver(EC2NodeDriver): """ Driver class for EC2 in the Western US Region """ name = 'Amazon EC2 (us-west-1)' _region = 'us-west-1' class EC2USWestOregonNodeDriver(EC2NodeDriver): """ Driver class for EC2 in the US West Oregon region. """ name = 'Amazon EC2 (us-west-2)' _region = 'us-west-2' class EC2APSENodeDriver(EC2NodeDriver): """ Driver class for EC2 in the Southeast Asia Pacific Region. """ name = 'Amazon EC2 (ap-southeast-1)' _region = 'ap-southeast-1' class EC2APNENodeDriver(EC2NodeDriver): """ Driver class for EC2 in the Northeast Asia Pacific Region. """ name = 'Amazon EC2 (ap-northeast-1)' _region = 'ap-northeast-1' class EC2SAEastNodeDriver(EC2NodeDriver): """ Driver class for EC2 in the South America (Sao Paulo) Region. """ name = 'Amazon EC2 (sa-east-1)' _region = 'sa-east-1' class EC2APSESydneyNodeDriver(EC2NodeDriver): """ Driver class for EC2 in the Southeast Asia Pacific (Sydney) Region. """ name = 'Amazon EC2 (ap-southeast-2)' _region = 'ap-southeast-2' class EucConnection(EC2Connection): """ Connection class for Eucalyptus """ host = None class EucNodeDriver(BaseEC2NodeDriver): """ Driver class for Eucalyptus """ name = 'Eucalyptus' website = 'http://www.eucalyptus.com/' api_name = 'ec2_us_east' region_name = 'us-east-1' connectionCls = EucConnection def __init__(self, key, secret=None, secure=True, host=None, path=None, port=None, api_version=DEFAULT_EUCA_API_VERSION): """ @inherits: :class:`EC2NodeDriver.__init__` :param path: The host where the API can be reached. :type path: ``str`` :param api_version: The API version to extend support for Eucalyptus proprietary API calls :type api_version: ``str`` """ super(EucNodeDriver, self).__init__(key, secret, secure, host, port) if path is None: path = '/services/Eucalyptus' self.path = path self.EUCA_NAMESPACE = 'http://msgs.eucalyptus.com/%s' % (api_version) def list_locations(self): raise NotImplementedError( 'list_locations not implemented for this driver') def _to_sizes(self, response): return [self._to_size(el) for el in response.findall( fixxpath(xpath='instanceTypeDetails/item', namespace=self.EUCA_NAMESPACE))] def _to_size(self, el): name = findtext(element=el, xpath='name', namespace=self.EUCA_NAMESPACE) cpu = findtext(element=el, xpath='cpu', namespace=self.EUCA_NAMESPACE) disk = findtext(element=el, xpath='disk', namespace=self.EUCA_NAMESPACE) memory = findtext(element=el, xpath='memory', namespace=self.EUCA_NAMESPACE) return NodeSize(id=name, name=name, ram=int(memory), disk=int(disk), bandwidth=None, price=None, driver=EucNodeDriver, extra={ 'cpu': int(cpu) }) def list_sizes(self): """ List available instance flavors/sizes :rtype: ``list`` of :class:`NodeSize` """ params = {'Action': 'DescribeInstanceTypes'} response = self.connection.request(self.path, params=params).object return self._to_sizes(response) def _add_instance_filter(self, params, node): """ Eucalyptus driver doesn't support filtering on instance id so this is a no-op. """ pass class NimbusConnection(EC2Connection): """ Connection class for Nimbus """ host = None class NimbusNodeDriver(BaseEC2NodeDriver): """ Driver class for Nimbus """ type = Provider.NIMBUS name = 'Nimbus' website = 'http://www.nimbusproject.org/' country = 'Private' api_name = 'nimbus' region_name = 'nimbus' friendly_name = 'Nimbus Private Cloud' connectionCls = NimbusConnection def ex_describe_addresses(self, nodes): """ Nimbus doesn't support elastic IPs, so this is a pass-through. @inherits: :class:`EC2NodeDriver.ex_describe_addresses` """ nodes_elastic_ip_mappings = {} for node in nodes: # empty list per node nodes_elastic_ip_mappings[node.id] = [] return nodes_elastic_ip_mappings def ex_create_tags(self, resource, tags): """ Nimbus doesn't support creating tags, so this is a pass-through. @inherits: :class:`EC2NodeDriver.ex_create_tags` """ pass class OutscaleConnection(EC2Connection): """ Connection class for Outscale """ host = None class OutscaleNodeDriver(BaseEC2NodeDriver): """ Base Outscale FCU node driver. Outscale per provider driver classes inherit from it. """ connectionCls = OutscaleConnection name = 'Outscale' website = 'http://www.outscale.com' path = '/' NODE_STATE_MAP = { 'pending': NodeState.PENDING, 'running': NodeState.RUNNING, 'shutting-down': NodeState.UNKNOWN, 'terminated': NodeState.TERMINATED, 'stopped': NodeState.STOPPED } def __init__(self, key, secret=None, secure=True, host=None, port=None, region='us-east-1', region_details=None, **kwargs): if hasattr(self, '_region'): region = self._region if region_details is None: raise ValueError('Invalid region_details argument') if region not in region_details.keys(): raise ValueError('Invalid region: %s' % (region)) self.region_name = region self.region_details = region_details details = self.region_details[region] self.api_name = details['api_name'] self.country = details['country'] self.connectionCls.host = details['endpoint'] self._not_implemented_msg =\ 'This method is not supported in the Outscale driver' super(BaseEC2NodeDriver, self).__init__(key=key, secret=secret, secure=secure, host=host, port=port, **kwargs) def create_node(self, **kwargs): """ Create a new Outscale node. The ex_iamprofile keyword is not supported. @inherits: :class:`BaseEC2NodeDriver.create_node` :keyword ex_keyname: The name of the key pair :type ex_keyname: ``str`` :keyword ex_userdata: User data :type ex_userdata: ``str`` :keyword ex_security_groups: A list of names of security groups to assign to the node. :type ex_security_groups: ``list`` :keyword ex_metadata: Key/Value metadata to associate with a node :type ex_metadata: ``dict`` :keyword ex_mincount: Minimum number of instances to launch :type ex_mincount: ``int`` :keyword ex_maxcount: Maximum number of instances to launch :type ex_maxcount: ``int`` :keyword ex_clienttoken: Unique identifier to ensure idempotency :type ex_clienttoken: ``str`` :keyword ex_blockdevicemappings: ``list`` of ``dict`` block device mappings. :type ex_blockdevicemappings: ``list`` of ``dict`` :keyword ex_ebs_optimized: EBS-Optimized if True :type ex_ebs_optimized: ``bool`` """ if 'ex_iamprofile' in kwargs: raise NotImplementedError("ex_iamprofile not implemented") return super(OutscaleNodeDriver, self).create_node(**kwargs) def ex_create_network(self, cidr_block, name=None): """ Create a network/VPC. Outscale does not support instance_tenancy. :param cidr_block: The CIDR block assigned to the network :type cidr_block: ``str`` :param name: An optional name for the network :type name: ``str`` :return: Dictionary of network properties :rtype: ``dict`` """ return super(OutscaleNodeDriver, self).ex_create_network(cidr_block, name=name) def ex_modify_instance_attribute(self, node, disable_api_termination=None, ebs_optimized=None, group_id=None, source_dest_check=None, user_data=None, instance_type=None): """ Modify node attributes. Ouscale support the following attributes: 'DisableApiTermination.Value', 'EbsOptimized', 'GroupId.n', 'SourceDestCheck.Value', 'UserData.Value', 'InstanceType.Value' :param node: Node instance :type node: :class:`Node` :param attributes: Dictionary with node attributes :type attributes: ``dict`` :return: True on success, False otherwise. :rtype: ``bool`` """ attributes = {} if disable_api_termination is not None: attributes['DisableApiTermination.Value'] = disable_api_termination if ebs_optimized is not None: attributes['EbsOptimized'] = ebs_optimized if group_id is not None: attributes['GroupId.n'] = group_id if source_dest_check is not None: attributes['SourceDestCheck.Value'] = source_dest_check if user_data is not None: attributes['UserData.Value'] = user_data if instance_type is not None: attributes['InstanceType.Value'] = instance_type return super(OutscaleNodeDriver, self).ex_modify_instance_attribute( node, attributes) def ex_register_image(self, name, description=None, architecture=None, root_device_name=None, block_device_mapping=None): """ Registers a Machine Image based off of an EBS-backed instance. Can also be used to create images from snapshots. Outscale does not support image_location, kernel_id and ramdisk_id. :param name: The name for the AMI being registered :type name: ``str`` :param description: The description of the AMI (optional) :type description: ``str`` :param architecture: The architecture of the AMI (i386/x86_64) (optional) :type architecture: ``str`` :param root_device_name: The device name for the root device Required if registering an EBS-backed AMI :type root_device_name: ``str`` :param block_device_mapping: A dictionary of the disk layout (optional) :type block_device_mapping: ``dict`` :rtype: :class:`NodeImage` """ return super(OutscaleNodeDriver, self).ex_register_image( name, description=description, architecture=architecture, root_device_name=root_device_name, block_device_mapping=block_device_mapping) def ex_copy_image(self, source_region, image, name=None, description=None): """ Outscale does not support copying images. @inherits: :class:`EC2NodeDriver.ex_copy_image` """ raise NotImplementedError(self._not_implemented_msg) def ex_get_limits(self): """ Outscale does not support getting limits. @inherits: :class:`EC2NodeDriver.ex_get_limits` """ raise NotImplementedError(self._not_implemented_msg) def ex_create_network_interface(self, subnet, name=None, description=None, private_ip_address=None): """ Outscale does not support creating a network interface within a VPC. @inherits: :class:`EC2NodeDriver.ex_create_network_interface` """ raise NotImplementedError(self._not_implemented_msg) def ex_delete_network_interface(self, network_interface): """ Outscale does not support deleting a network interface within a VPC. @inherits: :class:`EC2NodeDriver.ex_delete_network_interface` """ raise NotImplementedError(self._not_implemented_msg) def ex_attach_network_interface_to_node(self, network_interface, node, device_index): """ Outscale does not support attaching a network interface. @inherits: :class:`EC2NodeDriver.ex_attach_network_interface_to_node` """ raise NotImplementedError(self._not_implemented_msg) def ex_detach_network_interface(self, attachment_id, force=False): """ Outscale does not support detaching a network interface @inherits: :class:`EC2NodeDriver.ex_detach_network_interface` """ raise NotImplementedError(self._not_implemented_msg) def list_sizes(self, location=None): """ List available instance flavors/sizes This override the EC2 default method in order to use Outscale infos. :rtype: ``list`` of :class:`NodeSize` """ available_types =\ self.region_details[self.region_name]['instance_types'] sizes = [] for instance_type in available_types: attributes = OUTSCALE_INSTANCE_TYPES[instance_type] attributes = copy.deepcopy(attributes) price = self._get_size_price(size_id=instance_type) attributes.update({'price': price}) sizes.append(NodeSize(driver=self, **attributes)) return sizes class OutscaleSASNodeDriver(OutscaleNodeDriver): """ Outscale SAS node driver """ name = 'Outscale SAS' type = Provider.OUTSCALE_SAS def __init__(self, key, secret=None, secure=True, host=None, port=None, region='us-east-1', region_details=None, **kwargs): super(OutscaleSASNodeDriver, self).__init__( key=key, secret=secret, secure=secure, host=host, port=port, region=region, region_details=OUTSCALE_SAS_REGION_DETAILS, **kwargs) class OutscaleINCNodeDriver(OutscaleNodeDriver): """ Outscale INC node driver """ name = 'Outscale INC' type = Provider.OUTSCALE_INC def __init__(self, key, secret=None, secure=True, host=None, port=None, region='us-east-1', region_details=None, **kwargs): super(OutscaleINCNodeDriver, self).__init__( key=key, secret=secret, secure=secure, host=host, port=port, region=region, region_details=OUTSCALE_INC_REGION_DETAILS, **kwargs)<|fim▁end|>
'i2.4xlarge', 'i2.8xlarge',
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>use std::env; use std::process::Command; use std::str::{self, FromStr}; fn main(){ let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; // const fn stabilized in Rust 1.31: if minor >= 31 { println!("cargo:rustc-cfg=bitflags_const_fn"); } } fn rustc_minor_version() -> Option<u32> { let rustc = match env::var_os("RUSTC") { Some(rustc) => rustc, None => return None, }; let output = match Command::new(rustc).arg("--version").output() { Ok(output) => output, Err(_) => return None, }; let version = match str::from_utf8(&output.stdout) { Ok(version) => version, Err(_) => return None, }; <|fim▁hole|> let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } let next = match pieces.next() { Some(next) => next, None => return None, }; u32::from_str(next).ok() }<|fim▁end|>
<|file_name|>graph_test.go<|end_file_name|><|fim▁begin|>package graph_test import ( "testing" "github.com/filwisher/algo/graph" "github.com/filwisher/algo/set" ) func TestGraph(t *testing.T) { conn := 1 g := graph.NewGraph() for i := 2; i < 6; i++ { g.AddEdge(conn, i) } <|fim▁hole|> for e := range g.Adjacent(conn) { s.Add(e) } for i := 2; i < 6; i++ { if !s.Contains(i) { t.Errorf("graph does not contain edge between %d and %d", conn, i) } for e := range g.Adjacent(i) { if e != conn { t.Errorf("edges are not bidirectional") } } } }<|fim▁end|>
s := set.NewSet()
<|file_name|>dynamic.rs<|end_file_name|><|fim▁begin|>use maths::{Point2, Vector2, Basis2, Rotation2, Rad, EuclideanSpace, Rotation, ApproxEq, Angle}; use std::ops::{Deref, DerefMut}; use ecs::entity::{Entities, Accessor, EntityRef}; use ecs::state::CommitArgs; use ecs::module::{Component, Template}; use ecs::policy::Id; use std::ops::Index; use std::collections::VecDeque; use vec_map::VecMap; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Transform { pub position: Point2<f32>, pub rotation: Rad<f32>, pub scale: Vector2<f32>, } impl Transform { pub fn one() -> Self { Transform { position: Point2::new(0., 0.), rotation: Rad(0.), scale: Vector2::new(1., 1.), } } pub fn basis(&self) -> Basis2<f32> { Basis2::from_angle(self.rotation) } pub fn scale_vector(&self, v: Vector2<f32>) -> Vector2<f32> { Vector2::new(v.x * self.scale.x, v.y * self.scale.y) } } impl Template for Transform {} impl ApproxEq for Transform { type Epsilon = f32; #[inline] fn default_epsilon() -> Self::Epsilon { Self::Epsilon::default_epsilon() } #[inline] fn default_max_relative() -> Self::Epsilon { Self::Epsilon::default_max_relative() } #[inline] fn default_max_ulps() -> u32 { Self::Epsilon::default_max_ulps() } #[inline] fn relative_eq(&self, other: &Self, epsilon: Self::Epsilon, max_relative: Self::Epsilon) -> bool { self.position.relative_eq(&other.position, epsilon, max_relative) && self.rotation.relative_eq(&other.rotation, epsilon, max_relative) && self.scale.relative_eq(&other.scale, epsilon, max_relative) } #[inline] fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool { self.position.ulps_eq(&other.position, epsilon, max_ulps) && self.rotation.ulps_eq(&other.rotation, epsilon, max_ulps) && self.scale.ulps_eq(&other.scale, epsilon, max_ulps) } } #[derive(Debug, Clone, Copy)] pub struct TransformTemplate { pub parent: Option<EntityRef>, pub transform: Transform, } impl Template for TransformTemplate {} #[derive(Debug)] struct Instance { world: Transform, local: Transform, parent: Option<usize>, first_child: Option<usize>, next_sibling: Option<usize>, previous_sibling: Option<usize>, entity: Id, } type ParentIndex = usize; type InstanceIndex = usize; const INITIAL_STACK_CAPACITY: usize = 15; pub struct TransformStorage { instances: Vec<Instance>, entity_to_instance: VecMap<InstanceIndex>, transform_stack: VecDeque<(ParentIndex, InstanceIndex)>, } impl TransformStorage { pub fn new() -> Self { TransformStorage { instances: Vec::new(), entity_to_instance: VecMap::new(), transform_stack: VecDeque::with_capacity(INITIAL_STACK_CAPACITY), } } fn insert(&mut self, entities: &Entities, entity: Id, template: TransformTemplate) { use vec_map::Entry; let parent_index = template.parent .and_then(|entity_ref| entities.upgrade(entity_ref)) .and_then(|accessor| self.entity_to_instance.get(accessor.id() as usize).cloned()); let instance_index = match self.entity_to_instance.entry(entity as usize) { Entry::Vacant(vacant) => { let index = self.instances.len(); self.instances.push(Instance { world: Transform::one(), local: Transform::one(), parent: None, first_child: None, next_sibling: None, previous_sibling: None, entity: entity, }); *vacant.insert(index) } Entry::Occupied(mut occupied) => *occupied.get_mut(), }; self.set_parent_for_instance(instance_index, parent_index); self.set_local_transform_impl(entity, template.transform); } fn remove(&mut self, entity: Id) { if let Some(instance_index) = self.entity_to_instance.remove(entity as usize) { self.detach_from_parent(instance_index); let old_index = self.instances.len() - 1; self.instances.swap_remove(instance_index); let &mut TransformStorage { ref mut entity_to_instance, ref mut instances, .. } = self; // We need to update the references of the swapped instance. let siblings = instances.get_mut(instance_index).map(|instance| { entity_to_instance[instance.entity as usize] = instance_index; (instance.parent, instance.previous_sibling, instance.next_sibling) }); if let Some((parent, previous_sibling, next_sibling)) = siblings { // We have to check if we need to update parent first_child reference match parent { Some(parent) => { let parent = &mut instances[parent]; if parent.first_child == Some(old_index) { parent.first_child = Some(instance_index); } } _ => {} } previous_sibling.map(|index| instances[index].next_sibling = Some(instance_index)); next_sibling.map(|index| instances[index].previous_sibling = Some(instance_index)); } } } pub fn local(&self, entity: Accessor) -> Option<Transform> { self.entity_to_instance .get(entity.id() as usize) .map(|&index| self.instances[index].local) } pub fn world(&self, entity: Accessor) -> Option<Transform> { self.entity_to_instance .get(entity.id() as usize) .map(|&index| self.instances[index].world) } pub fn parent(&self, entity: Accessor) -> Option<Accessor> { if let Some(&instance_index) = self.entity_to_instance.get(entity.id() as usize) { let parent = self.instances[instance_index].parent; parent.map(|index| unsafe { Accessor::new_unchecked(self.instances[index].entity) }) } else { None } } pub fn children(&self, entity: Accessor) -> Children { let instance_index = self.entity_to_instance[entity.id() as usize]; Children { current: self.instances[instance_index].first_child } } pub fn set_parent(&mut self, entity: Accessor, parent: Accessor) { let entity_index = *self.entity_to_instance .get(entity.id() as usize) .expect("The entity does not have a transform attached to it."); let parent_index = *self.entity_to_instance .get(parent.id() as usize) .expect("The entity does not have a transform attached to it."); self.set_parent_for_instance(entity_index, Some(parent_index)); let parent_transform = self.instances[parent_index].world; self.transform(&parent_transform, entity_index); } pub fn remove_parent(&mut self, entity: Accessor) { let entity_index = *self.entity_to_instance .get(entity.id() as usize) .expect("The entity does not have a transform attached to it."); self.set_parent_for_instance(entity_index, None); self.transform(&Transform::one(), entity_index); } pub fn set_local(&mut self, entity: Accessor, transform: Transform) { self.set_local_transform_impl(entity.id(), transform); } fn set_local_transform_impl(&mut self, entity: Id, transform: Transform) { let instance_index = *self.entity_to_instance .get(entity as usize) .expect("The entity does not have a transform attached to it."); let parent = { let mut entity_instance = &mut self.instances[instance_index]; entity_instance.local = transform; entity_instance.parent }; let parent_transform = match parent { Some(parent_instance_index) => self.instances[parent_instance_index].world, None => Transform::one(), }; self.transform(&parent_transform, instance_index); if self.transform_stack.len() != 0 { let mut current_parent_index = instance_index; let mut current_parent_transform = self.instances[instance_index].world; while let Some((parent_index, instance_index)) = self.transform_stack.pop_front() { if parent_index != current_parent_index { current_parent_index = parent_index; current_parent_transform = self.instances[parent_index].world; } self.transform(&current_parent_transform, instance_index); } } } fn transform(&mut self, parent_transform: &Transform, instance_index: InstanceIndex) { let mut current_child = { let instance = &mut self.instances[instance_index]; let direction = parent_transform.basis() .rotate_vector(instance.local.position.to_vec()); let parent_to_child = parent_transform.scale_vector(direction); instance.world = Transform { position: parent_transform.position + parent_to_child, rotation: (parent_transform.rotation + instance.local.rotation).normalize(), scale: parent_transform.scale_vector(instance.local.scale), }; instance.first_child }; while let Some(child) = current_child { self.transform_stack.push_back((instance_index, child)); current_child = self.instances[child].next_sibling; } } fn set_parent_for_instance(&mut self, instance_index: InstanceIndex, parent: Option<ParentIndex>) { debug_assert!(!self.cycle_reference_check(instance_index, parent)); self.detach_from_parent(instance_index); if let Some(parent_index) = parent { self.instances[instance_index].parent = parent; self.append_child_to(parent_index, instance_index); } } fn cycle_reference_check(&self, instance_index: InstanceIndex, parent: Option<ParentIndex>) -> bool { if let Some(parent_index) = parent { if instance_index == parent_index { return true; } let mut current_child = self.instances[instance_index].first_child; while let Some(child) = current_child { if child == parent_index { return true; } current_child = self.instances[child].next_sibling; } } false } fn append_child_to(&mut self, parent_index: ParentIndex, instance_index: InstanceIndex) { let mut current_child = self.instances[parent_index].first_child; let mut last_child = None; while let Some(child) = current_child { last_child = current_child; current_child = self.instances[child].next_sibling; } match last_child { Some(last_child_index) => { self.instances[last_child_index].next_sibling = Some(instance_index); self.instances[instance_index].previous_sibling = Some(last_child_index); } None => { self.instances[parent_index].first_child = Some(instance_index); } } } fn detach_from_parent(&mut self, instance_index: InstanceIndex) { let linked_list_instances = { let instance = &mut self.instances[instance_index]; let parent = instance.parent.take(); (parent, instance.previous_sibling, instance.next_sibling) }; match linked_list_instances { (None, _, _) => {} (Some(parent), None, Some(next_sibling)) => { // We were the first child of the parent so we need to update the parent first_child link // to point on our next_sibling self.instances[parent].first_child = Some(next_sibling); self.instances[next_sibling].previous_sibling = None; } (_, Some(previous_sibling), Some(next_sibling)) => { // Here we have to update both sibling to point to each others; self.instances[previous_sibling].next_sibling = Some(next_sibling); self.instances[next_sibling].previous_sibling = Some(previous_sibling); } (_, Some(previous_sibling), None) => { // We were the tail, so we update the previous sibling to make it the new tail. self.instances[previous_sibling].next_sibling = None; } (Some(parent), None, None) => { // We were the only child self.instances[parent].first_child = None; } } } #[doc(hidden)] pub fn commit(&mut self, args: &CommitArgs) { let mut reader = args.update_reader_for::<Transform>(); while let Some((entity, template)) = reader.next_attach_query() { self.insert(args.entities, entity, template); } while let Some(entity) = reader.next_detach_query() { self.remove(entity); } for entity in args.world_removes() { self.remove(entity.id()); } } } pub struct Children { current: Option<usize>, } impl Children { pub fn next(&mut self, transforms: &TransformStorage) -> Option<Accessor> { match self.current { Some(current) => { let (entity_id, next_child) = { let instance = &transforms.instances[current]; (instance.entity, instance.next_sibling) }; self.current = next_child; let accessor = unsafe { Accessor::new_unchecked(entity_id) }; Some(accessor) } None => None, } } } #[cfg(test)] mod tests { use super::*; use maths::{Vector2, Rad, Deg, Point2, ApproxEq}; use ecs::entity::{Entities, Entity, Accessor}; macro_rules! transform_approx_eq { ($left:expr, $right:expr) => ( match ($left, $right) { (Some(left), Some(right)) => assert_ulps_eq!(left, right), _ => assert_eq!($left, $right) } ) } #[test] fn test_insert_transform_root() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (entity, accessor) = spawn_entity(&mut entities); let transform = Transform { position: Point2::new(5., 5.), rotation: Rad(0.4), scale: Vector2::new(1., 1.), }; storage.insert(&entities, entity.id(), TransformTemplate { transform: transform, parent: None, }); transform_approx_eq!(storage.local(accessor), Some(transform)); transform_approx_eq!(storage.world(accessor), Some(transform)); assert_eq!(storage.parent(accessor), None); } #[test] fn test_remove_transform_root() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (entity, accessor) = spawn_entity(&mut entities); let transform = Transform { position: Point2::new(5., 5.), rotation: Rad(0.4), scale: Vector2::new(1., 1.), }; storage.insert(&entities, entity.id(), TransformTemplate { transform: transform, parent: None, }); storage.remove(entity.id()); transform_approx_eq!(storage.local(accessor), None); transform_approx_eq!(storage.world(accessor), None); assert_eq!(storage.parent(accessor), None); } #[test] fn test_remove_twice() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (entity, _) = spawn_entity(&mut entities); storage.remove(entity.id()); storage.remove(entity.id()); } #[test] fn test_insert_twice() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, parent_accessor) = spawn_entity(&mut entities); let (child, child_accessor) = spawn_entity(&mut entities); let parent_transform = Transform { position: Point2::new(0., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; storage.insert(&entities, parent.id(), TransformTemplate { transform: parent_transform, parent: None, }); storage.insert(&entities, child.id(),<|fim▁hole|> }); let child_transform = Transform { position: Point2::new(5., 0.), rotation: Rad(0.), scale: Vector2::new(1., 1.), }; storage.insert(&entities, child.id(), TransformTemplate { transform: child_transform, parent: Some(entities.entity_ref(parent_accessor)), }); let expected = Transform { position: Point2::new(-10., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; transform_approx_eq!(storage.local(child_accessor), Some(child_transform)); transform_approx_eq!(storage.world(child_accessor), Some(expected)); assert_eq!(storage.parent(child_accessor), Some(parent_accessor)); } #[test] fn test_parent_transform() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, parent_accessor) = spawn_entity(&mut entities); let (child, child_accessor) = spawn_entity(&mut entities); let parent_transform = Transform { position: Point2::new(0., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; let child_transform = Transform { position: Point2::new(5., 0.), rotation: Rad(0.), scale: Vector2::new(1., 1.), }; storage.insert(&entities, parent.id(), TransformTemplate { transform: parent_transform, parent: None, }); storage.insert(&entities, child.id(), TransformTemplate { transform: child_transform, parent: Some(entities.entity_ref(parent_accessor)), }); transform_approx_eq!(storage.local(parent_accessor), Some(parent_transform)); transform_approx_eq!(storage.world(parent_accessor), Some(parent_transform)); assert_eq!(storage.parent(parent_accessor), None); let expected = Transform { position: Point2::new(-10., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; transform_approx_eq!(storage.local(child_accessor), Some(child_transform)); transform_approx_eq!(storage.world(child_accessor), Some(expected)); assert_eq!(storage.parent(child_accessor), Some(parent_accessor)); } #[test] fn test_remove_parent() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, parent_accessor) = spawn_entity(&mut entities); let (child, child_accessor) = spawn_entity(&mut entities); let parent_transform = Transform { position: Point2::new(0., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; let child_transform = Transform { position: Point2::new(5., 0.), rotation: Rad(0.), scale: Vector2::new(1., 1.), }; storage.insert(&entities, parent.id(), TransformTemplate { transform: parent_transform, parent: None, }); storage.insert(&entities, child.id(), TransformTemplate { transform: child_transform, parent: Some(entities.entity_ref(parent_accessor)), }); storage.remove_parent(child_accessor); transform_approx_eq!(storage.local(child_accessor), Some(child_transform)); transform_approx_eq!(storage.world(child_accessor), Some(child_transform)); assert_eq!(storage.parent(child_accessor), None); } #[test] fn test_set_parent() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, parent_accessor) = spawn_entity(&mut entities); let (child, child_accessor) = spawn_entity(&mut entities); let parent_transform = Transform { position: Point2::new(0., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; let child_transform = Transform { position: Point2::new(5., 0.), rotation: Rad(0.), scale: Vector2::new(1., 1.), }; storage.insert(&entities, parent.id(), TransformTemplate { transform: parent_transform, parent: None, }); storage.insert(&entities, child.id(), TransformTemplate { transform: child_transform, parent: None, }); storage.set_parent(child_accessor, parent_accessor); let expected = Transform { position: Point2::new(-10., 5.), rotation: Rad::from(Deg(180.)), scale: Vector2::new(2., 1.), }; transform_approx_eq!(storage.local(child_accessor), Some(child_transform)); transform_approx_eq!(storage.world(child_accessor), Some(expected)); assert_eq!(storage.parent(child_accessor), Some(parent_accessor)); } #[test] fn test_children_forward() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, spawned_entities) = spawn_entity_with_children(&mut entities, &mut storage, 3); let mut cursor = storage.children(parent); for child in spawned_entities { assert_eq!(cursor.next(&storage), Some(child)); } assert_eq!(cursor.next(&storage), None); } #[test] fn test_remove_the_only_child() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, spawned_entities) = spawn_entity_with_children(&mut entities, &mut storage, 1); let child = spawned_entities[0]; storage.remove(child.id()); let mut cursor = storage.children(parent); assert_eq!(cursor.next(&storage), None); } #[test] fn test_remove_child_head() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, spawned_entities) = spawn_entity_with_children(&mut entities, &mut storage, 2); let child_head = spawned_entities[0]; storage.remove(child_head.id()); let mut cursor = storage.children(parent); for child in spawned_entities.into_iter().skip(1) { assert_eq!(cursor.next(&storage), Some(child)); } assert_eq!(cursor.next(&storage), None); } #[test] fn test_remove_child_tail() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, mut spawned_entities) = spawn_entity_with_children(&mut entities, &mut storage, 2); let child_tail = spawned_entities.pop().unwrap(); storage.remove(child_tail.id()); let mut cursor = storage.children(parent); for child in spawned_entities.into_iter() { assert_eq!(cursor.next(&storage), Some(child)); } assert_eq!(cursor.next(&storage), None); } #[test] fn test_remove_child_in_the_middle() { let mut storage = TransformStorage::new(); let mut entities = Entities::new(); let (parent, mut spawned_entities) = spawn_entity_with_children(&mut entities, &mut storage, 3); let removed_child = spawned_entities.swap_remove(1); storage.remove(removed_child.id()); let mut cursor = storage.children(parent); for child in spawned_entities.into_iter() { assert_eq!(cursor.next(&storage), Some(child)); } assert_eq!(cursor.next(&storage), None); } fn spawn_entity_with_children<'a>(entities: &'a mut Entities, storage: &mut TransformStorage, children_count: usize) -> (Accessor<'a>, Vec<Accessor<'a>>) { let (parent, parent_accessor) = spawn_entity(entities); let parent_transform_template = TransformTemplate { transform: Transform::one(), parent: None, }; storage.insert(&entities, parent.id(), parent_transform_template); let mut children = Vec::new(); let child_transform_template = TransformTemplate { transform: Transform::one(), parent: Some(entities.entity_ref(parent_accessor)), }; for _ in 0..children_count { let (entity, accessor) = spawn_entity(entities); storage.insert(&entities, entity.id(), child_transform_template); children.push(accessor); } (parent_accessor, children) } fn spawn_entity<'a>(entities: &mut Entities) -> (Entity, Accessor<'a>) { let entity = entities.create(); entities.spawn(entity); (entity, unsafe { Accessor::new_unchecked(entity.id()) }) } }<|fim▁end|>
TransformTemplate { transform: Transform::one(), parent: None,
<|file_name|>skia.rs<|end_file_name|><|fim▁begin|>// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use libc::*; pub type SkiaGrContextRef = *mut c_void; pub type SkiaGrGLInterfaceRef = *const c_void; #[link(name = "skia")] extern { pub fn SkiaGrGLCreateNativeInterface() -> SkiaGrGLInterfaceRef; pub fn SkiaGrGLInterfaceRetain(anInterface: SkiaGrGLInterfaceRef); pub fn SkiaGrGLInterfaceRelease(anInterface: SkiaGrGLInterfaceRef); pub fn SkiaGrGLInterfaceHasExtension(anInterface: SkiaGrGLInterfaceRef, extension: *const c_char) -> bool; pub fn SkiaGrGLInterfaceGLVersionGreaterThanOrEqualTo(anInterface: SkiaGrGLInterfaceRef, major: i32, minor: i32) -> bool; pub fn SkiaGrContextCreate(anInterface: SkiaGrGLInterfaceRef) -> SkiaGrContextRef; pub fn SkiaGrContextRetain(aContext: SkiaGrContextRef);<|fim▁hole|> }<|fim▁end|>
pub fn SkiaGrContextRelease(aContext: SkiaGrContextRef);
<|file_name|>test_nonlin.py<|end_file_name|><|fim▁begin|>""" Unit tests for nonlinear solvers Author: Ondrej Certik May 2007 """ from __future__ import division, print_function, absolute_import from numpy.testing import assert_ import pytest from scipy._lib.six import xrange from scipy.optimize import nonlin, root from numpy import matrix, diag, dot from numpy.linalg import inv import numpy as np from .test_minpack import pressure_network SOLVERS = {'anderson': nonlin.anderson, 'diagbroyden': nonlin.diagbroyden, 'linearmixing': nonlin.linearmixing, 'excitingmixing': nonlin.excitingmixing, 'broyden1': nonlin.broyden1, 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov} MUST_WORK = {'anderson': nonlin.anderson, 'broyden1': nonlin.broyden1, 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov} #------------------------------------------------------------------------------- # Test problems #------------------------------------------------------------------------------- def F(x): x = np.asmatrix(x).T d = matrix(diag([3,2,1.5,1,0.5])) c = 0.01 f = -d*x - c*float(x.T*x)*x return f F.xin = [1,1,1,1,1] F.KNOWN_BAD = {} def F2(x): return x F2.xin = [1,2,3,4,5,6] F2.KNOWN_BAD = {'linearmixing': nonlin.linearmixing, 'excitingmixing': nonlin.excitingmixing} def F2_lucky(x): return x F2_lucky.xin = [0,0,0,0,0,0] F2_lucky.KNOWN_BAD = {} def F3(x): A = np.mat('-2 1 0; 1 -2 1; 0 1 -2') b = np.mat('1 2 3') return np.dot(A, x) - b F3.xin = [1,2,3] F3.KNOWN_BAD = {} def F4_powell(x): A = 1e4 return [A*x[0]*x[1] - 1, np.exp(-x[0]) + np.exp(-x[1]) - (1 + 1/A)] F4_powell.xin = [-1, -2] F4_powell.KNOWN_BAD = {'linearmixing': nonlin.linearmixing, 'excitingmixing': nonlin.excitingmixing, 'diagbroyden': nonlin.diagbroyden} def F5(x): return pressure_network(x, 4, np.array([.5, .5, .5, .5])) F5.xin = [2., 0, 2, 0] F5.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing, 'linearmixing': nonlin.linearmixing, 'diagbroyden': nonlin.diagbroyden} def F6(x): x1, x2 = x J0 = np.array([[-4.256, 14.7], [0.8394989, 0.59964207]]) v = np.array([(x1 + 3) * (x2**5 - 7) + 3*6, np.sin(x2 * np.exp(x1) - 1)]) return -np.linalg.solve(J0, v) F6.xin = [-0.5, 1.4] F6.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing, 'linearmixing': nonlin.linearmixing, 'diagbroyden': nonlin.diagbroyden} #------------------------------------------------------------------------------- # Tests #------------------------------------------------------------------------------- class TestNonlin(object): """ Check the Broyden methods for a few test problems. broyden1, broyden2, and newton_krylov must succeed for all functions. Some of the others don't -- tests in KNOWN_BAD are skipped. """ def _check_nonlin_func(self, f, func, f_tol=1e-2): x = func(f, f.xin, f_tol=f_tol, maxiter=200, verbose=0) assert_(np.absolute(f(x)).max() < f_tol) def _check_root(self, f, method, f_tol=1e-2): res = root(f, f.xin, method=method, options={'ftol': f_tol, 'maxiter': 200, 'disp': 0}) assert_(np.absolute(res.fun).max() < f_tol) @pytest.mark.xfail def _check_func_fail(self, *a, **kw): pass def test_problem_nonlin(self): for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]: for func in SOLVERS.values(): if func in f.KNOWN_BAD.values(): if func in MUST_WORK.values(): self._check_func_fail(f, func) continue self._check_nonlin_func(f, func) def test_tol_norm_called(self): # Check that supplying tol_norm keyword to nonlin_solve works self._tol_norm_used = False def local_norm_func(x): self._tol_norm_used = True return np.absolute(x).max() nonlin.newton_krylov(F, F.xin, f_tol=1e-2, maxiter=200, verbose=0, tol_norm=local_norm_func) assert_(self._tol_norm_used) def test_problem_root(self): for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]: for meth in SOLVERS: if meth in f.KNOWN_BAD: if meth in MUST_WORK: self._check_func_fail(f, meth) continue self._check_root(f, meth) class TestSecant(object): """Check that some Jacobian approximations satisfy the secant condition""" xs = [np.array([1,2,3,4,5], float), np.array([2,3,4,5,1], float), np.array([3,4,5,1,2], float), np.array([4,5,1,2,3], float), np.array([9,1,9,1,3], float), np.array([0,1,9,1,3], float), np.array([5,5,7,1,1], float), np.array([1,2,7,5,1], float),] fs = [x**2 - 1 for x in xs] def _check_secant(self, jac_cls, npoints=1, **kw): """ Check that the given Jacobian approximation satisfies secant conditions for last `npoints` points. """ jac = jac_cls(**kw) jac.setup(self.xs[0], self.fs[0], None) for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): jac.update(x, f) for k in xrange(min(npoints, j+1)): dx = self.xs[j-k+1] - self.xs[j-k] df = self.fs[j-k+1] - self.fs[j-k] assert_(np.allclose(dx, jac.solve(df))) # Check that the `npoints` secant bound is strict if j >= npoints: dx = self.xs[j-npoints+1] - self.xs[j-npoints] df = self.fs[j-npoints+1] - self.fs[j-npoints] assert_(not np.allclose(dx, jac.solve(df))) def test_broyden1(self): self._check_secant(nonlin.BroydenFirst) def test_broyden2(self): self._check_secant(nonlin.BroydenSecond) def test_broyden1_update(self): # Check that BroydenFirst update works as for a dense matrix jac = nonlin.BroydenFirst(alpha=0.1) jac.setup(self.xs[0], self.fs[0], None) B = np.identity(5) * (-1/0.1) for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): df = f - self.fs[last_j] dx = x - self.xs[last_j] B += (df - dot(B, dx))[:,None] * dx[None,:] / dot(dx, dx) jac.update(x, f) assert_(np.allclose(jac.todense(), B, rtol=1e-10, atol=1e-13)) def test_broyden2_update(self): # Check that BroydenSecond update works as for a dense matrix jac = nonlin.BroydenSecond(alpha=0.1) jac.setup(self.xs[0], self.fs[0], None) H = np.identity(5) * (-0.1) for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): df = f - self.fs[last_j] dx = x - self.xs[last_j] H += (dx - dot(H, df))[:,None] * df[None,:] / dot(df, df) jac.update(x, f) assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13)) def test_anderson(self): # Anderson mixing (with w0=0) satisfies secant conditions # for the last M iterates, see [Ey]_ # # .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3) class TestLinear(object): """Solve a linear equation; some methods find the exact solution in a finite number of steps""" def _check(self, jac, N, maxiter, complex=False, **kw): np.random.seed(123) A = np.random.randn(N, N) if complex: A = A + 1j*np.random.randn(N, N) b = np.random.randn(N) if complex: b = b + 1j*np.random.randn(N) def func(x): return dot(A, x) - b sol = nonlin.nonlin_solve(func, np.zeros(N), jac, maxiter=maxiter, f_tol=1e-6, line_search=None, verbose=0) assert_(np.allclose(dot(A, sol), b, atol=1e-6)) def test_broyden1(self): # Broyden methods solve linear systems exactly in 2*N steps self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, False) self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, True) def test_broyden2(self): # Broyden methods solve linear systems exactly in 2*N steps self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, False) self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, True) def test_anderson(self): # Anderson is rather similar to Broyden, if given enough storage space self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, False) self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, True) def test_krylov(self): # Krylov methods solve linear systems exactly in N inner steps self._check(nonlin.KrylovJacobian, 20, 2, False, inner_m=10) self._check(nonlin.KrylovJacobian, 20, 2, True, inner_m=10) class TestJacobianDotSolve(object): """Check that solve/dot methods in Jacobian approximations are consistent""" def _func(self, x): return x**2 - 1 + np.dot(self.A, x) def _check_dot(self, jac_cls, complex=False, tol=1e-6, **kw): np.random.seed(123) N = 7 def rand(*a): q = np.random.rand(*a) if complex: q = q + 1j*np.random.rand(*a) return q def assert_close(a, b, msg): d = abs(a - b).max() f = tol + abs(b).max()*tol if d > f: raise AssertionError('%s: err %g' % (msg, d)) self.A = rand(N, N) # initialize x0 = np.random.rand(N) jac = jac_cls(**kw) jac.setup(x0, self._func(x0), self._func) # check consistency for k in xrange(2*N): v = rand(N) if hasattr(jac, '__array__'): Jd = np.array(jac) if hasattr(jac, 'solve'): Gv = jac.solve(v) Gv2 = np.linalg.solve(Jd, v) assert_close(Gv, Gv2, 'solve vs array') if hasattr(jac, 'rsolve'): Gv = jac.rsolve(v) Gv2 = np.linalg.solve(Jd.T.conj(), v) assert_close(Gv, Gv2, 'rsolve vs array') if hasattr(jac, 'matvec'): Jv = jac.matvec(v) Jv2 = np.dot(Jd, v) assert_close(Jv, Jv2, 'dot vs array') if hasattr(jac, 'rmatvec'): Jv = jac.rmatvec(v) Jv2 = np.dot(Jd.T.conj(), v) assert_close(Jv, Jv2, 'rmatvec vs array') if hasattr(jac, 'matvec') and hasattr(jac, 'solve'): Jv = jac.matvec(v) Jv2 = jac.solve(jac.matvec(Jv)) assert_close(Jv, Jv2, 'dot vs solve') if hasattr(jac, 'rmatvec') and hasattr(jac, 'rsolve'): Jv = jac.rmatvec(v) Jv2 = jac.rmatvec(jac.rsolve(Jv)) assert_close(Jv, Jv2, 'rmatvec vs rsolve') x = rand(N) jac.update(x, self._func(x)) def test_broyden1(self): self._check_dot(nonlin.BroydenFirst, complex=False) self._check_dot(nonlin.BroydenFirst, complex=True) def test_broyden2(self): self._check_dot(nonlin.BroydenSecond, complex=False) self._check_dot(nonlin.BroydenSecond, complex=True) def test_anderson(self): self._check_dot(nonlin.Anderson, complex=False) self._check_dot(nonlin.Anderson, complex=True) def test_diagbroyden(self): self._check_dot(nonlin.DiagBroyden, complex=False) self._check_dot(nonlin.DiagBroyden, complex=True) def test_linearmixing(self): self._check_dot(nonlin.LinearMixing, complex=False) self._check_dot(nonlin.LinearMixing, complex=True) def test_excitingmixing(self): self._check_dot(nonlin.ExcitingMixing, complex=False) self._check_dot(nonlin.ExcitingMixing, complex=True) def test_krylov(self): self._check_dot(nonlin.KrylovJacobian, complex=False, tol=1e-3) self._check_dot(nonlin.KrylovJacobian, complex=True, tol=1e-3) class TestNonlinOldTests(object): """ Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) """ def test_broyden1(self): x = nonlin.broyden1(F,F.xin,iter=12,alpha=1) assert_(nonlin.norm(x) < 1e-9) assert_(nonlin.norm(F(x)) < 1e-9) def test_broyden2(self): x = nonlin.broyden2(F,F.xin,iter=12,alpha=1) assert_(nonlin.norm(x) < 1e-9) assert_(nonlin.norm(F(x)) < 1e-9) def test_anderson(self): x = nonlin.anderson(F,F.xin,iter=12,alpha=0.03,M=5) assert_(nonlin.norm(x) < 0.33) def test_linearmixing(self): x = nonlin.linearmixing(F,F.xin,iter=60,alpha=0.5) assert_(nonlin.norm(x) < 1e-7) assert_(nonlin.norm(F(x)) < 1e-7) def test_exciting(self): x = nonlin.excitingmixing(F,F.xin,iter=20,alpha=0.5) assert_(nonlin.norm(x) < 1e-5) assert_(nonlin.norm(F(x)) < 1e-5) def test_diagbroyden(self): x = nonlin.diagbroyden(F,F.xin,iter=11,alpha=1) assert_(nonlin.norm(x) < 1e-8) assert_(nonlin.norm(F(x)) < 1e-8) def test_root_broyden1(self): res = root(F, F.xin, method='broyden1', options={'nit': 12, 'jac_options': {'alpha': 1}}) assert_(nonlin.norm(res.x) < 1e-9) assert_(nonlin.norm(res.fun) < 1e-9) def test_root_broyden2(self): res = root(F, F.xin, method='broyden2', options={'nit': 12, 'jac_options': {'alpha': 1}}) assert_(nonlin.norm(res.x) < 1e-9) assert_(nonlin.norm(res.fun) < 1e-9) def test_root_anderson(self): res = root(F, F.xin, method='anderson', options={'nit': 12, 'jac_options': {'alpha': 0.03, 'M': 5}}) assert_(nonlin.norm(res.x) < 0.33) def test_root_linearmixing(self): res = root(F, F.xin, method='linearmixing', options={'nit': 60, 'jac_options': {'alpha': 0.5}}) assert_(nonlin.norm(res.x) < 1e-7) assert_(nonlin.norm(res.fun) < 1e-7) def test_root_excitingmixing(self): res = root(F, F.xin, method='excitingmixing', options={'nit': 20, 'jac_options': {'alpha': 0.5}}) assert_(nonlin.norm(res.x) < 1e-5)<|fim▁hole|> def test_root_diagbroyden(self): res = root(F, F.xin, method='diagbroyden', options={'nit': 11, 'jac_options': {'alpha': 1}}) assert_(nonlin.norm(res.x) < 1e-8) assert_(nonlin.norm(res.fun) < 1e-8)<|fim▁end|>
assert_(nonlin.norm(res.fun) < 1e-5)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Interfaces and abstractions for filesystem access. We should be agnostic whether we're using a "temporary" file system, rooted in a local tmp dir, or whether we're using a true HDFS. This file defines the interface. Note that PEP 355 (Path - object oriented filesystem paths) did not pass. Many file system methods are in __builtin__, os, or os.path, and take strings representing filenames as arguments. We maintain this usage of paths as arguments. When possible, the interfaces here have fidelity to the native python interfaces. """ import __builtin__ import errno import grp import logging import os import posixpath import pwd import re import shutil import stat import sys # SEEK_SET and family is found in posixfile or os, depending on the python version if sys.version_info[:2] < (2, 5): import posixfile _tmp_mod = posixfile else: _tmp_mod = os SEEK_SET, SEEK_CUR, SEEK_END = _tmp_mod.SEEK_SET, _tmp_mod.SEEK_CUR, _tmp_mod.SEEK_END del _tmp_mod # The web (and POSIX) always uses forward slash as a separator LEADING_DOUBLE_SEPARATORS = re.compile("^" + posixpath.sep*2) def normpath(path): """ Eliminates double-slashes. Oddly, posixpath.normpath doesn't eliminate leading double slashes, but it does clean-up triple-slashes. """ p = posixpath.normpath(path) return LEADING_DOUBLE_SEPARATORS.sub(posixpath.sep, p) class IllegalPathException(Exception): pass class LocalSubFileSystem(object): """ Facade around normal python filesystem calls, for a temporary/local file system rooted in a root directory. This is intended for testing, and is not a secure chroot alternative. So far, this doesn't have a notion of current working dir, so all paths are "absolute". I dislike the state that having cwd's implies, but it may be convenient. TODO(philip): * chown: want to implement with names, not uids. * chmod * stat: perhaps implement "stats" which returns a dictionary; Hadoop and posix have different stats * set_replication: no equivalent * file-system level stats I think this covers all the functionality in "src/contrib/thriftfs/if/hadoopfs.thrift", but there may be some bits missing. The implementation of the file-like object for HDFS will be a bit tricky: open(f, "w") is generally the equivalent of createFile, but it has to handle the case where f already exists (in which case the best we can do is append, if that). """ def __init__(self, root): """ A file system rooted in root. """ self.root = root self.name = "file://%s" % self.root if not os.path.isdir(root): logging.fatal("Root(%s) not found." % root + " Perhaps you need to run manage.py create_test_fs") def _resolve_path(self, path): """ Returns path to use in native file system. """ # Strip leading "/" if not path.startswith("/"): raise IllegalPathException("Path %s must start with leading /." % path) path = path.lstrip("/") joined = os.path.join(self.root, path) absolute = os.path.abspath(joined) normalized = os.path.normpath(absolute) prefix = os.path.commonprefix([self.root, normalized]) if prefix != self.root: raise IllegalPathException("Path %s is not valid." % path) return joined def _unresolve_path(self, path): """ Given an absolute path within the wrapped filesystem, return the path that the user of this class sees. """ # Resolve it to make it realy absolute assert path.startswith(self.root) return path[len(self.root):] def _wrap(f, paths=None, users=None, groups=None): """ Wraps an existing function f, and transforms path arguments to "resolved paths" and user arguments to uids. By default transforms the first (zeroth) argument as a path, but can be customized. This lets us write: def open(self, name, mode="r"): return open(self._resolve_path(name), mode) as open = _wrap(__builtin__.open) NOTE: No transformation is done on the keyword args; they are not accepted. (The alternative would be to require the names of the keyword transformations.) """ if users is None: users = [] if groups is None: groups = [] if paths is None and 0 not in users and 0 not in groups: paths = [0] # complicated way of taking the intersection of three lists. assert not reduce(set.intersection, map(set, [paths, users, groups])) def wrapped(*args): self = args[0] newargs = list(args[1:]) for i in paths: newargs[i] = self._resolve_path(newargs[i]) for i in users: newargs[i] = pwd.getpwnam(newargs[i]).pw_uid for i in groups: newargs[i] = grp.getgrnam(newargs[i]).gr_gid return f(*newargs) return wrapped # These follow their namesakes. open = _wrap(__builtin__.open) remove = _wrap(os.remove) mkdir = _wrap(os.mkdir) rmdir = _wrap(os.rmdir) listdir = _wrap(os.listdir) rename = _wrap(os.rename, paths=[0,1]) exists = _wrap(os.path.exists) isfile = _wrap(os.path.isfile) isdir = _wrap(os.path.isdir) chmod = _wrap(os.chmod) # This could be provided with an error_handler rmtree = _wrap(shutil.rmtree) chown = _wrap(os.chown, paths=[0], users=[1], groups=[2]) @property def uri(self): return self.name def stats(self, path, raise_on_fnf=True): path = self._resolve_path(path) try: statobj = os.stat(path) except OSError, ose: if ose.errno == errno.ENOENT and not raise_on_fnf: return None raise ret = dict() ret["path"] = self._unresolve_path(path) ret["size"] = statobj[stat.ST_SIZE] ret["mtime"] = statobj[stat.ST_MTIME] ret["mode"] = statobj[stat.ST_MODE] ret["user"] = pwd.getpwuid(statobj[stat.ST_UID]).pw_name ret["group"] = grp.getgrgid(statobj[stat.ST_GID]).gr_name return ret def setuser(self, user, groups=None): pass def status(self): return FakeStatus() def listdir_stats(self, path): """ This is an equivalent of listdir that, instead of returning file names, returns a list of stats instead. """ listdir_files = self.listdir(path) paths = [posixpath.join(path, f) for f in listdir_files] return [self.stats(path) for path in paths] def __repr__(self): return "LocalFileSystem(%s)" % repr(self.root) class FakeStatus(object): """ A fake implementation of HDFS health RPCs.<|fim▁hole|> because they will be encoded as JSON. """ def get_messages(self): """Warnings/lint checks.""" return [ dict(type="WARNING",message="All your base belong to us."), dict(type="INFO", message="Hamster Dance!") ] def get_health(self): o = dict() GB = 1024*1024*1024 o["bytesTotal"] = 5*GB o["bytesUsed"] = 5*GB/2 o["bytesRemaining"] = 2*GB o["bytesNonDfs"] = GB/2 o["liveDataNodes"] = 13 o["deadDataNodes"] = 2 o["upgradeStatus"] = dict(version=13, percentComplete=100, finalized=True) return o def get_datanode_report(self): r = [] for i in range(0, 13): dinfo = dict() dinfo["name"] = "fake-%d" % i dinfo["storageID"] = "fake-id-%d" % i dinfo["host"] = "fake-host-%d" % i dinfo["capacity"] = 123456789 dinfo["dfsUsed"] = 23456779 dinfo["remaining"] = 100000010 dinfo["xceiverCount"] = 3 dinfo["state"] = "NORMAL_STATE" r.append(dinfo) for i in range(0, 2): dinfo = dict() dinfo["name"] = "fake-dead-%d" % i dinfo["storageID"] = "fake-dead-id-%d" % i dinfo["host"] = "fake-dead-host-%d" % i dinfo["capacity"] = 523456789 dinfo["dfsUsed"] = 23456779 dinfo["remaining"] = 500000010 dinfo["xceiverCount"] = 3 dinfo["state"] = "DECOMISSION_INPROGRESS" r.append(dinfo) return r<|fim▁end|>
These follow the thrift naming conventions, but return dicts or arrays of dicts,
<|file_name|>sync.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt $.extend(frappe.model, { docinfo: {}, sync: function(r) { /* docs: extract docs, docinfo (attachments, comments, assignments) from incoming request and set in `locals` and `frappe.model.docinfo` */ var isPlain; if(!r.docs && !r.docinfo) r = {docs:r}; isPlain = $.isPlainObject(r.docs); if(isPlain) r.docs = [r.docs]; if(r.docs) { var last_parent_name = null; for(var i=0, l=r.docs.length; i<l; i++) { var d = r.docs[i]; frappe.model.add_to_locals(d); d.__last_sync_on = new Date(); if(d.doctype==="DocType") { frappe.meta.sync(d); } if(cur_frm && cur_frm.doctype==d.doctype && cur_frm.docname==d.name) { cur_frm.doc = d; } if(d.localname) { frappe.model.new_names[d.localname] = d.name; $(document).trigger('rename', [d.doctype, d.localname, d.name]); delete locals[d.doctype][d.localname]; // update docinfo to new dict keys if(i===0) { frappe.model.docinfo[d.doctype][d.name] = frappe.model.docinfo[d.doctype][d.localname]; frappe.model.docinfo[d.doctype][d.localname] = undefined;<|fim▁hole|> } } if(cur_frm && isPlain) cur_frm.dirty(); } // set docinfo (comments, assign, attachments) if(r.docinfo) { if(r.docs) { var doc = r.docs[0]; } else { if(cur_frm) var doc = cur_frm.doc; } if(doc) { if(!frappe.model.docinfo[doc.doctype]) frappe.model.docinfo[doc.doctype] = {}; frappe.model.docinfo[doc.doctype][doc.name] = r.docinfo; } } return r.docs; }, add_to_locals: function(doc) { if(!locals[doc.doctype]) locals[doc.doctype] = {}; if(!doc.name && doc.__islocal) { // get name (local if required) if(!doc.parentfield) frappe.model.clear_doc(doc); doc.name = frappe.model.get_new_name(doc.doctype); if(!doc.parentfield) frappe.provide("frappe.model.docinfo." + doc.doctype + "." + doc.name); } locals[doc.doctype][doc.name] = doc; // add child docs to locals if(!doc.parentfield) { for(var i in doc) { var value = doc[i]; if($.isArray(value)) { for (var x=0, y=value.length; x < y; x++) { var d = value[x]; if(!d.parent) d.parent = doc.name; frappe.model.add_to_locals(d); } } } } } });<|fim▁end|>
}
<|file_name|>icon.ts<|end_file_name|><|fim▁begin|>// (C) Copyright 2015 Moodle Pty 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. import { Component, Input, OnChanges, OnDestroy, ElementRef, SimpleChange } from '@angular/core'; import { Config } from 'ionic-angular'; /** * Core Icon is a component that enabled a posibility to add fontawesome icon to the html. It's recommended if both fontawesome * or ionicons can be used in the name attribute. To use fontawesome just place the full icon name with the fa- prefix and * the component will detect it. * Check available icons https://fontawesome.com/v4.7.0/icons/. */ @Component({ selector: 'core-icon', templateUrl: 'core-icon.html', }) export class CoreIconComponent implements OnChanges, OnDestroy { // Common params. @Input() name: string; @Input('color') color?: string; @Input('slash') slash?: boolean; // Display a red slash over the icon. // Ionicons params. @Input('isActive') isActive?: boolean; @Input('md') md?: string; @Input('ios') ios?: string; // FontAwesome params. @Input('fixed-width') fixedWidth: string; @Input('label') ariaLabel?: string; @Input() flipRtl?: boolean; // Whether to flip the icon in RTL. Defaults to false. protected element: HTMLElement; protected newElement: HTMLElement; constructor(el: ElementRef, private config: Config) { this.element = el.nativeElement; } /** * Detect changes on input properties. */ ngOnChanges(changes: {[name: string]: SimpleChange}): void { if (!changes.name || !this.name) { return; } const oldElement = this.newElement ? this.newElement : this.element; // Use a new created element to avoid ion-icon working. // This is necessary to make the FontAwesome stuff work. // It is also required to stop Ionic overriding the aria-label attribute. this.newElement = document.createElement('ion-icon'); if (this.name.startsWith('fa-')) { this.newElement.classList.add('icon'); this.newElement.classList.add('fa'); this.newElement.classList.add(this.name); if (this.isTrueProperty(this.fixedWidth)) { this.newElement.classList.add('fa-fw'); } if (this.color) { this.newElement.classList.add('fa-' + this.color); } } else { const mode = this.config.get('iconMode'); this.newElement.classList.add('icon'); this.newElement.classList.add('icon-' + mode); this.newElement.classList.add('ion-' + mode + '-' + this.name); } !this.ariaLabel && this.newElement.setAttribute('aria-hidden', 'true'); !this.ariaLabel && this.newElement.setAttribute('role', 'presentation'); this.ariaLabel && this.newElement.setAttribute('aria-label', this.ariaLabel); this.ariaLabel && this.newElement.setAttribute('title', this.ariaLabel); const attrs = this.element.attributes;<|fim▁hole|> const classes = attrs[i].value.split(' '); for (let j = 0; j < classes.length; j++) { if (classes[j]) { this.newElement.classList.add(classes[j]); } } } } else { this.newElement.setAttribute(attrs[i].name, attrs[i].value); } } if (this.slash) { this.newElement.classList.add('icon-slash'); } if (this.flipRtl) { this.newElement.classList.add('core-icon-dir-flip'); } oldElement.parentElement.replaceChild(this.newElement, oldElement); } /** * Check if the value is true or on. * * @param val value to be checked. * @return If has a value equivalent to true. */ isTrueProperty(val: any): boolean { if (typeof val === 'string') { val = val.toLowerCase().trim(); return (val === 'true' || val === 'on' || val === ''); } return !!val; } /** * Component destroyed. */ ngOnDestroy(): void { if (this.newElement) { this.newElement.remove(); } } }<|fim▁end|>
for (let i = attrs.length - 1; i >= 0; i--) { if (attrs[i].name == 'class') { // We don't want to override the classes we already added. Add them one by one. if (attrs[i].value) {
<|file_name|>template.py<|end_file_name|><|fim▁begin|># Copyright (C) 2007-2010 Samuel Abels. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2, as # published by the Free Software Foundation. # # 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 """ Executing Exscript templates on a connection. """ from Exscript import stdlib from Exscript.interpreter import Parser def _compile(conn, filename, template, parser_kwargs, **kwargs): if conn: hostname = conn.get_host() account = conn.last_account username = account is not None and account.get_name() or None else: hostname = 'undefined' username = None # Init the parser. parser = Parser(**parser_kwargs) parser.define(**kwargs) # Define the built-in variables and functions. builtin = dict(__filename__ = [filename or 'undefined'], __username__ = [username], __hostname__ = [hostname], __connection__ = conn) parser.define_object(**builtin) parser.define_object(**stdlib.functions) # Compile the template. return parser.parse(template, builtin.get('__filename__')[0]) def _run(conn, filename, template, parser_kwargs, **kwargs): compiled = _compile(conn, filename, template, parser_kwargs, **kwargs) return compiled.execute() def test(string, **kwargs): """ Compiles the given template, and raises an exception if that failed. Does nothing otherwise. @type string: string @param string: The template to compile. @type kwargs: dict @param kwargs: Variables to define in the template. """ _compile(None, None, string, {}, **kwargs) def test_secure(string, **kwargs): """ Like test(), but makes sure that each function that is used in the template has the Exscript.stdlib.util.safe_function decorator. Raises Exscript.interpreter.Exception.PermissionError if any function lacks the decorator. @type string: string @param string: The template to compile. @type kwargs: dict @param kwargs: Variables to define in the template. """ _compile(None, None, string, {'secure': True}, **kwargs) def test_file(filename, **kwargs): """ Convenience wrapper around test() that reads the template from a file instead. @type filename: string @param filename: The name of the template file. @type kwargs: dict @param kwargs: Variables to define in the template. """ _compile(None, filename, open(filename).read(), {}, **kwargs) def eval(conn, string, strip_command = True, **kwargs): """ Compiles the given template and executes it on the given connection. Raises an exception if the compilation fails. if strip_command is True, the first line of each response that is received after any command sent by the template is stripped. For example, consider the following template:: ls -1{extract /(\S+)/ as filenames} {loop filenames as filename} touch $filename {end} If strip_command is False, the response, (and hence, the `filenames' variable) contains the following:: ls -1 myfile myfile2 [...] By setting strip_command to True, the first line is ommitted. @type conn: Exscript.protocols.Protocol @param conn: The connection on which to run the template. @type string: string @param string: The template to compile. @type strip_command: bool @param strip_command: Whether to strip the command echo from the response. @type kwargs: dict @param kwargs: Variables to define in the template. @rtype: dict @return: The variables that are defined after execution of the script. """ parser_args = {'strip_command': strip_command} return _run(conn, None, string, parser_args, **kwargs) def eval_file(conn, filename, strip_command = True, **kwargs): """ Convenience wrapper around eval() that reads the template from a file instead. @type conn: Exscript.protocols.Protocol @param conn: The connection on which to run the template. @type filename: string @param filename: The name of the template file. @type strip_command: bool<|fim▁hole|> @type kwargs: dict @param kwargs: Variables to define in the template. """ template = open(filename, 'r').read() parser_args = {'strip_command': strip_command} return _run(conn, filename, template, parser_args, **kwargs) def paste(conn, string, **kwargs): """ Compiles the given template and executes it on the given connection. This function differs from eval() such that it does not wait for a prompt after sending each command to the connected host. That means that the script can no longer read the response of the host, making commands such as `extract' or `set_prompt' useless. The function raises an exception if the compilation fails, or if the template contains a command that requires a response from the host. @type conn: Exscript.protocols.Protocol @param conn: The connection on which to run the template. @type string: string @param string: The template to compile. @type kwargs: dict @param kwargs: Variables to define in the template. @rtype: dict @return: The variables that are defined after execution of the script. """ return _run(conn, None, string, {'no_prompt': True}, **kwargs) def paste_file(conn, filename, **kwargs): """ Convenience wrapper around paste() that reads the template from a file instead. @type conn: Exscript.protocols.Protocol @param conn: The connection on which to run the template. @type filename: string @param filename: The name of the template file. @type kwargs: dict @param kwargs: Variables to define in the template. """ template = open(filename, 'r').read() return _run(conn, None, template, {'no_prompt': True}, **kwargs)<|fim▁end|>
@param strip_command: Whether to strip the command echo from the response.
<|file_name|>make_appimage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function try: from configparser import RawConfigParser except ImportError: from ConfigParser import RawConfigParser import glob import os import shutil import subprocess import sys config = RawConfigParser(allow_no_value=True) config.read(os.path.join('gridsync', 'resources', 'config.txt')) settings = {} for section in config.sections(): if section not in settings: settings[section] = {} for option, value in config.items(section): settings[section][option] = value name = settings['application']['name'] name_lower = name.lower() linux_icon = settings['build']['linux_icon'] appdir_usr = os.path.join('build', 'AppDir', 'usr') appdir_bin = os.path.join(appdir_usr, 'bin') try: os.makedirs(appdir_usr) except OSError:<|fim▁hole|> shutil.copytree(os.path.join('dist', name), appdir_bin) except OSError: pass _, ext = os.path.splitext(linux_icon) icon_filepath = os.path.abspath(os.path.join('build', name_lower + ext)) shutil.copy2(linux_icon, icon_filepath) desktop_filepath = os.path.join('build', '{}.desktop'.format(name)) with open(desktop_filepath, 'w') as f: f.write('''[Desktop Entry] Categories=Utility; Type=Application Name={0} Exec={1} Icon={1} '''.format(name, name_lower) ) os.environ['LD_LIBRARY_PATH'] = appdir_bin os.environ['APPIMAGE_EXTRACT_AND_RUN'] = '1' linuxdeploy_args = [ 'linuxdeploy', '--appdir=build/AppDir', '--executable={}'.format(os.path.join(appdir_usr, 'bin', name_lower)), '--icon-file={}'.format(icon_filepath), '--desktop-file={}'.format(desktop_filepath), ] try: returncode = subprocess.call(linuxdeploy_args) except OSError: sys.exit( 'ERROR: `linuxdeploy` utility not found. Please ensure that it is ' 'on your $PATH and executable as `linuxdeploy` and try again.\n' '`linuxdeploy` can be downloaded from https://github.com/linuxdeploy/' 'linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage' ) if returncode: # XXX Ugly hack/workaround for "ERROR: Strip call failed: /tmp/.mount_linuxdns8a8k/usr/bin/strip: unable to copy file 'build/AppDir/usr/lib/libpython3.7m.so.1.0'; reason: Permission denied" observed on Travis-CI os.chmod(glob.glob('build/AppDir/usr/lib/libpython*.so.*')[0], 0o755) subprocess.call(linuxdeploy_args) for file in sorted(os.listdir(appdir_bin)): # The `linuxdeploy` utility adds a copy of each library to AppDir/usr/lib, # however, the main PyInstaller-generated ("gridsync") executable expects # these libraries to be located in the same directory as the ("gridsync") # executable itself (resulting in *two* copies of each library and thus # wasted disk-space); removing the copies inserted by `linuxdeploy` -- and # and replacing them with symlinks to the originals -- saves disk-space. dst = 'build/AppDir/usr/lib/{}'.format(file) if os.path.exists(dst): try: os.remove(dst) except OSError: print('WARNING: Could not remove file {}'.format(dst)) continue src = '../bin/{}'.format(file) print('Creating symlink: {} -> {}'.format(dst, src)) try: os.symlink(src, dst) except OSError: print('WARNING: Could not create symlink for {}'.format(dst)) os.remove('build/AppDir/AppRun') with open('build/AppDir/AppRun', 'w') as f: f.write('''#!/bin/sh exec "$(dirname "$(readlink -e "$0")")/usr/bin/{}" "$@" '''.format(name_lower) ) os.chmod('build/AppDir/AppRun', 0o755) # Create the .DirIcon symlink here/now to prevent appimagetool from # doing it later, thereby allowing the atime and mtime of the symlink # to be overriden along with all of the other files in the AppDir. try: os.symlink(os.path.basename(icon_filepath), "build/AppDir/.DirIcon") except OSError: pass subprocess.call(["python3", "scripts/update_permissions.py", "build/AppDir"]) subprocess.call(["python3", "scripts/update_timestamps.py", "build/AppDir"]) try: os.mkdir('dist') except OSError: pass try: subprocess.call([ 'appimagetool', 'build/AppDir', 'dist/{}.AppImage'.format(name) ]) except OSError: sys.exit( 'ERROR: `appimagetool` utility not found. Please ensure that it is ' 'on your $PATH and executable as `appimagetool` and try again.\n' '`appimagetool` can be downloaded from https://github.com/AppImage/A' 'ppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage' )<|fim▁end|>
pass try:
<|file_name|>_peering_service_prefixes_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # 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. # -------------------------------------------------------------------------- from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class PeeringServicePrefixesOperations: """PeeringServicePrefixesOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.peering.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, peering_service_name: str, prefix_name: str, **kwargs ) -> "_models.PeeringServicePrefix": """Gets the peering service prefix. :param resource_group_name: The resource group name. :type resource_group_name: str :param peering_service_name: The peering service name. :type peering_service_name: str :param prefix_name: The prefix name. :type prefix_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PeeringServicePrefix, or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefix"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-08-01-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore async def create_or_update( self, resource_group_name: str, peering_service_name: str, prefix_name: str, peering_service_prefix: "_models.PeeringServicePrefix", **kwargs ) -> "_models.PeeringServicePrefix": """Creates or updates the peering prefix.<|fim▁hole|> :type resource_group_name: str :param peering_service_name: The peering service name. :type peering_service_name: str :param prefix_name: The prefix name. :type prefix_name: str :param peering_service_prefix: The IP prefix for an peering. :type peering_service_prefix: ~azure.mgmt.peering.models.PeeringServicePrefix :keyword callable cls: A custom type or function that will be passed the direct response :return: PeeringServicePrefix, or the result of cls(response) :rtype: ~azure.mgmt.peering.models.PeeringServicePrefix :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.PeeringServicePrefix"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-08-01-preview" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(peering_service_prefix, 'PeeringServicePrefix') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('PeeringServicePrefix', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore async def delete( self, resource_group_name: str, peering_service_name: str, prefix_name: str, **kwargs ) -> None: """removes the peering prefix. :param resource_group_name: The resource group name. :type resource_group_name: str :param peering_service_name: The peering service name. :type peering_service_name: str :param prefix_name: The prefix name. :type prefix_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-08-01-preview" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'peeringServiceName': self._serialize.url("peering_service_name", peering_service_name, 'str'), 'prefixName': self._serialize.url("prefix_name", prefix_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Peering/peeringServices/{peeringServiceName}/prefixes/{prefixName}'} # type: ignore<|fim▁end|>
:param resource_group_name: The resource group name.
<|file_name|>ZonePlanningLayers.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import renderOrder from '../renderOrder'; import { RenderLayer } from '../browser_utils/Utils'; import { SharedState } from '../citybound'; import { shadersForLandUses } from './stripedShaders'; import colors from '../colors'; export const LAND_USES = [ "Residential", "Commercial", "Industrial", "Agricultural", "Recreational", "Administrative", ]; const landUseInstances = new Map(LAND_USES.map(landUse => [landUse, new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors[landUse]])])); const buildingOutlinesInstance = new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors.buildingOutlines]); export function ZonePlanningLayers({ state }: { state: SharedState; }) { const { zoneGroups, zoneOutlineGroups, buildingOutlinesGroup } = state.planning.rendering.currentPreview; return <> {[...zoneGroups.entries()].map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZones} decal={true} batches={[...groups.values()].map(groupMesh => ({ mesh: groupMesh, instances: landUseInstances.get(landUse) }))} />)} {[...zoneGroups.entries()].reverse().map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZonesStipple} decal={true} shader={shadersForLandUses[landUse]} batches={[...groups.values()].map(groupMesh => ({ mesh: groupMesh, instances: landUseInstances.get(landUse)<|fim▁hole|> instances: landUseInstances.get(landUse) }))} />)} <RenderLayer renderOrder={renderOrder.buildingOutlines} decal={true} batches={[...buildingOutlinesGroup.values()].map(groupMesh => ({ mesh: groupMesh, instances: buildingOutlinesInstance }))} /> </>; }<|fim▁end|>
}))} />)} {[...zoneOutlineGroups.entries()].map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZonesOutlines} decal={true} batches={[...groups.values()].map(groupMesh => ({ mesh: groupMesh,
<|file_name|>UseCountingXMLReaderWrapper.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2016-2017 Mozilla Foundation * * 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. * */ package nu.validator.xml; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException;<|fim▁hole|> implements XMLReader, ContentHandler { private final XMLReader wrappedReader; private ContentHandler contentHandler; private ErrorHandler errorHandler; private HttpServletRequest request; private StringBuilder documentContent; private boolean inBody; private boolean loggedLinkWithCharset; private boolean loggedScriptWithCharset; private boolean loggedStyleInBody; private boolean loggedRelAlternate; private boolean loggedRelAuthor; private boolean loggedRelBookmark; private boolean loggedRelCanonical; private boolean loggedRelDnsPrefetch; private boolean loggedRelExternal; private boolean loggedRelHelp; private boolean loggedRelIcon; private boolean loggedRelLicense; private boolean loggedRelNext; private boolean loggedRelNofollow; private boolean loggedRelNoopener; private boolean loggedRelNoreferrer; private boolean loggedRelPingback; private boolean loggedRelPreconnect; private boolean loggedRelPrefetch; private boolean loggedRelPreload; private boolean loggedRelPrerender; private boolean loggedRelPrev; private boolean loggedRelSearch; private boolean loggedRelServiceworker; private boolean loggedRelStylesheet; private boolean loggedRelTag; public UseCountingXMLReaderWrapper(XMLReader wrappedReader, HttpServletRequest request) { this.wrappedReader = wrappedReader; this.contentHandler = wrappedReader.getContentHandler(); this.request = request; this.inBody = false; this.loggedLinkWithCharset = false; this.loggedScriptWithCharset = false; this.loggedStyleInBody = false; this.loggedRelAlternate = false; this.loggedRelAuthor = false; this.loggedRelBookmark = false; this.loggedRelCanonical = false; this.loggedRelAlternate = false; this.loggedRelAuthor = false; this.loggedRelBookmark = false; this.loggedRelCanonical = false; this.loggedRelDnsPrefetch = false; this.loggedRelExternal = false; this.loggedRelHelp = false; this.loggedRelIcon = false; this.loggedRelLicense = false; this.loggedRelNext = false; this.loggedRelNofollow = false; this.loggedRelNoopener = false; this.loggedRelNoreferrer = false; this.loggedRelPingback = false; this.loggedRelPreconnect = false; this.loggedRelPrefetch = false; this.loggedRelPreload = false; this.loggedRelPrerender = false; this.loggedRelPrev = false; this.loggedRelSearch = false; this.loggedRelServiceworker = false; this.loggedRelStylesheet = false; this.loggedRelTag = false; this.documentContent = new StringBuilder(); wrappedReader.setContentHandler(this); } /** * @see org.xml.sax.helpers.XMLFilterImpl#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (contentHandler == null) { return; } contentHandler.characters(ch, start, length); } /** * @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String, * java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (contentHandler == null) { return; } contentHandler.endElement(uri, localName, qName); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startDocument() */ @Override public void startDocument() throws SAXException { if (contentHandler == null) { return; } documentContent.setLength(0); contentHandler.startDocument(); } /** * @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (contentHandler == null) { return; } if ("link".equals(localName)) { boolean hasAppleTouchIcon = false; boolean hasSizes = false; for (int i = 0; i < atts.getLength(); i++) { if ("rel".equals(atts.getLocalName(i))) { if (atts.getValue(i).contains("apple-touch-icon")) { hasAppleTouchIcon = true; } } else if ("sizes".equals(atts.getLocalName(i))) { hasSizes = true; } else if ("charset".equals(atts.getLocalName(i)) && !loggedLinkWithCharset) { loggedLinkWithCharset = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/link-with-charset-found", true); } } } if (request != null && hasAppleTouchIcon && hasSizes) { request.setAttribute( "http://validator.nu/properties/apple-touch-icon-with-sizes-found", true); } } else if ("script".equals(localName) && !loggedScriptWithCharset) { for (int i = 0; i < atts.getLength(); i++) { if ("charset".equals(atts.getLocalName(i))) { loggedScriptWithCharset = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/script-with-charset-found", true); } } } } else if (inBody && "style".equals(localName) && !loggedStyleInBody) { loggedStyleInBody = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/style-in-body-found", true); } } if (atts.getIndex("", "rel") > -1 && ("link".equals(localName) || "a".equals(localName))) { List<String> relValues = Arrays.asList( atts.getValue("", "rel").trim().toLowerCase() // .split("\\s+")); if (relValues.contains("alternate") && !loggedRelAlternate) { loggedRelAlternate = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-alternate-found", true); } } if (relValues.contains("author") && !loggedRelAuthor) { loggedRelAuthor = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-author-found", true); } } if (relValues.contains("bookmark") && !loggedRelBookmark) { loggedRelBookmark = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-bookmark-found", true); } } if (relValues.contains("canonical") && !loggedRelCanonical) { loggedRelCanonical = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-canonical-found", true); } } if (relValues.contains("dns-prefetch") && !loggedRelDnsPrefetch) { loggedRelDnsPrefetch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-dns-prefetch-found", true); } } if (relValues.contains("external") && !loggedRelExternal) { loggedRelExternal = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-external-found", true); } } if (relValues.contains("help") && !loggedRelHelp) { loggedRelHelp = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-help-found", true); } } if (relValues.contains("icon") && !loggedRelIcon) { loggedRelIcon = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-icon-found", true); } } if (relValues.contains("license") && !loggedRelLicense) { loggedRelLicense = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-license-found", true); } } if (relValues.contains("next") && !loggedRelNext) { loggedRelNext = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-next-found", true); } } if (relValues.contains("nofollow") && !loggedRelNofollow) { loggedRelNofollow = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-nofollow-found", true); } } if (relValues.contains("noopener") && !loggedRelNoopener) { loggedRelNoopener = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-noopener-found", true); } } if (relValues.contains("noreferrer") && !loggedRelNoreferrer) { loggedRelNoreferrer = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-noreferrer-found", true); } } if (relValues.contains("pingback") && !loggedRelPingback) { loggedRelPingback = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-pingback-found", true); } } if (relValues.contains("preconnect") && !loggedRelPreconnect) { loggedRelPreconnect = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-preconnect-found", true); } } if (relValues.contains("prefetch") && !loggedRelPrefetch) { loggedRelPrefetch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prefetch-found", true); } } if (relValues.contains("preload") && !loggedRelPreload) { loggedRelPreload = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-preload-found", true); } } if (relValues.contains("prerender") && !loggedRelPrerender) { loggedRelPrerender = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prerender-found", true); } } if (relValues.contains("prev") && !loggedRelPrev) { loggedRelPrev = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-prev-found", true); } } if (relValues.contains("search") && !loggedRelSearch) { loggedRelSearch = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-search-found", true); } } if (relValues.contains("serviceworker") && !loggedRelServiceworker) { loggedRelServiceworker = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-serviceworker-found", true); } } if (relValues.contains("stylesheet") && !loggedRelStylesheet) { loggedRelStylesheet = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-stylesheet-found", true); } } if (relValues.contains("tag") && !loggedRelTag) { loggedRelTag = true; if (request != null) { request.setAttribute( "http://validator.nu/properties/rel-tag-found", true); } } } contentHandler.startElement(uri, localName, qName, atts); } /** * @see org.xml.sax.helpers.XMLFilterImpl#setDocumentLocator(org.xml.sax.Locator) */ @Override public void setDocumentLocator(Locator locator) { if (contentHandler == null) { return; } contentHandler.setDocumentLocator(locator); } @Override public ContentHandler getContentHandler() { return contentHandler; } /** * @throws SAXException * @see org.xml.sax.ContentHandler#endDocument() */ @Override public void endDocument() throws SAXException { if (contentHandler == null) { return; } contentHandler.endDocument(); } /** * @param prefix * @throws SAXException * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ @Override public void endPrefixMapping(String prefix) throws SAXException { if (contentHandler == null) { return; } contentHandler.endPrefixMapping(prefix); } /** * @param ch * @param start * @param length * @throws SAXException * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (contentHandler == null) { return; } contentHandler.ignorableWhitespace(ch, start, length); } /** * @param target * @param data * @throws SAXException * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, * java.lang.String) */ @Override public void processingInstruction(String target, String data) throws SAXException { if (contentHandler == null) { return; } contentHandler.processingInstruction(target, data); } /** * @param name * @throws SAXException * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ @Override public void skippedEntity(String name) throws SAXException { if (contentHandler == null) { return; } contentHandler.skippedEntity(name); } /** * @param prefix * @param uri * @throws SAXException * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, * java.lang.String) */ @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { if (contentHandler == null) { return; } contentHandler.startPrefixMapping(prefix, uri); } /** * @return * @see org.xml.sax.XMLReader#getDTDHandler() */ @Override public DTDHandler getDTDHandler() { return wrappedReader.getDTDHandler(); } /** * @return * @see org.xml.sax.XMLReader#getEntityResolver() */ @Override public EntityResolver getEntityResolver() { return wrappedReader.getEntityResolver(); } /** * @return * @see org.xml.sax.XMLReader#getErrorHandler() */ @Override public ErrorHandler getErrorHandler() { return errorHandler; } /** * @param name * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#getFeature(java.lang.String) */ @Override public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return wrappedReader.getFeature(name); } /** * @param name * @return * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#getProperty(java.lang.String) */ @Override public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return wrappedReader.getProperty(name); } /** * @param input * @throws IOException * @throws SAXException * @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource) */ @Override public void parse(InputSource input) throws IOException, SAXException { wrappedReader.parse(input); } /** * @param systemId * @throws IOException * @throws SAXException * @see org.xml.sax.XMLReader#parse(java.lang.String) */ @Override public void parse(String systemId) throws IOException, SAXException { wrappedReader.parse(systemId); } /** * @param handler * @see org.xml.sax.XMLReader#setContentHandler(org.xml.sax.ContentHandler) */ @Override public void setContentHandler(ContentHandler handler) { contentHandler = handler; } /** * @param handler * @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler) */ @Override public void setDTDHandler(DTDHandler handler) { wrappedReader.setDTDHandler(handler); } /** * @param resolver * @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver) */ @Override public void setEntityResolver(EntityResolver resolver) { wrappedReader.setEntityResolver(resolver); } /** * @param handler * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ @Override public void setErrorHandler(ErrorHandler handler) { wrappedReader.setErrorHandler(handler); } /** * @param name * @param value * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean) */ @Override public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { wrappedReader.setFeature(name, value); } /** * @param name * @param value * @throws SAXNotRecognizedException * @throws SAXNotSupportedException * @see org.xml.sax.XMLReader#setProperty(java.lang.String, * java.lang.Object) */ @Override public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { wrappedReader.setProperty(name, value); } }<|fim▁end|>
import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; public final class UseCountingXMLReaderWrapper
<|file_name|>tap.py<|end_file_name|><|fim▁begin|># -*- test-case-name: twisted.names.test.test_tap -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Domain Name Server """ import os, traceback from twisted.python import usage from twisted.names import dns from twisted.application import internet, service from twisted.names import server from twisted.names import authority from twisted.names import secondary class Options(usage.Options): optParameters = [ ["interface", "i", "", "The interface to which to bind"], ["port", "p", "53", "The port on which to listen"], ["resolv-conf", None, None, "Override location of resolv.conf (implies --recursive)"], ["hosts-file", None, None, "Perform lookups with a hosts file"], ] optFlags = [ ["cache", "c", "Enable record caching"], ["recursive", "r", "Perform recursive lookups"], ["verbose", "v", "Log verbosely"], ] compData = usage.Completions( optActions={"interface" : usage.CompleteNetInterfaces()} ) zones = None zonefiles = None def __init__(self): usage.Options.__init__(self) self['verbose'] = 0 self.bindfiles = [] self.zonefiles = [] self.secondaries = [] def opt_pyzone(self, filename): """Specify the filename of a Python syntax zone definition""" if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.zonefiles.append(filename) def opt_bindzone(self, filename): """Specify the filename of a BIND9 syntax zone definition""" if not os.path.exists(filename): raise usage.UsageError(filename + ": No such file") self.bindfiles.append(filename) def opt_secondary(self, ip_domain): """Act as secondary for the specified domain, performing zone transfers from the specified IP (IP/domain) """ args = ip_domain.split('/', 1) if len(args) != 2: raise usage.UsageError("Argument must be of the form IP[:port]/domain") address = args[0].split(':') if len(address) == 1: address = (address[0], dns.PORT) else: try: port = int(address[1]) except ValueError: raise usage.UsageError( "Specify an integer port number, not %r" % (address[1],)) address = (address[0], port) self.secondaries.append((address, [args[1]])) def opt_verbose(self): """Increment verbosity level""" self['verbose'] += 1 def postOptions(self): if self['resolv-conf']: self['recursive'] = True self.svcs = [] self.zones = [] for f in self.zonefiles: try: self.zones.append(authority.PySourceAuthority(f)) except Exception: traceback.print_exc() raise usage.UsageError("Invalid syntax in " + f) for f in self.bindfiles: try: self.zones.append(authority.BindAuthority(f)) except Exception: traceback.print_exc() raise usage.UsageError("Invalid syntax in " + f) for f in self.secondaries: svc = secondary.SecondaryAuthorityService.fromServerAddressAndDomains(*f) self.svcs.append(svc) self.zones.append(self.svcs[-1].getAuthority()) try: self['port'] = int(self['port']) except ValueError: raise usage.UsageError("Invalid port: %r" % (self['port'],))<|fim▁hole|>def _buildResolvers(config): """ Build DNS resolver instances in an order which leaves recursive resolving as a last resort. @type config: L{Options} instance @param config: Parsed command-line configuration @return: Two-item tuple of a list of cache resovers and a list of client resolvers """ from twisted.names import client, cache, hosts ca, cl = [], [] if config['cache']: ca.append(cache.CacheResolver(verbose=config['verbose'])) if config['hosts-file']: cl.append(hosts.Resolver(file=config['hosts-file'])) if config['recursive']: cl.append(client.createResolver(resolvconf=config['resolv-conf'])) return ca, cl def makeService(config): ca, cl = _buildResolvers(config) f = server.DNSServerFactory(config.zones, ca, cl, config['verbose']) p = dns.DNSDatagramProtocol(f) f.noisy = 0 ret = service.MultiService() for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]: s = klass(config['port'], arg, interface=config['interface']) s.setServiceParent(ret) for svc in config.svcs: svc.setServiceParent(ret) return ret<|fim▁end|>
<|file_name|>range.test.js<|end_file_name|><|fim▁begin|>import { createRangeFromZeroTo } from '../../helpers/utils/range' describe('utils range', () => { describe('createRangeFromZeroTo range 2', () => { const range = createRangeFromZeroTo(2) it('return the array 0 to 1', () => { expect(range).toEqual([0, 1]) }) }) describe('createRangeFromZeroTo range 7', () => { const range = createRangeFromZeroTo(7) it('return the array 0 to 6', () => { expect(range).toEqual([0, 1, 2, 3, 4, 5, 6]) }) }) describe('createRangeFromZeroTo range 1', () => { const range = createRangeFromZeroTo(1) <|fim▁hole|> expect(range).toEqual([0]) }) }) describe('createRangeFromZeroTo range 0', () => { const range = createRangeFromZeroTo(0) it('return the array empty', () => { expect(range).toEqual([]) }) }) describe('createRangeFromZeroTo range undefined', () => { const range = createRangeFromZeroTo() it('return the array empty', () => { expect(range).toEqual([]) }) }) describe('createRangeFromZeroTo range string', () => { const range = createRangeFromZeroTo('toto') it('return the array empty', () => { expect(range).toEqual([]) }) }) })<|fim▁end|>
it('return the array 0', () => {
<|file_name|>day_5.rs<|end_file_name|><|fim▁begin|>use std::boxed::Box; use std::ptr::Shared; use std::option::Option; struct Node { elem: i32, next: Option<Box<Node>> } impl Node { fn new(e: i32) -> Node { Node { elem: e, next: None } } } #[derive(Default)] pub struct Queue { size: usize, head: Option<Box<Node>>, tail: Option<Shared<Node>> } #[allow(boxed_local)] impl Queue { pub fn new() -> Queue { Queue { size: 0, head: None, tail: None } } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn len(&self) -> usize { self.size } pub fn enqueue(&mut self, e: i32) { self.size += 1; let mut node = Box::new(Node::new(e)); let raw: *mut _ = &mut *node; match self.tail { Some(share) => unsafe { (**share).next = Some(node) }, None => self.head = Some(node), } unsafe { self.tail = Some(Shared::new(raw)); } } pub fn contains(&self, e: i32) -> bool { match self.head { Some(ref head) => { let mut node = head; while (*node).elem != e && (*node).next.is_some() { node = (*node).next.as_ref().unwrap(); } (*node).elem == e }, None => false, } } pub fn dequeue(&mut self) -> Option<i32> { self.head.take().map(<|fim▁hole|> self.size -= 1; h.elem } ) } }<|fim▁end|>
|head| { let h = *head; self.head = h.next;
<|file_name|>buffered_write_stream.hpp<|end_file_name|><|fim▁begin|>// // buffered_write_stream.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP #define BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/buffered_write_stream_fwd.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/completion_condition.hpp> #include <boost/asio/detail/bind_handler.hpp> #include <boost/asio/detail/buffered_stream_storage.hpp> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/error.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/write.hpp> #include <boost/asio/detail/push_options.hpp> namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace asio { /// Adds buffering to the write-related operations of a stream. /** * The buffered_write_stream class template can be used to add buffering to the * synchronous and asynchronous write operations of a stream. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Stream> class buffered_write_stream : private noncopyable { public: /// The type of the next layer. typedef typename remove_reference<Stream>::type next_layer_type; /// The type of the lowest layer. typedef typename next_layer_type::lowest_layer_type lowest_layer_type; #if defined(GENERATING_DOCUMENTATION) /// The default buffer size. static const std::size_t default_buffer_size = implementation_defined; #else BOOST_ASIO_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024); #endif /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> explicit buffered_write_stream(Arg& a) : next_layer_(a), storage_(default_buffer_size) { } /// Construct, passing the specified argument to initialise the next layer. template <typename Arg> buffered_write_stream(Arg& a, std::size_t buffer_size) : next_layer_(a), storage_(buffer_size) { } /// Get a reference to the next layer. next_layer_type& next_layer() { return next_layer_; } /// Get a reference to the lowest layer. lowest_layer_type& lowest_layer() { return next_layer_.lowest_layer(); } /// Get a const reference to the lowest layer. const lowest_layer_type& lowest_layer() const { return next_layer_.lowest_layer(); } /// Get the io_service associated with the object. pdalboost::asio::io_service& get_io_service() { return next_layer_.get_io_service(); } /// Close the stream. void close() { next_layer_.close(); } /// Close the stream. pdalboost::system::error_code close(pdalboost::system::error_code& ec) { return next_layer_.close(ec); } /// Flush all data from the buffer to the next layer. Returns the number of /// bytes written to the next layer on the last write operation. Throws an /// exception on failure. std::size_t flush(); /// Flush all data from the buffer to the next layer. Returns the number of /// bytes written to the next layer on the last write operation, or 0 if an /// error occurred. std::size_t flush(pdalboost::system::error_code& ec); /// Start an asynchronous flush. template <typename WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (pdalboost::system::error_code, std::size_t)) async_flush(BOOST_ASIO_MOVE_ARG(WriteHandler) handler); /// Write the given data to the stream. Returns the number of bytes written. /// Throws an exception on failure. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers); /// Write the given data to the stream. Returns the number of bytes written, /// or 0 if an error occurred and the error handler did not throw. template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, pdalboost::system::error_code& ec); /// Start an asynchronous write. The data being written must be valid for the /// lifetime of the asynchronous operation. template <typename ConstBufferSequence, typename WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (pdalboost::system::error_code, std::size_t)) async_write_some(const ConstBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(WriteHandler) handler); /// Read some data from the stream. Returns the number of bytes read. Throws /// an exception on failure. template <typename MutableBufferSequence><|fim▁hole|> /// Read some data from the stream. Returns the number of bytes read or 0 if /// an error occurred. template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, pdalboost::system::error_code& ec) { return next_layer_.read_some(buffers, ec); } /// Start an asynchronous read. The buffer into which the data will be read /// must be valid for the lifetime of the asynchronous operation. template <typename MutableBufferSequence, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (pdalboost::system::error_code, std::size_t)) async_read_some(const MutableBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(ReadHandler) handler) { detail::async_result_init< ReadHandler, void (pdalboost::system::error_code, std::size_t)> init( BOOST_ASIO_MOVE_CAST(ReadHandler)(handler)); next_layer_.async_read_some(buffers, BOOST_ASIO_MOVE_CAST(BOOST_ASIO_HANDLER_TYPE(ReadHandler, void (pdalboost::system::error_code, std::size_t)))(init.handler)); return init.result.get(); } /// Peek at the incoming data on the stream. Returns the number of bytes read. /// Throws an exception on failure. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers) { return next_layer_.peek(buffers); } /// Peek at the incoming data on the stream. Returns the number of bytes read, /// or 0 if an error occurred. template <typename MutableBufferSequence> std::size_t peek(const MutableBufferSequence& buffers, pdalboost::system::error_code& ec) { return next_layer_.peek(buffers, ec); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail() { return next_layer_.in_avail(); } /// Determine the amount of data that may be read without blocking. std::size_t in_avail(pdalboost::system::error_code& ec) { return next_layer_.in_avail(ec); } private: /// Copy data into the internal buffer from the specified source buffer. /// Returns the number of bytes copied. template <typename ConstBufferSequence> std::size_t copy(const ConstBufferSequence& buffers); /// The next layer. Stream next_layer_; // The data in the buffer. detail::buffered_stream_storage storage_; }; } // namespace asio } // namespace pdalboost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/buffered_write_stream.hpp> #endif // BOOST_ASIO_BUFFERED_WRITE_STREAM_HPP<|fim▁end|>
std::size_t read_some(const MutableBufferSequence& buffers) { return next_layer_.read_some(buffers); }
<|file_name|>dig.py<|end_file_name|><|fim▁begin|># coding=utf-8 # # Copyright 2016 F5 Networks 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. # """BIG-IP® utility module REST URI ``http://localhost/mgmt/tm/util/dig`` GUI Path N/A REST Kind ``tm:util:dig:*`` """ from f5.bigip.mixins import CommandExecutionMixin from f5.bigip.resource import UnnamedResource class Dig(UnnamedResource, CommandExecutionMixin): """BIG-IP® utility command .. note:: This is an unnamed resource so it has no ~Partition~Name pattern<|fim▁hole|> """ def __init__(self, util): super(Dig, self).__init__(util) self._meta_data['required_command_parameters'].update(('utilCmdArgs',)) self._meta_data['required_json_kind'] = 'tm:util:dig:runstate' self._meta_data['allowed_commands'].append('run')<|fim▁end|>
at the end of its URI.
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#[macro_use] extern crate nickel; extern crate config; extern crate pulldown_cmark; use nickel::Nickel; use std::path::Path; use std::collections::HashMap; use std::fs::File; use std::io::{Read,BufReader, Error}; use config::reader; use config::types::Config; use pulldown_cmark::Parser; use pulldown_cmark::html::push_html; use nickel::*; use nickel::extensions::Redirect; fn main() { let empty_default_config = Config::new(HashMap::new()); let configuration = reader::from_file(Path::new("Dokiofile")).unwrap_or(empty_default_config); let listening_port = configuration.lookup_integer32_or("port", 3000); let default_file = String::from(configuration.lookup_str_or("default_file", "README.md")); let theme = String::from(configuration.lookup_str_or("theme", "themes/dokio/index.hbs")); let mut server = Nickel::new(); server.get("/", middleware! { |_, response| let url_string = format!("http://localhost:{}/{}", listening_port, default_file.as_str()); return response.redirect(url_string); }); server.get("**.md", middleware! { |request, response| let file = request.path_without_query(); if let Ok(markdown_file) = read_file_to_string(file) { let mut data = HashMap::new();<|fim▁hole|> let mut html = String::new(); push_html(&mut html, parser); data.insert("markdown_file", html); return response.render(theme.as_str(), &data); } }); server.utilize(Mount::new("/", StaticFilesHandler::new("."))); let _server = server.listen(format!("localhost:{}", listening_port).as_str()); } fn read_file_to_string(path: Option<&str>) -> Result<String, Error> { let file_path = format!(".{}", path.unwrap()); let file = File::open(Path::new(file_path.as_str()))?; let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents)?; Ok(contents) }<|fim▁end|>
let parser = Parser::new(markdown_file.as_str());
<|file_name|>example-1.5.x.py<|end_file_name|><|fim▁begin|># Download the Python helper library from twilio.com/docs/python/install from twilio.rest import TwilioTaskRouterClient # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" workspace_sid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" client = TwilioTaskRouterClient(account_sid, auth_token) <|fim▁hole|>print(statistics.realtime["tasks_by_status"]["pending"]) print(statistics.realtime["tasks_by_status"]["assigned"])<|fim▁end|>
workspace = client.workspaces.get(workspace_sid) statistics = workspace.statistics.get() print(statistics.cumulative["avg_task_acceptance_time"]) print(statistics.cumulative["tasks_created"])
<|file_name|>library-directory.js<|end_file_name|><|fim▁begin|>// Plugin for using a local directory as a Library. Generates the payload for // an AssetList REST endpoint consisting of asset models as well as pagination // helpers. var _ = require('underscore'), fs = require('fs'), url = require('url'), path = require('path'), querystring = require('querystring'), Step = require('step'); module.exports = function(app, options, callback) { // Recursive readdir. `callback(err, files)` is given a `files` array where<|fim▁hole|> // each file is an object with `filename` and `stat` properties. var lsR = function(basedir, callback) { var files = []; var ls = []; Step( function() { fs.readdir(basedir, this); }, function(err, data) { if (data.length === 0) return this(); var group = this.group(); ls = _.map(data, function(v) { return path.join(basedir, v); }); _.each(ls, function(v) { fs.stat(v, group()); }); }, function(err, stats) { if (ls.length === 0) return this(); var group = this.group(); _.each(ls, function(v, k) { var next = group(); if (stats[k].isDirectory()) { lsR(v, next); } else { files.push({ filename: v, stat: stats[k] }); next(); } }); }, function(err, sub) { _.each(sub, function(v) { v && (files = files.concat(v)); }); callback(err, files); } ); } // Filter an array of files where filenames match regex `re`. var lsFilter = function(files, re) { return _.filter(files, function(f) { return f.filename.match(re); }); }; // Convert a list of files into asset models. var toAssets = function(files, base_dir, port) { return _.map(files, function(f) { return { url: url.format({ host: 'localhost:' + port, protocol: 'http:', pathname: path.join( '/api/Library/' + options.id + '/files/' // Ensure only one trailing slash + querystring.escape(f.filename.replace( base_dir.replace(/(\/)$/, '') + '/', '')) ) }), bytes: (Math.ceil(parseInt(f.stat.size) / 1048576)) + ' MB', id: path.basename(f.filename) }; }); }; // Sort and slice to the specified page. var paginate = function(objects, page, limit) { return _.sortBy(objects, function(f) { return f.id; }).slice(page * limit, page * limit + limit); }; // Generate the AssetList payload object. lsR(options.directory_path, function(err, files) { var assets = toAssets( lsFilter(files, /\.(zip|json|geojson|vrt|tiff?)$/i), options.directory_path, require('settings').port ); callback({ models: paginate( assets, options.page, options.limit ), page: options.page, pageTotal: Math.ceil(assets.length / options.limit) }); }); };<|fim▁end|>
<|file_name|>apiStatusContext.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>import { createContext } from 'react'; export const defaultApiStatus = { offline: false, apiUnreachable: '', appVersionBad: false, }; export default createContext(defaultApiStatus);<|fim▁end|>
<|file_name|>cramps.py<|end_file_name|><|fim▁begin|>from machinekit import hal from machinekit import rtapi as rt from machinekit import config as c from fdm.config import base def hardware_read(): hal.addf('hpg.capture-position', 'servo-thread') hal.addf('bb_gpio.read', 'servo-thread') def hardware_write(): hal.addf('hpg.update', 'servo-thread') hal.addf('bb_gpio.write', 'servo-thread')<|fim▁hole|> # load low-level drivers rt.loadrt('hal_bb_gpio', output_pins='816,822,823,824,825,826,914,923,925', input_pins='807,808,809,810,817,911,913') prubin = '%s/%s' % (c.Config().EMC2_RTLIB_DIR, c.find('PRUCONF', 'PRUBIN')) rt.loadrt(c.find('PRUCONF', 'DRIVER'), pru=0, num_stepgens=6, num_pwmgens=6, prucode=prubin, halname='hpg') # Python user-mode HAL module to read ADC value and generate a thermostat output for PWM defaultThermistor = 'semitec_103GT_2' hal.loadusr('hal_temp_bbb', name='temp', interval=0.05, filter_size=1, cape_board='CRAMPS', channels='04:%s,05:%s,02:%s,03:%s' % (c.find('HBP', 'THERMISTOR', defaultThermistor), c.find('EXTRUDER_0', 'THERMISTOR', defaultThermistor), c.find('EXTRUDER_1', 'THERMISTOR', defaultThermistor), c.find('EXTRUDER_2', 'THERMISTOR', defaultThermistor)), wait_name='temp') watchList.append(['temp', 0.1]) base.usrcomp_status('temp', 'temp-hw', thread='servo-thread') base.usrcomp_watchdog(watchList, 'estop-reset', thread='servo-thread', errorSignal='watchdog-error') def setup_hardware(thread): # PWM hal.Pin('hpg.pwmgen.00.pwm_period').set(10000000) # 100Hz hal.Pin('hpg.pwmgen.00.out.00.pin').set(811) hal.Pin('hpg.pwmgen.00.out.01.pin').set(915) hal.Pin('hpg.pwmgen.00.out.02.pin').set(927) hal.Pin('hpg.pwmgen.00.out.03.pin').set(921) hal.Pin('hpg.pwmgen.00.out.04.pin').set(941) hal.Pin('hpg.pwmgen.00.out.05.pin').set(922) # HBP hal.Pin('hpg.pwmgen.00.out.00.enable').set(True) hal.Pin('hpg.pwmgen.00.out.00.value').link('hbp-temp-pwm') # configure extruders for n in range(0, 3): hal.Pin('hpg.pwmgen.00.out.%02i.enable' % (n + 1)).set(True) hal.Pin('hpg.pwmgen.00.out.%02i.value' % (n + 1)).link('e%i-temp-pwm' % n) # configure fans for n in range(0, 2): hal.Pin('hpg.pwmgen.00.out.%02i.enable' % (n + 4)).link('f%i-pwm-enable' % n) hal.Pin('hpg.pwmgen.00.out.%02i.value' % (n + 4)).link('f%i-pwm' % n) hal.Signal('f%i-pwm-enable' % n).set(True) # configure leds # none # GPIO hal.Pin('bb_gpio.p8.in-08').link('limit-0-home') # X hal.Pin('bb_gpio.p8.in-07').link('limit-0-max') # X hal.Pin('bb_gpio.p8.in-10').link('limit-1-home') # Y hal.Pin('bb_gpio.p8.in-09').link('limit-1-max') # Y hal.Pin('bb_gpio.p9.in-13').link('limit-2-home') # Z hal.Pin('bb_gpio.p9.in-11').link('limit-2-max') # Z # probe ... # Adjust as needed for your switch polarity hal.Pin('bb_gpio.p8.in-08.invert').set(True) hal.Pin('bb_gpio.p8.in-07.invert').set(True) hal.Pin('bb_gpio.p8.in-10.invert').set(True) hal.Pin('bb_gpio.p8.in-09.invert').set(True) hal.Pin('bb_gpio.p9.in-13.invert').set(True) hal.Pin('bb_gpio.p9.in-11.invert').set(True) # ADC hal.Pin('temp.ch-04.value').link('hbp-temp-meas') hal.Pin('temp.ch-05.value').link('e0-temp-meas') hal.Pin('temp.ch-02.value').link('e1-temp-meas') hal.Pin('temp.ch-03.value').link('e2-temp-meas') # Stepper hal.Pin('hpg.stepgen.00.steppin').set(813) hal.Pin('hpg.stepgen.00.dirpin').set(812) hal.Pin('hpg.stepgen.01.steppin').set(815) hal.Pin('hpg.stepgen.01.dirpin').set(814) hal.Pin('hpg.stepgen.02.steppin').set(819) hal.Pin('hpg.stepgen.02.dirpin').set(818) hal.Pin('hpg.stepgen.03.steppin').set(916) hal.Pin('hpg.stepgen.03.dirpin').set(912) hal.Pin('hpg.stepgen.04.steppin').set(917) hal.Pin('hpg.stepgen.04.dirpin').set(918) hal.Pin('hpg.stepgen.05.steppin').set(924) hal.Pin('hpg.stepgen.05.dirpin').set(926) # machine power hal.Pin('bb_gpio.p9.out-23').link('emcmot-0-enable') #hal.Pin('bb_gpio.p9.out-23.invert').set(True) # Monitor estop input from hardware hal.Pin('bb_gpio.p8.in-17').link('estop-in') hal.Pin('bb_gpio.p8.in-17.invert').set(True) # drive estop-sw hal.Pin('bb_gpio.p8.out-26').link('estop-out') hal.Pin('bb_gpio.p8.out-26.invert').set(True) # Tie machine power signal to the Parport Cape LED # Feel free to tie any other signal you like to the LED hal.Pin('bb_gpio.p9.out-25').link('emcmot-0-enable') # hal.Pin('bb_gpio.p9.out-25.invert').set(True) # link emcmot.xx.enable to stepper driver enable signals hal.Pin('bb_gpio.p9.out-14').link('emcmot-0-enable') hal.Pin('bb_gpio.p9.out-14.invert').set(True)<|fim▁end|>
def init_hardware(): watchList = []
<|file_name|>textjs.js<|end_file_name|><|fim▁begin|>(function(global){ var PollXBlockI18N = { init: function() { (function(globals) { var django = globals.django || (globals.django = {}); django.pluralidx = function(count) { return (count == 1) ? 0 : 1; }; /* gettext library */ django.catalog = django.catalog || {}; if (!django.jsi18n_initialized) { django.gettext = function(msgid) { var value = django.catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } }; django.ngettext = function(singular, plural, count) { var value = django.catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value.constructor === Array ? value[django.pluralidx(count)] : value; } }; django.gettext_noop = function(msgid) { return msgid; }; django.pgettext = function(context, msgid) { var value = django.gettext(context + '\x04' + msgid); if (value.indexOf('\x04') != -1) { value = msgid; } return value; }; django.npgettext = function(context, singular, plural, count) { var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count); if (value.indexOf('\x04') != -1) { value = django.ngettext(singular, plural, count); } return value; }; django.interpolate = function(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else {<|fim▁hole|> /* formatting library */ django.formats = { "DATETIME_FORMAT": "j E Y H:i", "DATETIME_INPUT_FORMATS": [ "%d.%m.%Y %H:%M:%S", "%d.%m.%Y %H:%M:%S.%f", "%d.%m.%Y %H:%M", "%d.%m.%Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%Y-%m-%d" ], "DATE_FORMAT": "j E Y", "DATE_INPUT_FORMATS": [ "%d.%m.%Y", "%d.%m.%y", "%y-%m-%d", "%Y-%m-%d" ], "DECIMAL_SEPARATOR": ",", "FIRST_DAY_OF_WEEK": 1, "MONTH_DAY_FORMAT": "j E", "NUMBER_GROUPING": 3, "SHORT_DATETIME_FORMAT": "d-m-Y H:i", "SHORT_DATE_FORMAT": "d-m-Y", "THOUSAND_SEPARATOR": "\u00a0", "TIME_FORMAT": "H:i", "TIME_INPUT_FORMATS": [ "%H:%M:%S", "%H:%M:%S.%f", "%H:%M" ], "YEAR_MONTH_FORMAT": "F Y" }; django.get_format = function(format_type) { var value = django.formats[format_type]; if (typeof(value) == 'undefined') { return format_type; } else { return value; } }; /* add to global namespace */ globals.pluralidx = django.pluralidx; globals.gettext = django.gettext; globals.ngettext = django.ngettext; globals.gettext_noop = django.gettext_noop; globals.pgettext = django.pgettext; globals.npgettext = django.npgettext; globals.interpolate = django.interpolate; globals.get_format = django.get_format; django.jsi18n_initialized = true; } }(this)); } }; PollXBlockI18N.init(); global.PollXBlockI18N = PollXBlockI18N; }(this));<|fim▁end|>
return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } };
<|file_name|>test_root.py<|end_file_name|><|fim▁begin|><|fim▁hole|> assert response.data.decode('utf-8') == 'Hey enlil'<|fim▁end|>
def test_root(client): response = client.get('/') assert response.status_code == 200
<|file_name|>transpose.cpp<|end_file_name|><|fim▁begin|>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/dim4.hpp> #include <af/defines.h> #include <af/blas.h> #include <af/data.h> #include <af/arith.h> #include <err_common.hpp> #include <handle.hpp> #include <backend.hpp> #include <transpose.hpp> using af::dim4; using namespace detail; template<typename T> static inline af_array trs(const af_array in, const bool conjugate) { return getHandle<T>(detail::transpose<T>(getArray<T>(in), conjugate));<|fim▁hole|> af_err af_transpose(af_array *out, af_array in, const bool conjugate) { try { const ArrayInfo& info = getInfo(in); af_dtype type = info.getType(); af::dim4 dims = info.dims(); if (dims.elements() == 0) { return af_retain_array(out, in); } if (dims[0]==1 || dims[1]==1) { af::dim4 outDims(dims[1],dims[0],dims[2],dims[3]); if(conjugate) { af_array temp = 0; AF_CHECK(af_conjg(&temp, in)); AF_CHECK(af_moddims(out, temp, outDims.ndims(), outDims.get())); AF_CHECK(af_release_array(temp)); return AF_SUCCESS; } else { // for a vector OR a batch of vectors // we can use modDims to transpose AF_CHECK(af_moddims(out, in, outDims.ndims(), outDims.get())); return AF_SUCCESS; } } af_array output; switch(type) { case f32: output = trs<float> (in, conjugate); break; case c32: output = trs<cfloat> (in, conjugate); break; case f64: output = trs<double> (in, conjugate); break; case c64: output = trs<cdouble>(in, conjugate); break; case b8 : output = trs<char> (in, conjugate); break; case s32: output = trs<int> (in, conjugate); break; case u32: output = trs<uint> (in, conjugate); break; case u8 : output = trs<uchar> (in, conjugate); break; case s64: output = trs<intl> (in, conjugate); break; case u64: output = trs<uintl> (in, conjugate); break; case s16: output = trs<short> (in, conjugate); break; case u16: output = trs<ushort> (in, conjugate); break; default : TYPE_ERROR(1, type); } std::swap(*out,output); } CATCHALL; return AF_SUCCESS; } template<typename T> static inline void transpose_inplace(af_array in, const bool conjugate) { return detail::transpose_inplace<T>(getWritableArray<T>(in), conjugate); } af_err af_transpose_inplace(af_array in, const bool conjugate) { try { const ArrayInfo& info = getInfo(in); af_dtype type = info.getType(); af::dim4 dims = info.dims(); // InPlace only works on square matrices DIM_ASSERT(0, dims[0] == dims[1]); // If singleton element if(dims[0] == 1) return AF_SUCCESS; switch(type) { case f32: transpose_inplace<float> (in, conjugate); break; case c32: transpose_inplace<cfloat> (in, conjugate); break; case f64: transpose_inplace<double> (in, conjugate); break; case c64: transpose_inplace<cdouble>(in, conjugate); break; case b8 : transpose_inplace<char> (in, conjugate); break; case s32: transpose_inplace<int> (in, conjugate); break; case u32: transpose_inplace<uint> (in, conjugate); break; case u8 : transpose_inplace<uchar> (in, conjugate); break; case s64: transpose_inplace<intl> (in, conjugate); break; case u64: transpose_inplace<uintl> (in, conjugate); break; case s16: transpose_inplace<short> (in, conjugate); break; case u16: transpose_inplace<ushort> (in, conjugate); break; default : TYPE_ERROR(1, type); } } CATCHALL; return AF_SUCCESS; }<|fim▁end|>
}
<|file_name|>resources.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from fnmatch import fnmatch from django.db.models import F, Max from django.utils.functional import cached_property from pootle_store.models import Store from .models import StoreFS from .utils import StoreFSPathFilter, StorePathFilter class FSProjectResources(object): def __init__(self, project): self.project = project def __str__(self): return ( "<%s(%s)>" % (self.__class__.__name__, self.project)) @property def stores(self): return Store.objects.filter( translation_project__project=self.project) @property def tracked(self): return StoreFS.objects.filter( project=self.project).select_related("store") @property def synced(self): return ( self.tracked.exclude(last_sync_revision__isnull=True) .exclude(last_sync_hash__isnull=True)) @property def unsynced(self): return ( self.tracked.filter(last_sync_revision__isnull=True) .filter(last_sync_hash__isnull=True)) @property def trackable_stores(self): return self.stores.exclude(obsolete=True).filter(fs__isnull=True) class FSProjectStateResources(object): """Wrap FSPlugin and cache available resources Accepts `pootle_path` and `fs_path` glob arguments. If present all resources are filtered accordingly. """ def __init__(self, context, pootle_path=None, fs_path=None): self.context = context self.pootle_path = pootle_path self.fs_path = fs_path def match_fs_path(self, path): """Match fs_paths using file glob if set""" if not self.fs_path or fnmatch(path, self.fs_path): return path def _exclude_staged(self, qs): return ( qs.exclude(staged_for_removal=True) .exclude(staged_for_merge=True)) @cached_property def found_file_matches(self): return sorted(self.context.find_translations( fs_path=self.fs_path, pootle_path=self.pootle_path)) @cached_property def found_file_paths(self): return [x[1] for x in self.found_file_matches] @cached_property def resources(self): """Uncached Project resources provided by FSPlugin""" return self.context.resources @cached_property def store_filter(self): """Filter Store querysets using file globs""" return StorePathFilter( pootle_path=self.pootle_path) @cached_property def storefs_filter(self): """Filter StoreFS querysets using file globs""" return StoreFSPathFilter( pootle_path=self.pootle_path, fs_path=self.fs_path) @cached_property def synced(self): """Returns tracked StoreFSs that have sync information, and are not currently staged for any kind of operation """ return self.storefs_filter.filtered( self._exclude_staged(self.resources.synced)) @cached_property def trackable_stores(self): """Stores that are not currently tracked but could be""" _trackable = [] stores = self.store_filter.filtered(self.resources.trackable_stores) for store in stores: fs_path = self.match_fs_path( self.context.get_fs_path(store.pootle_path)) if fs_path: _trackable.append((store, fs_path)) return _trackable @cached_property def trackable_store_paths(self): """Dictionary of pootle_path, fs_path for trackable Stores""" return { store.pootle_path: fs_path for store, fs_path in self.trackable_stores} @cached_property def missing_file_paths(self): return [ path for path in self.tracked_paths.keys() if path not in self.found_file_paths] @cached_property def tracked(self): """StoreFS queryset of tracked resources""" return self.storefs_filter.filtered(self.resources.tracked) @cached_property def tracked_paths(self): """Dictionary of fs_path, path for tracked StoreFS""" return dict(self.tracked.values_list("path", "pootle_path")) @cached_property def unsynced(self): """Returns tracked StoreFSs that have NO sync information, and are not currently staged for any kind of operation """ return self.storefs_filter.filtered( self._exclude_staged( self.resources.unsynced)) @cached_property def pootle_changed(self): """StoreFS queryset of tracked resources where the Store has changed since it was last synced. """ return ( self.synced.exclude(store_id__isnull=True) .exclude(store__obsolete=True) .annotate(max_revision=Max("store__unit__revision")) .exclude(last_sync_revision=F("max_revision")))<|fim▁hole|> """Uncache cached_properties""" for k, v_ in self.__dict__.items(): if k in ["context", "pootle_path", "fs_path"]: continue del self.__dict__[k]<|fim▁end|>
def reload(self):
<|file_name|>views.py<|end_file_name|><|fim▁begin|>import ujson as json import pytz from datetime import datetime import requests from django.http import HttpResponse, Http404 from django.shortcuts import render def index(request): return render(request, 'timetable/index.html', {}) def query(request, term): ret = [] if len(term) > 1: r = requests.get( "https://transport.opendata.ch/v1/locations?query=" + term) data = r.json() if 'stations' in data: for match in data['stations'][:6]: ret.append(match['name']) return HttpResponse(json.dumps(ret), content_type="application/json") def connection(request, departure, selected_time, start, to): start = start.replace("$.$", "/") to = to.replace("$.$", "/") if start and to: tz = pytz.timezone('Europe/Zurich') dt = datetime.fromtimestamp(int(selected_time), tz=tz) params = { "from": start, "to": to, "time": str(dt.time())[:5], "date": str(dt.date()), "isArrivalTime": departure, } r = requests.get("https://transport.opendata.ch/v1/connections", params=params) data = r.json() connections = [] # print(r.text) try: for con in data["connections"]: sections = [] name = "" for section in con["sections"]: if not name and section["journey"]: name = "{} nach {}".format(section["journey"]["name"], section["arrival"]["location"]["name"]) sections.append( { "from": section["departure"]["location"]["name"], "from_platform": section["departure"]["platform"], "from_time": section["departure"]["departureTimestamp"], "to": section["arrival"]["location"]["name"], "to_platform": section["arrival"]["platform"], "to_time": section["arrival"]["arrivalTimestamp"], "route": "{} nach {}".format(section["journey"]["name"], section["arrival"]["location"]["name"]) if section[ "journey"] else "Fussweg", "capacity1st": section["journey"]["capacity1st"] if section["journey"] else None, "capacity2nd": section["journey"]["capacity2nd"] if section["journey"] else None, } ) connections.append( { "transfers": con["transfers"], "arrivalTimestamp": con["to"]["arrivalTimestamp"], "departureTimestamp": con["from"]["departureTimestamp"], "sections": sections, "name": name,<|fim▁hole|> "capacity1st": con["capacity1st"], "capacity2nd": con["capacity2nd"], } ) prev_time = 0 if not connections else connections[0]["arrivalTimestamp"] - 60 next_time = selected_time if not connections else connections[-1]["departureTimestamp"] + 60 return HttpResponse(json.dumps({"connections": connections, "nextTime": next_time, "prevTime": prev_time}), content_type="application/json") except KeyError: raise raise Http404("No connections found") except AttributeError: raise raise Http404("No connections found") raise Http404("No connections found")<|fim▁end|>
"platform": con["from"]["platform"], "from": con["from"]["station"]["name"], "to": con["to"]["station"]["name"],
<|file_name|>BaseTestHBaseClient.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2014 The Async HBase Authors. All rights reserved. * This file is part of Async HBase. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the StumbleUpon nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.hbase.async; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; import java.nio.charset.Charset; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.hbase.async.HBaseClient.ZKClient; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.channel.socket.nio.NioClientBossPool; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioWorkerPool; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.TimerTask; import org.junit.Before; import org.junit.Ignore; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.reflect.Whitebox; import com.stumbleupon.async.Deferred; @PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class, GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class, Executors.class, HashedWheelTimer.class, NioClientBossPool.class, NioWorkerPool.class })<|fim▁hole|> protected static final byte[] COMMA = { ',' }; protected static final byte[] TIMESTAMP = "1234567890".getBytes(); protected static final byte[] INFO = getStatic("INFO"); protected static final byte[] REGIONINFO = getStatic("REGIONINFO"); protected static final byte[] SERVER = getStatic("SERVER"); protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' }; protected static final byte[] KEY = { 'k', 'e', 'y' }; protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' }; protected static final byte[] FAMILY = { 'f' }; protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' }; protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' }; protected static final byte[] EMPTY_ARRAY = new byte[0]; protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE); protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890"); protected static final RegionInfo region = mkregion("table", "table,,1234567890"); protected static final int RS_PORT = 50511; protected static final String ROOT_IP = "192.168.0.1"; protected static final String META_IP = "192.168.0.2"; protected static final String REGION_CLIENT_IP = "192.168.0.3"; protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient"; protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient"; protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient"; protected HBaseClient client = null; /** Extracted from {@link #client}. */ protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache; /** Extracted from {@link #client}. */ protected ConcurrentHashMap<RegionInfo, RegionClient> region2client; /** Extracted from {@link #client}. */ protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions; /** Extracted from {@link #client}. */ protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre; /** Extracted from {@link #client}. */ protected HashMap<String, RegionClient> ip2client; /** Extracted from {@link #client}. */ protected Counter num_nsre_rpcs; /** Fake client supposedly connected to -ROOT-. */ protected RegionClient rootclient; /** Fake client supposedly connected to .META.. */ protected RegionClient metaclient; /** Fake client supposedly connected to our fake test table. */ protected RegionClient regionclient; /** Each new region client is dumped here */ protected List<RegionClient> region_clients = new ArrayList<RegionClient>(); /** Fake Zookeeper client */ protected ZKClient zkclient; /** Fake channel factory */ protected NioClientSocketChannelFactory channel_factory; /** Fake channel returned from the factory */ protected SocketChannel chan; /** Fake timer for testing */ protected FakeTimer timer; @Before public void before() throws Exception { region_clients.clear(); rootclient = mock(RegionClient.class); when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME); metaclient = mock(RegionClient.class); when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME); regionclient = mock(RegionClient.class); when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME); zkclient = mock(ZKClient.class); channel_factory = mock(NioClientSocketChannelFactory.class); chan = mock(SocketChannel.class); timer = new FakeTimer(); when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>()); PowerMockito.mockStatic(Executors.class); PowerMockito.when(Executors.defaultThreadFactory()) .thenReturn(mock(ThreadFactory.class)); PowerMockito.when(Executors.newCachedThreadPool()) .thenReturn(mock(ExecutorService.class)); PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments() .thenReturn(channel_factory); PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments() .thenReturn(timer); PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments() .thenReturn(mock(NioClientBossPool.class)); PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments() .thenReturn(mock(NioWorkerPool.class)); client = PowerMockito.spy(new HBaseClient("test-quorum-spec")); Whitebox.setInternalState(client, "zkclient", zkclient); Whitebox.setInternalState(client, "rootregion", rootclient); Whitebox.setInternalState(client, "jitter_percent", 0); regions_cache = Whitebox.getInternalState(client, "regions_cache"); region2client = Whitebox.getInternalState(client, "region2client"); client2regions = Whitebox.getInternalState(client, "client2regions"); got_nsre = Whitebox.getInternalState(client, "got_nsre"); ip2client = Whitebox.getInternalState(client, "ip2client"); injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT); injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT); when(channel_factory.newChannel(any(ChannelPipeline.class))) .thenReturn(chan); when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class)); when(rootclient.toString()).thenReturn("Mock RootClient"); PowerMockito.doAnswer(new Answer<RegionClient>(){ @Override public RegionClient answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final String endpoint = (String)args[0] + ":" + (Integer)args[1]; final RegionClient rc = mock(RegionClient.class); when(rc.getRemoteAddress()).thenReturn(endpoint); client2regions.put(rc, new ArrayList<RegionInfo>()); region_clients.add(rc); return rc; } }).when(client, "newClient", anyString(), anyInt()); } /** * Injects an entry in the local caches of the client. */ protected void injectRegionInCache(final RegionInfo region, final RegionClient client, final String ip) { regions_cache.put(region.name(), region); region2client.put(region, client); ArrayList<RegionInfo> regions = client2regions.get(client); if (regions == null) { regions = new ArrayList<RegionInfo>(1); client2regions.put(client, regions); } regions.add(region); ip2client.put(ip, client); } // ----------------- // // Helper functions. // // ----------------- // protected void clearCaches(){ regions_cache.clear(); region2client.clear(); client2regions.clear(); } protected static <T> T getStatic(final String fieldname) { return Whitebox.getInternalState(HBaseClient.class, fieldname); } /** * Creates a fake {@code .META.} row. * The row contains a single entry for all keys of {@link #TABLE}. */ protected static ArrayList<KeyValue> metaRow() { return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY); } /** * Creates a fake {@code .META.} row. * The row contains a single entry for {@link #TABLE}. * @param start_key The start key of the region in this entry. * @param stop_key The stop key of the region in this entry. */ protected static ArrayList<KeyValue> metaRow(final byte[] start_key, final byte[] stop_key) { final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2); row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE)); row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes())); return row; } protected static KeyValue metaRegionInfo( final byte[] start_key, final byte[] stop_key, final boolean offline, final boolean splitting, final byte[] table) { final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP); final byte is_splitting = (byte) (splitting ? 1 : 0); final byte[] regioninfo = concat( new byte[] { 0, // version (byte) stop_key.length, // vint: stop key length }, stop_key, offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline Bytes.fromLong(name.hashCode()), // long: region ID (make it random) new byte[] { (byte) name.length }, // vint: region name length name, // region name new byte[] { is_splitting, // boolean: splitting (byte) start_key.length, // vint: start key length }, start_key ); return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo); } protected static RegionInfo mkregion(final String table, final String name) { return new RegionInfo(table.getBytes(), name.getBytes(), HBaseClient.EMPTY_ARRAY); } protected static byte[] anyBytes() { return any(byte[].class); } /** Concatenates byte arrays together. */ protected static byte[] concat(final byte[]... arrays) { int len = 0; for (final byte[] array : arrays) { len += array.length; } final byte[] result = new byte[len]; len = 0; for (final byte[] array : arrays) { System.arraycopy(array, 0, result, len, array.length); len += array.length; } return result; } /** Creates a new Deferred that's already called back. */ protected static <T> Answer<Deferred<T>> newDeferred(final T result) { return new Answer<Deferred<T>>() { public Deferred<T> answer(final InvocationOnMock invocation) { return Deferred.fromResult(result); } }; } /** * A fake {@link Timer} implementation that fires up tasks immediately. * Tasks are called immediately from the current thread and a history of the * various tasks is logged. */ static final class FakeTimer extends HashedWheelTimer { final List<Map.Entry<TimerTask, Long>> tasks = new ArrayList<Map.Entry<TimerTask, Long>>(); final ArrayList<Timeout> timeouts = new ArrayList<Timeout>(); boolean run = true; @Override public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { try { tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay)); if (run) { task.run(null); // Argument never used in this code base. } final Timeout timeout = mock(Timeout.class); timeouts.add(timeout); return timeout; // Return value never used in this code base. } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Timer task failed: " + task, e); } } @Override public Set<Timeout> stop() { run = false; return new HashSet<Timeout>(timeouts); } } /** * A fake {@link org.jboss.netty.util.Timer} implementation. * Instead of executing the task it will store that task in a internal state * and provides a function to start the execution of the stored task. * This implementation thus allows the flexibility of simulating the * things that will be going on during the time out period of a TimerTask. * This was mainly return to simulate the timeout period for * alreadyNSREdRegion test, where the region will be in the NSREd mode only * during this timeout period, which was difficult to simulate using the * above {@link FakeTimer} implementation, as we don't get back the control * during the timeout period * * Here it will hold at most two Tasks. We have two tasks here because when * one is being executed, it may call for newTimeOut for another task. */ static final class FakeTaskTimer extends HashedWheelTimer { protected TimerTask newPausedTask = null; protected TimerTask pausedTask = null; @Override public synchronized Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) { if (pausedTask == null) { pausedTask = task; } else if (newPausedTask == null) { newPausedTask = task; } else { throw new IllegalStateException("Cannot Pause Two Timer Tasks"); } return null; } @Override public Set<Timeout> stop() { return null; } public boolean continuePausedTask() { if (pausedTask == null) { return false; } try { if (newPausedTask != null) { throw new IllegalStateException("Cannot be in this state"); } pausedTask.run(null); // Argument never used in this code base pausedTask = newPausedTask; newPausedTask = null; return true; } catch (Exception e) { throw new RuntimeException("Timer task failed: " + pausedTask, e); } } } /** * Generate and return a mocked HBase RPC for testing purposes with a valid * Deferred that can be called on execution. * @param deferred A deferred to watch for results * @return The RPC to pass through unit tests. */ protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) { final HBaseRpc rpc = mock(HBaseRpc.class); rpc.attempt = 0; when(rpc.getDeferred()).thenReturn(deferred); when(rpc.toString()).thenReturn("MockRPC"); PowerMockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { if (deferred != null) { deferred.callback(invocation.getArguments()[0]); } else { System.out.println("Deferred was null!!"); } return null; } }).when(rpc).callback(Object.class); return rpc; } }<|fim▁end|>
@Ignore // ignore for test runners public class BaseTestHBaseClient { protected static final Charset CHARSET = Charset.forName("ASCII");
<|file_name|>lumina-config_et.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="et"> <context> <name>AppDialog</name> <message> <location filename="../AppDialog.ui" line="14"/> <source>Select Application</source> <translation>Vali rakendus</translation> </message> <message> <location filename="../AppDialog.ui" line="20"/> <source>Search for....</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ColorDialog</name> <message> <location filename="../ColorDialog.ui" line="14"/> <source>Color Scheme Editor</source> <translation>Värvipaleti muutmine</translation> </message> <message> <location filename="../ColorDialog.ui" line="28"/> <source>Color Scheme:</source> <translation>Värvipalett:</translation> </message> <message> <location filename="../ColorDialog.ui" line="51"/> <source>Set new color for selection</source> <translation>Määra valitud elemendi värv</translation> </message> <message> <location filename="../ColorDialog.ui" line="54"/> <location filename="../ColorDialog.ui" line="70"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../ColorDialog.ui" line="67"/> <source>Manually set value for selection</source> <translation>Määra käsitsi valitud elemendi värv</translation> </message> <message> <location filename="../ColorDialog.ui" line="95"/> <source>Color</source> <translation>Element</translation> </message> <message> <location filename="../ColorDialog.ui" line="100"/> <source>Value</source> <translation>Värv</translation> </message> <message> <location filename="../ColorDialog.ui" line="105"/> <source>Sample</source> <translation>Näidis</translation> </message> <message> <location filename="../ColorDialog.ui" line="115"/> <source>Cancel</source> <translation>Loobu</translation> </message> <message> <location filename="../ColorDialog.ui" line="135"/> <source>Save</source> <translation>Salvesta</translation> </message> <message> <location filename="../ColorDialog.cpp" line="98"/> <source>Color Exists</source> <translation>Värvipalett eksisteerib</translation> </message> <message> <location filename="../ColorDialog.cpp" line="98"/> <source>This color scheme already exists. Overwrite it?</source> <translation>Sellise nimega palett on juba olemas. Kas kirjutada üle?</translation> </message> <message> <location filename="../ColorDialog.cpp" line="121"/> <location filename="../ColorDialog.cpp" line="122"/> <source>Select Color</source> <translation>Vali värv</translation> </message> <message> <location filename="../ColorDialog.cpp" line="142"/> <source>Color Value</source> <translation>Värvi väärtus</translation> </message> <message> <location filename="../ColorDialog.cpp" line="142"/> <source>Color:</source> <translation>Värv:</translation> </message> </context> <context> <name>GetPluginDialog</name> <message> <location filename="../GetPluginDialog.ui" line="14"/> <source>Select Plugin</source> <translation>Vali plugin</translation> </message> <message> <location filename="../GetPluginDialog.ui" line="26"/> <source>Select a Plugin:</source> <translation>Vali plugin:</translation> </message> <message> <location filename="../GetPluginDialog.ui" line="57"/> <source>Cancel</source> <translation>Loobu</translation> </message> <message> <location filename="../GetPluginDialog.ui" line="77"/> <source>Select</source> <translation>Vali</translation> </message> </context> <context> <name>PanelWidget</name> <message> <location filename="../PanelWidget.ui" line="32"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.ui" line="93"/> <source>Location</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.ui" line="114"/> <source>Edge:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.ui" line="131"/> <source>Size:</source> <translation>Suurus:</translation> </message> <message> <location filename="../PanelWidget.ui" line="138"/> <source> pixel(s) thick</source> <translation> piksli laiune</translation> </message> <message> <location filename="../PanelWidget.ui" line="157"/> <source>% length</source> <translation>% pikkusest</translation> </message> <message> <location filename="../PanelWidget.ui" line="183"/> <source>Alignment:</source> <translation>Joondus:</translation> </message> <message> <location filename="../PanelWidget.ui" line="204"/> <source>Appearance</source> <translation>Välimus</translation> </message> <message> <location filename="../PanelWidget.ui" line="222"/> <source>Auto-hide Panel</source> <translation>Peida paneel automaatselt</translation> </message> <message> <location filename="../PanelWidget.ui" line="229"/> <source>Use Custom Color</source> <translation>Kasuta kohandatud värvi</translation> </message> <message> <location filename="../PanelWidget.ui" line="250"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../PanelWidget.ui" line="257"/> <source>Sample</source> <translation>Näidis</translation> </message> <message> <location filename="../PanelWidget.ui" line="287"/> <source>Plugins</source> <translation>Pluginad</translation> </message> <message> <location filename="../PanelWidget.cpp" line="19"/> <source>Top/Left</source> <translation>Üleval/vasakul</translation> </message> <message> <location filename="../PanelWidget.cpp" line="20"/> <source>Center</source> <translation>Keskel</translation> </message> <message> <location filename="../PanelWidget.cpp" line="21"/> <source>Bottom/Right</source> <translation>All/paremal</translation> </message> <message> <location filename="../PanelWidget.cpp" line="22"/> <source>Top</source> <translation>Ülal</translation> </message><|fim▁hole|> <translation>All</translation> </message> <message> <location filename="../PanelWidget.cpp" line="24"/> <source>Left</source> <translation>Vasakul</translation> </message> <message> <location filename="../PanelWidget.cpp" line="25"/> <source>Right</source> <translation>Paremal</translation> </message> <message> <location filename="../PanelWidget.cpp" line="44"/> <location filename="../PanelWidget.cpp" line="117"/> <source>Panel %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../PanelWidget.cpp" line="155"/> <location filename="../PanelWidget.cpp" line="156"/> <source>Select Color</source> <translation type="unfinished">Vali värv</translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../LPlugins.cpp" line="80"/> <source>Desktop Bar</source> <translation>Töölaua riba</translation> </message> <message> <location filename="../LPlugins.cpp" line="81"/> <source>This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="87"/> <source>Spacer</source> <translation>Eraldaja</translation> </message> <message> <location filename="../LPlugins.cpp" line="88"/> <source>Invisible spacer to separate plugins.</source> <translation>Nähtamatu eraldaja pluginatele.</translation> </message> <message> <location filename="../LPlugins.cpp" line="102"/> <source>Controls for switching between the various virtual desktops.</source> <translation>Nupud töölaudade vahel liikumiseks.</translation> </message> <message> <location filename="../LPlugins.cpp" line="108"/> <source>Battery Monitor</source> <translation>Aku jälgija</translation> </message> <message> <location filename="../LPlugins.cpp" line="109"/> <source>Keep track of your battery status.</source> <translation>Jälgib aku olekut.</translation> </message> <message> <location filename="../LPlugins.cpp" line="115"/> <source>Time/Date</source> <translation>Kellaaeg/kuupäev</translation> </message> <message> <location filename="../LPlugins.cpp" line="116"/> <source>View the current time and date.</source> <translation>Kuupäeva ja kellaaja näitamine.</translation> </message> <message> <location filename="../LPlugins.cpp" line="122"/> <source>System Dashboard</source> <translation>Süsteemi vidinavaade</translation> </message> <message> <location filename="../LPlugins.cpp" line="123"/> <source>View or change system settings (audio volume, screen brightness, battery life, virtual desktops).</source> <translation>Vaata või muuda süsteemi sätteid (heli, ekraani heledus, aku, virtuaalsed töölauad).</translation> </message> <message> <location filename="../LPlugins.cpp" line="129"/> <location filename="../LPlugins.cpp" line="291"/> <source>Task Manager</source> <translation>Tegumihaldur</translation> </message> <message> <location filename="../LPlugins.cpp" line="136"/> <source>Task Manager (No Groups)</source> <translation>Tegumihaldur (gruppideta)</translation> </message> <message> <location filename="../LPlugins.cpp" line="143"/> <source>System Tray</source> <translation>Süsteemisalv</translation> </message> <message> <location filename="../LPlugins.cpp" line="144"/> <source>Display area for dockable system applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="151"/> <source>Hide all open windows and show the desktop</source> <translation>Peida kõik lahtiolevad aknad ja näita töölauda</translation> </message> <message> <location filename="../LPlugins.cpp" line="157"/> <source>Start Menu</source> <translation>Start-menüü</translation> </message> <message> <location filename="../LPlugins.cpp" line="190"/> <source>Calendar</source> <translation>Kalender</translation> </message> <message> <location filename="../LPlugins.cpp" line="191"/> <source>Display a calendar on the desktop</source> <translation>Kuva töölaual kalender</translation> </message> <message> <location filename="../LPlugins.cpp" line="164"/> <location filename="../LPlugins.cpp" line="197"/> <source>Application Launcher</source> <translation>Rakenduste käivitaja</translation> </message> <message> <location filename="../LPlugins.cpp" line="66"/> <source>User Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="67"/> <source>Start menu alternative focusing on the user&apos;s files, directories, and favorites.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="73"/> <source>Application Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="74"/> <source>Start menu alternative which focuses on launching applications.</source> <translation>Alternatiivne Start menüü mis fokuseerub rakenduste käivitamisele.</translation> </message> <message> <location filename="../LPlugins.cpp" line="94"/> <source>Line</source> <translation>Rida/Joon</translation> </message> <message> <location filename="../LPlugins.cpp" line="95"/> <source>Simple line to provide visual separation between items.</source> <translation>Lihtne joon et lihtsustada objektide visuaalset eristamist.</translation> </message> <message> <location filename="../LPlugins.cpp" line="101"/> <source>Workspace Switcher</source> <translation>Töölaudade Vahetaja</translation> </message> <message> <location filename="../LPlugins.cpp" line="130"/> <source>View and control any running application windows (group similar windows under a single button).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="137"/> <source>View and control any running application windows (every individual window has a button)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="150"/> <source>Show Desktop</source> <translation>Kuva töölaud</translation> </message> <message> <location filename="../LPlugins.cpp" line="158"/> <source>Unified system access and application launch menu.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="165"/> <source>Pin an application shortcut directly to the panel</source> <translation>Kinnita rakenduse otsetee paneelile</translation> </message> <message> <location filename="../LPlugins.cpp" line="198"/> <source>Desktop button for launching an application</source> <translation>Töölaua nupp rakenduste käivitamiseks</translation> </message> <message> <location filename="../LPlugins.cpp" line="204"/> <source>Desktop Icons View</source> <translation>Töölaua ikoonide vaade</translation> </message> <message> <location filename="../LPlugins.cpp" line="211"/> <source>Note Pad</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="212"/> <source>Keep simple text notes on your desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="171"/> <location filename="../LPlugins.cpp" line="218"/> <source>Audio Player</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="172"/> <location filename="../LPlugins.cpp" line="219"/> <source>Play through lists of audio files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="225"/> <source>System Monitor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="226"/> <source>Keep track of system statistics such as CPU/Memory usage and CPU temperatures.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="232"/> <source>RSS Reader</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="233"/> <source>Monitor RSS Feeds (Requires internet connection)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="256"/> <source>Terminal</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="257"/> <source>Start the default system terminal.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="264"/> <source>Browse the system with the default file manager.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="270"/> <location filename="../pages/getPage.cpp" line="47"/> <source>Applications</source> <translation>Rakendused</translation> </message> <message> <location filename="../LPlugins.cpp" line="271"/> <source>Show the system applications menu.</source> <translation>Näita süsteemi rakenduste menüüd.</translation> </message> <message> <location filename="../LPlugins.cpp" line="277"/> <source>Separator</source> <translation>Eraldaja</translation> </message> <message> <location filename="../LPlugins.cpp" line="278"/> <source>Static horizontal line.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="285"/> <source>Show the desktop settings menu.</source> <translation>Näita töölaua sätete menüüd.</translation> </message> <message> <location filename="../LPlugins.cpp" line="298"/> <source>Custom App</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="299"/> <source>Start a custom application</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="178"/> <location filename="../LPlugins.cpp" line="305"/> <source>Menu Script</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="205"/> <source>Configurable area for automatically showing desktop icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="263"/> <source>Browse Files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="284"/> <source>Preferences</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="292"/> <source>List the open, minimized, active, and urgent application windows</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="179"/> <location filename="../LPlugins.cpp" line="306"/> <source>Run an external script to generate a user defined menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="312"/> <source>Lock Session</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="313"/> <source>Lock the current desktop session</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="323"/> <source>Text</source> <translation>Tekst</translation> </message> <message> <location filename="../LPlugins.cpp" line="324"/> <source>Color to use for all visible text.</source> <translation>Nähtava teksti värv.</translation> </message> <message> <location filename="../LPlugins.cpp" line="329"/> <source>Text (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="330"/> <source>Text color for disabled or inactive items.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="335"/> <source>Text (Highlighted)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="336"/> <source>Text color when selection is highlighted.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="341"/> <source>Base Window Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="342"/> <source>Main background color for the window/dialog.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="347"/> <source>Base Window Color (Alternate)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="348"/> <source>Main background color for widgets that list or display collections of items.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="353"/> <source>Primary Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="354"/> <source>Dominant color for the theme.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="359"/> <source>Primary Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="360"/> <source>Dominant color for the theme (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="365"/> <source>Secondary Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="366"/> <source>Alternate color for the theme.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="371"/> <source>Secondary Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="372"/> <source>Alternate color for the theme (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="377"/> <source>Accent Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="378"/> <source>Color used for borders or other accents.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="383"/> <source>Accent Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="384"/> <source>Color used for borders or other accents (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="389"/> <source>Highlight Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="390"/> <source>Color used for highlighting an item.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="395"/> <source>Highlight Color (Disabled)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../LPlugins.cpp" line="396"/> <source>Color used for highlighting an item (more subdued).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="43"/> <source>Wallpaper Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="43"/> <source>Change background image(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="44"/> <source>Theme Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="44"/> <source>Change interface fonts and colors</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="45"/> <source>Window Effects</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="45"/> <source>Adjust transparency levels and window effects</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="46"/> <source>Startup Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="46"/> <source>Automatically start applications or services</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="43"/> <source>Wallpaper</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="44"/> <location filename="../pages/getPage.cpp" line="55"/> <source>Theme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="46"/> <source>Autostart</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="47"/> <source>Mimetype Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="47"/> <source>Change default applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="48"/> <source>Keyboard Shortcuts</source> <translation type="unfinished">Klaviatuuri kiirklahvid</translation> </message> <message> <location filename="../pages/getPage.cpp" line="48"/> <source>Change keyboard shortcuts</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="49"/> <source>Window Manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="49"/> <source>Window Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="49"/> <source>Change window settings and appearances</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="50"/> <source>Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="51"/> <source>Panels</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="52"/> <source>Menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="55"/> <source>Sound Themeing</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="55"/> <source>Change basic sound settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="50"/> <source>Desktop Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="50"/> <source>Change what icons or tools are embedded on the desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="51"/> <source>Panels and Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="51"/> <source>Change any floating panels and what they show</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="52"/> <source>Menu Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="52"/> <source>Change what options are shown on the desktop context menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="53"/> <source>Locale Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="53"/> <source>Change the default locale settings for this user</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="53"/> <source>Localization</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="54"/> <source>General Options</source> <translation type="unfinished">Üldised valikud</translation> </message> <message> <location filename="../pages/getPage.cpp" line="54"/> <source>User Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/getPage.cpp" line="54"/> <source>Change basic user settings such as time/date formats</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ScriptDialog</name> <message> <location filename="../ScriptDialog.ui" line="14"/> <source>Setup a JSON Menu Script</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="25"/> <source>Visible Name:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="32"/> <source>Executable:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="39"/> <source>Icon:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.ui" line="54"/> <location filename="../ScriptDialog.ui" line="87"/> <source>...</source> <translation type="unfinished">...</translation> </message> <message> <location filename="../ScriptDialog.ui" line="126"/> <source>Cancel</source> <translation type="unfinished">Loobu</translation> </message> <message> <location filename="../ScriptDialog.ui" line="133"/> <source>Apply</source> <translation type="unfinished">Rakenda</translation> </message> <message> <location filename="../ScriptDialog.cpp" line="57"/> <source>Select a menu script</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ScriptDialog.cpp" line="64"/> <source>Select an icon file</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ThemeDialog</name> <message> <location filename="../ThemeDialog.ui" line="14"/> <source>Theme Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ThemeDialog.ui" line="28"/> <source>Theme Name:</source> <translation>Teema nimi:</translation> </message> <message> <location filename="../ThemeDialog.ui" line="51"/> <source>color</source> <translation>värv</translation> </message> <message> <location filename="../ThemeDialog.ui" line="74"/> <source>Cancel</source> <translation>Loobu</translation> </message> <message> <location filename="../ThemeDialog.ui" line="94"/> <source>Save</source> <translation>Salvesta</translation> </message> <message> <location filename="../ThemeDialog.ui" line="101"/> <source>Apply</source> <translation>Rakenda</translation> </message> <message> <location filename="../ThemeDialog.cpp" line="65"/> <location filename="../ThemeDialog.cpp" line="82"/> <source>Theme Exists</source> <translation>Teema on olemas</translation> </message> <message> <location filename="../ThemeDialog.cpp" line="65"/> <location filename="../ThemeDialog.cpp" line="82"/> <source>This theme already exists. Overwrite it?</source> <translation>See teema on juba olemas. Kas kirjutada see üle?</translation> </message> </context> <context> <name>XDGDesktopList</name> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/> <source>Multimedia</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/> <source>Development</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/> <source>Education</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/> <source>Games</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/> <source>Graphics</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/> <source>Network</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/> <source>Office</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/> <source>Science</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/> <source>Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/> <source>System</source> <translation type="unfinished">Süsteem</translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/> <source>Utility</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/> <source>Wine</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/> <source>Unsorted</source> <translation type="unfinished"></translation> </message> </context> <context> <name>mainWindow</name> <message> <location filename="../mainWindow.ui" line="44"/> <source>Save</source> <translation type="unfinished">Salvesta</translation> </message> <message> <location filename="../mainWindow.ui" line="47"/> <source>Save current changes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="50"/> <source>Ctrl+S</source> <translation type="unfinished">Ctrl+S</translation> </message> <message> <location filename="../mainWindow.ui" line="55"/> <source>Back to settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="58"/> <location filename="../mainWindow.ui" line="61"/> <source>Back to overall settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.ui" line="72"/> <location filename="../mainWindow.ui" line="75"/> <source>Select monitor/desktop to configure</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="130"/> <source>Unsaved Changes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="130"/> <source>This page currently has unsaved changes, do you wish to save them now?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="132"/> <source>Yes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="133"/> <source>No</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainWindow.cpp" line="134"/> <source>Cancel</source> <translation type="unfinished">Loobu</translation> </message> </context> <context> <name>page_autostart</name> <message> <location filename="../pages/page_autostart.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.ui" line="39"/> <source>Add New Startup Service</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.ui" line="75"/> <source>Application</source> <translation type="unfinished">Rakendus</translation> </message> <message> <location filename="../pages/page_autostart.ui" line="85"/> <source>Binary</source> <translation type="unfinished">Käivitatav fail</translation> </message> <message> <location filename="../pages/page_autostart.ui" line="95"/> <source>File</source> <translation type="unfinished">Fail</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="66"/> <source>Startup Services</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="133"/> <source>Select Binary</source> <translation type="unfinished">Vali käivitatav fail</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="133"/> <source>Application Binaries (*)</source> <translation type="unfinished">Rakenduse käivitusfailid (*)</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="136"/> <source>Invalid Binary</source> <translation type="unfinished">Vigane käivitatav fail</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="136"/> <source>The selected file is not executable!</source> <translation type="unfinished">Valitud fail pole käivitatav!</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="150"/> <source>Select File</source> <translation type="unfinished">Vali fail</translation> </message> <message> <location filename="../pages/page_autostart.cpp" line="150"/> <source>All Files (*)</source> <translation type="unfinished">Kõik failid (*)</translation> </message> </context> <context> <name>page_compton</name> <message> <location filename="../pages/page_compton.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_compton.ui" line="32"/> <source>Disable Compositing Manager (session restart required)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_compton.ui" line="39"/> <source>Only use compositing with GPU acceleration </source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_compton.cpp" line="37"/> <source>Window Effects</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_defaultapps</name> <message> <location filename="../pages/page_defaultapps.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="166"/> <source>Advanced</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="189"/> <source>Specific File Types</source> <translation type="unfinished">Spetsiifilised failitüübid</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="226"/> <source>Type/Group</source> <translation type="unfinished">Tüüp/grupp</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="231"/> <source>Default Application</source> <translation type="unfinished">Vaikimisi rakendus</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="236"/> <source>Description</source> <translation type="unfinished">Kirjeldus</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="246"/> <source>Clear</source> <translation type="unfinished">Kustuta</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="269"/> <source>Set App</source> <translation type="unfinished">Määra rakendus</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="279"/> <source>Set Binary</source> <translation type="unfinished">Määra programm</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="39"/> <source>Basic Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="58"/> <source>Web Browser:</source> <translation type="unfinished">Veebibrauser:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="81"/> <source>E-Mail Client:</source> <translation type="unfinished">E-posti klient:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="108"/> <source>File Manager:</source> <translation type="unfinished">Failihaldur:</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="121"/> <source>Virtual Terminal:</source> <translation type="unfinished">Virtuaalne terminal</translation> </message> <message> <location filename="../pages/page_defaultapps.ui" line="128"/> <location filename="../pages/page_defaultapps.ui" line="138"/> <source>...</source> <translation type="unfinished">...</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="42"/> <source>Default Applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="152"/> <source>Click to Set</source> <translation type="unfinished">Klõpsa määramiseks</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="88"/> <source>%1 (%2)</source> <translation type="unfinished">%1 (%2)</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="272"/> <source>Select Binary</source> <translation type="unfinished">Vali käivitatav fail</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="279"/> <source>Invalid Binary</source> <translation type="unfinished">Vigane käivitatav fail</translation> </message> <message> <location filename="../pages/page_defaultapps.cpp" line="279"/> <source>The selected binary is not executable!</source> <translation type="unfinished">Valitud fail ei ole käivitatav!</translation> </message> </context> <context> <name>page_fluxbox_keys</name> <message> <location filename="../pages/page_fluxbox_keys.ui" line="34"/> <source>Basic Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="44"/> <source>Advanced Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="107"/> <source>Action</source> <translation type="unfinished">Toiming</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="112"/> <source>Keyboard Shortcut</source> <translation type="unfinished">Kiirklahvid</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="120"/> <source>Modify Shortcut</source> <translation type="unfinished">Muuda otseteed</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="141"/> <source>Clear Shortcut</source> <translation type="unfinished">Kustuta kiirklahv</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="151"/> <source>Apply Change</source> <translation type="unfinished">Rakenda muudatus</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="161"/> <source>Change Key Binding:</source> <translation type="unfinished">Muuda klahviseoseid:</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="184"/> <source>Note: Current key bindings need to be cleared and saved before they can be re-used.</source> <translation type="unfinished">Märkus: praegused klahvikombinatsioonid tuleb kustutada enne kui neid saab uuesti kasutada.</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="220"/> <source>View Syntax Codes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.ui" line="244"/> <source>&quot;Mod1&quot;: Alt key &quot;Mod4&quot;: Windows/Mac key &quot;Control&quot;: Ctrl key</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="70"/> <source>Keyboard Shortcuts</source> <translation type="unfinished">Klaviatuuri kiirklahvid</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="78"/> <source>Audio Volume Up</source> <translation type="unfinished">Heli tugevamaks</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="79"/> <source>Audio Volume Down</source> <translation type="unfinished">Heli vaiksemaks</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="80"/> <source>Screen Brightness Up</source> <translation type="unfinished">Ekraan heledamaks</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="81"/> <source>Screen Brightness Down</source> <translation type="unfinished">Ekraan tumedamaks</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="82"/> <source>Take Screenshot</source> <translation type="unfinished">Tee ekraanipilt</translation> </message> <message> <location filename="../pages/page_fluxbox_keys.cpp" line="83"/> <source>Lock Screen</source> <translation type="unfinished">Lukustuskuva</translation> </message> </context> <context> <name>page_fluxbox_settings</name> <message> <location filename="../pages/page_fluxbox_settings.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="34"/> <source>Simple Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="44"/> <source>Advanced Editor</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="81"/> <source>Number of Workspaces</source> <translation type="unfinished">Tööruumide arv</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="98"/> <source>New Window Placement</source> <translation type="unfinished">Uute akende paigutus</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="108"/> <source>Focus Policy</source> <translation type="unfinished">Fookuse reegel</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="118"/> <source>Window Theme</source> <translation type="unfinished">Akna kujundus</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="136"/> <source>Window Theme Preview</source> <translation type="unfinished">Akna kujunduse eelvaade</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.ui" line="190"/> <location filename="../pages/page_fluxbox_settings.cpp" line="181"/> <source>No Preview Available</source> <translation type="unfinished">Eelvaade puudub</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="70"/> <source>Window Manager Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="75"/> <source>Click To Focus</source> <translation type="unfinished">Hiireklõpsuga</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="76"/> <source>Active Mouse Focus</source> <translation type="unfinished">Hiire liigutamisel</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="77"/> <source>Strict Mouse Focus</source> <translation type="unfinished">Rangelt hiire all</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="80"/> <source>Align in a Row</source> <translation type="unfinished">Joonda ritta</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="81"/> <source>Align in a Column</source> <translation type="unfinished">Joonda tulpa</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="82"/> <source>Cascade</source> <translation type="unfinished">Kaskaad</translation> </message> <message> <location filename="../pages/page_fluxbox_settings.cpp" line="83"/> <source>Underneath Mouse</source> <translation type="unfinished">Hiire alla</translation> </message> </context> <context> <name>page_interface_desktop</name> <message> <location filename="../pages/page_interface_desktop.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_desktop.ui" line="26"/> <source>Embedded Utilities</source> <translation type="unfinished">Sisseehitatud tööriistad</translation> </message> <message> <location filename="../pages/page_interface_desktop.ui" line="79"/> <source>Display Desktop Folder Contents</source> <translation type="unfinished">Näita töölaua kausta sisu</translation> </message> <message> <location filename="../pages/page_interface_desktop.ui" line="86"/> <source>Display Removable Media Icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_desktop.cpp" line="56"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_interface_menu</name> <message> <location filename="../pages/page_interface_menu.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_menu.ui" line="38"/> <source>Context Menu Plugins</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_menu.cpp" line="46"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_interface_panels</name> <message> <location filename="../pages/page_interface_panels.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.ui" line="46"/> <source>Panel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.ui" line="96"/> <source>Profile</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="59"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="110"/> <source>No Panels</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="136"/> <source>Custom Profiles</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="136"/> <source>Copy Screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="143"/> <source>Apply</source> <translation type="unfinished">Rakenda</translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="144"/> <source>Delete</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="149"/> <location filename="../pages/page_interface_panels.cpp" line="204"/> <source>Create Profile</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_interface_panels.cpp" line="204"/> <source>Name:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_main</name> <message> <location filename="../pages/page_main.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.ui" line="32"/> <source>Search for....</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="56"/> <source>Interface Configuration</source> <translation type="unfinished">Liidese seadistus</translation> </message> <message> <location filename="../pages/page_main.cpp" line="60"/> <source>Appearance</source> <translation type="unfinished">Välimus</translation> </message> <message> <location filename="../pages/page_main.cpp" line="64"/> <source>Desktop Defaults</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="68"/> <source>User Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="72"/> <source>System Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_main.cpp" line="158"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_session_locale</name> <message> <location filename="../pages/page_session_locale.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="32"/> <source>System localization settings (restart required)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="39"/> <source>Language</source> <translation type="unfinished">Keel</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="49"/> <source>Messages</source> <translation type="unfinished">Teated</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="59"/> <source>Time</source> <translation type="unfinished">Aeg</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="69"/> <source>Numeric</source> <translation type="unfinished">Arv</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="79"/> <source>Monetary</source> <translation type="unfinished">Raha</translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="89"/> <source>Collate</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.ui" line="99"/> <source>CType</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.cpp" line="47"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_locale.cpp" line="91"/> <source>System Default</source> <translation type="unfinished">Süsteemi vaikeseade</translation> </message> </context> <context> <name>page_session_options</name> <message> <location filename="../pages/page_session_options.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="34"/> <source>Enable numlock on startup</source> <translation type="unfinished">Lülita numbrilukk käivitamisel sisse</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="41"/> <source>Play chimes on startup</source> <translation type="unfinished">Mängi käivitamisel heli</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="48"/> <source>Play chimes on exit</source> <translation type="unfinished">Mängi väljumisel heli</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="55"/> <source>Automatically create/remove desktop symlinks for applications that are installed/removed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="58"/> <source>Manage desktop app links</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="65"/> <source>Show application crash data</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="74"/> <source>Change User Icon</source> <translation type="unfinished">Muuda kasutaja ikooni</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="112"/> <source>Time Format:</source> <translation type="unfinished">Ajavorming:</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="124"/> <location filename="../pages/page_session_options.ui" line="168"/> <source>View format codes</source> <translation type="unfinished">Kuva vormingu koodid</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="139"/> <location filename="../pages/page_session_options.ui" line="183"/> <source>Sample:</source> <translation type="unfinished">Näide:</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="156"/> <source>Date Format:</source> <translation type="unfinished">Kuupäevavorming</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="203"/> <source>Display Format</source> <translation type="unfinished">Kuvavorming</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="220"/> <source>Window Manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.ui" line="248"/> <source>Reset Desktop Settings</source> <translation type="unfinished">Taasta töölaua sätted</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="267"/> <source>Return to system defaults</source> <translation type="unfinished">Taasta süsteemi vaiksesätted</translation> </message> <message> <location filename="../pages/page_session_options.ui" line="274"/> <source>Return to Lumina defaults</source> <translation type="unfinished">Taasta Lumina vaikeväärtused</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="18"/> <source>Time (Date as tooltip)</source> <translation type="unfinished">Kellaaeg (kuupäev kohtspikrina)</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="19"/> <source>Date (Time as tooltip)</source> <translation type="unfinished">Kuupäev (kellaaeg kohtspikrina)</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="20"/> <source>Time first then Date</source> <translation type="unfinished">Enne kellaaeg, siis kuupäev</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="21"/> <source>Date first then Time</source> <translation type="unfinished">Enne kuupäev, siis kellaaeg</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="60"/> <source>Window manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="93"/> <source>Desktop Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="174"/> <source>Select an image</source> <translation type="unfinished">Vali pilt</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="175"/> <source>Images</source> <translation type="unfinished">Pildid</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="179"/> <source>Reset User Image</source> <translation type="unfinished">Taasta kasutaja pilt</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="179"/> <source>Would you like to reset the user image to the system default?</source> <translation type="unfinished">Kas soovid taastada kasutaja pildi vaikimisi pildile?</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="218"/> <source>Valid Time Codes:</source> <translation type="unfinished">Lubatud ajakoodid:</translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="219"/> <source>%1: Hour without leading zero (1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="220"/> <source>%1: Hour with leading zero (01)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="221"/> <source>%1: Minutes without leading zero (2)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="222"/> <source>%1: Minutes with leading zero (02)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="223"/> <source>%1: Seconds without leading zero (3)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="224"/> <source>%1: Seconds with leading zero (03)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="225"/> <source>%1: AM/PM (12-hour) clock (upper or lower case)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="226"/> <source>%1: Timezone</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="227"/> <source>Time Codes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="241"/> <source>Valid Date Codes:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="242"/> <source>%1: Numeric day without a leading zero (1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="243"/> <source>%1: Numeric day with leading zero (01)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="244"/> <source>%1: Day as abbreviation (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="245"/> <source>%1: Day as full name (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="246"/> <source>%1: Numeric month without leading zero (2)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="247"/> <source>%1: Numeric month with leading zero (02)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="248"/> <source>%1: Month as abbreviation (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="249"/> <source>%1: Month as full name (localized)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="250"/> <source>%1: Year as 2-digit number (15)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="251"/> <source>%1: Year as 4-digit number (2015)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="252"/> <source>Text may be contained within single-quotes to ignore replacements</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_session_options.cpp" line="253"/> <source>Date Codes</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_soundtheme</name> <message> <location filename="../pages/page_soundtheme.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.ui" line="22"/> <location filename="../pages/page_soundtheme.ui" line="67"/> <location filename="../pages/page_soundtheme.ui" line="112"/> <source>Enabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.ui" line="36"/> <location filename="../pages/page_soundtheme.ui" line="81"/> <location filename="../pages/page_soundtheme.ui" line="126"/> <source>TextLabel</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.ui" line="56"/> <source>Set Startup Audio</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.ui" line="101"/> <source>Set Logout Audio</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.ui" line="146"/> <source>Set Battery Audio</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.cpp" line="40"/> <source>Sound Themes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.cpp" line="73"/> <source>Select Startup Sound</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.cpp" line="83"/> <source>Select Logout Sound</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_soundtheme.cpp" line="93"/> <source>Select Low Battery Sound</source> <translation type="unfinished"></translation> </message> </context> <context> <name>page_wallpaper</name> <message> <location filename="../pages/page_wallpaper.ui" line="14"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="90"/> <source>Single Background</source> <translation type="unfinished">Üks taustapilt</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="100"/> <source>Rotate Background</source> <translation type="unfinished">Vahetuv taustapilt</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="107"/> <source> Minutes</source> <translation type="unfinished"> minuti tagant</translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="110"/> <source>Every </source> <translation type="unfinished">Iga </translation> </message> <message> <location filename="../pages/page_wallpaper.ui" line="133"/> <source>Layout:</source> <translation type="unfinished">Paigutus:</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="55"/> <source>Wallpaper Settings</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="65"/> <source>System Default</source> <translation type="unfinished">Süsteemi vaikeseade</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="66"/> <location filename="../pages/page_wallpaper.cpp" line="236"/> <source>Solid Color: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="77"/> <source>Screen Resolution:</source> <translation type="unfinished">Ekraani eraldusvõime</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="99"/> <location filename="../pages/page_wallpaper.cpp" line="100"/> <source>Select Color</source> <translation type="unfinished">Vali värv</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="119"/> <source>File(s)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="120"/> <source>Directory (Single)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="121"/> <source>Directory (Recursive)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="122"/> <source>Solid Color</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="126"/> <source>Automatic</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="127"/> <source>Fullscreen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="128"/> <source>Fit screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="129"/> <source>Tile</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="130"/> <source>Center</source> <translation type="unfinished">Keskel</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="131"/> <source>Top Left</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="132"/> <source>Top Right</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="133"/> <source>Bottom Left</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="134"/> <source>Bottom Right</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="142"/> <source>No Background</source> <translation type="unfinished">Taust puudub</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="142"/> <source>(use system default)</source> <translation type="unfinished">(kasuta vaikeväärtust)</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="156"/> <source>Image Directory: %1 valid images</source> <translation type="unfinished"></translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="176"/> <source>File does not exist</source> <translation type="unfinished">Faili pole olemas</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="217"/> <source>Find Background Image(s)</source> <translation type="unfinished">Vali taustapilt või pildid</translation> </message> <message> <location filename="../pages/page_wallpaper.cpp" line="248"/> <location filename="../pages/page_wallpaper.cpp" line="266"/> <source>Find Background Image Directory</source> <translation type="unfinished"></translation> </message> </context> </TS><|fim▁end|>
<message> <location filename="../PanelWidget.cpp" line="23"/> <source>Bottom</source>
<|file_name|>session-card.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit, OnDestroy, Input} from '@angular/core'; import { Router } from '@angular/router'; import { FirebaseAuthState } from 'angularfire2'; import { UUID } from 'angular2-uuid'; import { AuthService } from '../shared/security/auth.service'; import { Session } from '../shared/model/session'; import { SessionService } from '../shared/model/session.service'; import { User } from '../shared/model/user'; type CardType = 'display' | 'pending'; @Component({ selector: 'app-session-card', templateUrl: './session-card.component.html', styleUrls: ['./session-card.component.scss'] }) export class SessionCardComponent implements OnInit, OnDestroy { typeToButtonLabels = { display: { notInSession: { primary: { content: 'Enroll', function: this.enrollSession }, secondary: { content: 'Details', function: this.sessionDetails } }, inSession: { primary: { content: 'Join Session', function: this.joinSession }, secondary: { content: 'Details', function: this.sessionDetails } }, pending: { disabled: { content: 'Enrollment is pending...' } } }, pending: { inSession: { tutor: { primary: { content: 'Accept', function: this.acceptPending }, secondary: { content: 'Deny', function: this.denyPending } }, tutee: { disabled: { content: 'Enrollment accepted!' } } }, pending: { disabled: { content: 'Enrollment is pending...' } } } }; subjectToLabel = { english: 'file-text2', history: 'history', math: 'calculator', science: 'lab', 'world-language': 'earth', default: 'rocket' }; @Input() type: CardType = 'display'; @Input() session: Session; // User input only used for `pending` type @Input() user: User; authSubscription: any; authInfo: FirebaseAuthState; menuId = UUID.UUID(); get sessionDate(): string { return this.session.start.format('M/D/Y'); } get startTime(): string { return this.session.start.format('h:mm'); } get endTime(): string { return this.session.end.format('h:mm'); } get role() { if (this.isTutor) { return 'tutor'; } else if (this.isTutee) { return 'tutee'; } return null; } get isTutor() { if (!this.authInfo) { return false; } return this.session.tutor.$key === this.authInfo.uid; } get isTutee() { if (!this.authInfo) { return false; } return this.session.tutees.some(user => user.$key === this.authInfo.uid); } get isPending() { if (!this.authInfo) { return false; } return this.session.pending.includes(this.authInfo.uid); } get displayPendingUserPic() { return this.type === 'pending' && this.user && this.user.$key !== this.authInfo.uid; } get sessionStatus() { if (this.isPending) { return 'pending'; } else if (this.inSession) { return 'inSession'; } return 'notInSession'; } get inSession() {<|fim▁hole|> ngOnInit() { this.authSubscription = this.authService.auth$.subscribe(authInfo => this.authInfo = authInfo); } ngOnDestroy() { this.authSubscription.unsubscribe(); } getButtonObject(button: string) { if (this.typeToButtonLabels[this.type] && this.typeToButtonLabels[this.type][this.sessionStatus]) { // Check if there's button text for the session status if (this.typeToButtonLabels[this.type][this.sessionStatus][this.role] && this.typeToButtonLabels[this.type][this.sessionStatus][this.role][button]) { return this.typeToButtonLabels[this.type][this.sessionStatus][this.role][button]; } // Fallback and see if there's any regular button text without specific roles if (this.typeToButtonLabels[this.type][this.sessionStatus] && this.typeToButtonLabels[this.type][this.sessionStatus][button]) { return this.typeToButtonLabels[this.type][this.sessionStatus][button]; } } return null; } activateBottonFunction(button: string) { const buttonObject = this.getButtonObject(button); if (!buttonObject || !buttonObject.function) { return function() {}; } return buttonObject.function.bind(this); } /** * Click handlers for buttons */ sessionDetails() { this.router.navigate(['session', this.session.$key, 'details']); } userDetails() { this.router.navigate(['user', this.user.$key, 'details']); } enrollSession() { this.sessionService.addTutees(this.session.$key, this.authInfo.uid) .subscribe( val => { // console.log('successfully enrolled in session', val); }, err => { console.log('enroll error', err); } ); } joinSession() { this.router.navigate(['session', this.session.$key]); } acceptPending() { this.sessionService.addTutees(this.session.$key, this.user.$key) .subscribe( val => { // console.log('successfully accepted user into session', val); }, err => { console.log('accepting user error', err); } ); } denyPending() { this.sessionService.denyPending(this.session.$key, this.user.$key) .subscribe( val => { // console.log('successfully denied user from session', val); }, err => { console.log('denying user error', err); } ); } updateSession() { this.router.navigate(['scheduling', 'update', this.session.$key]); } deleteSession() { this.sessionService.deleteSession(this.session.$key).subscribe( val => { // console.log('deleted') }, err => console.log(err) ); } checkPending() { this.router.navigate(['session', this.session.$key, {outlets: {'permissions-popup': null}}]); this.router.navigate(['session', this.session.$key, {outlets: {'requests-popup': ['requests']}}]); } }<|fim▁end|>
return this.isTutor || this.isTutee; } constructor(private router: Router, private authService: AuthService, private sessionService: SessionService) { }
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! Capstone low-level binding for Rust. //! //! See [Capstone's C language documentation](http://www.capstone-engine.org/lang_c.html) for more //! information. //! //! # Safety //! //! Obviously unsafe. //! //! Every `handle` shall be initialied first with `cs_open`. //! //! # Examples //! //! TODO #![allow(non_camel_case_types)] #![allow(dead_code)] #![recursion_limit="1000"] use std::os::raw::{c_void, c_int, c_uint, c_char}; pub type size_t = usize; #[cfg(not(any(target_arch="x86_64",target_arch="i686")))] mod placeholders { include!(concat!(env!("OUT_DIR"), "/placeholders.rs")); } #[cfg(target_arch="x86_64")] mod placeholders { pub type detail_data = [u64; 185]; pub type arm64_op_data = [u64; 2]; pub type arm_op_data = [u64; 2]; pub type mips_op_data = [u64; 2]; pub type ppc_op_data = [u32; 3]; pub type sparc_op_data = [u32; 2]; pub type sysz_op_data = [u64; 3]; pub type x86_op_data = [u64; 3]; pub type xcore_op_data = [u32; 3]; } #[cfg(target_arch="i686")] mod placeholders { pub type detail_data = [u32; 333]; pub type arm64_op_data = [u32; 3]; pub type arm_op_data = [u64; 2]; pub type mips_op_data = [u32; 3]; pub type ppc_op_data = [u32; 3]; pub type sparc_op_data = [u32; 2]; pub type sysz_op_data = [u32; 5]; pub type x86_op_data = [u32; 6]; pub type xcore_op_data = [u32; 3]; } #[macro_use] mod macros; pub mod arm; pub mod arm64; pub mod mips; pub mod ppc; pub mod sparc; pub mod sysz; pub mod x86; pub mod xcore; // automatically generated by rust-bindgen // then heavily modified /// Handle to a Capstone context /// /// 0 is not a valid context. pub type csh = size_t; fake_enum! { /// Architecture type pub enum cs_arch { /// ARM architecture (including Thumb, Thumb-2) CS_ARCH_ARM = 0, /// ARM-64, also called AArch64 CS_ARCH_ARM64 = 1, /// Mips architecture CS_ARCH_MIPS = 2, /// X86 architecture (including x86 & x86-64) CS_ARCH_X86 = 3, /// PowerPC architecture CS_ARCH_PPC = 4, /// Sparc architecture CS_ARCH_SPARC = 5, /// SystemZ architecture CS_ARCH_SYSZ = 6, /// XCore architecture CS_ARCH_XCORE = 7, CS_ARCH_MAX = 8, /// All architecture for `cs_support` CS_ARCH_ALL = 0xFFFF, /// Support value to verify diet mode of the engine. CS_SUPPORT_DIET = CS_ARCH_ALL+1, /// Support value to verify X86 reduce mode of the engine.<|fim▁hole|> } } fake_enum! { /// Mode type (architecture variant, not all combination are possible) pub enum cs_mode { /// Little-endian mode (default mode) CS_MODE_LITTLE_ENDIAN = 0, /// 32-bit ARM CS_MODE_ARM = 0, /// 16-bit mode X86 CS_MODE_16 = 1 << 1, /// 32-bit mode X86 CS_MODE_32 = 1 << 2, /// 64-bit mode X86 CS_MODE_64 = 1 << 3, /// ARM's Thumb mode, including Thumb-2 CS_MODE_THUMB = 1 << 4, /// ARM's Cortex-M series CS_MODE_MCLASS = 1 << 5, /// ARMv8 A32 encodings for ARM CS_MODE_V8 = 1 << 6, /// MicroMips mode (MIPS) CS_MODE_MICRO = 1 << 4, /// Mips III ISA CS_MODE_MIPS3 = 1 << 5, /// Mips32r6 ISA CS_MODE_MIPS32R6 = 1 << 6, /// General Purpose Registers are 64-bit wide (MIPS) CS_MODE_MIPSGP64 = 1 << 7, /// SparcV9 mode (Sparc) CS_MODE_V9 = 1 << 4, /// big-endian mode CS_MODE_BIG_ENDIAN = 1 << 31, /// Mips32 ISA (Mips) CS_MODE_MIPS32 = CS_MODE_32, /// Mips64 ISA (Mips) CS_MODE_MIPS64 = CS_MODE_64, } } pub type cs_malloc_t = Option<extern "C" fn(size: size_t) -> *mut c_void>; pub type cs_calloc_t = Option<extern "C" fn(nmemb: size_t, size: size_t) -> *mut c_void>; pub type cs_realloc_t = Option<unsafe extern "C" fn(ptr: *mut c_void, size: size_t) -> *mut c_void>; pub type cs_free_t = Option<unsafe extern "C" fn(ptr: *mut c_void)>; pub type cs_vsnprintf_t = Option<unsafe extern "C" fn()>; // pub type cs_vsnprintf_t = Option<unsafe extern "C" fn(str: *mut c_char, // size: size_t, // format: *const c_char, // ap: va_list) // -> c_int>; #[repr(C)] pub struct cs_opt_mem { pub malloc: cs_malloc_t, pub calloc: cs_calloc_t, pub realloc: cs_realloc_t, pub free: cs_free_t, pub vsnprintf: cs_vsnprintf_t, } impl ::std::default::Default for cs_opt_mem { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } fake_enum! { /// Runtime option for the disassembled engine pub enum cs_opt_type { /// Assembly output syntax CS_OPT_SYNTAX = 1, /// Break down instruction structure into details CS_OPT_DETAIL, /// Change engine's mode at run-time CS_OPT_MODE, /// User-defined dynamic memory related functions CS_OPT_MEM, /// Skip data when disassembling. Then engine is in SKIPDATA mode. CS_OPT_SKIPDATA, /// Setup user-defined function for SKIPDATA option CS_OPT_SKIPDATA_SETUP, } } fake_enum! { /// Runtime option value (associated with option type above) pub enum cs_opt_value { /// Turn OFF an option - default option of CS_OPT_DETAIL, CS_OPT_SKIPDATA. CS_OPT_OFF = 0, /// Turn ON an option (CS_OPT_DETAIL, CS_OPT_SKIPDATA). CS_OPT_ON = 3, /// Default asm syntax (CS_OPT_SYNTAX). CS_OPT_SYNTAX_DEFAULT = 0, /// X86 Intel asm syntax - default on X86 (CS_OPT_SYNTAX). CS_OPT_SYNTAX_INTEL, /// X86 ATT asm syntax (CS_OPT_SYNTAX). CS_OPT_SYNTAX_ATT, /// Prints register name with only number (CS_OPT_SYNTAX) CS_OPT_SYNTAX_NOREGNAME, } } fake_enum! { /// Common instruction operand types - to be consistent across all architectures. pub enum cs_op_type { /// Uninitialized/invalid operand. CS_OP_INVALID = 0, /// Register operand. CS_OP_REG = 1, /// Immediate operand. CS_OP_IMM = 2, /// Memory operand. CS_OP_MEM = 3, /// Floating-Point operand. CS_OP_FP = 4, } } fake_enum! { /// Common instruction groups - to be consistent across all architectures. pub enum cs_group_type { /// uninitialized/invalid group. CS_GRP_INVALID = 0, /// all jump instructions (conditional+direct+indirect jumps) CS_GRP_JUMP, /// all call instructions CS_GRP_CALL, /// all return instructions CS_GRP_RET, /// all interrupt instructions (int+syscall) CS_GRP_INT, /// all interrupt return instructions CS_GRP_IRET, } } pub type cs_skipdata_cb_t = Option<unsafe extern "C" fn(code: *const u8, code_size: size_t, offset: size_t, user_data: *mut c_void) -> size_t>; #[repr(C)] pub struct cs_opt_skipdata { pub mnemonic: *const c_char, pub callback: cs_skipdata_cb_t, pub user_data: *mut c_void, } impl ::std::default::Default for cs_opt_skipdata { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } #[repr(C)] pub struct cs_detail { pub regs_read: [u8; 12usize], pub regs_read_count: u8, pub regs_write: [u8; 20usize], pub regs_write_count: u8, pub groups: [u8; 8usize], pub groups_count: u8, data: placeholders::detail_data, } impl cs_detail { pub unsafe fn x86(&self) -> &x86::cs_x86 { ::std::mem::transmute(&self.data) } pub unsafe fn arm64(&self) -> &arm64::cs_arm64 { ::std::mem::transmute(&self.data) } pub unsafe fn arm(&self) -> &arm::cs_arm { ::std::mem::transmute(&self.data) } pub unsafe fn mips(&self) -> &mips::cs_mips { ::std::mem::transmute(&self.data) } pub unsafe fn ppc(&self) -> &ppc::cs_ppc { ::std::mem::transmute(&self.data) } pub unsafe fn sparc(&self) -> &sparc::cs_sparc { ::std::mem::transmute(&self.data) } pub unsafe fn sysz(&self) -> &sysz::cs_sysz { ::std::mem::transmute(&self.data) } pub unsafe fn xcore(&self) -> &xcore::cs_xcore { ::std::mem::transmute(&self.data) } } /// Information on a disassembled instruction #[repr(C)] pub struct cs_insn { /// Architecture-dependent instruction identifier, see `<ARCH>_INS_*` pub id: c_uint, /// Base address pub address: u64, /// Size of the instruction pub size: u16, /// Bytes of the instruction pub bytes: [u8; 16usize], /// C-string of the mnemonic pub mnemonic: [c_char; 32usize], /// C-string of the operands pub op_str: [c_char; 160usize], /// More details available if option `CS_OPTION_DETAIL` is on and if option /// `CS_OPTION_SKIPDATA` is not on pub detail: *mut cs_detail, } fake_enum! { /// All type of errors encountered by Capstone API. /// These are values returned by cs_errno() pub enum cs_err { /// No error: everything was fine CS_ERR_OK = 0, /// Out-Of-Memory error: cs_open(), cs_disasm(), cs_disasm_iter() CS_ERR_MEM, /// Unsupported architecture: cs_open() CS_ERR_ARCH, /// Invalid handle: cs_op_count(), cs_op_index() CS_ERR_HANDLE, /// Invalid csh argument: cs_close(), cs_errno(), cs_option() CS_ERR_CSH, /// Invalid/unsupported mode: cs_open() CS_ERR_MODE, /// Invalid/unsupported option: cs_option() CS_ERR_OPTION, /// Information is unavailable because detail option is OFF CS_ERR_DETAIL, /// Dynamic memory management uninitialized (see CS_OPT_MEM) CS_ERR_MEMSETUP, /// Unsupported version (bindings) CS_ERR_VERSION, /// Access irrelevant data in "diet" engine CS_ERR_DIET, /// Access irrelevant data for "data" instruction in SKIPDATA mode CS_ERR_SKIPDATA, /// X86 AT&T syntax is unsupported (opt-out at compile time) CS_ERR_X86_ATT, /// X86 Intel syntax is unsupported (opt-out at compile time) CS_ERR_X86_INTEL, } } #[link(name = "capstone", kind = "dylib")] extern "C" { /// Return combined API version & major and minor version numbers. pub fn cs_version(major: *mut c_int, minor: *mut c_int) -> c_uint; pub fn cs_support(query: c_int) -> u8; /// Initialize a Capstone `handle` (non-null pointer) for a given architecture type `arch` /// (`CS_ARCH_*`) and hardware `mode` (`CS_MODE_*`). /// /// Returns CS_ERR_OK on success, or other value on failure (refer to cs_err enum for detailed /// error). pub fn cs_open(arch: cs_arch, mode: cs_mode, handle: *mut csh) -> cs_err; /// Close a Capstone `handle` (and zeroed it). /// /// Release the handle when it is not used anymore but only when there is no /// longer usage of Capstone, in particular no access to `cs_insn` array. pub fn cs_close(handle: *mut csh) -> cs_err; /// Set option `typ` with given `value` for disassembling engine at runtime. pub fn cs_option(handle: csh, typ: cs_opt_type, value: size_t) -> cs_err; /// Report the last error number for the given Capstone `handle` when some API function fail. /// Like glibc's `errno`, `cs_errno` might not retain its old value once accessed. pub fn cs_errno(handle: csh) -> cs_err; /// Return a string describing given error `code`. pub fn cs_strerror(code: cs_err) -> *const c_char; /// Disassemble binary code in context of `handle`, given the `code` buffer of size /// `code_size`, the base `address` and the desired number (`count`) of instructions to decode /// and set a pointer to an array of instructions and returns the number of decoded /// instructions and the size of the buffers. /// /// # Safety /// /// * `code` shall be valid and points to an array of bytes of at least `code_size`. /// * `insn` shall be valid. pub fn cs_disasm(handle: csh, code: *const u8, code_size: size_t, address: u64, count: size_t, insn: *mut *mut cs_insn) -> size_t; /// Free a Capstone allocated array of instruction. /// /// # Safety /// /// `insn` shall originate either from a previous call to `cs_malloc`, in which case the count /// should be 1, or `cs_disasm` in which case the count should be the return value of /// `cs_disasm` pub fn cs_free(insn: *mut cs_insn, count: size_t); /// Allocate a single instruction to be freed with `cs_free(insn, 1)`. pub fn cs_malloc(handle: csh) -> *mut cs_insn; /// Fast API to disassemble binary code, given the code buffer, size, address and number of /// instructions to be decoded. pub fn cs_disasm_iter(handle: csh, code: *mut *const u8, size: *mut size_t, address: *mut u64, insn: *mut cs_insn) -> u8; pub fn cs_reg_name(handle: csh, reg_id: c_uint) -> *const c_char; pub fn cs_insn_name(handle: csh, insn_id: c_uint) -> *const c_char; pub fn cs_group_name(handle: csh, group_id: c_uint) -> *const c_char; pub fn cs_insn_group(handle: csh, insn: *const cs_insn, group_id: c_uint) -> u8; pub fn cs_reg_read(handle: csh, insn: *const cs_insn, reg_id: c_uint) -> u8; pub fn cs_reg_write(handle: csh, insn: *const cs_insn, reg_id: c_uint) -> u8; pub fn cs_op_count(handle: csh, insn: *const cs_insn, op_type: c_uint) -> c_int; pub fn cs_op_index(handle: csh, insn: *const cs_insn, op_type: c_uint, position: c_uint) -> c_int; }<|fim▁end|>
CS_SUPPORT_X86_REDUCE = CS_ARCH_ALL+2,
<|file_name|>cssmediarule.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::Parser; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; use dom::bindings::js::{MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule;<|fim▁hole|>use dom::cssstylesheet::CSSStyleSheet; use dom::medialist::MediaList; use dom::window::Window; use parking_lot::RwLock; use std::sync::Arc; use style::media_queries::parse_media_query_list; use style::stylesheets::MediaRule; use style_traits::ToCss; #[dom_struct] pub struct CSSMediaRule { cssrule: CSSConditionRule, #[ignore_heap_size_of = "Arc"] mediarule: Arc<RwLock<MediaRule>>, medialist: MutNullableJS<MediaList>, } impl CSSMediaRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, mediarule: Arc<RwLock<MediaRule>>) -> CSSMediaRule { let list = mediarule.read().rules.clone(); CSSMediaRule { cssrule: CSSConditionRule::new_inherited(parent_stylesheet, list), mediarule: mediarule, medialist: MutNullableJS::new(None), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, mediarule: Arc<RwLock<MediaRule>>) -> Root<CSSMediaRule> { reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule), window, CSSMediaRuleBinding::Wrap) } fn medialist(&self) -> Root<MediaList> { self.medialist.or_init(|| MediaList::new(self.global().as_window(), self.mediarule.read().media_queries.clone())) } /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface pub fn get_condition_text(&self) -> DOMString { let rule = self.mediarule.read(); let list = rule.media_queries.read(); list.to_css_string().into() } /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface pub fn set_condition_text(&self, text: DOMString) { let mut input = Parser::new(&text); let new_medialist = parse_media_query_list(&mut input); let rule = self.mediarule.read(); let mut list = rule.media_queries.write(); *list = new_medialist; } } impl SpecificCSSRule for CSSMediaRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::MEDIA_RULE } fn get_css(&self) -> DOMString { self.mediarule.read().to_css_string().into() } } impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media fn Media(&self) -> Root<MediaList> { self.medialist() } }<|fim▁end|>
use dom::cssrule::SpecificCSSRule;
<|file_name|>Spell.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 "AzeriteEmpoweredItem.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Battleground.h" #include "CellImpl.h" #include "CombatLogPackets.h" #include "Common.h" #include "ConditionMgr.h" #include "DB2Stores.h" #include "DatabaseEnv.h" #include "DisableMgr.h" #include "DynamicObject.h" #include "GameObjectAI.h" #include "GridNotifiersImpl.h" #include "Guild.h" #include "Group.h" #include "InstanceScript.h" #include "Item.h" #include "Log.h" #include "LootMgr.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "PathGenerator.h" #include "Pet.h" #include "Player.h" #include "ScriptMgr.h" #include "SharedDefines.h" #include "SpellAuraEffects.h" #include "SpellHistory.h" #include "SpellInfo.h" #include "SpellMgr.h" #include "SpellPackets.h" #include "SpellScript.h" #include "TemporarySummon.h" #include "TradeData.h" #include "Util.h" #include "VMapFactory.h" #include "Vehicle.h" #include "World.h" #include "WorldSession.h" #include <numeric> extern NonDefaultConstructible<pEffect> SpellEffects[TOTAL_SPELL_EFFECTS]; SpellDestination::SpellDestination() { _position.Relocate(0, 0, 0, 0); _transportGUID.Clear(); _transportOffset.Relocate(0, 0, 0, 0); } SpellDestination::SpellDestination(float x, float y, float z, float orientation, uint32 mapId) { _position.Relocate(x, y, z, orientation); _transportGUID.Clear(); _position.m_mapId = mapId; _transportOffset.Relocate(0, 0, 0, 0); } SpellDestination::SpellDestination(Position const& pos) { _position.Relocate(pos); _transportGUID.Clear(); _transportOffset.Relocate(0, 0, 0, 0); } SpellDestination::SpellDestination(WorldObject const& wObj) { _transportGUID = wObj.GetTransGUID(); _transportOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO()); _position.Relocate(wObj); } void SpellDestination::Relocate(Position const& pos) { if (!_transportGUID.IsEmpty()) { Position offset; _position.GetPositionOffsetTo(pos, offset); _transportOffset.RelocateOffset(offset); } _position.Relocate(pos); } void SpellDestination::Relocate(WorldLocation const &loc) { _position = loc; } void SpellDestination::RelocateOffset(Position const& offset) { if (!_transportGUID.IsEmpty()) _transportOffset.RelocateOffset(offset); _position.RelocateOffset(offset); } SpellCastTargets::SpellCastTargets() : m_targetMask(0), m_objectTarget(nullptr), m_itemTarget(nullptr), m_itemTargetEntry(0), m_pitch(0.0f), m_speed(0.0f) { } SpellCastTargets::SpellCastTargets(Unit* caster, WorldPackets::Spells::SpellCastRequest const& spellCastRequest) : m_targetMask(spellCastRequest.Target.Flags), m_objectTarget(nullptr), m_itemTarget(nullptr), m_objectTargetGUID(spellCastRequest.Target.Unit), m_itemTargetGUID(spellCastRequest.Target.Item), m_itemTargetEntry(0), m_pitch(0.0f), m_speed(0.0f), m_strTarget(spellCastRequest.Target.Name) { if (spellCastRequest.Target.SrcLocation) { m_src._transportGUID = spellCastRequest.Target.SrcLocation->Transport; Position* pos; if (!m_src._transportGUID.IsEmpty()) pos = &m_src._transportOffset; else pos = &m_src._position; pos->Relocate(spellCastRequest.Target.SrcLocation->Location); if (spellCastRequest.Target.Orientation) pos->SetOrientation(*spellCastRequest.Target.Orientation); } if (spellCastRequest.Target.DstLocation) { m_dst._transportGUID = spellCastRequest.Target.DstLocation->Transport; Position* pos; if (!m_dst._transportGUID.IsEmpty()) pos = &m_dst._transportOffset; else pos = &m_dst._position; pos->Relocate(spellCastRequest.Target.DstLocation->Location); if (spellCastRequest.Target.Orientation) pos->SetOrientation(*spellCastRequest.Target.Orientation); } SetPitch(spellCastRequest.MissileTrajectory.Pitch); SetSpeed(spellCastRequest.MissileTrajectory.Speed); if (spellCastRequest.SendCastFlags == 8) // Archaeology { uint32 kEntry, kCount, fEntry, fCount; uint8 type; for (auto const& weight : spellCastRequest.Weight) { type = weight.Type; switch (type) { case 1: // Fragments fEntry = weight.ID; // Currency id fCount = weight.Quantity; // Currency count break; case 2: // Keystones kEntry = weight.ID; // Item id kCount = weight.Quantity; // Item count break; } } if (kCount > 0 && caster->GetTypeId() == TYPEID_PLAYER) caster->ToPlayer()->DestroyItemCount(kEntry, -(int32(kCount)), true, false); if (fCount > 0 && caster->GetTypeId() == TYPEID_PLAYER) caster->ToPlayer()->ModifyCurrency(fEntry, -(int32(fCount)), false); } Update(caster); } SpellCastTargets::~SpellCastTargets() { } void SpellCastTargets::Write(WorldPackets::Spells::SpellTargetData& data) { data.Flags = m_targetMask; if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_CORPSE_ALLY | TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_CORPSE_ENEMY | TARGET_FLAG_UNIT_MINIPET)) data.Unit = m_objectTargetGUID; if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM) && m_itemTarget) data.Item = m_itemTarget->GetGUID(); if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { data.SrcLocation = boost::in_place(); data.SrcLocation->Transport = m_src._transportGUID; // relative position guid here - transport for example if (!m_src._transportGUID.IsEmpty()) data.SrcLocation->Location = m_src._transportOffset; else data.SrcLocation->Location = m_src._position; } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) { data.DstLocation = boost::in_place(); data.DstLocation->Transport = m_dst._transportGUID; // relative position guid here - transport for example if (!m_dst._transportGUID.IsEmpty()) data.DstLocation->Location = m_dst._transportOffset; else data.DstLocation->Location = m_dst._position; } if (m_targetMask & TARGET_FLAG_STRING) data.Name = m_strTarget; } ObjectGuid SpellCastTargets::GetOrigUnitTargetGUID() const { switch (m_origObjectTargetGUID.GetHigh()) { case HighGuid::Player: case HighGuid::Vehicle: case HighGuid::Creature: case HighGuid::Pet: return m_origObjectTargetGUID; default: return ObjectGuid(); } } void SpellCastTargets::SetOrigUnitTarget(Unit* target) { if (!target) return; m_origObjectTargetGUID = target->GetGUID(); } ObjectGuid SpellCastTargets::GetUnitTargetGUID() const { if (m_objectTargetGUID.IsUnit()) return m_objectTargetGUID; return ObjectGuid::Empty; } Unit* SpellCastTargets::GetUnitTarget() const { if (m_objectTarget) return m_objectTarget->ToUnit(); return NULL; } void SpellCastTargets::SetUnitTarget(Unit* target) { if (!target) return; m_objectTarget = target; m_objectTargetGUID = target->GetGUID(); m_targetMask |= TARGET_FLAG_UNIT; } ObjectGuid SpellCastTargets::GetGOTargetGUID() const { if (m_objectTargetGUID.IsAnyTypeGameObject()) return m_objectTargetGUID; return ObjectGuid::Empty; } GameObject* SpellCastTargets::GetGOTarget() const { if (m_objectTarget) return m_objectTarget->ToGameObject(); return NULL; } void SpellCastTargets::SetGOTarget(GameObject* target) { if (!target) return; m_objectTarget = target; m_objectTargetGUID = target->GetGUID(); m_targetMask |= TARGET_FLAG_GAMEOBJECT; } ObjectGuid SpellCastTargets::GetCorpseTargetGUID() const { if (m_objectTargetGUID.IsCorpse()) return m_objectTargetGUID; return ObjectGuid::Empty; } Corpse* SpellCastTargets::GetCorpseTarget() const { if (m_objectTarget) return m_objectTarget->ToCorpse(); return NULL; } WorldObject* SpellCastTargets::GetObjectTarget() const { return m_objectTarget; } ObjectGuid SpellCastTargets::GetObjectTargetGUID() const { return m_objectTargetGUID; } void SpellCastTargets::RemoveObjectTarget() { m_objectTarget = NULL; m_objectTargetGUID.Clear(); m_targetMask &= ~(TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK); } void SpellCastTargets::SetItemTarget(Item* item) { if (!item) return; m_itemTarget = item; m_itemTargetGUID = item->GetGUID(); m_itemTargetEntry = item->GetEntry(); m_targetMask |= TARGET_FLAG_ITEM; } void SpellCastTargets::SetTradeItemTarget(Player* caster) { m_itemTargetGUID = ObjectGuid::TradeItem; m_itemTargetEntry = 0; m_targetMask |= TARGET_FLAG_TRADE_ITEM; Update(caster); } void SpellCastTargets::UpdateTradeSlotItem() { if (m_itemTarget && (m_targetMask & TARGET_FLAG_TRADE_ITEM)) { m_itemTargetGUID = m_itemTarget->GetGUID(); m_itemTargetEntry = m_itemTarget->GetEntry(); } } SpellDestination const* SpellCastTargets::GetSrc() const { return &m_src; } Position const* SpellCastTargets::GetSrcPos() const { return &m_src._position; } void SpellCastTargets::SetSrc(float x, float y, float z) { m_src = SpellDestination(x, y, z); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::SetSrc(Position const& pos) { m_src = SpellDestination(pos); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::SetSrc(WorldObject const& wObj) { m_src = SpellDestination(wObj); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::ModSrc(Position const& pos) { ASSERT(m_targetMask & TARGET_FLAG_SOURCE_LOCATION); m_src.Relocate(pos); } void SpellCastTargets::RemoveSrc() { m_targetMask &= ~(TARGET_FLAG_SOURCE_LOCATION); } SpellDestination const* SpellCastTargets::GetDst() const { return &m_dst; } WorldLocation const* SpellCastTargets::GetDstPos() const { return &m_dst._position; } void SpellCastTargets::SetDst(float x, float y, float z, float orientation, uint32 mapId) { m_dst = SpellDestination(x, y, z, orientation, mapId); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(Position const& pos) { m_dst = SpellDestination(pos); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(WorldObject const& wObj) { m_dst = SpellDestination(wObj); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(SpellDestination const& spellDest) { m_dst = spellDest; m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::SetDst(SpellCastTargets const& spellTargets) { m_dst = spellTargets.m_dst; m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::ModDst(Position const& pos) { ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION); m_dst.Relocate(pos); } void SpellCastTargets::ModDst(SpellDestination const& spellDest) { ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION); m_dst = spellDest; } void SpellCastTargets::RemoveDst() { m_targetMask &= ~(TARGET_FLAG_DEST_LOCATION); } bool SpellCastTargets::HasSrc() const { return (GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) != 0; } bool SpellCastTargets::HasDst() const { return (GetTargetMask() & TARGET_FLAG_DEST_LOCATION) != 0; } void SpellCastTargets::Update(Unit* caster) { m_objectTarget = !m_objectTargetGUID.IsEmpty() ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : NULL; m_itemTarget = NULL; if (caster->GetTypeId() == TYPEID_PLAYER) { Player* player = caster->ToPlayer(); if (m_targetMask & TARGET_FLAG_ITEM) m_itemTarget = player->GetItemByGuid(m_itemTargetGUID); else if (m_targetMask & TARGET_FLAG_TRADE_ITEM) { if (m_itemTargetGUID == ObjectGuid::TradeItem) if (TradeData* pTrade = player->GetTradeData()) m_itemTarget = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED); } if (m_itemTarget) m_itemTargetEntry = m_itemTarget->GetEntry(); } // update positions by transport move if (HasSrc() && !m_src._transportGUID.IsEmpty()) { if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_src._transportGUID)) { m_src._position.Relocate(transport); m_src._position.RelocateOffset(m_src._transportOffset); } } if (HasDst() && !m_dst._transportGUID.IsEmpty()) { if (WorldObject* transport = ObjectAccessor::GetWorldObject(*caster, m_dst._transportGUID)) { m_dst._position.Relocate(transport); m_dst._position.RelocateOffset(m_dst._transportOffset); } } } void SpellCastTargets::OutDebug() const { if (!m_targetMask) TC_LOG_DEBUG("spells", "No targets"); TC_LOG_DEBUG("spells", "target mask: %u", m_targetMask); if (m_targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK)) TC_LOG_DEBUG("spells", "Object target: %s", m_objectTargetGUID.ToString().c_str()); if (m_targetMask & TARGET_FLAG_ITEM) TC_LOG_DEBUG("spells", "Item target: %s", m_itemTargetGUID.ToString().c_str()); if (m_targetMask & TARGET_FLAG_TRADE_ITEM) TC_LOG_DEBUG("spells", "Trade item target: %s", m_itemTargetGUID.ToString().c_str()); if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) TC_LOG_DEBUG("spells", "Source location: transport guid:%s trans offset: %s position: %s", m_src._transportGUID.ToString().c_str(), m_src._transportOffset.ToString().c_str(), m_src._position.ToString().c_str()); if (m_targetMask & TARGET_FLAG_DEST_LOCATION) TC_LOG_DEBUG("spells", "Destination location: transport guid:%s trans offset: %s position: %s", m_dst._transportGUID.ToString().c_str(), m_dst._transportOffset.ToString().c_str(), m_dst._position.ToString().c_str()); if (m_targetMask & TARGET_FLAG_STRING) TC_LOG_DEBUG("spells", "String: %s", m_strTarget.c_str()); TC_LOG_DEBUG("spells", "speed: %f", m_speed); TC_LOG_DEBUG("spells", "pitch: %f", m_pitch); } SpellValue::SpellValue(SpellInfo const* proto, Unit const* caster) { memset(EffectBasePoints, 0, sizeof(EffectBasePoints)); memset(EffectTriggerSpell, 0, sizeof(EffectTriggerSpell)); for (SpellEffectInfo const* effect : proto->GetEffects()) { if (effect) { EffectBasePoints[effect->EffectIndex] = effect->CalcBaseValue(caster, nullptr, 0, -1); EffectTriggerSpell[effect->EffectIndex] = effect->TriggerSpell; } } CustomBasePointsMask = 0; MaxAffectedTargets = proto->MaxAffectedTargets; RadiusMod = 1.0f; AuraStackAmount = 1; Duration = 0; } class TC_GAME_API SpellEvent : public BasicEvent { public: SpellEvent(Spell* spell); virtual ~SpellEvent(); virtual bool Execute(uint64 e_time, uint32 p_time) override; virtual void Abort(uint64 e_time) override; virtual bool IsDeletable() const override; protected: Spell* m_Spell; }; Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, ObjectGuid originalCasterGUID, bool skipCheck) : m_spellInfo(info), m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster), m_spellValue(new SpellValue(m_spellInfo, caster)), _spellEvent(nullptr) { m_customError = SPELL_CUSTOM_ERROR_NONE; m_skipCheck = skipCheck; m_fromClient = false; m_selfContainer = NULL; m_referencedFromCurrentSpell = false; m_executedCurrently = false; m_needComboPoints = m_spellInfo->NeedsComboPoints(); m_comboPointGain = 0; m_delayStart = 0; m_delayAtDamageCount = 0; m_applyMultiplierMask = 0; memset(m_damageMultipliers, 0, sizeof(m_damageMultipliers)); // Get data for type of attack m_attackType = info->GetAttackType(); m_spellSchoolMask = info->GetSchoolMask(); // Can be override for some spell (wand shoot for example) if (m_attackType == RANGED_ATTACK) // wand case if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER) if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK)) m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetTemplate()->GetDamageType()); if (!originalCasterGUID.IsEmpty()) m_originalCasterGUID = originalCasterGUID; else m_originalCasterGUID = m_caster->GetGUID(); if (m_originalCasterGUID == m_caster->GetGUID()) m_originalCaster = m_caster; else { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL; } m_spellState = SPELL_STATE_NULL; _triggeredCastFlags = triggerFlags; if (info->HasAttribute(SPELL_ATTR4_CAN_CAST_WHILE_CASTING)) _triggeredCastFlags = TriggerCastFlags(uint32(_triggeredCastFlags) | TRIGGERED_CAN_CAST_WHILE_CASTING_MASK); m_CastItem = NULL; m_castItemGUID.Clear(); m_castItemEntry = 0; m_castItemLevel = -1; m_castFlagsEx = 0; unitTarget = NULL; itemTarget = NULL; gameObjTarget = NULL; destTarget = NULL; damage = 0; targetMissInfo = SPELL_MISS_NONE; variance = 0.0f; effectHandleMode = SPELL_EFFECT_HANDLE_LAUNCH; effectInfo = nullptr; m_damage = 0; m_healing = 0; m_procAttacker = 0; m_procVictim = 0; m_hitMask = 0; focusObject = NULL; m_castId = ObjectGuid::Create<HighGuid::Cast>(SPELL_CAST_SOURCE_NORMAL, m_caster->GetMapId(), m_spellInfo->Id, m_caster->GetMap()->GenerateLowGuid<HighGuid::Cast>()); memset(m_misc.Raw.Data, 0, sizeof(m_misc.Raw.Data)); m_SpellVisual = caster->GetCastSpellXSpellVisualId(m_spellInfo); m_triggeredByAuraSpell = NULL; m_spellAura = NULL; //Auto Shot & Shoot (wand) m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell(); m_runesState = 0; m_casttime = 0; // setup to correct value in Spell::prepare, must not be used before. m_timer = 0; // will set to castime in prepare m_channeledDuration = 0; // will be setup in Spell::handle_immediate m_launchHandled = false; m_immediateHandled = false; m_currentTargetInfo = nullptr; m_channelTargetEffectMask = 0; // Determine if spell can be reflected back to the caster // Patch 1.2 notes: Spell Reflection no longer reflects abilities m_canReflect = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !m_spellInfo->HasAttribute(SPELL_ATTR0_ABILITY) && !m_spellInfo->HasAttribute(SPELL_ATTR1_CANT_BE_REFLECTED) && !m_spellInfo->HasAttribute(SPELL_ATTR0_UNAFFECTED_BY_INVULNERABILITY) && !m_spellInfo->IsPassive(); CleanupTargetList(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) m_destTargets[i] = SpellDestination(*m_caster); dispellSuccess = false; } Spell::~Spell() { // unload scripts for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr) { (*itr)->_Unload(); delete (*itr); } if (m_referencedFromCurrentSpell && m_selfContainer && *m_selfContainer == this) { // Clean the reference to avoid later crash. // If this error is repeating, we may have to add an ASSERT to better track down how we get into this case. TC_LOG_ERROR("spells", "SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id); *m_selfContainer = NULL; } if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER) ASSERT(m_caster->ToPlayer()->m_spellModTakingSpell != this); delete m_spellValue; } void Spell::InitExplicitTargets(SpellCastTargets const& targets) { m_targets = targets; m_targets.SetOrigUnitTarget(m_targets.GetUnitTarget()); // this function tries to correct spell explicit targets for spell // client doesn't send explicit targets correctly sometimes - we need to fix such spells serverside // this also makes sure that we correctly send explicit targets to client (removes redundant data) uint32 neededTargets = m_spellInfo->GetExplicitTargetMask(); if (WorldObject* target = m_targets.GetObjectTarget()) { // check if object target is valid with needed target flags // for unit case allow corpse target mask because player with not released corpse is a unit target if ((target->ToUnit() && !(neededTargets & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK))) || (target->ToGameObject() && !(neededTargets & TARGET_FLAG_GAMEOBJECT_MASK)) || (target->ToCorpse() && !(neededTargets & TARGET_FLAG_CORPSE_MASK))) m_targets.RemoveObjectTarget(); } else { // try to select correct unit target if not provided by client or by serverside cast if (neededTargets & (TARGET_FLAG_UNIT_MASK)) { Unit* unit = NULL; // try to use player selection as a target if (Player* playerCaster = m_caster->ToPlayer()) { // selection has to be found and to be valid target for the spell if (Unit* selectedUnit = ObjectAccessor::GetUnit(*m_caster, playerCaster->GetTarget())) if (m_spellInfo->CheckExplicitTarget(m_caster, selectedUnit) == SPELL_CAST_OK) unit = selectedUnit; } // try to use attacked unit as a target else if ((m_caster->GetTypeId() == TYPEID_UNIT) && neededTargets & (TARGET_FLAG_UNIT_ENEMY | TARGET_FLAG_UNIT)) unit = m_caster->GetVictim(); // didn't find anything - let's use self as target if (!unit && neededTargets & (TARGET_FLAG_UNIT_RAID | TARGET_FLAG_UNIT_PARTY | TARGET_FLAG_UNIT_ALLY)) unit = m_caster; m_targets.SetUnitTarget(unit); } } // check if spell needs dst target if (neededTargets & TARGET_FLAG_DEST_LOCATION) { // and target isn't set if (!m_targets.HasDst()) { // try to use unit target if provided if (WorldObject* target = targets.GetObjectTarget()) m_targets.SetDst(*target); // or use self if not available else m_targets.SetDst(*m_caster); } } else m_targets.RemoveDst(); if (neededTargets & TARGET_FLAG_SOURCE_LOCATION) { if (!targets.HasSrc()) m_targets.SetSrc(*m_caster); } else m_targets.RemoveSrc(); } void Spell::SelectExplicitTargets() { // here go all explicit target changes made to explicit targets after spell prepare phase is finished if (Unit* target = m_targets.GetUnitTarget()) { // check for explicit target redirection, for Grounding Totem for example if (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT_ENEMY || (m_spellInfo->GetExplicitTargetMask() & TARGET_FLAG_UNIT && !m_caster->IsFriendlyTo(target))) { Unit* redirect; switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: redirect = m_caster->GetMagicHitRedirectTarget(target, m_spellInfo); break; case SPELL_DAMAGE_CLASS_MELEE: case SPELL_DAMAGE_CLASS_RANGED: redirect = m_caster->GetMeleeHitRedirectTarget(target, m_spellInfo); break; default: redirect = NULL; break; } if (redirect && (redirect != target)) m_targets.SetUnitTarget(redirect); } } } void Spell::SelectSpellTargets() { // select targets for cast phase SelectExplicitTargets(); uint32 processedAreaEffectsMask = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; // not call for empty effect. // Also some spells use not used effect targets for store targets for dummy effect in triggered spells if (!effect->IsEffect()) continue; // set expected type of implicit targets to be sent to client uint32 implicitTargetMask = GetTargetFlagMask(effect->TargetA.GetObjectType()) | GetTargetFlagMask(effect->TargetB.GetObjectType()); if (implicitTargetMask & TARGET_FLAG_UNIT) m_targets.SetTargetFlag(TARGET_FLAG_UNIT); if (implicitTargetMask & (TARGET_FLAG_GAMEOBJECT | TARGET_FLAG_GAMEOBJECT_ITEM)) m_targets.SetTargetFlag(TARGET_FLAG_GAMEOBJECT); SelectEffectImplicitTargets(SpellEffIndex(effect->EffectIndex), effect->TargetA, processedAreaEffectsMask); SelectEffectImplicitTargets(SpellEffIndex(effect->EffectIndex), effect->TargetB, processedAreaEffectsMask); // Select targets of effect based on effect type // those are used when no valid target could be added for spell effect based on spell target type // some spell effects use explicit target as a default target added to target map (like SPELL_EFFECT_LEARN_SPELL) // some spell effects add target to target map only when target type specified (like SPELL_EFFECT_WEAPON) // some spell effects don't add anything to target map (confirmed with sniffs) (like SPELL_EFFECT_DESTROY_ALL_TOTEMS) SelectEffectTypeImplicitTargets(effect->EffectIndex); if (m_targets.HasDst()) AddDestTarget(*m_targets.GetDst(), effect->EffectIndex); if (m_spellInfo->IsChanneled()) { // maybe do this for all spells? if (m_UniqueTargetInfo.empty() && m_UniqueGOTargetInfo.empty() && m_UniqueItemInfo.empty() && !m_targets.HasDst()) { SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); return; } uint32 mask = (1 << effect->EffectIndex); for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->effectMask & mask) { m_channelTargetEffectMask |= mask; break; } } } } if (uint64 dstDelay = CalculateDelayMomentForDst(m_spellInfo->LaunchDelay)) m_delayMoment = dstDelay; } uint64 Spell::CalculateDelayMomentForDst(float launchDelay) const { if (m_targets.HasDst()) { if (m_targets.HasTraj()) { float speed = m_targets.GetSpeedXY(); if (speed > 0.0f) return uint64(std::floor((m_targets.GetDist2d() / speed + launchDelay) * 1000.0f)); } else if (m_spellInfo->HasAttribute(SPELL_ATTR9_SPECIAL_DELAY_CALCULATION)) return uint64(std::floor((m_spellInfo->Speed + launchDelay) * 1000.0f)); else if (m_spellInfo->Speed > 0.0f) { // We should not subtract caster size from dist calculation (fixes execution time desync with animation on client, eg. Malleable Goo cast by PP) float dist = m_caster->GetExactDist(*m_targets.GetDstPos()); return uint64(std::floor((dist / m_spellInfo->Speed + launchDelay) * 1000.0f)); } return uint64(std::floor(launchDelay * 1000.0f)); } return 0; } void Spell::RecalculateDelayMomentForDst() { m_delayMoment = CalculateDelayMomentForDst(0.0f); m_caster->m_Events.ModifyEventTime(_spellEvent, GetDelayStart() + m_delayMoment); } void Spell::SelectEffectImplicitTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32& processedEffectMask) { if (!targetType.GetTarget()) return; uint32 effectMask = 1 << effIndex; // set the same target list for all effects // some spells appear to need this, however this requires more research switch (targetType.GetSelectionCategory()) { case TARGET_SELECT_CATEGORY_NEARBY: case TARGET_SELECT_CATEGORY_CONE: case TARGET_SELECT_CATEGORY_AREA: //case TARGET_SELECT_CATEGORY_LINE: // targets for effect already selected if (effectMask & processedEffectMask) return; if (SpellEffectInfo const* _effect = m_spellInfo->GetEffect(effIndex)) { // choose which targets we can select at once for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { //for (uint32 j = effIndex + 1; j < MAX_SPELL_EFFECTS; ++j) if (!effect || effect->EffectIndex <= uint32(effIndex)) continue; if (effect->IsEffect() && _effect->TargetA.GetTarget() == effect->TargetA.GetTarget() && _effect->TargetB.GetTarget() == effect->TargetB.GetTarget() && _effect->ImplicitTargetConditions == effect->ImplicitTargetConditions && _effect->CalcRadius(m_caster) == effect->CalcRadius(m_caster) && CheckScriptEffectImplicitTargets(effIndex, effect->EffectIndex)) { effectMask |= 1 << effect->EffectIndex; } } } processedEffectMask |= effectMask; break; default: break; } switch (targetType.GetSelectionCategory()) { case TARGET_SELECT_CATEGORY_CHANNEL: SelectImplicitChannelTargets(effIndex, targetType); break; case TARGET_SELECT_CATEGORY_NEARBY: SelectImplicitNearbyTargets(effIndex, targetType, effectMask); break; case TARGET_SELECT_CATEGORY_CONE: SelectImplicitConeTargets(effIndex, targetType, effectMask); break; case TARGET_SELECT_CATEGORY_AREA: SelectImplicitAreaTargets(effIndex, targetType, effectMask); break; case TARGET_SELECT_CATEGORY_TRAJ: // just in case there is no dest, explanation in SelectImplicitDestDestTargets CheckDst(); SelectImplicitTrajTargets(effIndex, targetType); break; case TARGET_SELECT_CATEGORY_DEFAULT: switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_SRC: switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: m_targets.SetSrc(*m_caster); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_SRC"); break; } break; case TARGET_OBJECT_TYPE_DEST: switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: SelectImplicitCasterDestTargets(effIndex, targetType); break; case TARGET_REFERENCE_TYPE_TARGET: SelectImplicitTargetDestTargets(effIndex, targetType); break; case TARGET_REFERENCE_TYPE_DEST: SelectImplicitDestDestTargets(effIndex, targetType); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT_DEST"); break; } break; default: switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_CASTER: SelectImplicitCasterObjectTargets(effIndex, targetType); break; case TARGET_REFERENCE_TYPE_TARGET: SelectImplicitTargetObjectTargets(effIndex, targetType); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target reference type for TARGET_TYPE_OBJECT"); break; } break; } break; case TARGET_SELECT_CATEGORY_NYI: TC_LOG_DEBUG("spells", "SPELL: target type %u, found in spellID %u, effect %u is not implemented yet!", m_spellInfo->Id, effIndex, targetType.GetTarget()); break; default: ASSERT(false && "Spell::SelectEffectImplicitTargets: received not implemented select target category"); break; } } void Spell::SelectImplicitChannelTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target reference type"); return; } Spell* channeledSpell = m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL); if (!channeledSpell) { TC_LOG_DEBUG("spells", "Spell::SelectImplicitChannelTargets: cannot find channel spell for spell ID %u, effect %u", m_spellInfo->Id, effIndex); return; } switch (targetType.GetTarget()) { case TARGET_UNIT_CHANNEL_TARGET: { for (ObjectGuid const& channelTarget : m_originalCaster->m_unitData->ChannelObjects) { WorldObject* target = ObjectAccessor::GetUnit(*m_caster, channelTarget); CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); // unit target may be no longer avalible - teleported out of map for example Unit* unitTarget = target ? target->ToUnit() : nullptr; if (unitTarget) AddUnitTarget(unitTarget, 1 << effIndex); else TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); } break; } case TARGET_DEST_CHANNEL_TARGET: if (channeledSpell->m_targets.HasDst()) m_targets.SetDst(channeledSpell->m_targets); else { auto const& channelObjects = m_originalCaster->m_unitData->ChannelObjects; WorldObject* target = channelObjects.size() > 0 ? ObjectAccessor::GetWorldObject(*m_caster, *channelObjects.begin()) : nullptr; if (target) { CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); if (target) { SpellDestination dest(*target); CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.SetDst(dest); } } else TC_LOG_DEBUG("spells", "SPELL: cannot find channel spell destination for spell ID %u, effect %u", m_spellInfo->Id, effIndex); } break; case TARGET_DEST_CHANNEL_CASTER: { SpellDestination dest(*channeledSpell->GetCaster()); CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.SetDst(dest); break; } default: ASSERT(false && "Spell::SelectImplicitChannelTargets: received not implemented target type"); break; } } void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target reference type"); return; } SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); if (!effect) return; float range = 0.0f; switch (targetType.GetCheckType()) { case TARGET_CHECK_ENEMY: range = m_spellInfo->GetMaxRange(false, m_caster, this); break; case TARGET_CHECK_ALLY: case TARGET_CHECK_PARTY: case TARGET_CHECK_RAID: case TARGET_CHECK_RAID_CLASS: case TARGET_CHECK_RAID_DEATH: range = m_spellInfo->GetMaxRange(true, m_caster, this); break; case TARGET_CHECK_ENTRY: case TARGET_CHECK_DEFAULT: range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive(), m_caster, this); break; default: ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented selection check type"); break; } ConditionContainer* condList = effect->ImplicitTargetConditions; // handle emergency case - try to use other provided targets if no conditions provided if (targetType.GetCheckType() == TARGET_CHECK_ENTRY && (!condList || condList->empty())) { TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: no conditions entry for target with TARGET_CHECK_ENTRY of spell ID %u, effect %u - selecting default targets", m_spellInfo->Id, effIndex); switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_GOBJ: if (m_spellInfo->RequiresSpellFocus) { if (focusObject) AddGOTarget(focusObject, effMask); else { SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); } return; } break; case TARGET_OBJECT_TYPE_DEST: if (m_spellInfo->RequiresSpellFocus) { if (focusObject) { SpellDestination dest(*focusObject); CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.SetDst(dest); } else { SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); } return; } break; default: break; } } WorldObject* target = SearchNearbyTarget(range, targetType.GetObjectType(), targetType.GetCheckType(), condList); if (!target) { TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: cannot find nearby target for spell ID %u, effect %u", m_spellInfo->Id, effIndex); SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); return; } CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); if (!target) { TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set NULL target, effect %u", m_spellInfo->Id, effIndex); SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); return; } switch (targetType.GetObjectType()) { case TARGET_OBJECT_TYPE_UNIT: if (Unit* unit = target->ToUnit()) AddUnitTarget(unit, effMask, true, false); else { TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set object of wrong type, expected unit, got %s, effect %u", m_spellInfo->Id, target->GetGUID().GetTypeName(), effMask); SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); return; } break; case TARGET_OBJECT_TYPE_GOBJ: if (GameObject* gobjTarget = target->ToGameObject()) AddGOTarget(gobjTarget, effMask); else { TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set object of wrong type, expected gameobject, got %s, effect %u", m_spellInfo->Id, target->GetGUID().GetTypeName(), effMask); SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); return; } break; case TARGET_OBJECT_TYPE_DEST: { SpellDestination dest(*target); CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.SetDst(dest); break; } default: ASSERT(false && "Spell::SelectImplicitNearbyTargets: received not implemented target object type"); break; } SelectImplicitChainTargets(effIndex, targetType, target, effMask); } void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitConeTargets: received not implemented target reference type"); return; } std::list<WorldObject*> targets; SpellTargetObjectTypes objectType = targetType.GetObjectType(); SpellTargetCheckTypes selectionType = targetType.GetCheckType(); SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); if (!effect) return; ConditionContainer* condList = effect->ImplicitTargetConditions; float radius = effect->CalcRadius(m_caster) * m_spellValue->RadiusMod; if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList)) { Trinity::WorldObjectSpellConeTargetCheck check(DegToRad(m_spellInfo->ConeAngle), m_spellInfo->Width ? m_spellInfo->Width : m_caster->GetCombatReach(), radius, m_caster, m_spellInfo, selectionType, condList); Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellConeTargetCheck> searcher(m_caster, targets, check, containerTypeMask); SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellConeTargetCheck> >(searcher, containerTypeMask, m_caster, m_caster, radius); CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType); if (!targets.empty()) { // Other special target selection goes here if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) Trinity::Containers::RandomResize(targets, maxTargets); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) AddUnitTarget(unit, effMask, false); else if (GameObject* gObjTarget = (*itr)->ToGameObject()) AddGOTarget(gObjTarget, effMask); } } } } void Spell::SelectImplicitLineTargets(SpellEffIndex /*effIndex*/, SpellImplicitTargetInfo const& /*targetType*/, uint32 /*effMask*/) { /*if (targetType.GetReferenceType() != TARGET_REFERENCE_TYPE_CASTER) { ASSERT(false && "Spell::SelectImplicitLineTargets: received not implemented target reference type"); return; } std::list<WorldObject*> targets; SpellTargetObjectTypes objectType = targetType.GetObjectType(); SpellTargetCheckTypes selectionType = targetType.GetCheckType(); float radius = m_spellInfo->GetEffect(effIndex)->CalcRadius(m_caster, this); if (uint32 containerTypeMask = GetSearcherTypeMask(objectType, GetEffect(effIndex)->ImplicitTargetConditions)) { Trinity::WorldObjectSpellLineTargetCheck check(radius, m_caster, m_spellInfo, selectionType, GetEffect(effIndex)->ImplicitTargetConditions); Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellLineTargetCheck> searcher(m_caster, targets, check, containerTypeMask); SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellLineTargetCheck> >(searcher, containerTypeMask, m_caster, m_caster, radius); CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType); if (!targets.empty()) { if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) Trinity::Containers::RandomResize(targets, maxTargets); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { if (Unit* unitTarget = (*itr)->ToUnit()) AddUnitTarget(unitTarget, effMask, false); else if (GameObject* gObjTarget = (*itr)->ToGameObject()) AddGOTarget(gObjTarget, effMask); } } }*/ } void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { Unit* referer = NULL; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: case TARGET_REFERENCE_TYPE_DEST: case TARGET_REFERENCE_TYPE_CASTER: referer = m_caster; break; case TARGET_REFERENCE_TYPE_TARGET: referer = m_targets.GetUnitTarget(); break; case TARGET_REFERENCE_TYPE_LAST: { // find last added target for this effect for (std::vector<TargetInfo>::reverse_iterator ihit = m_UniqueTargetInfo.rbegin(); ihit != m_UniqueTargetInfo.rend(); ++ihit) { if (ihit->effectMask & (1 << effIndex)) { referer = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); break; } } break; } default: ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); return; } if (!referer) return; Position const* center = NULL; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: center = m_targets.GetSrcPos(); break; case TARGET_REFERENCE_TYPE_DEST: center = m_targets.GetDstPos(); break; case TARGET_REFERENCE_TYPE_CASTER: case TARGET_REFERENCE_TYPE_TARGET: case TARGET_REFERENCE_TYPE_LAST: center = referer; break; default: ASSERT(false && "Spell::SelectImplicitAreaTargets: received not implemented target reference type"); return; } std::list<WorldObject*> targets; SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); if (!effect) return; switch (targetType.GetTarget()) { case TARGET_UNIT_TARGET_ALLY_OR_RAID: if (Unit* targetedUnit = m_targets.GetUnitTarget()) { if (!m_caster->IsInRaidWith(targetedUnit)) { targets.push_back(m_targets.GetUnitTarget()); CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType); if (!targets.empty()) { // Other special target selection goes here if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) Trinity::Containers::RandomResize(targets, maxTargets); for (WorldObject* target : targets) { if (Unit* unit = target->ToUnit()) AddUnitTarget(unit, effMask, false, true, center); else if (GameObject* gObjTarget = target->ToGameObject()) AddGOTarget(gObjTarget, effMask); } } return; } center = targetedUnit; } break; case TARGET_UNIT_CASTER_AND_SUMMONS: targets.push_back(m_caster); break; default: break; } float radius = effect->CalcRadius(m_caster) * m_spellValue->RadiusMod; if (radius) SearchAreaTargets(targets, radius, center, referer, targetType.GetObjectType(), targetType.GetCheckType(), effect->ImplicitTargetConditions); CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType); if (!targets.empty()) { // Other special target selection goes here if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) Trinity::Containers::RandomResize(targets, maxTargets); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) AddUnitTarget(unit, effMask, false, true, center); else if (GameObject* gObjTarget = (*itr)->ToGameObject()) AddGOTarget(gObjTarget, effMask); } } } void Spell::SelectImplicitCasterDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { SpellDestination dest(*m_caster); switch (targetType.GetTarget()) { case TARGET_DEST_CASTER: break; case TARGET_DEST_HOME: if (Player* playerCaster = m_caster->ToPlayer()) dest = SpellDestination(playerCaster->m_homebindX, playerCaster->m_homebindY, playerCaster->m_homebindZ, playerCaster->GetOrientation(), playerCaster->m_homebindMapId); break; case TARGET_DEST_DB: if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id, effIndex)) { /// @todo fix this check if (m_spellInfo->HasEffect(SPELL_EFFECT_TELEPORT_UNITS) || m_spellInfo->HasEffect(SPELL_EFFECT_BIND)) dest = SpellDestination(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId); else if (st->target_mapId == m_caster->GetMapId()) dest = SpellDestination(st->target_X, st->target_Y, st->target_Z, st->target_Orientation); } else { TC_LOG_DEBUG("spells", "SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id); if (WorldObject* target = m_targets.GetObjectTarget()) dest = SpellDestination(*target); } break; case TARGET_DEST_CASTER_FISHING: { float minDist = m_spellInfo->GetMinRange(true); float maxDist = m_spellInfo->GetMaxRange(true); float dist = frand(minDist, maxDist); float x, y, z; float angle = float(rand_norm()) * static_cast<float>(M_PI * 35.0f / 180.0f) - static_cast<float>(M_PI * 17.5f / 180.0f); m_caster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS, dist, angle); float ground = m_caster->GetMap()->GetHeight(m_caster->GetPhaseShift(), x, y, z, true, 50.0f); float liquidLevel = VMAP_INVALID_HEIGHT_VALUE; LiquidData liquidData; if (m_caster->GetMap()->GetLiquidStatus(m_caster->GetPhaseShift(), x, y, z, MAP_ALL_LIQUIDS, &liquidData)) liquidLevel = liquidData.level; if (liquidLevel <= ground) // When there is no liquid Map::GetWaterOrGroundLevel returns ground level { SendCastResult(SPELL_FAILED_NOT_HERE); SendChannelUpdate(0); finish(false); return; } if (ground + 0.75 > liquidLevel) { SendCastResult(SPELL_FAILED_TOO_SHALLOW); SendChannelUpdate(0); finish(false); return; } dest = SpellDestination(x, y, liquidLevel, m_caster->GetOrientation()); break; } case TARGET_DEST_CASTER_GROUND: { float groundZ = m_caster->GetMap()->GetHeight(m_caster->GetPhaseShift(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ(), true, MAX_HEIGHT); dest = SpellDestination(m_caster->GetPositionX(), m_caster->GetPositionY(), groundZ, m_caster->GetOrientation()); break; } case TARGET_DEST_LAST_QUEST_GIVER: { if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex)) { float dist = effect->CalcRadius(m_caster); if (Player* casterPlayer = m_caster->ToPlayer()) if (WorldObject* target = casterPlayer->GetLastQuestGiver()) if (casterPlayer->GetDistance(target) < dist) dest = SpellDestination(*target); } break; } case TARGET_DEST_SUMMONER: if (TempSummon const* casterSummon = m_caster->ToTempSummon()) if (Unit const* summoner = casterSummon->GetSummoner()) dest = SpellDestination(*summoner); break; default: { if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex)) { float dist = effect->CalcRadius(m_caster); float angle = targetType.CalcDirectionAngle(); float objSize = m_caster->GetCombatReach(); switch (targetType.GetTarget()) { case TARGET_DEST_CASTER_SUMMON: dist = PET_FOLLOW_DIST; break; case TARGET_DEST_CASTER_RANDOM: if (dist > objSize) dist = objSize + (dist - objSize) * float(rand_norm()); break; case TARGET_DEST_CASTER_FRONT_LEFT: case TARGET_DEST_CASTER_BACK_LEFT: case TARGET_DEST_CASTER_FRONT_RIGHT: case TARGET_DEST_CASTER_BACK_RIGHT: { static float const DefaultTotemDistance = 3.0f; if (!effect->HasRadius() && !effect->HasMaxRadius()) dist = DefaultTotemDistance; break; } default: break; } if (dist < objSize) dist = objSize; Position pos = dest._position; m_caster->MovePositionToFirstCollision(pos, dist, angle); dest.Relocate(pos); } break; } } CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.SetDst(dest); } void Spell::SelectImplicitTargetDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { ASSERT(m_targets.GetObjectTarget() && "Spell::SelectImplicitTargetDestTargets - no explicit object target available!"); WorldObject* target = m_targets.GetObjectTarget(); SpellDestination dest(*target); switch (targetType.GetTarget()) { case TARGET_DEST_TARGET_ENEMY: case TARGET_DEST_TARGET_ANY: case TARGET_DEST_TARGET_ALLY: break; default: { if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex)) { float angle = targetType.CalcDirectionAngle(); float objSize = target->GetCombatReach(); float dist = effect->CalcRadius(m_caster); if (dist < objSize) dist = objSize; else if (targetType.GetTarget() == TARGET_DEST_TARGET_RANDOM) dist = objSize + (dist - objSize) * float(rand_norm()); Position pos = dest._position; target->MovePositionToFirstCollision(pos, dist, angle); dest.Relocate(pos); } break; } } CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.SetDst(dest); } void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { // set destination to caster if no dest provided // can only happen if previous destination target could not be set for some reason // (not found nearby target, or channel target for example // maybe we should abort the spell in such case? CheckDst(); SpellDestination dest(*m_targets.GetDst()); switch (targetType.GetTarget()) { case TARGET_DEST_DYNOBJ_ENEMY: case TARGET_DEST_DYNOBJ_ALLY: case TARGET_DEST_DYNOBJ_NONE: case TARGET_DEST_DEST: return; default: { if (SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex)) { float angle = targetType.CalcDirectionAngle(); float dist = effect->CalcRadius(m_caster); if (targetType.GetTarget() == TARGET_DEST_DEST_RANDOM) dist *= float(rand_norm()); Position pos = dest._position; m_caster->MovePositionToFirstCollision(pos, dist, angle); dest.Relocate(pos); } break; } } CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.ModDst(dest); } void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { WorldObject* target = NULL; bool checkIfValid = true; switch (targetType.GetTarget()) { case TARGET_UNIT_CASTER: target = m_caster; checkIfValid = false; break; case TARGET_UNIT_MASTER: target = m_caster->GetCharmerOrOwner(); break; case TARGET_UNIT_PET: target = m_caster->GetGuardianPet(); break; case TARGET_UNIT_SUMMONER: if (m_caster->IsSummon()) target = m_caster->ToTempSummon()->GetSummoner(); break; case TARGET_UNIT_VEHICLE: target = m_caster->GetVehicleBase(); break; case TARGET_UNIT_PASSENGER_0: case TARGET_UNIT_PASSENGER_1: case TARGET_UNIT_PASSENGER_2: case TARGET_UNIT_PASSENGER_3: case TARGET_UNIT_PASSENGER_4: case TARGET_UNIT_PASSENGER_5: case TARGET_UNIT_PASSENGER_6: case TARGET_UNIT_PASSENGER_7: if (m_caster->IsVehicle()) target = m_caster->GetVehicleKit()->GetPassenger(targetType.GetTarget() - TARGET_UNIT_PASSENGER_0); break; case TARGET_UNIT_OWN_CRITTER: target = ObjectAccessor::GetCreatureOrPetOrVehicle(*m_caster, m_caster->GetCritterGUID()); break; default: break; } CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); if (target && target->ToUnit()) AddUnitTarget(target->ToUnit(), 1 << effIndex, checkIfValid); } void Spell::SelectImplicitTargetObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { ASSERT((m_targets.GetObjectTarget() || m_targets.GetItemTarget()) && "Spell::SelectImplicitTargetObjectTargets - no explicit object or item target available!"); WorldObject* target = m_targets.GetObjectTarget(); CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); if (target) { if (Unit* unit = target->ToUnit()) AddUnitTarget(unit, 1 << effIndex, true, false); else if (GameObject* gobj = target->ToGameObject()) AddGOTarget(gobj, 1 << effIndex); SelectImplicitChainTargets(effIndex, targetType, target, 1 << effIndex); } // Script hook can remove object target and we would wrongly land here else if (Item* item = m_targets.GetItemTarget()) AddItemTarget(item, 1 << effIndex); } void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, WorldObject* target, uint32 effMask) { SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); if (!effect) return; uint32 maxTargets = effect->ChainTargets; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); if (maxTargets > 1) { // mark damage multipliers as used for (SpellEffectInfo const* eff : m_spellInfo->GetEffects()) if (eff && (effMask & (1 << eff->EffectIndex))) m_damageMultipliers[eff->EffectIndex] = 1.0f; m_applyMultiplierMask |= effMask; std::list<WorldObject*> targets; SearchChainTargets(targets, maxTargets - 1, target, targetType.GetObjectType(), targetType.GetCheckType() , effect->ImplicitTargetConditions, targetType.GetTarget() == TARGET_UNIT_TARGET_CHAINHEAL_ALLY); // Chain primary target is added earlier CallScriptObjectAreaTargetSelectHandlers(targets, effIndex, targetType); for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end(); ++itr) if (Unit* unit = (*itr)->ToUnit()) AddUnitTarget(unit, effMask, false); } } float tangent(float x) { x = std::tan(x); //if (x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x; //if (x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max(); //if (x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max(); if (x < 100000.0f && x > -100000.0f) return x; if (x >= 100000.0f) return 100000.0f; if (x <= 100000.0f) return -100000.0f; return 0.0f; } void Spell::SelectImplicitTrajTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { if (!m_targets.HasTraj()) return; float dist2d = m_targets.GetDist2d(); if (!dist2d) return; Position srcPos = *m_targets.GetSrcPos(); srcPos.SetOrientation(m_caster->GetOrientation()); float srcToDestDelta = m_targets.GetDstPos()->m_positionZ - srcPos.m_positionZ; SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); std::list<WorldObject*> targets; Trinity::WorldObjectSpellTrajTargetCheck check(dist2d, &srcPos, m_caster, m_spellInfo, targetType.GetCheckType(), effect->ImplicitTargetConditions); Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellTrajTargetCheck> searcher(m_caster, targets, check, GRID_MAP_TYPE_MASK_ALL); SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellTrajTargetCheck> > (searcher, GRID_MAP_TYPE_MASK_ALL, m_caster, &srcPos, dist2d); if (targets.empty()) return; targets.sort(Trinity::ObjectDistanceOrderPred(m_caster)); float b = tangent(m_targets.GetPitch()); float a = (srcToDestDelta - dist2d * b) / (dist2d * dist2d); if (a > -0.0001f) a = 0; // We should check if triggered spell has greater range (which is true in many cases, and initial spell has too short max range) // limit max range to 300 yards, sometimes triggered spells can have 50000yds float bestDist = m_spellInfo->GetMaxRange(false); if (SpellInfo const* triggerSpellInfo = sSpellMgr->GetSpellInfo(effect->TriggerSpell, GetCastDifficulty())) bestDist = std::min(std::max(bestDist, triggerSpellInfo->GetMaxRange(false)), std::min(dist2d, 300.0f)); std::list<WorldObject*>::const_iterator itr = targets.begin(); for (; itr != targets.end(); ++itr) { if (m_spellInfo->CheckTarget(m_caster, *itr, true) != SPELL_CAST_OK) continue; if (Unit* unit = (*itr)->ToUnit()) { if (m_caster == *itr || m_caster->IsOnVehicle(unit) || unit->GetVehicle()) continue; if (Creature* creatureTarget = unit->ToCreature()) { if (!(creatureTarget->GetCreatureTemplate()->type_flags & CREATURE_TYPE_FLAG_CAN_COLLIDE_WITH_MISSILES)) continue; } } const float size = std::max((*itr)->GetCombatReach(), 1.0f); const float objDist2d = srcPos.GetExactDist2d(*itr); const float dz = (*itr)->GetPositionZ() - srcPos.m_positionZ; const float horizontalDistToTraj = std::fabs(objDist2d * std::sin(srcPos.GetRelativeAngle(*itr))); const float sizeFactor = std::cos((horizontalDistToTraj / size) * (M_PI / 2.0f)); const float distToHitPoint = std::max(objDist2d * std::cos(srcPos.GetRelativeAngle(*itr)) - size * sizeFactor, 0.0f); const float height = distToHitPoint * (a * distToHitPoint + b); if (fabs(dz - height) > size + b / 2.0f + TRAJECTORY_MISSILE_SIZE) continue; if (distToHitPoint < bestDist) { bestDist = distToHitPoint; break; } } if (dist2d > bestDist) { float x = m_targets.GetSrcPos()->m_positionX + std::cos(m_caster->GetOrientation()) * bestDist; float y = m_targets.GetSrcPos()->m_positionY + std::sin(m_caster->GetOrientation()) * bestDist; float z = m_targets.GetSrcPos()->m_positionZ + bestDist * (a * bestDist + b); SpellDestination dest(x, y, z, m_caster->GetOrientation()); CallScriptDestinationTargetSelectHandlers(dest, effIndex, targetType); m_targets.ModDst(dest); } if (Vehicle* veh = m_caster->GetVehicleKit()) veh->SetLastShootPos(*m_targets.GetDstPos()); } void Spell::SelectEffectTypeImplicitTargets(uint32 effIndex) { // special case for SPELL_EFFECT_SUMMON_RAF_FRIEND and SPELL_EFFECT_SUMMON_PLAYER /// @todo this is a workaround - target shouldn't be stored in target map for those spells SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); if (!effect) return; switch (effect->Effect) { case SPELL_EFFECT_SUMMON_RAF_FRIEND: case SPELL_EFFECT_SUMMON_PLAYER: if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->GetTarget().IsEmpty()) { WorldObject* target = ObjectAccessor::FindPlayer(m_caster->GetTarget()); CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex), SpellImplicitTargetInfo()); if (target && target->ToPlayer()) AddUnitTarget(target->ToUnit(), 1 << effIndex, false); } return; default: break; } // select spell implicit targets based on effect type if (!effect->GetImplicitTargetType()) return; uint32 targetMask = effect->GetMissingTargetMask(); if (!targetMask) return; WorldObject* target = NULL; switch (effect->GetImplicitTargetType()) { // add explicit object target or self to the target map case EFFECT_IMPLICIT_TARGET_EXPLICIT: // player which not released his spirit is Unit, but target flag for it is TARGET_FLAG_CORPSE_MASK if (targetMask & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK)) { if (Unit* unit = m_targets.GetUnitTarget()) target = unit; else if (targetMask & TARGET_FLAG_CORPSE_MASK) { if (Corpse* corpseTarget = m_targets.GetCorpseTarget()) { /// @todo this is a workaround - corpses should be added to spell target map too, but we can't do that so we add owner instead if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) target = owner; } } else //if (targetMask & TARGET_FLAG_UNIT_MASK) target = m_caster; } if (targetMask & TARGET_FLAG_ITEM_MASK) { if (Item* item = m_targets.GetItemTarget()) AddItemTarget(item, 1 << effIndex); return; } if (targetMask & TARGET_FLAG_GAMEOBJECT_MASK) target = m_targets.GetGOTarget(); break; // add self to the target map case EFFECT_IMPLICIT_TARGET_CASTER: if (targetMask & TARGET_FLAG_UNIT_MASK) target = m_caster; break; default: break; } CallScriptObjectTargetSelectHandlers(target, SpellEffIndex(effIndex), SpellImplicitTargetInfo()); if (target) { if (target->ToUnit()) AddUnitTarget(target->ToUnit(), 1 << effIndex, false); else if (target->ToGameObject()) AddGOTarget(target->ToGameObject(), 1 << effIndex); } } uint32 Spell::GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionContainer* condList) { // this function selects which containers need to be searched for spell target uint32 retMask = GRID_MAP_TYPE_MASK_ALL; // filter searchers based on searched object type switch (objType) { case TARGET_OBJECT_TYPE_UNIT: case TARGET_OBJECT_TYPE_UNIT_AND_DEST: case TARGET_OBJECT_TYPE_CORPSE: case TARGET_OBJECT_TYPE_CORPSE_ENEMY: case TARGET_OBJECT_TYPE_CORPSE_ALLY: retMask &= GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_CREATURE; break; case TARGET_OBJECT_TYPE_GOBJ: case TARGET_OBJECT_TYPE_GOBJ_ITEM: retMask &= GRID_MAP_TYPE_MASK_GAMEOBJECT; break; default: break; } if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_DEAD)) retMask &= ~GRID_MAP_TYPE_MASK_CORPSE; if (m_spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS)) retMask &= GRID_MAP_TYPE_MASK_CORPSE | GRID_MAP_TYPE_MASK_PLAYER; if (m_spellInfo->HasAttribute(SPELL_ATTR3_ONLY_TARGET_GHOSTS)) retMask &= GRID_MAP_TYPE_MASK_PLAYER; if (condList) retMask &= sConditionMgr->GetSearcherTypeMaskForConditionList(*condList); return retMask; } template<class SEARCHER> void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius) { if (!containerMask) return; // search world and grid for possible targets bool searchInGrid = (containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_GAMEOBJECT)) != 0; bool searchInWorld = (containerMask & (GRID_MAP_TYPE_MASK_CREATURE | GRID_MAP_TYPE_MASK_PLAYER | GRID_MAP_TYPE_MASK_CORPSE)) != 0; if (searchInGrid || searchInWorld) { float x, y; x = pos->GetPositionX(); y = pos->GetPositionY(); CellCoord p(Trinity::ComputeCellCoord(x, y)); Cell cell(p); cell.SetNoCreate(); Map* map = referer->GetMap(); if (searchInWorld) Cell::VisitWorldObjects(x, y, map, searcher, radius); if (searchInGrid) Cell::VisitGridObjects(x, y, map, searcher, radius); } } WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList) { WorldObject* target = NULL; uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); if (!containerTypeMask) return NULL; Trinity::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList); Trinity::WorldObjectLastSearcher<Trinity::WorldObjectSpellNearbyTargetCheck> searcher(m_caster, target, check, containerTypeMask); SearchTargets<Trinity::WorldObjectLastSearcher<Trinity::WorldObjectSpellNearbyTargetCheck> > (searcher, containerTypeMask, m_caster, m_caster, range); return target; } void Spell::SearchAreaTargets(std::list<WorldObject*>& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList) { uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); if (!containerTypeMask) return; Trinity::WorldObjectSpellAreaTargetCheck check(range, position, m_caster, referer, m_spellInfo, selectionType, condList); Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> searcher(m_caster, targets, check, containerTypeMask); SearchTargets<Trinity::WorldObjectListSearcher<Trinity::WorldObjectSpellAreaTargetCheck> > (searcher, containerTypeMask, m_caster, position, range); } void Spell::SearchChainTargets(std::list<WorldObject*>& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionContainer* condList, bool isChainHeal) { // max dist for jump target selection float jumpRadius = 0.0f; switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_RANGED: // 7.5y for multi shot jumpRadius = 7.5f; break; case SPELL_DAMAGE_CLASS_MELEE: // 5y for swipe, cleave and similar jumpRadius = 5.0f; break; case SPELL_DAMAGE_CLASS_NONE: case SPELL_DAMAGE_CLASS_MAGIC: // 12.5y for chain heal spell since 3.2 patch if (isChainHeal) jumpRadius = 12.5f; // 10y as default for magic chain spells else jumpRadius = 10.0f; break; } if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_DISTANCE, jumpRadius, this); // chain lightning/heal spells and similar - allow to jump at larger distance and go out of los bool isBouncingFar = (m_spellInfo->HasAttribute(SPELL_ATTR4_AREA_TARGET_CHAIN) || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC); // max dist which spell can reach float searchRadius = jumpRadius; if (isBouncingFar) searchRadius *= chainTargets; std::list<WorldObject*> tempTargets; SearchAreaTargets(tempTargets, searchRadius, target, m_caster, objectType, selectType, condList); tempTargets.remove(target); // remove targets which are always invalid for chain spells // for some spells allow only chain targets in front of caster (swipe for example) if (!isBouncingFar) { for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end();) { std::list<WorldObject*>::iterator checkItr = itr++; if (!m_caster->HasInArc(static_cast<float>(M_PI), *checkItr)) tempTargets.erase(checkItr); } } while (chainTargets) { // try to get unit for next chain jump std::list<WorldObject*>::iterator foundItr = tempTargets.end(); // get unit with highest hp deficit in dist if (isChainHeal) { uint32 maxHPDeficit = 0; for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) { uint32 deficit = unit->GetMaxHealth() - unit->GetHealth(); if ((deficit > maxHPDeficit || foundItr == tempTargets.end()) && target->IsWithinDist(unit, jumpRadius) && target->IsWithinLOSInMap(unit, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) { foundItr = itr; maxHPDeficit = deficit; } } } } // get closest object else { for (std::list<WorldObject*>::iterator itr = tempTargets.begin(); itr != tempTargets.end(); ++itr) { if (foundItr == tempTargets.end()) { if ((!isBouncingFar || target->IsWithinDist(*itr, jumpRadius)) && target->IsWithinLOSInMap(*itr, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) foundItr = itr; } else if (target->GetDistanceOrder(*itr, *foundItr) && target->IsWithinLOSInMap(*itr, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) foundItr = itr; } } // not found any valid target - chain ends if (foundItr == tempTargets.end()) break; target = *foundItr; tempTargets.erase(foundItr); targets.push_back(target); --chainTargets; } } GameObject* Spell::SearchSpellFocus() { GameObject* focus = NULL; Trinity::GameObjectFocusCheck check(m_caster, m_spellInfo->RequiresSpellFocus); Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> searcher(m_caster, focus, check); SearchTargets<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> > (searcher, GRID_MAP_TYPE_MASK_GAMEOBJECT, m_caster, m_caster, m_caster->GetVisibilityRange()); return focus; } void Spell::prepareDataForTriggerSystem() { //========================================================================================== // Now fill data for trigger system, need know: // Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_hitMask) //========================================================================================== m_procVictim = m_procAttacker = 0; // Get data for type of attack and fill base info for trigger switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS; if (m_attackType == OFF_ATTACK) m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK; else m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK; m_procVictim = PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS; break; case SPELL_DAMAGE_CLASS_RANGED: // Auto attack if (m_spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; } else // Ranged spell attack { m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS; m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS; } break; default: if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && m_spellInfo->EquippedItemSubClassMask & (1 << ITEM_SUBCLASS_WEAPON_WAND) && m_spellInfo->HasAttribute(SPELL_ATTR2_AUTOREPEAT_FLAG)) // Wands auto attack { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; } // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget // Because spell positivity is dependant on target } // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap { m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION; // also fill up other flags (DoAllEffectOnTarget only fills up flag if both are not set) m_procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; m_procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; } // Hellfire Effect - trigger as DOT if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040) { m_procAttacker = PROC_FLAG_DONE_PERIODIC; m_procVictim = PROC_FLAG_TAKEN_PERIODIC; } } void Spell::CleanupTargetList() { m_UniqueTargetInfo.clear(); m_UniqueGOTargetInfo.clear(); m_UniqueItemInfo.clear(); m_delayMoment = 0; } class ProcReflectDelayed : public BasicEvent { public: ProcReflectDelayed(Unit* owner, ObjectGuid casterGuid) : _victim(owner), _casterGuid(casterGuid) { } bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override { Unit* caster = ObjectAccessor::GetUnit(*_victim, _casterGuid); if (!caster) return true; uint32 const typeMaskActor = PROC_FLAG_NONE; uint32 const typeMaskActionTarget = PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG | PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; uint32 const spellTypeMask = PROC_SPELL_TYPE_DAMAGE | PROC_SPELL_TYPE_NO_DMG_HEAL; uint32 const spellPhaseMask = PROC_SPELL_PHASE_NONE; uint32 const hitMask = PROC_HIT_REFLECT; caster->ProcSkillsAndAuras(_victim, typeMaskActor, typeMaskActionTarget, spellTypeMask, spellPhaseMask, hitMask, nullptr, nullptr, nullptr); return true; } private: Unit* _victim; ObjectGuid _casterGuid; }; void Spell::AddUnitTarget(Unit* target, uint32 effectMask, bool checkIfValid /*= true*/, bool implicit /*= true*/, Position const* losPosition /*= nullptr*/) { uint32 validEffectMask = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex)) != 0 && CheckEffectTarget(target, effect, losPosition)) validEffectMask |= 1 << effect->EffectIndex; effectMask &= validEffectMask; // no effects left if (!effectMask) return; if (checkIfValid) if (m_spellInfo->CheckTarget(m_caster, target, implicit || m_caster->GetEntry() == WORLD_TRIGGER) != SPELL_CAST_OK) // skip stealth checks for GO casts return; // Check for effect immune skip if immuned for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && target->IsImmunedToSpellEffect(m_spellInfo, effect->EffectIndex, m_caster)) effectMask &= ~(1 << effect->EffectIndex); ObjectGuid targetGUID = target->GetGUID(); // Lookup target in already in list for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (targetGUID == ihit->targetGUID) // Found in list { ihit->effectMask |= effectMask; // Immune effects removed from mask return; } } // This is new target calculate data for him // Get spell hit result on target TargetInfo targetInfo; targetInfo.targetGUID = targetGUID; // Store target GUID targetInfo.effectMask = effectMask; // Store all effects not immune targetInfo.processed = false; // Effects not apply on target targetInfo.alive = target->IsAlive(); targetInfo.damage = 0; targetInfo.crit = false; // Calculate hit result if (m_originalCaster) { targetInfo.missCondition = m_originalCaster->SpellHitResult(target, m_spellInfo, m_canReflect && !(m_spellInfo->IsPositive() && m_caster->IsFriendlyTo(target))); if (m_skipCheck && targetInfo.missCondition != SPELL_MISS_IMMUNE) targetInfo.missCondition = SPELL_MISS_NONE; } else targetInfo.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE; // Spell have speed - need calculate incoming time // Incoming time is zero for self casts. At least I think so. if (m_caster != target) { float hitDelay = m_spellInfo->LaunchDelay; if (m_spellInfo->HasAttribute(SPELL_ATTR9_SPECIAL_DELAY_CALCULATION)) hitDelay += m_spellInfo->Speed; else if (m_spellInfo->Speed > 0.0f) { // calculate spell incoming interval /// @todo this is a hack float dist = std::max(m_caster->GetDistance(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()), 5.0f); hitDelay += dist / m_spellInfo->Speed; } targetInfo.timeDelay = uint64(std::floor(hitDelay * 1000.0f)); } else targetInfo.timeDelay = 0ULL; // If target reflect spell back to caster if (targetInfo.missCondition == SPELL_MISS_REFLECT) { // Calculate reflected spell result on caster targetInfo.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, false); // can't reflect twice // Proc spell reflect aura when missile hits the original target target->m_Events.AddEvent(new ProcReflectDelayed(target, m_originalCasterGUID), target->m_Events.CalculateTime(targetInfo.timeDelay)); // Increase time interval for reflected spells by 1.5 targetInfo.timeDelay += targetInfo.timeDelay >> 1; } else targetInfo.reflectResult = SPELL_MISS_NONE; // Calculate minimum incoming time if (targetInfo.timeDelay && (!m_delayMoment || m_delayMoment > targetInfo.timeDelay)) m_delayMoment = targetInfo.timeDelay; // Add target to list m_UniqueTargetInfo.push_back(targetInfo); } void Spell::AddGOTarget(GameObject* go, uint32 effectMask) { uint32 validEffectMask = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex)) != 0 && CheckEffectTarget(go, effect)) validEffectMask |= 1 << effect->EffectIndex; effectMask &= validEffectMask; // no effects left if (!effectMask) return; ObjectGuid targetGUID = go->GetGUID(); // Lookup target in already in list for (std::vector<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) { if (targetGUID == ihit->targetGUID) // Found in list { ihit->effectMask |= effectMask; // Add only effect mask return; } } // This is new target calculate data for him GOTargetInfo target; target.targetGUID = targetGUID; target.effectMask = effectMask; target.processed = false; // Effects not apply on target // Spell have speed - need calculate incoming time if (static_cast<WorldObject*>(m_caster) != go) { float hitDelay = m_spellInfo->LaunchDelay; if (m_spellInfo->HasAttribute(SPELL_ATTR9_SPECIAL_DELAY_CALCULATION)) hitDelay += m_spellInfo->Speed; else if (m_spellInfo->Speed > 0.0f) { // calculate spell incoming interval float dist = std::max(m_caster->GetDistance(go->GetPositionX(), go->GetPositionY(), go->GetPositionZ()), 5.0f); hitDelay += dist / m_spellInfo->Speed; } target.timeDelay = uint64(std::floor(hitDelay * 1000.0f)); } else target.timeDelay = 0ULL; // Calculate minimum incoming time if (target.timeDelay && (!m_delayMoment || m_delayMoment > target.timeDelay)) m_delayMoment = target.timeDelay; // Add target to list m_UniqueGOTargetInfo.push_back(target); } void Spell::AddItemTarget(Item* item, uint32 effectMask) { uint32 validEffectMask = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex)) != 0 && CheckEffectTarget(item, effect)) validEffectMask |= 1 << effect->EffectIndex; effectMask &= validEffectMask; // no effects left if (!effectMask) return; // Lookup target in already in list for (std::vector<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) { if (item == ihit->item) // Found in list { ihit->effectMask |= effectMask; // Add only effect mask return; } } // This is new target add data ItemTargetInfo target; target.item = item; target.effectMask = effectMask; m_UniqueItemInfo.push_back(target); } void Spell::AddDestTarget(SpellDestination const& dest, uint32 effIndex) { m_destTargets[effIndex] = dest; } void Spell::DoAllEffectOnTarget(TargetInfo* target) { if (!target || target->processed) return; target->processed = true; // Target checked in apply effects procedure // Get mask of effects for target uint32 mask = target->effectMask; Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID); if (!unit && target->targetGUID.IsPlayer()) // only players may be targeted across maps { uint32 farMask = 0; // create far target mask for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && effect->IsFarUnitTargetEffect()) if ((1 << effect->EffectIndex) & mask) farMask |= (1 << effect->EffectIndex); if (!farMask) return; // find unit in world unit = ObjectAccessor::FindPlayer(target->targetGUID); if (!unit) return; // do far effects on the unit // can't use default call because of threading, do stuff as fast as possible for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (farMask & (1 << effect->EffectIndex))) HandleEffects(unit, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET); return; } if (!unit) return; if (unit->IsAlive() != target->alive) return; if (getState() == SPELL_STATE_DELAYED && !m_spellInfo->IsPositive() && (GameTime::GetGameTimeMS() - target->timeDelay) <= unit->m_lastSanctuaryTime) return; // No missinfo in that case // Get original caster (if exist) and calculate damage/healing from him data Unit* caster = m_originalCaster ? m_originalCaster : m_caster; // Skip if m_originalCaster not avaiable if (!caster) return; SpellMissInfo missInfo = target->missCondition; // Need init unitTarget by default unit (can changed in code on reflect) // Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem) unitTarget = unit; targetMissInfo = missInfo; // Reset damage/healing counter m_damage = target->damage; m_healing = -target->damage; m_currentTargetInfo = target; // Fill base trigger info uint32 procAttacker = m_procAttacker; uint32 procVictim = m_procVictim; uint32 hitMask = PROC_HIT_NONE; m_spellAura = nullptr; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied // Spells with this flag cannot trigger if effect is cast on self bool const canEffectTrigger = !m_spellInfo->HasAttribute(SPELL_ATTR3_CANT_TRIGGER_PROC) && unitTarget->CanProc() && (CanExecuteTriggersOnHit(mask) || missInfo == SPELL_MISS_IMMUNE || missInfo == SPELL_MISS_IMMUNE2); Unit* spellHitTarget = nullptr; if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target spellHitTarget = unit; else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) { if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him { spellHitTarget = m_caster; if (m_caster->GetTypeId() == TYPEID_UNIT) m_caster->ToCreature()->LowerPlayerDamageReq(target->damage); } } if (missInfo != SPELL_MISS_NONE) if (m_caster->IsCreature() && m_caster->IsAIEnabled) m_caster->ToCreature()->AI()->SpellMissTarget(unit, m_spellInfo, missInfo); PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(missInfo); bool enablePvP = false; // need to check PvP state before spell effects, but act on it afterwards if (spellHitTarget) { // if target is flagged for pvp also flag caster if a player if (unit->IsPvP() && m_caster->GetTypeId() == TYPEID_PLAYER) enablePvP = true; // Decide on PvP flagging now, but act on it later. SpellMissInfo missInfo2 = DoSpellHitOnUnit(spellHitTarget, mask); if (missInfo2 != SPELL_MISS_NONE) { if (missInfo2 != SPELL_MISS_MISS) m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo2); m_damage = 0; spellHitTarget = nullptr; } } // Do not take combo points on dodge and miss if (missInfo != SPELL_MISS_NONE && m_needComboPoints && m_targets.GetUnitTargetGUID() == target->targetGUID) m_needComboPoints = false; // Trigger info was not filled in Spell::prepareDataForTriggerSystem - we do it now if (canEffectTrigger && !procAttacker && !procVictim) { bool positive = true; if (m_damage > 0) positive = false; else if (!m_healing) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { // in case of immunity, check all effects to choose correct procFlags, as none has technically hit if (target->effectMask && !(target->effectMask & (1 << i))) continue; if (!m_spellInfo->IsPositiveEffect(i)) { positive = false; break; } } } switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: if (positive) { procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS; } else { procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; } break; case SPELL_DAMAGE_CLASS_NONE: if (positive) { procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS; } else { procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; } break; } } CallScriptOnHitHandlers(); // All calculated do it! // Do healing and triggers if (m_healing > 0) { bool crit = target->crit; uint32 addhealth = m_healing; if (crit) { hitMask |= PROC_HIT_CRITICAL; addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, nullptr); } else hitMask |= PROC_HIT_NORMAL; HealInfo healInfo(caster, unitTarget, addhealth, m_spellInfo, m_spellInfo->GetSchoolMask()); caster->HealBySpell(healInfo, crit); unitTarget->getHostileRefManager().threatAssist(caster, float(healInfo.GetEffectiveHeal()) * 0.5f, m_spellInfo); m_healing = healInfo.GetEffectiveHeal(); // Do triggers for unit if (canEffectTrigger) caster->ProcSkillsAndAuras(unitTarget, procAttacker, procVictim, PROC_SPELL_TYPE_HEAL, PROC_SPELL_PHASE_HIT, hitMask, this, nullptr, &healInfo); } // Do damage and triggers else if (m_damage > 0) { // Fill base damage struct (unitTarget - is real spell target) SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo, m_SpellVisual, m_spellSchoolMask, m_castId); // Check damage immunity if (unitTarget->IsImmunedToDamage(m_spellInfo)) { hitMask = PROC_HIT_IMMUNE; m_damage = 0; // no packet found in sniffs } else { // Add bonuses and fill damageInfo struct caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit); caster->DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb, SPELL_DIRECT_DAMAGE); hitMask |= createProcHitMask(&damageInfo, missInfo); procVictim |= PROC_FLAG_TAKEN_DAMAGE; m_damage = damageInfo.damage; caster->DealSpellDamage(&damageInfo, true); // Send log damage message to client caster->SendSpellNonMeleeDamageLog(&damageInfo); } // Do triggers for unit if (canEffectTrigger) { DamageInfo spellDamageInfo(damageInfo, SPELL_DIRECT_DAMAGE, m_attackType, hitMask); caster->ProcSkillsAndAuras(unitTarget, procAttacker, procVictim, PROC_SPELL_TYPE_DAMAGE, PROC_SPELL_PHASE_HIT, hitMask, this, &spellDamageInfo, nullptr); if (caster->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET) && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) caster->ToPlayer()->CastItemCombatSpell(spellDamageInfo); } } // Passive spell hits/misses or active spells only misses (only triggers) else { // Fill base damage struct (unitTarget - is real spell target) SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo, m_SpellVisual, m_spellSchoolMask); hitMask |= createProcHitMask(&damageInfo, missInfo); // Do triggers for unit if (canEffectTrigger) { DamageInfo spellNoDamageInfo(damageInfo, NODAMAGE, m_attackType, hitMask); caster->ProcSkillsAndAuras(unitTarget, procAttacker, procVictim, PROC_SPELL_TYPE_NO_DMG_HEAL, PROC_SPELL_PHASE_HIT, hitMask, this, &spellNoDamageInfo, nullptr); if (caster->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET) && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) caster->ToPlayer()->CastItemCombatSpell(spellNoDamageInfo); } // Failed Pickpocket, reveal rogue if (missInfo == SPELL_MISS_RESIST && m_spellInfo->HasAttribute(SPELL_ATTR0_CU_PICKPOCKET) && unitTarget->GetTypeId() == TYPEID_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); if (unitTarget->ToCreature()->IsAIEnabled) unitTarget->ToCreature()->AI()->AttackStart(m_caster); } } // set hitmask for finish procs m_hitMask |= hitMask; // spellHitTarget can be null if spell is missed in DoSpellHitOnUnit if (missInfo != SPELL_MISS_EVADE && spellHitTarget && !m_caster->IsFriendlyTo(unit) && (!m_spellInfo->IsPositive() || m_spellInfo->HasEffect(SPELL_EFFECT_DISPEL))) { m_caster->CombatStart(unit, m_spellInfo->HasInitialAggro()); if (!unit->IsStandState()) unit->SetStandState(UNIT_STAND_STATE_STAND); } // Check for SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER if (missInfo == SPELL_MISS_NONE && m_spellInfo->HasAttribute(SPELL_ATTR7_INTERRUPT_ONLY_NONPLAYER) && unit->GetTypeId() != TYPEID_PLAYER) caster->CastSpell(unit, SPELL_INTERRUPT_NONPLAYER, true); if (spellHitTarget) { //AI functions if (spellHitTarget->GetTypeId() == TYPEID_UNIT) if (spellHitTarget->ToCreature()->IsAIEnabled) spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo); if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled) m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo); // Needs to be called after dealing damage/healing to not remove breaking on damage auras DoTriggersOnSpellHit(spellHitTarget, mask); if (enablePvP) m_caster->ToPlayer()->UpdatePvP(true); CallScriptAfterHitHandlers(); } } SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) { if (!unit || !effectMask) return SPELL_MISS_EVADE; // Target may have begun evading between launch and hit phases - re-check now if (Creature* creatureTarget = unit->ToCreature()) if (creatureTarget->IsEvadingAttacks()) return SPELL_MISS_EVADE; // For delayed spells immunity may be applied between missile launch and hit - check immunity for that case if (m_spellInfo->HasHitDelay() && unit->IsImmunedToSpell(m_spellInfo, m_caster)) return SPELL_MISS_IMMUNE; // disable effects to which unit is immune SpellMissInfo returnVal = SPELL_MISS_IMMUNE; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex))) if (unit->IsImmunedToSpellEffect(m_spellInfo, effect->EffectIndex, m_caster)) effectMask &= ~(1 << effect->EffectIndex); if (!effectMask) return returnVal; if (Player* player = unit->ToPlayer()) { player->StartCriteriaTimer(CRITERIA_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id); player->UpdateCriteria(CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, 0, m_caster); player->UpdateCriteria(CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id); } if (Player* player = m_caster->ToPlayer()) { player->StartCriteriaTimer(CRITERIA_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id); player->UpdateCriteria(CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, 0, unit); } if (m_caster != unit) { // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells if (m_spellInfo->HasHitDelay() && unit->HasUnitFlag(UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID()) return SPELL_MISS_EVADE; if (m_caster->_IsValidAttackTarget(unit, m_spellInfo)) unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL); else if (m_caster->IsFriendlyTo(unit)) { // for delayed spells ignore negative spells (after duel end) for friendly targets /// @todo this cause soul transfer bugged // 63881 - Malady of the Mind jump spell (Yogg-Saron) if (m_spellInfo->HasHitDelay() && unit->GetTypeId() == TYPEID_PLAYER && !m_spellInfo->IsPositive() && m_spellInfo->Id != 63881) return SPELL_MISS_EVADE; // assisting case, healing and resurrection if (unit->HasUnitState(UNIT_STATE_ATTACK_PLAYER)) { m_caster->SetContestedPvP(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->UpdatePvP(true); } if (unit->IsInCombat() && m_spellInfo->HasInitialAggro()) { m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit); unit->getHostileRefManager().threatAssist(m_caster, 0.0f); } } } uint32 aura_effmask = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex) && effect->IsUnitOwnedAuraEffect())) aura_effmask |= 1 << effect->EffectIndex; // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add DiminishingGroup const diminishGroup = m_spellInfo->GetDiminishingReturnsGroupForSpell(); DiminishingLevels diminishLevel = DIMINISHING_LEVEL_1; if (diminishGroup && aura_effmask) { diminishLevel = unit->GetDiminishing(diminishGroup); DiminishingReturnsType type = m_spellInfo->GetDiminishingReturnsGroupType(); // Increase Diminishing on unit, current informations for actually casts will use values above if ((type == DRTYPE_PLAYER && (unit->GetCharmerOrOwnerPlayerOrPlayerItself() || (unit->GetTypeId() == TYPEID_UNIT && unit->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_ALL_DIMINISH))) || type == DRTYPE_ALL) unit->IncrDiminishing(m_spellInfo); } if (aura_effmask) { if (m_originalCaster) { int32 basePoints[MAX_SPELL_EFFECTS]; for (SpellEffectInfo const* auraSpellEffect : m_spellInfo->GetEffects()) if (auraSpellEffect) basePoints[auraSpellEffect->EffectIndex] = (m_spellValue->CustomBasePointsMask & (1 << auraSpellEffect->EffectIndex)) ? m_spellValue->EffectBasePoints[auraSpellEffect->EffectIndex] : auraSpellEffect->CalcBaseValue(m_originalCaster, unit, m_castItemEntry, m_castItemLevel); bool refresh = false; bool const resetPeriodicTimer = !(_triggeredCastFlags & TRIGGERED_DONT_RESET_PERIODIC_TIMER); m_spellAura = Aura::TryRefreshStackOrCreate(m_spellInfo, m_castId, effectMask, unit, m_originalCaster, GetCastDifficulty(), basePoints, m_CastItem, ObjectGuid::Empty, &refresh, resetPeriodicTimer, ObjectGuid::Empty, m_castItemEntry, m_castItemLevel); if (m_spellAura) { // Set aura stack amount to desired value if (m_spellValue->AuraStackAmount > 1) { if (!refresh) m_spellAura->SetStackAmount(m_spellValue->AuraStackAmount); else m_spellAura->ModStackAmount(m_spellValue->AuraStackAmount); } // Now Reduce spell duration using data received at spell hit // check whatever effects we're going to apply, diminishing returns only apply to negative aura effects bool positive = true; if (m_originalCaster == unit || !m_originalCaster->IsFriendlyTo(unit)) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((effectMask & (1 << i)) && !m_spellInfo->IsPositiveEffect(i)) { positive = false; break; } } } int32 duration = m_spellAura->GetMaxDuration(); // unit is immune to aura if it was diminished to 0 duration if (!positive && !unit->ApplyDiminishingToDuration(m_spellInfo, duration, m_originalCaster, diminishLevel)) { m_spellAura->Remove(); bool found = false; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex) && effect->Effect != SPELL_EFFECT_APPLY_AURA)) found = true; if (!found) return SPELL_MISS_IMMUNE; } else { static_cast<UnitAura*>(m_spellAura)->SetDiminishGroup(diminishGroup); duration = m_originalCaster->ModSpellDuration(m_spellInfo, unit, duration, positive, effectMask); if (duration > 0) { // Haste modifies duration of channeled spells if (m_spellInfo->IsChanneled()) m_originalCaster->ModSpellDurationTime(m_spellInfo, duration, this); else if (m_spellInfo->HasAttribute(SPELL_ATTR5_HASTE_AFFECT_DURATION)) { int32 origDuration = duration; duration = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect) if (AuraEffect const* eff = m_spellAura->GetEffect(effect->EffectIndex)) if (int32 period = eff->GetPeriod()) // period is hastened by UNIT_MOD_CAST_SPEED duration = std::max(std::max(origDuration / period, 1) * period, duration); // if there is no periodic effect if (!duration) duration = int32(origDuration * m_originalCaster->m_unitData->ModCastingSpeed); } } // Set duration to desired value if (m_spellValue->Duration > 0) duration = m_spellValue->Duration; if (duration != m_spellAura->GetMaxDuration()) { m_spellAura->SetMaxDuration(duration); m_spellAura->SetDuration(duration); } m_spellAura->_RegisterForTargets(); } } } } for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex))) HandleEffects(unit, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET); return SPELL_MISS_NONE; } void Spell::DoTriggersOnSpellHit(Unit* unit, uint32 effMask) { // handle SPELL_AURA_ADD_TARGET_TRIGGER auras // this is executed after spell proc spells on target hit // spells are triggered for each hit spell target // info confirmed with retail sniffs of permafrost and shadow weaving if (!m_hitTriggerSpells.empty()) { int32 _duration = 0; for (auto i = m_hitTriggerSpells.begin(); i != m_hitTriggerSpells.end(); ++i) { if (CanExecuteTriggersOnHit(effMask, i->triggeredByAura) && roll_chance_i(i->chance)) { m_caster->CastSpell(unit, i->triggeredSpell, TRIGGERED_FULL_MASK); TC_LOG_DEBUG("spells", "Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->triggeredSpell->Id); // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration // set duration of current aura to the triggered spell if (i->triggeredSpell->GetDuration() == -1) { if (Aura* triggeredAur = unit->GetAura(i->triggeredSpell->Id, m_caster->GetGUID())) { // get duration from aura-only once if (!_duration) { Aura* aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID()); _duration = aur ? aur->GetDuration() : -1; } triggeredAur->SetDuration(_duration); } } } } } // trigger linked auras remove/apply /// @todo remove/cleanup this, as this table is not documented and people are doing stupid things with it if (std::vector<int32> const* spellTriggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) { for (std::vector<int32>::const_iterator i = spellTriggered->begin(); i != spellTriggered->end(); ++i) { if (*i < 0) unit->RemoveAurasDueToSpell(-(*i)); else unit->CastSpell(unit, *i, true, nullptr, nullptr, m_caster->GetGUID()); } } } void Spell::DoAllEffectOnTarget(GOTargetInfo* target) { if (target->processed) // Check target return; target->processed = true; // Target checked in apply effects procedure uint32 effectMask = target->effectMask; if (!effectMask) return; GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); if (!go) return; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(SPELL_MISS_NONE); for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex))) HandleEffects(NULL, NULL, go, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET); if (go->AI()) go->AI()->SpellHit(m_caster, m_spellInfo); CallScriptOnHitHandlers(); CallScriptAfterHitHandlers(); } void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) { uint32 effectMask = target->effectMask; if (!target->item || !effectMask) return; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(SPELL_MISS_NONE); for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (effectMask & (1 << effect->EffectIndex))) HandleEffects(NULL, target->item, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT_TARGET); CallScriptOnHitHandlers(); CallScriptAfterHitHandlers(); } bool Spell::UpdateChanneledTargetList() { // Not need check return true if (m_channelTargetEffectMask == 0) return true; uint32 channelTargetEffectMask = m_channelTargetEffectMask; uint32 channelAuraMask = 0; float maxRadius = 0; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (effect && effect->Effect == SPELL_EFFECT_APPLY_AURA) { channelAuraMask |= 1 << effect->EffectIndex; maxRadius = std::max(effect->CalcRadius(m_caster, this), maxRadius); } } channelAuraMask &= channelTargetEffectMask; float range = 0; if (channelAuraMask) { range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive()); if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); if (!range) range = maxRadius; // add little tolerance level range += std::min(MAX_SPELL_RANGE_TOLERANCE, range*0.1f); // 10% but no more than MAX_SPELL_RANGE_TOLERANCE } for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask)) { Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (!unit) continue; if (IsValidDeadOrAliveTarget(unit)) { if (channelAuraMask & ihit->effectMask) { if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) { if (m_caster != unit && !m_caster->IsWithinDistInMap(unit, range)) { ihit->effectMask &= ~aurApp->GetEffectMask(); unit->RemoveAura(aurApp); continue; } } else // aura is dispelled continue; } channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target } } } // is all effects from m_needAliveTargetMask have alive targets return channelTargetEffectMask == 0; } bool Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura) { if (m_CastItem) { m_castItemGUID = m_CastItem->GetGUID(); m_castItemEntry = m_CastItem->GetEntry(); if (Player* owner = m_CastItem->GetOwner()) m_castItemLevel = int32(m_CastItem->GetItemLevel(owner)); else if (m_CastItem->GetOwnerGUID() == m_caster->GetGUID()) m_castItemLevel = int32(m_CastItem->GetItemLevel(m_caster->ToPlayer())); else { SendCastResult(SPELL_FAILED_EQUIPPED_ITEM); finish(false); return false; } } InitExplicitTargets(*targets); m_spellState = SPELL_STATE_PREPARING; if (triggeredByAura) { m_triggeredByAuraSpell = triggeredByAura->GetSpellInfo(); m_castItemLevel = triggeredByAura->GetBase()->GetCastItemLevel(); } // create and add update event for this spell _spellEvent = new SpellEvent(this); m_caster->m_Events.AddEvent(_spellEvent, m_caster->m_Events.CalculateTime(1)); //Prevent casting at cast another spell (ServerSide check) if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS) && m_caster->IsNonMeleeSpellCast(false, true, true) && !m_castId.IsEmpty()) { SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS); finish(false); return false; } if (DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, m_caster)) { SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE); finish(false); return false; } LoadScripts(); CallScriptOnPrepareHandlers(); // Fill cost data (do not use power for item casts) if (!m_CastItem) m_powerCost = m_spellInfo->CalcPowerCost(m_caster, m_spellSchoolMask, this); // Set combo point requirement if ((_triggeredCastFlags & TRIGGERED_IGNORE_COMBO_POINTS) || m_CastItem || !m_caster->m_playerMovingMe) m_needComboPoints = false; uint32 param1 = 0, param2 = 0; SpellCastResult result = CheckCast(true, &param1, &param2); // target is checked in too many locations and with different results to handle each of them // handle just the general SPELL_FAILED_BAD_TARGETS result which is the default result for most DBC target checks if (_triggeredCastFlags & TRIGGERED_IGNORE_TARGET_CHECK && result == SPELL_FAILED_BAD_TARGETS) result = SPELL_CAST_OK; if (result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering { // Periodic auras should be interrupted when aura triggers a spell which can't be cast // for example bladestorm aura should be removed on disarm as of patch 3.3.5 // channeled periodic spells should be affected by this (arcane missiles, penance, etc) // a possible alternative sollution for those would be validating aura target on unit state change if (triggeredByAura && triggeredByAura->IsPeriodic() && !triggeredByAura->GetBase()->IsPassive()) { SendChannelUpdate(0); triggeredByAura->GetBase()->SetDuration(0); } if (param1 || param2) SendCastResult(result, &param1, &param2); else SendCastResult(result); finish(false); return false; } // Prepare data for triggers prepareDataForTriggerSystem(); if (Player* player = m_caster->ToPlayer()) { if (!player->GetCommandStatus(CHEAT_CASTTIME)) { // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail) m_casttime = m_spellInfo->CalcCastTime(player->getLevel(), this); } else m_casttime = 0; // Set cast time to 0 if .cheat casttime is enabled. } else m_casttime = m_spellInfo->CalcCastTime(m_caster->getLevel(), this); CallScriptOnCalcCastTimeHandlers(); m_casttime *= m_caster->GetTotalAuraMultiplier(SPELL_AURA_MOD_CASTING_SPEED); // don't allow channeled spells / spells with cast time to be cast while moving // exception are only channeled spells that have no casttime and SPELL_ATTR5_CAN_CHANNEL_WHEN_MOVING // (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in) // don't cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect if (((m_spellInfo->IsChanneled() || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && !(m_caster->IsCharmed() && m_caster->GetCharmerGUID().IsCreature()) && m_caster->isMoving() && m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo)) { // 1. Has casttime, 2. Or doesn't have flag to allow movement during channel if (m_casttime || !m_spellInfo->IsMoveAllowedChannel()) { SendCastResult(SPELL_FAILED_MOVING); finish(false); return false; } } // focus if not controlled creature if (m_caster->GetTypeId() == TYPEID_UNIT && !m_caster->HasUnitFlag(UNIT_FLAG_PLAYER_CONTROLLED)) { if (!(m_spellInfo->IsNextMeleeSwingSpell() || IsAutoRepeat() || (_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING))) { if (m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget()) m_caster->ToCreature()->FocusTarget(this, m_targets.GetObjectTarget()); else if (m_spellInfo->HasAttribute(SPELL_ATTR5_DONT_TURN_DURING_CAST)) m_caster->ToCreature()->FocusTarget(this, nullptr); } } // set timer base at cast time ReSetTimer(); TC_LOG_DEBUG("spells", "Spell::prepare: spell id %u source %u caster %d customCastFlags %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, _triggeredCastFlags, m_targets.GetTargetMask()); //Containers for channeled spells have to be set /// @todoApply this to all cast spells if needed // Why check duration? 29350: channelled triggers channelled if ((_triggeredCastFlags & TRIGGERED_CAST_DIRECTLY) && (!m_spellInfo->IsChanneled() || !m_spellInfo->GetMaxDuration())) cast(true); else { // stealth must be removed at cast starting (at show channel bar) // skip triggered spell (item equip spell casting and other not explicit character casts/item uses) if (!(_triggeredCastFlags & TRIGGERED_IGNORE_AURA_INTERRUPT_FLAGS) && m_spellInfo->IsBreakingStealth()) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST); for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && effect->GetUsedTargetObjectType() == TARGET_OBJECT_TYPE_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK); break; } } m_caster->SetCurrentCastSpell(this); SendSpellStart(); if (!(_triggeredCastFlags & TRIGGERED_IGNORE_GCD)) TriggerGlobalCooldown(); //item: first cast may destroy item and second cast causes crash // commented out !m_spellInfo->StartRecoveryTime, it forces instant spells with global cooldown to be processed in spell::update // as a result a spell that passed CheckCast and should be processed instantly may suffer from this delayed process // the easiest bug to observe is LoS check in AddUnitTarget, even if spell passed the CheckCast LoS check the situation can change in spell::update // because target could be relocated in the meantime, making the spell fly to the air (no targets can be registered, so no effects processed, nothing in combat log) if (!m_casttime && /*!m_spellInfo->StartRecoveryTime && */!m_castItemGUID && GetCurrentContainer() == CURRENT_GENERIC_SPELL) cast(true); } return true; } void Spell::cancel() { if (m_spellState == SPELL_STATE_FINISHED) return; uint32 oldState = m_spellState; m_spellState = SPELL_STATE_FINISHED; m_autoRepeat = false; switch (oldState) { case SPELL_STATE_PREPARING: CancelGlobalCooldown(); /* fallthrough */ case SPELL_STATE_DELAYED: SendInterrupted(0); SendCastResult(SPELL_FAILED_INTERRUPTED); break; case SPELL_STATE_CASTING: for (std::vector<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if ((*ihit).missCondition == SPELL_MISS_NONE) if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL); SendChannelUpdate(0); SendInterrupted(0); SendCastResult(SPELL_FAILED_INTERRUPTED); m_appliedMods.clear(); break; default: break; } SetReferencedFromCurrent(false); if (m_selfContainer && *m_selfContainer == this) *m_selfContainer = NULL; m_caster->RemoveDynObject(m_spellInfo->Id); if (m_spellInfo->IsChanneled()) // if not channeled then the object for the current cast wasn't summoned yet m_caster->RemoveGameObject(m_spellInfo->Id, true); //set state back so finish will be processed m_spellState = oldState; finish(false); } void Spell::cast(bool skipCheck) { Player* modOwner = m_caster->GetSpellModOwner(); Spell* lastSpellMod = nullptr; if (modOwner) { lastSpellMod = modOwner->m_spellModTakingSpell; if (lastSpellMod) modOwner->SetSpellModTakingSpell(lastSpellMod, false); } _cast(skipCheck); if (lastSpellMod) modOwner->SetSpellModTakingSpell(lastSpellMod, true); } void Spell::_cast(bool skipCheck) { // update pointers base at GUIDs to prevent access to non-existed already object if (!UpdatePointers()) { // cancel the spell if UpdatePointers() returned false, something wrong happened there cancel(); return; } // cancel at lost explicit target during cast if (!m_targets.GetObjectTargetGUID().IsEmpty() && !m_targets.GetObjectTarget()) { cancel(); return; } if (Player* playerCaster = m_caster->ToPlayer()) { // now that we've done the basic check, now run the scripts // should be done before the spell is actually executed sScriptMgr->OnPlayerSpellCast(playerCaster, this, skipCheck); // As of 3.0.2 pets begin attacking their owner's target immediately // Let any pets know we've attacked something. Check DmgClass for harmful spells only // This prevents spells such as Hunter's Mark from triggering pet attack if (this->GetSpellInfo()->DmgClass != SPELL_DAMAGE_CLASS_NONE) if (Unit* unitTarget = m_targets.GetUnitTarget()) for (Unit* controlled : playerCaster->m_Controlled) if (Creature* cControlled = controlled->ToCreature()) if (cControlled->IsAIEnabled) cControlled->AI()->OwnerAttacked(unitTarget); } SetExecutedCurrently(true); if (!(_triggeredCastFlags & TRIGGERED_IGNORE_SET_FACING)) if (m_caster->GetTypeId() == TYPEID_UNIT && m_targets.GetObjectTarget() && m_caster != m_targets.GetObjectTarget()) m_caster->SetInFront(m_targets.GetObjectTarget()); // Should this be done for original caster? Player* modOwner = m_caster->GetSpellModOwner(); if (modOwner) { // Set spell which will drop charges for triggered cast spells // if not successfully cast, will be remove in finish(false) modOwner->SetSpellModTakingSpell(this, true); } CallScriptBeforeCastHandlers(); // skip check if done already (for instant cast spells for example) if (!skipCheck) { uint32 param1 = 0, param2 = 0; SpellCastResult castResult = CheckCast(false, &param1, &param2); if (castResult != SPELL_CAST_OK) { SendCastResult(castResult, &param1, &param2); SendInterrupted(0); if (modOwner) modOwner->SetSpellModTakingSpell(this, false); finish(false); SetExecutedCurrently(false); return; } // additional check after cast bar completes (must not be in CheckCast) // if trade not complete then remember it in trade data if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (modOwner) { if (TradeData* my_trade = modOwner->GetTradeData()) { if (!my_trade->IsInAcceptProcess()) { // Spell will be cast after completing the trade. Silently ignore at this place my_trade->SetSpell(m_spellInfo->Id, m_CastItem); SendCastResult(SPELL_FAILED_DONT_REPORT); SendInterrupted(0); modOwner->SetSpellModTakingSpell(this, false); finish(false); SetExecutedCurrently(false); return; } } } } } // if the spell allows the creature to turn while casting, then adjust server-side orientation to face the target now // client-side orientation is handled by the client itself, as the cast target is targeted due to Creature::FocusTarget if (m_caster->GetTypeId() == TYPEID_UNIT && !m_caster->HasUnitFlag(UNIT_FLAG_PLAYER_CONTROLLED)) if (m_spellInfo->CasterCanTurnDuringCast()) if (WorldObject* objTarget = m_targets.GetObjectTarget()) m_caster->SetInFront(objTarget); SelectSpellTargets(); // Spell may be finished after target map check if (m_spellState == SPELL_STATE_FINISHED) { SendInterrupted(0); // cleanup after mod system // triggered spell pointer can be not removed in some cases if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); finish(false); SetExecutedCurrently(false); return; } if (m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) if (Creature* pet = ObjectAccessor::GetCreature(*m_caster, m_caster->GetPetGUID())) pet->DespawnOrUnsummon(); PrepareTriggersExecutedOnHit(); CallScriptOnCastHandlers(); // traded items have trade slot instead of guid in m_itemTargetGUID // set to real guid to be sent later to the client m_targets.UpdateTradeSlotItem(); if (Player* player = m_caster->ToPlayer()) { if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) && m_CastItem) { player->StartCriteriaTimer(CRITERIA_TIMED_TYPE_ITEM, m_CastItem->GetEntry()); player->UpdateCriteria(CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry()); } player->UpdateCriteria(CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id); } if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)) { // Powers have to be taken before SendSpellGo TakePower(); TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot } else if (Item* targetItem = m_targets.GetItemTarget()) { /// Not own traded item (in trader trade slot) req. reagents including triggered spell case if (targetItem->GetOwnerGUID() != m_caster->GetGUID()) TakeReagents(); } // CAST SPELL SendSpellCooldown(); PrepareScriptHitHandlers(); if (!m_spellInfo->LaunchDelay) { HandleLaunchPhase(); m_launchHandled = true; } // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()... SendSpellGo(); // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells if ((m_spellInfo->HasHitDelay() && !m_spellInfo->IsChanneled()) || m_spellInfo->HasAttribute(SPELL_ATTR4_UNK4)) { // Remove used for cast item if need (it can be already NULL after TakeReagents call // in case delayed spell remove item at cast delay start TakeCastItem(); // Okay, maps created, now prepare flags m_immediateHandled = false; m_spellState = SPELL_STATE_DELAYED; SetDelayStart(0); if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCast(false, false, true)) m_caster->ClearUnitState(UNIT_STATE_CASTING); } else { // Immediate spell, no big deal handle_immediate(); } CallScriptAfterCastHandlers(); if (m_caster->IsCreature() && m_caster->IsAIEnabled) m_caster->ToCreature()->AI()->OnSpellCasted(m_spellInfo); if (m_caster->IsPlayer()) sScriptMgr->OnPlayerSuccessfulSpellCast(m_caster->ToPlayer(), this); if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id)) { for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i) if (*i < 0) m_caster->RemoveAurasDueToSpell(-(*i)); else m_caster->CastSpell(m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster, *i, true); } if (modOwner) { modOwner->SetSpellModTakingSpell(this, false); //Clear spell cooldowns after every spell is cast if .cheat cooldown is enabled. if (modOwner->GetCommandStatus(CHEAT_COOLDOWN)) { m_caster->GetSpellHistory()->ResetCooldown(m_spellInfo->Id, true); m_caster->GetSpellHistory()->RestoreCharge(m_spellInfo->ChargeCategoryId); } } SetExecutedCurrently(false); if (!m_originalCaster) return; // Handle procs on cast uint32 procAttacker = m_procAttacker; if (!procAttacker) { if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC) procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; else procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; } uint32 hitMask = m_hitMask; if (!(hitMask & PROC_HIT_CRITICAL)) hitMask |= PROC_HIT_NORMAL; m_originalCaster->ProcSkillsAndAuras(nullptr, procAttacker, PROC_FLAG_NONE, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_CAST, hitMask, this, nullptr, nullptr); // Call CreatureAI hook OnSuccessfulSpellCast if (Creature* caster = m_originalCaster->ToCreature()) if (caster->IsAIEnabled) caster->AI()->OnSuccessfulSpellCast(GetSpellInfo()); } void Spell::handle_immediate() { // start channeling if applicable if (m_spellInfo->IsChanneled()) { int32 duration = m_spellInfo->GetDuration(); if (duration > 0) { // First mod_duration then haste - see Missile Barrage // Apply duration mod if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); // Apply haste mods m_caster->ModSpellDurationTime(m_spellInfo, duration, this); m_spellState = SPELL_STATE_CASTING; m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags); m_channeledDuration = duration; SendChannelStart(duration); } else if (duration == -1) { m_spellState = SPELL_STATE_CASTING; m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags); SendChannelStart(duration); } } PrepareTargetProcessing(); // process immediate effects (items, ground, etc.) also initialize some variables _handle_immediate_phase(); // consider spell hit for some spells without target, so they may proc on finish phase correctly if (m_UniqueTargetInfo.empty()) m_hitMask = PROC_HIT_NORMAL; else { for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); } for (std::vector<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); FinishTargetProcessing(); // spell is finished, perform some last features of the spell here _handle_finish_phase(); // Remove used for cast item if need (it can be already NULL after TakeReagents call TakeCastItem(); if (m_spellState != SPELL_STATE_CASTING) finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell) } uint64 Spell::handle_delayed(uint64 t_offset) { if (!UpdatePointers()) { // finish the spell if UpdatePointers() returned false, something wrong happened there finish(false); return 0; } bool single_missile = m_targets.HasDst(); uint64 next_time = 0; if (!m_launchHandled) { uint64 launchMoment = uint64(std::floor(m_spellInfo->LaunchDelay * 1000.0f)); if (launchMoment > t_offset) return launchMoment; HandleLaunchPhase(); m_launchHandled = true; if (m_delayMoment > t_offset) { if (single_missile) return m_delayMoment; next_time = m_delayMoment; if ((m_UniqueTargetInfo.size() > 2 || (m_UniqueTargetInfo.size() == 1 && m_UniqueTargetInfo.front().targetGUID == m_caster->GetGUID())) || !m_UniqueGOTargetInfo.empty()) { t_offset = 0; // if LaunchDelay was present then the only target that has timeDelay = 0 is m_caster - and that is the only target we want to process now } } } if (single_missile && !t_offset) return m_delayMoment; Player* modOwner = m_caster->GetSpellModOwner(); if (modOwner) modOwner->SetSpellModTakingSpell(this, true); PrepareTargetProcessing(); if (!m_immediateHandled && t_offset) { _handle_immediate_phase(); m_immediateHandled = true; } // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases) for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->processed == false) { if (single_missile || ihit->timeDelay <= t_offset) { ihit->timeDelay = t_offset; DoAllEffectOnTarget(&(*ihit)); } else if (next_time == 0 || ihit->timeDelay < next_time) next_time = ihit->timeDelay; } } m_currentTargetInfo = nullptr; // now recheck gameobject targeting correctness for (std::vector<GOTargetInfo>::iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) { if (ighit->processed == false) { if (single_missile || ighit->timeDelay <= t_offset) DoAllEffectOnTarget(&(*ighit)); else if (next_time == 0 || ighit->timeDelay < next_time) next_time = ighit->timeDelay; } } FinishTargetProcessing(); if (modOwner) modOwner->SetSpellModTakingSpell(this, false); // All targets passed - need finish phase if (next_time == 0) { // spell is finished, perform some last features of the spell here _handle_finish_phase(); finish(true); // successfully finish spell cast // return zero, spell is finished now return 0; } else { // spell is unfinished, return next execution time return next_time; } } void Spell::_handle_immediate_phase() { m_spellAura = NULL; // handle some immediate features of the spell here HandleThreatSpells(); PrepareScriptHitHandlers(); // handle effects with SPELL_EFFECT_HANDLE_HIT mode for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { // don't do anything for empty effect if (!effect || !effect->IsEffect()) continue; // call effect handlers to handle destination hit HandleEffects(NULL, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_HIT); } // process items for (std::vector<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); } void Spell::_handle_finish_phase() { if (m_caster->m_playerMovingMe) { // Take for real after all targets are processed if (m_needComboPoints) m_caster->m_playerMovingMe->ClearComboPoints(); // Real add combo points from effects if (m_comboPointGain) m_caster->m_playerMovingMe->GainSpellComboPoints(m_comboPointGain); } if (m_caster->m_extraAttacks && m_spellInfo->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS)) { if (Unit* victim = ObjectAccessor::GetUnit(*m_caster, m_targets.GetOrigUnitTargetGUID())) m_caster->HandleProcExtraAttackFor(victim); else m_caster->m_extraAttacks = 0; } // Handle procs on finish if (!m_originalCaster) return; uint32 procAttacker = m_procAttacker; if (!procAttacker) { if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC) procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; else procAttacker = m_spellInfo->IsPositive() ? PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS : PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; } m_originalCaster->ProcSkillsAndAuras(nullptr, procAttacker, PROC_FLAG_NONE, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_FINISH, m_hitMask, this, nullptr, nullptr); } void Spell::SendSpellCooldown() { if (m_CastItem) m_caster->GetSpellHistory()->HandleCooldowns(m_spellInfo, m_CastItem, this); else m_caster->GetSpellHistory()->HandleCooldowns(m_spellInfo, m_castItemEntry, this); } void Spell::update(uint32 difftime) { // update pointers based at it's GUIDs if (!UpdatePointers()) { // cancel the spell if UpdatePointers() returned false, something wrong happened there cancel(); return; } if (!m_targets.GetUnitTargetGUID().IsEmpty() && !m_targets.GetUnitTarget()) { TC_LOG_DEBUG("spells", "Spell %u is cancelled due to removal of target.", m_spellInfo->Id); cancel(); return; } // check if the player caster has moved before the spell finished // with the exception of spells affected with SPELL_AURA_CAST_WHILE_WALKING effect SpellEffectInfo const* effect = m_spellInfo->GetEffect(EFFECT_0); if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) && m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && ((effect && effect->Effect != SPELL_EFFECT_STUCK) || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR)) && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo)) { // don't cancel for melee, autorepeat, triggered and instant spells if (!m_spellInfo->IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsTriggered() && !(IsChannelActive() && m_spellInfo->IsMoveAllowedChannel())) { // if charmed by creature, trust the AI not to cheat and allow the cast to proceed // @todo this is a hack, "creature" movesplines don't differentiate turning/moving right now // however, checking what type of movement the spline is for every single spline would be really expensive if (!m_caster->GetCharmerGUID().IsCreature()) cancel(); } } switch (m_spellState) { case SPELL_STATE_PREPARING: { if (m_timer > 0) { if (difftime >= (uint32)m_timer) m_timer = 0; else m_timer -= difftime; } if (m_timer == 0 && !m_spellInfo->IsNextMeleeSwingSpell() && !IsAutoRepeat()) // don't CheckCast for instant spells - done in spell::prepare, skip duplicate checks, needed for range checks for example cast(!m_casttime); break; } case SPELL_STATE_CASTING: { if (m_timer) { // check if there are alive targets left if (!UpdateChanneledTargetList()) { TC_LOG_DEBUG("spells", "Channeled spell %d is removed due to lack of targets", m_spellInfo->Id); m_timer = 0; // Also remove applied auras for (TargetInfo const& target : m_UniqueTargetInfo) if (Unit* unit = m_caster->GetGUID() == target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID)) unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL); } if (m_timer > 0) { if (difftime >= (uint32)m_timer) m_timer = 0; else m_timer -= difftime; } } if (m_timer == 0) { SendChannelUpdate(0); finish(); } break; } default: break; } } void Spell::finish(bool ok) { if (!m_caster) return; if (m_spellState == SPELL_STATE_FINISHED) return; m_spellState = SPELL_STATE_FINISHED; if (m_caster->IsCreature() && m_caster->IsAIEnabled) m_caster->ToCreature()->AI()->OnSpellFinished(m_spellInfo); if (m_spellInfo->IsChanneled()) m_caster->UpdateInterruptMask(); if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !m_caster->IsNonMeleeSpellCast(false, false, true)) m_caster->ClearUnitState(UNIT_STATE_CASTING); // Unsummon summon as possessed creatures on spell cancel if (m_spellInfo->IsChanneled() && m_caster->GetTypeId() == TYPEID_PLAYER) { if (Unit* charm = m_caster->GetCharm()) if (charm->GetTypeId() == TYPEID_UNIT && charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET) && charm->m_unitData->CreatedBySpell == int32(m_spellInfo->Id)) ((Puppet*)charm)->UnSummon(); } if (Creature* creatureCaster = m_caster->ToCreature()) creatureCaster->ReleaseFocus(this); if (!ok) return; if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsSummon()) { // Unsummon statue uint32 spell = m_caster->m_unitData->CreatedBySpell; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell, GetCastDifficulty()); if (spellInfo && spellInfo->IconFileDataId == 134230) { TC_LOG_DEBUG("spells", "Statue %s is unsummoned in spell %d finish", m_caster->GetGUID().ToString().c_str(), m_spellInfo->Id); m_caster->setDeathState(JUST_DIED); return; } } if (IsAutoActionResetSpell()) { bool found = false; Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET); for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i) { if ((*i)->IsAffectingSpell(m_spellInfo)) { found = true; break; } } if (!found && !m_spellInfo->HasAttribute(SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS)) { m_caster->resetAttackTimer(BASE_ATTACK); if (m_caster->haveOffhandWeapon()) m_caster->resetAttackTimer(OFF_ATTACK); m_caster->resetAttackTimer(RANGED_ATTACK); } } // potions disabled by client, send event "not in combat" if need if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (!m_triggeredByAuraSpell) m_caster->ToPlayer()->UpdatePotionCooldown(this); } // Stop Attack for some spells if (m_spellInfo->HasAttribute(SPELL_ATTR0_STOP_ATTACK_TARGET)) m_caster->AttackStop(); } template<class T> inline void FillSpellCastFailedArgs(T& packet, ObjectGuid castId, SpellInfo const* spellInfo, SpellCastResult result, SpellCustomErrors customError, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/, Player* caster) { packet.CastID = castId; packet.SpellID = spellInfo->Id; packet.Reason = result; switch (result) { case SPELL_FAILED_NOT_READY: if (param1) packet.FailedArg1 = *param1; else packet.FailedArg1 = 0; // unknown (value 1 update cooldowns on client flag) break; case SPELL_FAILED_REQUIRES_SPELL_FOCUS: if (param1) packet.FailedArg1 = *param1; else packet.FailedArg1 = spellInfo->RequiresSpellFocus; // SpellFocusObject.dbc id break; case SPELL_FAILED_REQUIRES_AREA: // AreaTable.dbc id if (param1) packet.FailedArg1 = *param1; else { // hardcode areas limitation case switch (spellInfo->Id) { case 41617: // Cenarion Mana Salve case 41619: // Cenarion Healing Salve packet.FailedArg1 = 3905; break; case 41618: // Bottled Nethergon Energy case 41620: // Bottled Nethergon Vapor packet.FailedArg1 = 3842; break; case 45373: // Bloodberry Elixir packet.FailedArg1 = 4075; break; default: // default case (don't must be) packet.FailedArg1 = 0; break; } } break; case SPELL_FAILED_TOTEMS: if (param1) { packet.FailedArg1 = *param1; if (param2) packet.FailedArg2 = *param2; } else { if (spellInfo->Totem[0]) packet.FailedArg1 = spellInfo->Totem[0]; if (spellInfo->Totem[1]) packet.FailedArg2 = spellInfo->Totem[1]; } break; case SPELL_FAILED_TOTEM_CATEGORY: if (param1) { packet.FailedArg1 = *param1; if (param2) packet.FailedArg2 = *param2; } else { if (spellInfo->TotemCategory[0]) packet.FailedArg1 = spellInfo->TotemCategory[0]; if (spellInfo->TotemCategory[1]) packet.FailedArg2 = spellInfo->TotemCategory[1]; } break; case SPELL_FAILED_EQUIPPED_ITEM_CLASS: case SPELL_FAILED_EQUIPPED_ITEM_CLASS_MAINHAND: case SPELL_FAILED_EQUIPPED_ITEM_CLASS_OFFHAND: if (param1 && param2) { packet.FailedArg1 = *param1; packet.FailedArg2 = *param2; } else { packet.FailedArg1 = spellInfo->EquippedItemClass; packet.FailedArg2 = spellInfo->EquippedItemSubClassMask; } break; case SPELL_FAILED_TOO_MANY_OF_ITEM: { if (param1) packet.FailedArg1 = *param1; else { uint32 item = 0; for (SpellEffectInfo const* effect : spellInfo->GetEffects()) if (effect->ItemType) item = effect->ItemType; ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item); if (proto && proto->GetItemLimitCategory()) packet.FailedArg1 = proto->GetItemLimitCategory(); } break; } case SPELL_FAILED_PREVENTED_BY_MECHANIC: if (param1) packet.FailedArg1 = *param1; else packet.FailedArg1 = spellInfo->GetAllEffectsMechanicMask(); // SpellMechanic.dbc id break; case SPELL_FAILED_NEED_EXOTIC_AMMO: if (param1) packet.FailedArg1 = *param1; else packet.FailedArg1 = spellInfo->EquippedItemSubClassMask; // seems correct... break; case SPELL_FAILED_NEED_MORE_ITEMS: if (param1 && param2) { packet.FailedArg1 = *param1; packet.FailedArg2 = *param2; } else { packet.FailedArg1 = 0; // Item id packet.FailedArg2 = 0; // Item count? } break; case SPELL_FAILED_MIN_SKILL: if (param1 && param2) { packet.FailedArg1 = *param1; packet.FailedArg2 = *param2; } else { packet.FailedArg1 = 0; // SkillLine.dbc id packet.FailedArg2 = 0; // required skill value } break; case SPELL_FAILED_FISHING_TOO_LOW: if (param1) packet.FailedArg1 = *param1; else packet.FailedArg1 = 0; // required fishing skill break; case SPELL_FAILED_CUSTOM_ERROR: packet.FailedArg1 = customError; break; case SPELL_FAILED_SILENCED: if (param1) packet.FailedArg1 = *param1; else packet.FailedArg1 = 0; // Unknown break; case SPELL_FAILED_REAGENTS: { if (param1) packet.FailedArg1 = *param1; else { uint32 missingItem = 0; for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { if (spellInfo->Reagent[i] <= 0) continue; uint32 itemid = spellInfo->Reagent[i]; uint32 itemcount = spellInfo->ReagentCount[i]; if (!caster->HasItemCount(itemid, itemcount)) { missingItem = itemid; break; } } packet.FailedArg1 = missingItem; // first missing item } break; } case SPELL_FAILED_CANT_UNTALENT: { ASSERT(param1); packet.FailedArg1 = *param1; break; } // TODO: SPELL_FAILED_NOT_STANDING default: break; } } void Spell::SendCastResult(SpellCastResult result, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) const { if (result == SPELL_CAST_OK) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (m_caster->ToPlayer()->IsLoading()) // don't send cast results at loading time return; if (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) result = SPELL_FAILED_DONT_REPORT; WorldPackets::Spells::CastFailed castFailed; castFailed.SpellXSpellVisualID = m_SpellVisual; FillSpellCastFailedArgs(castFailed, m_castId, m_spellInfo, result, m_customError, param1, param2, m_caster->ToPlayer()); m_caster->ToPlayer()->SendDirectMessage(castFailed.Write()); } void Spell::SendPetCastResult(SpellCastResult result, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) const { if (result == SPELL_CAST_OK) return; Unit* owner = m_caster->GetCharmerOrOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return; if (_triggeredCastFlags & TRIGGERED_DONT_REPORT_CAST_ERROR) result = SPELL_FAILED_DONT_REPORT; WorldPackets::Spells::PetCastFailed petCastFailed; FillSpellCastFailedArgs(petCastFailed, m_castId, m_spellInfo, result, SPELL_CUSTOM_ERROR_NONE, param1, param2, owner->ToPlayer()); owner->ToPlayer()->SendDirectMessage(petCastFailed.Write()); } void Spell::SendCastResult(Player* caster, SpellInfo const* spellInfo, uint32 spellVisual, ObjectGuid cast_count, SpellCastResult result, SpellCustomErrors customError /*= SPELL_CUSTOM_ERROR_NONE*/, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) { if (result == SPELL_CAST_OK) return; WorldPackets::Spells::CastFailed packet; packet.SpellXSpellVisualID = spellVisual; FillSpellCastFailedArgs(packet, cast_count, spellInfo, result, customError, param1, param2, caster); caster->GetSession()->SendPacket(packet.Write()); } void Spell::SendMountResult(MountResult result) { if (result == MountResult::Ok) return; if (!m_caster->IsPlayer()) return; Player* caster = m_caster->ToPlayer(); if (caster->IsLoading()) // don't send mount results at loading time return; WorldPackets::Spells::MountResult packet; packet.Result = AsUnderlyingType(result); caster->SendDirectMessage(packet.Write()); } void Spell::SendSpellStart() { if (!IsNeedSendToClient()) return; TC_LOG_DEBUG("spells", "Sending SMSG_SPELL_START id=%u", m_spellInfo->Id); uint32 castFlags = CAST_FLAG_HAS_TRAJECTORY; uint32 schoolImmunityMask = m_caster->GetSchoolImmunityMask(); uint32 mechanicImmunityMask = m_caster->GetMechanicImmunityMask(); if (schoolImmunityMask || mechanicImmunityMask) castFlags |= CAST_FLAG_IMMUNITY; if (((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) && !m_fromClient) castFlags |= CAST_FLAG_PENDING; if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NEEDS_AMMO_DATA)) castFlags |= CAST_FLAG_PROJECTILE; if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) && std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power != POWER_HEALTH; }) != m_powerCost.end()) castFlags |= CAST_FLAG_POWER_LEFT_SELF; if (std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power == POWER_RUNES; }) != m_powerCost.end()) castFlags |= CAST_FLAG_NO_GCD; // not needed, but Blizzard sends it WorldPackets::Spells::SpellStart packet; WorldPackets::Spells::SpellCastData& castData = packet.Cast; if (m_CastItem) castData.CasterGUID = m_CastItem->GetGUID(); else castData.CasterGUID = m_caster->GetGUID(); castData.CasterUnit = m_caster->GetGUID(); castData.CastID = m_castId; castData.OriginalCastID = m_originalCastId; castData.SpellID = m_spellInfo->Id; castData.SpellXSpellVisualID = m_SpellVisual; castData.CastFlags = castFlags; castData.CastFlagsEx = m_castFlagsEx; castData.CastTime = m_casttime; m_targets.Write(castData.Target); if (castFlags & CAST_FLAG_POWER_LEFT_SELF) { for (SpellPowerCost const& cost : m_powerCost) { WorldPackets::Spells::SpellPowerData powerData; powerData.Type = cost.Power; powerData.Cost = m_caster->GetPower(cost.Power); castData.RemainingPower.push_back(powerData); } } if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list { castData.RemainingRunes = boost::in_place(); //TODO: There is a crash caused by a spell with CAST_FLAG_RUNE_LIST casted by a creature //The creature is the mover of a player, so HandleCastSpellOpcode uses it as the caster if (Player* player = m_caster->ToPlayer()) { castData.RemainingRunes->Start = m_runesState; // runes state before castData.RemainingRunes->Count = player->GetRunesState(); // runes state after for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i) { // float casts ensure the division is performed on floats as we need float result float baseCd = float(player->GetRuneBaseCooldown()); castData.RemainingRunes->Cooldowns.push_back((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed } } else { castData.RemainingRunes->Start = 0; castData.RemainingRunes->Count = 0; for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i) castData.RemainingRunes->Cooldowns.push_back(0); } } if (castFlags & CAST_FLAG_PROJECTILE) UpdateSpellCastDataAmmo(castData.Ammo); if (castFlags & CAST_FLAG_IMMUNITY) { castData.Immunities.School = schoolImmunityMask; castData.Immunities.Value = mechanicImmunityMask; } /** @todo implement heal prediction packet data if (castFlags & CAST_FLAG_HEAL_PREDICTION) { castData.Predict.BeconGUID = ?? castData.Predict.Points = 0; castData.Predict.Type = 0; }**/ m_caster->SendMessageToSet(packet.Write(), true); } void Spell::SendSpellGo() { // not send invisible spell casting if (!IsNeedSendToClient()) return; TC_LOG_DEBUG("spells", "Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id); uint32 castFlags = CAST_FLAG_UNKNOWN_9; // triggered spells with spell visual != 0 if (((IsTriggered() && !m_spellInfo->IsAutoRepeatRangedSpell()) || m_triggeredByAuraSpell) && !m_fromClient) castFlags |= CAST_FLAG_PENDING; if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NEEDS_AMMO_DATA)) castFlags |= CAST_FLAG_PROJECTILE; // arrows/bullets visual if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->IsPet())) && std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power != POWER_HEALTH; }) != m_powerCost.end()) castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible if ((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && std::find_if(m_powerCost.begin(), m_powerCost.end(), [](SpellPowerCost const& cost) { return cost.Power == POWER_RUNES; }) != m_powerCost.end() && !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)) { castFlags |= CAST_FLAG_NO_GCD; // not needed, but Blizzard sends it castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list } if (m_spellInfo->HasEffect(SPELL_EFFECT_ACTIVATE_RUNE)) castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list if (m_targets.HasTraj()) castFlags |= CAST_FLAG_ADJUST_MISSILE; if (!m_spellInfo->StartRecoveryTime) castFlags |= CAST_FLAG_NO_GCD; WorldPackets::Spells::SpellGo packet; WorldPackets::Spells::SpellCastData& castData = packet.Cast; if (m_CastItem) castData.CasterGUID = m_CastItem->GetGUID(); else castData.CasterGUID = m_caster->GetGUID(); castData.CasterUnit = m_caster->GetGUID(); castData.CastID = m_castId; castData.OriginalCastID = m_originalCastId; castData.SpellID = m_spellInfo->Id; castData.SpellXSpellVisualID = m_SpellVisual; castData.CastFlags = castFlags; castData.CastFlagsEx = m_castFlagsEx; castData.CastTime = getMSTime(); UpdateSpellCastDataTargets(castData); m_targets.Write(castData.Target); if (castFlags & CAST_FLAG_POWER_LEFT_SELF) { for (SpellPowerCost const& cost : m_powerCost) { WorldPackets::Spells::SpellPowerData powerData; powerData.Type = cost.Power; powerData.Cost = m_caster->GetPower(cost.Power); castData.RemainingPower.push_back(powerData); } } if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list { castData.RemainingRunes = boost::in_place(); //TODO: There is a crash caused by a spell with CAST_FLAG_RUNE_LIST casted by a creature //The creature is the mover of a player, so HandleCastSpellOpcode uses it as the caster if (Player* player = m_caster->ToPlayer()) { castData.RemainingRunes->Start = m_runesState; // runes state before castData.RemainingRunes->Count = player->GetRunesState(); // runes state after for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i) { // float casts ensure the division is performed on floats as we need float result float baseCd = float(player->GetRuneBaseCooldown()); castData.RemainingRunes->Cooldowns.push_back((baseCd - float(player->GetRuneCooldown(i))) / baseCd * 255); // rune cooldown passed } } else { castData.RemainingRunes->Start = 0; castData.RemainingRunes->Count = 0; for (uint8 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i) castData.RemainingRunes->Cooldowns.push_back(0); } } if (castFlags & CAST_FLAG_ADJUST_MISSILE) { castData.MissileTrajectory.TravelTime = m_delayMoment; castData.MissileTrajectory.Pitch = m_targets.GetPitch(); } packet.LogData.Initialize(this); m_caster->SendCombatLogMessage(&packet); } /// Writes miss and hit targets for a SMSG_SPELL_GO packet void Spell::UpdateSpellCastDataTargets(WorldPackets::Spells::SpellCastData& data) { // This function also fill data for channeled spells: // m_needAliveTargetMask req for stop channeling if one target die for (TargetInfo& targetInfo : m_UniqueTargetInfo) { if (targetInfo.effectMask == 0) // No effect apply - all immune add state // possibly SPELL_MISS_IMMUNE2 for this?? targetInfo.missCondition = SPELL_MISS_IMMUNE2; if (targetInfo.missCondition == SPELL_MISS_NONE) // hits { data.HitTargets.push_back(targetInfo.targetGUID); data.HitStatus.emplace_back(SPELL_MISS_NONE); m_channelTargetEffectMask |= targetInfo.effectMask; } else // misses { data.MissTargets.push_back(targetInfo.targetGUID); data.MissStatus.emplace_back(targetInfo.missCondition, targetInfo.reflectResult); } } for (GOTargetInfo const& targetInfo : m_UniqueGOTargetInfo) data.HitTargets.push_back(targetInfo.targetGUID); // Always hits // Reset m_needAliveTargetMask for non channeled spell if (!m_spellInfo->IsChanneled()) m_channelTargetEffectMask = 0; } void Spell::UpdateSpellCastDataAmmo(WorldPackets::Spells::SpellAmmo& ammo) { uint32 ammoInventoryType = 0; uint32 ammoDisplayID = 0; if (m_caster->GetTypeId() == TYPEID_PLAYER) { Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK); if (pItem) { ammoInventoryType = pItem->GetTemplate()->GetInventoryType(); if (ammoInventoryType == INVTYPE_THROWN) ammoDisplayID = pItem->GetDisplayId(m_caster->ToPlayer()); else if (m_caster->HasAura(46699)) // Requires No Ammo { ammoDisplayID = 5996; // normal arrow ammoInventoryType = INVTYPE_AMMO; } } } else { for (uint8 i = 0; i < 3; ++i) { if (uint32 item_id = m_caster->GetVirtualItemId(i)) { if (ItemEntry const* itemEntry = sItemStore.LookupEntry(item_id)) { if (itemEntry->ClassID == ITEM_CLASS_WEAPON) { switch (itemEntry->SubclassID) { case ITEM_SUBCLASS_WEAPON_THROWN: ammoDisplayID = sDB2Manager.GetItemDisplayId(item_id, m_caster->GetVirtualItemAppearanceMod(i)); ammoInventoryType = itemEntry->InventoryType; break; case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: ammoDisplayID = 5996; // is this need fixing? ammoInventoryType = INVTYPE_AMMO; break; case ITEM_SUBCLASS_WEAPON_GUN: ammoDisplayID = 5998; // is this need fixing? ammoInventoryType = INVTYPE_AMMO; break; } if (ammoDisplayID) break; } } } } } ammo.DisplayID = ammoDisplayID; ammo.InventoryType = ammoInventoryType; } void Spell::SendSpellExecuteLog() { WorldPackets::CombatLog::SpellExecuteLog spellExecuteLog; spellExecuteLog.Caster = m_caster->GetGUID(); spellExecuteLog.SpellID = m_spellInfo->Id; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; if (_powerDrainTargets[effect->EffectIndex].empty() && _extraAttacksTargets[effect->EffectIndex].empty() && _durabilityDamageTargets[effect->EffectIndex].empty() && _genericVictimTargets[effect->EffectIndex].empty() && _tradeSkillTargets[effect->EffectIndex].empty() && _feedPetTargets[effect->EffectIndex].empty()) continue; spellExecuteLog.Effects.emplace_back(); WorldPackets::CombatLog::SpellExecuteLog::SpellLogEffect& spellLogEffect = spellExecuteLog.Effects.back(); spellLogEffect.Effect = effect->Effect; spellLogEffect.PowerDrainTargets = std::move(_powerDrainTargets[effect->EffectIndex]); spellLogEffect.ExtraAttacksTargets = std::move(_extraAttacksTargets[effect->EffectIndex]); spellLogEffect.DurabilityDamageTargets = std::move(_durabilityDamageTargets[effect->EffectIndex]); spellLogEffect.GenericVictimTargets = std::move(_genericVictimTargets[effect->EffectIndex]); spellLogEffect.TradeSkillTargets = std::move(_tradeSkillTargets[effect->EffectIndex]); spellLogEffect.FeedPetTargets = std::move(_feedPetTargets[effect->EffectIndex]); } if (!spellExecuteLog.Effects.empty()) m_caster->SendCombatLogMessage(&spellExecuteLog); } void Spell::ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit* target, uint32 powerType, uint32 points, float amplitude) { SpellLogEffectPowerDrainParams spellLogEffectPowerDrainParams; spellLogEffectPowerDrainParams.Victim = target->GetGUID(); spellLogEffectPowerDrainParams.Points = points; spellLogEffectPowerDrainParams.PowerType = powerType; spellLogEffectPowerDrainParams.Amplitude = amplitude; _powerDrainTargets[effIndex].push_back(spellLogEffectPowerDrainParams); } void Spell::ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit* victim, uint32 numAttacks) { SpellLogEffectExtraAttacksParams spellLogEffectExtraAttacksParams; spellLogEffectExtraAttacksParams.Victim = victim->GetGUID(); spellLogEffectExtraAttacksParams.NumAttacks = numAttacks; _extraAttacksTargets[effIndex].push_back(spellLogEffectExtraAttacksParams); } void Spell::ExecuteLogEffectInterruptCast(uint8 /*effIndex*/, Unit* victim, uint32 spellId) { WorldPackets::CombatLog::SpellInterruptLog data; data.Caster = m_caster->GetGUID(); data.Victim = victim->GetGUID(); data.InterruptedSpellID = m_spellInfo->Id; data.SpellID = spellId; m_caster->SendMessageToSet(data.Write(), true); } void Spell::ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit* victim, int32 itemId, int32 amount) { SpellLogEffectDurabilityDamageParams spellLogEffectDurabilityDamageParams; spellLogEffectDurabilityDamageParams.Victim = victim->GetGUID(); spellLogEffectDurabilityDamageParams.ItemID = itemId; spellLogEffectDurabilityDamageParams.Amount = amount; _durabilityDamageTargets[effIndex].push_back(spellLogEffectDurabilityDamageParams); } void Spell::ExecuteLogEffectOpenLock(uint8 effIndex, Object* obj) { SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams; spellLogEffectGenericVictimParams.Victim = obj->GetGUID(); _genericVictimTargets[effIndex].push_back(spellLogEffectGenericVictimParams); } void Spell::ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry) { SpellLogEffectTradeSkillItemParams spellLogEffectTradeSkillItemParams; spellLogEffectTradeSkillItemParams.ItemID = entry; _tradeSkillTargets[effIndex].push_back(spellLogEffectTradeSkillItemParams); } void Spell::ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry) { SpellLogEffectFeedPetParams spellLogEffectFeedPetParams; spellLogEffectFeedPetParams.ItemID = entry; _feedPetTargets[effIndex].push_back(spellLogEffectFeedPetParams); } void Spell::ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject* obj) { SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams; spellLogEffectGenericVictimParams.Victim = obj->GetGUID(); _genericVictimTargets[effIndex].push_back(spellLogEffectGenericVictimParams); } void Spell::ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject* obj) { SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams; spellLogEffectGenericVictimParams.Victim = obj->GetGUID(); _genericVictimTargets[effIndex].push_back(spellLogEffectGenericVictimParams); } void Spell::ExecuteLogEffectResurrect(uint8 effect, Unit* target) { SpellLogEffectGenericVictimParams spellLogEffectGenericVictimParams; spellLogEffectGenericVictimParams.Victim = target->GetGUID(); _genericVictimTargets[effect].push_back(spellLogEffectGenericVictimParams); } void Spell::SendInterrupted(uint8 result) { WorldPackets::Spells::SpellFailure failurePacket; failurePacket.CasterUnit = m_caster->GetGUID(); failurePacket.CastID = m_castId; failurePacket.SpellID = m_spellInfo->Id; failurePacket.SpellXSpellVisualID = m_SpellVisual; failurePacket.Reason = result; m_caster->SendMessageToSet(failurePacket.Write(), true); WorldPackets::Spells::SpellFailedOther failedPacket; failedPacket.CasterUnit = m_caster->GetGUID(); failedPacket.CastID = m_castId; failedPacket.SpellID = m_spellInfo->Id; failedPacket.Reason = result; m_caster->SendMessageToSet(failedPacket.Write(), true); } void Spell::SendChannelUpdate(uint32 time) { if (time == 0) { m_caster->ClearChannelObjects(); m_caster->SetChannelSpellId(0); m_caster->SetChannelSpellXSpellVisualId(0); } WorldPackets::Spells::SpellChannelUpdate spellChannelUpdate; spellChannelUpdate.CasterGUID = m_caster->GetGUID(); spellChannelUpdate.TimeRemaining = time; m_caster->SendMessageToSet(spellChannelUpdate.Write(), true); } void Spell::SendChannelStart(uint32 duration) { WorldPackets::Spells::SpellChannelStart spellChannelStart; spellChannelStart.CasterGUID = m_caster->GetGUID(); spellChannelStart.SpellID = m_spellInfo->Id; spellChannelStart.SpellXSpellVisualID = m_SpellVisual; spellChannelStart.ChannelDuration = duration; m_caster->SendMessageToSet(spellChannelStart.Write(), true); uint32 schoolImmunityMask = m_caster->GetSchoolImmunityMask(); uint32 mechanicImmunityMask = m_caster->GetMechanicImmunityMask(); if (schoolImmunityMask || mechanicImmunityMask) { spellChannelStart.InterruptImmunities = boost::in_place(); spellChannelStart.InterruptImmunities->SchoolImmunities = schoolImmunityMask; spellChannelStart.InterruptImmunities->Immunities = mechanicImmunityMask; } m_timer = duration; for (TargetInfo const& target : m_UniqueTargetInfo) { m_caster->AddChannelObject(target.targetGUID); if (m_UniqueTargetInfo.size() == 1 && m_UniqueGOTargetInfo.empty()) if(target.targetGUID != m_caster->GetGUID()) if (Creature* creatureCaster = m_caster->ToCreature()) if (!creatureCaster->IsFocusing(this)) creatureCaster->FocusTarget(this, ObjectAccessor::GetWorldObject(*creatureCaster, target.targetGUID)); } for (GOTargetInfo const& target : m_UniqueGOTargetInfo) m_caster->AddChannelObject(target.targetGUID); m_caster->SetChannelSpellId(m_spellInfo->Id); m_caster->SetChannelSpellXSpellVisualId(m_SpellVisual); } void Spell::SendResurrectRequest(Player* target) { // get resurrector name for creature resurrections, otherwise packet will be not accepted // for player resurrections the name is looked up by guid std::string const sentName(m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex())); WorldPackets::Spells::ResurrectRequest resurrectRequest; resurrectRequest.ResurrectOffererGUID = m_caster->GetGUID(); resurrectRequest.ResurrectOffererVirtualRealmAddress = GetVirtualRealmAddress(); if (Pet* pet = target->GetPet()) { if (CharmInfo* charmInfo = pet->GetCharmInfo()) resurrectRequest.PetNumber = charmInfo->GetPetNumber(); } resurrectRequest.SpellID = m_spellInfo->Id; //packet.ReadBit("UseTimer"); /// @todo: 6.x Has to be implemented resurrectRequest.Sickness = m_caster->GetTypeId() != TYPEID_PLAYER; // "you'll be afflicted with resurrection sickness" resurrectRequest.Name = sentName; target->GetSession()->SendPacket(resurrectRequest.Write()); } void Spell::TakeCastItem() { if (!m_CastItem) return; Player* player = m_caster->ToPlayer(); if (!player) return; // not remove cast item at triggered spell (equipping, weapon damage, etc) if (_triggeredCastFlags & TRIGGERED_IGNORE_CAST_ITEM) return; ItemTemplate const* proto = m_CastItem->GetTemplate(); if (!proto) { // This code is to avoid a crash // I'm not sure, if this is really an error, but I guess every item needs a prototype TC_LOG_ERROR("spells", "Cast item has no item prototype %s", m_CastItem->GetGUID().ToString().c_str()); return; } bool expendable = false; bool withoutCharges = false; for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects()) { if (itemEffect->LegacySlotIndex >= m_CastItem->m_itemData->SpellCharges.size()) continue; // item has limited charges if (itemEffect->Charges) { if (itemEffect->Charges < 0) expendable = true; int32 charges = m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex); // item has charges left if (charges) { (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use if (proto->GetMaxStackSize() == 1) m_CastItem->SetSpellCharges(itemEffect->LegacySlotIndex, charges); m_CastItem->SetState(ITEM_CHANGED, player); } // all charges used withoutCharges = (charges == 0); } } if (expendable && withoutCharges) { uint32 count = 1; m_caster->ToPlayer()->DestroyItemCount(m_CastItem, count, true); // prevent crash at access to deleted m_targets.GetItemTarget if (m_CastItem == m_targets.GetItemTarget()) m_targets.SetItemTarget(NULL); m_CastItem = NULL; m_castItemGUID.Clear(); m_castItemEntry = 0; } } void Spell::TakePower() { if (m_CastItem || m_triggeredByAuraSpell) return; //Don't take power if the spell is cast while .cheat power is enabled. if (m_caster->IsPlayer()) if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_POWER)) return; for (SpellPowerCost& cost : m_powerCost) { Powers powerType = Powers(cost.Power); bool hit = true; if (m_caster->IsPlayer()) { if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNES) { ObjectGuid targetGUID = m_targets.GetUnitTargetGUID(); if (!targetGUID.IsEmpty()) { for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE) { hit = false; //lower spell cost on fail (by talent aura) if (Player* modOwner = m_caster->ToPlayer()->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, cost.Amount); } break; } } } } } CallScriptOnTakePowerHandlers(cost); if (powerType == POWER_RUNES) { TakeRunePower(hit); continue; } if (!cost.Amount) continue; // health as power used if (powerType == POWER_HEALTH) { m_caster->ModifyHealth(-cost.Amount); continue; } if (powerType >= MAX_POWERS) { TC_LOG_ERROR("spells", "Spell::TakePower: Unknown power type '%d'", powerType); continue; } if (hit) m_caster->ModifyPower(powerType, -cost.Amount); else if (cost.Amount > 0) m_caster->ModifyPower(powerType, -irand(0, cost.Amount / 4)); } } SpellCastResult Spell::CheckRuneCost() const { int32 runeCost = std::accumulate(m_powerCost.begin(), m_powerCost.end(), 0, [](int32 totalCost, SpellPowerCost const& cost) { return totalCost + (cost.Power == POWER_RUNES ? cost.Amount : 0); }); if (!runeCost) return SPELL_CAST_OK; Player* player = m_caster->ToPlayer(); if (!player) return SPELL_CAST_OK; if (player->getClass() != CLASS_DEATH_KNIGHT) return SPELL_CAST_OK; int32 readyRunes = 0; for (int32 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i) if (player->GetRuneCooldown(i) == 0) ++readyRunes; if (readyRunes < runeCost) return SPELL_FAILED_NO_POWER; // not sure if result code is correct return SPELL_CAST_OK; } void Spell::TakeRunePower(bool didHit) { if (m_caster->GetTypeId() != TYPEID_PLAYER || m_caster->getClass() != CLASS_DEATH_KNIGHT) return; Player* player = m_caster->ToPlayer(); m_runesState = player->GetRunesState(); // store previous state int32 runeCost = std::accumulate(m_powerCost.begin(), m_powerCost.end(), 0, [](int32 totalCost, SpellPowerCost const& cost) { return totalCost + (cost.Power == POWER_RUNES ? cost.Amount : 0); }); for (int32 i = 0; i < player->GetMaxPower(POWER_RUNES); ++i) { if (!player->GetRuneCooldown(i) && runeCost > 0) { player->SetRuneCooldown(i, didHit ? player->GetRuneBaseCooldown() : uint32(RUNE_MISS_COOLDOWN)); --runeCost; } sScriptMgr->OnModifyPower(player, POWER_RUNES, 0, runeCost, false, false); } } void Spell::TakeReagents() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // do not take reagents for these item casts if (m_CastItem && m_CastItem->GetTemplate()->GetFlags() & ITEM_FLAG_NO_REAGENT_COST) return; Player* p_caster = m_caster->ToPlayer(); if (p_caster->CanNoReagentCast(m_spellInfo)) return; for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x) { if (m_spellInfo->Reagent[x] <= 0) continue; uint32 itemid = m_spellInfo->Reagent[x]; uint32 itemcount = m_spellInfo->ReagentCount[x]; // if CastItem is also spell reagent if (m_CastItem && m_CastItem->GetEntry() == itemid) { for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects()) { if (itemEffect->LegacySlotIndex >= m_CastItem->m_itemData->SpellCharges.size()) continue; // CastItem will be used up and does not count as reagent int32 charges = m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex); if (itemEffect->Charges < 0 && abs(charges) < 2) { ++itemcount; break; } } m_CastItem = NULL; m_castItemGUID.Clear(); m_castItemEntry = 0; } // if GetItemTarget is also spell reagent if (m_targets.GetItemTargetEntry() == itemid) m_targets.SetItemTarget(NULL); p_caster->DestroyItemCount(itemid, itemcount, true); } } void Spell::HandleThreatSpells() { if (m_UniqueTargetInfo.empty()) return; if (!m_spellInfo->HasInitialAggro()) return; float threat = 0.0f; if (SpellThreatEntry const* threatEntry = sSpellMgr->GetSpellThreatEntry(m_spellInfo->Id)) { if (threatEntry->apPctMod != 0.0f) threat += threatEntry->apPctMod * m_caster->GetTotalAttackPowerValue(BASE_ATTACK); threat += threatEntry->flatMod; } else if (!m_spellInfo->HasAttribute(SPELL_ATTR0_CU_NO_INITIAL_THREAT)) threat += m_spellInfo->SpellLevel; // past this point only multiplicative effects occur if (threat == 0.0f) return; // since 2.0.1 threat from positive effects also is distributed among all targets, so the overall caused threat is at most the defined bonus threat /= m_UniqueTargetInfo.size(); for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { float threatToAdd = threat; if (ihit->missCondition != SPELL_MISS_NONE) threatToAdd = 0.0f; Unit* target = ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (!target) continue; // positive spells distribute threat among all units that are in combat with target, like healing if (m_spellInfo->IsPositive()) target->getHostileRefManager().threatAssist(m_caster, threatToAdd, m_spellInfo); // for negative spells threat gets distributed among affected targets else { if (!target->CanHaveThreatList()) continue; target->AddThreat(m_caster, threatToAdd, m_spellInfo->GetSchoolMask(), m_spellInfo); } } TC_LOG_DEBUG("spells", "Spell %u, added an additional %f threat for %s %u target(s)", m_spellInfo->Id, threat, m_spellInfo->IsPositive() ? "assisting" : "harming", uint32(m_UniqueTargetInfo.size())); } void Spell::HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOTarget, uint32 i, SpellEffectHandleMode mode) { effectHandleMode = mode; unitTarget = pUnitTarget; itemTarget = pItemTarget; gameObjTarget = pGOTarget; destTarget = &m_destTargets[i]._position; effectInfo = m_spellInfo->GetEffect(i); if (!effectInfo) { TC_LOG_ERROR("spells", "Spell: %u HandleEffects at EffectIndex: %u missing effect", m_spellInfo->Id, i); return; } uint32 eff = effectInfo->Effect; TC_LOG_DEBUG("spells", "Spell: %u Effect: %u", m_spellInfo->Id, eff); damage = CalculateDamage(i, unitTarget, &variance); bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i, mode); if (!preventDefault && eff < TOTAL_SPELL_EFFECTS) { (this->*SpellEffects[eff].Value)((SpellEffIndex)i); } } SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) { // check death state if (!m_caster->IsAlive() && !m_spellInfo->IsPassive() && !(m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_DEAD) || (IsTriggered() && !m_triggeredByAuraSpell))) return SPELL_FAILED_CASTER_DEAD; // check cooldowns to prevent cheating if (!m_spellInfo->IsPassive()) { if (m_caster->GetTypeId() == TYPEID_PLAYER) { //can cast triggered (by aura only?) spells while have this flag if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE) && m_caster->ToPlayer()->HasPlayerFlag(PLAYER_ALLOW_ONLY_ABILITY)) return SPELL_FAILED_SPELL_IN_PROGRESS; // check if we are using a potion in combat for the 2nd+ time. Cooldown is added only after caster gets out of combat if (!IsIgnoringCooldowns() && m_caster->ToPlayer()->GetLastPotionId() && m_CastItem && (m_CastItem->IsPotion() || m_spellInfo->IsCooldownStartedOnEvent())) return SPELL_FAILED_NOT_READY; } if (!m_caster->GetSpellHistory()->IsReady(m_spellInfo, m_castItemEntry, IsIgnoringCooldowns())) { if (IsTriggered() || m_triggeredByAuraSpell) return SPELL_FAILED_DONT_REPORT; else return SPELL_FAILED_NOT_READY; } } if (m_spellInfo->HasAttribute(SPELL_ATTR7_IS_CHEAT_SPELL) && !m_caster->HasUnitFlag2(UNIT_FLAG2_ALLOW_CHEAT_SPELLS)) { m_customError = SPELL_CUSTOM_ERROR_GM_ONLY; return SPELL_FAILED_CUSTOM_ERROR; } // Check global cooldown if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_GCD) && HasGlobalCooldown()) return !m_spellInfo->HasAttribute(SPELL_ATTR0_DISABLED_WHILE_ACTIVE) ? SPELL_FAILED_NOT_READY : SPELL_FAILED_DONT_REPORT; // only triggered spells can be processed an ended battleground if (!IsTriggered() && m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground* bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() == STATUS_WAIT_LEAVE) return SPELL_FAILED_DONT_REPORT; if (m_caster->GetTypeId() == TYPEID_PLAYER && VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled()) { if (m_spellInfo->HasAttribute(SPELL_ATTR0_OUTDOORS_ONLY) && !m_caster->GetMap()->IsOutdoors(m_caster->GetPhaseShift(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) return SPELL_FAILED_ONLY_OUTDOORS; if (m_spellInfo->HasAttribute(SPELL_ATTR0_INDOORS_ONLY) && m_caster->GetMap()->IsOutdoors(m_caster->GetPhaseShift(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) return SPELL_FAILED_ONLY_INDOORS; } // only check at first call, Stealth auras are already removed at second call // for now, ignore triggered spells if (strict && !(_triggeredCastFlags & TRIGGERED_IGNORE_SHAPESHIFT)) { bool checkForm = true; // Ignore form req aura Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT); for (AuraEffect const* aurEff : ignore) { if (!aurEff->IsAffectingSpell(m_spellInfo)) continue; checkForm = false; break; } if (checkForm) { // Cannot be used in this stance/form SpellCastResult shapeError = m_spellInfo->CheckShapeshift(m_caster->GetShapeshiftForm()); if (shapeError != SPELL_CAST_OK) return shapeError; if ((m_spellInfo->HasAttribute(SPELL_ATTR0_ONLY_STEALTHED)) && !(m_caster->HasStealthAura())) return SPELL_FAILED_ONLY_STEALTHED; } } if (m_caster->HasAuraTypeWithMiscvalue(SPELL_AURA_BLOCK_SPELL_FAMILY, m_spellInfo->SpellFamilyName)) return SPELL_FAILED_SPELL_UNAVAILABLE; bool reqCombat = true; Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE); for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j) { if ((*j)->IsAffectingSpell(m_spellInfo)) { m_needComboPoints = false; if ((*j)->GetMiscValue() == 1) { reqCombat=false; break; } } } // caster state requirements // not for triggered spells (needed by execute) if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURASTATE)) { if (m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraStateType(m_spellInfo->CasterAuraState), m_spellInfo, m_caster)) return SPELL_FAILED_CASTER_AURASTATE; if (m_spellInfo->ExcludeCasterAuraState && m_caster->HasAuraState(AuraStateType(m_spellInfo->ExcludeCasterAuraState), m_spellInfo, m_caster)) return SPELL_FAILED_CASTER_AURASTATE; // Note: spell 62473 requres casterAuraSpell = triggering spell if (m_spellInfo->CasterAuraSpell && !m_caster->HasAura(m_spellInfo->CasterAuraSpell)) return SPELL_FAILED_CASTER_AURASTATE; if (m_spellInfo->ExcludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->ExcludeCasterAuraSpell)) return SPELL_FAILED_CASTER_AURASTATE; if (reqCombat && m_caster->IsInCombat() && !m_spellInfo->CanBeUsedInCombat()) return SPELL_FAILED_AFFECTING_COMBAT; } // cancel autorepeat spells if cast start when moving // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code) // Do not cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving() && (!m_caster->IsCharmed() || !m_caster->GetCharmerGUID().IsCreature()) && !m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_CAST_WHILE_WALKING, m_spellInfo)) { // skip stuck spell to allow use it in falling case and apply spell limitations at movement SpellEffectInfo const* effect = m_spellInfo->GetEffect(EFFECT_0); if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING_FAR) || (effect && effect->Effect != SPELL_EFFECT_STUCK)) && (IsAutoRepeat() || m_spellInfo->HasAuraInterruptFlag(AURA_INTERRUPT_FLAG_NOT_SEATED))) return SPELL_FAILED_MOVING; } // Check vehicle flags if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE)) { SpellCastResult vehicleCheck = m_spellInfo->CheckVehicle(m_caster); if (vehicleCheck != SPELL_CAST_OK) return vehicleCheck; } // check spell cast conditions from database { ConditionSourceInfo condInfo = ConditionSourceInfo(m_caster, m_targets.GetObjectTarget()); if (!sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id, condInfo)) { // mLastFailedCondition can be NULL if there was an error processing the condition in Condition::Meets (i.e. wrong data for ConditionTarget or others) if (condInfo.mLastFailedCondition && condInfo.mLastFailedCondition->ErrorType) { if (condInfo.mLastFailedCondition->ErrorType == SPELL_FAILED_CUSTOM_ERROR) m_customError = SpellCustomErrors(condInfo.mLastFailedCondition->ErrorTextId); return SpellCastResult(condInfo.mLastFailedCondition->ErrorType); } if (!condInfo.mLastFailedCondition || !condInfo.mLastFailedCondition->ConditionTarget) return SPELL_FAILED_CASTER_AURASTATE; return SPELL_FAILED_BAD_TARGETS; } } // Don't check explicit target for passive spells (workaround) (check should be skipped only for learn case) // those spells may have incorrect target entries or not filled at all (for example 15332) // such spells when learned are not targeting anyone using targeting system, they should apply directly to caster instead // also, such casts shouldn't be sent to client if (!(m_spellInfo->IsPassive() && (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster))) { // Check explicit target for m_originalCaster - todo: get rid of such workarounds Unit* caster = m_caster; if (m_originalCaster && m_caster->GetEntry() != WORLD_TRIGGER) // Do a simplified check for gameobject casts caster = m_originalCaster; SpellCastResult castResult = m_spellInfo->CheckExplicitTarget(caster, m_targets.GetObjectTarget(), m_targets.GetItemTarget()); if (castResult != SPELL_CAST_OK) return castResult; } if (Unit* target = m_targets.GetUnitTarget()) { SpellCastResult castResult = m_spellInfo->CheckTarget(m_caster, target, m_caster->GetEntry() == WORLD_TRIGGER); // skip stealth checks for GO casts if (castResult != SPELL_CAST_OK) return castResult; // If it's not a melee spell, check if vision is obscured by SPELL_AURA_INTERFERE_TARGETTING if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE) { for (auto const& itr : m_caster->GetAuraEffectsByType(SPELL_AURA_INTERFERE_TARGETTING)) if (!m_caster->IsFriendlyTo(itr->GetCaster()) && !target->HasAura(itr->GetId(), itr->GetCasterGUID())) return SPELL_FAILED_VISION_OBSCURED; for (auto const& itr : target->GetAuraEffectsByType(SPELL_AURA_INTERFERE_TARGETTING)) if (!m_caster->IsFriendlyTo(itr->GetCaster()) && (!target->HasAura(itr->GetId(), itr->GetCasterGUID()) || !m_caster->HasAura(itr->GetId(), itr->GetCasterGUID()))) return SPELL_FAILED_VISION_OBSCURED; } if (target != m_caster) { // Must be behind the target if ((m_spellInfo->HasAttribute(SPELL_ATTR0_CU_REQ_CASTER_BEHIND_TARGET)) && target->HasInArc(static_cast<float>(M_PI), m_caster)) return SPELL_FAILED_NOT_BEHIND; // Target must be facing you if ((m_spellInfo->HasAttribute(SPELL_ATTR0_CU_REQ_TARGET_FACING_CASTER)) && !target->HasInArc(static_cast<float>(M_PI), m_caster)) return SPELL_FAILED_NOT_INFRONT; if (m_caster->GetEntry() != WORLD_TRIGGER) // Ignore LOS for gameobjects casts (wrongly cast by a trigger) { WorldObject* losTarget = m_caster; if (IsTriggered() && m_triggeredByAuraSpell) if (DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell->Id)) losTarget = dynObj; if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !target->IsWithinLOSInMap(losTarget, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) return SPELL_FAILED_LINE_OF_SIGHT; } } } // Check for line of sight for spells with dest if (m_targets.HasDst()) { float x, y, z; m_targets.GetDstPos()->GetPosition(x, y, z); if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !m_caster->IsWithinLOS(x, y, z, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) return SPELL_FAILED_LINE_OF_SIGHT; } // check pet presence for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (effect && effect->TargetA.GetTarget() == TARGET_UNIT_PET) { if (!m_caster->GetGuardianPet()) { if (m_triggeredByAuraSpell) // not report pet not existence for triggered spells return SPELL_FAILED_DONT_REPORT; else return SPELL_FAILED_NO_PET; } break; } } // Spell cast only in battleground if ((m_spellInfo->HasAttribute(SPELL_ATTR3_BATTLEGROUND)) && m_caster->GetTypeId() == TYPEID_PLAYER) if (!m_caster->ToPlayer()->InBattleground()) return SPELL_FAILED_ONLY_BATTLEGROUNDS; // do not allow spells to be cast in arenas or rated battlegrounds if (Player* player = m_caster->ToPlayer()) if (player->InArena()/* || player->InRatedBattleGround() NYI*/) { SpellCastResult castResult = CheckArenaAndRatedBattlegroundCastRules(); if (castResult != SPELL_CAST_OK) return castResult; } // zone check if (m_caster->GetTypeId() == TYPEID_UNIT || !m_caster->ToPlayer()->IsGameMaster()) { uint32 zone, area; m_caster->GetZoneAndAreaId(zone, area); SpellCastResult locRes = m_spellInfo->CheckLocation(m_caster->GetMapId(), zone, area, m_caster->ToPlayer()); if (locRes != SPELL_CAST_OK) return locRes; } // not let players cast spells at mount (and let do it to creatures) if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_MOUNTED_OR_ON_VEHICLE) && !m_spellInfo->IsPassive() && !m_spellInfo->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_MOUNTED)) { if (m_caster->IsInFlight()) return SPELL_FAILED_NOT_ON_TAXI; else return SPELL_FAILED_NOT_MOUNTED; } // check spell focus object if (m_spellInfo->RequiresSpellFocus) { focusObject = SearchSpellFocus(); if (!focusObject) return SPELL_FAILED_REQUIRES_SPELL_FOCUS; } SpellCastResult castResult = SPELL_CAST_OK; // always (except passive spells) check items (only player related checks) if (!m_spellInfo->IsPassive()) { castResult = CheckItems(param1, param2); if (castResult != SPELL_CAST_OK) return castResult; } // Triggered spells also have range check /// @todo determine if there is some flag to enable/disable the check castResult = CheckRange(strict); if (castResult != SPELL_CAST_OK) return castResult; if (!(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)) { castResult = CheckPower(); if (castResult != SPELL_CAST_OK) return castResult; } if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS)) { castResult = CheckCasterAuras(param1); if (castResult != SPELL_CAST_OK) return castResult; } // script hook castResult = CallScriptCheckCastHandlers(); if (castResult != SPELL_CAST_OK) return castResult; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; // for effects of spells that have only one target switch (effect->Effect) { case SPELL_EFFECT_DUMMY: { if (m_spellInfo->Id == 19938) // Awaken Peon { Unit* unit = m_targets.GetUnitTarget(); if (!unit || !unit->HasAura(17743)) return SPELL_FAILED_BAD_TARGETS; } else if (m_spellInfo->Id == 31789) // Righteous Defense { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_DONT_REPORT; Unit* target = m_targets.GetUnitTarget(); if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty()) return SPELL_FAILED_BAD_TARGETS; } break; } case SPELL_EFFECT_LEARN_SPELL: { if (effect->TargetA.GetTarget() != TARGET_UNIT_PET) break; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(effect->TriggerSpell, DIFFICULTY_NONE); if (!learn_spellproto) return SPELL_FAILED_NOT_KNOWN; if (m_spellInfo->SpellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; break; } case SPELL_EFFECT_UNLOCK_GUILD_VAULT_TAB: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (Guild* guild = m_caster->ToPlayer()->GetGuild()) if (guild->GetLeaderGUID() != m_caster->ToPlayer()->GetGUID()) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; break; } case SPELL_EFFECT_LEARN_PET_SPELL: { // check target only for unit target case if (Unit* unit = m_targets.GetUnitTarget()) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Pet* pet = unit->ToPet(); if (!pet || pet->GetOwner() != m_caster) return SPELL_FAILED_BAD_TARGETS; SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(effect->TriggerSpell, DIFFICULTY_NONE); if (!learn_spellproto) return SPELL_FAILED_NOT_KNOWN; if (m_spellInfo->SpellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; } break; } case SPELL_EFFECT_APPLY_GLYPH: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_GLYPH_NO_SPEC; Player* caster = m_caster->ToPlayer(); if (!caster->HasSpell(m_misc.SpellId)) return SPELL_FAILED_NOT_KNOWN; if (uint32 glyphId = effect->MiscValue) { GlyphPropertiesEntry const* glyphProperties = sGlyphPropertiesStore.LookupEntry(glyphId); if (!glyphProperties) return SPELL_FAILED_INVALID_GLYPH; std::vector<uint32> const* glyphBindableSpells = sDB2Manager.GetGlyphBindableSpells(glyphId); if (!glyphBindableSpells) return SPELL_FAILED_INVALID_GLYPH; if (std::find(glyphBindableSpells->begin(), glyphBindableSpells->end(), m_misc.SpellId) == glyphBindableSpells->end()) return SPELL_FAILED_INVALID_GLYPH; if (std::vector<uint32> const* glyphRequiredSpecs = sDB2Manager.GetGlyphRequiredSpecs(glyphId)) { if (!caster->GetPrimarySpecialization()) return SPELL_FAILED_GLYPH_NO_SPEC; if (std::find(glyphRequiredSpecs->begin(), glyphRequiredSpecs->end(), caster->GetPrimarySpecialization()) == glyphRequiredSpecs->end()) return SPELL_FAILED_GLYPH_INVALID_SPEC; } uint32 replacedGlyph = 0; for (uint32 activeGlyphId : caster->GetGlyphs(caster->GetActiveTalentGroup())) { if (std::vector<uint32> const* activeGlyphBindableSpells = sDB2Manager.GetGlyphBindableSpells(activeGlyphId)) { if (std::find(activeGlyphBindableSpells->begin(), activeGlyphBindableSpells->end(), m_misc.SpellId) != activeGlyphBindableSpells->end()) { replacedGlyph = activeGlyphId; break; } } } for (uint32 activeGlyphId : caster->GetGlyphs(caster->GetActiveTalentGroup())) { if (activeGlyphId == replacedGlyph) continue; if (activeGlyphId == glyphId) return SPELL_FAILED_UNIQUE_GLYPH; if (sGlyphPropertiesStore.AssertEntry(activeGlyphId)->GlyphExclusiveCategoryID == glyphProperties->GlyphExclusiveCategoryID) return SPELL_FAILED_GLYPH_EXCLUSIVE_CATEGORY; } } break; } case SPELL_EFFECT_FEED_PET: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Item* foodItem = m_targets.GetItemTarget(); if (!foodItem) return SPELL_FAILED_BAD_TARGETS; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; if (!pet->HaveInDiet(foodItem->GetTemplate())) return SPELL_FAILED_WRONG_PET_FOOD; if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->GetBaseItemLevel())) return SPELL_FAILED_FOOD_LOWLEVEL; if (m_caster->IsInCombat() || pet->IsInCombat()) return SPELL_FAILED_AFFECTING_COMBAT; break; } case SPELL_EFFECT_POWER_BURN: case SPELL_EFFECT_POWER_DRAIN: { // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects) if (m_caster->IsPlayer()) if (effect->TargetA.GetTarget() != TARGET_UNIT_CASTER) if (Unit* target = m_targets.GetUnitTarget()) if (target != m_caster && target->GetPowerType() != Powers(effect->MiscValue)) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_CHARGE: { if (!(_triggeredCastFlags & TRIGGERED_IGNORE_CASTER_AURAS) && m_caster->HasUnitState(UNIT_STATE_ROOT)) return SPELL_FAILED_ROOTED; if (GetSpellInfo()->NeedsExplicitUnitTarget()) { Unit* target = m_targets.GetUnitTarget(); if (!target) return SPELL_FAILED_DONT_REPORT; // first we must check to see if the target is in LoS. A path can usually be built but LoS matters for charge spells if (!target->IsWithinLOSInMap(m_caster)) //Do full LoS/Path check. Don't exclude m2 return SPELL_FAILED_LINE_OF_SIGHT; float objSize = target->GetCombatReach(); float range = m_spellInfo->GetMaxRange(true, m_caster, this) * 1.5f + objSize; // can't be overly strict m_preGeneratedPath = std::make_unique<PathGenerator>(m_caster); m_preGeneratedPath->SetPathLengthLimit(range); // first try with raycast, if it fails fall back to normal path float targetObjectSize = std::min(target->GetCombatReach(), 4.0f); bool result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, true); if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT) return SPELL_FAILED_OUT_OF_RANGE; else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) { result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, false); if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT) return SPELL_FAILED_OUT_OF_RANGE; else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) return SPELL_FAILED_NOPATH; else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if not in a straight line return SPELL_FAILED_NOPATH; } else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if in a straight line return SPELL_FAILED_NOPATH; m_preGeneratedPath->ReducePathLenghtByDist(objSize); // move back } break; } case SPELL_EFFECT_SKINNING: { if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.GetUnitTarget() || m_targets.GetUnitTarget()->GetTypeId() != TYPEID_UNIT) return SPELL_FAILED_BAD_TARGETS; if (!m_targets.GetUnitTarget()->HasUnitFlag(UNIT_FLAG_SKINNABLE)) return SPELL_FAILED_TARGET_UNSKINNABLE; Creature* creature = m_targets.GetUnitTarget()->ToCreature(); if (!creature->IsCritter() && !creature->loot.isLooted()) return SPELL_FAILED_TARGET_NOT_LOOTED; uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill(); int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill); int32 TargetLevel = creature->GetCreatureTemplate()->minlevel; int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5); if (ReqValue > skillValue) return SPELL_FAILED_LOW_CASTLEVEL; // chance for fail at orange skinning attempt if ((m_selfContainer && (*m_selfContainer) == this) && skillValue < sWorld->GetConfigMaxSkillValue() && (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37)) return SPELL_FAILED_TRY_AGAIN; break; } case SPELL_EFFECT_OPEN_LOCK: { if (effect->TargetA.GetTarget() != TARGET_GAMEOBJECT_TARGET && effect->TargetA.GetTarget() != TARGET_GAMEOBJECT_ITEM_TARGET) break; if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc. // we need a go target in case of TARGET_GAMEOBJECT_TARGET || (effect->TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget())) return SPELL_FAILED_BAD_TARGETS; Item* pTempItem = NULL; if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) pTempItem = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED); } else if (m_targets.GetTargetMask() & TARGET_FLAG_ITEM) pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.GetItemTargetGUID()); // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM_TARGET if (effect->TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET && !m_targets.GetGOTarget() && (!pTempItem || !pTempItem->GetTemplate()->GetLockID() || !pTempItem->IsLocked())) return SPELL_FAILED_BAD_TARGETS; if (m_spellInfo->Id != 1842 || (m_targets.GetGOTarget() && m_targets.GetGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP)) if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners !m_caster->ToPlayer()->CanUseBattlegroundObject(m_targets.GetGOTarget())) return SPELL_FAILED_TRY_AGAIN; // get the lock entry uint32 lockId = 0; if (GameObject* go = m_targets.GetGOTarget()) { lockId = go->GetGOInfo()->GetLockId(); if (!lockId) return SPELL_FAILED_BAD_TARGETS; } else if (Item* itm = m_targets.GetItemTarget()) lockId = itm->GetTemplate()->GetLockID(); SkillType skillId = SKILL_NONE; int32 reqSkillValue = 0; int32 skillValue = 0; // check lock compatibility SpellCastResult res = CanOpenLock(effect->EffectIndex, lockId, skillId, reqSkillValue, skillValue); if (res != SPELL_CAST_OK) return res; break; } case SPELL_EFFECT_RESURRECT_PET: { Creature* pet = m_caster->GetGuardianPet(); if (pet && pet->IsAlive()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; break; } // This is generic summon effect case SPELL_EFFECT_SUMMON: { SummonPropertiesEntry const* SummonProperties = sSummonPropertiesStore.LookupEntry(effect->MiscValueB); if (!SummonProperties) break; switch (SummonProperties->Control) { case SUMMON_CATEGORY_PET: if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && !m_caster->GetPetGUID().IsEmpty()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; /* fallthrough */ // intentional, check both GetPetGUID() and GetCharmGUID for SUMMON_CATEGORY_PET case SUMMON_CATEGORY_PUPPET: if (!m_caster->GetCharmGUID().IsEmpty()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } break; } case SPELL_EFFECT_CREATE_TAMED_PET: { if (m_targets.GetUnitTarget()) { if (m_targets.GetUnitTarget()->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && !m_targets.GetUnitTarget()->GetPetGUID().IsEmpty()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; } break; } case SPELL_EFFECT_SUMMON_PET: { if (!m_caster->GetPetGUID().IsEmpty()) //let warlock do a replacement summon { if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player) if (Pet* pet = m_caster->ToPlayer()->GetPet()) pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID()); } else if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) return SPELL_FAILED_ALREADY_HAVE_SUMMON; } if (!m_caster->GetCharmGUID().IsEmpty()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } case SPELL_EFFECT_SUMMON_PLAYER: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_caster->GetTarget()) return SPELL_FAILED_BAD_TARGETS; Player* target = ObjectAccessor::FindPlayer(m_caster->ToPlayer()->GetTarget()); if (!target || m_caster->ToPlayer() == target || (!target->IsInSameRaidWith(m_caster->ToPlayer()) && m_spellInfo->Id != 48955)) // refer-a-friend spell return SPELL_FAILED_BAD_TARGETS; if (target->HasSummonPending()) return SPELL_FAILED_SUMMON_PENDING; // check if our map is dungeon MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId()); if (map->IsDungeon()) { uint32 mapId = m_caster->GetMap()->GetId(); Difficulty difficulty = m_caster->GetMap()->GetDifficultyID(); if (map->IsRaid()) if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty)) if (InstancePlayerBind* casterBind = m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty)) if (targetBind->perm && targetBind->save != casterBind->save) return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE; InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(mapId); if (!instance) return SPELL_FAILED_TARGET_NOT_IN_INSTANCE; if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId)) return SPELL_FAILED_BAD_TARGETS; } break; } // RETURN HERE case SPELL_EFFECT_SUMMON_RAF_FRIEND: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Player* playerCaster = m_caster->ToPlayer(); // if (!(playerCaster->GetTarget())) return SPELL_FAILED_BAD_TARGETS; Player* target = playerCaster->GetSelectedPlayer(); if (!target || !(target->GetSession()->GetRecruiterId() == playerCaster->GetSession()->GetAccountId() || target->GetSession()->GetAccountId() == playerCaster->GetSession()->GetRecruiterId())) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_LEAP: case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER: { //Do not allow to cast it before BG starts. if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() != STATUS_IN_PROGRESS) return SPELL_FAILED_TRY_AGAIN; break; } case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF: { if (!m_targets.GetUnitTarget() || m_targets.GetUnitTarget() == m_caster) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_LEAP_BACK: { if (m_caster->HasUnitState(UNIT_STATE_ROOT)) { if (m_caster->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_ROOTED; else return SPELL_FAILED_DONT_REPORT; } break; } case SPELL_EFFECT_JUMP: case SPELL_EFFECT_JUMP_DEST: { if (m_caster->HasUnitState(UNIT_STATE_ROOT)) return SPELL_FAILED_ROOTED; break; } case SPELL_EFFECT_TALENT_SPEC_SELECT: { ChrSpecializationEntry const* spec = sChrSpecializationStore.LookupEntry(m_misc.SpecializationId); Player* player = m_caster->ToPlayer(); if (!player) return SPELL_FAILED_TARGET_NOT_PLAYER; if (!spec || (spec->ClassID != m_caster->getClass() && !spec->IsPetSpecialization())) return SPELL_FAILED_NO_SPEC; if (spec->IsPetSpecialization()) { Pet* pet = player->GetPet(); if (!pet || !pet->IsHunterPet() || !pet->GetCharmInfo()) return SPELL_FAILED_NO_PET; } // can't change during already started arena/battleground if (Battleground const* bg = player->GetBattleground()) if (bg->GetStatus() == STATUS_IN_PROGRESS) return SPELL_FAILED_NOT_IN_BATTLEGROUND; break; } case SPELL_EFFECT_REMOVE_TALENT: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; TalentEntry const* talent = sTalentStore.LookupEntry(m_misc.TalentId); if (!talent) return SPELL_FAILED_DONT_REPORT; if (m_caster->GetSpellHistory()->HasCooldown(talent->SpellID)) { if (param1) *param1 = talent->SpellID; return SPELL_FAILED_CANT_UNTALENT; } break; } case SPELL_EFFECT_GIVE_ARTIFACT_POWER: case SPELL_EFFECT_GIVE_ARTIFACT_POWER_NO_BONUS: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Aura* artifactAura = m_caster->GetAura(ARTIFACTS_ALL_WEAPONS_GENERAL_WEAPON_EQUIPPED_PASSIVE); if (!artifactAura) return SPELL_FAILED_NO_ARTIFACT_EQUIPPED; Item* artifact = m_caster->ToPlayer()->GetItemByGuid(artifactAura->GetCastItemGUID()); if (!artifact) return SPELL_FAILED_NO_ARTIFACT_EQUIPPED; if (effect->Effect == SPELL_EFFECT_GIVE_ARTIFACT_POWER) { ArtifactEntry const* artifactEntry = sArtifactStore.LookupEntry(artifact->GetTemplate()->GetArtifactID()); if (!artifactEntry || artifactEntry->ArtifactCategoryID != effect->MiscValue) return SPELL_FAILED_WRONG_ARTIFACT_EQUIPPED; } break; } default: break; } } for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; switch (effect->ApplyAuraName) { case SPELL_AURA_MOD_POSSESS_PET: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_NO_PET; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; if (!pet->GetCharmerGUID().IsEmpty()) return SPELL_FAILED_CHARMED; break; } case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_AOE_CHARM: { if (!m_caster->GetCharmerGUID().IsEmpty()) return SPELL_FAILED_CHARMED; if (effect->ApplyAuraName == SPELL_AURA_MOD_CHARM || effect->ApplyAuraName == SPELL_AURA_MOD_POSSESS) { if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET) && !m_caster->GetPetGUID().IsEmpty()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (!m_caster->GetCharmGUID().IsEmpty()) return SPELL_FAILED_ALREADY_HAVE_CHARM; } if (Unit* target = m_targets.GetUnitTarget()) { if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (target->IsMounted()) return SPELL_FAILED_CANT_BE_CHARMED; if (!target->GetCharmerGUID().IsEmpty()) return SPELL_FAILED_CHARMED; if (target->GetOwner() && target->GetOwner()->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_TARGET_IS_PLAYER_CONTROLLED; int32 value = CalculateDamage(effect->EffectIndex, target); if (value && int32(target->GetLevelForTarget(m_caster)) > value) return SPELL_FAILED_HIGHLEVEL; } break; } case SPELL_AURA_MOUNTED: { if (m_caster->IsInWater() && m_spellInfo->HasAura(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED)) return SPELL_FAILED_ONLY_ABOVEWATER; // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells bool allowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena(); InstanceTemplate const* it = sObjectMgr->GetInstanceTemplate(m_caster->GetMapId()); if (it) allowMount = it->AllowMount; if (m_caster->GetTypeId() == TYPEID_PLAYER && !allowMount && !m_spellInfo->RequiredAreasID) return SPELL_FAILED_NO_MOUNTS_ALLOWED; if (m_caster->IsInDisallowedMountForm()) { SendMountResult(MountResult::Shapeshifted); // mount result gets sent before the cast result return SPELL_FAILED_DONT_REPORT; } break; }<|fim▁hole|> // can be cast at non-friendly unit or own pet/charm if (m_caster->IsFriendlyTo(m_targets.GetUnitTarget())) return SPELL_FAILED_TARGET_FRIENDLY; break; } case SPELL_AURA_FLY: case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED: { // not allow cast fly spells if not have req. skills (all spells is self target) // allow always ghost flight spells if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->IsAlive()) { Battlefield* Bf = sBattlefieldMgr->GetBattlefieldToZoneId(m_originalCaster->GetZoneId()); if (AreaTableEntry const* area = sAreaTableStore.LookupEntry(m_originalCaster->GetAreaId())) if (area->Flags[0] & AREA_FLAG_NO_FLY_ZONE || (Bf && !Bf->CanFlyIn())) return SPELL_FAILED_NOT_HERE; } break; } case SPELL_AURA_PERIODIC_MANA_LEECH: { if (effect->IsTargetingArea()) break; if (!m_targets.GetUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem) break; if (m_targets.GetUnitTarget()->GetPowerType() != POWER_MANA) return SPELL_FAILED_BAD_TARGETS; break; } default: break; } } // check trade slot case (last, for allow catch any another cast problems) if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (m_CastItem) return SPELL_FAILED_ITEM_ENCHANT_TRADE_WINDOW; if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_NOT_TRADING; TradeData* my_trade = m_caster->ToPlayer()->GetTradeData(); if (!my_trade) return SPELL_FAILED_NOT_TRADING; if (m_targets.GetItemTargetGUID() != ObjectGuid::TradeItem) return SPELL_FAILED_BAD_TARGETS; if (!IsTriggered()) if (my_trade->GetSpell()) return SPELL_FAILED_ITEM_ALREADY_ENCHANTED; } // check if caster has at least 1 combo point for spells that require combo points if (m_needComboPoints) if (Player* plrCaster = m_caster->ToPlayer()) if (!plrCaster->GetComboPoints()) return SPELL_FAILED_NO_COMBO_POINTS; // all ok return SPELL_CAST_OK; } SpellCastResult Spell::CheckPetCast(Unit* target) { if (m_caster->HasUnitState(UNIT_STATE_CASTING) && !(_triggeredCastFlags & TRIGGERED_IGNORE_CAST_IN_PROGRESS)) //prevent spellcast interruption by another spellcast return SPELL_FAILED_SPELL_IN_PROGRESS; // dead owner (pets still alive when owners ressed?) if (Unit* owner = m_caster->GetCharmerOrOwner()) if (!owner->IsAlive()) return SPELL_FAILED_CASTER_DEAD; if (!target && m_targets.GetUnitTarget()) target = m_targets.GetUnitTarget(); if (m_spellInfo->NeedsExplicitUnitTarget()) { if (!target) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; m_targets.SetUnitTarget(target); } // check cooldown if (Creature* creatureCaster = m_caster->ToCreature()) if (!creatureCaster->GetSpellHistory()->IsReady(m_spellInfo)) return SPELL_FAILED_NOT_READY; // Check if spell is affected by GCD if (m_spellInfo->StartRecoveryCategory > 0) if (m_caster->GetCharmInfo() && m_caster->GetSpellHistory()->HasGlobalCooldown(m_spellInfo)) return SPELL_FAILED_NOT_READY; return CheckCast(true); } SpellCastResult Spell::CheckCasterAuras(uint32* param1) const { // spells totally immuned to caster auras (wsg flag drop, give marks etc) if (m_spellInfo->HasAttribute(SPELL_ATTR6_IGNORE_CASTER_AURAS)) return SPELL_CAST_OK; // these attributes only show the spell as usable on the client when it has related aura applied // still they need to be checked against certain mechanics // SPELL_ATTR5_USABLE_WHILE_STUNNED by default only MECHANIC_STUN (ie no sleep, knockout, freeze, etc.) bool usableWhileStunned = m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_STUNNED); // SPELL_ATTR5_USABLE_WHILE_FEARED by default only fear (ie no horror) bool usableWhileFeared = m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_FEARED); // SPELL_ATTR5_USABLE_WHILE_CONFUSED by default only disorient (ie no polymorph) bool usableWhileConfused = m_spellInfo->HasAttribute(SPELL_ATTR5_USABLE_WHILE_CONFUSED); // Check whether the cast should be prevented by any state you might have. SpellCastResult result = SPELL_CAST_OK; // Get unit state uint32 const unitflag = m_caster->m_unitData->Flags; // this check should only be done when player does cast directly // (ie not when it's called from a script) Breaks for example PlayerAI when charmed /* if (!m_caster->GetCharmerGUID().IsEmpty()) { if (Unit* charmer = m_caster->GetCharmer()) if (charmer->GetUnitBeingMoved() != m_caster && !CheckSpellCancelsCharm(param1)) result = SPELL_FAILED_CHARMED; } */ // spell has attribute usable while having a cc state, check if caster has allowed mechanic auras, another mechanic types must prevent cast spell auto mechanicCheck = [&](AuraType type) -> SpellCastResult { bool foundNotMechanic = false; Unit::AuraEffectList const& auras = m_caster->GetAuraEffectsByType(type); for (AuraEffect const* aurEff : auras) { uint32 const mechanicMask = aurEff->GetSpellInfo()->GetAllEffectsMechanicMask(); if (mechanicMask && !(mechanicMask & GetSpellInfo()->GetAllowedMechanicMask())) { foundNotMechanic = true; // fill up aura mechanic info to send client proper error message if (param1) { *param1 = aurEff->GetSpellInfo()->GetEffect(aurEff->GetEffIndex())->Mechanic; if (!*param1) *param1 = aurEff->GetSpellInfo()->Mechanic; } break; } } if (foundNotMechanic) { switch (type) { case SPELL_AURA_MOD_STUN: return SPELL_FAILED_STUNNED; case SPELL_AURA_MOD_FEAR: return SPELL_FAILED_FLEEING; case SPELL_AURA_MOD_CONFUSE: return SPELL_FAILED_CONFUSED; default: ABORT(); return SPELL_FAILED_NOT_KNOWN; } } return SPELL_CAST_OK; }; if (unitflag & UNIT_FLAG_STUNNED) { if (usableWhileStunned) { SpellCastResult mechanicResult = mechanicCheck(SPELL_AURA_MOD_STUN); if (mechanicResult != SPELL_CAST_OK) result = mechanicResult; } else if (!CheckSpellCancelsStun(param1)) result = SPELL_FAILED_STUNNED; } else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType & SPELL_PREVENTION_TYPE_SILENCE && !CheckSpellCancelsSilence(param1)) result = SPELL_FAILED_SILENCED; else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType & SPELL_PREVENTION_TYPE_PACIFY && !CheckSpellCancelsPacify(param1)) result = SPELL_FAILED_PACIFIED; else if (unitflag & UNIT_FLAG_FLEEING) { if (usableWhileFeared) { SpellCastResult mechanicResult = mechanicCheck(SPELL_AURA_MOD_FEAR); if (mechanicResult != SPELL_CAST_OK) result = mechanicResult; } else if (!CheckSpellCancelsFear(param1)) result = SPELL_FAILED_FLEEING; } else if (unitflag & UNIT_FLAG_CONFUSED) { if (usableWhileConfused) { SpellCastResult mechanicResult = mechanicCheck(SPELL_AURA_MOD_CONFUSE); if (mechanicResult != SPELL_CAST_OK) result = mechanicResult; } else if (!CheckSpellCancelsConfuse(param1)) result = SPELL_FAILED_CONFUSED; } else if (m_caster->HasUnitFlag2(UNIT_FLAG2_NO_ACTIONS) && m_spellInfo->PreventionType & SPELL_PREVENTION_TYPE_NO_ACTIONS && !CheckSpellCancelsNoActions(param1)) result = SPELL_FAILED_NO_ACTIONS; // Attr must make flag drop spell totally immune from all effects if (result != SPELL_CAST_OK) return (param1 && *param1) ? SPELL_FAILED_PREVENTED_BY_MECHANIC : result; return SPELL_CAST_OK; } bool Spell::CheckSpellCancelsAuraEffect(AuraType auraType, uint32* param1) const { // Checking auras is needed now, because you are prevented by some state but the spell grants immunity. Unit::AuraEffectList const& auraEffects = m_caster->GetAuraEffectsByType(auraType); if (auraEffects.empty()) return true; for (AuraEffect const* aurEff : auraEffects) { if (m_spellInfo->SpellCancelsAuraEffect(aurEff)) continue; if (param1) { *param1 = aurEff->GetSpellEffectInfo()->Mechanic; if (!*param1) *param1 = aurEff->GetSpellInfo()->Mechanic; } return false; } return true; } bool Spell::CheckSpellCancelsCharm(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_CHARM, param1) && CheckSpellCancelsAuraEffect(SPELL_AURA_AOE_CHARM, param1) && CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_POSSESS, param1); } bool Spell::CheckSpellCancelsStun(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_STUN, param1) && CheckSpellCancelsAuraEffect(SPELL_AURA_STRANGULATE, param1); } bool Spell::CheckSpellCancelsSilence(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_SILENCE, param1) && CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_PACIFY_SILENCE, param1); } bool Spell::CheckSpellCancelsPacify(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_PACIFY, param1) && CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_PACIFY_SILENCE, param1); } bool Spell::CheckSpellCancelsFear(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_FEAR, param1) && CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_FEAR_2, param1); } bool Spell::CheckSpellCancelsConfuse(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_CONFUSE, param1); } bool Spell::CheckSpellCancelsNoActions(uint32* param1) const { return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_NO_ACTIONS, param1); } SpellCastResult Spell::CheckArenaAndRatedBattlegroundCastRules() { bool isRatedBattleground = false; // NYI bool isArena = !isRatedBattleground; // check USABLE attributes // USABLE takes precedence over NOT_USABLE if (isRatedBattleground && m_spellInfo->HasAttribute(SPELL_ATTR9_USABLE_IN_RATED_BATTLEGROUNDS)) return SPELL_CAST_OK; if (isArena && m_spellInfo->HasAttribute(SPELL_ATTR4_USABLE_IN_ARENA)) return SPELL_CAST_OK; // check NOT_USABLE attributes if (m_spellInfo->HasAttribute(SPELL_ATTR4_NOT_USABLE_IN_ARENA_OR_RATED_BG)) return isArena ? SPELL_FAILED_NOT_IN_ARENA : SPELL_FAILED_NOT_IN_RATED_BATTLEGROUND; if (isArena && m_spellInfo->HasAttribute(SPELL_ATTR9_NOT_USABLE_IN_ARENA)) return SPELL_FAILED_NOT_IN_ARENA; // check cooldowns uint32 spellCooldown = m_spellInfo->GetRecoveryTime(); if (isArena && spellCooldown > 10 * MINUTE * IN_MILLISECONDS) // not sure if still needed return SPELL_FAILED_NOT_IN_ARENA; if (isRatedBattleground && spellCooldown > 15 * MINUTE * IN_MILLISECONDS) return SPELL_FAILED_NOT_IN_RATED_BATTLEGROUND; return SPELL_CAST_OK; } int32 Spell::CalculateDamage(uint8 i, Unit const* target, float* var /*= nullptr*/) const { bool needRecalculateBasePoints = !(m_spellValue->CustomBasePointsMask & (1 << i)); return m_caster->CalculateSpellDamage(target, m_spellInfo, i, needRecalculateBasePoints ? nullptr : &m_spellValue->EffectBasePoints[i], var, m_castItemEntry, m_castItemLevel); } bool Spell::CanAutoCast(Unit* target) { if (!target) return (CheckPetCast(target) == SPELL_CAST_OK); ObjectGuid targetguid = target->GetGUID(); // check if target already has the same or a more powerful aura for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; if (!effect->IsAura()) continue; AuraType const& auraType = AuraType(effect->ApplyAuraName); Unit::AuraEffectList const& auras = target->GetAuraEffectsByType(auraType); for (Unit::AuraEffectList::const_iterator auraIt = auras.begin(); auraIt != auras.end(); ++auraIt) { if (GetSpellInfo()->Id == (*auraIt)->GetSpellInfo()->Id) return false; switch (sSpellMgr->CheckSpellGroupStackRules(GetSpellInfo(), (*auraIt)->GetSpellInfo())) { case SPELL_GROUP_STACK_RULE_EXCLUSIVE: return false; case SPELL_GROUP_STACK_RULE_EXCLUSIVE_FROM_SAME_CASTER: if (GetCaster() == (*auraIt)->GetCaster()) return false; break; case SPELL_GROUP_STACK_RULE_EXCLUSIVE_SAME_EFFECT: // this one has further checks, but i don't think they're necessary for autocast logic case SPELL_GROUP_STACK_RULE_EXCLUSIVE_HIGHEST: if (abs(effect->BasePoints) <= abs((*auraIt)->GetAmount())) return false; break; case SPELL_GROUP_STACK_RULE_DEFAULT: default: break; } } } SpellCastResult result = CheckPetCast(target); if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT) { // do not check targets for ground-targeted spells (we target them on top of the intended target anyway) if (GetSpellInfo()->ExplicitTargetMask & TARGET_FLAG_DEST_LOCATION) return true; SelectSpellTargets(); //check if among target units, our WANTED target is as well (->only self cast spells return false) for (std::vector<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetguid) return true; } // either the cast failed or the intended target wouldn't be hit return false; } void Spell::CheckSrc() { if (!m_targets.HasSrc()) m_targets.SetSrc(*m_caster); } void Spell::CheckDst() { if (!m_targets.HasDst()) m_targets.SetDst(*m_caster); } SpellCastResult Spell::CheckRange(bool strict) const { // Don't check for instant cast spells if (!strict && m_casttime == 0) return SPELL_CAST_OK; float minRange, maxRange; std::tie(minRange, maxRange) = GetMinMaxRange(strict); // dont check max_range to strictly after cast if (m_spellInfo->RangeEntry && m_spellInfo->RangeEntry->Flags != SPELL_RANGE_MELEE && !strict) maxRange += std::min(MAX_SPELL_RANGE_TOLERANCE, maxRange*0.1f); // 10% but no more than MAX_SPELL_RANGE_TOLERANCE // get square values for sqr distance checks minRange *= minRange; maxRange *= maxRange; Unit* target = m_targets.GetUnitTarget(); if (target && target != m_caster) { if (m_caster->GetExactDistSq(target) > maxRange) return SPELL_FAILED_OUT_OF_RANGE; if (minRange > 0.0f && m_caster->GetExactDistSq(target) < minRange) return SPELL_FAILED_OUT_OF_RANGE; if (m_caster->GetTypeId() == TYPEID_PLAYER && (((m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target)) && !m_caster->IsWithinBoundaryRadius(target))) return SPELL_FAILED_UNIT_NOT_INFRONT; } if (m_targets.HasDst() && !m_targets.HasTraj()) { if (m_caster->GetExactDistSq(m_targets.GetDstPos()) > maxRange) return SPELL_FAILED_OUT_OF_RANGE; if (minRange > 0.0f && m_caster->GetExactDistSq(m_targets.GetDstPos()) < minRange) return SPELL_FAILED_OUT_OF_RANGE; } return SPELL_CAST_OK; } std::pair<float, float> Spell::GetMinMaxRange(bool strict) const { float rangeMod = 0.0f; float minRange = 0.0f; float maxRange = 0.0f; if (strict && m_spellInfo->IsNextMeleeSwingSpell()) { maxRange = 100.0f; return std::pair<float, float>(minRange, maxRange); } if (m_spellInfo->RangeEntry) { Unit* target = m_targets.GetUnitTarget(); if (m_spellInfo->RangeEntry->Flags & SPELL_RANGE_MELEE) { rangeMod = m_caster->GetMeleeRange(target ? target : m_caster); // when the target is not a unit, take the caster's combat reach as the target's combat reach. } else { float meleeRange = 0.0f; if (m_spellInfo->RangeEntry->Flags & SPELL_RANGE_RANGED) meleeRange = m_caster->GetMeleeRange(target ? target : m_caster); // when the target is not a unit, take the caster's combat reach as the target's combat reach. minRange = m_caster->GetSpellMinRangeForTarget(target, m_spellInfo) + meleeRange; maxRange = m_caster->GetSpellMaxRangeForTarget(target, m_spellInfo); if (target || m_targets.GetCorpseTarget()) { rangeMod = m_caster->GetCombatReach() + (target ? target->GetCombatReach() : m_caster->GetCombatReach()); if (minRange > 0.0f && !(m_spellInfo->RangeEntry->Flags & SPELL_RANGE_RANGED)) minRange += rangeMod; } } if (target && m_caster->isMoving() && target->isMoving() && !m_caster->IsWalking() && !target->IsWalking() && (m_spellInfo->RangeEntry->Flags & SPELL_RANGE_MELEE || target->GetTypeId() == TYPEID_PLAYER)) rangeMod += 8.0f / 3.0f; } if (m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) && m_caster->GetTypeId() == TYPEID_PLAYER) if (Item* ranged = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK, true)) maxRange *= ranged->GetTemplate()->GetRangedModRange() * 0.01f; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, maxRange, const_cast<Spell*>(this)); maxRange += rangeMod; return std::pair<float, float>(minRange, maxRange); } SpellCastResult Spell::CheckPower() const { // item cast not used power if (m_CastItem) return SPELL_CAST_OK; for (SpellPowerCost const& cost : m_powerCost) { // health as power used - need check health amount if (cost.Power == POWER_HEALTH) { if (int32(m_caster->GetHealth()) <= cost.Amount) return SPELL_FAILED_CASTER_AURASTATE; continue; } // Check valid power type if (cost.Power >= MAX_POWERS) { TC_LOG_ERROR("spells", "Spell::CheckPower: Unknown power type '%d'", cost.Power); return SPELL_FAILED_UNKNOWN; } //check rune cost only if a spell has PowerType == POWER_RUNES if (cost.Power == POWER_RUNES) { SpellCastResult failReason = CheckRuneCost(); if (failReason != SPELL_CAST_OK) return failReason; } // Check power amount if (int32(m_caster->GetPower(cost.Power)) < cost.Amount) return SPELL_FAILED_NO_POWER; } return SPELL_CAST_OK; } SpellCastResult Spell::CheckItems(uint32* param1 /*= nullptr*/, uint32* param2 /*= nullptr*/) const { Player* player = m_caster->ToPlayer(); if (!player) return SPELL_CAST_OK; if (m_spellInfo->HasAttribute(SPELL_ATTR2_IGNORE_ITEM_CHECK)) return SPELL_CAST_OK; if (!m_CastItem) { if (!m_castItemGUID.IsEmpty()) return SPELL_FAILED_ITEM_NOT_READY; } else { uint32 itemid = m_CastItem->GetEntry(); if (!player->HasItemCount(itemid)) return SPELL_FAILED_ITEM_NOT_READY; ItemTemplate const* proto = m_CastItem->GetTemplate(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects()) if (itemEffect->LegacySlotIndex < m_CastItem->m_itemData->SpellCharges.size() && itemEffect->Charges) if (m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex) == 0) return SPELL_FAILED_NO_CHARGES_REMAIN; // consumable cast item checks if (proto->GetClass() == ITEM_CLASS_CONSUMABLE && m_targets.GetUnitTarget()) { // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example SpellCastResult failReason = SPELL_CAST_OK; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { // skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.GetUnitTarget() is not the real target but the caster if (!effect || effect->TargetA.GetTarget() == TARGET_UNIT_PET) continue; if (effect->Effect == SPELL_EFFECT_HEAL) { if (m_targets.GetUnitTarget()->IsFullHealth()) { failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH; continue; } else { failReason = SPELL_CAST_OK; break; } } // Mana Potion, Rage Potion, Thistle Tea(Rogue), ... if (effect->Effect == SPELL_EFFECT_ENERGIZE) { if (effect->MiscValue < 0 || effect->MiscValue >= int8(MAX_POWERS)) { failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER; continue; } Powers power = Powers(effect->MiscValue); if (m_targets.GetUnitTarget()->GetPower(power) == m_targets.GetUnitTarget()->GetMaxPower(power)) { failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER; continue; } else { failReason = SPELL_CAST_OK; break; } } } if (failReason != SPELL_CAST_OK) return failReason; } } // check target item if (!m_targets.GetItemTargetGUID().IsEmpty()) { Item* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_ITEM_GONE; if (!item->IsFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // if not item target then required item must be equipped else { if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT)) if (!player->HasItemFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // do not take reagents for these item casts if (!(m_CastItem && m_CastItem->GetTemplate()->GetFlags() & ITEM_FLAG_NO_REAGENT_COST)) { bool checkReagents = !(_triggeredCastFlags & TRIGGERED_IGNORE_POWER_AND_REAGENT_COST) && !player->CanNoReagentCast(m_spellInfo); // Not own traded item (in trader trade slot) requires reagents even if triggered spell if (!checkReagents) if (Item* targetItem = m_targets.GetItemTarget()) if (targetItem->GetOwnerGUID() != m_caster->GetGUID()) checkReagents = true; // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case. if (checkReagents) { for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { if (m_spellInfo->Reagent[i] <= 0) continue; uint32 itemid = m_spellInfo->Reagent[i]; uint32 itemcount = m_spellInfo->ReagentCount[i]; // if CastItem is also spell reagent if (m_CastItem && m_CastItem->GetEntry() == itemid) { ItemTemplate const* proto = m_CastItem->GetTemplate(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; for (ItemEffectEntry const* itemEffect : m_CastItem->GetEffects()) { if (itemEffect->LegacySlotIndex >= m_CastItem->m_itemData->SpellCharges.size()) continue; // CastItem will be used up and does not count as reagent int32 charges = m_CastItem->GetSpellCharges(itemEffect->LegacySlotIndex); if (itemEffect->Charges < 0 && abs(charges) < 2) { ++itemcount; break; } } } if (!player->HasItemCount(itemid, itemcount)) { if (param1) *param1 = itemid; return SPELL_FAILED_REAGENTS; } } } // check totem-item requirements (items presence in inventory) uint32 totems = 2; for (uint8 i = 0; i < 2; ++i) { if (m_spellInfo->Totem[i] != 0) { if (player->HasItemCount(m_spellInfo->Totem[i])) { totems -= 1; continue; } } else totems -= 1; } if (totems != 0) return SPELL_FAILED_TOTEMS; // Check items for TotemCategory (items presence in inventory) uint32 totemCategory = 2; for (uint8 i = 0; i < 2; ++i) { if (m_spellInfo->TotemCategory[i] != 0) { if (player->HasItemTotemCategory(m_spellInfo->TotemCategory[i])) { totemCategory -= 1; continue; } } else totemCategory -= 1; } if (totemCategory != 0) return SPELL_FAILED_TOTEM_CATEGORY; } // special checks for spell effects for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; switch (effect->Effect) { case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_LOOT: { // m_targets.GetUnitTarget() means explicit cast, otherwise we dont check for possible equip error Unit* target = m_targets.GetUnitTarget() ? m_targets.GetUnitTarget() : m_caster; if (target && target->GetTypeId() == TYPEID_PLAYER && !IsTriggered() && effect->ItemType) { ItemPosCountVec dest; InventoryResult msg = target->ToPlayer()->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, effect->ItemType, 1); if (msg != EQUIP_ERR_OK) { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(effect->ItemType); /// @todo Needs review if (pProto && !(pProto->GetItemLimitCategory())) { player->SendEquipError(msg, nullptr, nullptr, effect->ItemType); return SPELL_FAILED_DONT_REPORT; } else { if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000))) return SPELL_FAILED_TOO_MANY_OF_ITEM; else if (!(target->ToPlayer()->HasItemCount(effect->ItemType))) { player->SendEquipError(msg, nullptr, nullptr, effect->ItemType); return SPELL_FAILED_DONT_REPORT; } else if (SpellEffectInfo const* efi = m_spellInfo->GetEffect(EFFECT_1)) player->CastSpell(m_caster, efi->CalcValue(), false); // move this to anywhere return SPELL_FAILED_DONT_REPORT; } } } break; } case SPELL_EFFECT_ENCHANT_ITEM: if (effect->ItemType && m_targets.GetItemTarget() && (m_targets.GetItemTarget()->IsVellum())) { // cannot enchant vellum for other player if (m_targets.GetItemTarget()->GetOwner() != m_caster) return SPELL_FAILED_NOT_TRADEABLE; // do not allow to enchant vellum from scroll made by vellum-prevent exploit if (m_CastItem && m_CastItem->GetTemplate()->GetFlags() & ITEM_FLAG_NO_REAGENT_COST) return SPELL_FAILED_TOTEM_CATEGORY; ItemPosCountVec dest; InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, effect->ItemType, 1); if (msg != EQUIP_ERR_OK) { player->SendEquipError(msg, nullptr, nullptr, effect->ItemType); return SPELL_FAILED_DONT_REPORT; } } /* fallthrough */ case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC: { Item* targetItem = m_targets.GetItemTarget(); if (!targetItem) return SPELL_FAILED_ITEM_NOT_FOUND; // required level has to be checked also! Exploit fix if (targetItem->GetItemLevel(targetItem->GetOwner()) < m_spellInfo->BaseLevel || (targetItem->GetRequiredLevel() && uint32(targetItem->GetRequiredLevel()) < m_spellInfo->BaseLevel)) return SPELL_FAILED_LOWLEVEL; bool isItemUsable = false; for (ItemEffectEntry const* itemEffect : targetItem->GetEffects()) { if (itemEffect->SpellID && itemEffect->TriggerType == ITEM_SPELLTRIGGER_ON_USE) { isItemUsable = true; break; } } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(effect->MiscValue); // do not allow adding usable enchantments to items that have use effect already if (enchantEntry) { for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s) { switch (enchantEntry->Effect[s]) { case ITEM_ENCHANTMENT_TYPE_USE_SPELL: if (isItemUsable) return SPELL_FAILED_ON_USE_ENCHANT; break; case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET: { uint32 numSockets = 0; for (uint32 socket = 0; socket < MAX_ITEM_PROTO_SOCKETS; ++socket) if (targetItem->GetSocketColor(socket)) ++numSockets; if (numSockets == MAX_ITEM_PROTO_SOCKETS || targetItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)) return SPELL_FAILED_MAX_SOCKETS; break; } } } } // Not allow enchant in trade slot for some enchant type if (targetItem->GetOwner() != m_caster) { if (!enchantEntry) return SPELL_FAILED_ERROR; if (enchantEntry->Flags & ENCHANTMENT_CAN_SOULBOUND) return SPELL_FAILED_NOT_TRADEABLE; } break; } case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: { Item* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_ITEM_NOT_FOUND; // Not allow enchant in trade slot for some enchant type if (item->GetOwner() != m_caster) { uint32 enchant_id = effect->MiscValue; SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return SPELL_FAILED_ERROR; if (pEnchant->Flags & ENCHANTMENT_CAN_SOULBOUND) return SPELL_FAILED_NOT_TRADEABLE; } // Apply item level restriction if the enchanting spell has max level restrition set if (m_CastItem && m_spellInfo->MaxLevel > 0) { if (item->GetTemplate()->GetBaseItemLevel() < (uint32)m_CastItem->GetTemplate()->GetBaseRequiredLevel()) return SPELL_FAILED_LOWLEVEL; if (item->GetTemplate()->GetBaseItemLevel() > m_spellInfo->MaxLevel) return SPELL_FAILED_HIGHLEVEL; } break; } case SPELL_EFFECT_ENCHANT_HELD_ITEM: // check item existence in effect code (not output errors at offhand hold item effect to main hand for example break; case SPELL_EFFECT_DISENCHANT: { Item const* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_CANT_BE_DISENCHANTED; // prevent disenchanting in trade slot if (item->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_DISENCHANTED; ItemTemplate const* itemProto = item->GetTemplate(); if (!itemProto) return SPELL_FAILED_CANT_BE_DISENCHANTED; ItemDisenchantLootEntry const* itemDisenchantLoot = item->GetDisenchantLoot(m_caster->ToPlayer()); if (!itemDisenchantLoot) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (itemDisenchantLoot->SkillRequired > player->GetSkillValue(SKILL_ENCHANTING)) return SPELL_FAILED_LOW_CASTLEVEL; break; } case SPELL_EFFECT_PROSPECTING: { Item* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_CANT_BE_PROSPECTED; //ensure item is a prospectable ore if (!(item->GetTemplate()->GetFlags() & ITEM_FLAG_IS_PROSPECTABLE)) return SPELL_FAILED_CANT_BE_PROSPECTED; //prevent prospecting in trade slot if (item->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_PROSPECTED; //Check for enough skill in jewelcrafting uint32 item_prospectingskilllevel = item->GetTemplate()->GetRequiredSkillRank(); if (item_prospectingskilllevel > player->GetSkillValue(SKILL_JEWELCRAFTING)) return SPELL_FAILED_LOW_CASTLEVEL; //make sure the player has the required ores in inventory if (item->GetCount() < 5) { if (param1 && param2) { *param1 = item->GetEntry(); *param2 = 5; } return SPELL_FAILED_NEED_MORE_ITEMS; } if (!LootTemplates_Prospecting.HaveLootFor(m_targets.GetItemTargetEntry())) return SPELL_FAILED_CANT_BE_PROSPECTED; break; } case SPELL_EFFECT_MILLING: { Item* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_CANT_BE_MILLED; //ensure item is a millable herb if (!(item->GetTemplate()->GetFlags() & ITEM_FLAG_IS_MILLABLE)) return SPELL_FAILED_CANT_BE_MILLED; //prevent milling in trade slot if (item->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_MILLED; //Check for enough skill in inscription uint32 item_millingskilllevel = item->GetTemplate()->GetRequiredSkillRank(); if (item_millingskilllevel > player->GetSkillValue(SKILL_INSCRIPTION)) return SPELL_FAILED_LOW_CASTLEVEL; //make sure the player has the required herbs in inventory if (item->GetCount() < 5) { if (param1 && param2) { *param1 = item->GetEntry(); *param2 = 5; } return SPELL_FAILED_NEED_MORE_ITEMS; } if (!LootTemplates_Milling.HaveLootFor(m_targets.GetItemTargetEntry())) return SPELL_FAILED_CANT_BE_MILLED; break; } case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: { if (m_attackType != RANGED_ATTACK) break; Item* pItem = player->GetWeaponForAttack(m_attackType); if (!pItem || pItem->IsBroken()) return SPELL_FAILED_EQUIPPED_ITEM; switch (pItem->GetTemplate()->GetSubClass()) { case ITEM_SUBCLASS_WEAPON_THROWN: { uint32 ammo = pItem->GetEntry(); if (!player->HasItemCount(ammo)) return SPELL_FAILED_NO_AMMO; break; } case ITEM_SUBCLASS_WEAPON_GUN: case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: case ITEM_SUBCLASS_WEAPON_WAND: break; default: break; } break; } case SPELL_EFFECT_RECHARGE_ITEM: { uint32 itemId = effect->ItemType; ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId); if (!proto) return SPELL_FAILED_ITEM_AT_MAX_CHARGES; if (Item* item = player->GetItemByEntry(itemId)) for (ItemEffectEntry const* itemEffect : item->GetEffects()) if (itemEffect->LegacySlotIndex <= item->m_itemData->SpellCharges.size() && itemEffect->Charges != 0 && item->GetSpellCharges(itemEffect->LegacySlotIndex) == itemEffect->Charges) return SPELL_FAILED_ITEM_AT_MAX_CHARGES; break; } case SPELL_EFFECT_RESPEC_AZERITE_EMPOWERED_ITEM: { Item const* item = m_targets.GetItemTarget(); if (!item) return SPELL_FAILED_AZERITE_EMPOWERED_ONLY; if (item->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_DONT_REPORT; AzeriteEmpoweredItem const* azeriteEmpoweredItem = item->ToAzeriteEmpoweredItem(); if (!azeriteEmpoweredItem) return SPELL_FAILED_AZERITE_EMPOWERED_ONLY; bool hasSelections = false; for (int32 tier = 0; tier < azeriteEmpoweredItem->GetMaxAzeritePowerTier(); ++tier) { if (azeriteEmpoweredItem->GetSelectedAzeritePower(tier)) { hasSelections = true; break; } } if (!hasSelections) return SPELL_FAILED_AZERITE_EMPOWERED_NO_CHOICES_TO_UNDO; if (!m_caster->ToPlayer()->HasEnoughMoney(azeriteEmpoweredItem->GetRespecCost())) return SPELL_FAILED_DONT_REPORT; break; } default: break; } } // check weapon presence in slots for main/offhand weapons if (!(_triggeredCastFlags & TRIGGERED_IGNORE_EQUIPPED_ITEM_REQUIREMENT) && m_spellInfo->EquippedItemClass >= 0) { auto weaponCheck = [this](WeaponAttackType attackType) -> SpellCastResult { Item const* item = m_caster->ToPlayer()->GetWeaponForAttack(attackType); // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; return SPELL_CAST_OK; }; if (m_spellInfo->HasAttribute(SPELL_ATTR3_MAIN_HAND)) { SpellCastResult mainHandResult = weaponCheck(BASE_ATTACK); if (mainHandResult != SPELL_CAST_OK) return mainHandResult; } if (m_spellInfo->HasAttribute(SPELL_ATTR3_REQ_OFFHAND)) { SpellCastResult offHandResult = weaponCheck(OFF_ATTACK); if (offHandResult != SPELL_CAST_OK) return offHandResult; } } return SPELL_CAST_OK; } void Spell::Delayed() // only called in DealDamage() { if (!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER) return; //if (m_spellState == SPELL_STATE_DELAYED) // return; // spell is active and can't be time-backed if (isDelayableNoMore()) // Spells may only be delayed twice return; // spells not loosing casting time (slam, dynamites, bombs..) //if (!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE)) // return; //check pushback reduce int32 delaytime = 150; // spellcasting delay is normally 500ms, updated Legion 2x150ms ~ int32 delayReduce = 100; // must be initialized to 100 for percent modifiers m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; AddPct(delaytime, -delayReduce); if (m_timer + delaytime > m_casttime) { delaytime = m_casttime - m_timer; m_timer = m_casttime; } else m_timer += delaytime; TC_LOG_DEBUG("spells", "Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime); WorldPackets::Spells::SpellDelayed spellDelayed; spellDelayed.Caster = m_caster->GetGUID(); spellDelayed.ActualDelay = delaytime; m_caster->SendMessageToSet(spellDelayed.Write(), true); } void Spell::DelayedChannel() { if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING) return; if (isDelayableNoMore()) // Spells may only be delayed twice return; //check pushback reduce // should be affected by modifiers, not take the dbc duration. //int32 duration = ((m_channeledDuration > 0) ? m_channeledDuration : m_spellInfo->GetDuration()); // needs some more research, sniff shows anywhere from 130 to 189, it is not a pct of duration // https://gist.github.com/EPS1L0N/fa8977a74918ba4b9c63 int32 delaytime = 150; int32 delayReduce = 100; // must be initialized to 100 for percent modifiers m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; AddPct(delaytime, -delayReduce); if (m_timer <= delaytime) { delaytime = m_timer; m_timer = 0; } else m_timer -= delaytime; TC_LOG_DEBUG("spells", "Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer); for (std::vector<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if ((*ihit).missCondition == SPELL_MISS_NONE) if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime); // partially interrupt persistent area auras if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id)) dynObj->Delay(delaytime); SendChannelUpdate(m_timer); } bool Spell::UpdatePointers() { if (m_originalCasterGUID == m_caster->GetGUID()) m_originalCaster = m_caster; else { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL; } if (!m_castItemGUID.IsEmpty() && m_caster->GetTypeId() == TYPEID_PLAYER) { m_CastItem = m_caster->ToPlayer()->GetItemByGuid(m_castItemGUID); m_castItemLevel = -1; // cast item not found, somehow the item is no longer where we expected if (!m_CastItem) return false; // check if the item is really the same, in case it has been wrapped for example if (m_castItemEntry != m_CastItem->GetEntry()) return false; m_castItemLevel = int32(m_CastItem->GetItemLevel(m_caster->ToPlayer())); } m_targets.Update(m_caster); // further actions done only for dest targets if (!m_targets.HasDst()) return true; // cache last transport WorldObject* transport = NULL; // update effect destinations (in case of moved transport dest target) for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (!effect) continue; SpellDestination& dest = m_destTargets[effect->EffectIndex]; if (!dest._transportGUID) continue; if (!transport || transport->GetGUID() != dest._transportGUID) transport = ObjectAccessor::GetWorldObject(*m_caster, dest._transportGUID); if (transport) { dest._position.Relocate(transport); dest._position.RelocateOffset(dest._transportOffset); } } return true; } SpellPowerCost const* Spell::GetPowerCost(Powers power) const { std::vector<SpellPowerCost> const& costs = GetPowerCost(); auto c = std::find_if(costs.begin(), costs.end(), [power](SpellPowerCost const& cost) { return cost.Power == power; }); if (c != costs.end()) return &(*c); return nullptr; } float Spell::GetSpellPowerCostModifier(Powers power) const { float maxCost = 0.f; for (SpellPowerEntry const* powerEntry : GetSpellInfo()->PowerCosts) if (powerEntry->PowerType == power) maxCost += powerEntry->ManaCost + powerEntry->OptionalCost; if (SpellPowerCost const* powerCost = GetPowerCost(power)) return powerCost->Amount / maxCost; return 0.f; } CurrentSpellTypes Spell::GetCurrentContainer() const { if (m_spellInfo->IsNextMeleeSwingSpell()) return CURRENT_MELEE_SPELL; else if (IsAutoRepeat()) return CURRENT_AUTOREPEAT_SPELL; else if (m_spellInfo->IsChanneled()) return CURRENT_CHANNELED_SPELL; return CURRENT_GENERIC_SPELL; } Difficulty Spell::GetCastDifficulty() const { return m_caster->GetMap()->GetDifficultyID(); } bool Spell::CheckEffectTarget(Unit const* target, SpellEffectInfo const* effect, Position const* losPosition) const { if (!effect->IsEffect()) return false; switch (effect->ApplyAuraName) { case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_MOD_POSSESS_PET: case SPELL_AURA_AOE_CHARM: if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle()) return false; if (target->IsMounted()) return false; if (!target->GetCharmerGUID().IsEmpty()) return false; if (int32 value = CalculateDamage(effect->EffectIndex, target)) if ((int32)target->GetLevelForTarget(m_caster) > value) return false; break; default: break; } // check for ignore LOS on the effect itself if (m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS)) return true; // if spell is triggered, need to check for LOS disable on the aura triggering it and inherit that behaviour if (IsTriggered() && m_triggeredByAuraSpell && (m_triggeredByAuraSpell->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_triggeredByAuraSpell->Id, NULL, SPELL_DISABLE_LOS))) return true; /// @todo shit below shouldn't be here, but it's temporary //Check targets for LOS visibility switch (effect->Effect) { case SPELL_EFFECT_SKIN_PLAYER_CORPSE: { if (!m_targets.GetCorpseTargetGUID()) { if (target->IsWithinLOSInMap(m_caster, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2) && target->HasUnitFlag(UNIT_FLAG_SKINNABLE)) return true; return false; } Corpse* corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.GetCorpseTargetGUID()); if (!corpse) return false; if (target->GetGUID() != corpse->GetOwnerGUID()) return false; if (!corpse->HasDynamicFlag(CORPSE_DYNFLAG_LOOTABLE)) return false; if (!corpse->IsWithinLOSInMap(m_caster, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) return false; break; } default: { if (losPosition) return target->IsWithinLOS(losPosition->GetPositionX(), losPosition->GetPositionY(), losPosition->GetPositionZ(), LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2); else { // Get GO cast coordinates if original caster -> GO WorldObject* caster = NULL; if (m_originalCasterGUID.IsGameObject()) caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID); if (!caster) caster = m_caster; if (target != m_caster && !target->IsWithinLOSInMap(caster, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) return false; } } } return true; } bool Spell::CheckEffectTarget(GameObject const* target, SpellEffectInfo const* effect) const { if (!effect->IsEffect()) return false; switch (effect->Effect) { case SPELL_EFFECT_GAMEOBJECT_DAMAGE: case SPELL_EFFECT_GAMEOBJECT_REPAIR: case SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE: if (target->GetGoType() != GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) return false; break; default: break; } return true; } bool Spell::CheckEffectTarget(Item const* /*target*/, SpellEffectInfo const* effect) const { if (!effect->IsEffect()) return false; return true; } bool Spell::IsTriggered() const { return (_triggeredCastFlags & TRIGGERED_FULL_MASK) != 0; } bool Spell::IsIgnoringCooldowns() const { return (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD) != 0; } bool Spell::IsProcDisabled() const { return (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) != 0; } bool Spell::IsChannelActive() const { return m_caster->GetChannelSpellId() != 0; } bool Spell::IsAutoActionResetSpell() const { /// @todo changed SPELL_INTERRUPT_FLAG_AUTOATTACK -> SPELL_INTERRUPT_FLAG_INTERRUPT to fix compile - is this check correct at all? if (IsTriggered() || !(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT)) return false; if (!m_casttime && m_spellInfo->HasAttribute(SPELL_ATTR6_NOT_RESET_SWING_IF_INSTANT)) return false; return true; } bool Spell::IsNeedSendToClient() const { return m_SpellVisual || m_spellInfo->IsChanneled() || (m_spellInfo->HasAttribute(SPELL_ATTR8_AURA_SEND_AMOUNT)) || m_spellInfo->HasHitDelay() || (!m_triggeredByAuraSpell && !IsTriggered()); } bool Spell::HaveTargetsForEffect(uint8 effect) const { for (std::vector<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; for (std::vector<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; for (std::vector<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; return false; } SpellEvent::SpellEvent(Spell* spell) : BasicEvent() { m_Spell = spell; } SpellEvent::~SpellEvent() { if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->cancel(); if (m_Spell->IsDeletable()) { delete m_Spell; } else { TC_LOG_ERROR("spells", "~SpellEvent: %s %s tried to delete non-deletable spell %u. Was not deleted, causes memory leak.", (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUID().ToString().c_str(), m_Spell->m_spellInfo->Id); ABORT(); } } bool SpellEvent::Execute(uint64 e_time, uint32 p_time) { // update spell if it is not finished if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->update(p_time); // check spell state to process switch (m_Spell->getState()) { case SPELL_STATE_FINISHED: { // spell was finished, check deletable state if (m_Spell->IsDeletable()) { // check, if we do have unfinished triggered spells return true; // spell is deletable, finish event } // event will be re-added automatically at the end of routine) break; } case SPELL_STATE_DELAYED: { // first, check, if we have just started if (m_Spell->GetDelayStart() != 0) { // no, we aren't, do the typical update // check, if we have channeled spell on our hands /* if (m_Spell->m_spellInfo->IsChanneled()) { // evented channeled spell is processed separately, cast once after delay, and not destroyed till finish // check, if we have casting anything else except this channeled spell and autorepeat if (m_Spell->GetCaster()->IsNonMeleeSpellCast(false, true, true)) { // another non-melee non-delayed spell is cast now, abort m_Spell->cancel(); } else { // Set last not triggered spell for apply spellmods ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true); // do the action (pass spell to channeling state) m_Spell->handle_immediate(); // And remove after effect handling ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false); } // event will be re-added automatically at the end of routine) } else */ { // run the spell handler and think about what we can do next uint64 t_offset = e_time - m_Spell->GetDelayStart(); uint64 n_offset = m_Spell->handle_delayed(t_offset); if (n_offset) { // re-add us to the queue m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false); return false; // event not complete } // event complete // finish update event will be re-added automatically at the end of routine) } } else { // delaying had just started, record the moment m_Spell->SetDelayStart(e_time); // handle effects on caster if the spell has travel time but also affects the caster in some way uint64 n_offset = m_Spell->handle_delayed(0); if (m_Spell->m_spellInfo->LaunchDelay) ASSERT(n_offset == uint64(std::floor(m_Spell->m_spellInfo->LaunchDelay * 1000.0f))); else ASSERT(n_offset == m_Spell->GetDelayMoment()); // re-plan the event for the delay moment m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false); return false; // event not complete } break; } default: { // all other states // event will be re-added automatically at the end of routine) break; } } // spell processing not complete, plan event on the next update interval m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false); return false; // event not complete } void SpellEvent::Abort(uint64 /*e_time*/) { // oops, the spell we try to do is aborted if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->cancel(); } bool SpellEvent::IsDeletable() const { return m_Spell->IsDeletable(); } bool Spell::IsValidDeadOrAliveTarget(Unit const* target) const { if (target->IsAlive()) return !m_spellInfo->IsRequiringDeadTarget(); if (m_spellInfo->IsAllowingDeadTarget()) return true; return false; } void Spell::HandleLaunchPhase() { // handle effects with SPELL_EFFECT_HANDLE_LAUNCH mode for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { // don't do anything for empty effect if (!effect || !effect->IsEffect()) continue; HandleEffects(NULL, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_LAUNCH); } float multiplier[MAX_SPELL_EFFECTS]; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) if (effect && (m_applyMultiplierMask & (1 << effect->EffectIndex))) multiplier[effect->EffectIndex] = effect->CalcDamageMultiplier(m_originalCaster, this); PrepareTargetProcessing(); for (auto ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { TargetInfo& target = *ihit; uint32 mask = target.effectMask; if (!mask) continue; DoAllEffectOnLaunchTarget(target, multiplier); } FinishTargetProcessing(); } void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier) { Unit* unit = NULL; // In case spell hit target, do all effect on that target if (targetInfo.missCondition == SPELL_MISS_NONE) unit = m_caster->GetGUID() == targetInfo.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, targetInfo.targetGUID); // In case spell reflect from target, do all effect on caster (if hit) else if (targetInfo.missCondition == SPELL_MISS_REFLECT && targetInfo.reflectResult == SPELL_MISS_NONE) unit = m_caster; if (!unit) return; for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (effect && (targetInfo.effectMask & (1<<effect->EffectIndex))) { m_damage = 0; m_healing = 0; HandleEffects(unit, NULL, NULL, effect->EffectIndex, SPELL_EFFECT_HANDLE_LAUNCH_TARGET); if (m_damage > 0) { if (effect->IsTargetingArea() || effect->IsAreaAuraEffect() || effect->IsEffect(SPELL_EFFECT_PERSISTENT_AREA_AURA)) { m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask)); if (m_caster->GetTypeId() != TYPEID_PLAYER) m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask)); if (m_caster->GetTypeId() == TYPEID_PLAYER) { uint32 targetAmount = m_UniqueTargetInfo.size(); if (targetAmount > 20) m_damage = m_damage * 20/targetAmount; } } } if (m_applyMultiplierMask & (1 << effect->EffectIndex)) { m_damage = int32(m_damage * m_damageMultipliers[effect->EffectIndex]); m_damageMultipliers[effect->EffectIndex] *= multiplier[effect->EffectIndex]; } targetInfo.damage += m_damage; } } targetInfo.crit = m_caster->IsSpellCrit(unit, this, nullptr, m_spellSchoolMask, m_attackType); } SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue) { if (!lockId) // possible case for GO and maybe for items. return SPELL_CAST_OK; // Get LockInfo LockEntry const* lockInfo = sLockStore.LookupEntry(lockId); if (!lockInfo) return SPELL_FAILED_BAD_TARGETS; SpellEffectInfo const* effect = m_spellInfo->GetEffect(effIndex); if (!effect) return SPELL_FAILED_BAD_TARGETS; // no idea about correct error bool reqKey = false; // some locks not have reqs for (int j = 0; j < MAX_LOCK_CASE; ++j) { switch (lockInfo->Type[j]) { // check key item (many fit cases can be) case LOCK_KEY_ITEM: if (lockInfo->Index[j] && m_CastItem && int32(m_CastItem->GetEntry()) == lockInfo->Index[j]) return SPELL_CAST_OK; reqKey = true; break; // check key skill (only single first fit case can be) case LOCK_KEY_SKILL: { // wrong locktype, skip if (effect->MiscValue != lockInfo->Index[j]) continue; reqKey = true; skillId = SkillByLockType(LockType(lockInfo->Index[j])); if (skillId != SKILL_NONE || lockInfo->Index[j] == LOCKTYPE_LOCKPICKING) { reqSkillValue = lockInfo->Skill[j]; // castitem check: rogue using skeleton keys. the skill values should not be added in this case. skillValue = 0; if (!m_CastItem && m_caster->GetTypeId() == TYPEID_PLAYER) skillValue = m_caster->ToPlayer()->GetSkillValue(skillId); else if (lockInfo->Index[j] == LOCKTYPE_LOCKPICKING) skillValue = m_caster->getLevel() * 5; else if (!m_CastItem && m_caster->IsPlayer()) skillValue = m_caster->ToPlayer()->GetSkillValue(skillId); // skill bonus provided by casting spell (mostly item spells) // add the effect base points modifier from the spell cast (cheat lock / skeleton key etc.) if (effect->TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || effect->TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET) skillValue += effect->CalcValue(); if (skillValue < reqSkillValue) return SPELL_FAILED_LOW_CASTLEVEL; } return SPELL_CAST_OK; } } } if (reqKey) return SPELL_FAILED_BAD_TARGETS; return SPELL_CAST_OK; } void Spell::SetSpellValue(SpellValueMod mod, int32 value) { if (mod < SPELLVALUE_BASE_POINT_END) { m_spellValue->EffectBasePoints[mod] = value; m_spellValue->CustomBasePointsMask |= 1 << mod; return; } if (mod >= SPELLVALUE_TRIGGER_SPELL && mod < SPELLVALUE_TRIGGER_SPELL_END) { if (m_spellInfo->GetEffect(mod - SPELLVALUE_TRIGGER_SPELL) != nullptr) m_spellValue->EffectTriggerSpell[mod - SPELLVALUE_TRIGGER_SPELL] = (uint32)value; return; } switch (mod) { case SPELLVALUE_RADIUS_MOD: m_spellValue->RadiusMod = (float)value / 10000; break; case SPELLVALUE_MAX_TARGETS: m_spellValue->MaxAffectedTargets = (uint32)value; break; case SPELLVALUE_AURA_STACK: m_spellValue->AuraStackAmount = uint8(value); break; case SPELLVALUE_DURATION: m_spellValue->Duration = (uint32)value; break; default: break; } } void Spell::PrepareTargetProcessing() { } void Spell::FinishTargetProcessing() { SendSpellExecuteLog(); } void Spell::LoadScripts() { sScriptMgr->CreateSpellScripts(m_spellInfo->Id, m_loadedScripts, this); for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr) { TC_LOG_DEBUG("spells", "Spell::LoadScripts: Script `%s` for spell `%u` is loaded now", (*itr)->_GetScriptName()->c_str(), m_spellInfo->Id); (*itr)->Register(); } } void Spell::CallScriptBeforeCastHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_CAST); auto hookItrEnd = (*scritr)->BeforeCast.end(), hookItr = (*scritr)->BeforeCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnPrepareHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_PREPARE); auto hookItrEnd = (*scritr)->OnPrepare.end(), hookItr = (*scritr)->OnPrepare.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnCastHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_CAST); auto hookItrEnd = (*scritr)->OnCast.end(), hookItr = (*scritr)->OnCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptAfterCastHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_CAST); auto hookItrEnd = (*scritr)->AfterCast.end(), hookItr = (*scritr)->AfterCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnTakePowerHandlers(SpellPowerCost& powerCost) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_TAKE_POWER); auto hookItrEnd = (*scritr)->OnTakePower.end(), hookItr = (*scritr)->OnTakePower.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr, powerCost); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnCalcCastTimeHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CALC_CAST_TIME); auto hookItrEnd = (*scritr)->OnCalcCastTime.end(), hookItr = (*scritr)->OnCalcCastTime.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr, m_casttime); (*scritr)->_FinishScriptCall(); } } SpellCastResult Spell::CallScriptCheckCastHandlers() { SpellCastResult retVal = SPELL_CAST_OK; for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CHECK_CAST); auto hookItrEnd = (*scritr)->OnCheckCast.end(), hookItr = (*scritr)->OnCheckCast.begin(); for (; hookItr != hookItrEnd; ++hookItr) { SpellCastResult tempResult = (*hookItr).Call(*scritr); if (retVal == SPELL_CAST_OK) retVal = tempResult; } (*scritr)->_FinishScriptCall(); } return retVal; } void Spell::PrepareScriptHitHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) (*scritr)->_InitHit(); } bool Spell::CallScriptEffectHandlers(SpellEffIndex effIndex, SpellEffectHandleMode mode) { // execute script effect handler hooks and check if effects was prevented bool preventDefault = false; for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { HookList<SpellScript::EffectHandler>::iterator effItr, effEndItr; SpellScriptHookType hookType; switch (mode) { case SPELL_EFFECT_HANDLE_LAUNCH: effItr = (*scritr)->OnEffectLaunch.begin(); effEndItr = (*scritr)->OnEffectLaunch.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH; break; case SPELL_EFFECT_HANDLE_LAUNCH_TARGET: effItr = (*scritr)->OnEffectLaunchTarget.begin(); effEndItr = (*scritr)->OnEffectLaunchTarget.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_LAUNCH_TARGET; break; case SPELL_EFFECT_HANDLE_HIT: effItr = (*scritr)->OnEffectHit.begin(); effEndItr = (*scritr)->OnEffectHit.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT; break; case SPELL_EFFECT_HANDLE_HIT_TARGET: effItr = (*scritr)->OnEffectHitTarget.begin(); effEndItr = (*scritr)->OnEffectHitTarget.end(); hookType = SPELL_SCRIPT_HOOK_EFFECT_HIT_TARGET; break; default: ABORT(); return false; } (*scritr)->_PrepareScriptCall(hookType); for (; effItr != effEndItr; ++effItr) // effect execution can be prevented if (!(*scritr)->_IsEffectPrevented(effIndex) && (*effItr).IsEffectAffected(m_spellInfo, effIndex)) (*effItr).Call(*scritr, effIndex); if (!preventDefault) preventDefault = (*scritr)->_IsDefaultEffectPrevented(effIndex); (*scritr)->_FinishScriptCall(); } return preventDefault; } void Spell::CallScriptSuccessfulDispel(SpellEffIndex effIndex) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_EFFECT_SUCCESSFUL_DISPEL); auto hookItrEnd = (*scritr)->OnEffectSuccessfulDispel.end(), hookItr = (*scritr)->OnEffectSuccessfulDispel.begin(); for (; hookItr != hookItrEnd; ++hookItr) hookItr->Call(*scritr, effIndex); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptBeforeHitHandlers(SpellMissInfo missInfo) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_HIT); auto hookItrEnd = (*scritr)->BeforeHit.end(), hookItr = (*scritr)->BeforeHit.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr, missInfo); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnHitHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_HIT); auto hookItrEnd = (*scritr)->OnHit.end(), hookItr = (*scritr)->OnHit.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptAfterHitHandlers() { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_HIT); auto hookItrEnd = (*scritr)->AfterHit.end(), hookItr = (*scritr)->AfterHit.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptObjectAreaTargetSelectHandlers(std::list<WorldObject*>& targets, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_AREA_TARGET_SELECT); auto hookItrEnd = (*scritr)->OnObjectAreaTargetSelect.end(), hookItr = (*scritr)->OnObjectAreaTargetSelect.begin(); for (; hookItr != hookItrEnd; ++hookItr) if (hookItr->IsEffectAffected(m_spellInfo, effIndex) && targetType.GetTarget() == hookItr->GetTarget()) hookItr->Call(*scritr, targets); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptObjectTargetSelectHandlers(WorldObject*& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_OBJECT_TARGET_SELECT); auto hookItrEnd = (*scritr)->OnObjectTargetSelect.end(), hookItr = (*scritr)->OnObjectTargetSelect.begin(); for (; hookItr != hookItrEnd; ++hookItr) if (hookItr->IsEffectAffected(m_spellInfo, effIndex) && targetType.GetTarget() == hookItr->GetTarget()) hookItr->Call(*scritr, target); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnSummonHandlers(Creature* creature) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_ON_SUMMON); auto hookItrEnd = (*scritr)->OnEffectSummon.end(), hookItr = (*scritr)->OnEffectSummon.begin(); for (; hookItr != hookItrEnd; ++hookItr) hookItr->Call(*scritr, creature); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptDestinationTargetSelectHandlers(SpellDestination& target, SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_DESTINATION_TARGET_SELECT); auto hookItrEnd = (*scritr)->OnDestinationTargetSelect.end(), hookItr = (*scritr)->OnDestinationTargetSelect.begin(); for (; hookItr != hookItrEnd; ++hookItr) if (hookItr->IsEffectAffected(m_spellInfo, effIndex) && targetType.GetTarget() == hookItr->GetTarget()) hookItr->Call(*scritr, target); (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptCalcCritChanceHandlers(Unit* victim, float& chance) { for (auto scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end(); ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_CALC_CRIT_CHANCE); auto hookItrEnd = (*scritr)->OnCalcCritChance.end(), hookItr = (*scritr)->OnCalcCritChance.begin(); for (; hookItr != hookItrEnd; ++hookItr) (*hookItr).Call(*scritr, victim, chance); (*scritr)->_FinishScriptCall(); } } bool Spell::CheckScriptEffectImplicitTargets(uint32 effIndex, uint32 effIndexToCheck) { // Skip if there are not any script if (m_loadedScripts.empty()) return true; for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr) { auto targetSelectHookEnd = (*itr)->OnObjectTargetSelect.end(), targetSelectHookItr = (*itr)->OnObjectTargetSelect.begin(); for (; targetSelectHookItr != targetSelectHookEnd; ++targetSelectHookItr) if (((*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) || (!(*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*targetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck))) return false; auto areaTargetSelectHookEnd = (*itr)->OnObjectAreaTargetSelect.end(), areaTargetSelectHookItr = (*itr)->OnObjectAreaTargetSelect.begin(); for (; areaTargetSelectHookItr != areaTargetSelectHookEnd; ++areaTargetSelectHookItr) if (((*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && !(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck)) || (!(*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndex) && (*areaTargetSelectHookItr).IsEffectAffected(m_spellInfo, effIndexToCheck))) return false; } return true; } bool Spell::CanExecuteTriggersOnHit(uint32 effMask, SpellInfo const* triggeredByAura /*= nullptr*/) const { bool only_on_caster = (triggeredByAura && (triggeredByAura->HasAttribute(SPELL_ATTR4_PROC_ONLY_ON_CASTER))); // If triggeredByAura has SPELL_ATTR4_PROC_ONLY_ON_CASTER then it can only proc on a cast spell with TARGET_UNIT_CASTER for (SpellEffectInfo const* effect : m_spellInfo->GetEffects()) { if (effect && ((effMask & (1 << effect->EffectIndex)) && (!only_on_caster || (effect->TargetA.GetTarget() == TARGET_UNIT_CASTER)))) return true; } return false; } void Spell::PrepareTriggersExecutedOnHit() { // handle SPELL_AURA_ADD_TARGET_TRIGGER auras: // save auras which were present on spell caster on cast, to prevent triggered auras from affecting caster // and to correctly calculate proc chance when combopoints are present Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER); for (AuraEffect const* aurEff : targetTriggers) { if (!aurEff->IsAffectingSpell(m_spellInfo)) continue; if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(aurEff->GetSpellEffectInfo()->TriggerSpell, GetCastDifficulty())) { // calculate the chance using spell base amount, because aura amount is not updated on combo-points change // this possibly needs fixing int32 auraBaseAmount = aurEff->GetBaseAmount(); // proc chance is stored in effect amount int32 chance = m_caster->CalculateSpellDamage(nullptr, aurEff->GetSpellInfo(), aurEff->GetEffIndex(), &auraBaseAmount); chance *= aurEff->GetBase()->GetStackAmount(); // build trigger and add to the list m_hitTriggerSpells.emplace_back(spellInfo, aurEff->GetSpellInfo(), chance); } } } // Global cooldowns management enum GCDLimits { MIN_GCD = 750, MAX_GCD = 1500 }; bool Spell::HasGlobalCooldown() const { // Only players or controlled units have global cooldown if (m_caster->GetTypeId() != TYPEID_PLAYER && !m_caster->GetCharmInfo()) return false; return m_caster->GetSpellHistory()->HasGlobalCooldown(m_spellInfo); } void Spell::TriggerGlobalCooldown() { int32 gcd = m_spellInfo->StartRecoveryTime; if (!gcd || !m_spellInfo->StartRecoveryCategory) return; // Only players or controlled units have global cooldown if (m_caster->GetTypeId() != TYPEID_PLAYER && !m_caster->GetCharmInfo()) return; if (m_caster->GetTypeId() == TYPEID_PLAYER) if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_COOLDOWN)) return; // Global cooldown can't leave range 1..1.5 secs // There are some spells (mostly not cast directly by player) that have < 1 sec and > 1.5 sec global cooldowns // but as tests show are not affected by any spell mods. if (m_spellInfo->StartRecoveryTime >= MIN_GCD && m_spellInfo->StartRecoveryTime <= MAX_GCD) { // gcd modifier auras are applied only to own spells and only players have such mods if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this); bool isMeleeOrRangedSpell = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED || m_spellInfo->HasAttribute(SPELL_ATTR0_REQ_AMMO) || m_spellInfo->HasAttribute(SPELL_ATTR0_ABILITY); // Apply haste rating if (gcd > MIN_GCD && ((m_spellInfo->StartRecoveryCategory == 133 && !isMeleeOrRangedSpell) || m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_MOD_GLOBAL_COOLDOWN_BY_HASTE, m_spellInfo))) { gcd = int32(float(gcd) * m_caster->m_unitData->ModSpellHaste); RoundToInterval<int32>(gcd, MIN_GCD, MAX_GCD); } if (gcd > MIN_GCD && m_caster->HasAuraTypeWithAffectMask(SPELL_AURA_MOD_GLOBAL_COOLDOWN_BY_HASTE_REGEN, m_spellInfo)) { gcd = int32(float(gcd) * m_caster->m_unitData->ModHasteRegen); RoundToInterval<int32>(gcd, MIN_GCD, MAX_GCD); } } m_caster->GetSpellHistory()->AddGlobalCooldown(m_spellInfo, gcd); } void Spell::CancelGlobalCooldown() { if (!m_spellInfo->StartRecoveryTime) return; // Cancel global cooldown when interrupting current cast if (m_caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) != this) return; // Only players or controlled units have global cooldown if (m_caster->GetTypeId() != TYPEID_PLAYER && !m_caster->GetCharmInfo()) return; m_caster->GetSpellHistory()->CancelGlobalCooldown(m_spellInfo); } namespace Trinity { WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList) : _caster(caster), _referer(referer), _spellInfo(spellInfo), _targetSelectionType(selectionType), _condList(condList) { if (condList) _condSrcInfo = new ConditionSourceInfo(nullptr, caster); else _condSrcInfo = nullptr; } WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck() { delete _condSrcInfo; } bool WorldObjectSpellTargetCheck::operator()(WorldObject* target) { if (_spellInfo->CheckTarget(_caster, target, true) != SPELL_CAST_OK) return false; Unit* unitTarget = target->ToUnit(); if (Corpse* corpseTarget = target->ToCorpse()) { // use ofter for party/assistance checks if (Player* owner = ObjectAccessor::FindPlayer(corpseTarget->GetOwnerGUID())) unitTarget = owner; else return false; } if (unitTarget) { switch (_targetSelectionType) { case TARGET_CHECK_ENEMY: if (unitTarget->IsTotem()) return false; if (!_caster->_IsValidAttackTarget(unitTarget, _spellInfo)) return false; break; case TARGET_CHECK_ALLY: if (unitTarget->IsTotem()) return false; if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) return false; break; case TARGET_CHECK_PARTY: if (unitTarget->IsTotem()) return false; if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) return false; if (!_referer->IsInPartyWith(unitTarget)) return false; break; case TARGET_CHECK_RAID_CLASS: if (_referer->getClass() != unitTarget->getClass()) return false; /* fallthrough */ case TARGET_CHECK_RAID_DEATH: case TARGET_CHECK_RAID: if (_targetSelectionType == TARGET_CHECK_RAID_DEATH) if (!_referer->isDead()) return false; if (unitTarget->IsTotem()) return false; if (!_caster->_IsValidAssistTarget(unitTarget, _spellInfo)) return false; if (!_referer->IsInRaidWith(unitTarget)) return false; break; case TARGET_CHECK_DEATH: if (!unitTarget->isDead()) return false; break; case TARGET_CHECK_SUMMONED: if (!unitTarget->IsSummon()) return false; if (unitTarget->ToTempSummon()->GetSummonerGUID() != _caster->GetGUID()) return false; break; case TARGET_CHECK_THREAT: if (_referer->getThreatManager().getThreat(unitTarget, true) <= 0.0f) return false; break; case TARGET_CHECK_TAP: if (_referer->GetTypeId() != TYPEID_UNIT || unitTarget->GetTypeId() != TYPEID_PLAYER) return false; if (!_referer->ToCreature()->IsTappedBy(unitTarget->ToPlayer())) return false; break; default: break; } } if (!_condSrcInfo) return true; _condSrcInfo->mConditionTargets[0] = target; return sConditionMgr->IsObjectMeetToConditions(*_condSrcInfo, *_condList); } WorldObjectSpellNearbyTargetCheck::WorldObjectSpellNearbyTargetCheck(float range, Unit* caster, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList) : WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(caster) { } bool WorldObjectSpellNearbyTargetCheck::operator()(WorldObject* target) { float dist = target->GetDistance(*_position); if (dist < _range && WorldObjectSpellTargetCheck::operator ()(target)) { _range = dist; return true; } return false; } WorldObjectSpellAreaTargetCheck::WorldObjectSpellAreaTargetCheck(float range, Position const* position, Unit* caster, Unit* referer, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList) : WorldObjectSpellTargetCheck(caster, referer, spellInfo, selectionType, condList), _range(range), _position(position) { } bool WorldObjectSpellAreaTargetCheck::operator()(WorldObject* target) { if (target->ToGameObject()) { // isInRange including the dimension of the GO bool isInRange = target->ToGameObject()->IsInRange(_position->GetPositionX(), _position->GetPositionY(), _position->GetPositionZ(), _range); if (!isInRange) return false; } else { bool isInsideCylinder = target->IsWithinDist2d(_position, _range) && std::abs(target->GetPositionZ() - _position->GetPositionZ()) <= _range; if (!isInsideCylinder) return false; } return WorldObjectSpellTargetCheck::operator ()(target); } WorldObjectSpellConeTargetCheck::WorldObjectSpellConeTargetCheck(float coneAngle, float lineWidth, float range, Unit* caster, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList) : WorldObjectSpellAreaTargetCheck(range, caster, caster, caster, spellInfo, selectionType, condList), _coneAngle(coneAngle), _lineWidth(lineWidth) { } bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target) { if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_BACK)) { if (!_caster->isInBack(target, _coneAngle)) return false; } else if (_spellInfo->HasAttribute(SPELL_ATTR0_CU_CONE_LINE)) { if (!_caster->HasInLine(target, target->GetCombatReach(), _lineWidth)) return false; } else { if (!_caster->IsWithinBoundaryRadius(target->ToUnit())) // ConeAngle > 0 -> select targets in front // ConeAngle < 0 -> select targets in back if (_caster->HasInArc(_coneAngle, target) != G3D::fuzzyGe(_coneAngle, 0.f)) return false; } return WorldObjectSpellAreaTargetCheck::operator ()(target); } WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo, SpellTargetCheckTypes selectionType, ConditionContainer* condList) : WorldObjectSpellTargetCheck(caster, caster, spellInfo, selectionType, condList), _range(range), _position(position) { } bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target) { // return all targets on missile trajectory (0 - size of a missile) if (!_caster->HasInLine(target, target->GetCombatReach(), TRAJECTORY_MISSILE_SIZE)) return false; if (target->GetExactDist2d(_position) > _range) return false; return WorldObjectSpellTargetCheck::operator ()(target); } } //namespace Trinity<|fim▁end|>
case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS: { if (!m_targets.GetUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS;
<|file_name|>plugin.js<|end_file_name|><|fim▁begin|>/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ import _ from 'underscore'; import Backbone from 'backbone'; export default Backbone.Model.extend({ idAttribute: 'key', defaults: { _hidden: false, _system: false }, _matchAttribute: function (attr, query) { var value = this.get(attr) || ''; return value.search(new RegExp(query, 'i')) !== -1; }, match: function (query) { return this._matchAttribute('name', query) || this._matchAttribute('category', query) || this._matchAttribute('description', query); }, _action: function (options) { var that = this; var opts = _.extend({}, options, { type: 'POST', data: { key: this.id }, beforeSend: function () { // disable global ajax notifications }, success: function () { options.success(that); }, error: function (jqXHR) { that.set({ _status: 'failed', _errors: jqXHR.responseJSON.errors }); } }); var xhr = Backbone.ajax(opts); this.trigger('request', this, xhr); return xhr; }, install: function () { return this._action({ url: baseUrl + '/api/plugins/install', success: function (model) { model.set({ _status: 'installing' }); } }); }, update: function () { return this._action({ url: baseUrl + '/api/plugins/update',<|fim▁hole|> }); }, uninstall: function () { return this._action({ url: baseUrl + '/api/plugins/uninstall', success: function (model) { model.set({ _status: 'uninstalling' }); } }); } });<|fim▁end|>
success: function (model) { model.set({ _status: 'installing' }); }
<|file_name|>d2d1_3.rs<|end_file_name|><|fim▁begin|>// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. //! Mappings for the contents of d2d1_3.h use ctypes::c_void; use shared::basetsd::{UINT16, UINT32, UINT64}; use shared::dxgi::{IDXGIDevice, IDXGISurface}; use shared::dxgitype::DXGI_COLOR_SPACE_TYPE; use shared::minwindef::{BOOL, BYTE, DWORD, FLOAT}; use shared::ntdef::WCHAR; use shared::winerror::HRESULT; use um::d2d1::{ D2D1_BITMAP_INTERPOLATION_MODE, D2D1_COLOR_F, D2D1_DRAW_TEXT_OPTIONS, D2D1_GAMMA_1_0, D2D1_GAMMA_2_2, D2D1_MATRIX_3X2_F, D2D1_POINT_2F, D2D1_RECT_F, D2D1_RECT_U, D2D1_SIZE_F, ID2D1Bitmap, ID2D1Brush, ID2D1Image, ID2D1ImageVtbl, ID2D1Resource, ID2D1ResourceVtbl, ID2D1SimplifiedGeometrySink, }; use um::d2d1_1::{ D2D1_BUFFER_PRECISION, D2D1_DEVICE_CONTEXT_OPTIONS, D2D1_INTERPOLATION_MODE, D2D1_PRIMITIVE_BLEND, ID2D1ColorContext, ID2D1ColorContextVtbl, ID2D1CommandList, ID2D1GdiMetafile, ID2D1GdiMetafileSink, ID2D1GdiMetafileSinkVtbl, ID2D1GdiMetafileVtbl, }; use um::d2d1_2::{ ID2D1CommandSink1, ID2D1CommandSink1Vtbl, ID2D1Device1, ID2D1Device1Vtbl, ID2D1DeviceContext1, ID2D1DeviceContext1Vtbl, ID2D1Factory2, ID2D1Factory2Vtbl, }; use um::d2d1effects::D2D1_BLEND_MODE; use um::d2d1svg::ID2D1SvgDocument; use um::dcommon::{D2D1_ALPHA_MODE, DWRITE_GLYPH_IMAGE_FORMATS, DWRITE_MEASURING_MODE}; use um::dwrite::{DWRITE_GLYPH_RUN, IDWriteFontFace, IDWriteTextFormat, IDWriteTextLayout}; use um::objidlbase::IStream; use um::wincodec::IWICBitmapSource; ENUM!{enum D2D1_INK_NIB_SHAPE { D2D1_INK_NIB_SHAPE_ROUND = 0, D2D1_INK_NIB_SHAPE_SQUARE = 1, }} ENUM!{enum D2D1_ORIENTATION { D2D1_ORIENTATION_DEFAULT = 1, D2D1_ORIENTATION_FLIP_HORIZONTAL = 2, D2D1_ORIENTATION_ROTATE_CLOCKWISE180 = 3, D2D1_ORIENTATION_ROTATE_CLOCKWISE180_FLIP_HORIZONTAL = 4, D2D1_ORIENTATION_ROTATE_CLOCKWISE90_FLIP_HORIZONTAL = 5, D2D1_ORIENTATION_ROTATE_CLOCKWISE270 = 6, D2D1_ORIENTATION_ROTATE_CLOCKWISE270_FLIP_HORIZONTAL = 7, D2D1_ORIENTATION_ROTATE_CLOCKWISE90 = 8, }} ENUM!{enum D2D1_IMAGE_SOURCE_LOADING_OPTIONS { D2D1_IMAGE_SOURCE_LOADING_OPTIONS_NONE = 0, D2D1_IMAGE_SOURCE_LOADING_OPTIONS_RELEASE_SOURCE = 1, D2D1_IMAGE_SOURCE_LOADING_OPTIONS_CACHE_ON_DEMAND = 2, }} ENUM!{enum D2D1_IMAGE_SOURCE_FROM_DXGI_OPTIONS { D2D1_IMAGE_SOURCE_FROM_DXGI_OPTIONS_NONE = 0, D2D1_IMAGE_SOURCE_FROM_DXGI_OPTIONS_LOW_QUALITY_PRIMARY_CONVERSION = 1, }} ENUM!{enum D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS { D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_NONE = 0, D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_DISABLE_DPI_SCALE = 1, }} STRUCT!{struct D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES { orientation: D2D1_ORIENTATION, scaleX: FLOAT, scaleY: FLOAT, interpolationMode: D2D1_INTERPOLATION_MODE, options: D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS, }} STRUCT!{struct D2D1_INK_POINT { x: FLOAT, y: FLOAT, radius: FLOAT, }} STRUCT!{struct D2D1_INK_BEZIER_SEGMENT { point1: D2D1_INK_POINT, point2: D2D1_INK_POINT, point3: D2D1_INK_POINT, }} STRUCT!{struct D2D1_INK_STYLE_PROPERTIES { nibShape: D2D1_INK_NIB_SHAPE, nibTransform: D2D1_MATRIX_3X2_F, }} ENUM!{enum D2D1_PATCH_EDGE_MODE { D2D1_PATCH_EDGE_MODE_ALIASED = 0, D2D1_PATCH_EDGE_MODE_ANTIALIASED = 1, D2D1_PATCH_EDGE_MODE_ALIASED_INFLATED = 2, }} STRUCT!{struct D2D1_GRADIENT_MESH_PATCH { point00: D2D1_POINT_2F, point01: D2D1_POINT_2F, point02: D2D1_POINT_2F, point03: D2D1_POINT_2F, point10: D2D1_POINT_2F, point11: D2D1_POINT_2F, point12: D2D1_POINT_2F, point13: D2D1_POINT_2F, point20: D2D1_POINT_2F, point21: D2D1_POINT_2F, point22: D2D1_POINT_2F, point23: D2D1_POINT_2F, point30: D2D1_POINT_2F, point31: D2D1_POINT_2F, point32: D2D1_POINT_2F, point33: D2D1_POINT_2F, color00: D2D1_COLOR_F, color03: D2D1_COLOR_F, color30: D2D1_COLOR_F, color33: D2D1_COLOR_F, topEdgeMode: D2D1_PATCH_EDGE_MODE, leftEdgeMode: D2D1_PATCH_EDGE_MODE, bottomEdgeMode: D2D1_PATCH_EDGE_MODE, rightEdgeMode: D2D1_PATCH_EDGE_MODE, }} ENUM!{enum D2D1_SPRITE_OPTIONS { D2D1_SPRITE_OPTIONS_NONE = 0, D2D1_SPRITE_OPTIONS_CLAMP_TO_SOURCE_RECTANGLE = 1, }} ENUM!{enum D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION { D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DEFAULT = 0, D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION_DISABLE = 1, }} ENUM!{enum D2D1_GAMMA1 { D2D1_GAMMA1_G22 = D2D1_GAMMA_2_2, D2D1_GAMMA1_G10 = D2D1_GAMMA_1_0, D2D1_GAMMA1_G2084 = 2, }} STRUCT!{struct D2D1_SIMPLE_COLOR_PROFILE { redPrimary: D2D1_POINT_2F, greenPrimary: D2D1_POINT_2F, bluePrimary: D2D1_POINT_2F, whitePointXZ: D2D1_POINT_2F, gamma: D2D1_GAMMA1, }} ENUM!{enum D2D1_COLOR_CONTEXT_TYPE { D2D1_COLOR_CONTEXT_TYPE_ICC = 0, D2D1_COLOR_CONTEXT_TYPE_SIMPLE = 1, D2D1_COLOR_CONTEXT_TYPE_DXGI = 2, }} DEFINE_GUID!{IID_ID2D1InkStyle, 0xbae8b344, 0x23fc, 0x4071, 0x8c, 0xb5, 0xd0, 0x5d, 0x6f, 0x07, 0x38, 0x48} DEFINE_GUID!{IID_ID2D1Ink, 0xb499923b, 0x7029, 0x478f, 0xa8, 0xb3, 0x43, 0x2c, 0x7c, 0x5f, 0x53, 0x12} DEFINE_GUID!{IID_ID2D1GradientMesh, 0xf292e401, 0xc050, 0x4cde, 0x83, 0xd7, 0x04, 0x96, 0x2d, 0x3b, 0x23, 0xc2} DEFINE_GUID!{IID_ID2D1ImageSource, 0xc9b664e5, 0x74a1, 0x4378, 0x9a, 0xc2, 0xee, 0xfc, 0x37, 0xa3, 0xf4, 0xd8} DEFINE_GUID!{IID_ID2D1ImageSourceFromWic, 0x77395441, 0x1c8f, 0x4555, 0x86, 0x83, 0xf5, 0x0d, 0xab, 0x0f, 0xe7, 0x92} DEFINE_GUID!{IID_ID2D1TransformedImageSource, 0x7f1f79e5, 0x2796, 0x416c, 0x8f, 0x55, 0x70, 0x0f, 0x91, 0x14, 0x45, 0xe5} DEFINE_GUID!{IID_ID2D1LookupTable3D, 0x53dd9855, 0xa3b0, 0x4d5b, 0x82, 0xe1, 0x26, 0xe2, 0x5c, 0x5e, 0x57, 0x97} DEFINE_GUID!{IID_ID2D1DeviceContext2, 0x394ea6a3, 0x0c34, 0x4321, 0x95, 0x0b, 0x6c, 0xa2, 0x0f, 0x0b, 0xe6, 0xc7} DEFINE_GUID!{IID_ID2D1Device2, 0xa44472e1, 0x8dfb, 0x4e60, 0x84, 0x92, 0x6e, 0x28, 0x61, 0xc9, 0xca, 0x8b} DEFINE_GUID!{IID_ID2D1Factory3, 0x0869759f, 0x4f00, 0x413f, 0xb0, 0x3e, 0x2b, 0xda, 0x45, 0x40, 0x4d, 0x0f} DEFINE_GUID!{IID_ID2D1CommandSink2, 0x3bab440e, 0x417e, 0x47df, 0xa2, 0xe2, 0xbc, 0x0b, 0xe6, 0xa0, 0x09, 0x16} DEFINE_GUID!{IID_ID2D1GdiMetafile1, 0x2e69f9e8, 0xdd3f, 0x4bf9, 0x95, 0xba, 0xc0, 0x4f, 0x49, 0xd7, 0x88, 0xdf} DEFINE_GUID!{IID_ID2D1GdiMetafileSink1, 0xfd0ecb6b, 0x91e6, 0x411e, 0x86, 0x55, 0x39, 0x5e, 0x76, 0x0f, 0x91, 0xb4} DEFINE_GUID!{IID_ID2D1SpriteBatch, 0x4dc583bf, 0x3a10, 0x438a, 0x87, 0x22, 0xe9, 0x76, 0x52, 0x24, 0xf1, 0xf1} DEFINE_GUID!{IID_ID2D1DeviceContext3, 0x235a7496, 0x8351, 0x414c, 0xbc, 0xd4, 0x66, 0x72, 0xab, 0x2d, 0x8e, 0x00} DEFINE_GUID!{IID_ID2D1Device3, 0x852f2087, 0x802c, 0x4037, 0xab, 0x60, 0xff, 0x2e, 0x7e, 0xe6, 0xfc, 0x01} DEFINE_GUID!{IID_ID2D1Factory4, 0xbd4ec2d2, 0x0662, 0x4bee, 0xba, 0x8e, 0x6f, 0x29, 0xf0, 0x32, 0xe0, 0x96} DEFINE_GUID!{IID_ID2D1CommandSink3, 0x18079135, 0x4cf3, 0x4868, 0xbc, 0x8e, 0x06, 0x06, 0x7e, 0x6d, 0x24, 0x2d} DEFINE_GUID!{IID_ID2D1SvgGlyphStyle, 0xaf671749, 0xd241, 0x4db8, 0x8e, 0x41, 0xdc, 0xc2, 0xe5, 0xc1, 0xa4, 0x38} DEFINE_GUID!{IID_ID2D1DeviceContext4, 0x8c427831, 0x3d90, 0x4476, 0xb6, 0x47, 0xc4, 0xfa, 0xe3, 0x49, 0xe4, 0xdb} DEFINE_GUID!{IID_ID2D1Device4, 0xd7bdb159, 0x5683, 0x4a46, 0xbc, 0x9c, 0x72, 0xdc, 0x72, 0x0b, 0x85, 0x8b} DEFINE_GUID!{IID_ID2D1Factory5, 0xc4349994, 0x838e, 0x4b0f, 0x8c, 0xab, 0x44, 0x99, 0x7d, 0x9e, 0xea, 0xcc} DEFINE_GUID!{IID_ID2D1CommandSink4, 0xc78a6519, 0x40d6, 0x4218, 0xb2, 0xde, 0xbe, 0xee, 0xb7, 0x44, 0xbb, 0x3e} DEFINE_GUID!{IID_ID2D1ColorContext1, 0x1ab42875, 0xc57f, 0x4be9, 0xbd, 0x85, 0x9c, 0xd7, 0x8d, 0x6f, 0x55, 0xee} DEFINE_GUID!{IID_ID2D1DeviceContext5, 0x7836d248, 0x68cc, 0x4df6, 0xb9, 0xe8, 0xde, 0x99, 0x1b, 0xf6, 0x2e, 0xb7} DEFINE_GUID!{IID_ID2D1Device5, 0xd55ba0a4, 0x6405, 0x4694, 0xae, 0xf5, 0x08, 0xee, 0x1a, 0x43, 0x58, 0xb4} DEFINE_GUID!{IID_ID2D1Factory6, 0xf9976f46, 0xf642, 0x44c1, 0x97, 0xca, 0xda, 0x32, 0xea, 0x2a, 0x26, 0x35} DEFINE_GUID!{IID_ID2D1CommandSink5, 0x7047dd26, 0xb1e7, 0x44a7, 0x95, 0x9a, 0x83, 0x49, 0xe2, 0x14, 0x4f, 0xa8} DEFINE_GUID!{IID_ID2D1DeviceContext6, 0x985f7e37, 0x4ed0, 0x4a19, 0x98, 0xa3, 0x15, 0xb0, 0xed, 0xfd, 0xe3, 0x06} DEFINE_GUID!{IID_ID2D1Device6, 0x7bfef914, 0x2d75, 0x4bad, 0xbe, 0x87, 0xe1, 0x8d, 0xdb, 0x07, 0x7b, 0x6d} DEFINE_GUID!{IID_ID2D1Factory7, 0xbdc2bdd3, 0xb96c, 0x4de6, 0xbd, 0xf7, 0x99, 0xd4, 0x74, 0x54, 0x54, 0xde} RIDL!{#[uuid(0xbae8b344, 0x23fc, 0x4071, 0x8c, 0xb5, 0xd0, 0x5d, 0x6f, 0x07, 0x38, 0x48)] interface ID2D1InkStyle(ID2D1InkStyleVtbl): ID2D1Resource(ID2D1ResourceVtbl) { fn SetNibTransform( transform: *const D2D1_MATRIX_3X2_F, ) -> (), fn GetNibTransform( transform: *mut D2D1_MATRIX_3X2_F, ) -> (), fn SetNibShape( nibShape: D2D1_INK_NIB_SHAPE, ) -> (), fn GetNibShape() -> D2D1_INK_NIB_SHAPE, }} RIDL!{#[uuid(0xb499923b, 0x7029, 0x478f, 0xa8, 0xb3, 0x43, 0x2c, 0x7c, 0x5f, 0x53, 0x12)] interface ID2D1Ink(ID2D1InkVtbl): ID2D1Resource(ID2D1ResourceVtbl) { fn SetStartPoint( startPoint: *const D2D1_INK_POINT, ) -> (), fn GetStartPoint() -> D2D1_INK_POINT, fn AddSegments( segments: *const D2D1_INK_BEZIER_SEGMENT, segmentsCount: UINT32, ) -> HRESULT, fn RemoveSegmentsAtEnd( segmentsCount: UINT32, ) -> HRESULT, fn SetSegments( startSegment: UINT32, segments: *const D2D1_INK_BEZIER_SEGMENT, segmentsCount: UINT32, ) -> HRESULT, fn SetSegmentAtEnd( segment: *const D2D1_INK_BEZIER_SEGMENT, ) -> HRESULT, fn GetSegmentCount() -> UINT32, fn GetSegments( startSegment: UINT32, segments: *mut D2D1_INK_BEZIER_SEGMENT, segmentsCount: UINT32, ) -> HRESULT, fn StreamAsGeometry( inkStyle: *mut ID2D1InkStyle, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: FLOAT, geometrySink: *mut ID2D1SimplifiedGeometrySink, ) -> HRESULT, fn GetBounds( inkStyle: *mut ID2D1InkStyle, worldTransform: *const D2D1_MATRIX_3X2_F, bounds: *mut D2D1_RECT_F, ) -> HRESULT, }} RIDL!{#[uuid(0xf292e401, 0xc050, 0x4cde, 0x83, 0xd7, 0x04, 0x96, 0x2d, 0x3b, 0x23, 0xc2)] interface ID2D1GradientMesh(ID2D1GradientMeshVtbl): ID2D1Resource(ID2D1ResourceVtbl) { fn GetPatchCount() -> UINT32, fn GetPatches( startIndex: UINT32, patches: *mut D2D1_GRADIENT_MESH_PATCH, patchesCount: UINT32, ) -> HRESULT, }} RIDL!{#[uuid(0xc9b664e5, 0x74a1, 0x4378, 0x9a, 0xc2, 0xee, 0xfc, 0x37, 0xa3, 0xf4, 0xd8)] interface ID2D1ImageSource(ID2D1ImageSourceVtbl): ID2D1Image(ID2D1ImageVtbl) { fn OfferResources() -> HRESULT, fn TryReclaimResources( resourcesDiscarded: *mut BOOL, ) -> HRESULT, }} RIDL!{#[uuid(0x77395441, 0x1c8f, 0x4555, 0x86, 0x83, 0xf5, 0x0d, 0xab, 0x0f, 0xe7, 0x92)] interface ID2D1ImageSourceFromWic(ID2D1ImageSourceFromWicVtbl): ID2D1ImageSource(ID2D1ImageSourceVtbl) { fn EnsureCached( rectangleToFill: *const D2D1_RECT_U, ) -> HRESULT, fn TrimCache( rectangleToPreserve: *const D2D1_RECT_U, ) -> HRESULT, fn GetSource( wicBitmapSource: *mut *mut IWICBitmapSource, ) -> (), }} RIDL!{#[uuid(0x7f1f79e5, 0x2796, 0x416c, 0x8f, 0x55, 0x70, 0x0f, 0x91, 0x14, 0x45, 0xe5)] interface ID2D1TransformedImageSource(ID2D1TransformedImageSourceVtbl): ID2D1Image(ID2D1ImageVtbl) { fn GetSource( imageSource: *mut *mut ID2D1ImageSource, ) -> (), fn GetProperties( properties: *mut D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES, ) -> (), }} RIDL!{#[uuid(0x53dd9855, 0xa3b0, 0x4d5b, 0x82, 0xe1, 0x26, 0xe2, 0x5c, 0x5e, 0x57, 0x97)] interface ID2D1LookupTable3D(ID2D1LookupTable3DVtbl): ID2D1Resource(ID2D1ResourceVtbl) {}} RIDL!{#[uuid(0x394ea6a3, 0x0c34, 0x4321, 0x95, 0x0b, 0x6c, 0xa2, 0x0f, 0x0b, 0xe6, 0xc7)] interface ID2D1DeviceContext2(ID2D1DeviceContext2Vtbl): ID2D1DeviceContext1(ID2D1DeviceContext1Vtbl) { fn CreateInk( startPoint: *const D2D1_INK_POINT, ink: *mut *mut ID2D1Ink, ) -> HRESULT, fn CreateInkStyle( inkStyleProperties: *const D2D1_INK_STYLE_PROPERTIES, inkStyle: *mut *mut ID2D1InkStyle, ) -> HRESULT, fn CreateGradientMesh( patches: *const D2D1_GRADIENT_MESH_PATCH, patchesCount: UINT32, gradientMesh: *mut *mut ID2D1GradientMesh, ) -> HRESULT, fn CreateImageSourceFromWic( wicBitmapSource: *mut IWICBitmapSource, loadingOptions: D2D1_IMAGE_SOURCE_LOADING_OPTIONS, alphaMode: D2D1_ALPHA_MODE, imageSource: *mut *mut ID2D1ImageSourceFromWic, ) -> HRESULT, fn CreateLookupTable3D( precision: D2D1_BUFFER_PRECISION, extents: *const UINT32, data: *const BYTE, dataCount: UINT32, strides: *const UINT32, lookupTable: *mut *mut ID2D1LookupTable3D, ) -> HRESULT, fn CreateImageSourceFromDxgi( surfaces: *const *mut IDXGISurface, surfaceCount: UINT32, colorSpace: DXGI_COLOR_SPACE_TYPE, options: D2D1_IMAGE_SOURCE_FROM_DXGI_OPTIONS, imageSource: *mut *mut ID2D1ImageSource, ) -> HRESULT, fn GetGradientMeshWorldBounds( gradientMesh: *mut ID2D1GradientMesh, pBounds: *mut D2D1_RECT_F, ) -> HRESULT, fn DrawInk( ink: *mut ID2D1Ink, brush: *mut ID2D1Brush, inkStyle: *mut ID2D1InkStyle, ) -> (), fn DrawGradientMesh( gradientMesh: *mut ID2D1GradientMesh, ) -> (), fn DrawGdiMetafile( gdiMetafile: *mut ID2D1GdiMetafile, destinationRectangle: *const D2D1_RECT_F, sourceRectangle: *const D2D1_RECT_F, ) -> (), fn CreateTransformedImageSource( imageSource: *mut ID2D1ImageSource, properties: *const D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES, transformedImageSource: *mut *mut ID2D1TransformedImageSource, ) -> HRESULT, }} RIDL!{#[uuid(0xa44472e1, 0x8dfb, 0x4e60, 0x84, 0x92, 0x6e, 0x28, 0x61, 0xc9, 0xca, 0x8b)] interface ID2D1Device2(ID2D1Device2Vtbl): ID2D1Device1(ID2D1Device1Vtbl) { fn CreateDeviceContext( options: D2D1_DEVICE_CONTEXT_OPTIONS, deviceContext2: *mut *mut ID2D1DeviceContext2, ) -> HRESULT, fn FlushDeviceContexts( bitmap: *mut ID2D1Bitmap, ) -> (), fn GetDxgiDevice( dxgiDevice: *mut *mut IDXGIDevice, ) -> HRESULT, }} RIDL!{#[uuid(0x0869759f, 0x4f00, 0x413f, 0xb0, 0x3e, 0x2b, 0xda, 0x45, 0x40, 0x4d, 0x0f)] interface ID2D1Factory3(ID2D1Factory3Vtbl): ID2D1Factory2(ID2D1Factory2Vtbl) { fn CreateDevice( dxgiDevice: *mut IDXGIDevice, d2dDevice2: *mut *mut ID2D1Device2, ) -> HRESULT, }} RIDL!{#[uuid(0x3bab440e, 0x417e, 0x47df, 0xa2, 0xe2, 0xbc, 0x0b, 0xe6, 0xa0, 0x09, 0x16)] interface ID2D1CommandSink2(ID2D1CommandSink2Vtbl): ID2D1CommandSink1(ID2D1CommandSink1Vtbl) { fn DrawInk( ink: *mut ID2D1Ink, brush: *mut ID2D1Brush, inkStyle: *mut ID2D1InkStyle, ) -> (), fn DrawGradientMesh( gradientMesh: *mut ID2D1GradientMesh, ) -> (),<|fim▁hole|> sourceRectangle: *const D2D1_RECT_F, ) -> (), }} RIDL!{#[uuid(0x2e69f9e8, 0xdd3f, 0x4bf9, 0x95, 0xba, 0xc0, 0x4f, 0x49, 0xd7, 0x88, 0xdf)] interface ID2D1GdiMetafile1(ID2D1GdiMetafile1Vtbl): ID2D1GdiMetafile(ID2D1GdiMetafileVtbl) { fn GetDpi( dpiX: *mut FLOAT, dpiY: *mut FLOAT, ) -> HRESULT, fn GetSourceBounds( bounds: *mut D2D1_RECT_F, ) -> HRESULT, }} RIDL!{#[uuid(0xfd0ecb6b, 0x91e6, 0x411e, 0x86, 0x55, 0x39, 0x5e, 0x76, 0x0f, 0x91, 0xb4)] interface ID2D1GdiMetafileSink1(ID2D1GdiMetafileSink1Vtbl): ID2D1GdiMetafileSink(ID2D1GdiMetafileSinkVtbl) { fn ProcessRecord( recordType: DWORD, recordData: *const c_void, recordDataSize: DWORD, flags: UINT32, ) -> HRESULT, }} RIDL!{#[uuid(0x4dc583bf, 0x3a10, 0x438a, 0x87, 0x22, 0xe9, 0x76, 0x52, 0x24, 0xf1, 0xf1)] interface ID2D1SpriteBatch(ID2D1SpriteBatchVtbl): ID2D1Resource(ID2D1ResourceVtbl) { fn AddSprites( spriteCount: UINT32, destinationRectangle: *const D2D1_RECT_F, sourceRectangles: *const D2D1_RECT_U, colors: *const D2D1_COLOR_F, transforms: *const D2D1_MATRIX_3X2_F, destinationRectanglesStride: UINT32, sourceRectanglesStride: UINT32, colorsStride: UINT32, transformsStride: D2D1_MATRIX_3X2_F, ) -> HRESULT, fn SetSprites( startIndex: UINT32, spriteCount: UINT32, destinationRectangle: *const D2D1_RECT_F, sourceRectangles: *const D2D1_RECT_U, colors: *const D2D1_COLOR_F, transforms: *const D2D1_MATRIX_3X2_F, destinationRectanglesStride: UINT32, sourceRectanglesStride: UINT32, colorsStride: UINT32, transformsStride: D2D1_MATRIX_3X2_F, ) -> HRESULT, fn GetSprites( startIndex: UINT32, spriteCount: UINT32, destinationRectangle: *mut D2D1_RECT_F, sourceRectangles: *mut D2D1_RECT_U, colors: *mut D2D1_COLOR_F, transforms: *mut D2D1_MATRIX_3X2_F, ) -> HRESULT, fn GetSpriteCount() -> UINT32, fn Clear() -> (), }} RIDL!{#[uuid(0x235a7496, 0x8351, 0x414c, 0xbc, 0xd4, 0x66, 0x72, 0xab, 0x2d, 0x8e, 0x00)] interface ID2D1DeviceContext3(ID2D1DeviceContext3Vtbl): ID2D1DeviceContext2(ID2D1DeviceContext2Vtbl) { fn CreateSpriteBatch( spriteBatch: *mut *mut ID2D1SpriteBatch, ) -> HRESULT, fn DrawSpriteBatch( spriteBatch: *mut ID2D1SpriteBatch, startIndex: UINT32, spriteCount: UINT32, bitmap: *mut ID2D1Bitmap, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE, spriteOptions: D2D1_SPRITE_OPTIONS, ) -> (), }} RIDL!{#[uuid(0x852f2087, 0x802c, 0x4037, 0xab, 0x60, 0xff, 0x2e, 0x7e, 0xe6, 0xfc, 0x01)] interface ID2D1Device3(ID2D1Device3Vtbl): ID2D1Device2(ID2D1Device2Vtbl) { fn CreateDeviceContext( options: D2D1_DEVICE_CONTEXT_OPTIONS, deviceContext3: *mut *mut ID2D1DeviceContext3, ) -> HRESULT, }} RIDL!{#[uuid(0xbd4ec2d2, 0x0662, 0x4bee, 0xba, 0x8e, 0x6f, 0x29, 0xf0, 0x32, 0xe0, 0x96)] interface ID2D1Factory4(ID2D1Factory4Vtbl): ID2D1Factory3(ID2D1Factory3Vtbl) { fn CreateDevice( dxgiDevice: *mut IDXGIDevice, d2dDevice3: *mut *mut ID2D1Device3, ) -> HRESULT, }} RIDL!{#[uuid(0x18079135, 0x4cf3, 0x4868, 0xbc, 0x8e, 0x06, 0x06, 0x7e, 0x6d, 0x24, 0x2d)] interface ID2D1CommandSink3(ID2D1CommandSink3Vtbl): ID2D1CommandSink2(ID2D1CommandSink2Vtbl) { fn DrawSpriteBatch( spriteBatch: *mut ID2D1SpriteBatch, startIndex: UINT32, spriteCount: UINT32, bitmap: *mut ID2D1Bitmap, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE, spriteOptions: D2D1_SPRITE_OPTIONS, ) -> (), }} RIDL!{#[uuid(0xaf671749, 0xd241, 0x4db8, 0x8e, 0x41, 0xdc, 0xc2, 0xe5, 0xc1, 0xa4, 0x38)] interface ID2D1SvgGlyphStyle(ID2D1SvgGlyphStyleVtbl): ID2D1Resource(ID2D1ResourceVtbl) { fn SetFill( brush: *mut ID2D1Brush, ) -> HRESULT, fn GetFill( brush: *mut *mut ID2D1Brush, ) -> (), fn SetStroke( brush: *mut ID2D1Brush, strokeWidth: FLOAT, dashes: *const FLOAT, dashesCount: UINT32, dashOffset: FLOAT, ) -> HRESULT, fn GetStrokeDashesCount() -> UINT32, fn GetStroke( brush: *mut *mut ID2D1Brush, strokeWidth: *mut FLOAT, dashes: *mut FLOAT, dashesCount: UINT32, dashOffset: *mut FLOAT, ) -> (), }} RIDL!{#[uuid(0x8c427831, 0x3d90, 0x4476, 0xb6, 0x47, 0xc4, 0xfa, 0xe3, 0x49, 0xe4, 0xdb)] interface ID2D1DeviceContext4(ID2D1DeviceContext4Vtbl): ID2D1DeviceContext3(ID2D1DeviceContext3Vtbl) { fn CreateSvgGlyphStyle( svgGlyphStyle: *mut *mut ID2D1SvgGlyphStyle, ) -> HRESULT, fn DrawText( string: *const WCHAR, stringLength: UINT32, textFormat: *mut IDWriteTextFormat, layoutRect: *const D2D1_RECT_F, defaultFillBrush: *mut ID2D1Brush, svgGlyphStyle: *mut ID2D1SvgGlyphStyle, colorPaletteIndex: UINT32, options: D2D1_DRAW_TEXT_OPTIONS, measuringMode: DWRITE_MEASURING_MODE, ) -> (), fn DrawTextLayout( origin: D2D1_POINT_2F, textLayout: *mut IDWriteTextLayout, defaultFillBrush: *mut ID2D1Brush, svgGlyphStyle: *mut ID2D1SvgGlyphStyle, colorPaletteIndex: UINT32, options: D2D1_DRAW_TEXT_OPTIONS, ) -> (), fn DrawColorBitmapGlyphRun( glyphImageFormat: DWRITE_GLYPH_IMAGE_FORMATS, baselineOrigin: D2D1_POINT_2F, glyphRun: *const DWRITE_GLYPH_RUN, measuringMode: DWRITE_MEASURING_MODE, bitmapSnapOption: D2D1_COLOR_BITMAP_GLYPH_SNAP_OPTION, ) -> (), fn DrawSvgGlyphRun( baselineOrigin: D2D1_POINT_2F, glyphRun: *const DWRITE_GLYPH_RUN, defaultFillBrush: *mut ID2D1Brush, svgGlyphStyle: *mut ID2D1SvgGlyphStyle, colorPaletteIndex: UINT32, measuringMode: DWRITE_MEASURING_MODE, ) -> (), fn GetColorBitmapGlyphImage( glyphImageFormat: DWRITE_GLYPH_IMAGE_FORMATS, glyphOrigin: D2D1_POINT_2F, fontFace: *mut IDWriteFontFace, fontEmSize: FLOAT, glyphIndex: UINT16, isSideways: BOOL, worldTransform: *const D2D1_MATRIX_3X2_F, dpiX: FLOAT, dpiY: FLOAT, glyphTransform: *mut D2D1_MATRIX_3X2_F, glyphImage: *mut *mut ID2D1Image, ) -> HRESULT, fn GetSvgGlyphImage( glyphImageFormat: DWRITE_GLYPH_IMAGE_FORMATS, glyphOrigin: D2D1_POINT_2F, fontFace: *mut IDWriteFontFace, fontEmSize: FLOAT, glyphIndex: UINT16, isSideways: BOOL, worldTransform: *const D2D1_MATRIX_3X2_F, defaultFillBrush: *mut ID2D1Brush, svgGlyphStyle: *mut ID2D1SvgGlyphStyle, colorPaletteIndex: UINT32, glyphTransform: *mut D2D1_MATRIX_3X2_F, glyphImage: *mut *mut ID2D1CommandList, ) -> HRESULT, }} RIDL!{#[uuid(0xd7bdb159, 0x5683, 0x4a46, 0xbc, 0x9c, 0x72, 0xdc, 0x72, 0x0b, 0x85, 0x8b)] interface ID2D1Device4(ID2D1Device4Vtbl): ID2D1Device3(ID2D1Device3Vtbl) { fn CreateDeviceContext( options: D2D1_DEVICE_CONTEXT_OPTIONS, deviceContext4: *mut *mut ID2D1DeviceContext4, ) -> HRESULT, fn SetMaximumColorGlyphCacheMemory( maximumInBytes: UINT64, ) -> (), fn GetMaximumColorGlyphCacheMemory() -> UINT64, }} RIDL!{#[uuid(0xc4349994, 0x838e, 0x4b0f, 0x8c, 0xab, 0x44, 0x99, 0x7d, 0x9e, 0xea, 0xcc)] interface ID2D1Factory5(ID2D1Factory5Vtbl): ID2D1Factory4(ID2D1Factory4Vtbl) { fn CreateDevice( dxgiDevice: *mut IDXGIDevice, d2dDevice4: *mut *mut ID2D1Device4, ) -> HRESULT, }} RIDL!{#[uuid(0xc78a6519, 0x40d6, 0x4218, 0xb2, 0xde, 0xbe, 0xee, 0xb7, 0x44, 0xbb, 0x3e)] interface ID2D1CommandSink4(ID2D1CommandSink4Vtbl): ID2D1CommandSink3(ID2D1CommandSink3Vtbl) { fn SetPrimitiveBlend2( primitiveBlend: D2D1_PRIMITIVE_BLEND, ) -> HRESULT, }} RIDL!{#[uuid(0x1ab42875, 0xc57f, 0x4be9, 0xbd, 0x85, 0x9c, 0xd7, 0x8d, 0x6f, 0x55, 0xee)] interface ID2D1ColorContext1(ID2D1ColorContext1Vtbl): ID2D1ColorContext(ID2D1ColorContextVtbl) { fn GetColorContextType() -> D2D1_COLOR_CONTEXT_TYPE, fn GetDXGIColorSpace() -> DXGI_COLOR_SPACE_TYPE, fn GetSimpleColorProfile( simpleProfile: *mut D2D1_SIMPLE_COLOR_PROFILE, ) -> HRESULT, }} RIDL!{#[uuid(0x7836d248, 0x68cc, 0x4df6, 0xb9, 0xe8, 0xde, 0x99, 0x1b, 0xf6, 0x2e, 0xb7)] interface ID2D1DeviceContext5(ID2D1DeviceContext5Vtbl): ID2D1DeviceContext4(ID2D1DeviceContext4Vtbl) { fn CreateSvgDocument( inputXmlStream: *mut IStream, viewportSize: D2D1_SIZE_F, svgDocument: *mut *mut ID2D1SvgDocument, ) -> HRESULT, fn DrawSvgDocument( svgDocument: *mut ID2D1SvgDocument, ) -> (), fn CreateColorContextFromDxgiColorSpace( colorSpace: DXGI_COLOR_SPACE_TYPE, colorContext: *mut *mut ID2D1ColorContext1, ) -> HRESULT, fn CreateColorContextFromSimpleColorProfile( simpleProfile: *const D2D1_SIMPLE_COLOR_PROFILE, colorContext: *mut *mut ID2D1ColorContext1, ) -> HRESULT, }} RIDL!{#[uuid(0xd55ba0a4, 0x6405, 0x4694, 0xae, 0xf5, 0x08, 0xee, 0x1a, 0x43, 0x58, 0xb4)] interface ID2D1Device5(ID2D1Device5Vtbl): ID2D1Device4(ID2D1Device4Vtbl) { fn CreateDeviceContext( options: D2D1_DEVICE_CONTEXT_OPTIONS, deviceContext5: *mut *mut ID2D1DeviceContext5, ) -> HRESULT, }} RIDL!{#[uuid(0xf9976f46, 0xf642, 0x44c1, 0x97, 0xca, 0xda, 0x32, 0xea, 0x2a, 0x26, 0x35)] interface ID2D1Factory6(ID2D1Factory6Vtbl): ID2D1Factory5(ID2D1Factory5Vtbl) { fn CreateDevice( dxgiDevice: *mut IDXGIDevice, d2dDevice5: *mut *mut ID2D1Device5, ) -> HRESULT, }} RIDL!{#[uuid(0x7047dd26, 0xb1e7, 0x44a7, 0x95, 0x9a, 0x83, 0x49, 0xe2, 0x14, 0x4f, 0xa8)] interface ID2D1CommandSink5(ID2D1CommandSink5Vtbl): ID2D1CommandSink4(ID2D1CommandSink4Vtbl) { fn BlendImage( image: *mut ID2D1Image, blendMode: D2D1_BLEND_MODE, targetOffset: *const D2D1_POINT_2F, imageRectangle: *const D2D1_RECT_F, interpolationMode: D2D1_INTERPOLATION_MODE, ) -> HRESULT, }} RIDL!{#[uuid(0x985f7e37, 0x4ed0, 0x4a19, 0x98, 0xa3, 0x15, 0xb0, 0xed, 0xfd, 0xe3, 0x06)] interface ID2D1DeviceContext6(ID2D1DeviceContext6Vtbl): ID2D1DeviceContext5(ID2D1DeviceContext5Vtbl) { fn BlendImage( image: *mut ID2D1Image, blendMode: D2D1_BLEND_MODE, targetOffset: *const D2D1_POINT_2F, imageRectangle: *const D2D1_RECT_F, interpolationMode: D2D1_INTERPOLATION_MODE, ) -> HRESULT, }} RIDL!{#[uuid(0x7bfef914, 0x2d75, 0x4bad, 0xbe, 0x87, 0xe1, 0x8d, 0xdb, 0x07, 0x7b, 0x6d)] interface ID2D1Device6(ID2D1Device6Vtbl): ID2D1Device5(ID2D1Device5Vtbl) { fn CreateDeviceContext( options: D2D1_DEVICE_CONTEXT_OPTIONS, deviceContext6: *mut *mut ID2D1DeviceContext6, ) -> HRESULT, }} RIDL!{#[uuid(0xbdc2bdd3, 0xb96c, 0x4de6, 0xbd, 0xf7, 0x99, 0xd4, 0x74, 0x54, 0x54, 0xde)] interface ID2D1Factory7(ID2D1Factory7Vtbl): ID2D1Factory6(ID2D1Factory6Vtbl) { fn CreateDevice( dxgiDevice: *mut IDXGIDevice, d2dDevice6: *mut *mut ID2D1Device6, ) -> HRESULT, }} extern "system" { pub fn D2D1GetGradientMeshInteriorPointsFromCoonsPatch( pPoint0: *const D2D1_POINT_2F, pPoint1: *const D2D1_POINT_2F, pPoint2: *const D2D1_POINT_2F, pPoint3: *const D2D1_POINT_2F, pPoint4: *const D2D1_POINT_2F, pPoint5: *const D2D1_POINT_2F, pPoint6: *const D2D1_POINT_2F, pPoint7: *const D2D1_POINT_2F, pPoint8: *const D2D1_POINT_2F, pPoint9: *const D2D1_POINT_2F, pPoint10: *const D2D1_POINT_2F, pPoint11: *const D2D1_POINT_2F, pTensorPoint11: *mut D2D1_POINT_2F, pTensorPoint12: *mut D2D1_POINT_2F, pTensorPoint21: *mut D2D1_POINT_2F, pTensorPoint22: *mut D2D1_POINT_2F, ); }<|fim▁end|>
fn DrawGdiMetafile( gdiMetafile: *mut ID2D1GdiMetafile, destinationRectangle: *const D2D1_RECT_F,
<|file_name|>obj_file_io.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ object file io is a Python object to single file I/O framework. The word 'framework' means you can use any serialization/deserialization algorithm here. - dump: dump python object to a file. - safe_dump: add atomic writing guarantee for ``dump``. - load: load python object from a file. Features: 1. ``compress``: built-in compress/decompress options. 2. ``overwrite``: an option to prevent from overwrite existing file. 3. ``verbose``: optional built-in logger can display help infomation. Usage: suppose you have a function (dumper function, has to take python object as input, and return a binary object) can dump python object to binary:: import pickle def dump(obj): return pickle.dumps(obj) def load(binary): return pickle.loads(binary) You just need to add a decorator, and new function will do all magic for you: from obj_file_io import dump_func, safe_dump_func, load_func @dump_func def dump(obj): return pickle.dumps(obj) @safe_dump_func def safe_dump(obj): return pickle.dumps(obj) @load_func def load(binary): return pickle.loads(binary) **中文文档** object file io是一个将Python对象对单个本地文件的I/O """ import os import time import zlib import logging import inspect from atomicwrites import atomic_write # logging util logger = logging.getLogger() logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) logger.addHandler(stream_handler) def prt_console(message, verbose): """Print message to console, if ``verbose`` is True. """ if verbose: logger.info(message) def _check_serializer_type(serializer_type): if serializer_type not in ["binary", "str"]: raise ValueError("serializer_type has to be one of 'binary' or 'str'!") # dump, load def _dump(obj, abspath, serializer_type, dumper_func=None, compress=True, overwrite=False, verbose=False, **kwargs): """Dump object to file. :param abspath: The file path you want dump to. :type abspath: str :param serializer_type: 'binary' or 'str'. :type serializer_type: str :param dumper_func: A dumper function that takes an object as input, return binary or string. :type dumper_func: callable function :param compress: default ``False``. If True, then compress binary. :type compress: bool :param overwrite: default ``False``, If ``True``, when you dump to existing file, it silently overwrite it. If ``False``, an alert message is shown. Default setting ``False`` is to prevent overwrite file by mistake. :type overwrite: boolean :param verbose: default True, help-message-display trigger. :type verbose: boolean """ _check_serializer_type(serializer_type) if not inspect.isfunction(dumper_func): raise TypeError("dumper_func has to be a function take object as input " "and return binary!") prt_console("\nDump to '%s' ..." % abspath, verbose) if os.path.exists(abspath): if not overwrite: prt_console( " Stop! File exists and overwrite is not allowed", verbose, ) return st = time.clock() b_or_str = dumper_func(obj, **kwargs) if serializer_type is "str": b = b_or_str.encode("utf-8") else: b = b_or_str if compress: b = zlib.compress(b) with atomic_write(abspath, overwrite=overwrite, mode="wb") as f: f.write(b) elapsed = time.clock() - st prt_console(" Complete! Elapse %.6f sec." % elapsed, verbose) if serializer_type is "str": return b_or_str else: return b def _load(abspath, serializer_type, loader_func=None,<|fim▁hole|> :param abspath: The file path you want load from. :type abspath: str :param serializer_type: 'binary' or 'str'. :type serializer_type: str :param loader_func: A loader function that takes binary as input, return an object. :type loader_func: callable function :param decompress: default ``False``. If True, then decompress binary. :type decompress: bool :param verbose: default True, help-message-display trigger. :type verbose: boolean """ _check_serializer_type(serializer_type) if not inspect.isfunction(loader_func): raise TypeError("loader_func has to be a function take binary as input " "and return an object!") prt_console("\nLoad from '%s' ..." % abspath, verbose) if not os.path.exists(abspath): raise ValueError("'%s' doesn't exist." % abspath) st = time.clock() with open(abspath, "rb") as f: b = f.read() if decompress: b = zlib.decompress(b) if serializer_type is "str": obj = loader_func(b.decode("utf-8"), **kwargs) else: obj = loader_func(b, **kwargs) elapsed = time.clock() - st prt_console(" Complete! Elapse %.6f sec." % elapsed, verbose) return obj def dump_func(serializer_type): """A decorator for ``_dump(dumper_func=dumper_func, **kwargs)`` """ def outer_wrapper(dumper_func): def wrapper(*args, **kwargs): return _dump( *args, dumper_func=dumper_func, serializer_type=serializer_type, **kwargs ) return wrapper return outer_wrapper def load_func(serializer_type): """A decorator for ``_load(loader_func=loader_func, **kwargs)`` """ def outer_wrapper(loader_func): def wrapper(*args, **kwargs): return _load( *args, loader_func=loader_func, serializer_type=serializer_type, **kwargs ) return wrapper return outer_wrapper<|fim▁end|>
decompress=True, verbose=False, **kwargs): """load object from file.
<|file_name|>test_price_list.py<|end_file_name|><|fim▁begin|>test_records = [ [{<|fim▁hole|> "valid_for_all_countries": 1 }] ]<|fim▁end|>
"doctype": "Price List", "price_list_name": "_Test Price List", "currency": "INR",
<|file_name|>MultilevelSensor.java<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************* */ package com.whizzosoftware.wzwave.node.generic; import com.whizzosoftware.wzwave.commandclass.BasicCommandClass; import com.whizzosoftware.wzwave.commandclass.CommandClass; import com.whizzosoftware.wzwave.commandclass.MultilevelSensorCommandClass; import com.whizzosoftware.wzwave.node.NodeInfo; import com.whizzosoftware.wzwave.node.NodeListener; import com.whizzosoftware.wzwave.node.ZWaveNode; import com.whizzosoftware.wzwave.persist.PersistenceContext; /** * A Multilevel Sensor node. * * @author Dan Noguerol */ public class MultilevelSensor extends ZWaveNode { public static final byte ID = 0x21; public MultilevelSensor(NodeInfo info, boolean listening, NodeListener listener) { super(info, listening, listener); addCommandClass(BasicCommandClass.ID, new BasicCommandClass()); addCommandClass(MultilevelSensorCommandClass.ID, new MultilevelSensorCommandClass()); } public MultilevelSensor(PersistenceContext pctx, Byte nodeId, NodeListener listener) { super(pctx, nodeId, listener); } protected CommandClass performBasicCommandClassMapping(BasicCommandClass cc) { // Basic commands should get mapped to MultilevelSensor commands return getCommandClass(MultilevelSensorCommandClass.ID); } @Override protected void refresh(boolean deferIfNotListening) { } }<|fim▁end|>
******************************************************************************* * Copyright (c) 2013 Whizzo Software, LLC. * All rights reserved. This program and the accompanying materials
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use std::path::Path; use std::sync::Arc; use linefeed::complete::{Completer, Completion}; use linefeed::prompter::Prompter; use linefeed::terminal::Terminal; pub mod dots; pub mod env; pub mod make; pub mod path; pub mod ssh; use crate::libs; use crate::parsers; use crate::shell; use crate::tools; pub struct CicadaCompleter { pub sh: Arc<shell::Shell>, } fn for_make(line: &str) -> bool { libs::re::re_contains(line, r"^ *make ") } fn for_env(line: &str) -> bool { libs::re::re_contains(line, r" *\$[_a-zA-Z0-9]*$") } fn for_ssh(line: &str) -> bool { libs::re::re_contains(line, r"^ *(ssh|scp).* +[^ \./]+ *$") } fn for_cd(line: &str) -> bool { libs::re::re_contains(line, r"^ *cd +") } fn for_bin(line: &str) -> bool { // TODO: why 'echo hi|ech<TAB>' doesn't complete in real? // but passes in test cases? let ptn = r"(^ *(sudo|which)? *[a-zA-Z0-9_\.-]+$)|(^.+\| *(sudo|which)? *[a-zA-Z0-9_\.-]+$)"; libs::re::re_contains(line, ptn) } fn for_dots(line: &str) -> bool { let args = parsers::parser_line::line_to_plain_tokens(line); let len = args.len(); if len == 0 { return false; } let dir = tools::get_user_completer_dir(); let dot_file = format!("{}/{}.yaml", dir, args[0]); Path::new(dot_file.as_str()).exists() } impl<Term: Terminal> Completer<Term> for CicadaCompleter { fn complete( &self, word: &str, reader: &Prompter<Term>, start: usize, _end: usize, ) -> Option<Vec<Completion>> { let line = reader.buffer(); // these completions should not fail back to path completion. if for_bin(line) { let cpl = Arc::new(path::BinCompleter { sh: self.sh.clone(), }); return cpl.complete(word, reader, start, _end); } if for_cd(line) { let cpl = Arc::new(path::CdCompleter); return cpl.complete(word, reader, start, _end); } // the following completions needs fail back to use path completion, // so that `$ make generate /path/to/fi<Tab>` still works. if for_ssh(line) { let cpl = Arc::new(ssh::SshCompleter); if let Some(x) = cpl.complete(word, reader, start, _end) { if !x.is_empty() { return Some(x); } } } if for_make(line) { let cpl = Arc::new(make::MakeCompleter); if let Some(x) = cpl.complete(word, reader, start, _end) { if !x.is_empty() { return Some(x); } } } if for_env(line) { let cpl = Arc::new(env::EnvCompleter); if let Some(x) = cpl.complete(word, reader, start, _end) { if !x.is_empty() { return Some(x); } } } if for_dots(line) { let cpl = Arc::new(dots::DotsCompleter); if let Some(x) = cpl.complete(word, reader, start, _end) { if !x.is_empty() { return Some(x); } } } let cpl = Arc::new(path::PathCompleter); cpl.complete(word, reader, start, _end) } fn word_start(&self, line: &str, end: usize, _reader: &Prompter<Term>) -> usize { escaped_word_start(&line[..end]) }<|fim▁hole|> let mut start_position: usize = 0; let mut found_bs = false; let mut found_space = false; let mut with_quote = false; let mut ch_quote = '\0'; let mut extra_bytes = 0; for (i, c) in line.chars().enumerate() { if found_space { found_space = false; start_position = i + extra_bytes; } if c == '\\' { found_bs = true; continue; } if c == ' ' && !found_bs && !with_quote { found_space = true; continue; } if !with_quote && !found_bs && (c == '"' || c == '\'') { with_quote = true; ch_quote = c; } else if with_quote && !found_bs && ch_quote == c { with_quote = false; } let bytes_c = c.len_utf8(); if bytes_c > 1 { extra_bytes += bytes_c - 1; } found_bs = false; } if found_space { start_position = line.len(); } start_position } #[cfg(test)] mod tests { use super::escaped_word_start; use super::for_bin; #[test] fn test_escaped_word_start() { assert_eq!(escaped_word_start("ls a"), 3); assert_eq!(escaped_word_start("ls abc"), 3); assert_eq!(escaped_word_start("ll 中文yoo"), 3); assert_eq!(escaped_word_start("ll yoo中文"), 3); assert_eq!(escaped_word_start(" ls foo"), 7); assert_eq!(escaped_word_start("ls foo bar"), 7); assert_eq!(escaped_word_start("ls føo bar"), 8); assert_eq!(escaped_word_start("ls a\\ "), 3); assert_eq!(escaped_word_start("ls a\\ b"), 3); assert_eq!(escaped_word_start("ls a\\ b\\ c"), 3); assert_eq!(escaped_word_start(" ls a\\ b\\ c"), 7); assert_eq!(escaped_word_start("mv foo\\ bar abc"), 12); assert_eq!(escaped_word_start("mv føo\\ bar abc"), 13); assert_eq!(escaped_word_start("ls a\\'"), 3); assert_eq!(escaped_word_start("ls a\\'b"), 3); assert_eq!(escaped_word_start("ls a\\'b\\'c"), 3); assert_eq!(escaped_word_start(" ls a\\'b\\'c"), 7); assert_eq!(escaped_word_start("ls a\\\""), 3); assert_eq!(escaped_word_start("ls a\\\"b"), 3); assert_eq!(escaped_word_start("ls a\\\"b\\\"c"), 3); assert_eq!(escaped_word_start(" ls a\\\"b\\\"c"), 7); assert_eq!(escaped_word_start("ls \"a'b'c"), 3); assert_eq!(escaped_word_start("ls \'a\"b\"c"), 3); assert_eq!(escaped_word_start("rm "), 3); assert_eq!(escaped_word_start("ls a "), 5); assert_eq!(escaped_word_start(" ls foo "), 11); assert_eq!(escaped_word_start("ls \"a b"), 3); assert_eq!(escaped_word_start("ls \"a "), 3); assert_eq!(escaped_word_start("ls \"a b "), 3); assert_eq!(escaped_word_start("ls \'a b"), 3); assert_eq!(escaped_word_start("ls \'a "), 3); assert_eq!(escaped_word_start("ls \'a b "), 3); assert_eq!(escaped_word_start("\"ls\" \"a b"), 5); assert_eq!(escaped_word_start("echo føo b"), 10); assert_eq!(escaped_word_start("echo føo "), 10); assert_eq!(escaped_word_start("echo \\["), 5); } #[test] fn test_for_bin() { assert!(for_bin("foo")); assert!(for_bin("foo|bar")); assert!(for_bin("foo|bar|baz")); assert!(for_bin("foo | bar")); assert!(for_bin("foo | bar | baz")); assert!(!for_bin("foo bar")); assert!(!for_bin("foo bar | foo bar")); } }<|fim▁end|>
} pub fn escaped_word_start(line: &str) -> usize {
<|file_name|>main.go<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2013 ASMlover. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list ofconditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materialsprovided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE.<|fim▁hole|> "bufio" "os" ) func main() { f, _ := os.Open("./main.go") r := bufio.NewReader(f) for { s, err := r.ReadString('\n') if err != nil { break } fmt.Fprintf(os.Stdout, "%v", s) } }<|fim▁end|>
*/ package main import ( "fmt"
<|file_name|>QTableColumnConstraint.java<|end_file_name|><|fim▁begin|>package org.plasma.provisioning.rdb.mysql.v5_5.query; import org.plasma.provisioning.rdb.mysql.v5_5.TableColumnConstraint; import org.plasma.query.DataProperty; import org.plasma.query.Expression; import org.plasma.query.dsl.DataNode; import org.plasma.query.dsl.DomainRoot; import org.plasma.query.dsl.PathNode; import org.plasma.sdo.helper.PlasmaTypeHelper; /** * Generated Domain Specific Language (DSL) implementation class representing * the domain model entity <b>TableColumnConstraint</b>. * * <p> * </p> * <b>Data Store Mapping:</b> Corresponds to the physical data store entity * <b>REFERENTIAL_CONSTRAINTS</b>. * */ public class QTableColumnConstraint extends DomainRoot { private QTableColumnConstraint() { super(PlasmaTypeHelper.INSTANCE.getType(TableColumnConstraint.class));<|fim▁hole|> /** * Constructor which instantiates a domain query path node. A path may span * multiple namespaces and therefore Java inplementation packages based on the * <a href= * "http://docs.plasma-sdo.org/api/org/plasma/config/PlasmaConfiguration.html" * >Condiguration</a>. Note: while this constructor is public, it is not for * application use! * * @param source * the source path node * @param sourceProperty * the source property logical name */ public QTableColumnConstraint(PathNode source, String sourceProperty) { super(source, sourceProperty); } /** * Constructor which instantiates a domain query path node. A path may span * multiple namespaces and therefore Java inplementation packages based on the * <a href= * "http://docs.plasma-sdo.org/api/org/plasma/config/PlasmaConfiguration.html" * >Condiguration</a>. Note: while this constructor is public, it is not for * application use! * * @param source * the source path node * @param sourceProperty * the source property logical name * @param expr * the path predicate expression */ public QTableColumnConstraint(PathNode source, String sourceProperty, Expression expr) { super(source, sourceProperty, expr); } /** * Returns a new DSL query for <a * href="http://docs.plasma-sdo.org/api/org/plasma/sdo/PlasmaType.html" * >Type</a> <b>TableColumnConstraint</b> which can be used either as a query * root or as the start (entry point) for a new path predicate expression. * * @return a new DSL query */ public static QTableColumnConstraint newQuery() { return new QTableColumnConstraint(); } /** * Returns a DSL data element for property, <b>name</b>. * * @return a DSL data element for property, <b>name</b>. */ public DataProperty name() { return new DataNode(this, TableColumnConstraint.PROPERTY.name.name()); } /** * Returns a DSL data element for property, <b>owner</b>. * * @return a DSL data element for property, <b>owner</b>. */ public DataProperty owner() { return new DataNode(this, TableColumnConstraint.PROPERTY.owner.name()); } /** * Returns a DSL query element for reference property, <b>table</b>. * * @return a DSL query element for reference property, <b>table</b>. */ public QTable table() { return new QTable(this, TableColumnConstraint.PROPERTY.table.name()); } }<|fim▁end|>
}
<|file_name|>colors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # coding:utf-8 from twython import Twython from colors import const #import const import numpy as np import PIL.Image as img import colorsys import StringIO import os from datetime import datetime from datetime import timedelta from random import randint number_of_colours = 1094 def is_morning(): return 6 <= (datetime.utcnow() + timedelta(hours=9)).hour <= 9 class Colour(object): def __init__(self, name, hexcode, url): self.name = name # 0-255 self.hexcode = hexcode self.rgb = tuple( int(hexcode[i:i+2],16) for i in range(0,6,2) ) self.hsv = tuple( colorsys.rgb_to_hsv(*map(lambda x: x/255.0, self.rgb))) self.url = url or "https://en.wikipedia.org/wiki/{}".format( name.replace(' ','_')) @staticmethod def from_string(line): name,code,url = line.strip('\n').split('\t') return Colour(name, code, url) def to_string(self): hsv_to_show = [ int(self.hsv[0]*360+0.5), int(self.hsv[1]*100+0.5), int(self.hsv[2]*100+0.5) ] hsv_str = "({}°, {}%, {}%)".format(*hsv_to_show) text = "{name} [hex:{code}, RGB:{rgb}, HSV:{hsv}] ({link})".format( name=self.name, code=self.hexcode, rgb=self.rgb, hsv=hsv_str, link=self.url) return text def to_image(self, size): colordata = np.array(list(self.rgb)*(size*size), dtype=np.uint8).reshape(size,size,3) colorpic = img.fromarray(colordata) picdata = StringIO.StringIO() colorpic.save(picdata,format='png') picdata.seek(0) return picdata def is_light(self): return self.hsv[2] > 0.5 class ColoursBot(object): def __init__(self, keys=const.keys, size=200, ncolour = number_of_colours, fileloc=os.path.dirname(__file__)+'/colors_simp_with_link.txt'): try: self.api = Twython(keys['api_key'],keys['api_secret'], keys['access_token'], keys['access_token_secret']) except Exception as e: print("An error occured in initialization.\n{}".format(e)) self.ncolour=ncolour self.fileloc=fileloc self.size=size with open(fileloc, 'r') as f: self.colors = list(map(Colour.from_string,f)) def pick_colour(self): if is_morning(): colors = list(filter(lambda c: c.is_light(), self.colors)) else: colors = self.colors n_max = len(colors) return colors[randint(0,n_max-1)] def update(self): c = self.pick_colour()<|fim▁hole|> self.api.update_status_with_media( status=text, media=picdata) return c if __name__ == "__main__": a = ColoursBot() print(a.update())<|fim▁end|>
text = c.to_string() picdata = c.to_image(self.size) # https://twython.readthedocs.org/en/latest/usage/advanced_usage.html
<|file_name|>sps_30.py<|end_file_name|><|fim▁begin|>""" Created on 1 May 2019 @author: Bruno Beloff ([email protected]) https://www.sensirion.com/en/environmental-sensors/particulate-matter-sensors-pm25/ https://bytes.com/topic/python/answers/171354-struct-ieee-754-internal-representation Firmware report: 89667EE8A8B34BC0 """ import time from scs_core.data.datetime import LocalizedDatetime from scs_core.data.datum import Decode, Encode from scs_core.particulate.sps_datum import SPSDatum, SPSDatumCounts from scs_dfe.particulate.opc import OPC from scs_host.bus.i2c import I2C # -------------------------------------------------------------------------------------------------------------------- class SPS30(OPC): """ classdocs """ SOURCE = 'S30' MIN_SAMPLE_PERIOD = 1.0 # seconds MAX_SAMPLE_PERIOD = 10.0 # seconds DEFAULT_SAMPLE_PERIOD = 10.0 # seconds DEFAULT_ADDR = 0x69 # ---------------------------------------------------------------------------------------------------------------- __BOOT_TIME = 4.0 # seconds __POWER_CYCLE_TIME = 2.0 # seconds __FAN_START_TIME = 2.0 # seconds __FAN_STOP_TIME = 2.0 # seconds __CLEANING_TIME = 10.0 # seconds __MAX_PERMITTED_ZERO_READINGS = 4 __CMD_START_MEASUREMENT = 0x0010 __CMD_STOP_MEASUREMENT = 0x0104 __CMD_READ_DATA_READY_FLAG = 0x0202 __CMD_READ_MEASURED_VALUES = 0x0300 __CMD_AUTO_CLEANING_INTERVAL = 0x8004 __CMD_START_FAN_CLEANING = 0x5607 __CMD_READ_ARTICLE_CODE = 0xd025 __CMD_READ_SERIAL_NUMBER = 0xd033 __CMD_RESET = 0xd304 __POST_WRITE_DELAY = 0.020 # seconds __LOCK_TIMEOUT = 2.0 # ---------------------------------------------------------------------------------------------------------------- @classmethod def source(cls): return cls.SOURCE @classmethod def uses_spi(cls): return False @classmethod def datum_class(cls): return SPSDatum # ---------------------------------------------------------------------------------------------------------------- @classmethod def __decode(cls, chars): decoded = [] for i in range(0, len(chars), 3): group = chars[i:i + 2] decoded.extend(group) actual_crc = chars[i + 2] required_crc = cls.__crc(group) if actual_crc != required_crc: raise ValueError("bad checksum: required: 0x%02x actual: 0x%02x" % (required_crc, actual_crc)) return decoded @classmethod def __encode(cls, chars): encoded = [] for i in range(0, len(chars), 2): group = chars[i:i + 2] encoded.extend(group) encoded.append(cls.__crc(group)) return encoded @staticmethod def __crc(data): crc = 0xff for datum in data: crc ^= datum for bit in range(8, 0, -1): crc = ((crc << 1) ^ 0x31 if crc & 0x80 else (crc << 1)) & 0xff return crc # ---------------------------------------------------------------------------------------------------------------- @classmethod def lock_timeout(cls): return cls.__LOCK_TIMEOUT @classmethod def boot_time(cls): return cls.__BOOT_TIME @classmethod def power_cycle_time(cls): return cls.__POWER_CYCLE_TIME @classmethod def max_permitted_zero_readings(cls): return cls.__MAX_PERMITTED_ZERO_READINGS # ---------------------------------------------------------------------------------------------------------------- def __init__(self, interface, i2c_bus, i2c_addr): """ Constructor """ super().__init__(interface) self.__i2c_bus = i2c_bus self.__i2c_addr = i2c_addr # ---------------------------------------------------------------------------------------------------------------- def operations_on(self): self.__write(self.__CMD_START_MEASUREMENT, self.__FAN_START_TIME, 0x03, 0x00) def operations_off(self): self.__read(self.__CMD_STOP_MEASUREMENT, self.__FAN_STOP_TIME) def reset(self): self.__read(self.__CMD_RESET, self.__BOOT_TIME) # ---------------------------------------------------------------------------------------------------------------- def clean(self): self.__read(self.__CMD_START_FAN_CLEANING, self.__CLEANING_TIME) @property def cleaning_interval(self): r = self.__read(self.__CMD_AUTO_CLEANING_INTERVAL, 0, 6) interval = Decode.unsigned_long(r[0:4], '>') return interval @cleaning_interval.setter def cleaning_interval(self, interval): values = Encode.unsigned_long(interval, '>') self.__write(self.__CMD_AUTO_CLEANING_INTERVAL, self.__POST_WRITE_DELAY, *values) # ---------------------------------------------------------------------------------------------------------------- def data_ready(self): chars = self.__read(self.__CMD_READ_DATA_READY_FLAG, 0, 3) return chars[1] == 0x01 def sample(self): r = self.__read(self.__CMD_READ_MEASURED_VALUES, 0, 60) # density... pm1 = Decode.float(r[0:4], '>') pm2p5 = Decode.float(r[4:8], '>') pm4 = Decode.float(r[8:12], '>') pm10 = Decode.float(r[12:16], '>') # count... pm0p5_count = Decode.float(r[16:20], '>') pm1_count = Decode.float(r[20:24], '>') pm2p5_count = Decode.float(r[24:28], '>') pm4_count = Decode.float(r[28:32], '>') pm10_count = Decode.float(r[32:36], '>') # typical size... tps = Decode.float(r[36:40], '>') # time... rec = LocalizedDatetime.now().utc() # report... counts = SPSDatumCounts(pm0p5_count, pm1_count, pm2p5_count, pm4_count, pm10_count) return SPSDatum(self.SOURCE, rec, pm1, pm2p5, pm4, pm10, counts, tps) # ---------------------------------------------------------------------------------------------------------------- def version(self): r = self.__read(self.__CMD_READ_ARTICLE_CODE, 0, 48) version = ''.join(chr(byte) for byte in r) return version def serial_no(self): r = self.__read(self.__CMD_READ_SERIAL_NUMBER, 0, 48) serial_no = ''.join(chr(byte) for byte in r) return serial_no def firmware(self): return self.serial_no() # ---------------------------------------------------------------------------------------------------------------- def get_firmware_conf(self): raise NotImplementedError def set_firmware_conf(self, jdict): raise NotImplementedError def commit_firmware_conf(self): raise NotImplementedError # ---------------------------------------------------------------------------------------------------------------- @property def bus(self): return self.__i2c_bus @property def address(self): return self.__i2c_addr # ---------------------------------------------------------------------------------------------------------------- @property def lock_name(self): return self.__class__.__name__ + '-' + str(self.__i2c_bus) + '-' + ("0x%02x" % self.__i2c_addr) # ---------------------------------------------------------------------------------------------------------------- def __read(self, command, wait, count=0): try: self.obtain_lock() try: I2C.Sensors.start_tx(self.__i2c_addr)<|fim▁hole|> finally: I2C.Sensors.end_tx() time.sleep(wait) return values finally: self.release_lock() def __write(self, command, wait, *values): try: self.obtain_lock() try: I2C.Sensors.start_tx(self.__i2c_addr) encoded = self.__encode(values) I2C.Sensors.write_addr16(command, *encoded) finally: I2C.Sensors.end_tx() time.sleep(wait) finally: self.release_lock() # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return "SPS30:{interface:%s, i2c_bus:%d i2c_addr:0x%02x}" % \ (self.interface, self.__i2c_bus, self.__i2c_addr)<|fim▁end|>
encoded = I2C.Sensors.read_cmd16(command, count) values = self.__decode(encoded)
<|file_name|>info.py<|end_file_name|><|fim▁begin|># Copyright 2013 Daniel Richman # # This file is part of The Snowball Ticketing System. # # The Snowball Ticketing System 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. # # The Snowball Ticketing System 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 The Snowball Ticketing System. If not, see # <http://www.gnu.org/licenses/>. """ Information This package contains utility functions that help produce, and a Flask blueprint containing, the static views (homepage, info about the ball, ...). Further, the :func:`prerender` function may be used to generate the HTML that would have been produced by those views in advance, so it may be served directly without going via Python """ from __future__ import unicode_literals import os import os.path import re import functools import yaml import shutil import flask import flask.json import jinja2 from flask import render_template, request from . import utils __all__ = ["bp", "prerender"] page_filename_re = re.compile(r'^([a-zA-Z_]+)\.html$') data_filename_re = re.compile("^([a-z]+)\.yaml$") logger = utils.getLogger(__name__) #: the :class:`flask.Blueprint` containing info views bp = flask.Blueprint('info', __name__) root_dir = os.path.join(os.path.dirname(__file__), '..') data_dir = os.path.join(root_dir, 'data') templates_dir = os.path.join(root_dir, 'templates') pages_dir = os.path.join(templates_dir, 'theme', 'pages') prerendered_dir = os.path.join(root_dir, 'prerendered') def load_data(data_dir): data = {} for filename in os.listdir(data_dir): key, = data_filename_re.match(filename).groups() with open(os.path.join(data_dir, filename)) as f: data[key] = yaml.safe_load(f) return data def find_pages(pages_dir): for page in os.listdir(pages_dir): match = page_filename_re.match(page) assert match yield match.groups()[0] def setup(bp, pages): for endpoint in pages: if endpoint == 'index': url = "/" else: url = "/" + endpoint.replace("_", "-") template = "theme/pages/{0}.html".format(endpoint) view = functools.partial(render_template, template, **pages_data) bp.add_url_rule(url, endpoint, view) bp.add_app_template_global(pages, 'info_pages') def prerender_pages(app, pages, output_dir): # Note, this assumes that it's OK for url_for to produce # urls rooted at / # Also assumes the blueprint is attached at / # Don't use _external! for filename in os.listdir(output_dir): if filename != '.gitignore': logger.debug("Cleaning %s", filename) os.unlink(os.path.join(output_dir, filename)) else: logger.debug("Keeping .gitignore") with app.test_request_context(): for endpoint in pages: filename = os.path.join(output_dir, endpoint + ".html") template = "theme/pages/{0}.html".format(endpoint) <|fim▁hole|> with open(filename, "w") as f: f.write(render_template(template, **pages_data)) pages = list(find_pages(pages_dir)) pages_data = load_data(data_dir) setup(bp, pages) #: Given an app with `bp` attached, generate static info pages in prerendered/ prerender = functools.partial(prerender_pages, pages=pages, output_dir=prerendered_dir)<|fim▁end|>
logger.debug("Rendering endpoint %r -> %r", endpoint, filename)
<|file_name|>unixccompiler.py<|end_file_name|><|fim▁begin|>"""distutils.unixccompiler Contains the UnixCCompiler class, a subclass of CCompiler that handles the "typical" Unix-style command-line C compiler: * macros defined with -Dname[=value] * macros undefined with -Uname * include search directories specified with -Idir * libraries specified with -lllib * library search directories specified with -Ldir * compile handled by 'cc' (or similar) executable with -c option: compiles .c to .o * link static library handled by 'ar' command (possibly with 'ranlib') * link shared library handled by 'cc -shared' """ import os, sys, re from distutils import sysconfig from distutils.dep_util import newer from distutils.ccompiler import \ CCompiler, gen_preprocess_options, gen_lib_options from distutils.errors import \ DistutilsExecError, CompileError, LibError, LinkError from distutils import log if sys.platform == 'darwin': import _osx_support # XXX Things not currently handled: # * optimization/debug/warning flags; we just use whatever's in Python's # Makefile and live with it. Is this adequate? If not, we might # have to have a bunch of subclasses GNUCCompiler, SGICCompiler, # SunCCompiler, and I suspect down that road lies madness. # * even if we don't know a warning flag from an optimization flag, # we need some way for outsiders to feed preprocessor/compiler/linker # flags in to us -- eg. a sysadmin might want to mandate certain flags # via a site config file, or a user might want to set something for # compiling this module distribution only via the setup.py command # line, whatever. As long as these options come from something on the # current system, they can be as system-dependent as they like, and we # should just happily stuff them into the preprocessor/compiler/linker # options and carry on. class UnixCCompiler(CCompiler): compiler_type = 'unix' # These are used by CCompiler in two places: the constructor sets # instance attributes 'preprocessor', 'compiler', etc. from them, and # 'set_executable()' allows any of these to be set. The defaults here # are pretty generic; they will probably have to be set by an outsider # (eg. using information discovered by the sysconfig about building # Python extensions). executables = {'preprocessor' : None, 'compiler' : ["cc"], 'compiler_so' : ["cc"], 'compiler_cxx' : ["cc"], 'linker_so' : ["cc", "-shared"], 'linker_exe' : ["cc"], 'archiver' : ["ar", "-cr"], 'ranlib' : None, } if sys.platform[:6] == "darwin": executables['ranlib'] = ["ranlib"] # Needed for the filename generation methods provided by the base # class, CCompiler. NB. whoever instantiates/uses a particular # UnixCCompiler instance should set 'shared_lib_ext' -- we set a # reasonable common default here, but it's not necessarily used on all # Unices! src_extensions = [".c",".C",".cc",".cxx",".cpp",".m"] obj_extension = ".o" static_lib_extension = ".a" shared_lib_extension = ".so" dylib_lib_extension = ".dylib" static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s" if sys.platform == "cygwin": exe_extension = ".exe" def preprocess(self, source, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None): fixed_args = self._fix_compile_args(None, macros, include_dirs) ignore, macros, include_dirs = fixed_args pp_opts = gen_preprocess_options(macros, include_dirs) pp_args = self.preprocessor + pp_opts if output_file: pp_args.extend(['-o', output_file]) if extra_preargs: pp_args[:0] = extra_preargs if extra_postargs: pp_args.extend(extra_postargs) pp_args.append(source) # We need to preprocess: either we're being forced to, or we're # generating output to stdout, or there's a target output file and # the source file is newer than the target (or the target doesn't # exist). if self.force or output_file is None or newer(source, output_file): if output_file: self.mkpath(os.path.dirname(output_file)) try: self.spawn(pp_args) except DistutilsExecError as msg: raise CompileError(msg) def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): compiler_so = self.compiler_so if sys.platform == 'darwin': compiler_so = _osx_support.compiler_fixup(compiler_so, cc_args + extra_postargs) try: self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) except DistutilsExecError as msg: raise CompileError(msg) def create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None): objects, output_dir = self._fix_object_args(objects, output_dir) output_filename = \ self.library_filename(output_libname, output_dir=output_dir) if self._need_link(objects, output_filename): self.mkpath(os.path.dirname(output_filename)) self.spawn(self.archiver + [output_filename] + objects + self.objects) # Not many Unices required ranlib anymore -- SunOS 4.x is, I # think the only major Unix that does. Maybe we need some # platform intelligence here to skip ranlib if it's not # needed -- or maybe Python's configure script took care of # it for us, hence the check for leading colon. if self.ranlib: try: self.spawn(self.ranlib + [output_filename]) except DistutilsExecError as msg: raise LibError(msg) else: log.debug("skipping %s (up-to-date)", output_filename) def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): objects, output_dir = self._fix_object_args(objects, output_dir) fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) libraries, library_dirs, runtime_library_dirs = fixed_args lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) if not isinstance(output_dir, (str, type(None))): raise TypeError("'output_dir' must be a string or None") if output_dir is not None: output_filename = os.path.join(output_dir, output_filename) if self._need_link(objects, output_filename): ld_args = (objects + self.objects + lib_opts + ['-o', output_filename]) if debug: ld_args[:0] = ['-g'] if extra_preargs: ld_args[:0] = extra_preargs if extra_postargs: ld_args.extend(extra_postargs) self.mkpath(os.path.dirname(output_filename)) try: if target_desc == CCompiler.EXECUTABLE: linker = self.linker_exe[:] else: linker = self.linker_so[:] if target_lang == "c++" and self.compiler_cxx: # skip over environment variable settings if /usr/bin/env # is used to set up the linker's environment. # This is needed on OSX. Note: this assumes that the # normal and C++ compiler have the same environment # settings. i = 0 if os.path.basename(linker[0]) == "env": i = 1 while '=' in linker[i]: i += 1 linker[i] = self.compiler_cxx[i] if sys.platform == 'darwin': linker = _osx_support.compiler_fixup(linker, ld_args) self.spawn(linker + ld_args) except DistutilsExecError as msg: raise LinkError(msg) else: log.debug("skipping %s (up-to-date)", output_filename) # -- Miscellaneous methods ----------------------------------------- # These are all used by the 'gen_lib_options() function, in # ccompiler.py. def library_dir_option(self, dir): return "-L" + dir def _is_gcc(self, compiler_name): <|fim▁hole|> def runtime_library_dir_option(self, dir): # XXX Hackish, at the very least. See Python bug #445902: # http://sourceforge.net/tracker/index.php # ?func=detail&aid=445902&group_id=5470&atid=105470 # Linkers on different platforms need different options to # specify that directories need to be added to the list of # directories searched for dependencies when a dynamic library # is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to # be told to pass the -R option through to the linker, whereas # other compilers and gcc on other systems just know this. # Other compilers may need something slightly different. At # this time, there's no way to determine this information from # the configuration data stored in the Python installation, so # we use this hack. compiler = os.path.basename(sysconfig.get_config_var("CC")) if sys.platform[:6] == "darwin": # MacOSX's linker doesn't understand the -R flag at all return "-L" + dir elif sys.platform[:5] == "hp-ux": if self._is_gcc(compiler): return ["-Wl,+s", "-L" + dir] return ["+s", "-L" + dir] elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5": return ["-rpath", dir] else: if self._is_gcc(compiler): # gcc on non-GNU systems does not need -Wl, but can # use it anyway. Since distutils has always passed in # -Wl whenever gcc was used in the past it is probably # safest to keep doing so. if sysconfig.get_config_var("GNULD") == "yes": # GNU ld needs an extra option to get a RUNPATH # instead of just an RPATH. return "-Wl,--enable-new-dtags,-R" + dir else: return "-Wl,-R" + dir else: # No idea how --enable-new-dtags would be passed on to # ld if this system was using GNU ld. Don't know if a # system like this even exists. return "-R" + dir def library_option(self, lib): return "-l" + lib def find_library_file(self, dirs, lib, debug=0): shared_f = self.library_filename(lib, lib_type='shared') dylib_f = self.library_filename(lib, lib_type='dylib') static_f = self.library_filename(lib, lib_type='static') if sys.platform == 'darwin': # On OSX users can specify an alternate SDK using # '-isysroot', calculate the SDK root if it is specified # (and use it further on) cflags = sysconfig.get_config_var('CFLAGS') m = re.search(r'-isysroot\s+(\S+)', cflags) if m is None: sysroot = '/' else: sysroot = m.group(1) for dir in dirs: shared = os.path.join(dir, shared_f) dylib = os.path.join(dir, dylib_f) static = os.path.join(dir, static_f) if sys.platform == 'darwin' and ( dir.startswith('/System/') or ( dir.startswith('/usr/') and not dir.startswith('/usr/local/'))): shared = os.path.join(sysroot, dir[1:], shared_f) dylib = os.path.join(sysroot, dir[1:], dylib_f) static = os.path.join(sysroot, dir[1:], static_f) # We're second-guessing the linker here, with not much hard # data to go on: GCC seems to prefer the shared library, so I'm # assuming that *all* Unix C compilers do. And of course I'm # ignoring even GCC's "-static" option. So sue me. if os.path.exists(dylib): return dylib elif os.path.exists(shared): return shared elif os.path.exists(static): return static # Oops, didn't find it in *any* of 'dirs' return None<|fim▁end|>
return "gcc" in compiler_name or "g++" in compiler_name
<|file_name|>folders.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Plugins related to folders and paths """ from hyde.plugin import Plugin from hyde.fs import Folder class FlattenerPlugin(Plugin): """ The plugin class for flattening nested folders. """ def __init__(self, site): super(FlattenerPlugin, self).__init__(site) def begin_site(self): """ Finds all the folders that need flattening and changes the relative deploy path of all resources in those folders. """ items = [] try: items = self.site.config.flattener.items except AttributeError: pass for item in items: node = None target = ''<|fim▁hole|> target = Folder(item.target) except AttributeError: continue if node: for resource in node.walk_resources(): target_path = target.child(resource.name) self.logger.debug( 'Flattening resource path [%s] to [%s]' % (resource, target_path)) resource.relative_deploy_path = target_path<|fim▁end|>
try: node = self.site.content.node_from_relative_path(item.source)
<|file_name|>inheritedConstructorWithRestParams2.js<|end_file_name|><|fim▁begin|>//// [inheritedConstructorWithRestParams2.ts] class IBaseBase<T, U> { constructor(x: U) { } } interface IBase<T, U> extends IBaseBase<T, U> { } class BaseBase2 { constructor(x: number) { } } declare class BaseBase<T, U> extends BaseBase2 implements IBase<T, U> { constructor(x: T, ...y: U[]); constructor(x1: T, x2: T, ...y: U[]); constructor(x1: T, x2: U, y: T); } class Base extends BaseBase<string, number> { } class Derived extends Base { } // Ok new Derived("", ""); new Derived("", 3); new Derived("", 3, 3); new Derived("", 3, 3, 3); new Derived("", 3, ""); new Derived("", "", 3); new Derived("", "", 3, 3); // Errors new Derived(3); new Derived("", 3, "", 3); new Derived("", 3, "", ""); //// [inheritedConstructorWithRestParams2.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var IBaseBase = (function () { function IBaseBase(x) { } return IBaseBase; })(); var BaseBase2 = (function () { function BaseBase2(x) { } return BaseBase2; })(); var Base = (function (_super) { __extends(Base, _super); function Base() { _super.apply(this, arguments); } return Base; })(BaseBase); var Derived = (function (_super) { __extends(Derived, _super); function Derived() { _super.apply(this, arguments); } return Derived; })(Base); // Ok new Derived("", ""); new Derived("", 3); <|fim▁hole|>new Derived("", 3, ""); new Derived("", "", 3); new Derived("", "", 3, 3); // Errors new Derived(3); new Derived("", 3, "", 3); new Derived("", 3, "", "");<|fim▁end|>
new Derived("", 3, 3); new Derived("", 3, 3, 3);
<|file_name|>text.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Specified types for text properties. use cssparser::{Parser, Token}; use parser::{Parse, ParserContext}; use selectors::parser::SelectorParseErrorKind; #[allow(unused_imports)] use std::ascii::AsciiExt; use style_traits::ParseError; use values::computed::{Context, ToComputedValue}; use values::computed::text::LineHeight as ComputedLineHeight; use values::computed::text::TextOverflow as ComputedTextOverflow; use values::generics::text::InitialLetter as GenericInitialLetter; use values::generics::text::LineHeight as GenericLineHeight; use values::generics::text::Spacing; use values::specified::{AllowQuirks, Integer, NonNegativeNumber, Number}; use values::specified::length::{FontRelativeLength, Length, LengthOrPercentage, NoCalcLength}; use values::specified::length::NonNegativeLengthOrPercentage; /// A specified type for the `initial-letter` property. pub type InitialLetter = GenericInitialLetter<Number, Integer>; /// A specified value for the `letter-spacing` property. pub type LetterSpacing = Spacing<Length>; /// A specified value for the `word-spacing` property. pub type WordSpacing = Spacing<LengthOrPercentage>; /// A specified value for the `line-height` property. pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLengthOrPercentage>; impl Parse for InitialLetter { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { if input.try(|i| i.expect_ident_matching("normal")).is_ok() { return Ok(GenericInitialLetter::Normal); } let size = Number::parse_at_least_one(context, input)?; let sink = input.try(|i| Integer::parse_positive(context, i)).ok(); Ok(GenericInitialLetter::Specified(size, sink)) } } impl Parse for LetterSpacing { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Spacing::parse_with(context, input, |c, i| { Length::parse_quirky(c, i, AllowQuirks::Yes) }) } } impl Parse for WordSpacing { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Spacing::parse_with(context, input, |c, i| { LengthOrPercentage::parse_quirky(c, i, AllowQuirks::Yes) }) } } impl Parse for LineHeight { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { if let Ok(number) = input.try(|i| NonNegativeNumber::parse(context, i)) { return Ok(GenericLineHeight::Number(number)) } if let Ok(nlop) = input.try(|i| NonNegativeLengthOrPercentage::parse(context, i)) { return Ok(GenericLineHeight::Length(nlop)) } let location = input.current_source_location(); let ident = input.expect_ident()?; match ident { ref ident if ident.eq_ignore_ascii_case("normal") => { Ok(GenericLineHeight::Normal) }, #[cfg(feature = "gecko")] ref ident if ident.eq_ignore_ascii_case("-moz-block-height") => { Ok(GenericLineHeight::MozBlockHeight) }, ident => Err(location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))), } } } impl ToComputedValue for LineHeight { type ComputedValue = ComputedLineHeight; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { use values::computed::Length as ComputedLength; use values::specified::length::FontBaseSize; match *self { GenericLineHeight::Normal => { GenericLineHeight::Normal }, #[cfg(feature = "gecko")] GenericLineHeight::MozBlockHeight => { GenericLineHeight::MozBlockHeight }, GenericLineHeight::Number(number) => { GenericLineHeight::Number(number.to_computed_value(context)) }, GenericLineHeight::Length(ref non_negative_lop) => { let result = match non_negative_lop.0 { LengthOrPercentage::Length(NoCalcLength::Absolute(ref abs)) => { context.maybe_zoom_text(abs.to_computed_value(context).into()).0 } LengthOrPercentage::Length(ref length) => { length.to_computed_value(context) }, LengthOrPercentage::Percentage(ref p) => { FontRelativeLength::Em(p.0) .to_computed_value( context, FontBaseSize::CurrentStyle, ) } LengthOrPercentage::Calc(ref calc) => { let computed_calc = calc.to_computed_value_zoomed(context, FontBaseSize::CurrentStyle); let font_relative_length = FontRelativeLength::Em(computed_calc.percentage()) .to_computed_value( context, FontBaseSize::CurrentStyle, ).px(); let absolute_length = computed_calc.unclamped_length().px(); let pixel = computed_calc .clamping_mode .clamp(absolute_length + font_relative_length); ComputedLength::new(pixel) } }; GenericLineHeight::Length(result.into()) } } } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { match *computed {<|fim▁hole|> GenericLineHeight::Normal }, #[cfg(feature = "gecko")] GenericLineHeight::MozBlockHeight => { GenericLineHeight::MozBlockHeight }, GenericLineHeight::Number(ref number) => { GenericLineHeight::Number(NonNegativeNumber::from_computed_value(number)) }, GenericLineHeight::Length(ref length) => { GenericLineHeight::Length(NoCalcLength::from_computed_value(&length.0).into()) } } } } /// A generic value for the `text-overflow` property. #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)] pub enum TextOverflowSide { /// Clip inline content. Clip, /// Render ellipsis to represent clipped inline content. Ellipsis, /// Render a given string to represent clipped inline content. String(Box<str>), } impl Parse for TextOverflowSide { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<TextOverflowSide, ParseError<'i>> { let location = input.current_source_location(); match *input.next()? { Token::Ident(ref ident) => { match_ignore_ascii_case! { ident, "clip" => Ok(TextOverflowSide::Clip), "ellipsis" => Ok(TextOverflowSide::Ellipsis), _ => Err(location.new_custom_error( SelectorParseErrorKind::UnexpectedIdent(ident.clone()) )) } } Token::QuotedString(ref v) => { Ok(TextOverflowSide::String(v.as_ref().to_owned().into_boxed_str())) } ref t => Err(location.new_unexpected_token_error(t.clone())), } } } #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)] /// text-overflow. Specifies rendering when inline content overflows its line box edge. pub struct TextOverflow { /// First value. Applies to end line box edge if no second is supplied; line-left edge otherwise. pub first: TextOverflowSide, /// Second value. Applies to the line-right edge if supplied. pub second: Option<TextOverflowSide>, } impl Parse for TextOverflow { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<TextOverflow, ParseError<'i>> { let first = TextOverflowSide::parse(context, input)?; let second = input.try(|input| TextOverflowSide::parse(context, input)).ok(); Ok(TextOverflow { first, second }) } } impl ToComputedValue for TextOverflow { type ComputedValue = ComputedTextOverflow; #[inline] fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue { if let Some(ref second) = self.second { Self::ComputedValue { first: self.first.clone(), second: second.clone(), sides_are_logical: false, } } else { Self::ComputedValue { first: TextOverflowSide::Clip, second: self.first.clone(), sides_are_logical: true, } } } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { if computed.sides_are_logical { assert!(computed.first == TextOverflowSide::Clip); TextOverflow { first: computed.second.clone(), second: None, } } else { TextOverflow { first: computed.first.clone(), second: Some(computed.second.clone()), } } } }<|fim▁end|>
GenericLineHeight::Normal => {
<|file_name|>test_user_avatar.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import import six from base64 import b64encode from django.core.urlresolvers import reverse from sentry.models import UserAvatar from sentry.testutils import APITestCase class UserAvatarTest(APITestCase): def test_get(self): user = self.create_user(email='[email protected]') self.login_as(user=user) url = reverse('sentry-api-0-user-avatar', kwargs={ 'user_id': 'me', }) response = self.client.get(url, format='json') assert response.status_code == 200, response.content assert response.data['id'] == six.text_type(user.id) assert response.data['avatar']['avatarType'] == 'letter_avatar' assert response.data['avatar']['avatarUuid'] is None def test_gravatar(self): user = self.create_user(email='[email protected]') self.login_as(user=user) url = reverse('sentry-api-0-user-avatar', kwargs={ 'user_id': 'me', }) response = self.client.put(url, data={'avatar_type': 'gravatar'}, format='json') avatar = UserAvatar.objects.get(user=user) assert response.status_code == 200, response.content assert avatar.get_avatar_type_display() == 'gravatar' def test_upload(self): user = self.create_user(email='[email protected]') self.login_as(user=user)<|fim▁hole|> 'user_id': 'me', }) response = self.client.put(url, data={ 'avatar_type': 'upload', 'avatar_photo': b64encode(self.load_fixture('avatar.jpg')), }, format='json') avatar = UserAvatar.objects.get(user=user) assert response.status_code == 200, response.content assert avatar.get_avatar_type_display() == 'upload' assert avatar.file def test_put_bad(self): user = self.create_user(email='[email protected]') UserAvatar.objects.create(user=user) self.login_as(user=user) url = reverse('sentry-api-0-user-avatar', kwargs={ 'user_id': 'me', }) response = self.client.put(url, data={'avatar_type': 'upload'}, format='json') avatar = UserAvatar.objects.get(user=user) assert response.status_code == 400 assert avatar.get_avatar_type_display() == 'letter_avatar' response = self.client.put(url, data={'avatar_type': 'foo'}, format='json') assert response.status_code == 400 assert avatar.get_avatar_type_display() == 'letter_avatar' def test_put_forbidden(self): user = self.create_user(email='[email protected]') user2 = self.create_user(email='[email protected]') self.login_as(user=user) url = reverse('sentry-api-0-user-avatar', kwargs={ 'user_id': user2.id, }) response = self.client.put(url, data={'avatar_type': 'gravatar'}, format='json') assert response.status_code == 403<|fim▁end|>
url = reverse('sentry-api-0-user-avatar', kwargs={
<|file_name|>feed_parse_extractDhragonisslytherinWordpressCom.py<|end_file_name|><|fim▁begin|>def extractDhragonisslytherinWordpressCom(item): ''' Parser for 'dhragonisslytherin.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None<|fim▁hole|> ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False<|fim▁end|>
tagmap = [
<|file_name|>cli.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node 'use strict'; const fs = require('fs'); const repl = require('repl'); const program = require('commander'); const esper = require('..'); const Engine = esper.Engine; function enterRepl() { function replEval(cmd, context, fn, cb) { engine.evalDetatched(cmd).then(function(result) { cb(null, result); }, function(err) { console.log(err.stack); cb(null); }); } return repl.start({ prompt: 'js> ', eval: replEval }); } program .version(esper.version) .usage('[options] [script...]') .option('-v, --version', 'print esper version') .option('-i, --interactive', 'enter REPL') .option('-s, --strict', 'force strict mode') .option('-d, --debug', 'turn on performance debugging') .option('-c, --compile <mode>', 'set compileing mode') .option('-e, --eval <script>', 'evaluate script') .option('-p, --print <script>', 'evaluate script and print result') .option('-l, --language <language>', `set langauge (${Object.keys(esper.languages).join(', ')})`) .parse(process.argv); if ( program.language ) esper.plugin('lang-' + program.language); if ( program.v ) { console.log("v" + esper.version); process.exit(); } let engine = new Engine({ strict: !!program.strict, debug: !!program.debug, runtime: true, addInternalStack: !!program.debug, compile: program.compile || 'pre', language: program.language || 'javascript', esposeESHostGlobal: true, esRealms: true, }); let toEval = program.args.slice(0).map((f) => ({type: 'file', value: f})); if ( program.eval ) toEval.push({type: 'str', value: program.eval + '\n'}); if ( program.print ) toEval.push({type: 'str', value: program.print + '\n', print: true}); if ( toEval.length < 1 ) program.interactive = true; function next() { if ( toEval.length === 0 ) { if ( program.interactive ) return enterRepl(); else return process.exit(); } var fn = toEval.shift(); var code; if ( fn.type === 'file' ) { code = fs.readFileSync(fn.value, 'utf8'); } else { code = fn.value; } return engine.evalDetatched(code).then(function(val) { if ( fn.print && val ) console.log(val.debugString); return next(); }).catch(function(e) { if ( e.stack ) { process.stderr.write(e.stack + "\n"); } else { process.stderr.write(`${e.name}: ${e.message}\n`); } }); } next(); /* Usage: node [options] [ -e script | script.js ] [arguments] node debug script.js [arguments] Options: -v, --version print Node.js version -e, --eval script evaluate script<|fim▁hole|> -r, --require module to preload (option can be repeated) --no-deprecation silence deprecation warnings --throw-deprecation throw an exception anytime a deprecated function is used --trace-deprecation show stack traces on deprecations --trace-sync-io show stack trace when use of sync IO is detected after the first tick --track-heap-objects track heap object allocations for heap snapshots --v8-options print v8 command line options --tls-cipher-list=val use an alternative default TLS cipher list --icu-data-dir=dir set ICU data load path to dir (overrides NODE_ICU_DATA) Environment variables: NODE_PATH ':'-separated list of directories prefixed to the module search path. NODE_DISABLE_COLORS set to 1 to disable colors in the REPL NODE_ICU_DATA data path for ICU (Intl object) data NODE_REPL_HISTORY path to the persistent REPL history file Documentation can be found at https://nodejs.org/ */<|fim▁end|>
-p, --print evaluate script and print result -c, --check syntax check script without executing -i, --interactive always enter the REPL even if stdin does not appear to be a terminal
<|file_name|>ToonidoApp.java<|end_file_name|><|fim▁begin|>package app.toonido.mindorks.toonido; import android.app.Application; import com.parse.Parse; /** * Created by janisharali on 30/09/15. */ public class ToonidoApp extends Application { @Override public void onCreate() { super.onCreate(); // Enable Local Datastore. Parse.enableLocalDatastore(this);<|fim▁hole|>}<|fim▁end|>
Parse.initialize(this, ToonidoConstants.PARSE_APPLICATION_ID, ToonidoConstants.PARSE_CLIENT_KEY); }
<|file_name|>insc.py<|end_file_name|><|fim▁begin|># coding: utf-8 if DefLANG in ("RU", "UA"): AnsBase_temp = tuple([line.decode("utf-8") for line in ( "\nВсего входов - %d\nВремя последнего входа - %s\nПоследняя роль - %s", # 0 "\nВремя последнего выхода - %s\nПричина выхода - %s", # 1 "\nНики: %s", # 2 "Нет статистики.", # 3 "«%s» сидит здесь - %s.", # 4 "Ты провёл здесь - %s.", # 5 "Здесь нет такого юзера." # 6 )]) else: AnsBase_temp = ( "\nTotal joins - %d\nThe Last join-time - %s\nThe last role - %s", # 0 "\nThe last leave-time - %s\nExit reason - %s", # 1 "\nNicks: %s", # 2 "No statistics.", # 3<|fim▁hole|><|fim▁end|>
"'%s' spent here - %s.", # 4 "You spent here - %s.", # 5 "No such user here." # 6 )
<|file_name|>_postgres_builtins.py<|end_file_name|><|fim▁begin|>""" pygments.lexers._postgres_builtins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Self-updating data files for PostgreSQL lexer. :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ # Autogenerated: please edit them if you like wasting your time. KEYWORDS = ( 'ABORT', 'ABSOLUTE', 'ACCESS', 'ACTION', 'ADD', 'ADMIN', 'AFTER', 'AGGREGATE', 'ALL', 'ALSO', 'ALTER', 'ALWAYS', 'ANALYSE', 'ANALYZE', 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASSERTION', 'ASSIGNMENT', 'ASYMMETRIC', 'AT', 'ATTACH', 'ATTRIBUTE', 'AUTHORIZATION', 'BACKWARD', 'BEFORE', 'BEGIN', 'BETWEEN', 'BIGINT', 'BINARY', 'BIT', 'BOOLEAN', 'BOTH', 'BY', 'CACHE', 'CALL', 'CALLED', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAIN', 'CHAR', 'CHARACTER', 'CHARACTERISTICS', 'CHECK', 'CHECKPOINT', 'CLASS', 'CLOSE', 'CLUSTER', 'COALESCE', 'COLLATE', 'COLLATION', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMENTS', 'COMMIT', 'COMMITTED', 'CONCURRENTLY', 'CONFIGURATION', 'CONFLICT', 'CONNECTION', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENT', 'CONTINUE', 'CONVERSION', 'COPY', 'COST', 'CREATE', 'CROSS', 'CSV', 'CUBE', 'CURRENT', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'CYCLE', 'DATA', 'DATABASE', 'DAY', 'DEALLOCATE', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFAULTS', 'DEFERRABLE', 'DEFERRED', 'DEFINER', 'DELETE', 'DELIMITER', 'DELIMITERS', 'DEPENDS', 'DESC', 'DETACH', 'DICTIONARY', 'DISABLE', 'DISCARD', 'DISTINCT', 'DO', 'DOCUMENT', 'DOMAIN', 'DOUBLE', 'DROP', 'EACH', 'ELSE', 'ENABLE', 'ENCODING', 'ENCRYPTED', 'END', 'ENUM', 'ESCAPE', 'EVENT', 'EXCEPT', 'EXCLUDE', 'EXCLUDING', 'EXCLUSIVE', 'EXECUTE', 'EXISTS', 'EXPLAIN', 'EXPRESSION', 'EXTENSION', 'EXTERNAL', 'EXTRACT', 'FALSE', 'FAMILY', 'FETCH', 'FILTER', 'FIRST', 'FLOAT', 'FOLLOWING', 'FOR', 'FORCE', 'FOREIGN', 'FORWARD', 'FREEZE', 'FROM', 'FULL', 'FUNCTION', 'FUNCTIONS', 'GENERATED', 'GLOBAL', 'GRANT', 'GRANTED', 'GREATEST', 'GROUP', 'GROUPING', 'GROUPS', 'HANDLER', 'HAVING', 'HEADER', 'HOLD', 'HOUR', 'IDENTITY', 'IF', 'ILIKE', 'IMMEDIATE', 'IMMUTABLE', 'IMPLICIT', 'IMPORT', 'IN', 'INCLUDE', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDEXES', 'INHERIT', 'INHERITS', 'INITIALLY', 'INLINE', 'INNER', 'INOUT', 'INPUT', 'INSENSITIVE', 'INSERT', 'INSTEAD', 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'INVOKER', 'IS', 'ISNULL', 'ISOLATION', 'JOIN', 'KEY', 'LABEL', 'LANGUAGE', 'LARGE', 'LAST', 'LATERAL', 'LEADING', 'LEAKPROOF', 'LEAST', 'LEFT', 'LEVEL', 'LIKE', 'LIMIT', 'LISTEN', 'LOAD', 'LOCAL', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATION', 'LOCK', 'LOCKED', 'LOGGED', 'MAPPING', 'MATCH', 'MATERIALIZED', 'MAXVALUE', 'METHOD', 'MINUTE', 'MINVALUE', 'MODE', 'MONTH', 'MOVE', 'NAME', 'NAMES', 'NATIONAL', 'NATURAL', 'NCHAR', 'NEW', 'NEXT', 'NFC', 'NFD', 'NFKC', 'NFKD', 'NO', 'NONE', 'NORMALIZE', 'NORMALIZED', 'NOT', 'NOTHING', 'NOTIFY', 'NOTNULL', 'NOWAIT', 'NULL', 'NULLIF', 'NULLS', 'NUMERIC', 'OBJECT', 'OF', 'OFF', 'OFFSET', 'OIDS', 'OLD', 'ON', 'ONLY', 'OPERATOR', 'OPTION', 'OPTIONS', 'OR', 'ORDER', 'ORDINALITY', 'OTHERS', 'OUT', 'OUTER', 'OVER', 'OVERLAPS', 'OVERLAY', 'OVERRIDING', 'OWNED', 'OWNER', 'PARALLEL', 'PARSER', 'PARTIAL', 'PARTITION', 'PASSING', 'PASSWORD', 'PLACING', 'PLANS', 'POLICY', 'POSITION', 'PRECEDING', 'PRECISION', 'PREPARE', 'PREPARED', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVILEGES', 'PROCEDURAL', 'PROCEDURE', 'PROCEDURES', 'PROGRAM', 'PUBLICATION',<|fim▁hole|> 'RANGE', 'READ', 'REAL', 'REASSIGN', 'RECHECK', 'RECURSIVE', 'REF', 'REFERENCES', 'REFERENCING', 'REFRESH', 'REINDEX', 'RELATIVE', 'RELEASE', 'RENAME', 'REPEATABLE', 'REPLACE', 'REPLICA', 'RESET', 'RESTART', 'RESTRICT', 'RETURNING', 'RETURNS', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE', 'ROUTINES', 'ROW', 'ROWS', 'RULE', 'SAVEPOINT', 'SCHEMA', 'SCHEMAS', 'SCROLL', 'SEARCH', 'SECOND', 'SECURITY', 'SELECT', 'SEQUENCE', 'SEQUENCES', 'SERIALIZABLE', 'SERVER', 'SESSION', 'SESSION_USER', 'SET', 'SETOF', 'SETS', 'SHARE', 'SHOW', 'SIMILAR', 'SIMPLE', 'SKIP', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SQL', 'STABLE', 'STANDALONE', 'START', 'STATEMENT', 'STATISTICS', 'STDIN', 'STDOUT', 'STORAGE', 'STORED', 'STRICT', 'STRIP', 'SUBSCRIPTION', 'SUBSTRING', 'SUPPORT', 'SYMMETRIC', 'SYSID', 'SYSTEM', 'TABLE', 'TABLES', 'TABLESAMPLE', 'TABLESPACE', 'TEMP', 'TEMPLATE', 'TEMPORARY', 'TEXT', 'THEN', 'TIES', 'TIME', 'TIMESTAMP', 'TO', 'TRAILING', 'TRANSACTION', 'TRANSFORM', 'TREAT', 'TRIGGER', 'TRIM', 'TRUE', 'TRUNCATE', 'TRUSTED', 'TYPE', 'TYPES', 'UESCAPE', 'UNBOUNDED', 'UNCOMMITTED', 'UNENCRYPTED', 'UNION', 'UNIQUE', 'UNKNOWN', 'UNLISTEN', 'UNLOGGED', 'UNTIL', 'UPDATE', 'USER', 'USING', 'VACUUM', 'VALID', 'VALIDATE', 'VALIDATOR', 'VALUE', 'VALUES', 'VARCHAR', 'VARIADIC', 'VARYING', 'VERBOSE', 'VERSION', 'VIEW', 'VIEWS', 'VOLATILE', 'WHEN', 'WHERE', 'WHITESPACE', 'WINDOW', 'WITH', 'WITHIN', 'WITHOUT', 'WORK', 'WRAPPER', 'WRITE', 'XML', 'XMLATTRIBUTES', 'XMLCONCAT', 'XMLELEMENT', 'XMLEXISTS', 'XMLFOREST', 'XMLNAMESPACES', 'XMLPARSE', 'XMLPI', 'XMLROOT', 'XMLSERIALIZE', 'XMLTABLE', 'YEAR', 'YES', 'ZONE', ) DATATYPES = ( 'bigint', 'bigserial', 'bit', 'bit varying', 'bool', 'boolean', 'box', 'bytea', 'char', 'character', 'character varying', 'cidr', 'circle', 'date', 'decimal', 'double precision', 'float4', 'float8', 'inet', 'int', 'int2', 'int4', 'int8', 'integer', 'interval', 'json', 'jsonb', 'line', 'lseg', 'macaddr', 'macaddr8', 'money', 'numeric', 'path', 'pg_lsn', 'pg_snapshot', 'point', 'polygon', 'real', 'serial', 'serial2', 'serial4', 'serial8', 'smallint', 'smallserial', 'text', 'time', 'timestamp', 'timestamptz', 'timetz', 'tsquery', 'tsvector', 'txid_snapshot', 'uuid', 'varbit', 'varchar', 'with time zone', 'without time zone', 'xml', ) PSEUDO_TYPES = ( 'any', 'anyarray', 'anycompatible', 'anycompatiblearray', 'anycompatiblenonarray', 'anycompatiblerange', 'anyelement', 'anyenum', 'anynonarray', 'anyrange', 'cstring', 'event_trigger', 'fdw_handler', 'index_am_handler', 'internal', 'language_handler', 'pg_ddl_command', 'record', 'table_am_handler', 'trigger', 'tsm_handler', 'unknown', 'void', ) # Remove 'trigger' from types PSEUDO_TYPES = tuple(sorted(set(PSEUDO_TYPES) - set(map(str.lower, KEYWORDS)))) PLPGSQL_KEYWORDS = ( 'ALIAS', 'CONSTANT', 'DIAGNOSTICS', 'ELSIF', 'EXCEPTION', 'EXIT', 'FOREACH', 'GET', 'LOOP', 'NOTICE', 'OPEN', 'PERFORM', 'QUERY', 'RAISE', 'RETURN', 'REVERSE', 'SQLSTATE', 'WHILE', ) if __name__ == '__main__': # pragma: no cover import re try: from urllib import urlopen except ImportError: from urllib.request import urlopen from pygments.util import format_lines # One man's constant is another man's variable. SOURCE_URL = 'https://github.com/postgres/postgres/raw/master' KEYWORDS_URL = SOURCE_URL + '/src/include/parser/kwlist.h' DATATYPES_URL = SOURCE_URL + '/doc/src/sgml/datatype.sgml' def update_myself(): content = urlopen(DATATYPES_URL).read().decode('utf-8', errors='ignore') data_file = list(content.splitlines()) datatypes = parse_datatypes(data_file) pseudos = parse_pseudos(data_file) content = urlopen(KEYWORDS_URL).read().decode('utf-8', errors='ignore') keywords = parse_keywords(content) update_consts(__file__, 'DATATYPES', datatypes) update_consts(__file__, 'PSEUDO_TYPES', pseudos) update_consts(__file__, 'KEYWORDS', keywords) def parse_keywords(f): kw = [] for m in re.finditer(r'PG_KEYWORD\("(.+?)"', f): kw.append(m.group(1).upper()) if not kw: raise ValueError('no keyword found') kw.sort() return kw def parse_datatypes(f): dt = set() for line in f: if '<sect1' in line: break if '<entry><type>' not in line: continue # Parse a string such as # time [ (<replaceable>p</replaceable>) ] [ without time zone ] # into types "time" and "without time zone" # remove all the tags line = re.sub("<replaceable>[^<]+</replaceable>", "", line) line = re.sub("<[^>]+>", "", line) # Drop the parts containing braces for tmp in [t for tmp in line.split('[') for t in tmp.split(']') if "(" not in t]: for t in tmp.split(','): t = t.strip() if not t: continue dt.add(" ".join(t.split())) dt = list(dt) dt.sort() return dt def parse_pseudos(f): dt = [] re_start = re.compile(r'\s*<table id="datatype-pseudotypes-table">') re_entry = re.compile(r'\s*<entry><type>(.+?)</type></entry>') re_end = re.compile(r'\s*</table>') f = iter(f) for line in f: if re_start.match(line) is not None: break else: raise ValueError('pseudo datatypes table not found') for line in f: m = re_entry.match(line) if m is not None: dt.append(m.group(1)) if re_end.match(line) is not None: break else: raise ValueError('end of pseudo datatypes table not found') if not dt: raise ValueError('pseudo datatypes not found') dt.sort() return dt def update_consts(filename, constname, content): with open(filename) as f: data = f.read() # Line to start/end inserting re_match = re.compile(r'^%s\s*=\s*\($.*?^\s*\)$' % constname, re.M | re.S) m = re_match.search(data) if not m: raise ValueError('Could not find existing definition for %s' % (constname,)) new_block = format_lines(constname, content) data = data[:m.start()] + new_block + data[m.end():] with open(filename, 'w', newline='\n') as f: f.write(data) update_myself()<|fim▁end|>
'QUOTE',
<|file_name|>fabrics.go<|end_file_name|><|fim▁begin|>// // Copyright (c) 2018, Joyent, Inc. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // package network import ( "context" "encoding/json" "net/http" "path" "strconv" "github.com/joyent/triton-go/client" "github.com/pkg/errors" ) type FabricsClient struct { client *client.Client } type FabricVLAN struct { Name string `json:"name"` ID int `json:"vlan_id"` Description string `json:"description"` } type ListVLANsInput struct{} func (c *FabricsClient) ListVLANs(ctx context.Context, _ *ListVLANsInput) ([]*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans") reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to list VLANs") } var result []*FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode list VLANs response") } return result, nil } type CreateVLANInput struct { Name string `json:"name"` ID int `json:"vlan_id"` Description string `json:"description,omitempty"` } func (c *FabricsClient) CreateVLAN(ctx context.Context, input *CreateVLANInput) (*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans") reqInputs := client.RequestInput{ Method: http.MethodPost, Path: fullPath, Body: input, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to create VLAN") } var result *FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode create VLAN response") } return result, nil } type UpdateVLANInput struct { ID int `json:"-"` Name string `json:"name"` Description string `json:"description"` } func (c *FabricsClient) UpdateVLAN(ctx context.Context, input *UpdateVLANInput) (*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID)) reqInputs := client.RequestInput{ Method: http.MethodPut, Path: fullPath, Body: input, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to update VLAN") } var result *FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode update VLAN response") } return result, nil } type GetVLANInput struct { ID int `json:"-"` } func (c *FabricsClient) GetVLAN(ctx context.Context, input *GetVLANInput) (*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID)) reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to get VLAN") } var result *FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode get VLAN response") } return result, nil } type DeleteVLANInput struct { ID int `json:"-"` } func (c *FabricsClient) DeleteVLAN(ctx context.Context, input *DeleteVLANInput) error { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID)) reqInputs := client.RequestInput{ Method: http.MethodDelete, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return errors.Wrap(err, "unable to delete VLAN") } return nil } type ListFabricsInput struct { FabricVLANID int `json:"-"` } func (c *FabricsClient) List(ctx context.Context, input *ListFabricsInput) ([]*Network, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks") reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() }<|fim▁hole|> return nil, errors.Wrap(err, "unable to list fabrics") } var result []*Network decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode list fabrics response") } return result, nil } type CreateFabricInput struct { FabricVLANID int `json:"-"` Name string `json:"name"` Description string `json:"description,omitempty"` Subnet string `json:"subnet"` ProvisionStartIP string `json:"provision_start_ip"` ProvisionEndIP string `json:"provision_end_ip"` Gateway string `json:"gateway,omitempty"` Resolvers []string `json:"resolvers,omitempty"` Routes map[string]string `json:"routes,omitempty"` InternetNAT bool `json:"internet_nat"` } func (c *FabricsClient) Create(ctx context.Context, input *CreateFabricInput) (*Network, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks") reqInputs := client.RequestInput{ Method: http.MethodPost, Path: fullPath, Body: input, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to create fabric") } var result *Network decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode create fabric response") } return result, nil } type GetFabricInput struct { FabricVLANID int `json:"-"` NetworkID string `json:"-"` } func (c *FabricsClient) Get(ctx context.Context, input *GetFabricInput) (*Network, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID) reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to get fabric") } var result *Network decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode get fabric response") } return result, nil } type DeleteFabricInput struct { FabricVLANID int `json:"-"` NetworkID string `json:"-"` } func (c *FabricsClient) Delete(ctx context.Context, input *DeleteFabricInput) error { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID) reqInputs := client.RequestInput{ Method: http.MethodDelete, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return errors.Wrap(err, "unable to delete fabric") } return nil }<|fim▁end|>
if err != nil {
<|file_name|>car_factory.rs<|end_file_name|><|fim▁begin|>use super::car_type::{Body, CarType, Colour}; pub struct CarFactory { car_types: Vec<CarType>, } impl CarFactory { pub fn new() -> CarFactory {<|fim▁hole|> pub fn get_car_type_id(&mut self, body: Body, colour: Colour) -> u8 { let position = self.car_types .iter() .position(|ref r| r.body == body && r.colour == colour); match position { Some(x) => x as u8, None => { let car_type = CarType::new(body, colour); self.car_types.push(car_type); (self.car_types.len() - 1) as u8 } } } pub fn get_car_type(&mut self, id: u8) -> Option<&CarType> { self.car_types.get(id as usize) } pub fn print(&self) { println!("Number of car types: {}", self.car_types.len()); } }<|fim▁end|>
CarFactory { car_types: Vec::new(), } }
<|file_name|>BarChartDemoWebPart.ts<|end_file_name|><|fim▁begin|>import * as React from 'react'; import * as ReactDom from 'react-dom'; import * as strings from 'BarChartDemoWebPartStrings'; import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, } from '@microsoft/sp-webpart-base'; import { PropertyPaneWebPartInformation } from '@pnp/spfx-property-controls/lib/PropertyPaneWebPartInformation'; import BarChartDemo from './components/BarChartDemo'; import { IBarChartDemoProps } from './components/IBarChartDemo.types';<|fim▁hole|> description: string; } /** * This web part retrieves data asynchronously and renders a bar chart once loaded * It mimics a "real-life" scenario by loading (random) data asynchronously * and rendering the chart once the data has been retrieved. * To keep the demo simple, we don't specify custom colors. */ export default class BarChartDemoWebPart extends BaseClientSideWebPart<IBarChartDemoWebPartProps> { public render(): void { const element: React.ReactElement<IBarChartDemoProps > = React.createElement( BarChartDemo, { // there are no properties to pass for this demo } ); ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { groups: [ { groupFields: [ PropertyPaneWebPartInformation({ description: strings.WebPartDescription, moreInfoLink: strings.MoreInfoLinkUrl, key: 'webPartInfoId' }) ] } ] } ] }; } }<|fim▁end|>
export interface IBarChartDemoWebPartProps {
<|file_name|>test_i3wm-formula.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_i3wm-formula ---------------------------------- Tests for `i3wm-formula` module. """ import unittest from i3wm-formula import i3wm-formula class TestI3wm-formula(unittest.TestCase): def setUp(self): pass<|fim▁hole|> def test_something(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>KangXiZiDian-djvu2tiff.py<|end_file_name|><|fim▁begin|># This tool convert KangXiZiDian djvu files to tiff files. # Download djvu files: http://bbs.dartmouth.edu/~fangq/KangXi/KangXi.tar # Character page info: http://wenq.org/unihan/Unihan.txt as kIRGKangXi field. # Character seek position in Unihan.txt http://wenq.org/unihan/unihandata.txt # DjVuLibre package provides the ddjvu tool. # The 410 page is bad, but it should be blank page in fact. so just remove 410.tif <|fim▁hole|> pages = list(range(1, 1683+1)) for i in pages: page = str(i) print(page) os.system("ddjvu -format=tiff -page="+ page + " -scale=100 -quality=150 KangXiZiDian.djvu"+ " tif/" + page + ".tif")<|fim▁end|>
import os if __name__ == "__main__": os.system("mkdir tif")
<|file_name|>neoip_upnp_call_addport.hpp<|end_file_name|><|fim▁begin|>/*! \file \brief Declaration of the upnp_call_addport_t */ #ifndef __NEOIP_UPNP_CALL_ADDPORT_HPP__ #define __NEOIP_UPNP_CALL_ADDPORT_HPP__ /* system include */ /* local include */ #include "neoip_upnp_call_addport_cb.hpp" #include "neoip_upnp_call_cb.hpp" #include "neoip_tokeep_check.hpp" #include "neoip_copy_ctor_checker.hpp" #include "neoip_namespace.hpp" NEOIP_NAMESPACE_BEGIN // list of forward declaration class upnp_disc_res_t; class upnp_call_profile_t; class upnp_sockfam_t; class delay_t; /** \brief handle the listener of the nslan */ class upnp_call_addport_t : NEOIP_COPY_CTOR_DENY, private upnp_call_cb_t { private: /*************** upnp_call_t ***************************************/ upnp_call_t * upnp_call; bool neoip_upnp_call_cb(void *cb_userptr, upnp_call_t &cb_call, const upnp_err_t &upnp_err , const strvar_db_t &replied_var) throw(); /*************** callback stuff ***************************************/ upnp_call_addport_cb_t *callback; //!< callback used to notify result void * userptr; //!< userptr associated with the callback bool notify_callback(const upnp_err_t &upnp_err) throw(); TOKEEP_CHECK_DECL_DFL(); //!< used to sanity check the 'tokeep' value returned by callback public: /*************** ctor/dtor ***************************************/ upnp_call_addport_t() throw(); ~upnp_call_addport_t() throw(); /*************** setup function ***************************************/ upnp_call_addport_t &set_profile(const upnp_call_profile_t &profile) throw(); <|fim▁hole|> , upnp_call_addport_cb_t *callback, void * userptr) throw(); }; NEOIP_NAMESPACE_END #endif // __NEOIP_UPNP_CALL_ADDPORT_HPP__<|fim▁end|>
upnp_err_t start(const upnp_disc_res_t &disc_res, uint16_t port_pview, uint16_t port_lview , const upnp_sockfam_t &sock_fam, const delay_t &lease_delay , const std::string &description_str
<|file_name|>AvgCacheCalc.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # This file is part of the pebil project. # # Copyright (c) 2010, University of California Regents # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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/>. # # Counter for a folder # /pmaclabs/icepic/ti10_round1_icepic_large_0256/processed_trace # Executable: # AvgCacheCalc.py # # This will calculate the Average of Cache hits for a series of processed metasim files. # # # Usage: # # A number of arguments are needed. The arguments determine how to select the set of files to process # and whether to compute the average across all files or not. # # Either sysid or taskid is required # sysid - calculates a single average for all files with the same sysid # - use with --sysid option to speciy which sysid to use. # - for file icepic_large_0256_0127.sysid44, the sysid is 44 # # taskid - prints an average for each file with the same task id (ie 1 set of averages for for each sysid found) # - use with --taskid option to specify the task id # - for file icepic_large_0256_0127.sysid44, the taskid is 0127 # # # app icepic,hycom,..." # dataset large, standard..." # cpu_count 256,1024,... input will be padded with 0s to 4 digits # Optional: # dir - current dir is used if these argument is not given # As an example take the folder: # /pmaclabs/ti10/ti10_round1_icepic_large_0256/processed_trace # # # SysID mode: #mattl@trebek[21]$ ./AvgCacheCalc.py --app icepic --dataset large --cpu_count 1024 --sysid 99 --dir /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # # # Reading files from: /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # Averaging for all files like icepic_large_1024*.sysid99 # Number of files: 1024 # Cache 1 average %= 98.365459015 incl(98.365459015) # Cache 2 average %= 0.000974823792366 incl(98.3654743948) # Cache 3 average %= 0.0 incl(98.3654743948) # # # TaskID: # mattl@trebek[20]$ ./AvgCacheCalc.py --app icepic --dataset large --cpu_count 1024 --taskid 125 --dir /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # # Reading files from: /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # Averaging for all files like icepic_large_1024_0125* # Number of files: 32 # sysid0 99.5021899287 # sysid3 98.3544410843 98.4873748354 # sysid4 99.0521953314 99.0939555641 # sysid21 98.2867244765 98.496093132 # sysid22 98.8836107446 99.0731860899 99.5543906444 # sysid23 98.086753753 98.4952485239 # sysid44 98.8836107446 99.0772427056 99.5790751053 # sysid54 96.785672042 99.0781143074 # sysid64 98.3544410843 98.4789295449 98.4817196019 # sysid67 74.5078816751 # sysid68 23.7552154266 # sysid69 30.5848561276 # sysid70 33.5335710304 # sysid71 37.710498373 # sysid72 98.2910942185 98.2910942244 98.2910942244 # sysid73 98.3544410843 98.4789295449 98.49290069 # sysid74 98.3544410843 98.4789295449 98.4887431283 # sysid75 98.9182843857 99.0849451175 99.5487031836 # sysid77 98.086753753 98.4769519456 98.4956922971 # sysid78 98.9182843857 99.0849451175 99.1358601016 # sysid81 98.2910942185 98.2910942244 98.2910942244 # sysid82 98.2910942185 98.2910942244 98.2910942244 # sysid96 98.3544410843 98.4789295449 98.4928364694 # sysid97 98.3544410843 98.4789295449 98.492618417 # sysid98 98.2910942185 98.2910942244 98.2910942244 # sysid99 98.2910942185 98.2910942244 98.2910942244 # sysid100 98.3544410843 98.4789295449 98.4884141107 # sysid101 98.3544410843 98.4789295449 98.4884425654 # sysid102 98.2910942185 98.2910942244 98.2910942244 # sysid103 98.2910942185 98.2910942244 98.2910942244 # sysid104 98.086753753 98.4769519456 98.5007917366 # sysid105 98.086753753 98.4769519456 98.4966562518 import sys, os, glob, re # function for getting average for a single file # used by sysid argument def getAvgSingle(fileNameGetAvg): """calcuates the average cache hits for a file""" #print "TESTING:: file:", fileNameGetAvg #this part is from counter_mikey.py try: traceFile = open(fileNameGetAvg, 'r') fileLines = traceFile.readlines() traceFile.close() except IOError: print "Warning: file" + traceFile, "not found" exit() #Process file #count the lines, track each line in a list everyLine = [] totalMisses = [] totalAccesses = [] myLine = fileLines[0].split() cLevel = len(myLine)-3 #print "TESTING:: cLevel=", cLevel for i in range(0,cLevel,1): totalMisses.append(0) totalAccesses.append(0) if cLevel < 1 or cLevel > 3: print "FATAL: Expected 1, 2 or 3 cache levels" exit() idx = 1 for myLine in fileLines: # tokenize the line and verify that we get the correct number of tokens myLine = myLine.split() if cLevel != len(myLine)-3: print "FATAL: expected " + cLevel + " hit rates on line " + str(idx) exit() # ascribe each token to an aptly-named variable #blockid = long(myLine[0]) ###ASK MIKEY - needed?### #fpCount = long(myLine[1]) ###ASK MIKEY - needed?### memCount = long(myLine[2]) inclRate = [] for i in range(0,len(totalMisses),1): inclRate.append(float(myLine[i+3])) #print "myLine[", i+3, "]= ", myLine[i+3] # convert each inclusive hit rate to an exclusive rate exclRate = [inclRate[0]] for i in range(1,len(inclRate),1): thisRate = float(inclRate[i]) prevRate = float(inclRate[i-1]) if prevRate < 100.0: exclRate.append(100.0*float(thisRate - prevRate)/(100.0 - prevRate)) else: exclRate.append(float(0.0)) blockAccesses = [] blockMisses = [] blockAccesses.append(memCount) ## blockHits[n] stores the number of memory accesses that make it to cache level N for i in range(0,len(totalMisses)-1,1): blockMisses.append((blockAccesses[i]*(float(100.0)-exclRate[i]))/float(100.0)) # print "block L" + str(i+1) + " misses: " + str(blockMisses[i]) blockAccesses.append(blockMisses[i]) # print "block L" + str(i+2) + " accesses: " + str(blockAccesses[i+1]) blockMisses.append(blockAccesses[cLevel-1]*((100.0-exclRate[cLevel-1])/100.0)) # print "block L" + str(cLevel) + " misses: " + str(blockMisses[cLevel-1]) for i in range(0,len(totalMisses),1): totalMisses[i] += blockMisses[i] totalAccesses[i] += blockAccesses[i] totalHits = 0 cacheValues = [] for i in range(0,len(totalMisses),1): levelHits = (totalAccesses[i] - totalMisses[i]) totalHits += levelHits #assign values to tuple and return cacheValues.append((levelHits)/(totalAccesses[i])*100) cacheValues.append(100*totalHits/totalAccesses[0]) #print "Cache " + str(i+1) + " average %= " + str((levelHits)/(totalAccesses[i])*100) + " incl(" + str(100*totalHits/totalAccesses[0]) + ")" #print "cacheValues:", cacheValues return cacheValues # function for getting average for a single file # used by taskid argument # printType: 1 = taskid prints ex: taskid0001 # printType: 2 = sysid pritns sysid72 def printAvgSingle(fileNamepAvg, printType): #print "Avg for file:", fileNamepAvg fileidx = fileNamepAvg.rfind("/") shortfileName = fileNamepAvg[fileidx+1:] #print "TESTING: FileName:", shortfileName # get the sysid# for printing later try: sysidname = shortfileName[shortfileName.index('.')+1:] taskidname = shortfileName[shortfileName.index('.')-4:shortfileName.index('.')] #print "TESTING: sysidname=", sysidname except ValueError: print "ERROR: Invalid filename no '.' found in filename:", shortfileName exit() except IndexError: #If file has '.' as last char, this could error print "Error: Invalid location of . in filename. this shouldn't happen-", shortfileName exit() #lifted from counter_mikey.py try: traceFile = open(fileNamepAvg, 'r') except IOError, NameError: print "ERROR: can't find that file: " + fileNamepAvg exit() #Process file #count the lines, track each line in a list everyLine = [] fileLines = traceFile.readlines() traceFile.close() myLine = fileLines[0].split() cLevel = len(myLine)-3 totalMisses = [] totalAccesses = [] for i in range(0,cLevel,1): totalMisses.append(0) totalAccesses.append(0) ####validate cLevel 4,5, or 6 is expected #print "TESTING: This file has", cLevel, "cache level(s)" ##print "Eachline has", len(myLines), "columns" if cLevel < 1 or cLevel > 3: print "ERROR: Expected 1, 2, or 3 cache levels" exit() #### create if, else for cLevel = 4,5,6 idx = 1 for myLine in fileLines: # tokenize the line and verify that we get the correct number of tokens myLine = myLine.split() if cLevel != len(myLine)-3: print "ERROR: expected " + cLevel + " hit rates on line " + str(idx) # ascribe each token to an aptly-named variable blockid = long(myLine[0]) fpCount = long(myLine[1]) memCount = long(myLine[2]) inclRate = [] for i in range(0,len(totalMisses),1): inclRate.append(float(myLine[i+3])) # convert each inclusive hit rate to an exclusive rate exclRate = [inclRate[0]] for i in range(1,len(inclRate),1): thisRate = float(inclRate[i]) prevRate = float(inclRate[i-1]) if prevRate < 100.0: exclRate.append(100.0*float(thisRate - prevRate)/(100.0 - prevRate)) else: exclRate.append(float(0.0)) # print str(myLine) + ' -> ', # print str(blockid) + '\t' + str(fpCount) + '\t' + str(memCount), # for i in range(0,len(exclRate),1): # print '\t' + str(exclRate[i]), # print '' blockAccesses = [] blockMisses = [] blockAccesses.append(memCount) # print "block L1 accesses: " + str(blockAccesses[0]) ## blockHits[n] stores the number of memory accesses that make it to cache level N for i in range(0,len(totalMisses)-1,1): blockMisses.append((blockAccesses[i]*(float(100.0)-exclRate[i]))/float(100.0)) # print "block L" + str(i+1) + " misses: " + str(blockMisses[i]) blockAccesses.append(blockMisses[i]) # print "block L" + str(i+2) + " accesses: " + str(blockAccesses[i+1]) blockMisses.append(blockAccesses[cLevel-1]*((100.0-exclRate[cLevel-1])/100.0)) # print "block L" + str(cLevel) + " misses: " + str(blockMisses[cLevel-1]) for i in range(0,len(totalMisses),1): totalMisses[i] += blockMisses[i] totalAccesses[i] += blockAccesses[i] # if printType == 1: # print "taskid" + str(taskidname), # if printType == 2: # print sysidname.rjust(8), print shortfileName, totalHits = 0 for i in range(0,len(totalMisses),1): levelHits = (totalAccesses[i] - totalMisses[i]) totalHits += levelHits #print "Cache " + str(i+1) + " average %= " + str((levelHits)/(totalAccesses[i])*100) + " incl(" + str(100*totalHits/totalAccesses[0]) + ")" print str(100*totalHits/totalAccesses[0]).ljust(13), print "" # used to sort list of files in natural or numeric order def sort_nicely( l ): """ Sort the given list in the way that humans expect. """ def convert(text): if text.isdigit(): return int(text) else: return text ##convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] l.sort( key=alphanum_key ) #prints a usage error message and exits def errorMsg(): print print "Usage : ./AvgCacheCalc.py\n" print "required:" print "\t--app string; eg icepic,hycom,..." print "\t--dataset string; eg large, standard..." print "\t--cpu_count int; eg 256,1024,...\n" print "One of these two are required:" print "\t--taskid int; eg 0001" print "\t--sysid int; 1, 2, or 3 chars - 75\n" print "optional" print "\t--dir string; eg /pmaclabs/ti10/ti10_icepic_standard_0128/processed_trace/ [default=.]" exit() diridx = -1 sysidx = -1 taskidx = -1 sysidindexerr = 0 taskidindexerr = 0 try: #check for sysid sysidx = sys.argv.index("--sysid") #print "past sysidx ValueError" #print "sysidx=", sysidx if sysidx != -1: sysid = sys.argv[sysidx+1] #print "sysid=", sysid except IndexError: print "TESTING: IndexError:No --sysid argument. ->pass" sysidindexerr = 1 pass except ValueError: #print "TESTING: ValueError --sysid ->pass" # sysid may not be needed, taskid maybe used pass try: # check for taskid taskidx = sys.argv.index("--taskid") task = sys.argv[taskidx+1] # pad task with 0s if needed while len(task) < 4: task = "0"+task #print "TESTING:task=", task #print "taskidx=", taskidx #print "taskid=", task except IndexError: print "TESTING: IndexError: No --taskid argument. ->pass" taskidindexerr = 1 pass except ValueError: #print "TESTING: ValueError --taskid ->pass" pass # if neither sysid or taskid is used, error if sysidx == -1 and taskidx == -1: print "Either --sysid or --taskid required - neither used" errorMsg() # if both sysid and taskid are used, error if sysidx != -1 and taskidx != -1: print "Either --sysid or --taskid required - both used" errorMsg() # check to make sure sys or task value was given # needed because we skipped this check before #print "Testing: sysidx and taskidx sysidx=", sysidx," taskidx=", taskidx if sysidx != -1 and sysidindexerr == 1: # we are using sysid and there was a no value after print "No --sysid value given, please provide argument\n" errorMsg() if taskidx != -1 and taskidindexerr == 1: # we are using taskid and there was a no value after print "No --taskid value given, please provide argument\n" errorMsg() # check for dir # not required, uses current dir try: diridx = sys.argv.index("--dir") except ValueError: #print"no dir->ok" pass # if --dir is not used, current dir willbe used try: if diridx == -1: dirRead = os.getcwd() #use currend dir if none given #print "TESTING: current dir used dir=", dirRead else: dirRead = sys.argv[diridx+1] #print "TESTING: input used ***WHAT ABOUT SLASH AT END*** dir=", dirRead #pad a '/' to the end of the directory if dirRead[-1] != '/': dirRead = dirRead + '/' except IndexError: print "No --dir value given, please provide argument\n" errorMsg() except ValueError: print "TESTING:Error with --dir argument, see usage below\n" errorMsg() try: #check for app appidx = sys.argv.index("--app") appname = sys.argv[appidx+1] #print "app=", appname except IndexError: print "No --app value given, please provide argument\n" errorMsg() except ValueError: print "Error with --app argument, see usage below\n" errorMsg() try: #check for dataset datasetidx = sys.argv.index("--dataset") datasetname = sys.argv[datasetidx+1] #print "dataset=", datasetname except IndexError: print "No --dataset value given, please provide argument\n" errorMsg() except ValueError: print "Error with --dataset argument, see usage below\n" errorMsg() try: #check for cpu_count cpuidx = sys.argv.index("--cpu_count") cpu = sys.argv[cpuidx+1] #print "cpu=", cpu #print "cpu type:", type(cpu) cpulen = len(cpu) if cpulen > 4: # error if more than 4 digits print "ERROR: cpu_count cannot be greater than 4 digits" exit() if cpulen < 4: # pad with 0 if less than 4 digits #print "TESTING: cpulen:", cpulen, "needs to be 4" while len(cpu) < 4: cpu = "0"+cpu cpulen = len(cpu) except IndexError: print "No --cpu_count value given, please provide argument\n" errorMsg() except ValueError: print "Error with --cpu_count argument, see usage below\n" errorMsg() fileName = appname+"_"+datasetname+"_"+cpu # print "filename:", fileName # print "dirRead:", dirRead <|fim▁hole|>if taskidx == -1: #use sysid print "Averaging for all files like "+fileName+"*.sysid"+sysid fileList = glob.glob(dirRead+fileName+"*.sysid"+sysid) #or gets the list of files with the taskid value elif sysidx == -1: #use taskid print "Averaging for all files like "+fileName+"_"+task+"*" #print dirRead+fileName+"_"+task+".*" fileList = glob.glob(dirRead+fileName+"_"+task+".*") else: print "ERROR: No one should get here either taskid or sysid should have been validated" errorMsg() #for i in range(len(fileList)): # print "TESTING:filelist[", i, "]=",fileList[i] #sort the list of files #fileList.sort() #sort numerically sort_nicely(fileList) #print "fileList[0]:", fileList[0] #print "fileList type:", type(fileList) # Catch if there are no files matching the request if len(fileList) == 0: print "ERROR: No files match input...exiting" exit() print "Number of files: ", len(fileList) #print "This may take a moment" if taskidx == -1: #use sysid dirAvg = [] # goes through each file and collects all the averages # inclusive and exclusive for Caches 1-3 (if 2 and 3 are present) for i in range(0, len(fileList)): dirAvg.append(getAvgSingle(fileList[i])) printAvgSingle(fileList[i],1) print "\n *** Averaged Hit rates ***" print fileName+"*.sysid"+sysid, numCache = len(dirAvg[0]) totalCache = [0,0,0,0,0,0] #print "TESTING:numcache for avg of files is:", numCache #print "TESTING:dirAvg[0]=", dirAvg[0] #print "TESTING:len(dirAvg[0])=", len(dirAvg[0]) #print "TESTING:len(dirAvg)=", len(dirAvg) #print "TESTING:numCache range= ", range(numCache) #calcute averages for the folder for i in range(len(dirAvg)): #if len(dirAvg[i]) > 4: #print "TESTING:dirAvg[",i,"][4]=", dirAvg[i][4] for j in range(numCache): #print "::j=",j,"dirAvg[",i,"][",j,"]= ", dirAvg[i][j] totalCache[j] = totalCache[j]+dirAvg[i][j] #print values of the cache for i in range(0, len(totalCache), 2): if totalCache[i+1] !=0: print totalCache[i+1]/len(dirAvg), #print "excl", totalCache[i]/len(dirAvg) #print "Cache " + str((i/2)+1) + " average %= " + str(totalCache[i]/len(dirAvg)) + " incl(" + str(totalCache[i+1]/len(dirAvg)) + ")" elif sysidx == -1: #use taskid for i in range(0, len(fileList)): printAvgSingle(fileList[i],2)<|fim▁end|>
print print "Reading files from: ", dirRead #gets the list of files with a matching sysid value
<|file_name|>transformer.py<|end_file_name|><|fim▁begin|># Authors: Mainak Jas <[email protected]> # Alexandre Gramfort <[email protected]> # Romain Trachel <[email protected]> # # License: BSD (3-clause) import numpy as np from .mixin import TransformerMixin from .. import pick_types from ..filter import (low_pass_filter, high_pass_filter, band_pass_filter, band_stop_filter) from ..time_frequency import multitaper_psd from ..externals import six from ..utils import _check_type_picks, deprecated class Scaler(TransformerMixin): """Standardizes data across channels Parameters ---------- info : instance of Info The measurement info with_mean : boolean, True by default If True, center the data before scaling. with_std : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation).<|fim▁hole|> Attributes ---------- info : instance of Info The measurement info ch_mean_ : dict The mean value for each channel type std_ : dict The standard deviation for each channel type """ def __init__(self, info, with_mean=True, with_std=True): self.info = info self.with_mean = with_mean self.with_std = with_std self.ch_mean_ = dict() # TODO rename attribute self.std_ = dict() # TODO rename attribute def fit(self, epochs_data, y): """Standardizes data across channels Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data to concatenate channels. y : array, shape (n_epochs,) The label for each epoch. Returns ------- self : instance of Scaler Returns the modified instance. """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) X = np.atleast_3d(epochs_data) picks_list = dict() picks_list['mag'] = pick_types(self.info, meg='mag', ref_meg=False, exclude='bads') picks_list['grad'] = pick_types(self.info, meg='grad', ref_meg=False, exclude='bads') picks_list['eeg'] = pick_types(self.info, eeg='grad', ref_meg=False, exclude='bads') self.picks_list_ = picks_list for key, this_pick in picks_list.items(): if self.with_mean: ch_mean = X[:, this_pick, :].mean(axis=1)[:, None, :] self.ch_mean_[key] = ch_mean # TODO rename attribute if self.with_std: ch_std = X[:, this_pick, :].mean(axis=1)[:, None, :] self.std_[key] = ch_std # TODO rename attribute return self def transform(self, epochs_data, y=None): """Standardizes data across channels Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data. y : None | array, shape (n_epochs,) The label for each epoch. If None not used. Defaults to None. Returns ------- X : array, shape (n_epochs, n_channels, n_times) The data concatenated over channels. """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) X = np.atleast_3d(epochs_data) for key, this_pick in six.iteritems(self.picks_list_): if self.with_mean: X[:, this_pick, :] -= self.ch_mean_[key] if self.with_std: X[:, this_pick, :] /= self.std_[key] return X def inverse_transform(self, epochs_data, y=None): """ Inverse standardization of data across channels Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data. y : None | array, shape (n_epochs,) The label for each epoch. If None not used. Defaults to None. Returns ------- X : array, shape (n_epochs, n_channels, n_times) The data concatenated over channels. """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) X = np.atleast_3d(epochs_data) for key, this_pick in six.iteritems(self.picks_list_): if self.with_mean: X[:, this_pick, :] += self.ch_mean_[key] if self.with_std: X[:, this_pick, :] *= self.std_[key] return X class EpochsVectorizer(TransformerMixin): """EpochsVectorizer transforms epoch data to fit into a scikit-learn pipeline. Parameters ---------- info : instance of Info The measurement info. Attributes ---------- n_channels : int The number of channels. n_times : int The number of time points. """ def __init__(self, info=None): self.info = info self.n_channels = None self.n_times = None def fit(self, epochs_data, y): """For each epoch, concatenate data from different channels into a single feature vector. Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data to concatenate channels. y : array, shape (n_epochs,) The label for each epoch. Returns ------- self : instance of ConcatenateChannels returns the modified instance """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) return self def transform(self, epochs_data, y=None): """For each epoch, concatenate data from different channels into a single feature vector. Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data. y : None | array, shape (n_epochs,) The label for each epoch. If None not used. Defaults to None. Returns ------- X : array, shape (n_epochs, n_channels * n_times) The data concatenated over channels """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) epochs_data = np.atleast_3d(epochs_data) n_epochs, n_channels, n_times = epochs_data.shape X = epochs_data.reshape(n_epochs, n_channels * n_times) # save attributes for inverse_transform self.n_epochs = n_epochs self.n_channels = n_channels self.n_times = n_times return X def inverse_transform(self, X, y=None): """For each epoch, reshape a feature vector into the original data shape Parameters ---------- X : array, shape (n_epochs, n_channels * n_times) The feature vector concatenated over channels y : None | array, shape (n_epochs,) The label for each epoch. If None not used. Defaults to None. Returns ------- epochs_data : array, shape (n_epochs, n_channels, n_times) The original data """ if not isinstance(X, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(X)) return X.reshape(-1, self.n_channels, self.n_times) @deprecated("Class 'ConcatenateChannels' has been renamed to " "'EpochsVectorizer' and will be removed in release 0.11.") class ConcatenateChannels(EpochsVectorizer): pass class PSDEstimator(TransformerMixin): """Compute power spectrum density (PSD) using a multi-taper method Parameters ---------- sfreq : float The sampling frequency. fmin : float The lower frequency of interest. fmax : float The upper frequency of interest. bandwidth : float The bandwidth of the multi taper windowing function in Hz. adaptive : bool Use adaptive weights to combine the tapered spectra into PSD (slow, use n_jobs >> 1 to speed up computation). low_bias : bool Only use tapers with more than 90% spectral concentration within bandwidth. n_jobs : int Number of parallel jobs to use (only used if adaptive=True). normalization : str Either "full" or "length" (default). If "full", the PSD will be normalized by the sampling rate as well as the length of the signal (as in nitime). verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). """ def __init__(self, sfreq=2 * np.pi, fmin=0, fmax=np.inf, bandwidth=None, adaptive=False, low_bias=True, n_jobs=1, normalization='length', verbose=None): self.sfreq = sfreq self.fmin = fmin self.fmax = fmax self.bandwidth = bandwidth self.adaptive = adaptive self.low_bias = low_bias self.n_jobs = n_jobs self.verbose = verbose self.normalization = normalization def fit(self, epochs_data, y): """Compute power spectrum density (PSD) using a multi-taper method Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data. y : array, shape (n_epochs,) The label for each epoch Returns ------- self : instance of PSDEstimator returns the modified instance """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) return self def transform(self, epochs_data, y=None): """Compute power spectrum density (PSD) using a multi-taper method Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data y : None | array, shape (n_epochs,) The label for each epoch. If None not used. Defaults to None. Returns ------- psd : array, shape (n_signals, len(freqs)) or (len(freqs),) The computed PSD. """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) epochs_data = np.atleast_3d(epochs_data) n_epochs, n_channels, n_times = epochs_data.shape X = epochs_data.reshape(n_epochs * n_channels, n_times) psd, _ = multitaper_psd(x=X, sfreq=self.sfreq, fmin=self.fmin, fmax=self.fmax, bandwidth=self.bandwidth, adaptive=self.adaptive, low_bias=self.low_bias, n_jobs=self.n_jobs, normalization=self.normalization, verbose=self.verbose) _, n_freqs = psd.shape psd = psd.reshape(n_epochs, n_channels, n_freqs) return psd class FilterEstimator(TransformerMixin): """Estimator to filter RtEpochs Applies a zero-phase low-pass, high-pass, band-pass, or band-stop filter to the channels selected by "picks". l_freq and h_freq are the frequencies below which and above which, respectively, to filter out of the data. Thus the uses are: - l_freq < h_freq: band-pass filter - l_freq > h_freq: band-stop filter - l_freq is not None, h_freq is None: low-pass filter - l_freq is None, h_freq is not None: high-pass filter If n_jobs > 1, more memory is required as "len(picks) * n_times" additional time points need to be temporarily stored in memory. Parameters ---------- info : instance of Info Measurement info. l_freq : float | None Low cut-off frequency in Hz. If None the data are only low-passed. h_freq : float | None High cut-off frequency in Hz. If None the data are only high-passed. picks : array-like of int | None Indices of channels to filter. If None only the data (MEG/EEG) channels will be filtered. filter_length : str (Default: '10s') | int | None Length of the filter to use. If None or "len(x) < filter_length", the filter length used is len(x). Otherwise, if int, overlap-add filtering with a filter of the specified length in samples) is used (faster for long signals). If str, a human-readable time in units of "s" or "ms" (e.g., "10s" or "5500ms") will be converted to the shortest power-of-two length at least that duration. l_trans_bandwidth : float Width of the transition band at the low cut-off frequency in Hz. h_trans_bandwidth : float Width of the transition band at the high cut-off frequency in Hz. n_jobs : int | str Number of jobs to run in parallel. Can be 'cuda' if scikits.cuda is installed properly, CUDA is initialized, and method='fft'. method : str 'fft' will use overlap-add FIR filtering, 'iir' will use IIR forward-backward filtering (via filtfilt). iir_params : dict | None Dictionary of parameters to use for IIR filtering. See mne.filter.construct_iir_filter for details. If iir_params is None and method="iir", 4th order Butterworth will be used. verbose : bool, str, int, or None If not None, override default verbose level (see mne.verbose). Defaults to self.verbose. """ def __init__(self, info, l_freq, h_freq, picks=None, filter_length='10s', l_trans_bandwidth=0.5, h_trans_bandwidth=0.5, n_jobs=1, method='fft', iir_params=None, verbose=None): self.info = info self.l_freq = l_freq self.h_freq = h_freq self.picks = _check_type_picks(picks) self.filter_length = filter_length self.l_trans_bandwidth = l_trans_bandwidth self.h_trans_bandwidth = h_trans_bandwidth self.n_jobs = n_jobs self.method = method self.iir_params = iir_params def fit(self, epochs_data, y): """Filters data Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data. y : array, shape (n_epochs,) The label for each epoch. Returns ------- self : instance of FilterEstimator Returns the modified instance """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) if self.picks is None: self.picks = pick_types(self.info, meg=True, eeg=True, ref_meg=False, exclude=[]) if self.l_freq == 0: self.l_freq = None if self.h_freq is not None and self.h_freq > (self.info['sfreq'] / 2.): self.h_freq = None if self.l_freq is not None and not isinstance(self.l_freq, float): self.l_freq = float(self.l_freq) if self.h_freq is not None and not isinstance(self.h_freq, float): self.h_freq = float(self.h_freq) if self.info['lowpass'] is None or (self.h_freq is not None and (self.l_freq is None or self.l_freq < self.h_freq) and self.h_freq < self.info['lowpass']): self.info['lowpass'] = self.h_freq if self.info['highpass'] is None or (self.l_freq is not None and (self.h_freq is None or self.l_freq < self.h_freq) and self.l_freq > self.info['highpass']): self.info['highpass'] = self.l_freq return self def transform(self, epochs_data, y=None): """Filters data Parameters ---------- epochs_data : array, shape (n_epochs, n_channels, n_times) The data. y : None | array, shape (n_epochs,) The label for each epoch. If None not used. Defaults to None. Returns ------- X : array, shape (n_epochs, n_channels, n_times) The data after filtering """ if not isinstance(epochs_data, np.ndarray): raise ValueError("epochs_data should be of type ndarray (got %s)." % type(epochs_data)) epochs_data = np.atleast_3d(epochs_data) if self.l_freq is None and self.h_freq is not None: epochs_data = \ low_pass_filter(epochs_data, self.info['sfreq'], self.h_freq, filter_length=self.filter_length, trans_bandwidth=self.l_trans_bandwidth, method=self.method, iir_params=self.iir_params, picks=self.picks, n_jobs=self.n_jobs, copy=False, verbose=False) if self.l_freq is not None and self.h_freq is None: epochs_data = \ high_pass_filter(epochs_data, self.info['sfreq'], self.l_freq, filter_length=self.filter_length, trans_bandwidth=self.h_trans_bandwidth, method=self.method, iir_params=self.iir_params, picks=self.picks, n_jobs=self.n_jobs, copy=False, verbose=False) if self.l_freq is not None and self.h_freq is not None: if self.l_freq < self.h_freq: epochs_data = \ band_pass_filter(epochs_data, self.info['sfreq'], self.l_freq, self.h_freq, filter_length=self.filter_length, l_trans_bandwidth=self.l_trans_bandwidth, h_trans_bandwidth=self.h_trans_bandwidth, method=self.method, iir_params=self.iir_params, picks=self.picks, n_jobs=self.n_jobs, copy=False, verbose=False) else: epochs_data = \ band_stop_filter(epochs_data, self.info['sfreq'], self.h_freq, self.l_freq, filter_length=self.filter_length, l_trans_bandwidth=self.h_trans_bandwidth, h_trans_bandwidth=self.l_trans_bandwidth, method=self.method, iir_params=self.iir_params, picks=self.picks, n_jobs=self.n_jobs, copy=False, verbose=False) return epochs_data<|fim▁end|>
<|file_name|>array-type.ts<|end_file_name|><|fim▁begin|>import { string_type } from '../../constants'; import { emit } from '../../emit'; import { create_array_type, is_array_type } from '../array-type'; it('should return correctly', () => { expect( emit( create_array_type({ type: string_type, }), ), ).toMatchSnapshot(); }); describe('is_array_type', () => { it('should return correctly', () => { const element = create_array_type({<|fim▁hole|> }); expect(is_array_type(element)).toBe(true); }); });<|fim▁end|>
type: string_type,
<|file_name|>nproc.rs<|end_file_name|><|fim▁begin|>#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. *<|fim▁hole|> */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] extern crate libc; #[macro_use] extern crate uucore; use std::env; #[cfg(target_os = "linux")] pub const _SC_NPROCESSORS_CONF: libc::c_int = 83; #[cfg(target_os = "macos")] pub const _SC_NPROCESSORS_CONF: libc::c_int = libc::_SC_NPROCESSORS_CONF; #[cfg(target_os = "freebsd")] pub const _SC_NPROCESSORS_CONF: libc::c_int = 57; #[cfg(target_os = "netbsd")] pub const _SC_NPROCESSORS_CONF: libc::c_int = 1001; static NAME: &'static str = "nproc"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag( "", "all", "print the number of cores available to the system", ); opts.optopt("", "ignore", "ignore up to N cores", "N"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(err) => { show_error!("{}", err); return 1; } }; if matches.opt_present("version") { println!("{} {}", NAME, VERSION); return 0; } if matches.opt_present("help") { let msg = format!( "{0} {1} Usage: {0} [OPTIONS]... Print the number of cores available to the current process.", NAME, VERSION ); print!("{}", opts.usage(&msg)); return 0; } let mut ignore = match matches.opt_str("ignore") { Some(numstr) => match numstr.parse() { Ok(num) => num, Err(e) => { show_error!("\"{}\" is not a valid number: {}", numstr, e); return 1; } }, None => 0, }; if !matches.opt_present("all") { ignore += match env::var("OMP_NUM_THREADS") { Ok(threadstr) => match threadstr.parse() { Ok(num) => num, Err(_) => 0, }, Err(_) => 0, }; } let mut cores = if matches.opt_present("all") { num_cpus_all() } else { num_cpus::get() }; if cores <= ignore { cores = 1; } else { cores -= ignore; } println!("{}", cores); 0 } #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd"))] fn num_cpus_all() -> usize { let nprocs = unsafe { libc::sysconf(_SC_NPROCESSORS_CONF) }; if nprocs == 1 { // In some situation, /proc and /sys are not mounted, and sysconf returns 1. // However, we want to guarantee that `nproc --all` >= `nproc`. num_cpus::get() } else { if nprocs > 0 { nprocs as usize } else { 1 } } } // Other platform(e.g., windows), num_cpus::get() directly. #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd")))] fn num_cpus_all() -> usize { num_cpus::get() }<|fim▁end|>
* (c) Michael Gehring <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code.
<|file_name|>permissions.py<|end_file_name|><|fim▁begin|>""" Provides a set of pluggable permission policies. """ from __future__ import unicode_literals from django.http import Http404 from rest_framework import exceptions from rest_framework.compat import is_authenticated SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class BasePermission(object): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True class AllowAny(BasePermission): """ Allow any access. This isn't strictly required, since you could use an empty permission_classes list, but it's useful because it makes the intention more explicit. """ def has_permission(self, request, view): return True class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return request.user and is_authenticated(request.user) class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): return request.user and request.user.is_staff class IsAuthenticatedOrReadOnly(BasePermission): """ The request is authenticated as a user, or is a read-only request. """ def has_permission(self, request, view): return ( request.method in SAFE_METHODS or request.user and is_authenticated(request.user) ) class DjangoModelPermissions(BasePermission): """ The request is authenticated using `django.contrib.auth` permissions. See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions It ensures that the user is authenticated, and has the appropriate `add`/`change`/`delete` permissions on the model. This permission can only be applied against view classes that provide a `.queryset` attribute. """ # Map methods into required permission codes. # Override this if you need to also provide 'view' permissions, # or if you want to provide custom permission codes. perms_map = { 'GET': [], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): """ Given a model and an HTTP method, return the list of permission codes that the user is required to have. """ kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def has_permission(self, request, view): # Workaround to ensure DjangoModelPermissions are not applied # to the root view when using DefaultRouter. if getattr(view, '_ignore_model_permissions', False): return True if hasattr(view, 'get_queryset'): queryset = view.get_queryset() else: queryset = getattr(view, 'queryset', None) assert queryset is not None, ( 'Cannot apply DjangoModelPermissions on a view that ' 'does not set `.queryset` or have a `.get_queryset()` method.' ) perms = self.get_required_permissions(request.method, queryset.model) return ( request.user and (is_authenticated(request.user) or not self.authenticated_users_only) and request.user.has_perms(perms) ) class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions): """ Similar to DjangoModelPermissions, except that anonymous users are allowed read-only access. """ authenticated_users_only = False class DjangoObjectPermissions(DjangoModelPermissions): """ The request is authenticated using Django's object-level permissions. It requires an object-permissions-enabled backend, such as Django Guardian. It ensures that the user is authenticated, and has the appropriate `add`/`change`/`delete` permissions on the object using .has_perms. This permission can only be applied against view classes that provide a `.queryset` attribute. """ perms_map = { 'GET': [], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } def get_required_object_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def has_object_permission(self, request, view, obj): if hasattr(view, 'get_queryset'): queryset = view.get_queryset() else: queryset = getattr(view, 'queryset', None) assert queryset is not None, ( 'Cannot apply DjangoObjectPermissions on a view that ' 'does not set `.queryset` or have a `.get_queryset()` method.' ) model_cls = queryset.model user = request.user perms = self.get_required_object_permissions(request.method, model_cls)<|fim▁hole|> # a 404 response. if request.method in SAFE_METHODS: # Read permissions already checked and failed, no need # to make another lookup. raise Http404 read_perms = self.get_required_object_permissions('GET', model_cls) if not user.has_perms(read_perms, obj): raise Http404 # Has read permissions. return False return True<|fim▁end|>
if not user.has_perms(perms, obj): # If the user does not have permissions we need to determine if # they have read permissions to see 403, or not, and simply see
<|file_name|>import_tasks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core' } DOCUMENTATION = ''' --- author: Ansible Core Team (@ansible) module: import_tasks short_description: Import a task list description: - Imports a list of tasks to be added to the current playbook for subsequent execution. version_added: "2.4" options: free-form: description: - The name of the imported file is specified directly without any other option. - Most keywords, including loops and conditionals, only applied to the imported tasks, not to this statement itself. If you need any of those to apply, use M(include_tasks) instead. notes: - This is a core feature of Ansible, rather than a module, and cannot be overridden like a module. ''' <|fim▁hole|>EXAMPLES = """ - hosts: all tasks: - debug: msg: task1 - name: Include task list in play import_tasks: stuff.yaml - debug: msg: task10 - hosts: all tasks: - debug: msg: task1 - name: Apply conditional to all imported tasks import_tasks: stuff.yaml when: hostvar is defined """ RETURN = """ # This module does not return anything except tasks to execute. """<|fim▁end|>
<|file_name|>path.rs<|end_file_name|><|fim▁begin|>extern crate url; use url::percent_encoding::percent_decode; use regex; use json::{JsonValue, ToJson}; lazy_static! { pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap(); } pub struct Path { regex: regex::Regex, pub path: String, pub params: Vec<String> }<|fim▁hole|>pub fn normalize<'a>(path: &'a str) -> &'a str { if path.starts_with("/") { &path[1..] } else { path } } impl Path { pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) { let obj = params.as_object_mut().expect("Params must be object"); for param in self.params.iter() { obj.insert( param.clone(), percent_decode( captures.name(&param).unwrap_or("").as_bytes() ).decode_utf8_lossy().to_string().to_json()); } } pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> { self.regex.captures(path) } pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> { let mut regex_body = "^".to_string() + &Path::sub_regex(path); if endpoint { regex_body = regex_body + "$"; } let regex = match regex::Regex::new(&regex_body) { Ok(re) => re, Err(err) => return Err(format!("{}", err)) }; let mut params = vec![]; for capture in MATCHER.captures_iter(path) { params.push(capture.at(1).unwrap_or("").to_string()); } Ok(Path { path: path.to_string(), params: params, regex: regex }) } fn sub_regex(path: &str) -> String { return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)"); } } #[test] fn it_normalize() { assert_eq!(normalize("/test"), "test"); assert_eq!(normalize("test"), "test"); } #[test] fn sub_regex() { let res = Path::sub_regex(":user_id/messages/:message_id"); assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)") } #[test] fn parse_and_match() { let path = Path::parse(":user_id/messages/:message_id", true).unwrap(); assert!(match path.is_match("1920/messages/100500") { Some(captures) => { captures.name("user_id").unwrap() == "1920" && captures.name("message_id").unwrap() == "100500" } None => false }); assert!(match path.is_match("1920/messages/not_match/100500") { Some(_) => false, None => true }); } #[test] fn parse_and_match_root() { let path = Path::parse("", true).unwrap(); assert!(match path.is_match("") { Some(captures) => captures.at(0).unwrap() == "", None => false }); } #[test] fn parse_and_match_single_val() { let path = Path::parse(":id", true).unwrap(); assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") { Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000", None => false }); }<|fim▁end|>