repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
cmd2001/Codes | Projects_20170403/coprime_f.cpp | 954 | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn=110;
long long int lst[maxn],cnt,ans,x;
int t;
inline bool judge(register long long int x)
{
if(x==1) return 1;
for(int i=2,sq=sqrt(x);i<=sq;i++)
{
if(!(x%i)) return 1;
}
return 0;
}
inline void calc(register long long int x)
{
for(int i=2;i<=x;i++)
{
if(!(x%i)) lst[++cnt]=i;
while(!(x%i)) x/=i;
}
}
inline void init()
{
memset(lst,0,sizeof(lst));
cnt=0;
ans=0;
}
inline long long int multi(long long int a,long long int b)
{
a%=
int main()
{
//freopen("coprime.in","r",stdin);
//freopen("coprime.out","w",stdout);
scanf("%d",&t);
while(t--)
{
init();
scanf("%lld",&x);
if(!judge(x)) {printf("%lld\n",x-1);continue;}
ans=x;
calc(x);
for(int i=1;i<=cnt;i++) ans/=lst[i],ans*=(lst[i]-1);
printf("%lld\n",ans);
}
fclose(stdin);
fclose(stdout);
return 0;
}
| gpl-3.0 |
Shirasho/Cascade | scripts/sourcify-cli.js | 1176 | const path = require('path');
const shell = require('shelljs');
const argv = require('yargs').argv;
let which;
shell.config.silent = true;
if (shell.which('npm')) {
which = 'npm';
}
if (shell.which('yarn')) {
which = 'yarn';
}
if (!which) {
shell.echo('Error: Yarn or NPM required (Yarn preferred). Install Yarn or NPM and try again.');
shell.exit(1);
}
if (which !== 'yarn') {
shell.echo('Warning: It is highly recommend you install Yarn which will prevent installed packages' +
' from being redownloaded during every compilation request. https://yarnpkg.com/en/');
}
shell.echo(`Detected package manager: ${which}`);
const projectRoot = path.join(__dirname, '..');
const srcDir = path.join(projectRoot, 'src', 'scss');
const distDir = path.join(projectRoot, 'dist', 'css');
const outputStyle = argv.dev ? 'expanded' : 'compressed';
shell.echo(`Transpiling stylesheets {style=${outputStyle}}...`);
if (shell.exec(`node-sass --include-path=${srcDir} --source-map true` +
` --output-style=${outputStyle} ${srcDir} -o ${distDir}`).code !== 0) {
shell.echo('Error: Unable to transpile scss files.');
shell.exit(1);
} | gpl-3.0 |
joaduo/mepinta | plugins/c_and_cpp/k3dv1/plugins/c_and_cpp/processors/k3dv1/mesh/generators/polyhedron/PolyCylinder/PolyCylinder__0001_code/PolyCylinder.cpp | 9199 | //Mepinta
//Copyright (c) 2011-2012, Joaquin G. Duo, mepinta@joaquinduo.com.ar
//
// K-3D
// Copyright (c) 1995-2006, Timothy M. Shead
//
//This file is part of Mepinta.
//
//Mepinta 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.
//
//Mepinta 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 Mepinta. If not, see <http://www.gnu.org/licenses/>.
/** \file
Code based on the PolyCylinder plugin of the K-3D project.
*/
#include <mepintasdk/sdk.h>
#include <k3dsdk/MPExtension/plugins/processors/mesh/MeshSourceBase.h>
#include <k3dsdk/MPExtension/plugins/export_method.h>
//Included Data Types
#include <data_types/k3dv1/mesh/mesh.h>
#include <data_types/k3dv1/imaterial/imaterial.h>
#include <data_types/c/builtin/int/int.h>
#include <data_types/c/builtin/double/double.h>
#include <k3dsdk/polyhedron.h>
#include <boost/scoped_ptr.hpp>
class PolyCylinder:
public k3d::MPExtension::plugins::processors::mesh::MeshSourceBase
{
private:
//Called when creating vertices, edges and faces
int updateMeshTopology(k3d::mesh& Output, k3d::imaterial* material){
//Declare Inputs
INPUT(k3d::int32_t,u_segments,args);
INPUT(k3d::int32_t,v_segments,args);
Output = k3d::mesh();
boost::scoped_ptr<k3d::polyhedron::primitive> polyhedron(k3d::polyhedron::create(Output));
polyhedron->shell_types.push_back(k3d::polyhedron::POLYGONS);
k3d::polyhedron::add_cylinder(Output, *polyhedron, 0, v_segments, u_segments, material);
updateMeshGeometryPrivate(Output,material,polyhedron);
return EXIT_NORMAL;
}
int updateMeshGeometry(k3d::mesh& Output){
log_debug("Right now all the suff is done on the 'updateMeshTopology' method.(I suppose a solvable technical reason)\n");
return EXIT_NORMAL;
}
//Called when updating the vertices positions
int updateMeshGeometryPrivate(k3d::mesh& Output, k3d::imaterial* material, boost::scoped_ptr<k3d::polyhedron::primitive>& polyhedron){
//Declare Inputs
INPUT(k3d::bool_t,bottom_cap,args);
INPUT(k3d::int32_t,bottom_segments,args);
INPUT(k3d::double_t,radius,args);
INPUT(k3d::bool_t,top_cap,args);
INPUT(k3d::int32_t,top_segments,args);
INPUT(k3d::double_t,u_power,args);
INPUT(k3d::int32_t,u_segments,args);
INPUT(k3d::int32_t,v_segments,args);
INPUT(k3d::double_t,z_max,args);
INPUT(k3d::double_t,z_min,args);
const k3d::double_t inv_u_power = u_power ? 1.0 / u_power : 1.0;
k3d::mesh::points_t& points = Output.points.writable();
k3d::mesh::selection_t& point_selection = Output.point_selection.writable();
// Shape the cylinder points
for(k3d::int32_t v = 0; v <= v_segments; ++v)
{
const k3d::double_t height = k3d::ratio(v, v_segments);
for(k3d::int32_t u = 0; u != u_segments; ++u)
{
const k3d::double_t theta = k3d::pi_times_2() * k3d::ratio(u, u_segments);
k3d::double_t x = cos(theta);
k3d::double_t y = -sin(theta);
k3d::double_t z = k3d::mix(z_max, z_min, height);
x = radius * k3d::sign(x) * std::pow(std::abs(x), inv_u_power);
y = radius * k3d::sign(y) * std::pow(std::abs(y), inv_u_power);
points[v * u_segments + u] = k3d::point3(x, y, z);
}
}
//const k3d::uint_t top_rim_offset = 0;
const k3d::uint_t bottom_rim_offset = v_segments * u_segments;
// Optionally cap the top_cap of the cylinder ...
if(top_cap)
{
if(!top_segments)
{
polyhedron->face_shells.push_back(0);
polyhedron->face_first_loops.push_back(polyhedron->loop_first_edges.size());
polyhedron->face_loop_counts.push_back(1);
polyhedron->face_selections.push_back(0);
polyhedron->face_materials.push_back(material);
polyhedron->loop_first_edges.push_back(polyhedron->clockwise_edges.size());
for(k3d::int32_t u = 0; u != u_segments; ++u)
{
polyhedron->clockwise_edges.push_back(polyhedron->clockwise_edges.size() + 1);
polyhedron->edge_selections.push_back(0);
polyhedron->vertex_points.push_back((u_segments - u) % u_segments);
polyhedron->vertex_selections.push_back(0);
}
polyhedron->clockwise_edges.back() = polyhedron->loop_first_edges.back();
}
else
{
const k3d::uint_t middle_point_index = points.size();
const k3d::point3 middle_point(0, 0, z_max);
points.push_back(middle_point);
point_selection.push_back(0);
// Create segment quads
k3d::uint_t last_ring_point_offset = 0;
k3d::uint_t current_ring_point_offset = 0;
for(k3d::int32_t n = top_segments; n > 1; --n)
{
current_ring_point_offset = points.size();
const k3d::double_t factor = k3d::ratio(n - 1, top_segments);
for(k3d::int32_t u = 0; u < u_segments; ++u)
{
points.push_back(middle_point + factor * (points[u] - middle_point));
point_selection.push_back(0);
}
for(k3d::int32_t u = 0; u < u_segments; ++u)
{
k3d::polyhedron::add_quadrilateral(
Output,
*polyhedron,
0,
last_ring_point_offset + (u + 1) % u_segments,
last_ring_point_offset + (u + 0) % u_segments,
current_ring_point_offset + (u + 0) % u_segments,
current_ring_point_offset + (u + 1) % u_segments,
material);
}
last_ring_point_offset = current_ring_point_offset;
}
// Create middle triangle fan
for(k3d::int32_t u = 0; u != u_segments; ++u)
{
k3d::polyhedron::add_triangle(
Output,
*polyhedron,
0,
current_ring_point_offset + (u + 1) % u_segments,
current_ring_point_offset + (u + 0) % u_segments,
middle_point_index,
material);
}
}
}
// Optionally cap the bottom_cap of the cylinder ...
if(bottom_cap)
{
if(!bottom_segments)
{
polyhedron->face_shells.push_back(0);
polyhedron->face_first_loops.push_back(polyhedron->loop_first_edges.size());
polyhedron->face_loop_counts.push_back(1);
polyhedron->face_selections.push_back(0);
polyhedron->face_materials.push_back(material);
polyhedron->loop_first_edges.push_back(polyhedron->clockwise_edges.size());
for(k3d::int32_t u = 0; u != u_segments; ++u)
{
polyhedron->clockwise_edges.push_back(polyhedron->clockwise_edges.size() + 1);
polyhedron->edge_selections.push_back(0);
polyhedron->vertex_points.push_back(bottom_rim_offset + u);
polyhedron->vertex_selections.push_back(0);
}
polyhedron->clockwise_edges.back() = polyhedron->loop_first_edges.back();
}
else
{
const k3d::uint_t middle_point_index = points.size();
const k3d::point3 middle_point(0, 0, z_min);
points.push_back(middle_point);
point_selection.push_back(0);
// Create segment quads
k3d::uint_t last_ring_point_offset = v_segments * u_segments;
k3d::uint_t current_ring_point_offset = v_segments * u_segments;
for(k3d::int32_t n = bottom_segments; n > 1; --n)
{
current_ring_point_offset = points.size();
const k3d::double_t factor = k3d::ratio(n - 1, bottom_segments);
for(k3d::int32_t u = 0; u < u_segments; ++u)
{
points.push_back(middle_point + factor * (points[(v_segments * u_segments) + u] - middle_point));
point_selection.push_back(0);
}
for(k3d::int32_t u = 0; u < u_segments; ++u)
{
k3d::polyhedron::add_quadrilateral(
Output,
*polyhedron,
0,
last_ring_point_offset + (u + 0) % u_segments,
last_ring_point_offset + (u + 1) % u_segments,
current_ring_point_offset + (u + 1) % u_segments,
current_ring_point_offset + (u + 0) % u_segments,
material);
}
last_ring_point_offset = current_ring_point_offset;
}
// Create middle triangle fan
for(k3d::int32_t u = 0; u != u_segments; ++u)
{
k3d::polyhedron::add_triangle(
Output,
*polyhedron,
0,
current_ring_point_offset + (u + 0) % u_segments,
current_ring_point_offset + (u + 1) % u_segments,
middle_point_index,
material);
}
}
}
return EXIT_NORMAL;
}
};
EXPORT_METHOD(PolyCylinder,updateMeshTopology);
EXPORT_METHOD(PolyCylinder,updateMeshGeometry);
| gpl-3.0 |
davidlaietta/obm-genesis-child | front-page.php | 713 | <?php
/**
* Front Page Template
*
* Child Theme Name: OBM-Genesis-Child
* Author: Orange Blossom Media
* Url: https://orangeblossommedia.com/
*
* @package OBM-Genesis-Child
*/
// Execute custom home page. If no widgets active, then loop.
add_action( 'genesis_meta', 'obm_custom_homepage' );
/**
* Controls display of homepage
*/
function obm_custom_homepage() {
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
// Remove default page content.
remove_action( 'genesis_loop', 'genesis_do_loop' );
add_action( 'genesis_loop', 'obm_do_home_loop' );
}
/**
* Creates a custom loop for the homepage content.
*/
function obm_do_home_loop() {
}
genesis();
| gpl-3.0 |
dmsimard/ara | ara/setup/__init__.py | 1094 | # Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA 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.
#
# ARA 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 ARA. If not, see <http://www.gnu.org/licenses/>.
import os
# The path where ARA is installed (parent directory)
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
plugins = os.path.abspath(os.path.join(path, "plugins"))
action_plugins = os.path.abspath(os.path.join(plugins, "action"))
callback_plugins = os.path.abspath(os.path.join(plugins, "callback"))
lookup_plugins = os.path.abspath(os.path.join(plugins, "lookup"))
| gpl-3.0 |
AltOS-Rust/cm0-port | src/interrupt/mod.rs | 4891 | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*/
//! This module defines interrupt behavior.
mod defs;
mod enable;
mod pending;
mod priority;
use volatile::Volatile;
use self::enable::{ISER, ICER};
use self::pending::{ISPR, ICPR};
use self::priority::IPR;
use self::defs::*;
use core::ops::{Deref, DerefMut};
pub use self::priority::Priority;
// Defines all the perpherials that have interrupts.
#[allow(missing_docs)]
#[derive(Copy, Clone)]
pub enum Hardware {
Wwdg = NVIC_WWDG_INT,
Pvdvddio2 = NVIC_PVDVDDIO2_INT,
Rtc = NVIC_RTC_INT,
Flash = NVIC_FLASH_INT,
Rcccrs = NVIC_RCCCRS_INT,
Exti01 = NVIC_EXTI01_INT,
Exti23 = NVIC_EXTI23_INT,
Exti415 = NVIC_EXTI415_INT,
Tsc = NVIC_TSC_INT,
Dmach1 = NVIC_DMACH1_INT,
Dmach23 = NVIC_DMACH23_INT,
Dmach4Plus = NVIC_DMACH4PLUS_INT,
Adccomp = NVIC_ADCCOMP_INT,
Tim1Brkup = NVIC_TIM1BRKUP_INT,
Tim1cc = NVIC_TIM1CC_INT,
Tim2 = NVIC_TIM2_INT,
Tim3 = NVIC_TIM3_INT,
Tim6 = NVIC_TIM6_INT,
Tim7 = NVIC_TIM7_INT,
Tim14 = NVIC_TIM14_INT,
Tim15 = NVIC_TIM15_INT,
Tim16 = NVIC_TIM16_INT,
Tim17 = NVIC_TIM17_INT,
I2C1 = NVIC_I2C1_INT,
I2C2 = NVIC_I2C2_INT,
Spi1 = NVIC_SPI1_INT,
Spi2 = NVIC_SPI2_INT,
Usart1 = NVIC_USART1_INT,
Usart2 = NVIC_USART2_INT,
Usart3Plus = NVIC_USART3PLUS_INT,
Ceccan = NVIC_CECCAN_INT,
Usb = NVIC_USB_INT,
}
/// Get an instance of the nested vector interrupt control.
pub fn nvic() -> Nvic {
Nvic::new()
}
pad_field!(PadSmall[0x7C]);
pad_field!(PadLarge[0x17C]);
#[derive(Copy, Clone, Debug)]
#[repr(C)]
#[doc(hidden)]
pub struct RawNvic {
iser: ISER,
_pad0: PadSmall,
icer: ICER,
_pad1: PadSmall,
ispr: ISPR,
_pad2: PadSmall,
icpr: ICPR,
_pad3: PadLarge,
ipr: [IPR; 8],
}
/// Controls the interrupt vectors for enabling/disabling interrupts for the peripherals.
pub struct Nvic(Volatile<RawNvic>);
impl Nvic {
fn new() -> Self {
unsafe { Nvic(Volatile::new(NVIC_ADDR as *const _)) }
}
}
impl Deref for Nvic {
type Target = RawNvic;
fn deref(&self) -> &Self::Target {
&*(self.0)
}
}
impl DerefMut for Nvic {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *(self.0)
}
}
impl RawNvic {
/// Enable the interrupt for the specified peripheral.
pub fn enable_interrupt(&mut self, hardware: Hardware) {
self.iser.enable_interrupt(hardware);
}
/// Disable the interrupt for the specified peripheral.
pub fn disable_interrupt(&mut self, hardware: Hardware) {
self.icer.disable_interrupt(hardware);
}
/// Check if the interrupt for the peripheral is enabled.
pub fn interrupt_is_enabled(&self, hardware: Hardware) -> bool {
self.iser.interrupt_is_enabled(hardware)
}
/// Cause an interrupt for the specified peripheral to be set pending.
///
/// If the interrupt is enabled, the interrupt handler will be called.
/// Otherwise, no interrupt will be generated until the interrupt is enabled
/// for the specified peripheral.
pub fn set_pending(&mut self, hardware: Hardware) {
self.ispr.set_pending(hardware);
}
/// Clear the pending interrupt for the specified peripheral.
pub fn clear_pending(&mut self, hardware: Hardware) {
self.icpr.clear_pending(hardware);
}
/// Check if interrupt is pending for the specified peripheral.
pub fn interrupt_is_pending(&self, hardware: Hardware) -> bool {
self.ispr.interrupt_is_pending(hardware)
}
/// Set the priority of the interrupt for the specified peripheral.
pub fn set_priority(&mut self, priority: Priority, hardware: Hardware) {
let interrupt = hardware as u8;
let ipr_offset = interrupt / 4;
let priority_offset = interrupt % 4;
self.ipr[ipr_offset as usize].set_priority(priority, priority_offset);
}
/// Get the priority of the interrupt for the specified peripheral.
pub fn get_priority(&self, hardware: Hardware) -> Priority {
let interrupt = hardware as u8;
let ipr_offset = interrupt / 4;
let priority_offset = interrupt % 4;
self.ipr[ipr_offset as usize].get_priority(priority_offset)
}
}
| gpl-3.0 |
Traderain/Wolven-kit | WolvenKit.CR2W/Types/W3/RTTIConvert/W3InteractionSwitch.cs | 999 | using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class W3InteractionSwitch : W3PhysicalSwitch
{
[Ordinal(1)] [RED("isActivatedByPlayer")] public CBool IsActivatedByPlayer { get; set;}
[Ordinal(2)] [RED("focusModeHighlight")] public CEnum<EFocusModeVisibility> FocusModeHighlight { get; set;}
[Ordinal(3)] [RED("interactionActiveInState")] public CEnum<ESwitchState> InteractionActiveInState { get; set;}
public W3InteractionSwitch(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3InteractionSwitch(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | gpl-3.0 |
smourph/mes-elus | tests/Entity/Datagouv/Acteur/InfoNaissanceTest.php | 1352 | <?php
namespace App\Tests\Entity\Datagouv\Acteur;
use App\Entity\Datagouv\Acteur\InfoNaissance;
use DateTime;
use PHPUnit\Framework\TestCase;
/**
* Class InfoNaissanceTest.
*/
class InfoNaissanceTest extends TestCase
{
public function testGetterAndSetter(): void
{
$infoNaissance = new InfoNaissance();
$infoNaissance->setDateNais(new DateTime('2001-01-01'));
$this->assertEquals(new DateTime('2001-01-01'), $infoNaissance->getDateNais());
$infoNaissance->setVilleNais('ville1');
$this->assertEquals('ville1', $infoNaissance->getVilleNais());
$infoNaissance->setDepNais('dep1');
$this->assertEquals('dep1', $infoNaissance->getDepNais());
$infoNaissance->setPaysNais('pays1');
$this->assertEquals('pays1', $infoNaissance->getPaysNais());
}
public function testNullableAttributes(): void
{
$infoNaissance = new InfoNaissance();
$infoNaissance->setDateNais(null);
$this->assertNull($infoNaissance->getDateNais());
$infoNaissance->setVilleNais(null);
$this->assertNull($infoNaissance->getVilleNais());
$infoNaissance->setDepNais(null);
$this->assertNull($infoNaissance->getDepNais());
$infoNaissance->setPaysNais(null);
$this->assertNull($infoNaissance->getPaysNais());
}
}
| gpl-3.0 |
rbuj/FreeRouting | src/main/java/net/freerouting/freeroute/BoardMenuParameter.java | 2528 | /*
* Copyright (C) 2014 Alfons Wirtz
* website www.freerouting.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 at <http://www.gnu.org/licenses/>
* for more details.
*
* BoardWindowsMenu.java
*
* Created on 12. Februar 2005, 06:08
*/
package net.freerouting.freeroute;
import java.util.Locale;
import java.util.Map;
import static java.util.Map.entry;
/**
* Creates the parameter menu of a board frame.
*
* @author Alfons Wirtz
*/
@SuppressWarnings("serial")
final class BoardMenuParameter extends BoardMenu {
/**
* Returns a new windows menu for the board frame.
*/
static BoardMenuParameter get_instance(BoardFrame p_board_frame) {
BoardMenuParameter parameter_menu = new BoardMenuParameter(p_board_frame);
java.util.ResourceBundle resources = java.util.ResourceBundle.getBundle(
BoardMenuParameter.class.getPackageName() + ".resources.BoardMenuParameter",
Locale.getDefault());
parameter_menu.setText(resources.getString("parameter"));
Map<SavableSubwindowKey, String> menu_items = Map.ofEntries(
entry(SavableSubwindowKey.SELECT_PARAMETER, "select"),
entry(SavableSubwindowKey.ROUTE_PARAMETER, "route"),
entry(SavableSubwindowKey.AUTOROUTE_PARAMETER, "autoroute"),
entry(SavableSubwindowKey.MOVE_PARAMETER, "move"));
for (Map.Entry<SavableSubwindowKey, String> entry : menu_items.entrySet()) {
javax.swing.JMenuItem menu_item = new javax.swing.JMenuItem();
menu_item.setText(resources.getString(entry.getValue()));
menu_item.addActionListener((java.awt.event.ActionEvent evt) -> {
parameter_menu.board_frame.savable_subwindows.get(entry.getKey()).setVisible(true);
});
parameter_menu.add(menu_item);
}
return parameter_menu;
}
/**
* Creates a new instance of BoardSelectMenu
*/
private BoardMenuParameter(BoardFrame p_board_frame) {
super(p_board_frame);
}
}
| gpl-3.0 |
Better-Aether/Better-Aether | src/main/java/com/gildedgames/aether/common/entities/ai/EntityAI.java | 335 | package com.gildedgames.aether.common.entities.ai;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ai.EntityAIBase;
public abstract class EntityAI<T extends Entity> extends EntityAIBase
{
private T entity;
public EntityAI(T entity)
{
this.entity = entity;
}
public T entity()
{
return this.entity;
}
}
| gpl-3.0 |
hbp-unibi/cypress | test/core/test_connector.cpp | 16843 | /*
* Cypress -- C++ Spiking Neural Network Simulation Framework
* Copyright (C) 2016 Andreas Stöckel
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gtest/gtest.h"
#include <cypress/core/connector.hpp>
namespace cypress {
void print_conns(std::vector<LocalConnection>& conns){
for (auto c : conns) {
std::cout << c.src << ", "
<< c.tar << ", " << c.SynapseParameters[0] << ", "
<< c.SynapseParameters[1] << std::endl;
}
}
TEST(connector, all_to_all)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 2, 1, 0, 5, Connector::all_to_all(0.16, 0.1)},
{0, 2, 4, 2, 0, 5, Connector::all_to_all(0.1, 0.05)},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{
{0, 0, 0.16, 0.1}, {0, 1, 0.16, 0.1},
{0, 2, 0.16, 0.1}, {0, 3, 0.16, 0.1},
{0, 4, 0.16, 0.1}, {1, 0, 0.16, 0.1},
{1, 1, 0.16, 0.1}, {1, 2, 0.16, 0.1},
{1, 3, 0.16, 0.1}, {1, 4, 0.16, 0.1},},
{{2, 0, 0.1, 0.05}, {2, 1, 0.1, 0.05},
{2, 2, 0.1, 0.05}, {2, 3, 0.1, 0.05},
{2, 4, 0.1, 0.05}, {3, 0, 0.1, 0.05},
{3, 1, 0.1, 0.05}, {3, 2, 0.1, 0.05},
{3, 3, 0.1, 0.05}, {3, 4, 0.1, 0.05},
}}),
connections);
connections = instantiate_connections({
{0, 0, 2, 1, 0, 5, Connector::all_to_all(0.16, 0.1, false)},
{0, 2, 4, 2, 0, 5, Connector::all_to_all(0.1, 0.05, false)},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{
{0, 0, 0.16, 0.1}, {0, 1, 0.16, 0.1},
{0, 2, 0.16, 0.1}, {0, 3, 0.16, 0.1},
{0, 4, 0.16, 0.1}, {1, 0, 0.16, 0.1},
{1, 1, 0.16, 0.1}, {1, 2, 0.16, 0.1},
{1, 3, 0.16, 0.1}, {1, 4, 0.16, 0.1},},
{{2, 0, 0.1, 0.05}, {2, 1, 0.1, 0.05},
{2, 2, 0.1, 0.05}, {2, 3, 0.1, 0.05},
{2, 4, 0.1, 0.05}, {3, 0, 0.1, 0.05},
{3, 1, 0.1, 0.05}, {3, 2, 0.1, 0.05},
{3, 3, 0.1, 0.05}, {3, 4, 0.1, 0.05},}
}),
connections);
connections = instantiate_connections(
{{0, 0, 2, 0, 0, 5, Connector::all_to_all(0.16, 0.1, true)}});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{{0, 0, 0.16, 0.1},
{0, 1, 0.16, 0.1},
{0, 2, 0.16, 0.1},
{0, 3, 0.16, 0.1},
{0, 4, 0.16, 0.1},
{1, 0, 0.16, 0.1},
{1, 1, 0.16, 0.1},
{1, 2, 0.16, 0.1},
{1, 3, 0.16, 0.1},
{1, 4, 0.16, 0.1}}}),
connections);
// pid_src nid_src0 nid_src1 pid_tar nid_tar0 nid_tar1 connector
connections = instantiate_connections(
{{0, 0, 2, 0, 0, 5, Connector::all_to_all(0.16, 0.1, false)}});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{{0, 1, 0.16, 0.1},
{0, 2, 0.16, 0.1},
{0, 3, 0.16, 0.1},
{0, 4, 0.16, 0.1},
{1, 0, 0.16, 0.1},
{1, 2, 0.16, 0.1},
{1, 3, 0.16, 0.1},
{1, 4, 0.16, 0.1}}}),
connections);
}
TEST(connector, one_to_one)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 2, 1, 3, 5, Connector::one_to_one(0.16, 0.1)},
{0, 2, 4, 2, 10, 12, Connector::one_to_one(0.1, 0.05)},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{
{0, 3, 0.16, 0.1},
{1, 4, 0.16, 0.1},},
{{2, 10, 0.1, 0.05},
{3, 11, 0.1, 0.05},}
}),
connections);
}
TEST(connector, from_list)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::from_list({{
{0, 1, 0.16, 0.0},
{10, 8, 0.1, 0.0},
{11, 3, 0.12},
{12, 3, 0.00, 0.0},
{12, 3, 0.05},
{14, 3, -0.05, 0.0},
{12, 2, 0.00, -1.0},
}})},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{
{0, 1, 0.16, 0.0},
{10, 8, 0.1, 0.0},
{11, 3, 0.12},
{12, 3, 0.05},
{14, 3, -0.05, 0.0},}
})[0],
connections[0]);
}
TEST(connector, from_list_limited_range)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 16, 1, 0, 4,
Connector::from_list({{
{0, 1, 0.16, 0.0},
{10, 8, 0.1, 0.0},
{11, 3, 0.12},
{12, 3, 0.00, 0.0},
{12, 3, 0.05},
{14, 3, -0.05, 0.0},
{12, 2, 0.00, -1.0},}
})},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({
{{0, 1, 0.16, 0.0},
{11, 3, 0.12},
{12, 3, 0.05},
{14, 3, -0.05, 0.0},
}}),
connections);
}
TEST(connector, functor)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 16, 1, 0, 4,
Connector::functor([](NeuronIndex src, NeuronIndex tar) {
if (src == tar) {
return Synapse(0.16, 0.1);
}
return Synapse();
})},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{
{0, 0, 0.16, 0.1},
{1, 1, 0.16, 0.1},
{2, 2, 0.16, 0.1},
{3, 3, 0.16, 0.1},}
}),
connections);
}
TEST(connector, uniform_functor)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 16, 1, 0, 4,
Connector::functor(
[](NeuronIndex src, NeuronIndex tar) { return src == tar; }, 0.16,
0.1)},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({{
{0, 0, 0.16, 0.1},
{1, 1, 0.16, 0.1},
{2, 2, 0.16, 0.1},
{3, 3, 0.16, 0.1},}
}),
connections);
}
TEST(connector, uniform_functor_huge_matrix)
{
std::vector<std::vector<LocalConnection>> connections = instantiate_connections({
{0, 0, 10000, 1, 0, 10000,
Connector::functor(
[](NeuronIndex src, NeuronIndex tar) {
return src == tar && src < 4 && tar < 4;
},
0.16, 0.1)},
});
EXPECT_EQ(std::vector<std::vector<LocalConnection>>({
{{0, 0, 0.16, 0.1},
{1, 1, 0.16, 0.1},
{2, 2, 0.16, 0.1},
{3, 3, 0.16, 0.1},
}}),
connections);
}
TEST(connector, fixed_probability)
{
std::vector<std::vector<LocalConnection>> connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1)},
});
std::vector<std::vector<LocalConnection>> connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1)},
});
EXPECT_TRUE(connections1[0].size() < 16 * 16 * 0.3);
EXPECT_TRUE(connections2[0].size() < 16 * 16 * 0.3);
EXPECT_TRUE(connections1[0] != connections2[0]);
StaticSynapse synap({0.015, 1});
connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_probability(Connector::all_to_all(synap), 0.1)},
});
EXPECT_TRUE(connections1[0].size() < 16 * 16 * 0.3);
for (size_t i = 0; i < 20; i++) {
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1, true)},
});
EXPECT_TRUE(connections1[0].size() < 16 * 16 * 0.3);
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 1.0, true)},
});
EXPECT_TRUE(connections1[0].size() == 16 * 16);
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 1.0, false)},
});
EXPECT_TRUE(connections1[0].size() == 15 * 16);
for (auto conn : connections1[0]) {
EXPECT_TRUE(conn.src != conn.tar);
}
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1, false)},
});
EXPECT_TRUE(connections1[0].size() < 16 * 16 * 0.3);
for (auto conn : connections1[0]) {
EXPECT_TRUE(conn.src != conn.tar);
}
}
}
TEST(connector, fixed_probability_seed)
{
std::vector<LocalConnection> connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1,
size_t(436283))},
})[0];
std::vector<LocalConnection> connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1,
size_t(436283))},
})[0];
EXPECT_TRUE(connections1.size() < 16 * 16 * 0.3);
EXPECT_TRUE(connections2.size() < 16 * 16 * 0.3);
EXPECT_TRUE(connections1 == connections2);
for (size_t i = 0; i < 20; i++) {
std::vector<LocalConnection> connections3 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_probability(Connector::all_to_all(), 0.1, 436283,
false)},
})[0];
EXPECT_TRUE(connections1.size() < 16 * 16 * 0.3);
for (auto conn : connections3) {
EXPECT_TRUE(conn.src != conn.tar);
}
EXPECT_TRUE(connections3 != connections2);
}
}
TEST(connector, fixed_fan_in)
{
std::vector<LocalConnection> connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_in(8, 0.1, 1.0)},
})[0];
std::vector<LocalConnection> connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_in(16, 0.1, 1.0)},
})[0];
std::vector<LocalConnection> connections3 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::all_to_all(0.1, 1.0)},
})[0];
std::vector<size_t> fan_in(16);
for (auto c : connections1) {
fan_in[c.tar]++;
}
for (size_t fi : fan_in) {
EXPECT_EQ(8U, fi);
}
EXPECT_TRUE(connections1.size() == 8 * 16);
EXPECT_TRUE(connections2.size() == 16 * 16);
EXPECT_TRUE(connections2 == connections3);
// No self Connections
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16, Connector::fixed_fan_in(8, 0.1, 1.0, false)},
})[0];
connections2 = instantiate_connections({
{0, 0, 16, 0, 0, 16, Connector::fixed_fan_in(16, 0.1, 1.0, false)},
})[0];
connections3 = instantiate_connections({
{0, 0, 16, 0, 0, 16, Connector::all_to_all(0.1, 1.0, false)},
})[0];
std::vector<size_t> fan_in2(16);
for (auto c : connections1) {
fan_in2[c.tar]++;
}
for (size_t fi : fan_in2) {
EXPECT_EQ(8U, fi);
}
for (auto conn : connections1) {
EXPECT_TRUE(conn.src != conn.tar);
}
for (auto conn : connections2) {
EXPECT_TRUE(conn.src != conn.tar);
}
EXPECT_EQ(size_t(8 * 16), connections1.size());
EXPECT_EQ(size_t(16 * 15), connections2.size());
EXPECT_TRUE(connections2 == connections3);
// No self connections, different pops
connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_in(8, 0.1, 1.0, false)},
})[0];
connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_in(16, 0.1, 1.0, false)},
})[0];
connections3 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::all_to_all(0.1, 1.0, false)},
})[0];
std::vector<size_t> fan_in3(16);
for (auto c : connections1) {
fan_in3[c.tar]++;
}
for (size_t fi : fan_in3) {
EXPECT_EQ(8U, fi);
}
EXPECT_EQ(size_t(8 * 16), connections1.size());
EXPECT_EQ(size_t(16 * 16), connections2.size());
EXPECT_TRUE(connections2 == connections3);
}
TEST(connector, fixed_fan_in_seed)
{
std::vector<LocalConnection>connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_fan_in(8, 0.1, 1.0, size_t(8791))},
})[0];
std::vector<LocalConnection> connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_fan_in(8, 0.1, 1.0, size_t(8791))},
})[0];
std::vector<LocalConnection> connections3 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_fan_in(8, 0.1, 1.0, size_t(8792))},
})[0];
EXPECT_TRUE(connections1 == connections2);
EXPECT_TRUE(connections2 != connections3);
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_fan_in(8, 0.1, 1.0, size_t(8791), false)},
})[0];
connections2 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_fan_in(8, 0.1, 1.0, size_t(8791), false)},
})[0];
EXPECT_TRUE(connections1 == connections2);
}
TEST(connector, fixed_fan_out)
{
std::vector<LocalConnection> connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_out(8, 0.1, 1.0)},
})[0];
std::vector<LocalConnection> connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_out(16, 0.1, 1.0)},
})[0];
std::vector<LocalConnection> connections3 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::all_to_all(0.1, 1.0)},
})[0];
std::vector<size_t> fan_out(16);
for (auto c : connections1) {
fan_out[c.src]++;
}
for (size_t fo : fan_out) {
EXPECT_EQ(8U, fo);
}
EXPECT_TRUE(connections1.size() == 8 * 16);
EXPECT_TRUE(connections2.size() == 16 * 16);
EXPECT_TRUE(connections2 == connections3);
// No self Connections
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16, Connector::fixed_fan_out(8, 0.1, 1.0, false)},
})[0];
connections2 = instantiate_connections({
{0, 0, 16, 0, 0, 16, Connector::fixed_fan_out(16, 0.1, 1.0, false)},
})[0];
connections3 = instantiate_connections({
{0, 0, 16, 0, 0, 16, Connector::all_to_all(0.1, 1.0, false)},
})[0];
std::vector<size_t> fan_out2(16);
for (auto c : connections1) {
fan_out2[c.src]++;
}
for (size_t fo : fan_out2) {
EXPECT_EQ(8U, fo);
}
for (auto conn : connections1) {
EXPECT_TRUE(conn.src != conn.tar);
}
for (auto conn : connections2) {
EXPECT_TRUE(conn.src != conn.tar);
}
EXPECT_EQ(size_t(8 * 16), connections1.size());
EXPECT_EQ(size_t(16 * 15), connections2.size());
EXPECT_TRUE(connections2 == connections3);
// No self connections, different pops
connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_out(8, 0.1, 1.0, false)},
})[0];
connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::fixed_fan_out(16, 0.1, 1.0, false)},
})[0];
connections3 = instantiate_connections({
{0, 0, 16, 1, 0, 16, Connector::all_to_all(0.1, 1.0, false)},
})[0];
std::vector<size_t> fan_out3(16);
for (auto c : connections1) {
fan_out3[c.src]++;
}
for (size_t fo : fan_out3) {
EXPECT_EQ(8U, fo);
}
EXPECT_EQ(size_t(8 * 16), connections1.size());
EXPECT_EQ(size_t(16 * 16), connections2.size());
EXPECT_TRUE(connections2 == connections3);
}
TEST(connector, fixed_fan_out_seed)
{
std::vector<LocalConnection> connections1 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_fan_out(8, 0.1, 1.0, size_t(8791))},
})[0];
std::vector<LocalConnection> connections2 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_fan_out(8, 0.1, 1.0, size_t(8791))},
})[0];
std::vector<LocalConnection> connections3 = instantiate_connections({
{0, 0, 16, 1, 0, 16,
Connector::fixed_fan_out(8, 0.1, 1.0, size_t(8792))},
})[0];
EXPECT_TRUE(connections1 == connections2);
EXPECT_TRUE(connections2 != connections3);
connections1 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_fan_out(8, 0.1, 1.0, size_t(8791), false)},
})[0];
connections2 = instantiate_connections({
{0, 0, 16, 0, 0, 16,
Connector::fixed_fan_out(8, 0.1, 1.0, size_t(8791), false)},
})[0];
EXPECT_TRUE(connections1 == connections2);
}
} // namespace cypress
| gpl-3.0 |
swarm-lab/videoplayR | src/vpModule.cpp | 3430 | #include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include "opencv2/opencv.hpp"
#include "vpImage.hpp"
#include "vpVideo.hpp"
#include "vpStream.hpp"
#include "io.hpp"
#include "imgProc.hpp"
RCPP_MODULE(vp) {
Rcpp::class_<vpImage>("vpImage")
.field_readonly("type", &vpImage::type, "Returns image type.")
.field_readonly("dim", &vpImage::dim, "Returns the dimensions in pixels of the image.")
.method("img2r", &vpImage::img2r, "Converts image to R matrix or array.")
;
Rcpp::class_<vpVideo>("vpVideo")
.field_readonly("length", &vpVideo::length, "Returns total number of frames in the video.")
.field_readonly("fps", &vpVideo::fps, "Returns the framerate of the video.")
.field_readonly("dim", &vpVideo::dim, "Returns the dimensions in pixels of the video.")
;
Rcpp::class_<vpStream>("vpStream")
.field_readonly("dim", &vpStream::dim, "Returns the dimensions in pixels of the video stream.")
.field_readonly("brightness", &vpStream::brightness, "Returns the brightness setting of the video stream.")
.field_readonly("contrast", &vpStream::contrast, "Returns the contrast setting of the video stream.")
.field_readonly("saturation", &vpStream::saturation, "Returns the saturation setting of the video stream.")
.field_readonly("hue", &vpStream::hue, "Returns the hue setting of the video stream.")
.field_readonly("gain", &vpStream::gain, "Returns the gain setting of the video stream.")
.field_readonly("exposure", &vpStream::exposure, "Returns the exposure setting of the video stream.")
.method("set", &vpStream::set, "Set value of a video stream setting.")
;
Rcpp::function("_readImg", &_readImg, Rcpp::List::create(Rcpp::_["filename"]), "Load image file in memory.");
Rcpp::function("_writeImg", &_writeImg, Rcpp::List::create(Rcpp::_["filename"], Rcpp::_["image"]), "Save image object to file.");
Rcpp::function("_readVid", &_readVid, Rcpp::List::create(Rcpp::_["filename"]), "Load video file in memory.");
Rcpp::function("readStream", &readStream, Rcpp::List::create(Rcpp::_["cam"] = 0), "Open camera stream.");
Rcpp::function("release", &release, Rcpp::List::create(Rcpp::_["stream"]), "Release open video stream.");
Rcpp::function("getFrame", &getFrame, Rcpp::List::create(Rcpp::_["video"], Rcpp::_["frame"]), "Grab a specific frame from a video.");
Rcpp::function("nextFrame", &nextFrame, Rcpp::List::create(Rcpp::_["stream"]), "Grab next frame from a video stream.");
Rcpp::function("_img2r", &_img2r, Rcpp::List::create(Rcpp::_["image"]), "Convert a vpImage object to a matrix or an array.");
Rcpp::function("r2img", &r2img, Rcpp::List::create(Rcpp::_["array"], Rcpp::_["numeric"] = false), "Convert a matrix or an array to a vpImage object.");
Rcpp::function("ddd2d", &ddd2d, Rcpp::List::create(Rcpp::_["image"]), "Flatten a 3-channels image to 1 channel.");
Rcpp::function("d2ddd", &d2ddd, Rcpp::List::create(Rcpp::_["image"]), "Expand a 1-channel image to 3 channels.");
Rcpp::function("thresholding", &thresholding, Rcpp::List::create(Rcpp::_["image"], Rcpp::_["thres"], Rcpp::_["type"]), "Convert image to binary image .");
Rcpp::function("blend", &blend, Rcpp::List::create(Rcpp::_["image1"], Rcpp::_["image2"], Rcpp::_["operation"]), "Element-wise operations on image objects .");
Rcpp::function("blobDetector", &blobDetector, Rcpp::List::create(Rcpp::_["image"]), "Find blobs in binary image.");
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_gCIDE/src/tmp/generated_gcide/Grammar.java | 1243 | package tmp.generated_gcide;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Grammar extends GenASTNode implements ISourceFile {
public Grammar(ASTStringNode findintroductionblock, ArrayList<Production> production, ASTStringNode eof, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<ASTStringNode>("findintroductionblock", findintroductionblock),
new PropertyZeroOrMore<Production>("production", production),
new PropertyOne<ASTStringNode>("eof", eof)
}, firstToken, lastToken);
}
public Grammar(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public IASTNode deepCopy() {
return new Grammar(cloneProperties(),firstToken,lastToken);
}
public ASTStringNode getFindintroductionblock() {
return ((PropertyOne<ASTStringNode>)getProperty("findintroductionblock")).getValue();
}
public ArrayList<Production> getProduction() {
return ((PropertyZeroOrMore<Production>)getProperty("production")).getValue();
}
public ASTStringNode getEof() {
return ((PropertyOne<ASTStringNode>)getProperty("eof")).getValue();
}
}
| gpl-3.0 |
MinedroidFTW/DualCraft | org/server/classic/model/impl/WaterBehaviour.java | 4770 | package dualcraft.org.server.classic.model.impl;
/*License
====================
Copyright (c) 2010-2012 Daniel Vidmar
We use a modified GNU gpl v 3 license for this.
GNU gpl v 3 is included in License.txt
The modified part of the license is some additions which state the following:
"Redistributions of this project in source or binary must give credit to UnXoft Interactive and DualCraft"
"Redistributions of this project in source or binary must modify at least 300 lines of code in order to release
an initial version. This will require documentation or proof of the 300 modified lines of code."
"Our developers reserve the right to add any additions made to a redistribution of DualCraft into the main
project"
"Our developers reserver the right if they suspect a closed source software using any code from our project
to request to overview the source code of the suspected software. If the owner of the suspected software refuses
to allow a devloper to overview the code then we shall/are granted the right to persue legal action against
him/her"*/
import dualcraft.org.server.classic.Configuration;
import dualcraft.org.server.classic.model.BlockBehaviour;
import dualcraft.org.server.classic.model.BlockConstants;
import dualcraft.org.server.classic.model.BlockManager;
import dualcraft.org.server.classic.model.Level;
import java.util.ArrayList;
import java.util.Collections;
/**
* A block behaviour that handles water. Takes into account water's preference
* for downward flow.
*
*/
public class WaterBehaviour implements BlockBehaviour {
public void handlePassive(Level level, int x, int y, int z, int type) {
level.queueActiveBlockUpdate(x, y, z);
}
public void handleDestroy(Level level, int x, int y, int z, int type) {
}
public void handleScheduledBehaviour(Level level, int x, int y, int z, int type) {
// represents different directions in the Cartesian plane, z axis is
// ignored and handled specially
Integer[][] spreadRules = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 1, 0 }, { 0, -1, 0 } };
ArrayList<Integer[]> shuffledRules = new ArrayList<Integer[]>();
for(Integer[] rule : spreadRules)
shuffledRules.add(rule);
Collections.shuffle(shuffledRules);
spreadRules = shuffledRules.toArray(spreadRules);
int spongeRadius = Configuration.getConfiguration().getSpongeRadius();
for (int spongeX = (-1 * spongeRadius); spongeX <= spongeRadius; spongeX++) {
for (int spongeY = (-1 * spongeRadius); spongeY <= spongeRadius; spongeY++) {
for (int spongeZ = (-1 * spongeRadius); spongeZ <= spongeRadius; spongeZ++) {
if (level.getBlock(x + spongeX, y + spongeY, z + spongeZ) == BlockConstants.SPONGE)
return;
}
}
}
byte underBlock = level.getBlock(x, y, z - 1);
// there is lava under me
if (underBlock == BlockConstants.LAVA || underBlock == BlockConstants.STILL_LAVA) {
level.setBlock(x, y, z, BlockConstants.AIR);
level.setBlock(x, y, z - 1, BlockConstants.ROCK);
// move me down
} else if (!BlockManager.getBlockManager().getBlock(underBlock).isSolid() && !BlockManager.getBlockManager().getBlock(underBlock).isLiquid()) {
level.setBlock(x, y, z - 1, BlockConstants.WATER);
level.setBlock(x, y, z, BlockConstants.AIR);
// spread outward
} else {
OUTERMOST_OUTWARD: for (int i = 0; i <= spreadRules.length - 1; i++) {
byte thisOutwardBlock = level.getBlock(x + spreadRules[i][0], y + spreadRules[i][1], z + spreadRules[i][2]);
for (int spongeX = (-1 * spongeRadius); spongeX <= spongeRadius; spongeX++) {
for (int spongeY = (-1 * spongeRadius); spongeY <= spongeRadius; spongeY++) {
for (int spongeZ = (-1 * spongeRadius); spongeZ <= spongeRadius; spongeZ++) {
if (level.getBlock(x + spreadRules[i][0] + spongeX, y + spreadRules[i][1] + spongeY, z + spreadRules[i][2] + spongeZ) == BlockConstants.SPONGE)
break OUTERMOST_OUTWARD;
}
}
}
// check for lava
if (thisOutwardBlock == BlockConstants.LAVA || thisOutwardBlock == BlockConstants.STILL_LAVA) {
level.setBlock(x, y, z, BlockConstants.AIR);
level.setBlock(x + spreadRules[i][0], y + spreadRules[i][1], z + spreadRules[i][2], BlockConstants.ROCK);
} else if (level.getBlock(x + spreadRules[i][0], y + spreadRules[i][1], z + spreadRules[i][2] - 1) == BlockConstants.AIR &&
level.getBlock(x, y, z - 1) == BlockConstants.WATER) {
break OUTERMOST_OUTWARD;
} else if (!BlockManager.getBlockManager().getBlock(thisOutwardBlock).isSolid() && !BlockManager.getBlockManager().getBlock(thisOutwardBlock).isLiquid()) {
//level.setBlock(x, y, z, BlockConstants.AIR);
level.setBlock(x + spreadRules[i][0], y + spreadRules[i][1], z + spreadRules[i][2], BlockConstants.WATER);
}
}
}
}
}
| gpl-3.0 |
Endika/odoo-saas-tools | saas_server/__openerp__.py | 467 | {
'name': 'SaaS Server',
'version': '1.0.0',
'author': 'Ivan Yelizariev',
'category': 'SaaS',
'license': 'GPL-3',
'website': 'https://it-projects.info',
'depends': ['auth_oauth', 'saas_base', 'saas_utils', 'website'],
'data': [
'views/saas_server.xml',
'views/res_config.xml',
'data/auth_oauth_data.xml',
'data/ir_config_parameter.xml',
'data/pre_install.yml',
],
'installable': True,
}
| gpl-3.0 |
munhyunsu/Hobby | SocketExample/tcp_client.py | 274 | #!/usr/bin/env python3
# Echo client program (TCP)
import socket
HOST = '127.0.0.1 '
PORT = 50007
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
| gpl-3.0 |
pschmitt/hass-config | config/hass/www/community/lovelace-hass-aarlo/hass-aarlo.js | 44757 |
const LitElement = Object.getPrototypeOf(
customElements.get("ha-panel-lovelace")
);
const html = LitElement.prototype.html;
class AarloGlance extends LitElement {
// To quieten down JetBrains...
// created_at_pretty;
// states;
// image_click;
// door_bell;
// door_lock;
// door2_bell;
// door2_lock;
// top_title;
// top_date;
// top_status;
// videos;
static get properties() {
return {
// XXX I wanted these in a Object types but litElement doesn't seem
// to catch property changes in an object...
// What media are showing.
// These are changed by user input on the GUI
_image: String,
_video: String,
_stream: String,
_library: String,
_libraryOffset: String,
// Any time a render is needed we bump this number.
_change: Number,
}
}
constructor() {
super();
this._hass = null;
this._config = null;
this._change = 0;
this._hls = null;
this.resetStatuses();
this.resetVisiblity();
}
static get outerStyleTemplate() {
return html`
<style>
ha-card {
position: relative;
min-height: 48px;
overflow: hidden;
}
.box {
white-space: var(--paper-font-common-nowrap_-_white-space); overflow: var(--paper-font-common-nowrap_-_overflow); text-overflow: var(--paper-font-common-nowrap_-_text-overflow);
position: absolute;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.4);
padding: 4px 8px;
font-size: 16px;
line-height: 36px;
color: white;
display: flex;
justify-content: space-between;
}
.box-top {
top: 0;
}
.box-bottom {
bottom: 0;
}
.box-bottom-small {
bottom: 0;
line-height: 30px;
}
.box-title {
font-weight: 500;
margin-left: 4px;
}
.box-status {
font-weight: 500;
margin-right: 4px;
text-transform: capitalize;
}
ha-icon {
cursor: pointer;
padding: 2px;
color: #a9a9a9;
}
ha-icon.state-update {
color: #cccccc;
}
ha-icon.state-on {
color: white;
}
ha-icon.state-warn {
color: orange;
}
ha-icon.state-error {
color: red;
}
</style>
`;
}
static get innerStyleTemplate() {
return html`
<style>
div.base-16x9 {
width: 100%;
overflow: hidden;
margin: 0;
padding-top: 55%;
position: relative;
}
.img-16x9 {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
transform: translate(-50%, -50%);
cursor: pointer;
}
.video-16x9 {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: auto;
transform: translate(-50%, -50%);
}
.library-16x9 {
cursor: pointer;
width: 100%;
}
.lrow {
display: flex;
margin: 6px 2px 6px 2px;
}
.lcolumn {
flex: 32%;
padding: 2px;
}
.hidden {
display: none;
}
#brokenImage {
background: grey url("/static/images/image-broken.svg") center/36px
no-repeat;
}
.slidecontainer {
width: 70%;
text-align: center;
}
.slider {
-webkit-appearance: none;
width: 100%;
height: 10px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 10px;
height: 10px;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 10px;
height: 10px;
background: #4CAF50;
cursor: pointer;
}
</style>
`;
}
render() {
return html`
${AarloGlance.outerStyleTemplate}
<ha-card>
${AarloGlance.innerStyleTemplate}
<div id="aarlo-wrapper" class="base-16x9">
<video class="${this._v.stream} video-16x9"
id="stream-${this._s.cameraId}"
poster="${this._streamPoster}"
@ended="${() => { this.stopStream(); }}"
@mouseover="${() => { this.mouseOverVideo(); }}"
@click="${() => { this.clickVideo(); }}">
Your browser does not support the video tag.
</video>
<video class="${this._v.video} video-16x9"
autoplay playsinline
id="video-${this._s.cameraId}"
src="${this._video}"
type="${this._videoType}"
poster="${this._videoPoster}"
@ended="${() => { this.stopVideo(); }}"
@mouseover="${() => { this.mouseOverVideo(); }}"
@click="${() => { this.clickVideo(); }}">
Your browser does not support the video tag.
</video>
<img class="${this._v.image} img-16x9"
id="image-${this._s.cameraId}"
src="${this._image}"
alt="${this._s.imageFullDate}"
title="${this._s.imageFullDate}"
@click="${() => { this.clickImage(); }}">
</img>
<div class="${this._v.library} img-16x9" >
<div class="lrow">
<div class="lcolumn">
<img class="${this._s.libraryItem[0].hidden} library-16x9"
src="${this._s.libraryItem[0].thumbnail}"
alt="${this._s.libraryItem[0].captured_at}"
title="${this._s.libraryItem[0].captured_at}"
@click="${() => { this.showLibraryVideo(0); }}"/>
<img class="${this._s.libraryItem[3].hidden} library-16x9"
src="${this._s.libraryItem[3].thumbnail}"
alt="${this._s.libraryItem[3].captured_at}"
title="${this._s.libraryItem[3].captured_at}"
@click="${() => { this.showLibraryVideo(3); }}"/>
<img class="${this._s.libraryItem[6].hidden} library-16x9"
src="${this._s.libraryItem[6].thumbnail}"
alt="${this._s.libraryItem[6].captured_at}"
title="${this._s.libraryItem[6].captured_at}"
@click="${() => { this.showLibraryVideo(6); }}"/>
</div>
<div class="lcolumn">
<img class="${this._s.libraryItem[1].hidden} library-16x9"
src="${this._s.libraryItem[1].thumbnail}"
alt="${this._s.libraryItem[1].captured_at}"
title="${this._s.libraryItem[1].captured_at}"
@click="${() => { this.showLibraryVideo(1); }}"/>
<img class="${this._s.libraryItem[4].hidden} library-16x9"
src="${this._s.libraryItem[4].thumbnail}"
alt="${this._s.libraryItem[4].captured_at}"
title="${this._s.libraryItem[4].captured_at}"
@click="${() => { this.showLibraryVideo(4); }}"/>
<img class="${this._s.libraryItem[7].hidden} library-16x9"
src="${this._s.libraryItem[7].thumbnail}"
alt="${this._s.libraryItem[7].captured_at}"
title="${this._s.libraryItem[7].captured_at}"
@click="${() => { this.showLibraryVideo(7); }}"/>
</div>
<div class="lcolumn">
<img class="${this._s.libraryItem[2].hidden} library-16x9"
src="${this._s.libraryItem[2].thumbnail}"
alt="${this._s.libraryItem[2].captured_at}"
title="${this._s.libraryItem[2].captured_at}"
@click="${() => { this.showLibraryVideo(2); }}"/>
<img class="${this._s.libraryItem[5].hidden} library-16x9"
src="${this._s.libraryItem[5].thumbnail}"
alt="${this._s.libraryItem[5].captured_at}"
title="${this._s.libraryItem[5].captured_at}"
@click="${() => { this.showLibraryVideo(5); }}"/>
<img class="${this._s.libraryItem[8].hidden} library-16x9"
src="${this._s.libraryItem[8].thumbnail}"
alt="${this._s.libraryItem[8].captured_at}"
title="${this._s.libraryItem[8].captured_at}"
@click="${() => { this.showLibraryVideo(8); }}"/>
</div>
</div>
</div>
<div class="${this._v.brokeStatus} img-16x9" style="height: 100px" id="brokenImage"></div>
</div>
<div class="box box-top ${this._v.topBar}">
<div class="box-title ${this._v.topTitle}">
${this._s.cameraName}
</div>
<div class="box-status ${this._v.topDate} ${this._v.image_date}" title="${this._s.imageFullDate}">
${this._s.imageDate}
</div>
<div class="box-status ${this._v.topStatus}">
${this._s.cameraState}
</div>
</div>
<div class="box box-bottom ${this._v.bottomBar}">
<div class="box-title ${this._v.bottomTitle}">
${this._s.cameraName}
</div>
<div>
<ha-icon @click="${() => { this.moreInfo(this._s.motionId); }}" class="${this._s.motionOn} ${this._v.motion}" icon="mdi:run-fast" title="${this._s.motionText}"></ha-icon>
<ha-icon @click="${() => { this.moreInfo(this._s.soundId); }}" class="${this._s.soundOn} ${this._v.sound}" icon="mdi:ear-hearing" title="${this._s.soundText}"></ha-icon>
<ha-icon @click="${() => { this.showLibrary(0); }}" class="${this._s.capturedOn} ${this._v.captured}" icon="${this._s.capturedIcon}" title="${this._s.capturedText}"></ha-icon>
<ha-icon @click="${() => { this.showOrStopStream(); }}" class="${this._s.playOn} ${this._v.play}" icon="${this._s.playIcon}" title="${this._s.playText}"></ha-icon>
<ha-icon @click="${() => { this.wsUpdateSnapshot(); }}" class="${this._s.snapshotOn} ${this._v.snapshot}" icon="${this._s.snapshotIcon}" title="${this._s.snapshotText}"></ha-icon>
<ha-icon @click="${() => { this.moreInfo(this._s.batteryId); }}" class="${this._s.batteryState} ${this._v.battery}" icon="mdi:${this._s.batteryIcon}" title="${this._s.batteryText}"></ha-icon>
<ha-icon @click="${() => { this.moreInfo(this._s.signalId); }}" class="state-update ${this._v.signal}" icon="${this._s.signalIcon}" title="${this._s.signalText}"></ha-icon>
</div>
<div class="box-title ${this._v.bottomDate} ${this._v.image_date}" title="${this._s.imageFullDate}">
${this._s.imageDate}
</div>
<div class="box-status ${this._v.doorStatus}">
<ha-icon @click="${() => { this.moreInfo(this._s.doorId); }}" class="${this._s.doorOn} ${this._v.door}" icon="${this._s.doorIcon}" title="${this._s.doorText}"></ha-icon>
<ha-icon @click="${() => { this.moreInfo(this._s.doorBellId); }}" class="${this._s.doorBellOn} ${this._v.doorBell}" icon="${this._s.doorBellIcon}" title="${this._s.doorBellText}"></ha-icon>
<ha-icon @click="${() => { this.toggleLock(this._s.doorLockId); }}" class="${this._s.doorLockOn} ${this._v.doorLock}" icon="${this._s.doorLockIcon}" title="${this._s.doorLockText}"></ha-icon>
<ha-icon @click="${() => { this.moreInfo(this._s.door2Id); }}" class="${this._s.door2On} ${this._v.door2}" icon="${this._s.door2Icon}" title="${this._s.door2Text}"></ha-icon>
<ha-icon @click="${() => { this.moreInfo(this._s.door2BellId); }}" class="${this._s.door2BellOn} ${this._v.door2Bell}" icon="${this._s.door2BellIcon}" title="${this._s.door2BellText}"></ha-icon>
<ha-icon @click="${() => { this.toggleLock(this._s.door2LockId); }}" class="${this._s.door2LockOn} ${this._v.door2Lock}" icon="${this._s.door2LockIcon}" title="${this._s.door2LockText}"></ha-icon>
</div>
<div class="box-status ${this._v.bottomStatus}">
${this._s.cameraState}
</div>
</div>
<div class="box box-bottom-small ${this._v.library}">
<div >
<ha-icon @click="${() => { this.setLibraryBase(this._libraryOffset - 9); }}" class="${this._v.libraryPrev} state-on" icon="mdi:chevron-left" title="previous"></ha-icon>
</div>
<div >
<ha-icon @click="${() => { this.stopLibrary(); }}" class="state-on" icon="mdi:close" title="close library"></ha-icon>
</div>
<div >
<ha-icon @click="${() => { this.setLibraryBase(this._libraryOffset + 9); }}" class="${this._v.libraryNext} state-on" icon="mdi:chevron-right" title="next"></ha-icon>
</div>
</div>
<div class="box box-bottom ${this._v.videoControls}">
<div >
<ha-icon @click="${() => { this.controlStopVideoOrStream(); }}" class="${this._v.videoStop}" icon="mdi:stop" title="Click to stop"></ha-icon>
<ha-icon @click="${() => { this.controlPlayVideo(); }}" class="${this._v.videoPlay}" icon="mdi:play" title="Click to play"></ha-icon>
<ha-icon @click="${() => { this.controlPauseVideo(); }}" class="${this._v.videoPause}" icon="mdi:pause" title="Click to pause"></ha-icon>
</div>
<div class='slidecontainer'>
<input type="range" id="video-seek-${this._s.cameraId}" value="0" min="1" max="100" class="slider ${this._v.videoSeek}">
</div>
<div >
<ha-icon @click="${() => { this.controlFullScreen(); }}" class="${this._v.videoFull}" icon="mdi:fullscreen" title="Click to go full screen"></ha-icon>
</div>
</div>
</ha-card>
`;
}
throwError( error ) {
console.error( error );
throw new Error( error )
}
changed() {
this._change++
}
getState(_id, default_value = '') {
return this._hass !== null && _id in this._hass.states ?
this._hass.states[_id] : {
state: default_value,
attributes: {
friendly_name: 'unknown',
wired_only: false,
image_source: "unknown",
charging: false
}
};
}
emptyLibrary() {
this._s.libraryItem = [ ];
while( this._s.libraryItem.length < 9 ) {
this._s.libraryItem.push( { 'hidden':'hidden','thumbnail':'/static/images/image-broken.svg','captured_at':'' } )
}
}
resetVisiblity() {
this._v = {
// media
image: 'hidden',
stream: 'hidden',
video: 'hidden',
library: 'hidden',
broke: 'hidden',
// decorations
play: 'hidden',
snapshot: 'hidden',
libraryPrev: 'hidden',
libraryNext: 'hidden',
topBar: 'hidden',
bottomBar: 'hidden',
doorStatus: 'hidden',
videoControls: 'hidden',
// sensors
date: 'hidden',
battery: 'hidden',
signal: 'hidden',
motion: 'hidden',
sound: 'hidden',
captured: 'hidden',
door: 'hidden',
door2: 'hidden',
doorLock: 'hidden',
door2Lock: 'hidden',
doorBell: 'hidden',
door2Bell: 'hidden',
videoPlay: 'hidden',
videoStop: 'hidden',
videoPause: 'hidden',
videoSeek: 'hidden',
videoFull: 'hidden',
}
}
resetStatuses() {
this._s = {
cameraName: 'unknown',
cameraState: 'unknown',
imageSource: 'unknown',
playOn: 'not-used',
playText: 'not-used',
playIcon: 'mdi:camera',
snapshotOn: 'not-used',
snapshotText: 'not-used',
snapshotIcon: 'mdi:camera',
batteryIcon: 'not-used',
batteryState: 'state-update',
batteryText: 'not-used',
signalText: 'not-used',
signalIcon: 'mdi:wifi-strength-4',
motionOn: 'not-used',
motionText: 'not-used',
soundOn: 'not-used',
soundText: 'not-used',
capturedText: 'not-used',
capturedOn: '',
capturedIcon: 'mdi:file-video',
doorOn: 'not-used',
doorText: 'not-used',
doorIcon: 'not-used',
door2On: 'not-used',
door2Text: 'not-used',
door2Icon: 'not-used',
doorLockOn: 'not-used',
doorLockText: 'not-used',
doorLockIcon: 'not-used',
door2LockOn: 'not-used',
door2LockText: 'not-used',
door2LockIcon: 'not-used',
doorBellOn: 'not-used',
doorBellText: 'not-used',
doorBellIcon: 'not-used',
door2BellOn: 'not-used',
door2BellText: 'not-used',
door2BellIcon: 'not-used',
};
this.emptyLibrary();
}
updateStatuses( oldValue ) {
// nothing?
if ( this._hass === null ) {
return;
}
// CAMERA
const camera = this.getState(this._s.cameraId,'unknown');
// Initial setting? Get camera name.
if ( oldValue === null ) {
this._s.cameraName = this._config.name ? this._config.name : camera.attributes.friendly_name;
}
// See if camera has changed. Update on the off chance something useful
// has happened.
if ( camera.state !== this._s.cameraState ) {
if ( this._s.cameraState === 'taking snapshot' ) {
console.log( 'updating1 ' + this._s.cameraName + ':' + this._s.cameraState + '-->' + camera.state );
this.wsUpdateCameraImageSrc();
this.updateCameraImageSourceLater(5);
this.updateCameraImageSourceLater(10)
} else {
console.log( 'updating2 ' + this._s.cameraName + ':' + this._s.cameraState + '-->' + camera.state );
this.wsUpdateCameraImageSrc()
}
}
// Save out current state for later.
this._s.cameraState = camera.state;
if ( this._s.imageSource !== camera.attributes.image_source ) {
console.log( 'updating3 ' + this._s.cameraName + ':' + this._s.imageSource + '-->' + camera.attributes.image_source );
this._s.imageSource = camera.attributes.image_source
}
// FUNCTIONS
if( this._v.play === '' ) {
this._s.playOn = 'state-on';
if ( camera.state !== 'streaming' ) {
this._s.playText = 'click to live-stream';
this._s.playIcon = 'mdi:play'
} else {
this._s.playText = 'click to stop stream';
this._s.playIcon = 'mdi:stop'
}
}
if( this._v.snapshot === '' ) {
this._s.snapshotOn = '';
this._s.snapshotText = 'click to update image';
this._s.snapshotIcon = 'mdi:camera'
}
// SENSORS
if( this._v.battery === '' ) {
if ( camera.attributes.wired_only ) {
this._s.batteryText = 'Plugged In';
this._s.batteryIcon = 'power-plug';
this._s.batteryState = 'state-update';
} else {
const battery = this.getState(this._s.batteryId, 0);
const batteryPrefix = camera.attributes.charging ? 'battery-charging' : 'battery';
this._s.batteryText = 'Battery Strength: ' + battery.state +'%';
this._s.batteryIcon = batteryPrefix + ( battery.state < 10 ? '-outline' :
( battery.state > 90 ? '' : '-' + Math.round(battery.state/10) + '0' ) );
this._s.batteryState = battery.state < 25 ? 'state-warn' : ( battery.state < 15 ? 'state-error' : 'state-update' );
}
}
if( this._v.signal === '' ) {
const signal = this.getState(this._s.signalId, 0);
this._s.signalText = 'Signal Strength: ' + signal.state;
this._s.signalIcon = signal.state === 0 ? 'mdi:wifi-outline' : 'mdi:wifi-strength-' + signal.state;
}
if( this._v.motion === '' ) {
this._s.motionOn = this.getState(this._s.motionId,'off').state === 'on' ? 'state-on' : '';
this._s.motionText = 'Motion: ' + (this._s.motionOn !== '' ? 'detected' : 'clear');
}
if( this._v.sound === '' ) {
this._s.soundOn = this.getState(this._s.soundId,'off').state === 'on' ? 'state-on' : '';
this._s.soundText = 'Sound: ' + (this._s.soundOn !== '' ? 'detected' : 'clear');
}
if( this._v.captured === '' ) {
const captured = this.getState(this._s.captureId, 0).state;
const last = this.getState(this._s.lastId, 0).state;
this._s.capturedText = 'Captured: ' + ( captured === 0 ? 'nothing today' : captured + ' clips today, last at ' + last );
this._s.capturedIcon = this._video ? 'mdi:stop' : 'mdi:file-video';
this._s.capturedOn = captured !== 0 ? 'state-update' : ''
}
// OPTIONAL DOORS
if( this._v.door === '' ) {
const doorState = this.getState(this._s.doorId, 'off');
this._s.doorOn = doorState.state === 'on' ? 'state-on' : '';
this._s.doorText = doorState.attributes.friendly_name + ': ' + (this._s.doorOn === '' ? 'closed' : 'open');
this._s.doorIcon = this._s.doorOn === '' ? 'mdi:door' : 'mdi:door-open';
}
if( this._v.door2 === '' ) {
const door2State = this.getState(this._s.door2Id, 'off');
this._s.door2On = door2State.state === 'on' ? 'state-on' : '';
this._s.door2Text = door2State.attributes.friendly_name + ': ' + (this._s.door2On === '' ? 'closed' : 'open');
this._s.door2Icon = this._s.door2On === '' ? 'mdi:door' : 'mdi:door-open';
}
if( this._v.doorLock === '' ) {
const doorLockState = this.getState(this._s.doorLockId, 'locked');
this._s.doorLockOn = doorLockState.state === 'locked' ? 'state-on' : 'state-warn';
this._s.doorLockText = doorLockState.attributes.friendly_name + ': ' + (this._s.doorLockOn === 'state-on' ? 'locked (click to unlock)' : 'unlocked (click to lock)');
this._s.doorLockIcon = this._s.doorLockOn === 'state-on' ? 'mdi:lock' : 'mdi:lock-open';
}
if( this._v.door2Lock === '' ) {
const door2LockState = this.getState(this._s.door2LockId, 'locked');
this._s.door2LockOn = door2LockState.state === 'locked' ? 'state-on' : 'state-warn';
this._s.door2LockText = door2LockState.attributes.friendly_name + ': ' + (this._s.door2LockOn === 'state-on' ? 'locked (click to unlock)' : 'unlocked (click to lock)');
this._s.door2LockIcon = this._s.door2LockOn === 'state-on' ? 'mdi:lock' : 'mdi:lock-open';
}
if( this._v.doorBell === '' ) {
const doorBellState = this.getState(this._s.doorBellId, 'off');
this._s.doorBellOn = doorBellState.state === 'on' ? 'state-on' : '';
this._s.doorBellText = doorBellState.attributes.friendly_name + ': ' + (this._s.doorBellOn === 'state-on' ? 'ding ding!' : 'idle');
this._s.doorBellIcon = 'mdi:doorbell-video';
}
if( this._v.door2Bell === '' ) {
const door2BellState = this.getState(this._s.door2BellId, 'off');
this._s.door2BellOn = door2BellState.state === 'on' ? 'state-on' : '';
this._s.door2BellText = door2BellState.attributes.friendly_name + ': ' + (this._s.door2BellOn === 'state-on' ? 'ding ding!' : 'idle');
this._s.door2BellIcon = 'mdi:doorbell-video';
}
this.changed();
}
updateMedia() {
// reset everything...
this._v.stream = 'hidden';
this._v.video = 'hidden';
this._v.library = 'hidden';
this._v.libraryPrev = 'hidden';
this._v.libraryNext = 'hidden';
this._v.image = 'hidden';
this._v.topBar = 'hidden';
this._v.bottomBar = 'hidden';
this._v.brokeStatus = 'hidden';
this._v.videoControls = 'hidden';
if( this._stream ) {
this._v.stream = '';
this._v.videoPlay = 'hidden';
this._v.videoStop = '';
this._v.videoPause = 'hidden';
this._v.videoSeek = 'hidden';
this._v.videoFull = '';
this.showVideoControls(2);
// Start HLS to handle video streaming.
if (this._hls === null) {
const video = this.shadowRoot.getElementById('stream-' + this._s.cameraId);
if (Hls.isSupported()) {
this._hls = new Hls();
this._hls.attachMedia(video);
this._hls.on(Hls.Events.MEDIA_ATTACHED, () => {
this._hls.loadSource(this._stream);
this._hls.on(Hls.Events.MANIFEST_PARSED, () => {
video.play();
});
})
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = this._stream;
video.addEventListener('loadedmetadata', function () {
video.play();
});
}
}
} else if( this._video ) {
this._v.video = '';
this._v.videoPlay = 'hidden';
this._v.videoStop = '';
this._v.videoPause = '';
this._v.videoSeek = '';
this._v.videoFull = '';
this.setUpSeekBar();
this.showVideoControls(2);
} else if ( this._library ) {
this.emptyLibrary();
this._v.library = '';
this._v.libraryPrev = this._libraryOffset > 0 ? '' : 'hidden';
this._v.libraryNext = this._libraryOffset + 9 < this._library.length ? '' : 'hidden';
let i;
let j;
const last = Math.min(this._libraryOffset + 9, this._library.length);
for( i = 0, j = this._libraryOffset; j < last; i++,j++ ) {
let captured_text = this._library[j].created_at_pretty;
if ( this._library[j].trigger && this._library[j].trigger !== '' ) {
captured_text += ' (' + this._library[j].trigger.toLowerCase() + ')'
}
this._s.libraryItem[i] = ( { 'hidden':'',
'thumbnail':this._library[j].thumbnail,
'captured_at':'captured: ' + captured_text } );
}
} else if ( this._image ) {
const camera = this.getState(this._s.cameraId,'unknown');
this._v.image = '';
this._v.brokeStatus = 'hidden';
this._v.topBar = this._v.topTitle === '' || this._v.topDate === '' || this._v.topStatus === '' ? '':'hidden';
this._v.bottomBar = '';
// image title
this._s.imageFullDate = camera.attributes.image_source ? camera.attributes.image_source : '';
this._s.imageDate = '';
if( this._s.imageFullDate.startsWith('capture/') ) {
this._s.imageDate = this.getState(this._s.lastId,0).state;
this._s.imageFullDate = 'automatically captured at ' + this._s.imageDate;
} else if( this._s.imageFullDate.startsWith('snapshot/') ) {
this._s.imageDate = this._s.imageFullDate.substr(9);
this._s.imageFullDate = 'snapshot captured at ' + this._s.imageDate;
}
} else {
this._v.brokeStatus = '';
this._v.topBar = this._v.topTitle === '' || this._v.topDate === '' || this._v.topStatus === '' ? '':'hidden';
this._v.bottomBar = '';
}
this.changed();
}
updated(changedProperties) {
changedProperties.forEach( (oldValue, propName) => {
switch( propName ) {
case '_image':
case '_video':
case '_stream':
case '_library':
case '_libraryOffset':
this.updateMedia();
break;
case '_change':
console.log( 'change is updated' );
break;
}
});
}
set hass( hass ) {
const old = this._hass;
this._hass = hass;
this.updateStatuses( old )
}
checkConfig() {
if ( this._hass === null ) {
return;
}
if ( !(this._s.cameraId in this._hass.states) ) {
this.throwError( 'unknown camera' );
}
if ( this._s.doorId && !(this._s.doorId in this._hass.states) ) {
this.throwError( 'unknown door' )
}
if ( this._s.doorBellId && !(this._s.doorBellId in this._hass.states) ) {
this.throwError( 'unknown door bell' )
}
if ( this._s.doorLockId && !(this._s.doorLockId in this._hass.states) ) {
this.throwError( 'unknown door lock' )
}
if ( this._s.door2Id && !(this._s.door2Id in this._hass.states) ) {
this.throwError( 'unknown door (#2)' )
}
if ( this._s.door2BellId && !(this._s.door2BellId in this._hass.states) ) {
this.throwError( 'unknown door bell (#2)' )
}
if ( this._s.door2LockId && !(this._s.door2LockId in this._hass.states) ) {
this.throwError( 'unknown door lock (#2)' )
}
}
setConfig(config) {
let camera = null;
if( config.entity ) {
camera = config.entity.replace( 'camera.aarlo_','' );
}
if( config.camera ) {
camera = config.camera;
}
if( camera === null ) {
this.throwError( 'missing a camera definition' );
}
if( !config.show ) {
this.throwError( 'missing show components' );
}
// save new config and reset decoration properties
this._config = config;
this.checkConfig();
this.resetStatuses();
// camera and sensors
this._s.cameraId = 'camera.aarlo_' + camera;
this._s.motionId = 'binary_sensor.aarlo_motion_' + camera;
this._s.soundId = 'binary_sensor.aarlo_sound_' + camera;
this._s.batteryId = 'sensor.aarlo_battery_level_' + camera;
this._s.signalId = 'sensor.aarlo_signal_strength_' + camera;
this._s.captureId = 'sensor.aarlo_captured_today_' + camera;
this._s.lastId = 'sensor.aarlo_last_' + camera;
// door definition
this._s.doorId = config.door ? config.door: null;
this._s.doorBellId = config.door_bell ? config.door_bell : null;
this._s.doorLockId = config.door_lock ? config.door_lock : null;
// door2 definition
this._s.door2Id = config.door2 ? config.door2: null;
this._s.door2BellId = config.door2_bell ? config.door2_bell : null;
this._s.door2LockId = config.door2_lock ? config.door2_lock : null;
// what are we hiding?
const hide = this._config.hide || [];
const hide_title = hide.includes('title') ? 'hidden':'';
const hide_date = hide.includes('date') ? 'hidden':'';
const hide_status = hide.includes('status') ? 'hidden':'';
// what are we showing?
const show = this._config.show || [];
// on click
this._v.imageClick = config.image_click ? config.image_click : false;
// ui configuration
this._v.topTitle = config.top_title ? hide_title:'hidden';
this._v.topDate = config.top_date ? hide_date:'hidden';
this._v.topStatus = config.top_status ? hide_status:'hidden';
this._v.bottomTitle = config.top_title ? 'hidden':hide_title;
this._v.bottomDate = config.top_date ? 'hidden':hide_date;
this._v.bottomStatus = config.top_status ? 'hidden':hide_status;
this._v.play = show.includes('play') ? '':'hidden';
this._v.snapshot = show.includes('snapshot') ? '':'hidden';
this._v.battery = show.includes('battery') || show.includes('battery_level') ? '':'hidden';
this._v.signal = show.includes('signal_strength') ? '':'hidden';
this._v.motion = show.includes('motion') ? '':'hidden';
this._v.sound = show.includes('sound') ? '':'hidden';
this._v.captured = show.includes('captured') || show.includes('captured_today') ? '':'hidden';
this._v.image_date = show.includes('image_date') ? '':'hidden';
this._v.door = this._s.doorId ? '':'hidden';
this._v.doorLock = this._s.doorLockId ? '':'hidden';
this._v.doorBell = this._s.doorBellId ? '':'hidden';
this._v.door2 = this._s.door2Id ? '':'hidden';
this._v.door2Lock = this._s.door2LockId ? '':'hidden';
this._v.door2Bell = this._s.door2BellId ? '':'hidden';
this._v.doorStatus = ( this._v.door === '' || this._v.doorLock === '' ||
this._v.doorBell === '' || this._v.door2 === '' ||
this._v.door2Lock === '' || this._v.door2Bell === '' ) ? '':'hidden';
// render changes
this.changed();
}
getCardSize() {
return 3;
}
moreInfo( id ) {
const event = new Event('hass-more-info', {
bubbles: true,
cancelable: false,
composed: true,
});
event.detail = { entityId: id };
this.shadowRoot.dispatchEvent(event);
return event;
}
async wsLoadLibrary(at_most ) {
try {
const library = await this._hass.callWS({
type: "aarlo_library",
entity_id: this._s.cameraId,
at_most: at_most,
});
return ( library.videos.length > 0 ) ? library.videos : null;
} catch (err) {
return null
}
}
async wsStartStream() {
try {
return await this._hass.callWS({
type: "camera/stream",
entity_id: this._s.cameraId,
})
} catch (err) {
return null
}
}
async wsStopStream() {
try {
return await this._hass.callWS({
type: "aarlo_stop_activity",
entity_id: this._s.cameraId,
})
} catch (err) {
return null
}
}
async wsUpdateSnapshot() {
try {
const {content_type: contentType, content} = await this._hass.callWS({
type: "aarlo_snapshot_image",
entity_id: this._s.cameraId,
});
this._image = `data:${contentType};base64, ${content}`;
} catch (err) {
this._image = null
}
}
async wsUpdateCameraImageSrc() {
try {
const {content_type: contentType, content} = await this._hass.callWS({
type: "camera_thumbnail",
entity_id: this._s.cameraId,
});
this._image = `data:${contentType};base64, ${content}`;
} catch (err) {
this._image = null
}
}
async playVideo() {
const video = await this.wsLoadLibrary(1);
if ( video ) {
this._video = video[0].url;
this._videoPoster = video[0].thumbnail;
this._videoType = "video/mp4"
} else {
this._video = null;
this._videoPoster = null;
this._videoType = null
}
}
stopVideo() {
if ( this._video ) {
const video = this.shadowRoot.getElementById('video-' + this._s.cameraId);
video.pause();
this._video = null
}
}
async playStream() {
const stream = await this.wsStartStream();
if (stream) {
this._stream = stream.url;
this._streamPoster = this._image;
} else {
this._stream = null;
this._streamPoster = null;
}
}
async stopStream() {
if (this._stream) {
const stream = this.shadowRoot.getElementById('stream-' + this._s.cameraId);
stream.pause();
await this.wsStopStream();
this._stream = null;
}
if (this._hls) {
this._hls.stopLoad();
this._hls.destroy();
this._hls = null
}
}
showOrStopStream() {
const camera = this.getState(this._s.cameraId,'unknown');
if ( camera.state === 'streaming' ) {
this.stopStream()
} else {
this.playStream()
}
}
async showLibrary(base) {
this._video = null;
this._library = await this.wsLoadLibrary(99);
this._libraryOffset = base
}
showLibraryVideo(index) {
index += this._libraryOffset;
if (this._library && index < this._library.length) {
this._video = this._library[index].url;
this._videoPoster = this._library[index].thumbnail;
} else {
this._video = null;
this._videoPoster = null
}
}
setLibraryBase(base) {
this._libraryOffset = base
}
stopLibrary() {
this.stopVideo();
this._library = null
}
clickImage() {
if ( this._v.imageClick === 'play' ) {
this.playStream()
} else {
this.playVideo()
}
}
clickVideo() {
if (this._v.videoControls === 'hidden') {
this.showVideoControls(2)
} else {
this.hideVideoControls();
}
}
mouseOverVideo() {
this.showVideoControls(2)
}
controlStopVideoOrStream() {
this.stopVideo();
this.stopStream();
}
controlPauseVideo( ) {
const video = this.shadowRoot.getElementById('video-' + this._s.cameraId);
video.pause();
this._v.videoPlay = '';
this._v.videoPause = 'hidden';
this.changed()
}
controlPlayVideo( ) {
const video = this.shadowRoot.getElementById('video-' + this._s.cameraId);
video.play();
this._v.videoPlay = 'hidden';
this._v.videoPause = '';
this.changed()
}
controlFullScreen() {
const prefix = this._stream ? 'stream-' : 'video-';
const video = this.shadowRoot.getElementById( prefix + this._s.cameraId);
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
}
toggleLock( id ) {
if ( this.getState(id,'locked').state === 'locked' ) {
this._hass.callService( 'lock','unlock', { entity_id:id } )
} else {
this._hass.callService( 'lock','lock', { entity_id:id } )
}
}
setUpSeekBar() {
let video = this.shadowRoot.getElementById('video-' + this._s.cameraId);
let seekBar = this.shadowRoot.getElementById('video-seek-' + this._s.cameraId);
video.addEventListener("timeupdate", function() {
seekBar.value = (100 / video.duration) * video.currentTime;
});
seekBar.addEventListener("change", function() {
video.currentTime = video.duration * (seekBar.value / 100);
});
seekBar.addEventListener("mousedown", () => {
this.showVideoControls(0);
video.pause();
});
seekBar.addEventListener("mouseup", () => {
video.play();
this.hideVideoControlsLater()
});
this.showVideoControls(2);
}
showVideoControls(seconds = 0) {
this._v.videoControls = '';
this.hideVideoControlsCancel();
if (seconds !== 0) {
this.hideVideoControlsLater(seconds);
}
this.changed()
}
hideVideoControls() {
this.hideVideoControlsCancel();
this._v.videoControls = 'hidden';
this.changed()
}
hideVideoControlsLater(seconds = 2) {
this.hideVideoControlsCancel();
this._s.controlTimeout = setTimeout(() => {
this._s.controlTimeout = null;
this.hideVideoControls()
}, seconds * 1000);
}
hideVideoControlsCancel() {
if ( this._s.controlTimeout !== null ) {
clearTimeout( this._s.controlTimeout );
this._s.controlTimeout = null
}
}
updateCameraImageSourceLater(seconds = 2) {
setTimeout(() => {
this.wsUpdateCameraImageSrc()
}, seconds * 1000);
}
}
const s = document.createElement("script");
s.src = 'https://cdn.jsdelivr.net/npm/hls.js@latest';
s.onload = function() {
const s2 = document.createElement("script");
s2.src = 'https://cdn.jsdelivr.net/npm/mobile-detect@1.4.3/mobile-detect.min.js';
s2.onload = function() {
customElements.define('aarlo-glance', AarloGlance);
};
document.head.appendChild(s2);
};
document.head.appendChild(s);
| gpl-3.0 |
abueldahab/medalyser | library/Zend/Log/Exception.php | 1147 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
/** Zend_Exception */
require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Log
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
*/
class Zend_Log_Exception extends Zend_Exception
{
}
| gpl-3.0 |
smtech/canvas-management | index.php | 2981 | <?php
require_once 'common.inc.php';
use smtech\CanvasManagement\Toolbox;
use smtech\ReflexiveCanvasLTI\LTI\ToolProvider;
use smtech\ReflexiveCanvasLTI\Exception\ConfigurationException;
/* store any requested actions for future handling */
$action = (empty($_REQUEST['action']) ?
ACTION_UNSPECIFIED :
strtolower($_REQUEST['action'])
);
/* action requests only come from outside the LTI! */
if ($action) {
unset($_SESSION[ToolProvider::class]);
}
/* authenticate LTI launch request, if present */
if ($toolbox->lti_isLaunching()) {
/* http://stackoverflow.com/a/14329752 */
// session_start(); // already called in common.inc.php
@session_destroy(); // TODO I don't feel good about suppressing errors
@session_unset();
@session_start();
@session_regenerate_id(true);
$_SESSION[Toolbox::class] =& $toolbox;
session_write_close();
$toolbox->lti_authenticate();
exit;
}
/* if authenticated LTI launch, redirect to appropriate placement view */
if (!empty($_SESSION[ToolProvider::class]['canvas']['account_id'])) {
$toolbox->smarty_display('home.tpl');
exit;
/* if not authenticated, default to showing credentials */
} else {
$action = (empty($action) ?
ACTION_CONFIG :
$action
);
}
/* process any actions */
switch ($action) {
/* reset cached install data from config file */
case ACTION_INSTALL:
$_SESSION['toolbox'] = Toolbox::fromConfiguration(CONFIG_FILE, true);
$toolbox =& $_SESSION['toolbox'];
/* test to see if we can connect to the API */
try {
$toolbox->getAPI();
} catch (ConfigurationException $e) {
/* if there isn't an API token in config.xml, are there OAuth credentials? */
if ($e->getCode() === ConfigurationException::CANVAS_API_INCORRECT) {
$toolbox->interactiveGetAccessToken('This tool requires access to the Canvas APIs by an administrative user. This API access is used to make (sometimes dramatic) updates to your course and user data via administrative scripts. Please enter the URL of your Canvas instance below (e.g. <code>https://canvas.instructure.com</code> -- the URL that you would enter to log in to Canvas). If you are not already logged in, you will be asked to log in. After logging in, you will be asked to authorize this tool.</p><p>If you are already logged, but <em>not</em> logged in as an administrative user, please log out now, so that you may log in as administrative user to authorize this tool.');
exit;
} else { /* no (understandable) API credentials available -- doh! */
throw $e;
}
}
/* finish by opening consumers control panel */
header('Location: consumers.php');
exit;
/* show LTI configuration XML file */
case ACTION_CONFIG:
header('Content-type: application/xml');
echo $toolbox->saveConfigurationXML();
exit;
}
| gpl-3.0 |
Interfacelab/ilab-media-tools | views/base/fields/password.blade.php | 504 | <div id="setting-{{$name}}" {{(($conditions) ? 'data-conditions="true"' : '')}}>
<div style="display:none">
<input type="password" tabindex="-1">
</div>
<input size='40' type='password' id="{{$name}}" name='{{$name}}' value='{{$value}}' placeholder='{{$placeholder}}'>
@if($description)
<p class='description'>{!! $description !!}</p>
@endif
@if($conditions)
<script id="{{$name}}-conditions" type="text/plain">
{!! json_encode($conditions, JSON_PRETTY_PRINT) !!}
</script>
@endif
</div>
| gpl-3.0 |
zhdk/madek | app/controllers/keywords_controller.rb | 462 | class KeywordsController< ApplicationController
def index
query = params[:query]
with = params[:with]
keywords = Keyword.hacky_search(query).select "DISTINCT ON (keyword_term_id) * "
respond_to do |format|
format.json {
# TODO sort directly on sql query
render :json => view_context.hash_for(keywords, with).sort{|a,b| a[:label].downcase <=> b[:label].downcase}.to_json
}
format.html
end
end
end
| gpl-3.0 |
mbednarski/Chiron | chiron/plotter.py | 4558 | import os
import datetime
import abc
import numpy as np
import matplotlib.pyplot as plt
import sys
import logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
class SeriesTransformer(abc.ABC):
@abc.abstractmethod
def transform(self, data):
pass
class SeriesBase(abc.ABC):
def __init__(self, name, friendly_name=None):
self.name = name
self._location = None
self.friendly_name = friendly_name if friendly_name is not None else name
def set_location(self, location):
self._location = location
def _read_values(self):
files = [os.path.join(self._location, x) for x in os.listdir(self._location)]
files.sort()
values = None
for f in files:
fcontent = np.load(f)
if values is None:
values = fcontent
continue
values = np.vstack((values, fcontent))
return values
@abc.abstractmethod
def _get_data(self):
pass
def plot(self, axis, **kwargs):
data = self._get_data()
axis.plot(data, label=self.friendly_name, **kwargs)
axis.legend()
class RawSeries(SeriesBase):
def _get_data(self):
return self._read_values()
def __init__(self, name, friendly_name=None):
super().__init__(name, friendly_name)
class RollingAverageSeries(SeriesBase):
def __init__(self, name, friendly_name=None, window=50):
super().__init__(name, friendly_name)
self.window = window
def _get_data(self):
data = self._read_values()
data = self._compute_rolling_average(data, self.window)
return data
def _compute_rolling_average(self, array, window):
avgs = np.zeros_like(array)
for i in range(avgs.shape[0]):
avgs[i] = np.mean(array[i - window:i])
return avgs
class MaxSeries(SeriesBase):
def _get_data(self):
data = self._read_values()
data = self._compute_max(data)
return data
def __init__(self, name, friendly_name):
super().__init__(name, friendly_name)
def _compute_max(self, data):
maxs = np.zeros_like(data)
for i in range(maxs.shape[0]):
maxs[i] = np.max(data[:i + 1])
return maxs
class Plotter(object):
def __init__(self, root_directory, shape=(1, 1)):
logger.info("")
self._root_directory = root_directory
self._session_location = None
self._session_datetime = None
self._series_to_plot = []
self._series_locations = {}
self.fig, self.axes = plt.subplots(shape[0], shape[1])
def select_session(self):
raise NotImplementedError()
def select_latest_session(self):
ls = [(x, os.path.join(self._root_directory, x)) for x in os.listdir(self._root_directory)]
ls = filter(lambda x: os.path.isdir(x[1]), ls)
parsed = [
(x[0], x[1],
datetime.datetime.strptime(x[0], '%Y-%m-%d_%H_%M_%S'))
for x
in ls
]
parsed.sort(key=lambda x: x[2])
latest = parsed[-1]
self._session_location = latest[1]
self._session_datetime = latest[2]
self._series_locations = self._get_collections(self._session_location)
def _get_collections(self, root):
ls = [(x, os.path.join(root, x)) for x in os.listdir(root)]
ls = filter(lambda x: os.path.isdir(x[1]), ls)
return dict(list(ls))
def append(self, series, axis=1):
series.set_location(self._series_locations[series.name])
self._series_to_plot.append((series, axis))
def plot(self):
for s, axis in self._series_to_plot:
s.plot(self.axes[axis])
plt.show()
def main():
root_dir = r'C:\p\github\Chiron\chiron\agents\monitor'
p = Plotter(root_dir, shape=(2, 1))
p.select_latest_session()
p.append(RollingAverageSeries('episode_reward', '10 avg reward', 10), 0)
p.append(RollingAverageSeries('episode_reward', '50 avg reward', 50), 0)
p.append(RollingAverageSeries('episode_reward', '100 avg reward', 100), 0)
p.append(RollingAverageSeries('episode_reward', '200 avg reward', 200), 0)
p.append(MaxSeries('episode_reward', 'max reward'), 0)
p.append(RawSeries('epsilon', 'epsilon'), 1)
p.plot()
if __name__ == '__main__':
main()
| gpl-3.0 |
ChaoticEvil/django_base | src/apps/news/admin.py | 1998 | from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
from .models import Category, Tag, News
class CategoryAdmin(admin.ModelAdmin):
fieldsets = [
(
_('Категория'),
{'fields': [('title', 'slug')]}
),
]
prepopulated_fields = {'slug': ('title',)}
list_display = ('id', 'title', 'slug')
list_display_links = ('id', 'title')
search_fields = ['title', 'slug']
class TagAdmin(admin.ModelAdmin):
fieldsets = [
(
_('Тег'),
{'fields': [('title', 'slug')]}
),
]
prepopulated_fields = {'slug': ('title',)}
list_display = ('id', 'title', 'slug')
list_display_links = ('id', 'title')
search_fields = ['title', 'slug']
class NewsAdmin(admin.ModelAdmin):
fieldsets = [
(_('Новость'), {
'fields': [
('title', 'category'), 'cover', 'teaser', 'body', 'tags', 'pub_date', 'gallery', 'is_public'
],
}),
]
radio_fields = {'category': admin.HORIZONTAL}
raw_id_fields = ('gallery',)
autocomplete_lookup_fields = {'fk': ['gallery']}
list_display = ('id', 'img_thumbnail', 'title', 'pub_date', 'author', 'is_public')
list_display_links = ('id', 'img_thumbnail', 'title')
list_per_page = 25
sortable_field_name = 'title'
search_fields = ['title', 'teaser']
list_filter = ['is_public', 'pub_date', 'author', 'category', 'tags']
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
def img_thumbnail(self, obj):
return format_html(
"<img src='%s' alt='%s' />" % (obj.cover.url_sm, obj.title)
)
img_thumbnail.short_description = _('Превью')
img_thumbnail.allow_tags = True
admin.site.register(Tag, TagAdmin)
admin.site.register(News, NewsAdmin)
admin.site.register(Category, CategoryAdmin)
| gpl-3.0 |
informatom/mercator | spec/controllers/orders_controller_spec.rb | 52351 | require 'spec_helper'
describe OrdersController, :type => :controller do
before :each do
no_redirects and act_as_user
@basket = create(:order, user_id: @user.id)
@product = create(:product)
@lineitem = create(:lineitem, order_id: @basket.id,
user_id: @user.id,
product_id: @product.id)
create(:constant_shipping_cost)
@parked_basket = create(:parked_basket, user_id: @user.id)
create(:lineitem, order_id: @parked_basket.id,
user_id: @user.id,
product_id: @product.id)
@newer_gtc = create(:newer_gtc)
request.env['HTTP_REFERER'] = categories_path
end
context "auto actions" do
describe "GET #index_for_user" do
it "renders index template" do
get :index_for_user, user_id: @user.id
expect(response.body).to render_template "orders/index_for_user"
end
end
end
describe "GET #show" do
it "reads current gtc" do
@older_gtc = create(:older_gtc)
get :show, id: @basket.id
expect(assigns(:current_gtc)).to eql @newer_gtc
end
it "reads the parked basket" do
get :show, id: @basket.id
expect(assigns(:parked_basket)).to eql @parked_basket
end
it "unset confirmation for current_user" do
@user.update(confirmation: true)
get :show, id: @basket.id
expect(@user.confirmation).to eql false
end
end
describe "POST #refresh" do
it "loads the order" do
xhr :post, :refresh, id: @basket.id, render: "whatever"
expect(assigns(:order)).to eql @basket
end
end
describe "POST #payment_status" do
it "loads the order" do
post :payment_status, id: @basket.id
expect(assigns(:order)).to eql @basket
end
it "renders confirm" do
post :payment_status, id: @basket.id
expect(response.body).to render_template :confirm
end
end
context "lifecycle actions" do
describe "PUT #do_from_offer" do
it "is available" do
expect(Order::Lifecycle.can_from_offer? @user).to be
end
end
describe "PUT #do_archive_parked_basket" do
it "sets flash messages" do
put :do_archive_parked_basket, id: @parked_basket.id
expect(flash[:notice]).to eql nil
expect(flash[:success]).to eql "The parked basket was archived."
end
it "redirects to" do
put :do_archive_parked_basket, id: @parked_basket.id
expect(response).to redirect_to categories_path
end
end
describe "PUT #do_place" do
before :each do
@user.update(gtc_version_of: @newer_gtc.version_of)
@basket.update(billing_method: "pre_payment")
end
it "loads the order" do
put :do_place, id: @basket.id
expect(assigns(:order)).to eql @basket
end
context "success for mesonic push" do
before :each do
allow(Rails).to receive(:env) {"production"}
expect_any_instance_of(User).to receive(:update_erp_account_nr)
expect_any_instance_of(Order).to receive(:push_to_mesonic) {true}
end
it "updates mesonic erp account nr and pushes to mesonic, if enabled" do
put :do_place, id: @basket.id
end
it "renders confirm" do
put :do_place, id: @basket.id
expect(response.body).to render_template :confirm
end
it "sets the flash messages" do
put :do_place, id: @basket.id
expect(flash[:notice]).to eql nil
expect(flash[:success]).to eql "Your order is transmitted and will be processed shortly."
end
end
context "failure for mesonic push" do
before :each do
allow(Rails).to receive(:env) {"production"}
expect_any_instance_of(User).to receive(:update_erp_account_nr)
expect_any_instance_of(Order).to receive(:push_to_mesonic) {false}
end
it "trues to mesonic erp account nr and pushes to mesonic, if enabled" do
put :do_place, id: @basket.id
end
it "renders confirm" do
put :do_place, id: @basket.id
expect(response.body).to render_template :error
end
it "sets the flash messages" do
put :do_place, id: @basket.id
expect(flash[:notice]).to eql nil
expect(flash[:error]).to eql "Your order could not be processed. We will analyze the problem shortly."
end
end
end
describe "PUT #do_pay" do
before :each do
@user.update(gtc_version_of: @newer_gtc.version_of)
@basket.update(billing_method: "e_payment")
end
it "loads the order" do
put :do_place, id: @basket.id
expect(assigns(:order)).to eql @basket
end
context "successful payment" do
before :each do
expect_any_instance_of(Order).to receive(:pay) { double(Struct, body: {select_payment_response: {location: categories_path }})}
end
it "triggers payment, if enabled" do
put :do_pay, id: @basket.id
end
it "redirects to location in select payment response / response" do
put :do_pay, id: @basket.id
expect(response.body).to redirect_to categories_path
end
end
context "failed payment" do
before :each do
expect_any_instance_of(Order).to receive(:pay) { double(Struct, body: { select_payment_response: { location: nil,
err_text: "some error text" }})}
end
it "triggers payment, if enabled" do
put :do_pay, id: @basket.id
end
it "renders show" do
put :do_pay, id: @basket.id
expect(response.body).to render_template :show
end
it "sets the flash messages" do
put :do_pay, id: @basket.id
expect(flash[:notice]).to eql nil
expect(flash[:error]).to eql "some error text"
end
end
end
describe "PUT #do_cash_payment" do
context "order is basket" do
it "is available for basket" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id)
expect(@order.lifecycle.can_cash_payment? @user).to be
end
it "sets cash_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id)
@order.lifecycle.cash_payment!(@user)
expect(@order.billing_method).to eql "cash_payment"
end
it "it is not avaiilable for non pickup_shipmant" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "parcel_service_shipment",
user_id: @user.id)
put :do_cash_payment, id: @order.id
expect(response).to have_http_status(403)
end
it "it is not available for cash_payment" do
@order = create(:order, billing_method: "cash_payment",
shipping_method: "pickup_shipment",
user_id: @user.id)
put :do_cash_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "accepted_offer")
expect(@order.lifecycle.can_cash_payment? @user).to be
end
it "sets cash_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "accepted_offer")
@order.lifecycle.cash_payment!(@user)
expect(@order.billing_method).to eql "cash_payment"
end
it "it is not avaiilable for non pickup_shipmant" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "parcel_service_shipment",
user_id: @user.id,
state: "accepted_offer")
put :do_cash_payment, id: @order.id
expect(response).to have_http_status(403)
end
it "it is not available for cash_payment" do
@order = create(:order, billing_method: "cash_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "accepted_offer")
put :do_cash_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is payment_failed" do
it "is available for payment_failed" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_cash_payment? @user).to be
end
it "sets cash_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "payment_failed")
@order.lifecycle.cash_payment!(@user)
expect(@order.billing_method).to eql "cash_payment"
end
it "it is not avaiilable for non pickup_shipmant" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "parcel_service_shipment",
user_id: @user.id,
state: "payment_failed")
put :do_cash_payment, id: @order.id
expect(response).to have_http_status(403)
end
it "it is not available for cash_payment" do
@order = create(:order, billing_method: "cash_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "payment_failed")
put :do_cash_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
end
describe "PUT #do_atm_payment" do
context "order is basket" do
it "is available for basket" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id)
expect(@order.lifecycle.can_atm_payment? @user).to be
end
it "sets atm_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id)
@order.lifecycle.atm_payment!(@user)
expect(@order.billing_method).to eql "atm_payment"
end
it "it is not avaiilable for non pickup_shipmant" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "parcel_service_shipment",
user_id: @user.id)
put :do_atm_payment, id: @order.id
expect(response).to have_http_status(403)
end
it "it is not available for atm_payment" do
@order = create(:order, billing_method: "atm_payment",
shipping_method: "pickup_shipment",
user_id: @user.id)
put :do_atm_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "accepted_offer")
expect(@order.lifecycle.can_atm_payment? @user).to be
end
it "sets atm_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "accepted_offer")
@order.lifecycle.atm_payment!(@user)
expect(@order.billing_method).to eql "atm_payment"
end
it "it is not avaiilable for non pickup_shipmant" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "parcel_service_shipment",
user_id: @user.id,
state: "accepted_offer")
put :do_atm_payment, id: @order.id
expect(response).to have_http_status(403)
end
it "it is not available for atm_payment" do
@order = create(:order, billing_method: "atm_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "accepted_offer")
put :do_atm_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is payment_failed" do
it "is available for payment_failed" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_atm_payment? @user).to be
end
it "sets atm_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "payment_failed")
@order.lifecycle.atm_payment!(@user)
expect(@order.billing_method).to eql "atm_payment"
end
it "it is not avaiilable for non pickup_shipmant" do
@order = create(:order, billing_method: "e_payment",
shipping_method: "parcel_service_shipment",
user_id: @user.id,
state: "payment_failed")
put :do_atm_payment, id: @order.id
expect(response).to have_http_status(403)
end
it "it is not available for atm_payment" do
@order = create(:order, billing_method: "atm_payment",
shipping_method: "pickup_shipment",
user_id: @user.id,
state: "payment_failed")
put :do_atm_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
end
describe "PUT #do_pre_payment" do
context "order is basket" do
it "is available for basket" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id)
expect(@order.lifecycle.can_pre_payment? @user).to be
end
it "sets pre_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id)
@order.lifecycle.pre_payment!(@user)
expect(@order.billing_method).to eql "pre_payment"
end
it "it is not available for pre_payment" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id)
put :do_pre_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id,
state: "accepted_offer")
expect(@order.lifecycle.can_pre_payment? @user).to be
end
it "sets pre_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id,
state: "accepted_offer")
@order.lifecycle.pre_payment!(@user)
expect(@order.billing_method).to eql "pre_payment"
end
it "it is not available for pre_payment" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id,
state: "accepted_offer")
put :do_pre_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is payment_failed" do
it "is available for payment_failed" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_pre_payment? @user).to be
end
it "sets pre_payment as billing_method" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id,
state: "payment_failed")
@order.lifecycle.pre_payment!(@user)
expect(@order.billing_method).to eql "pre_payment"
end
it "it is not available for pre_payment" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id,
state: "payment_failed")
put :do_pre_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
end
describe "PUT #do_e_payment" do
context "order is basket" do
it "is available for basket" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id)
expect(@order.lifecycle.can_e_payment? @user).to be
end
it "sets e_payment as billing_method" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id)
@order.lifecycle.e_payment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
it "it is not available for e_payment" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id)
put :do_e_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id,
state: "accepted_offer")
expect(@order.lifecycle.can_e_payment? @user).to be
end
it "sets e_payment as billing_method" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id,
state: "accepted_offer")
@order.lifecycle.e_payment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
it "it is not available for e_payment" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id,
state: "accepted_offer")
put :do_e_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
context "order is payment_failed" do
it "is available for payment_failed" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_e_payment? @user).to be
end
it "sets e_payment as billing_method" do
@order = create(:order, billing_method: "pre_payment",
user_id: @user.id,
state: "payment_failed")
@order.lifecycle.e_payment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
it "it is not available for e_payment" do
@order = create(:order, billing_method: "e_payment",
user_id: @user.id,
state: "payment_failed")
put :do_e_payment, id: @order.id
expect(response).to have_http_status(403)
end
end
end
describe "PUT #do_check" do
before :each do
@older_gtc = create(:older_gtc)
@current_gtc = create(:newer_gtc)
@user.update(gtc_version_of: @current_gtc.version_of)
end
context "order is basket" do
it "is available for basket" do
@order = create(:order, user_id: @user.id)
expect(@order.lifecycle.can_check? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id)
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_check? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil)
expect(@order.lifecycle.can_check? @user).to be_falsy
end
it "is not available if shipping_method is not filled" do
@order = create(:order, user_id: @user.id,
shipping_method: nil)
expect(@order.lifecycle.can_check? @user).to be_falsy
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer")
expect(@order.lifecycle.can_check? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_check? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
state: "accepted_offer")
expect(@order.lifecycle.can_check? @user).to be_falsy
end
it "is not available if shipping_method is not filled" do
@order = create(:order, user_id: @user.id,
shipping_method: nil,
state: "accepted_offer")
expect(@order.lifecycle.can_check? @user).to be_falsy
end
end
context "order is in_payment" do
it "is available for in_payment" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
expect(@order.lifecycle.can_check? @user).to be
end
it "is not available if gtc accepted is not current" do
@user.update(gtc_version_of: @older_gtc.version_of)
@order = create(:order, user_id: @user.id,
state: "in_payment")
expect(@order.lifecycle.can_check? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
state: "accepted_offer")
expect(@order.lifecycle.can_check? @user).to be_falsy
end
it "is not available if shipping_method is not filled" do
@order = create(:order, user_id: @user.id,
shipping_method: nil,
state: "accepted_offer")
expect(@order.lifecycle.can_check? @user).to be_falsy
end
end
end
describe "PUT #do_place" do
before :each do
@older_gtc = create(:older_gtc)
@current_gtc = create(:newer_gtc)
@user.update(gtc_version_of: @current_gtc.version_of)
end
context "order is basket" do
it "is available for basket" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment")
expect(@order.lifecycle.can_place? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_place? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
billing_method: "pre_payment")
expect(@order.lifecycle.can_place? @user).to be_falsy
end
it "is not available if billing method is e-payment" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment")
expect(@order.lifecycle.can_place? @user).to be_falsy
end
it "changes the state to ordered" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment")
@user.update(gtc_version_of: @current_gtc.version_of)
@order.lifecycle.place!(@user)
expect(@order.state).to eql "ordered"
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, user_id: @user.id,
state:"accepted_offer",
billing_method: "pre_payment")
expect(@order.lifecycle.can_place? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
state:"accepted_offer",
billing_method: "pre_payment")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_place? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
state:"accepted_offer",
billing_method: "pre_payment")
expect(@order.lifecycle.can_place? @user).to be_falsy
end
it "is not available if billing method is e-payment" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state:"accepted_offer")
expect(@order.lifecycle.can_place? @user).to be_falsy
end
it "changes the state to ordered" do
@order = create(:order, user_id: @user.id,
state:"accepted_offer",
billing_method: "pre_payment")
@user.update(gtc_version_of: @current_gtc.version_of)
@order.lifecycle.place!(@user)
expect(@order.state).to eql "ordered"
end
end
end
describe "PUT #do_pay" do
before :each do
@older_gtc = create(:older_gtc)
@current_gtc = create(:newer_gtc)
@user.update(gtc_version_of: @current_gtc.version_of)
end
context "order is basket" do
it "is available for basket" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment")
expect(@order.lifecycle.can_pay? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
billing_method: "e_payment")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing method is not e_payment" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "changes the state to ordered" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment")
@user.update(gtc_version_of: @current_gtc.version_of)
@order.lifecycle.pay!(@user)
expect(@order.state).to eql "in_payment"
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "accepted_offer")
expect(@order.lifecycle.can_pay? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "accepted_offer")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
billing_method: "e_payment",
state: "accepted_offer")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing method is not e_payment" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment",
state: "accepted_offer")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "changes the state to ordered" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "accepted_offer")
@user.update(gtc_version_of: @current_gtc.version_of)
@order.lifecycle.pay!(@user)
expect(@order.state).to eql "in_payment"
end
end
context "order is in_payment" do
it "is available for in_payment" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "in_payment")
expect(@order.lifecycle.can_pay? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "in_payment")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
billing_method: "e_payment",
state: "in_payment")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing method is not e_payment" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment",
state: "in_payment")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "changes the state to ordered" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "in_payment")
@user.update(gtc_version_of: @current_gtc.version_of)
@order.lifecycle.pay!(@user)
expect(@order.state).to eql "in_payment"
end
end
context "order is payment_failed" do
it "is available for payment_failed" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "payment_failed")
expect(@order.lifecycle.can_pay? @user).to be
end
it "is not available if gtc accepted is not current" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "payment_failed")
@user.update(gtc_version_of: @older_gtc.version_of)
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing address is not filled" do
@order = create(:order, user_id: @user.id,
billing_city: nil,
billing_method: "e_payment",
state: "payment_failed")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "is not available if billing method is not e_payment" do
@order = create(:order, user_id: @user.id,
billing_method: "pre_payment",
state: "payment_failed")
expect(@order.lifecycle.can_pay? @user).to be_falsy
end
it "changes the state to ordered" do
@order = create(:order, user_id: @user.id,
billing_method: "e_payment",
state: "payment_failed")
@user.update(gtc_version_of: @current_gtc.version_of)
@order.lifecycle.pay!(@user)
expect(@order.state).to eql "in_payment"
end
end
end
describe "PUT #do_failing_payment" do
before :each do
@mpay24_user = create(:mpay24_user)
end
context "order is in_payment" do
it "is available for mpay24_user" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
expect(@order.lifecycle.can_failing_payment? @mpay24_user).to be
end
it "is not available for user" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
expect(@order.lifecycle.can_failing_payment? @user).to be_falsy
end
it "changes the status to payment_failed" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
@order.lifecycle.failing_payment!(@mpay24_user)
expect(@order.state).to eql "payment_failed"
end
end
context "order is payment_failed" do
it "is available for mpay24_user" do
@order = create(:order, user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_failing_payment? @mpay24_user).to be
end
it "is not available for user" do
@order = create(:order, user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_failing_payment? @user).to be_falsy
end
it "changes the status to payment_failed" do
@order = create(:order, user_id: @user.id,
state: "payment_failed")
@order.lifecycle.failing_payment!(@mpay24_user)
expect(@order.state).to eql "payment_failed"
end
end
context "order is paid" do
it "is available for mpay24_user" do
@order = create(:order, user_id: @user.id,
state: "paid")
expect(@order.lifecycle.can_failing_payment? @mpay24_user).to be
end
it "is not available for user" do
@order = create(:order, user_id: @user.id,
state: "paid")
expect(@order.lifecycle.can_failing_payment? @user).to be_falsy
end
it "changes the status to payment_failed" do
@order = create(:order, user_id: @user.id,
state: "paid")
@order.lifecycle.failing_payment!(@mpay24_user)
expect(@order.state).to eql "payment_failed"
end
end
end
describe "PUT #do_successful_payment" do
before :each do
@mpay24_user = create(:mpay24_user)
end
context "order is in_payment" do
it "is available for mpay24_user" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
expect(@order.lifecycle.can_successful_payment? @mpay24_user).to be
end
it "is not available for user" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
expect(@order.lifecycle.can_successful_payment? @user).to be_falsy
end
it "changes the status to payment_failed" do
@order = create(:order, user_id: @user.id,
state: "in_payment")
@order.lifecycle.successful_payment!(@mpay24_user)
expect(@order.state).to eql "paid"
end
end
context "order is payment_failed" do
it "is available for mpay24_user" do
@order = create(:order, user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_successful_payment? @mpay24_user).to be
end
it "is not available for user" do
@order = create(:order, user_id: @user.id,
state: "payment_failed")
expect(@order.lifecycle.can_successful_payment? @user).to be_falsy
end
it "changes the status to payment_failed" do
@order = create(:order, user_id: @user.id,
state: "payment_failed")
@order.lifecycle.successful_payment!(@mpay24_user)
expect(@order.state).to eql "paid"
end
end
context "order is paid" do
it "is available for mpay24_user" do
@order = create(:order, user_id: @user.id,
state: "paid")
expect(@order.lifecycle.can_successful_payment? @mpay24_user).to be
end
it "is not available for user" do
@order = create(:order, user_id: @user.id,
state: "paid")
expect(@order.lifecycle.can_successful_payment? @user).to be_falsy
end
it "changes the status to payment_failed" do
@order = create(:order, user_id: @user.id,
state: "paid")
@order.lifecycle.successful_payment!(@mpay24_user)
expect(@order.state).to eql "paid"
end
end
end
describe "PUT #do_park" do
it "is available for basket" do
@order = create(:order, user_id: @user.id,
state: "basket")
expect(@order.lifecycle.can_park? @user).to be
end
it "changes the status to parked" do
@order = create(:order, user_id: @user.id,
state: "basket")
@order.lifecycle.park!(@user)
expect(@order.state).to eql "parked"
end
end
describe "PUT #do_archive_parked_basket" do
it "is available for parked basket" do
@order = create(:order, user_id: @user.id,
state: "parked")
expect(@order.lifecycle.can_archive_parked_basket? @user).to be
end
it "changes the status to parked" do
@order = create(:order, user_id: @user.id,
state: "parked")
@order.lifecycle.archive_parked_basket!(@user)
expect(@order.state).to eql "archived_basket"
end
end
describe "PUT #do_pickup_shipment" do
before :each do
@shipping_cost_article = create(:shipping_cost_article)
@inventory_versandspesen = create(:inventory_with_two_prices, number: @shipping_cost_article.number,
product_id: @shipping_cost_article.id)
end
context "order is basket" do
it "is available for basket" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "parcel_service_shipment")
expect(@order.lifecycle.can_pickup_shipment? @user).to be
end
it "updates the shipment method" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "parcel_service_shipment")
@order.lifecycle.pickup_shipment!(@user)
expect(@order.shipping_method).to eql "pickup_shipment"
end
it "deletes a shipping cost line" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "parcel_service_shipment")
allow(@order).to receive(:acting_user) { @user }
@order.add_shipment_costs
expect { @order.lifecycle.pickup_shipment!(@user) }.to change {@order.lineitems.count}.by -1
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "parcel_service_shipment")
expect(@order.lifecycle.can_pickup_shipment? @user).to be
end
it "updates the shipment method" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "parcel_service_shipment")
@order.lifecycle.pickup_shipment!(@user)
expect(@order.shipping_method).to eql "pickup_shipment"
end
it "deletes a shipping cost line" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "parcel_service_shipment")
allow(@order).to receive(:acting_user) { @user }
@order.add_shipment_costs
expect { @order.lifecycle.pickup_shipment!(@user) }.to change {@order.lineitems.count}.by -1
end
end
end
describe "PUT #parcel_service_shipment" do
before :each do
@shipping_cost_article = create(:shipping_cost_article)
@inventory_versandspesen = create(:inventory_with_two_prices, number: @shipping_cost_article.number,
product_id: @shipping_cost_article.id)
end
context "order is basket" do
it "is available for basket" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "pickup_shipment")
expect(@order.lifecycle.can_parcel_service_shipment? @user).to be
end
it "updates the shipment method" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "pickup_shipment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.shipping_method).to eql "parcel_service_shipment"
end
it "adds a shipping cost line" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "pickup_shipment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.lineitems.find_by(product_number: @shipping_cost_article.number)).to be_a Lineitem
end
it "is not available for parcel service shipment" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "parcel_service_shipment")
expect(@order.lifecycle.can_parcel_service_shipment? @user).to be false
end
it "is not available for not shippable product" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "pickup_shipment")
@not_shippable_product = create(:product, number: "not shippable",
not_shippable: true)
create(:lineitem, order_id: @order.id,
product_id: @not_shippable_product.id)
expect(@order.lifecycle.can_parcel_service_shipment? @user).to be false
end
it "updates the billing_method, if it was atm_payment" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "pickup_shipment",
billing_method: "atm_payment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
it "updates the billing_method, if it was cash_payment" do
@order = create(:order, user_id: @user.id,
state: "basket",
shipping_method: "pickup_shipment",
billing_method: "cash_payment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
end
context "order is accepted_offer" do
it "is available for accepted_offer" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "pickup_shipment")
expect(@order.lifecycle.can_parcel_service_shipment? @user).to be
end
it "updates the shipment method" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "pickup_shipment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.shipping_method).to eql "parcel_service_shipment"
end
it "adds a shipping cost line" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "pickup_shipment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.lineitems.find_by(product_number: @shipping_cost_article.number)).to be_a Lineitem
end
it "is not available for parcel service shipment" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "parcel_service_shipment")
expect(@order.lifecycle.can_parcel_service_shipment? @user).to be false
end
it "is not available for not shippable product" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "pickup_shipment")
@not_shippable_product = create(:product, number: "not shippable",
not_shippable: true)
create(:lineitem, order_id: @order.id,
product_id: @not_shippable_product.id)
expect(@order.lifecycle.can_parcel_service_shipment? @user).to be false
end
it "updates the billing_method, if it was atm_payment" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "pickup_shipment",
billing_method: "atm_payment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
it "updates the billing_method, if it was cash_payment" do
@order = create(:order, user_id: @user.id,
state: "accepted_offer",
shipping_method: "pickup_shipment",
billing_method: "cash_payment")
@order.lifecycle.parcel_service_shipment!(@user)
expect(@order.billing_method).to eql "e_payment"
end
end
end
describe "PUT #do_delete_all_positions" do
it "is available for basket" do
@order = create(:order, user_id: @user.id,
state: "basket")
@lineitem = create(:lineitem, order_id: @order.id,
product_id: @product.id,
user_id: @user.id)
expect(@order.lifecycle.can_delete_all_positions? @user).to be
end
it "deletes all lineitems" do
@order = create(:order, user_id: @user.id,
state: "basket")
@lineitem = create(:lineitem, order_id: @order.id,
product_id: @product.id,
user_id: @user.id)
@second_product = create(:second_product)
@onother_lineitem = create(:lineitem, order_id: @order.id,
product_id: @second_product.id,
user_id: @user.id)
expect {@order.lifecycle.delete_all_positions!(@user)}.to change {@order.lineitems.count}.by -2
end
it "is not available if there are no lineitems" do
@order = create(:order, user_id: @user.id,
state: "basket")
expect(@order.lifecycle.can_delete_all_positions? @user).to be false
end
end
end
end | gpl-3.0 |
mwveliz/siglas-mppp | apps/funcionarios/modules/funcionario/lib/funcionarioGeneratorConfiguration.class.php | 320 | <?php
/**
* funcionario module configuration.
*
* @package siglas-(institucion)
* @subpackage funcionario
* @author Your name here
* @version SVN: $Id: configuration.php 0.1. 2011-01-23 18:33:00 livio.lopez $
*/
class funcionarioGeneratorConfiguration extends BaseFuncionarioGeneratorConfiguration
{
}
| gpl-3.0 |
magic3org/magic3 | widgets/default_content/include/container/default_contentCommonDef.php | 4161 | <?php
/**
* index.php用共通定義クラス
*
* PHP versions 5
*
* LICENSE: This source file is licensed under the terms of the GNU General Public License.
*
* @package Magic3 Framework
* @author 平田直毅(Naoki Hirata) <naoki@aplo.co.jp>
* @copyright Copyright 2006-2018 Magic3 Project.
* @license http://www.gnu.org/copyleft/gpl.html GPL License
* @version SVN: $Id$
* @link http://www.magic3.org
*/
class default_contentCommonDef
{
static $_contentType = ''; // コンテンツタイプ
static $_deviceType = 0; // デバイスタイプ
static $_deviceTypeName = 'PC'; // デバイスタイプ名
static $_viewContentType = 'ct'; // 参照数カウント用コンテンツタイプ(将来的にはcontentを使用)
// DB定義値
static $CF_USE_JQUERY = 'use_jquery'; // jQueryスクリプトを作成するかどうか
static $CF_USE_CONTENT_TEMPLATE = 'use_content_template'; // コンテンツ単位のテンプレート設定を行うかどうか
static $CF_USE_PASSWORD = 'use_password'; // パスワードアクセス制御
static $CF_PASSWORD_CONTENT = 'password_content'; // パスワード画面コンテンツ
static $CF_LAYOUT_VIEW_DETAIL = 'layout_view_detail'; // コンテンツレイアウト(詳細表示)
static $CF_OUTPUT_HEAD = 'output_head'; // ヘッダ出力するかどうか
static $CF_HEAD_VIEW_DETAIL = 'head_view_detail'; // ヘッダ出力(詳細表示)
const CF_AUTO_GENERATE_ATTACH_FILE_LIST = 'auto_generate_attach_file_list'; // 添付ファイルリストを自動作成
const CONTENT_WIDGET_ID = 'default_content'; // デフォルトの汎用コンテンツ編集ウィジェット
const ATTACH_FILE_DIR = '/etc/content'; // 添付ファイル格納ディレクトリ
const DOWNLOAD_CONTENT_TYPE = '-file'; // ダウンロードするコンテンツのタイプ
const DEFAULT_CONTENT_LAYOUT = '[#BODY#][#FILES#][#PAGES#][#LINKS#]'; // デフォルトのコンテンツレイアウト
const DEFAULT_HEAD_VIEW_DETAIL = '<meta property="og:type" content="article" /><meta property="og:title" content="[#CT_TITLE#]" /><meta property="og:url" content="[#CT_URL#]" /><meta property="og:image" content="[#CT_IMAGE#]" /><meta property="og:description" content="[#CT_DESCRIPTION#]" /><meta property="og:site_name" content="[#SITE_NAME#]" />'; // デフォルトのヘッダ出力(詳細表示)
/**
* 汎用コンテンツ定義値をDBから取得
*
* @param object $db DBオブジェクト
* @return array 取得データ
*/
static function loadConfig($db)
{
$retVal = array();
// 汎用コンテンツ定義を読み込み
$ret = $db->getAllConfig(self::$_contentType, $rows);
if ($ret){
// 取得データを連想配列にする
$configCount = count($rows);
for ($i = 0; $i < $configCount; $i++){
$key = $rows[$i]['ng_id'];
$value = $rows[$i]['ng_value'];
$retVal[$key] = $value;
}
}
return $retVal;
}
/**
* 添付ファイル格納ディレクトリ取得
*
* @return string ディレクトリパス
*/
static function getAttachFileDir()
{
global $gEnvManager;
$dir = $gEnvManager->getIncludePath() . self::ATTACH_FILE_DIR;
if (!file_exists($dir)) mkdir($dir, M3_SYSTEM_DIR_PERMISSION, true/*再帰的*/);
return $dir;
}
/**
* レイアウトからユーザ定義フィールドを取得
*
* @param string $src 変換するデータ
* @return array フィールドID
*/
/* static function parseUserMacro($src)
{
$fields = array();
$pattern = '/' . preg_quote(M3_TAG_START . M3_TAG_MACRO_USER_KEY) . '([A-Z0-9_]+):?(.*?)' . preg_quote(M3_TAG_END) . '/u';
preg_match_all($pattern, $src, $matches, PREG_SET_ORDER);
for ($i = 0; $i < count($matches); $i++){
$key = M3_TAG_MACRO_USER_KEY . $matches[$i][1];
$value = $matches[$i][2];
if (!array_key_exists($key, $fields)) $fields[$key] = $value;
}
return $fields;
}*/
static function parseUserMacro($src)
{
global $gInstanceManager;
static $fields;
if (!isset($fields)) $fields = $gInstanceManager->getTextConvManager()->parseUserMacro($src);
return $fields;
}
}
?>
| gpl-3.0 |
marcgenou/kanpai | kanpai/db/seeds.rb | 16553 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Experience.delete_all
Experience.create!(title: "NYC Marathon" , category: "sport" , description: "New York City Marathon" , image_url: "photos/exp01.jpg" , price: 300 , season: "autumn" , date: "2015-11-01" , duration: "one day" , tags: "marathon, new york city, running" , address: "fort wadsworth, ny")
Experience.create!(title: "Tudor's route" , category: "cultural" , description: "Tudor's route" , image_url: "photos/exp02.jpg" , price: 100 , season: "year-round" , date: "" , duration: "one day" , tags: "tudor, henry viii, london" , address: "hampton court palace, uk")
Experience.create!(title: "Shopping London" , category: "leisure" , description: "Shopping in London" , image_url: "photos/exp03.jpg" , price: 3000 , season: "year-round" , date: "" , duration: "one day" , tags: "shopping, london, harrods, bond street" , address: "bond street london")
Experience.create!(title: "Victorian route" , category: "cultural" , description: "Victorian houses" , image_url: "photos/exp04.jpg" , price: 100 , season: "year-round" , date: "" , duration: "two days" , tags: "queen victoria, downtown abbey, victorian" , address: "westminster palace, uk")
Experience.create!(title: "Parisien gardens" , category: "leisure" , description: "Gardens in Paris" , image_url: "photos/exp05.jpg" , price: 10 , season: "spring" , date: "" , duration: "one day" , tags: "monet, gardens, spring, flowers" , address: "lycee general claude monet, paris")
Experience.create!(title: "Volcanic pedals" , category: "sport" , description: "Bike route around Lanzarote" , image_url: "photos/exp06.jpg" , price: 300 , season: "spring" , date: "" , duration: "five days" , tags: "mtb, lanzarote, volcanoes" , address: "puerto del carmen, lanzarote")
Experience.create!(title: "Scotland on budget" , category: "adventure" , description: "Edinburgh and highlands on a budget" , image_url: "photos/exp07.jpg" , price: 650 , season: "summer" , date: "" , duration: "six days" , tags: "scotland, highlands, edinburgh" , address: "royal mile, edinburgh")
Experience.create!(title: "Geisha's life" , category: "cultural" , description: "Kyoto surroundings" , image_url: "photos/exp08.jpg" , price: 200 , season: "spring" , date: "" , duration: "two days" , tags: "fushimi inari, kyoto, pontocho" , address: "pontocho, kyoto")
Experience.create!(title: "Fletcher's legacy" , category: "adventure" , description: "Pitcairn and south pacific islands" , image_url: "photos/exp09.jpg" , price: 2000 , season: "year-round" , date: "" , duration: "three weeks" , tags: "fletcher captain, bounty, mutiny, pitcairn" , address: "pitcairn")
Experience.create!(title: "Me, my bike and the atlantic" , category: "sport" , description: "Motorbiking in the Azores roads" , image_url: "photos/exp10.jpg" , price: 1000 , season: "summer" , date: "" , duration: "one week" , tags: "moto, atlantic, island, azores, solitude" , address: "azores, portugal")
Experience.create!(title: "The real Tattoine" , category: "adventure" , description: "An adventure travel to the tunisian desert" , image_url: "photos/exp11.jpg" , price: 500 , season: "winter" , date: "" , duration: "four days" , tags: "tunisian, tattoine, star wars, skywalker" , address: "tataouine, tunisia")
Experience.create!(title: "Man TT" , category: "sport" , description: "Isle of Man Tourist Trophy" , image_url: "photos/exp12.jpg" , price: 400 , season: "spring" , date: "2015-05-30" , duration: "two weeks" , tags: "motorbikes, isle of man, tourist trophy" , address: "douglas, isle of man")
Experience.create!(title: "This is for real" , category: "leisure" , description: "Poker tournaments" , image_url: "photos/exp13.jpg" , price: 2000 , season: "year-round" , date: "" , duration: "two days" , tags: "las vegas, texas hold'em, casino, poker" , address: "aria hotel, las vegas")
Experience.create!(title: "Under the Red Sea" , category: "sport" , description: "Diving the Red sea" , image_url: "photos/exp14.jpg" , price: 1500 , season: "winter" , date: "" , duration: "five days" , tags: "red sea, diving, coral, egypt" , address: "marsa alam, egypt")
Experience.create!(title: "Milford track" , category: "sport" , description: "From Te Anau to Milford Sound" , image_url: "photos/exp15.jpg" , price: 300 , season: "winter" , date: "" , duration: "four days" , tags: "new zealand, hiking, trekking, milford" , address: "te anau, new zealand")
Experience.create!(title: "Sufers Paradise" , category: "sport" , description: "Surf in Gold Coast" , image_url: "photos/exp16.jpg" , price: 300 , season: "autumn" , date: "" , duration: "three days" , tags: "surf, gold coast, nobby beach" , address: "sufers paradise, australia")
Experience.create!(title: "Puffins observer" , category: "adventure" , description: "Atlantic puffin observation" , image_url: "photos/exp17.jpg" , price: 300 , season: "spring" , date: "" , duration: "two days" , tags: "puffin, birds, faroe" , address: "faroe islands ")
Experience.create!(title: "The hanami" , category: "leisure" , description: "Picnic in Shinjuku Gyoen" , image_url: "photos/exp18.jpg" , price: 20 , season: "spring" , date: "" , duration: "one day" , tags: "hanami, sakura, cherry blossom, picnic" , address: "shinjuku gyoen, tokyo")
Experience.create!(title: "Hiking Mauritius" , category: "sport" , description: "Mauritius trails and paths" , image_url: "photos/exp19.jpg" , price: 800 , season: "winter" , date: "" , duration: "five days" , tags: "hiking, trails, mauritius" , address: "le pouce,mauritius")
Experience.create!(title: "The last baobab" , category: "cultural" , description: "Madagascar wildlife" , image_url: "photos/exp20.jpg" , price: 300 , season: "winter" , date: "" , duration: "three days" , tags: "baobab trees, diving, wildlife" , address: "morondava, madagascar")
Experience.create!(title: "Bungee jumping at Victoria Falls" , category: "adventure" , description: "Victoria falls bungee" , image_url: "photos/exp21.jpg" , price: 300 , season: "year-round" , date: "" , duration: "one day" , tags: "bungee, jumping, zimbabwe" , address: "victoria falls, zimbabwe")
Experience.create!(title: "Flying the red desert" , category: "adventure" , description: "Hot air ballons flight over the Namib" , image_url: "photos/exp22.jpg" , price: 300 , season: "autumn" , date: "" , duration: "two days" , tags: "namib, red desert, hot air ballons" , address: "namib desert, namibia")
Experience.create!(title: "Penguins at Punta Arena" , category: "adventure" , description: "Penguins in Magallanes region" , image_url: "photos/exp23.jpg" , price: 300 , season: "winter" , date: "" , duration: "one day" , tags: "penguin, punta arena, patagonia" , address: "seno otway, chile")
Experience.create!(title: "Entresijos and gallinejas" , category: "food" , description: "Madrid famous dish" , image_url: "photos/exp24.jpg" , price: 20 , season: "year-round" , date: "" , duration: "one day" , tags: "frying, entresijos, gallinejas" , address: "Embajadores 84, madrid")
Experience.create!(title: "Resting in Turks or..." , category: "leisure" , description: "Turks and Caicos holidays" , image_url: "photos/exp25.jpg" , price: 3000 , season: "year-round" , date: "" , duration: "six days" , tags: "resorts, grace bay, turks and caicos" , address: "grace bay, turks and caicos")
Experience.create!(title: "Street cart roulette" , category: "food" , description: "Backpacking degustation menu " , image_url: "photos/exp26.jpg" , price: 5 , season: "year-round" , date: "" , duration: "one day" , tags: "khao san road, food, street cart, backpacker" , address: "khao san road, bangkok")
Experience.create!(title: "Chinese Venice" , category: "cultural" , description: "Suzhou, the venice of the east" , image_url: "photos/exp27.jpg" , price: 500 , season: "autumn" , date: "" , duration: "three days" , tags: "suzhou, china, gardens, canals" , address: "humble administrators garden, suzhou, china")
Experience.create!(title: "Surfing sand waves" , category: "adventure" , description: "Kalbarri sandboarding" , image_url: "photos/exp28.jpg" , price: 100 , season: "year-round" , date: "" , duration: "one day" , tags: "kalbarri, sandboarding, australia, surf" , address: "kalbarri visitor center, australia")
Experience.create!(title: "Wild Tasmania" , category: "adventure" , description: "Tasmanian kayak expedition" , image_url: "photos/exp29.jpg" , price: 2200 , season: "winter" , date: "" , duration: "one week" , tags: "tasmania, kayak, wilderness, isolation" , address: "bathurst harbour airport, australia")
Experience.create!(title: "Teaching in Vietnam" , category: "volunteering" , description: "English teaching experience in south Vietnam" , image_url: "photos/exp30.jpg" , price: 1000 , season: "year-round" , date: "" , duration: "three weeks" , tags: "saigon, vietnam, teaching, english" , address: "ho chi minh city, vietnam")
Experience.create!(title: "Punxsutawney again" , category: "leisure" , description: "Phil the groundhog guessing about winter" , image_url: "photos/exp31.jpg" , price: 100 , season: "winter" , date: "2015-02-02" , duration: "one day" , tags: "phil, bill murray, punxsutawney, winter" , address: "punxsutawney, pennsylvania")
Experience.create!(title: "A royal garden" , category: "nature" , description: "Kew Royal Botanic Gardens" , image_url: "photos/exp32.jpg" , price: 50 , season: "year-round" , date: "" , duration: "one day" , tags: "royal botanic gardens, kew, garden, royal family" , address: "royal botanic gardens, kew")
Experience.create!(title: "My first time: London" , category: "cultural" , description: "A first visit to the England capital" , image_url: "photos/exp33.jpg" , price: 1000 , season: "summer" , date: "" , duration: "one week" , tags: "london, first time, tower bridge, london tower" , address: "london")
Experience.create!(title: "Camden markets" , category: "leisure" , description: "Walking the Camden town markets" , image_url: "photos/exp34.jpg" , price: 200 , season: "spring" , date: "" , duration: "two days" , tags: "camden, camden lock, camden market, shopping, london markets" , address: "camden market, london")
Experience.create!(title: "Old Trafford experience" , category: "leisure" , description: "Manchester United museum" , image_url: "photos/exp35.jpg" , price: 35 , season: "year-round" , date: "" , duration: "one day" , tags: "manu, machester united, red devils, football" , address: "old trafford, manchester")
Experience.create!(title: "The Storr and the Old Man of Storr" , category: "sport" , description: "A spectacular walk to a famous summit, passing through an iconic landscape. Superb views in all directions." , image_url: "photos/exp36.jpg" , price: 50 , season: "summer" , date: "" , duration: "one day" , tags: "old man of storr, scotland, highlands" , address: "old man of storr, scotland")
Experience.create!(title: "The Skye Trail" , category: "adventure" , description: "The Skye Trail - a challenging unofficial route through the island aimed at experienced hillwalkers - takes in some of the very best of the island - and that means the UK's finest landscapes." , image_url: "photos/exp37.jpg" , price: 350 , season: "summer" , date: "" , duration: "one week" , tags: "skye trail, scotland, highlands, hiking, trekking" , address: "skye, scotland")
Experience.create!(title: "Edinburgh International Festival" , category: "cultural" , description: "Festival 2015 will run from 7 to 31 August, opening with an incredible free event, The Harmonium Project, in Festival Square and the Virgin Money Fireworks Concert will bring the summer festival season to an explosive conclusion. To find out more about these events and everything in between, browse the art forms or look at the full diary. " , image_url: "photos/exp38.jpg" , price: 1500 , season: "summer" , date: "2015-08-07" , duration: "three weeks" , tags: "edinburgh, arts, theatre, performance, scotland" , address: "edinburgh, scotland")
Experience.create!(title: "You'll never walk alone" , category: "event" , description: "Enjoy a Liverpool FC match" , image_url: "photos/exp39.jpg" , price: 200 , season: "spring" , date: "" , duration: "one day" , tags: "liverpool, reds, anfield, mersey" , address: "anfield, liverpool")
Experience.create!(title: "The Globe" , category: "cultural" , description: "Oak-and-thatch replica of original Elizabethan theatre, showing Shakespeare plays in the open air." , image_url: "photos/exp40.jpg" , price: 90 , season: "year-round" , date: "" , duration: "one day" , tags: "shakespeare, theatre, the globe" , address: "globe theatre, london")
Experience.create!(title: "Brands Hatch academy" , category: "sport" , description: "Track academy in Brands Hatch" , image_url: "photos/exp41.jpg" , price: 1050 , season: "year-round" , date: "" , duration: "one day" , tags: "brands hatch, track days, academy" , address: "brands hatch circuit, united kingdom")
Experience.create!(title: "ATP World Tour Finals" , category: "event" , description: "Only the best eight singles players and best eight doubles teams of the season qualify for the prestigious Barclays ATP World Tour Finals, which will be staged at The O2 arena in London for a seventh straight year in 2015. The singles champion will be presented The Brad Drewett Trophy, in memory of the ATP Executive Chairman and President who passed away on 3 May 2013." , image_url: "photos/exp42.jpg" , price: 300 , season: "winter" , date: "2015-11-15" , duration: "one week" , tags: "atp, masters finals, nadal, federer, djokovic" , address: "the o2, london")
Experience.create!(title: "Fifteen" , category: "food" , description: "Made famous by Jamie Oliver's TV series in 2002, at Fifteen you can expect Jamie's trademark quirky, delicious food in a trendy, celebrity-filled setting. The Mediterranean menu, which is as seasonal and locally-sourced as possible, is complemented by the laid-back vibe. Money from your bill goes towards teaching the restaurant's trainee chefs." , image_url: "photos/exp43.jpg" , price: 60 , season: "year-round" , date: "" , duration: "one day" , tags: "jamie oliver, tv chefs, restaurants" , address: "fifteen, london")
Experience.create!(title: "The english tea room" , category: "food" , description: "The award-winning afternoon tea at Brown's Hotel includes freshly cut sandwiches, warm scones with clotted cream and strawberry preserve, alongside a delectable choice of teas, and cakes from the trolley. Afternoon tea delights may include passion fruit tennis balls, strawberry tartlets, Pimm’s jelly, and raspberry macarons." , image_url: "photos/exp44.jpg" , price: 50 , season: "year-round" , date: "" , duration: "one day" , tags: "tea, luxury, browns hotel" , address: "browns hotel, london")
Experience.create!(title: "Wimbledon's finals" , category: "event" , description: "All England club finals" , image_url: "photos/exp45.jpg" , price: 3000 , season: "summer" , date: "2015-07-05" , duration: "one day" , tags: "grand slam, tennis, wimbledon" , address: "All England Lawn Tennis & Croquet Club, london")
Experience.create!(title: "Riding Hyde Park" , category: "sport" , description: "Hop on a steed and trot your way through one of London's most central parks, courtesy of those lovely equestrian types at Hyde Park Stables" , image_url: "photos/exp46.jpg" , price: 110 , season: "year-round" , date: "" , duration: "one day" , tags: "hyde park stables, horses, equestrian" , address: "63 Bathurst Mews, Paddington, London W2 2SB")
Experience.create!(title: "The Asmara Suite" , category: "leisure" , description: "The Ushvani Signature Massage - Think of the best massage you’ve ever had and triple it." , image_url: "photos/exp47.jpg" , price: 1100 , season: "year-round" , date: "" , duration: "one day" , tags: "ushvani, spa, relax, body treatment" , address: "1 Cadogan Gardens, Knightsbridge, London SW3 2RJ")
Experience.create!(title: "50 years of Pennine Way" , category: "adventure" , description: "The Pennine Way is a National Trail in England, with a small section in Scotland" , image_url: "photos/exp48.jpg" , price: 600 , season: "spring" , date: "" , duration: "one week" , tags: "trails, countryfield, hiking" , address: "edale, derbyshire")
| gpl-3.0 |
MHTaleb/Encologim | lib/JasperReport/src/net/sf/jasperreports/engine/export/DefaultHyperlinkProducerFactory.java | 2105 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2016 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.export;
import java.util.Iterator;
import java.util.List;
import net.sf.jasperreports.engine.JasperReportsContext;
/**
* Extension-based hyperlink producer factory implementation.
* <p>
*
* @author Teodor Danciu (teodord@users.sourceforge.net)
*/
public class DefaultHyperlinkProducerFactory extends JRHyperlinkProducerFactory
{
private JasperReportsContext jasperReportsContext;
/**
*
*/
public DefaultHyperlinkProducerFactory(JasperReportsContext jasperReportsContext)
{
this.jasperReportsContext = jasperReportsContext;
}
@Override
public JRHyperlinkProducer getHandler(String linkType)
{
if (linkType == null)
{
return null;
}
List<JRHyperlinkProducerFactory> factories = jasperReportsContext.getExtensions(
JRHyperlinkProducerFactory.class);
for (Iterator<JRHyperlinkProducerFactory> it = factories.iterator(); it.hasNext();)
{
JRHyperlinkProducerFactory factory = it.next();
JRHyperlinkProducer producer = factory.getHandler(linkType);
if (producer != null)
{
return producer;
}
}
return null;
}
}
| gpl-3.0 |
AllaMaevskaya/AliceO2 | Detectors/TPC/simulation/macro/laserTrackGenerator.C | 2446 | // Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// 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.
/// \file laserTrackGenerator
/// \brief This macro implements a simple generator for laser tracks.
///
/// The laser track definitions are loaded from file.
/// Momenta need to be rescaled to avoid crashes in geant.
/// The sign is inverted to track them from the mirror inside the active volume
/// \author Jens Wiechula, Jens.Wiechula@ikf.uni-frankfurt.de
#if !defined(__CLING__) || defined(__ROOTCLING__)
#include <array>
#include "FairGenerator.h"
#include "FairPrimaryGenerator.h"
#include "DataFormatsTPC/LaserTrack.h"
#endif
class LaserTrackGenerator : public FairGenerator
{
public:
LaserTrackGenerator() : FairGenerator("TPCLaserTrackGenerator")
{
mLaserTrackContainer.loadTracksFromFile();
}
Bool_t ReadEvent(FairPrimaryGenerator* primGen) override
{
// loop over all tracks and add them to the generator
const auto& tracks = mLaserTrackContainer.getLaserTracks();
// TODO: use something better instead. The particle should stop at the inner field cage of the TPC.
// perhaps use a custom particle with special treatment in Detector.cxx
//const int pdgCode = 2212;
const int pdgCode = 11;
std::array<float, 3> xyz;
std::array<float, 3> pxyz;
for (const auto& track : tracks) {
track.getXYZGlo(xyz);
track.getPxPyPzGlo(pxyz);
// rescale to 1TeV to avoid segfault in geant
// change sign to propagate tracks from the mirror invards
// the tracking, however, will give values with the original sign
auto norm = -1000. / track.getP();
primGen->AddTrack(pdgCode, pxyz[0] * norm, pxyz[1] * norm, pxyz[2] * norm, xyz[0], xyz[1], xyz[2]);
printf("Add track %.2f %.2f %.2f %.2f %.2f %.2f\n", pxyz[0] * norm, pxyz[1] * norm, pxyz[2] * norm, xyz[0], xyz[1], xyz[2]);
}
return kTRUE;
}
private:
o2::tpc::LaserTrackContainer mLaserTrackContainer;
};
FairGenerator* laserTrackGenerator()
{
auto gen = new LaserTrackGenerator();
return gen;
}
| gpl-3.0 |
rmelo19/rmelo19-arduino | fritzing/fritzing.0.9.2b.64.pc/parts/part-gen-scripts/misc_scripts/replace.py | 2407 | # usage:
# replace.py -d <directory> -f <find> -r <replace> -s <suffix>
#
# <directory> is a folder, with subfolders, containing <suffix> files. In each <suffix> file in the directory or its children
# replace <text> with <replace>
import sys, os, re
import optparse
def usage():
print """
usage:
replace.py -d [directory] -f [text] -r [replace] -s [suffix]
directory is a folder containing [suffix] files.
In each [suffix] file in the directory or its subfolders,
replace [text] with [replace]
"""
def main():
parser = optparse.OptionParser()
parser.add_option('-s', '--suffix', dest="suffix" )
parser.add_option('-d', '--directory', dest="directory")
parser.add_option('-f', '--find', dest="find" )
parser.add_option('-r', '--replace', dest="replace")
(options, args) = parser.parse_args()
if not options.directory:
parser.error("directory argument not given")
usage()
return
if not options.find:
parser.error("find argument not given")
usage()
return
if not options.replace:
parser.error("replace argument not given")
usage()
return
outputDir = options.directory
findtext = options.find
replacetext = options.replace
suffix = options.suffix
if not(outputDir):
usage()
return
if findtext.startswith('"') or findtext.startswith("'"):
findtext = findtext[1:-1]
if replacetext.startswith('"') or replacetext.startswith("'"):
replacetext = replacetext[1:-1]
print "replace text",findtext,"with",replacetext,"in", suffix,"files"
for root, dirs, files in os.walk(outputDir, topdown=False):
for filename in files:
if (filename.endswith(suffix)):
infile = open(os.path.join(root, filename), "r")
svg = infile.read();
infile.close();
rslt = svg.find(findtext)
if (rslt >= 0):
svg = svg.replace(findtext, replacetext)
outfile = open(os.path.join(root, filename), "w")
outfile.write(svg);
outfile.close()
print "{0}".format(os.path.join(root, filename))
if __name__ == "__main__":
main()
| gpl-3.0 |
blacklagoon/Xcore-406 | src/server/worldserver/Main.cpp | 5023 | /*
* Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010-2011 Project SkyFire <http://www.projectskyfire.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/// \addtogroup Trinityd Trinity Daemon
/// @{
/// \file
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <ace/Version.h>
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "Configuration/Config.h"
#include "Log.h"
#include "Master.h"
#ifndef _TRINITY_CORE_CONFIG
# define _TRINITY_CORE_CONFIG "./configs/worldserver.conf"
#endif //_TRINITY_CORE_CONFIG
#ifdef _WIN32
#include "ServiceWin32.h"
char serviceName[] = "worldserver";
char serviceLongName[] = "UltraCore G5 world service";
char serviceDescription[] = "UltraCore G5 World of Warcraft emulator world service";
/*
* -1 - not in service mode
* 0 - stopped
* 1 - running
* 2 - paused
*/
int m_ServiceStatus = -1;
#endif
WorldDatabaseWorkerPool WorldDatabase; ///< Accessor to the world database
CharacterDatabaseWorkerPool CharacterDatabase; ///< Accessor to the character database
LoginDatabaseWorkerPool LoginDatabase; ///< Accessor to the realm/login database
uint32 realmID; ///< Id of the realm
/// Print out the usage string for this program on the console.
void usage(const char *prog)
{
sLog->outString("Usage: \n %s [<options>]\n"
" -c config_file use config_file as configuration file\n\r"
#ifdef _WIN32
" Running as service functions:\n\r"
" --service run as service\n\r"
" -s install install service\n\r"
" -s uninstall uninstall service\n\r"
#endif
, prog);
}
/// Launch the Trinity server
extern int main(int argc, char **argv)
{
///- Command line parsing to get the configuration file name
char const* cfg_file = _TRINITY_CORE_CONFIG;
int c = 1;
while( c < argc )
{
if (strcmp(argv[c], "-c") == 0)
{
if (++c >= argc)
{
sLog->outError("Runtime-Error: -c option requires an input argument");
usage(argv[0]);
return 1;
}
else
cfg_file = argv[c];
}
#ifdef _WIN32
////////////
//Services//
////////////
if (strcmp(argv[c], "-s") == 0)
{
if (++c >= argc)
{
sLog->outError("Runtime-Error: -s option requires an input argument");
usage(argv[0]);
return 1;
}
if (strcmp(argv[c], "install") == 0)
{
if (WinServiceInstall())
sLog->outString("Installing service");
return 1;
}
else if (strcmp(argv[c], "uninstall") == 0)
{
if (WinServiceUninstall())
sLog->outString("Uninstalling service");
return 1;
}
else
{
sLog->outError("Runtime-Error: unsupported option %s", argv[c]);
usage(argv[0]);
return 1;
}
}
if (strcmp(argv[c], "--service") == 0)
{
WinServiceRun();
}
////
#endif
++c;
}
if (!sConfig->SetSource(cfg_file))
{
sLog->outError("Invalid or missing configuration file : %s", cfg_file);
sLog->outError("Verify that the file exists and has \'[worldserver]' written in the top of the file!");
return 1;
}
sLog->outString("Using configuration file %s.", cfg_file);
sLog->outDetail("%s (Library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
sLog->outDetail("Using ACE: %s", ACE_VERSION);
///- and run the 'Master'
/// \todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd?
int ret = sMaster->Run();
// at sMaster return function exist with codes
// 0 - normal shutdown
// 1 - shutdown at error
// 2 - restart command used, this code can be used by restarter for restart Trinityd
return ret;
}
/// @} | gpl-3.0 |
dschrimpf/randi3-core | src/main/scala/org/randi3/dao/AuditDao.scala | 2365 | package org.randi3.dao
import scalaz._
import Scalaz._
import scala.slick.session.Database.threadLocalSession
import java.sql.Timestamp
import org.randi3.utility._
import collection.mutable.ListBuffer
import org.randi3.model.{ActionType, AuditEntry}
import org.joda.time.DateTime
import scala.slick.lifted.Parameters
trait AuditDaoComponent {
this: DaoComponent with
Logging with
UtilityDBComponent with
I18NComponent=>
val auditDao: AuditDao
class AuditDao {
import driver.Implicit._
import schema._
import utilityDB._
import i18n._
private def queryAuditEntriesFromClassAndIdentifier(clazz: String, identifier: Int) = for {
auditEntry <- Audit if auditEntry.clazz === clazz && auditEntry.identifier === identifier
} yield auditEntry
private val queryAuditEntriesFromUsername = for {
username <- Parameters[String]
auditEntry <- Audit if auditEntry.username === username
} yield auditEntry
def create(auditEntry: AuditEntry): Validation[String, Boolean] = {
logger.info(auditEntry.toString)
onDB {
threadLocalSession withTransaction {
Audit.noId insert(new Timestamp(auditEntry.time.getMillis), auditEntry.username, auditEntry.action.toString, auditEntry.clazz.getName, auditEntry.identifier, auditEntry.text)
}
Success(true)
}
}
def getAll(clazz: Class[Any], identifier: Int): Validation[String, List[AuditEntry]] = {
onDB {
generateAuditEntryFromDatabaseRows(queryAuditEntriesFromClassAndIdentifier(clazz.getName, identifier).list)
}
}
def getAll(username: String): Validation[String, List[AuditEntry]] = {
onDB {
generateAuditEntryFromDatabaseRows(queryAuditEntriesFromUsername(username).list)
}
}
private def generateAuditEntryFromDatabaseRows(rows: List[(Int, Timestamp, String, String, String, Int, String)]): Validation[String, List[AuditEntry]] = {
//TODO check and uiName
val resultList = new ListBuffer[AuditEntry]()
rows.foreach {
row =>
val clazz = getClass.getClassLoader.loadClass(row._5).asInstanceOf[Class[Any]]
resultList += new AuditEntry(row._1, new DateTime(row._2.getTime), row._3, ActionType.withName(row._4), clazz, row._6, text(row._7))
}
resultList.toList.success
}
}
}
| gpl-3.0 |
valecs97/Contest | Contest/testFunction/testIteration_1.py | 1603 | '''
Created on Oct 18, 2016
@author: Vitoc
'''
from iteration_1.addModule import addModuleClass
from iteration_1.modifyModule import modifyModuleClass
class testIteration_1Class:
def __init__(self):
return
def testAddOp(self):
addClass = addModuleClass()
try:
assert(addClass.add([],[1,2,3])==[[1,2,3]])
assert(addClass.add([[1,2]],[9,10,11])==[[1,2],[9,10,11]])
assert(False)
except ValueError:
assert(True)
def testInsertOp(self):
addClass = addModuleClass()
assert(addClass.insert([[1,1,1],[2,2,2],[3,3,3]],[5,5,5],2)==[[1,1,1],[2,2,2],[5,5,5]])
try:
assert(addClass.insert([[1,1,1],[2,2,2],[3,3,3]],[5,5,11],2)==[[1,1,1],[2,2,2],[5,5,5]])
assert(False)
except ValueError:
assert(True)
del addClass
def testRemoveOp(self):
modifyClass = modifyModuleClass()
assert(modifyClass.remove([[1,2,3],[4,5,6],[7,8,9]],2)==[[1,2,3],[4,5,6],[0,0,0]])
try:
modifyClass.remove([[1,2,3],[3,4,5]],7)
assert(False) #asa sa facem la examen
except ValueError:
assert(True)
del modifyClass
def testReplaceOp(self):
modifyClass = modifyModuleClass()
try:
assert(modifyClass.replace([[1,1,1],[2,2,2],[3,3,3]],4,0,9)==[[1,1,9],[2,2,2],[3,3,3]])
assert(False)
except ValueError:
assert(True)
del modifyClass | gpl-3.0 |
lidarr/Lidarr | src/NzbDrone.Core.Test/Download/CompletedDownloadServiceTests/ImportFixture.cs | 18362 | using System.Collections.Generic;
using FizzWare.NBuilder;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using NzbDrone.Common.Disk;
using NzbDrone.Core.DecisionEngine;
using NzbDrone.Core.Download;
using NzbDrone.Core.Download.TrackedDownloads;
using NzbDrone.Core.History;
using NzbDrone.Core.MediaFiles;
using NzbDrone.Core.MediaFiles.TrackImport;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Music;
using NzbDrone.Core.Parser;
using NzbDrone.Core.Parser.Model;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Test.Common;
namespace NzbDrone.Core.Test.Download.CompletedDownloadServiceTests
{
[TestFixture]
public class ImportFixture : CoreTest<CompletedDownloadService>
{
private TrackedDownload _trackedDownload;
[SetUp]
public void Setup()
{
var completed = Builder<DownloadClientItem>.CreateNew()
.With(h => h.Status = DownloadItemStatus.Completed)
.With(h => h.OutputPath = new OsPath(@"C:\DropFolder\MyDownload".AsOsAgnostic()))
.With(h => h.Title = "Drone.S01E01.HDTV")
.Build();
var remoteAlbum = BuildRemoteAlbum();
_trackedDownload = Builder<TrackedDownload>.CreateNew()
.With(c => c.State = TrackedDownloadState.Downloading)
.With(c => c.DownloadItem = completed)
.With(c => c.RemoteAlbum = remoteAlbum)
.Build();
Mocker.GetMock<IDownloadClient>()
.SetupGet(c => c.Definition)
.Returns(new DownloadClientDefinition { Id = 1, Name = "testClient" });
Mocker.GetMock<IProvideDownloadClient>()
.Setup(c => c.Get(It.IsAny<int>()))
.Returns(Mocker.GetMock<IDownloadClient>().Object);
Mocker.GetMock<IHistoryService>()
.Setup(s => s.MostRecentForDownloadId(_trackedDownload.DownloadItem.DownloadId))
.Returns(new History.History());
Mocker.GetMock<IParsingService>()
.Setup(s => s.GetArtist("Drone.S01E01.HDTV"))
.Returns(remoteAlbum.Artist);
Mocker.GetMock<IProvideImportItemService>()
.Setup(s => s.ProvideImportItem(It.IsAny<DownloadClientItem>(), It.IsAny<DownloadClientItem>()))
.Returns<DownloadClientItem, DownloadClientItem>((i, p) => i);
}
private Album CreateAlbum(int id, int trackCount)
{
return new Album
{
Id = id,
AlbumReleases = new List<AlbumRelease>
{
new AlbumRelease
{
Monitored = true,
TrackCount = trackCount
}
}
};
}
private RemoteAlbum BuildRemoteAlbum()
{
return new RemoteAlbum
{
Artist = new Artist(),
Albums = new List<Album> { CreateAlbum(1, 1) }
};
}
private void GivenABadlyNamedDownload()
{
_trackedDownload.DownloadItem.DownloadId = "1234";
_trackedDownload.DownloadItem.Title = "Droned Pilot"; // Set a badly named download
Mocker.GetMock<IHistoryService>()
.Setup(s => s.MostRecentForDownloadId(It.Is<string>(i => i == "1234")))
.Returns(new History.History() { SourceTitle = "Droned S01E01" });
Mocker.GetMock<IParsingService>()
.Setup(s => s.GetArtist(It.IsAny<string>()))
.Returns((Artist)null);
Mocker.GetMock<IParsingService>()
.Setup(s => s.GetArtist("Droned S01E01"))
.Returns(BuildRemoteAlbum().Artist);
}
private void GivenArtistMatch()
{
Mocker.GetMock<IParsingService>()
.Setup(s => s.GetArtist(It.IsAny<string>()))
.Returns(_trackedDownload.RemoteAlbum.Artist);
}
[Test]
public void should_not_mark_as_imported_if_all_files_were_rejected()
{
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure"),
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure")
});
Subject.Import(_trackedDownload);
Mocker.GetMock<IEventAggregator>()
.Verify(v => v.PublishEvent<DownloadCompletedEvent>(It.IsAny<DownloadCompletedEvent>()), Times.Never());
AssertNotImported();
}
[Test]
public void should_not_mark_as_imported_if_no_tracks_were_parsed()
{
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure"),
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() }, new Rejection("Rejected!")), "Test Failure")
});
_trackedDownload.RemoteAlbum.Albums.Clear();
Subject.Import(_trackedDownload);
AssertNotImported();
}
[Test]
public void should_not_mark_as_failed_if_nothing_found_to_import()
{
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>());
Subject.Import(_trackedDownload);
_trackedDownload.State.Should().Be(TrackedDownloadState.Importing);
}
[Test]
public void should_not_mark_as_imported_if_all_files_were_skipped()
{
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure"),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure")
});
Subject.Import(_trackedDownload);
AssertNotImported();
}
[Test]
public void should_mark_as_imported_if_all_tracks_were_imported_but_extra_files_were_not()
{
GivenArtistMatch();
_trackedDownload.RemoteAlbum.Albums = new List<Album>
{
CreateAlbum(1, 3)
};
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure")
});
Subject.Import(_trackedDownload);
AssertImported();
}
[Test]
public void should_not_mark_as_imported_if_some_tracks_were_not_imported()
{
_trackedDownload.RemoteAlbum.Albums = new List<Album>
{
CreateAlbum(1, 1),
CreateAlbum(1, 2),
CreateAlbum(1, 1)
};
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure"),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }), "Test Failure")
});
var history = Builder<History.History>.CreateListOfSize(2)
.BuildList();
Mocker.GetMock<IHistoryService>()
.Setup(s => s.FindByDownloadId(It.IsAny<string>()))
.Returns(history);
Mocker.GetMock<ITrackedDownloadAlreadyImported>()
.Setup(s => s.IsImported(_trackedDownload, history))
.Returns(true);
Subject.Import(_trackedDownload);
AssertNotImported();
}
[Test]
public void should_not_mark_as_imported_if_some_of_episodes_were_not_imported_including_history()
{
var tracks = Builder<Track>.CreateListOfSize(3).BuildList();
var releases = Builder<AlbumRelease>.CreateListOfSize(3).All().With(x => x.Monitored = true).With(x => x.TrackCount = 1).BuildList();
releases[0].Tracks = new List<Track> { tracks[0] };
releases[1].Tracks = new List<Track> { tracks[1] };
releases[2].Tracks = new List<Track> { tracks[2] };
var albums = Builder<Album>.CreateListOfSize(3).BuildList();
albums[0].AlbumReleases = new List<AlbumRelease> { releases[0] };
albums[1].AlbumReleases = new List<AlbumRelease> { releases[1] };
albums[2].AlbumReleases = new List<AlbumRelease> { releases[2] };
_trackedDownload.RemoteAlbum.Albums = albums;
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv" })),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure"),
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv" }), "Test Failure")
});
var history = Builder<History.History>.CreateListOfSize(2)
.BuildList();
Mocker.GetMock<IHistoryService>()
.Setup(s => s.FindByDownloadId(It.IsAny<string>()))
.Returns(history);
Mocker.GetMock<ITrackedDownloadAlreadyImported>()
.Setup(s => s.IsImported(It.IsAny<TrackedDownload>(), It.IsAny<List<History.History>>()))
.Returns(false);
Subject.Import(_trackedDownload);
AssertNotImported();
}
[Test]
public void should_mark_as_imported_if_all_tracks_were_imported()
{
_trackedDownload.RemoteAlbum.Albums = new List<Album>
{
CreateAlbum(1, 2)
};
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() })),
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv".AsOsAgnostic() }))
});
Subject.Import(_trackedDownload);
AssertImported();
}
[Test]
public void should_mark_as_imported_if_all_episodes_were_imported_including_history()
{
var track1 = new Track { Id = 1 };
var track2 = new Track { Id = 2 };
var releases = Builder<AlbumRelease>.CreateListOfSize(2).All().With(x => x.Monitored = true).With(x => x.TrackCount = 1).BuildList();
releases[0].Tracks = new List<Track> { track1 };
releases[1].Tracks = new List<Track> { track2 };
var albums = Builder<Album>.CreateListOfSize(2).BuildList();
albums[0].AlbumReleases = new List<AlbumRelease> { releases[0] };
albums[1].AlbumReleases = new List<AlbumRelease> { releases[1] };
_trackedDownload.RemoteAlbum.Albums = albums;
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv", Tracks = new List<Track> { track1 } })),
new ImportResult(
new ImportDecision<LocalTrack>(
new LocalTrack { Path = @"C:\TestPath\Droned.S01E02.mkv", Tracks = new List<Track> { track2 } }), "Test Failure")
});
var history = Builder<History.History>.CreateListOfSize(2)
.BuildList();
Mocker.GetMock<IHistoryService>()
.Setup(s => s.FindByDownloadId(It.IsAny<string>()))
.Returns(history);
Mocker.GetMock<ITrackedDownloadAlreadyImported>()
.Setup(s => s.IsImported(It.IsAny<TrackedDownload>(), It.IsAny<List<History.History>>()))
.Returns(true);
Subject.Import(_trackedDownload);
AssertImported();
}
[Test]
public void should_mark_as_imported_if_the_download_can_be_tracked_using_the_source_seriesid()
{
GivenABadlyNamedDownload();
Mocker.GetMock<IDownloadedTracksImportService>()
.Setup(v => v.ProcessPath(It.IsAny<string>(), It.IsAny<ImportMode>(), It.IsAny<Artist>(), It.IsAny<DownloadClientItem>()))
.Returns(new List<ImportResult>
{
new ImportResult(new ImportDecision<LocalTrack>(new LocalTrack { Path = @"C:\TestPath\Droned.S01E01.mkv".AsOsAgnostic() }))
});
Mocker.GetMock<IArtistService>()
.Setup(v => v.GetArtist(It.IsAny<int>()))
.Returns(BuildRemoteAlbum().Artist);
Subject.Import(_trackedDownload);
AssertImported();
}
private void AssertNotImported()
{
Mocker.GetMock<IEventAggregator>()
.Verify(v => v.PublishEvent(It.IsAny<DownloadCompletedEvent>()), Times.Never());
_trackedDownload.State.Should().Be(TrackedDownloadState.ImportFailed);
}
private void AssertImported()
{
Mocker.GetMock<IDownloadedTracksImportService>()
.Verify(v => v.ProcessPath(_trackedDownload.DownloadItem.OutputPath.FullPath, ImportMode.Auto, _trackedDownload.RemoteAlbum.Artist, _trackedDownload.DownloadItem), Times.Once());
Mocker.GetMock<IEventAggregator>()
.Verify(v => v.PublishEvent(It.IsAny<DownloadCompletedEvent>()), Times.Once());
_trackedDownload.State.Should().Be(TrackedDownloadState.Imported);
}
}
}
| gpl-3.0 |
jlpoolen/utsushi | drivers/esci/action.hpp | 7051 | // action.hpp -- template and derived ESC/I protocol commands
// Copyright (C) 2012, 2015 SEIKO EPSON CORPORATION
// Copyright (C) 2009 Olaf Meeuwissen
//
// License: GPL-3.0+
// Author : AVASYS CORPORATION
// Author : Olaf Meeuwissen
// Origin : FreeRISCI
//
// This file is part of the 'Utsushi' package.
// This package 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 ought to have received a copy of the GNU General Public License
// along with this package. If not, see <http://www.gnu.org/licenses/>.
#ifndef drivers_esci_action_hpp_
#define drivers_esci_action_hpp_
#include <boost/throw_exception.hpp>
#include "command.hpp"
#include "exception.hpp"
namespace utsushi {
namespace _drv_ {
namespace esci
{
//! Device movers and shakers ;-)
/*! A selected few commands are available to directly control
hardware processes of the device (on the other side of a
connexion). This template captures the implementation of
these commands.
*/
template <byte b1, byte b2 = 0x00, streamsize size = 1>
class action : public command
{
public:
action (void)
: rep_(0)
{}
void
operator>> (connexion& cnx)
{
cnx.send (cmd_, size);
cnx.recv (&rep_, 1);
this->validate_reply ();
}
protected:
static const byte cmd_[2]; //!< command byte(s)
byte rep_; //!< reply byte
//! Makes sure the reply is as expected.
/*! Most action commands return an ACK if everything is in
order. In case the command should not have been sent a
NAK is returned.
\throw invalid_command when a NAK is received
\throw unknown_reply when receiving an out of the blue
value
\todo Subclass abort_scan and end_of_transmission. These
do \e not return a NAK.
*/
virtual void
validate_reply (void) const
{
if (ACK == rep_)
return;
if (NAK == rep_)
BOOST_THROW_EXCEPTION (invalid_command ());
BOOST_THROW_EXCEPTION (unknown_reply ());
}
};
template <byte b1, byte b2, streamsize size>
const byte action<b1,b2,size>::cmd_[2] = { b1, b2 };
//! Stop scanning as soon as possible.
/*! This command instructs the device to stop sending image data
and discard whatever data has been buffered.
\note This command is reserved for use by start_scan command
implementations.
\note When sent while the device is awaiting commands, this
command may be ignored and \e not generate a reply.
*/
typedef action<CAN> abort_scan;
//! Stop scanning at end of medium.
/*! This command is used to instruct the device to stop sending
image data when it detects an end of medium condition. Any
internally buffered data will be discarded by the device.
\note This command is to be used by the start_extended_scan
command implementation and should only be sent when
start_extended_scan::is_at_page_end() returns \c true.
\note When sent while the device is awaiting commands, this
command is ignored and does \e not generate a reply.
\todo Figure out how this is different from an abort_scan.
What use case does this serve?
*/
typedef action<EOT> end_of_transmission;
//! Remove media from an automatic document feeder.
/*! This command is only effective when the document feeder has
been activated. The device replies with an ACK in case the
command was effective, a NAK otherwise. The command ejects
the media that is inside the ADF unit. This may refer to a
single sheet of media that was being scanned as well as the
whole stack of sheets that the user put in the feeder. The
command may defer its reply until the last sheet has been
ejected.
Depending on the model, when no media is present, media is
loaded first, then ejected.
The command should be sent after an ADF type scan has been
cancelled.
\note Use the \ref load_media command to obtain the next
media sheet on page type ADF units.
\note When doing a duplex scan using a sheet-through type
ADF unit, this command should only be used to eject
media after cancellation.
\todo Document auto-form-feed behaviour.
\sa set_option_unit, set_scan_parameters::option_unit()
\sa get_extended_identity::adf_is_page_type(),
get_extended_status::adf_is_page_type()
\sa abort_scan, end_of_transmission
*/
class eject_media
: public action<FF>
{
void
operator>> (connexion& cnx)
{
cnx.send (cmd_, 1, 0);
cnx.recv (&rep_, 1, 0);
this->validate_reply ();
}
};
//! Fetch media for the next scan.
/*! This command is only effective with activated page type ADF
units. The device replies with an ACK in case the command
was effective, a NAK otherwise. The command prepares the
ADF unit for the next scan. It loads media from the tray if
none is present and when doing a simplex scan. In case of a
duplex scan, it turns over the media so the flip side can be
scanned. Only after the flip side has been scanned will the
command load media from the tray.
This command should only be used with page type ADF units.
\note Use the \ref eject_media command to remove media from
the ADF unit.
\sa set_option_unit, set_scan_parameters::option_unit()
\sa get_extended_identity::adf_is_page_type(),
get_extended_status::adf_is_page_type()
*/
typedef action<PF> load_media;
//! Interrupt the lamp's warming up process.
/*! Sending this command when the device is not actually warming
up has no effect.
\note This command should only be used when the device has
support for it.
\sa get_scanner_status::can_cancel_warming_up(),
get_scanner_status::is_warming_up(),
get_extended_status::is_warming_up()
*/
typedef action<ESC,LOWER_W,2> cancel_warming_up;
} // namespace esci
} // namespace _drv_
} // namespace utsushi
#endif /* drivers_esci_action_hpp_ */
| gpl-3.0 |
dumischbaenger/ews-example | src/main/java/de/dumischbaenger/ws/CreateItemResponseType.java | 890 |
package de.dumischbaenger.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für CreateItemResponseType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="CreateItemResponseType">
* <complexContent>
* <extension base="{http://schemas.microsoft.com/exchange/services/2006/messages}BaseResponseMessageType">
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CreateItemResponseType", namespace = "http://schemas.microsoft.com/exchange/services/2006/messages")
public class CreateItemResponseType
extends BaseResponseMessageType
{
}
| gpl-3.0 |
leobaiano/WC-MaxiPago | helper/post-type.php | 1887 | <?php
/**
* LB Post Type
*
* @author Leo Baiano <ljunior2005@gmail.com>
*/
class LB_Post_Type_WC_MaxiPago {
/**
* Slug.
*
* @var string
*/
private $slug;
/**
* Name.
*
* @var string
*/
private $name;
/**
* Supports.
*
* @var array
*/
private $supports;
/**
* Domain.
*
* @var string
*/
private $domain;
public function __construct( $slug, $name, $supports, $domain ) {
$this->slug = $slug;
$this->name = $name;
$this->supports = $supports;
$this->domain = $domain;
$this->create_cpt();
}
public function create_cpt() {
$labels = array(
'name' => __( $this->name, $this->domain ),
'singular_name' => __( $this->name, $this->domain ),
'add_new' => __( 'Adicionar novo', $this->domain ),
'add_new_item' => __( 'Adicionar novo', $this->domain ),
'edit_item' => __( 'Editar item', $this->domain ),
'new_item' => __( 'Novo item', $this->domain ),
'view_item' => __( 'Ver item', $this->domain ),
'search_items' => __( 'Procurar itens', $this->domain ),
'not_found' => __( 'Nenhum item encontrado', $this->domain ),
'not_found_in_trash' => __( 'Nenhum item encontrado na lixeira', $this->domain ),
'parent_item_colon' => __( 'Pai:', $this->domain ),
'menu_name' => __( $this->name, $this->domain ),
);
// Define o comportamento
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => $this->supports,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => array(
'slug' => $this->slug,
'with_front' => false,
'feeds' => true,
'pages' => true
),
'capability_type' => 'post'
);
register_post_type( $this->slug, $args );
}
}
| gpl-3.0 |
Ribesg/NPlugins | NGeneral/src/main/java/fr/ribesg/bukkit/ngeneral/simplefeature/TimeCommand.java | 3657 | /***************************************************************************
* Project file: NPlugins - NGeneral - TimeCommand.java *
* Full Class name: fr.ribesg.bukkit.ngeneral.simplefeature.TimeCommand *
* *
* Copyright (c) 2012-2015 Ribesg - www.ribesg.fr *
* This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt *
* Please contact me at ribesg[at]yahoo.fr if you improve this file! *
***************************************************************************/
package fr.ribesg.bukkit.ngeneral.simplefeature;
import fr.ribesg.bukkit.ncore.common.MinecraftTime;
import fr.ribesg.bukkit.ncore.lang.MessageId;
import fr.ribesg.bukkit.ngeneral.NGeneral;
import fr.ribesg.bukkit.ngeneral.Perms;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class TimeCommand implements CommandExecutor {
private static final String COMMAND = "time";
private final NGeneral plugin;
public TimeCommand(final NGeneral instance) {
this.plugin = instance;
this.plugin.setCommandExecutor(COMMAND, this);
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) {
if (command.getName().equals(COMMAND)) {
if (!Perms.hasTime(sender)) {
this.plugin.sendMessage(sender, MessageId.noPermissionForCommand);
return true;
} else if (args.length == 1) {
if (!(sender instanceof Player)) {
this.plugin.sendMessage(sender, MessageId.missingWorldArg);
return true;
}
final Player player = (Player)sender;
final World world = player.getWorld();
final long value = this.parseValue(args[0]);
if (value == -1) {
return false;
}
world.setTime(value);
this.plugin.broadcastMessage(MessageId.general_timeSet, args[0], world.getName(), player.getName());
return true;
} else if (args.length == 2) {
final World world = Bukkit.getWorld(args[1]);
if (world == null) {
this.plugin.sendMessage(sender, MessageId.unknownWorld, args[1]);
return true;
}
final long value = this.parseValue(args[0]);
if (value == -1) {
return false;
}
world.setTime(value);
this.plugin.broadcastMessage(MessageId.general_timeSet, args[0], world.getName(), sender.getName());
return true;
} else {
return false;
}
} else {
return false;
}
}
private long parseValue(final String value) {
switch (value.toLowerCase()) {
case "d":
case "day":
return MinecraftTime.DAY.start();
case "n":
case "night":
return MinecraftTime.NIGHT.start();
default:
try {
final long l = Long.parseLong(value);
return l % MinecraftTime.DAY_LENGTH;
} catch (final NumberFormatException e) {
return -1;
}
}
}
}
| gpl-3.0 |
NHOrus/OpenXcom | src/Battlescape/AIModule.cpp | 60187 | /*
* Copyright 2010-2016 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include <climits>
#include <algorithm>
#include "AIModule.h"
#include "../Savegame/BattleItem.h"
#include "../Savegame/Node.h"
#include "../Savegame/SavedBattleGame.h"
#include "../Savegame/SavedGame.h"
#include "TileEngine.h"
#include "Map.h"
#include "BattlescapeState.h"
#include "../Savegame/Tile.h"
#include "Pathfinding.h"
#include "../Engine/RNG.h"
#include "../Engine/Logger.h"
#include "../Engine/Game.h"
#include "../Mod/Armor.h"
#include "../Mod/Mod.h"
#include "../Mod/RuleItem.h"
#include "../fmath.h"
namespace OpenXcom
{
/**
* Sets up a BattleAIState.
* @param save Pointer to the battle game.
* @param unit Pointer to the unit.
* @param node Pointer to the node the unit originates from.
*/
AIModule::AIModule(SavedBattleGame *save, BattleUnit *unit, Node *node) : _save(save), _unit(unit), _aggroTarget(0), _knownEnemies(0), _visibleEnemies(0), _spottingEnemies(0),
_escapeTUs(0), _ambushTUs(0), _rifle(false), _melee(false), _blaster(false),
_didPsi(false), _AIMode(AI_PATROL), _closestDist(100), _fromNode(node), _toNode(0)
{
_traceAI = Options::traceAI;
_reserve = BA_NONE;
_intelligence = _unit->getIntelligence();
_escapeAction = new BattleAction();
_ambushAction = new BattleAction();
_attackAction = new BattleAction();
_patrolAction = new BattleAction();
_psiAction = new BattleAction();
_targetFaction = FACTION_PLAYER;
if (_unit->getOriginalFaction() == FACTION_NEUTRAL)
{
_targetFaction = FACTION_HOSTILE;
}
}
/**
* Deletes the BattleAIState.
*/
AIModule::~AIModule()
{
delete _escapeAction;
delete _ambushAction;
delete _attackAction;
delete _patrolAction;
delete _psiAction;
}
/**
* Loads the AI state from a YAML file.
* @param node YAML node.
*/
void AIModule::load(const YAML::Node &node)
{
int fromNodeID, toNodeID;
fromNodeID = node["fromNode"].as<int>(-1);
toNodeID = node["toNode"].as<int>(-1);
_AIMode = node["AIMode"].as<int>(AI_PATROL);
_wasHitBy = node["wasHitBy"].as<std::vector<int> >(_wasHitBy);
// TODO: Figure out why AI are sometimes left with junk nodes
if (fromNodeID >= 0 && (size_t)fromNodeID < _save->getNodes()->size())
{
_fromNode = _save->getNodes()->at(fromNodeID);
}
if (toNodeID >= 0 && (size_t)toNodeID < _save->getNodes()->size())
{
_toNode = _save->getNodes()->at(toNodeID);
}
}
/**
* Saves the AI state to a YAML file.
* @return YAML node.
*/
YAML::Node AIModule::save() const
{
int fromNodeID = -1, toNodeID = -1;
if (_fromNode)
fromNodeID = _fromNode->getID();
if (_toNode)
toNodeID = _toNode->getID();
YAML::Node node;
node["fromNode"] = fromNodeID;
node["toNode"] = toNodeID;
node["AIMode"] = _AIMode;
node["wasHitBy"] = _wasHitBy;
return node;
}
/**
* Runs any code the state needs to keep updating every AI cycle.
* @param action (possible) AI action to execute after thinking is done.
*/
void AIModule::think(BattleAction *action)
{
action->type = BA_RETHINK;
action->actor = _unit;
action->weapon = _unit->getMainHandWeapon(false);
_attackAction->diff = _save->getBattleState()->getGame()->getSavedGame()->getDifficultyCoefficient();
_attackAction->actor = _unit;
_attackAction->weapon = action->weapon;
_attackAction->number = action->number;
_escapeAction->number = action->number;
_knownEnemies = countKnownTargets();
_visibleEnemies = selectNearestTarget();
_spottingEnemies = getSpottingUnits(_unit->getPosition());
_melee = (_unit->getMeleeWeapon() != 0);
_rifle = false;
_blaster = false;
_reachable = _save->getPathfinding()->findReachable(_unit, _unit->getTimeUnits());
_wasHitBy.clear();
if (_unit->getCharging() && _unit->getCharging()->isOut())
{
_unit->setCharging(0);
}
if (_traceAI)
{
if (_unit->getFaction() == FACTION_HOSTILE)
{
Log(LOG_INFO) << "Unit has " << _visibleEnemies << "/" << _knownEnemies << " known enemies visible, " << _spottingEnemies << " of whom are spotting him. ";
}
else
{
Log(LOG_INFO) << "Civilian Unit has " << _visibleEnemies << " enemies visible, " << _spottingEnemies << " of whom are spotting him. ";
}
std::string AIMode;
switch (_AIMode)
{
case AI_PATROL:
AIMode = "Patrol";
break;
case AI_AMBUSH:
AIMode = "Ambush";
break;
case AI_COMBAT:
AIMode = "Combat";
break;
case AI_ESCAPE:
AIMode = "Escape";
break;
}
Log(LOG_INFO) << "Currently using " << AIMode << " behaviour";
}
if (action->weapon)
{
RuleItem *rule = action->weapon->getRules();
if (_save->isItemUsable(action->weapon))
{
if (rule->getBattleType() == BT_FIREARM)
{
if (rule->getWaypoints() != 0 || (action->weapon->getAmmoItem() && action->weapon->getAmmoItem()->getRules()->getWaypoints() != 0))
{
_blaster = true;
_reachableWithAttack = _save->getPathfinding()->findReachable(_unit, _unit->getTimeUnits() - _unit->getActionTUs(BA_AIMEDSHOT, action->weapon));
}
else
{
_rifle = true;
_reachableWithAttack = _save->getPathfinding()->findReachable(_unit, _unit->getTimeUnits() - _unit->getActionTUs(BA_SNAPSHOT, action->weapon));
}
}
else if (rule->getBattleType() == BT_MELEE)
{
_melee = true;
_reachableWithAttack = _save->getPathfinding()->findReachable(_unit, _unit->getTimeUnits() - _unit->getActionTUs(BA_HIT, action->weapon));
}
}
else
{
action->weapon = 0;
}
}
if (_spottingEnemies && !_escapeTUs)
{
setupEscape();
}
if (_knownEnemies && !_melee && !_ambushTUs)
{
setupAmbush();
}
setupAttack();
setupPatrol();
if (_psiAction->type != BA_NONE && !_didPsi)
{
_didPsi = true;
action->type = _psiAction->type;
action->target = _psiAction->target;
action->number -= 1;
action->weapon = _psiAction->weapon;
return;
}
else
{
_didPsi = false;
}
bool evaluate = false;
switch (_AIMode)
{
case AI_PATROL:
evaluate = (bool)(_spottingEnemies || _visibleEnemies || _knownEnemies || RNG::percent(10));
break;
case AI_AMBUSH:
evaluate = (!_rifle || !_ambushTUs || _visibleEnemies);
break;
case AI_COMBAT:
evaluate = (_attackAction->type == BA_RETHINK);
break;
case AI_ESCAPE:
evaluate = (!_spottingEnemies || !_knownEnemies);
break;
}
if (_spottingEnemies > 2
|| _unit->getHealth() < 2 * _unit->getBaseStats()->health / 3
|| (_aggroTarget && _aggroTarget->getTurnsSinceSpotted() > _intelligence))
{
evaluate = true;
}
if (_save->isCheating() && _AIMode != AI_COMBAT)
{
evaluate = true;
}
if (evaluate)
{
evaluateAIMode();
if (_traceAI)
{
std::string AIMode;
switch (_AIMode)
{
case AI_PATROL:
AIMode = "Patrol";
break;
case AI_AMBUSH:
AIMode = "Ambush";
break;
case AI_COMBAT:
AIMode = "Combat";
break;
case AI_ESCAPE:
AIMode = "Escape";
break;
}
Log(LOG_INFO) << "Re-Evaluated, now using " << AIMode << " behaviour";
}
}
_reserve = BA_NONE;
switch (_AIMode)
{
case AI_ESCAPE:
_unit->setCharging(0);
action->type = _escapeAction->type;
action->target = _escapeAction->target;
// end this unit's turn.
action->finalAction = true;
// ignore new targets.
action->desperate = true;
// spin 180 at the end of your route.
_unit->setHiding(true);
break;
case AI_PATROL:
_unit->setCharging(0);
if (action->weapon && action->weapon->getRules()->getBattleType() == BT_FIREARM)
{
switch (_unit->getAggression())
{
case 0:
_reserve = BA_AIMEDSHOT;
break;
case 1:
_reserve = BA_AUTOSHOT;
break;
case 2:
_reserve = BA_SNAPSHOT;
break;
default:
break;
}
}
action->type = _patrolAction->type;
action->target = _patrolAction->target;
break;
case AI_COMBAT:
action->type = _attackAction->type;
action->target = _attackAction->target;
// this may have changed to a grenade.
action->weapon = _attackAction->weapon;
if (action->weapon && action->type == BA_THROW && action->weapon->getRules()->getBattleType() == BT_GRENADE)
{
_unit->spendTimeUnits(4 + _unit->getActionTUs(BA_PRIME, action->weapon));
}
// if this is a firepoint action, set our facing.
action->finalFacing = _attackAction->finalFacing;
action->TU = _unit->getActionTUs(_attackAction->type, _attackAction->weapon);
// if this is a "find fire point" action, don't increment the AI counter.
if (action->type == BA_WALK && _rifle
// so long as we can take a shot afterwards.
&& _unit->getTimeUnits() > _unit->getActionTUs(BA_SNAPSHOT, action->weapon))
{
action->number -= 1;
}
else if (action->type == BA_LAUNCH)
{
action->waypoints = _attackAction->waypoints;
}
break;
case AI_AMBUSH:
_unit->setCharging(0);
action->type = _ambushAction->type;
action->target = _ambushAction->target;
// face where we think our target will appear.
action->finalFacing = _ambushAction->finalFacing;
// end this unit's turn.
action->finalAction = true;
break;
default:
break;
}
if (action->type == BA_WALK)
{
// if we're moving, we'll have to re-evaluate our escape/ambush position.
if (action->target != _unit->getPosition())
{
_escapeTUs = 0;
_ambushTUs = 0;
}
else
{
action->type = BA_NONE;
}
}
}
/*
* sets the "was hit" flag to true.
*/
void AIModule::setWasHitBy(BattleUnit *attacker)
{
if (attacker->getFaction() != _unit->getFaction() && !getWasHitBy(attacker->getId()))
_wasHitBy.push_back(attacker->getId());
}
/*
* Gets whether the unit was hit.
* @return if it was hit.
*/
bool AIModule::getWasHitBy(int attacker) const
{
return std::find(_wasHitBy.begin(), _wasHitBy.end(), attacker) != _wasHitBy.end();
}
/*
* Sets up a patrol action.
* this is mainly going from node to node, moving about the map.
* handles node selection, and fills out the _patrolAction with useful data.
*/
void AIModule::setupPatrol()
{
Node *node;
_patrolAction->TU = 0;
if (_toNode != 0 && _unit->getPosition() == _toNode->getPosition())
{
if (_traceAI)
{
Log(LOG_INFO) << "Patrol destination reached!";
}
// destination reached
// head off to next patrol node
_fromNode = _toNode;
_toNode->freeNode();
_toNode = 0;
// take a peek through window before walking to the next node
int dir = _save->getTileEngine()->faceWindow(_unit->getPosition());
if (dir != -1 && dir != _unit->getDirection())
{
_unit->lookAt(dir);
while (_unit->getStatus() == STATUS_TURNING)
{
_unit->turn();
}
}
}
if (_fromNode == 0)
{
// assume closest node as "from node"
// on same level to avoid strange things, and the node has to match unit size or it will freeze
int closest = 1000000;
for (std::vector<Node*>::iterator i = _save->getNodes()->begin(); i != _save->getNodes()->end(); ++i)
{
if ((*i)->isDummy())
{
continue;
}
node = *i;
int d = _save->getTileEngine()->distanceSq(_unit->getPosition(), node->getPosition());
if (_unit->getPosition().z == node->getPosition().z
&& d < closest
&& (!(node->getType() & Node::TYPE_SMALL) || _unit->getArmor()->getSize() == 1))
{
_fromNode = node;
closest = d;
}
}
}
int triesLeft = 5;
while (_toNode == 0 && triesLeft)
{
triesLeft--;
// look for a new node to walk towards
bool scout = true;
if (_save->getMissionType() != "STR_BASE_DEFENSE")
{
// after turn 20 or if the morale is low, everyone moves out the UFO and scout
// also anyone standing in fire should also probably move
if (_save->isCheating() || !_fromNode || _fromNode->getRank() == 0 ||
(_save->getTile(_unit->getPosition()) && _save->getTile(_unit->getPosition())->getFire()))
{
scout = true;
}
else
{
scout = false;
}
}
// in base defense missions, the smaller aliens walk towards target nodes - or if there, shoot objects around them
else if (_unit->getArmor()->getSize() == 1)
{
// can i shoot an object?
if (_fromNode->isTarget() &&
_attackAction->weapon &&
_attackAction->weapon->getRules()->getAccuracySnap() &&
_attackAction->weapon->getAmmoItem() &&
_attackAction->weapon->getAmmoItem()->getRules()->getDamageType() != DT_HE &&
_save->getModuleMap()[_fromNode->getPosition().x / 10][_fromNode->getPosition().y / 10].second > 0)
{
// scan this room for objects to destroy
int x = (_unit->getPosition().x/10)*10;
int y = (_unit->getPosition().y/10)*10;
for (int i = x; i < x+9; i++)
for (int j = y; j < y+9; j++)
{
MapData *md = _save->getTile(Position(i, j, 1))->getMapData(O_OBJECT);
if (md && md->isBaseModule())
{
_patrolAction->actor = _unit;
_patrolAction->target = Position(i, j, 1);
_patrolAction->weapon = _attackAction->weapon;
_patrolAction->type = BA_SNAPSHOT;
_patrolAction->TU = _patrolAction->actor->getActionTUs(_patrolAction->type, _patrolAction->weapon);
return;
}
}
}
else
{
// find closest high value target which is not already allocated
int closest = 1000000;
for (std::vector<Node*>::iterator i = _save->getNodes()->begin(); i != _save->getNodes()->end(); ++i)
{
if ((*i)->isDummy())
{
continue;
}
if ((*i)->isTarget() && !(*i)->isAllocated())
{
node = *i;
int d = _save->getTileEngine()->distanceSq(_unit->getPosition(), node->getPosition());
if (!_toNode || (d < closest && node != _fromNode))
{
_toNode = node;
closest = d;
}
}
}
}
}
if (_toNode == 0)
{
_toNode = _save->getPatrolNode(scout, _unit, _fromNode);
if (_toNode == 0)
{
_toNode = _save->getPatrolNode(!scout, _unit, _fromNode);
}
}
if (_toNode != 0)
{
_save->getPathfinding()->calculate(_unit, _toNode->getPosition());
if (_save->getPathfinding()->getStartDirection() == -1)
{
_toNode = 0;
}
_save->getPathfinding()->abortPath();
}
}
if (_toNode != 0)
{
_toNode->allocateNode();
_patrolAction->actor = _unit;
_patrolAction->type = BA_WALK;
_patrolAction->target = _toNode->getPosition();
}
else
{
_patrolAction->type = BA_RETHINK;
}
}
/**
* Try to set up an ambush action
* The idea is to check within a 11x11 tile square for a tile which is not seen by our aggroTarget,
* but that can be reached by him. we then intuit where we will see the target first from our covered
* position, and set that as our final facing.
* Fills out the _ambushAction with useful data.
*/
void AIModule::setupAmbush()
{
_ambushAction->type = BA_RETHINK;
int bestScore = 0;
_ambushTUs = 0;
std::vector<int> path;
if (selectClosestKnownEnemy())
{
const int BASE_SYSTEMATIC_SUCCESS = 100;
const int COVER_BONUS = 25;
const int FAST_PASS_THRESHOLD = 80;
Position origin = _save->getTileEngine()->getSightOriginVoxel(_aggroTarget);
// we'll use node positions for this, as it gives map makers a good degree of control over how the units will use the environment.
for (std::vector<Node*>::const_iterator i = _save->getNodes()->begin(); i != _save->getNodes()->end(); ++i)
{
if ((*i)->isDummy())
{
continue;
}
Position pos = (*i)->getPosition();
Tile *tile = _save->getTile(pos);
if (tile == 0 || _save->getTileEngine()->distance(pos, _unit->getPosition()) > 10 || pos.z != _unit->getPosition().z || tile->getDangerous() ||
std::find(_reachableWithAttack.begin(), _reachableWithAttack.end(), _save->getTileIndex(pos)) == _reachableWithAttack.end())
continue; // just ignore unreachable tiles
if (_traceAI)
{
// colour all the nodes in range purple.
tile->setPreview(10);
tile->setMarkerColor(13);
}
// make sure we can't be seen here.
Position target;
if (!_save->getTileEngine()->canTargetUnit(&origin, tile, &target, _aggroTarget, false, _unit) && !getSpottingUnits(pos))
{
_save->getPathfinding()->calculate(_unit, pos);
int ambushTUs = _save->getPathfinding()->getTotalTUCost();
// make sure we can move here
if (_save->getPathfinding()->getStartDirection() != -1)
{
int score = BASE_SYSTEMATIC_SUCCESS;
score -= ambushTUs;
// make sure our enemy can reach here too.
_save->getPathfinding()->calculate(_aggroTarget, pos);
if (_save->getPathfinding()->getStartDirection() != -1)
{
// ideally we'd like to be behind some cover, like say a window or a low wall.
if (_save->getTileEngine()->faceWindow(pos) != -1)
{
score += COVER_BONUS;
}
if (score > bestScore)
{
path = _save->getPathfinding()->copyPath();
bestScore = score;
_ambushTUs = (pos == _unit->getPosition()) ? 1 : ambushTUs;
_ambushAction->target = pos;
if (bestScore > FAST_PASS_THRESHOLD)
{
break;
}
}
}
}
}
}
if (bestScore > 0)
{
_ambushAction->type = BA_WALK;
// i should really make a function for this
origin = (_ambushAction->target * Position(16,16,24)) +
// 4 because -2 is eyes and 2 below that is the rifle (or at least that's my understanding)
Position(8,8, _unit->getHeight() + _unit->getFloatHeight() - _save->getTile(_ambushAction->target)->getTerrainLevel() - 4);
Position currentPos = _aggroTarget->getPosition();
_save->getPathfinding()->setUnit(_aggroTarget);
Position nextPos;
size_t tries = path.size();
// hypothetically walk the target through the path.
while (tries > 0)
{
_save->getPathfinding()->getTUCost(currentPos, path.back(), &nextPos, _aggroTarget, 0, false);
path.pop_back();
currentPos = nextPos;
Tile *tile = _save->getTile(currentPos);
Position target;
// do a virtual fire calculation
if (_save->getTileEngine()->canTargetUnit(&origin, tile, &target, _unit, false, _aggroTarget))
{
// if we can virtually fire at the hypothetical target, we know which way to face.
_ambushAction->finalFacing = _save->getTileEngine()->getDirectionTo(_ambushAction->target, currentPos);
break;
}
--tries;
}
if (_traceAI)
{
Log(LOG_INFO) << "Ambush estimation will move to " << _ambushAction->target;
}
return;
}
}
if (_traceAI)
{
Log(LOG_INFO) << "Ambush estimation failed";
}
}
/**
* Try to set up a combat action
* This will either be a psionic, grenade, or weapon attack,
* or potentially just moving to get a line of sight to a target.
* Fills out the _attackAction with useful data.
*/
void AIModule::setupAttack()
{
_attackAction->type = BA_RETHINK;
_psiAction->type = BA_NONE;
// if enemies are known to us but not necessarily visible, we can attack them with a blaster launcher or psi.
if (_knownEnemies)
{
if (psiAction())
{
// at this point we can save some time with other calculations - the unit WILL make a psionic attack this turn.
return;
}
if (_blaster)
{
wayPointAction();
}
}
// if we CAN see someone, that makes them a viable target for "regular" attacks.
if (selectNearestTarget())
{
// if we have both types of weapon, make a determination on which to use.
if (_melee && _rifle)
{
selectMeleeOrRanged();
}
if (_unit->getGrenadeFromBelt())
{
grenadeAction();
}
if (_melee)
{
meleeAction();
}
if (_rifle)
{
projectileAction();
}
}
if (_attackAction->type != BA_RETHINK)
{
if (_traceAI)
{
if (_attackAction->type != BA_WALK)
{
Log(LOG_INFO) << "Attack estimation desires to shoot at " << _attackAction->target;
}
else
{
Log(LOG_INFO) << "Attack estimation desires to move to " << _attackAction->target;
}
}
return;
}
else if (_spottingEnemies || _unit->getAggression() < RNG::generate(0, 3))
{
// if enemies can see us, or if we're feeling lucky, we can try to spot the enemy.
if (findFirePoint())
{
if (_traceAI)
{
Log(LOG_INFO) << "Attack estimation desires to move to " << _attackAction->target;
}
return;
}
}
if (_traceAI)
{
Log(LOG_INFO) << "Attack estimation failed";
}
}
/**
* Attempts to find cover, and move toward it.
* The idea is to check within a 11x11 tile square for a tile which is not seen by our aggroTarget.
* If there is no such tile, we run away from the target.
* Fills out the _escapeAction with useful data.
*/
void AIModule::setupEscape()
{
int unitsSpottingMe = getSpottingUnits(_unit->getPosition());
int currentTilePreference = 15;
int tries = -1;
bool coverFound = false;
selectNearestTarget();
_escapeTUs = 0;
int dist = _aggroTarget ? _save->getTileEngine()->distance(_unit->getPosition(), _aggroTarget->getPosition()) : 0;
int bestTileScore = -100000;
int score = -100000;
Position bestTile(0, 0, 0);
Tile *tile = 0;
// weights of various factors in choosing a tile to which to withdraw
const int EXPOSURE_PENALTY = 10;
const int FIRE_PENALTY = 40;
const int BASE_SYSTEMATIC_SUCCESS = 100;
const int BASE_DESPERATE_SUCCESS = 110;
const int FAST_PASS_THRESHOLD = 100; // a score that's good enough to quit the while loop early; it's subjective, hand-tuned and may need tweaking
std::vector<Position> randomTileSearch = _save->getTileSearch();
RNG::shuffle(randomTileSearch);
while (tries < 150 && !coverFound)
{
_escapeAction->target = _unit->getPosition(); // start looking in a direction away from the enemy
if (!_save->getTile(_escapeAction->target))
{
_escapeAction->target = _unit->getPosition(); // cornered at the edge of the map perhaps?
}
score = 0;
if (tries == -1)
{
// you know, maybe we should just stay where we are and not risk reaction fire...
// or maybe continue to wherever we were running to and not risk looking stupid
if (_save->getTile(_unit->lastCover) != 0)
{
_escapeAction->target = _unit->lastCover;
}
}
else if (tries < 121)
{
// looking for cover
_escapeAction->target.x += randomTileSearch[tries].x;
_escapeAction->target.y += randomTileSearch[tries].y;
score = BASE_SYSTEMATIC_SUCCESS;
if (_escapeAction->target == _unit->getPosition())
{
if (unitsSpottingMe > 0)
{
// maybe don't stay in the same spot? move or something if there's any point to it?
_escapeAction->target.x += RNG::generate(-20,20);
_escapeAction->target.y += RNG::generate(-20,20);
}
else
{
score += currentTilePreference;
}
}
}
else
{
if (tries == 121)
{
if (_traceAI)
{
Log(LOG_INFO) << "best score after systematic search was: " << bestTileScore;
}
}
score = BASE_DESPERATE_SUCCESS; // ruuuuuuun
_escapeAction->target = _unit->getPosition();
_escapeAction->target.x += RNG::generate(-10,10);
_escapeAction->target.y += RNG::generate(-10,10);
_escapeAction->target.z = _unit->getPosition().z + RNG::generate(-1,1);
if (_escapeAction->target.z < 0)
{
_escapeAction->target.z = 0;
}
else if (_escapeAction->target.z >= _save->getMapSizeZ())
{
_escapeAction->target.z = _unit->getPosition().z;
}
}
tries++;
// THINK, DAMN YOU
tile = _save->getTile(_escapeAction->target);
int distanceFromTarget = _aggroTarget ? _save->getTileEngine()->distance(_aggroTarget->getPosition(), _escapeAction->target) : 0;
if (dist >= distanceFromTarget)
{
score -= (distanceFromTarget - dist) * 10;
}
else
{
score += (distanceFromTarget - dist) * 10;
}
int spotters = 0;
if (!tile)
{
score = -100001; // no you can't quit the battlefield by running off the map.
}
else
{
spotters = getSpottingUnits(_escapeAction->target);
if (std::find(_reachable.begin(), _reachable.end(), _save->getTileIndex(_escapeAction->target)) == _reachable.end())
continue; // just ignore unreachable tiles
if (_spottingEnemies || spotters)
{
if (_spottingEnemies <= spotters)
{
score -= (1 + spotters - _spottingEnemies) * EXPOSURE_PENALTY; // that's for giving away our position
}
else
{
score += (_spottingEnemies - spotters) * EXPOSURE_PENALTY;
}
}
if (tile->getFire())
{
score -= FIRE_PENALTY;
}
if (tile->getDangerous())
{
score -= BASE_SYSTEMATIC_SUCCESS;
}
if (_traceAI)
{
tile->setMarkerColor(score < 0 ? 3 : (score < FAST_PASS_THRESHOLD/2 ? 8 : (score < FAST_PASS_THRESHOLD ? 9 : 5)));
tile->setPreview(10);
tile->setTUMarker(score);
}
}
if (tile && score > bestTileScore)
{
// calculate TUs to tile; we could be getting this from findReachable() somehow but that would break something for sure...
_save->getPathfinding()->calculate(_unit, _escapeAction->target);
if (_escapeAction->target == _unit->getPosition() || _save->getPathfinding()->getStartDirection() != -1)
{
bestTileScore = score;
bestTile = _escapeAction->target;
_escapeTUs = _save->getPathfinding()->getTotalTUCost();
if (_escapeAction->target == _unit->getPosition())
{
_escapeTUs = 1;
}
if (_traceAI)
{
tile->setMarkerColor(score < 0 ? 7 : (score < FAST_PASS_THRESHOLD/2 ? 10 : (score < FAST_PASS_THRESHOLD ? 4 : 5)));
tile->setPreview(10);
tile->setTUMarker(score);
}
}
_save->getPathfinding()->abortPath();
if (bestTileScore > FAST_PASS_THRESHOLD) coverFound = true; // good enough, gogogo
}
}
_escapeAction->target = bestTile;
if (_traceAI)
{
_save->getTile(_escapeAction->target)->setMarkerColor(13);
}
if (bestTileScore <= -100000)
{
if (_traceAI)
{
Log(LOG_INFO) << "Escape estimation failed.";
}
_escapeAction->type = BA_RETHINK; // do something, just don't look dumbstruck :P
return;
}
else
{
if (_traceAI)
{
Log(LOG_INFO) << "Escape estimation completed after " << tries << " tries, " << _save->getTileEngine()->distance(_unit->getPosition(), bestTile) << " squares or so away.";
}
_escapeAction->type = BA_WALK;
}
}
/**
* Counts how many targets, both xcom and civilian are known to this unit
* @return how many targets are known to us.
*/
int AIModule::countKnownTargets() const
{
int knownEnemies = 0;
if (_unit->getFaction() == FACTION_HOSTILE)
{
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if (validTarget(*i, true, true))
{
++knownEnemies;
}
}
}
return knownEnemies;
}
/*
* counts how many enemies (xcom only) are spotting any given position.
* @param pos the Position to check for spotters.
* @return spotters.
*/
int AIModule::getSpottingUnits(const Position& pos) const
{
// if we don't actually occupy the position being checked, we need to do a virtual LOF check.
bool checking = pos != _unit->getPosition();
int tally = 0;
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if (validTarget(*i, false, false))
{
int dist = _save->getTileEngine()->distance(pos, (*i)->getPosition());
if (dist > 20) continue;
Position originVoxel = _save->getTileEngine()->getSightOriginVoxel(*i);
originVoxel.z -= 2;
Position targetVoxel;
if (checking)
{
if (_save->getTileEngine()->canTargetUnit(&originVoxel, _save->getTile(pos), &targetVoxel, *i, false, _unit))
{
tally++;
}
}
else
{
if (_save->getTileEngine()->canTargetUnit(&originVoxel, _save->getTile(pos), &targetVoxel, *i, false))
{
tally++;
}
}
}
}
return tally;
}
/**
* Selects the nearest known living target we can see/reach and returns the number of visible enemies.
* This function includes civilians as viable targets.
* @return viable targets.
*/
int AIModule::selectNearestTarget()
{
int tally = 0;
_closestDist= 100;
_aggroTarget = 0;
Position target;
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if (validTarget(*i, true, _unit->getFaction() == FACTION_HOSTILE) &&
_save->getTileEngine()->visible(_unit, (*i)->getTile()))
{
tally++;
int dist = _save->getTileEngine()->distance(_unit->getPosition(), (*i)->getPosition());
if (dist < _closestDist)
{
bool valid = false;
if (_rifle || !_melee)
{
BattleAction action;
action.actor = _unit;
action.weapon = _attackAction->weapon;
action.target = (*i)->getPosition();
Position origin = _save->getTileEngine()->getOriginVoxel(action, 0);
valid = _save->getTileEngine()->canTargetUnit(&origin, (*i)->getTile(), &target, _unit, false);
}
else
{
if (selectPointNearTarget(*i, _unit->getTimeUnits()))
{
int dir = _save->getTileEngine()->getDirectionTo(_attackAction->target, (*i)->getPosition());
valid = _save->getTileEngine()->validMeleeRange(_attackAction->target, dir, _unit, *i, 0);
}
}
if (valid)
{
_closestDist = dist;
_aggroTarget = *i;
}
}
}
}
if (_aggroTarget)
{
return tally;
}
return 0;
}
/**
* Selects the nearest known living Xcom unit.
* used for ambush calculations
* @return if we found one.
*/
bool AIModule::selectClosestKnownEnemy()
{
_aggroTarget = 0;
int minDist = 255;
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if (validTarget(*i, true, false))
{
int dist = _save->getTileEngine()->distance((*i)->getPosition(), _unit->getPosition());
if (dist < minDist)
{
minDist = dist;
_aggroTarget = *i;
}
}
}
return _aggroTarget != 0;
}
/**
* Selects a random known living Xcom or civilian unit.
* @return if we found one.
*/
bool AIModule::selectRandomTarget()
{
int farthest = -100;
_aggroTarget = 0;
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
if (validTarget(*i, true, _unit->getFaction() == FACTION_HOSTILE))
{
int dist = RNG::generate(0,20) - _save->getTileEngine()->distance(_unit->getPosition(), (*i)->getPosition());
if (dist > farthest)
{
farthest = dist;
_aggroTarget = *i;
}
}
}
return _aggroTarget != 0;
}
/**
* Selects a point near enough to our target to perform a melee attack.
* @param target Pointer to a target.
* @param maxTUs Maximum time units the path to the target can cost.
* @return True if a point was found.
*/
bool AIModule::selectPointNearTarget(BattleUnit *target, int maxTUs) const
{
int size = _unit->getArmor()->getSize();
int targetsize = target->getArmor()->getSize();
bool returnValue = false;
unsigned int distance = 1000;
for (int z = -1; z <= 1; ++z)
{
for (int x = -size; x <= targetsize; ++x)
{
for (int y = -size; y <= targetsize; ++y)
{
if (x || y) // skip the unit itself
{
Position checkPath = target->getPosition() + Position (x, y, z);
if (_save->getTile(checkPath) == 0 || std::find(_reachable.begin(), _reachable.end(), _save->getTileIndex(checkPath)) == _reachable.end())
continue;
int dir = _save->getTileEngine()->getDirectionTo(checkPath, target->getPosition());
bool valid = _save->getTileEngine()->validMeleeRange(checkPath, dir, _unit, target, 0);
bool fitHere = _save->setUnitPosition(_unit, checkPath, true);
if (valid && fitHere && !_save->getTile(checkPath)->getDangerous())
{
_save->getPathfinding()->calculate(_unit, checkPath, 0, maxTUs);
if (_save->getPathfinding()->getStartDirection() != -1 && _save->getPathfinding()->getPath().size() < distance)
{
_attackAction->target = checkPath;
returnValue = true;
distance = _save->getPathfinding()->getPath().size();
}
_save->getPathfinding()->abortPath();
}
}
}
}
}
return returnValue;
}
/**
* Selects an AI mode based on a number of factors, some RNG and the results of the rest of the determinations.
*/
void AIModule::evaluateAIMode()
{
if ((_unit->getCharging() && _attackAction->type != BA_RETHINK))
{
_AIMode = AI_COMBAT;
return;
}
// don't try to run away as often if we're a melee type, and really don't try to run away if we have a viable melee target, or we still have 50% or more TUs remaining.
int escapeOdds = 15;
if (_melee)
{
escapeOdds = 12;
}
if (_unit->getFaction() == FACTION_HOSTILE && (_unit->getTimeUnits() > _unit->getBaseStats()->tu / 2 || _unit->getCharging()))
{
escapeOdds = 5;
}
int ambushOdds = 12;
int combatOdds = 20;
// we're less likely to patrol if we see enemies.
int patrolOdds = _visibleEnemies ? 15 : 30;
// the enemy sees us, we should take retreat into consideration, and forget about patrolling for now.
if (_spottingEnemies)
{
patrolOdds = 0;
if (_escapeTUs == 0)
{
setupEscape();
}
}
// melee/blaster units shouldn't consider ambush
if (!_rifle || _ambushTUs == 0)
{
ambushOdds = 0;
if (_melee)
{
combatOdds *= 1.3;
}
}
// if we KNOW there are enemies around...
if (_knownEnemies)
{
if (_knownEnemies == 1)
{
combatOdds *= 1.2;
}
if (_escapeTUs == 0)
{
if (selectClosestKnownEnemy())
{
setupEscape();
}
else
{
escapeOdds = 0;
}
}
}
else if (_unit->getFaction() == FACTION_HOSTILE)
{
combatOdds = 0;
escapeOdds = 0;
}
// take our current mode into consideration
switch (_AIMode)
{
case AI_PATROL:
patrolOdds *= 1.1;
break;
case AI_AMBUSH:
ambushOdds *= 1.1;
break;
case AI_COMBAT:
combatOdds *= 1.1;
break;
case AI_ESCAPE:
escapeOdds *= 1.1;
break;
}
// take our overall health into consideration
if (_unit->getHealth() < _unit->getBaseStats()->health / 3)
{
escapeOdds *= 1.7;
combatOdds *= 0.6;
ambushOdds *= 0.75;
}
else if (_unit->getHealth() < 2 * (_unit->getBaseStats()->health / 3))
{
escapeOdds *= 1.4;
combatOdds *= 0.8;
ambushOdds *= 0.8;
}
else if (_unit->getHealth() < _unit->getBaseStats()->health)
{
escapeOdds *= 1.1;
}
// take our aggression into consideration
switch (_unit->getAggression())
{
case 0:
escapeOdds *= 1.4;
combatOdds *= 0.7;
break;
case 1:
ambushOdds *= 1.1;
break;
case 2:
combatOdds *= 1.4;
escapeOdds *= 0.7;
break;
default:
combatOdds *= Clamp(1.2 + (_unit->getAggression() / 10.0), 0.1, 2.0);
escapeOdds *= Clamp(0.9 - (_unit->getAggression() / 10.0), 0.1, 2.0);
break;
}
if (_AIMode == AI_COMBAT)
{
ambushOdds *= 1.5;
}
// factor in the spotters.
if (_spottingEnemies)
{
escapeOdds = 10 * escapeOdds * (_spottingEnemies + 10) / 100;
combatOdds = 5 * combatOdds * (_spottingEnemies + 20) / 100;
}
else
{
escapeOdds /= 2;
}
// factor in visible enemies.
if (_visibleEnemies)
{
combatOdds = 10 * combatOdds * (_visibleEnemies + 10) /100;
if (_closestDist < 5)
{
ambushOdds = 0;
}
}
// make sure we have an ambush lined up, or don't even consider it.
if (_ambushTUs)
{
ambushOdds *= 1.7;
}
else
{
ambushOdds = 0;
}
// factor in mission type
if (_save->getMissionType() == "STR_BASE_DEFENSE")
{
escapeOdds *= 0.75;
ambushOdds *= 0.6;
}
// no weapons, not psychic? don't pick combat or ambush
if (!_melee && !_rifle && !_blaster && !_unit->getGrenadeFromBelt() && _unit->getBaseStats()->psiSkill == 0)
{
combatOdds = 0;
ambushOdds = 0;
}
// generate a random number to represent our decision.
int decision = RNG::generate(1, std::max(1, patrolOdds + ambushOdds + escapeOdds + combatOdds));
if (decision > escapeOdds)
{
if (decision > escapeOdds + ambushOdds)
{
if (decision > escapeOdds + ambushOdds + combatOdds)
{
_AIMode = AI_PATROL;
}
else
{
_AIMode = AI_COMBAT;
}
}
else
{
_AIMode = AI_AMBUSH;
}
}
else
{
_AIMode = AI_ESCAPE;
}
// if the aliens are cheating, or the unit is charging, enforce combat as a priority.
if ((_unit->getFaction() == FACTION_HOSTILE && _save->isCheating()) || _unit->getCharging() != 0)
{
_AIMode = AI_COMBAT;
}
// enforce the validity of our decision, and try fallback behaviour according to priority.
if (_AIMode == AI_COMBAT)
{
if (_save->getTile(_attackAction->target) && _save->getTile(_attackAction->target)->getUnit())
{
if (_attackAction->type != BA_RETHINK)
{
return;
}
if (findFirePoint())
{
return;
}
}
else if (selectRandomTarget() && findFirePoint())
{
return;
}
_AIMode = AI_PATROL;
}
if (_AIMode == AI_PATROL)
{
if (_toNode)
{
return;
}
_AIMode = AI_AMBUSH;
}
if (_AIMode == AI_AMBUSH)
{
if (_ambushTUs != 0)
{
return;
}
_AIMode = AI_ESCAPE;
}
}
/**
* Find a position where we can see our target, and move there.
* check the 11x11 grid for a position nearby where we can potentially target him.
* @return True if a possible position was found.
*/
bool AIModule::findFirePoint()
{
if (!selectClosestKnownEnemy())
return false;
std::vector<Position> randomTileSearch = _save->getTileSearch();
RNG::shuffle(randomTileSearch);
Position target;
const int BASE_SYSTEMATIC_SUCCESS = 100;
const int FAST_PASS_THRESHOLD = 125;
int bestScore = 0;
_attackAction->type = BA_RETHINK;
for (std::vector<Position>::const_iterator i = randomTileSearch.begin(); i != randomTileSearch.end(); ++i)
{
Position pos = _unit->getPosition() + *i;
Tile *tile = _save->getTile(pos);
if (tile == 0 ||
std::find(_reachableWithAttack.begin(), _reachableWithAttack.end(), _save->getTileIndex(pos)) == _reachableWithAttack.end())
continue;
int score = 0;
// i should really make a function for this
Position origin = (pos * Position(16,16,24)) +
// 4 because -2 is eyes and 2 below that is the rifle (or at least that's my understanding)
Position(8,8, _unit->getHeight() + _unit->getFloatHeight() - tile->getTerrainLevel() - 4);
if (_save->getTileEngine()->canTargetUnit(&origin, _aggroTarget->getTile(), &target, _unit, false))
{
_save->getPathfinding()->calculate(_unit, pos);
// can move here
if (_save->getPathfinding()->getStartDirection() != -1)
{
score = BASE_SYSTEMATIC_SUCCESS - getSpottingUnits(pos) * 10;
score += _unit->getTimeUnits() - _save->getPathfinding()->getTotalTUCost();
if (!_aggroTarget->checkViewSector(pos))
{
score += 10;
}
if (score > bestScore)
{
bestScore = score;
_attackAction->target = pos;
_attackAction->finalFacing = _save->getTileEngine()->getDirectionTo(pos, _aggroTarget->getPosition());
if (score > FAST_PASS_THRESHOLD)
{
break;
}
}
}
}
}
if (bestScore > 70)
{
_attackAction->type = BA_WALK;
if (_traceAI)
{
Log(LOG_INFO) << "Firepoint found at " << _attackAction->target << ", with a score of: " << bestScore;
}
return true;
}
if (_traceAI)
{
Log(LOG_INFO) << "Firepoint failed, best estimation was: " << _attackAction->target << ", with a score of: " << bestScore;
}
return false;
}
/**
* Decides if it worth our while to create an explosion here.
* @param targetPos The target's position.
* @param attackingUnit The attacking unit.
* @param radius How big the explosion will be.
* @param diff Game difficulty.
* @param grenade Is the explosion coming from a grenade?
* @return True if it is worthwhile creating an explosion in the target position.
*/
bool AIModule::explosiveEfficacy(Position targetPos, BattleUnit *attackingUnit, int radius, int diff, bool grenade) const
{
// i hate the player and i want him dead, but i don't want to piss him off.
Mod *mod = _save->getBattleState()->getGame()->getMod();
if ((!grenade && _save->getTurn() < mod->getTurnAIUseBlaster()) ||
(grenade && _save->getTurn() < mod->getTurnAIUseGrenade()))
{
return false;
}
Tile *targetTile = _save->getTile(targetPos);
// don't throw grenades at flying enemies.
if (grenade && targetPos.z > 0 && targetTile->hasNoFloor(_save->getTile(targetPos - Position(0,0,1))))
{
return false;
}
if (diff == -1)
{
diff = _save->getBattleState()->getGame()->getSavedGame()->getDifficultyCoefficient();
}
int distance = _save->getTileEngine()->distance(attackingUnit->getPosition(), targetPos);
int injurylevel = attackingUnit->getBaseStats()->health - attackingUnit->getHealth();
int desperation = (100 - attackingUnit->getMorale()) / 10;
int enemiesAffected = 0;
// if we're below 1/3 health, let's assume things are dire, and increase desperation.
if (injurylevel > (attackingUnit->getBaseStats()->health / 3) * 2)
desperation += 3;
int efficacy = desperation;
// don't go kamikaze unless we're already doomed.
if (abs(attackingUnit->getPosition().z - targetPos.z) <= Options::battleExplosionHeight && distance <= radius)
{
efficacy -= 4;
}
// allow difficulty to have its influence
efficacy += diff/2;
// account for the unit we're targetting
BattleUnit *target = targetTile->getUnit();
if (target && !targetTile->getDangerous())
{
++enemiesAffected;
++efficacy;
}
for (std::vector<BattleUnit*>::iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
// don't grenade dead guys
if (!(*i)->isOut() &&
// don't count ourself twice
(*i) != attackingUnit &&
// don't count the target twice
(*i) != target &&
// don't count units that probably won't be affected cause they're out of range
abs((*i)->getPosition().z - targetPos.z) <= Options::battleExplosionHeight &&
_save->getTileEngine()->distance((*i)->getPosition(), targetPos) <= radius)
{
// don't count people who were already grenaded this turn
if ((*i)->getTile()->getDangerous() ||
// don't count units we don't know about
((*i)->getFaction() == _targetFaction && (*i)->getTurnsSinceSpotted() > _intelligence))
continue;
// trace a line from the grenade origin to the unit we're checking against
Position voxelPosA = Position ((targetPos.x * 16)+8, (targetPos.y * 16)+8, (targetPos.z * 24)+12);
Position voxelPosB = Position (((*i)->getPosition().x * 16)+8, ((*i)->getPosition().y * 16)+8, ((*i)->getPosition().z * 24)+12);
std::vector<Position> traj;
int collidesWith = _save->getTileEngine()->calculateLine(voxelPosA, voxelPosB, false, &traj, target, true, false, *i);
if (collidesWith == V_UNIT && traj.front() / Position(16,16,24) == (*i)->getPosition())
{
if ((*i)->getFaction() == _targetFaction)
{
++enemiesAffected;
++efficacy;
}
else if ((*i)->getFaction() == attackingUnit->getFaction() || (attackingUnit->getFaction() == FACTION_NEUTRAL && (*i)->getFaction() == FACTION_PLAYER))
efficacy -= 2; // friendlies count double
}
}
}
// don't throw grenades at single targets, unless morale is in the danger zone
// or we're halfway towards panicking while bleeding to death.
if (grenade && desperation < 6 && enemiesAffected < 2)
{
return false;
}
return (efficacy > 0 || enemiesAffected >= 10);
}
/**
* Attempts to take a melee attack/charge an enemy we can see.
* Melee targetting: we can see an enemy, we can move to it so we're charging blindly toward an enemy.
*/
void AIModule::meleeAction()
{
int attackCost = _unit->getActionTUs(BA_HIT, _unit->getMeleeWeapon());
if (_unit->getTimeUnits() < attackCost)
{
// cannot make a melee attack - consider some other behaviour, like running away, or standing motionless.
return;
}
if (_aggroTarget != 0 && !_aggroTarget->isOut())
{
if (_save->getTileEngine()->validMeleeRange(_unit, _aggroTarget, _save->getTileEngine()->getDirectionTo(_unit->getPosition(), _aggroTarget->getPosition())))
{
meleeAttack();
return;
}
}
int chargeReserve = _unit->getTimeUnits() - attackCost;
int distance = (chargeReserve / 4) + 1;
_aggroTarget = 0;
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
int newDistance = _save->getTileEngine()->distance(_unit->getPosition(), (*i)->getPosition());
if (newDistance > 20 ||
!validTarget(*i, true, _unit->getFaction() == FACTION_HOSTILE))
continue;
//pick closest living unit that we can move to
if ((newDistance < distance || newDistance == 1) && !(*i)->isOut())
{
if (newDistance == 1 || selectPointNearTarget(*i, chargeReserve))
{
_aggroTarget = (*i);
_attackAction->type = BA_WALK;
_unit->setCharging(_aggroTarget);
distance = newDistance;
}
}
}
if (_aggroTarget != 0)
{
if (_save->getTileEngine()->validMeleeRange(_unit, _aggroTarget, _save->getTileEngine()->getDirectionTo(_unit->getPosition(), _aggroTarget->getPosition())))
{
meleeAttack();
}
}
if (_traceAI && _aggroTarget) { Log(LOG_INFO) << "AIModule::meleeAction:" << " [target]: " << (_aggroTarget->getId()) << " at: " << _attackAction->target; }
if (_traceAI && _aggroTarget) { Log(LOG_INFO) << "CHARGE!"; }
}
/**
* Attempts to fire a waypoint projectile at an enemy we, or one of our teammates sees.
*
* Waypoint targeting: pick from any units currently spotted by our allies.
*/
void AIModule::wayPointAction()
{
int attackCost = _unit->getActionTUs(BA_LAUNCH, _attackAction->weapon);
if (_unit->getTimeUnits() < attackCost)
{
// cannot make a launcher attack - consider some other behaviour, like running away, or standing motionless.
return;
}
_aggroTarget = 0;
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end() && _aggroTarget == 0; ++i)
{
if (!validTarget(*i, true, _unit->getFaction() == FACTION_HOSTILE))
continue;
_save->getPathfinding()->calculate(_unit, (*i)->getPosition(), *i, -1);
if (_save->getPathfinding()->getStartDirection() != -1 &&
explosiveEfficacy((*i)->getPosition(), _unit, (_attackAction->weapon->getAmmoItem()->getRules()->getPower()/20)+1, _attackAction->diff))
{
_aggroTarget = *i;
}
_save->getPathfinding()->abortPath();
}
if (_aggroTarget != 0)
{
_attackAction->type = BA_LAUNCH;
_attackAction->TU = _unit->getActionTUs(BA_LAUNCH, _attackAction->weapon);
if (_attackAction->TU > _unit->getTimeUnits())
{
_attackAction->type = BA_RETHINK;
return;
}
_attackAction->waypoints.clear();
int PathDirection;
int CollidesWith;
int maxWaypoints = _attackAction->weapon->getRules()->getWaypoints();
if (maxWaypoints == 0)
{
maxWaypoints = _attackAction->weapon->getAmmoItem()->getRules()->getWaypoints();
}
if (maxWaypoints == -1)
{
maxWaypoints = 6 + (_attackAction->diff * 2);
}
Position LastWayPoint = _unit->getPosition();
Position LastPosition = _unit->getPosition();
Position CurrentPosition = _unit->getPosition();
Position DirectionVector;
_save->getPathfinding()->calculate(_unit, _aggroTarget->getPosition(), _aggroTarget, -1);
PathDirection = _save->getPathfinding()->dequeuePath();
while (PathDirection != -1 && (int)_attackAction->waypoints.size() < maxWaypoints)
{
LastPosition = CurrentPosition;
_save->getPathfinding()->directionToVector(PathDirection, &DirectionVector);
CurrentPosition = CurrentPosition + DirectionVector;
Position voxelPosA ((CurrentPosition.x * 16)+8, (CurrentPosition.y * 16)+8, (CurrentPosition.z * 24)+16);
Position voxelPosb ((LastWayPoint.x * 16)+8, (LastWayPoint.y * 16)+8, (LastWayPoint.z * 24)+16);
CollidesWith = _save->getTileEngine()->calculateLine(voxelPosA, voxelPosb, false, 0, _unit, true);
if (CollidesWith > V_EMPTY && CollidesWith < V_UNIT)
{
_attackAction->waypoints.push_back(LastPosition);
LastWayPoint = LastPosition;
}
else if (CollidesWith == V_UNIT)
{
BattleUnit* target = _save->getTile(CurrentPosition)->getUnit();
if (target == _aggroTarget)
{
_attackAction->waypoints.push_back(CurrentPosition);
LastWayPoint = CurrentPosition;
}
}
PathDirection = _save->getPathfinding()->dequeuePath();
}
_attackAction->target = _attackAction->waypoints.front();
if (LastWayPoint != _aggroTarget->getPosition())
{
_attackAction->type = BA_RETHINK;
}
}
}
/**
* Attempts to fire at an enemy we can see.
*
* Regular targeting: we can see an enemy, we have a gun, let's try to shoot.
*/
void AIModule::projectileAction()
{
_attackAction->target = _aggroTarget->getPosition();
if (!_attackAction->weapon->getAmmoItem()->getRules()->getExplosionRadius() ||
explosiveEfficacy(_aggroTarget->getPosition(), _unit, _attackAction->weapon->getAmmoItem()->getRules()->getExplosionRadius(), _attackAction->diff))
{
selectFireMethod();
}
}
/**
* Selects a fire method based on range, time units, and time units reserved for cover.
*/
void AIModule::selectFireMethod()
{
int distance = _save->getTileEngine()->distance(_unit->getPosition(), _attackAction->target);
_attackAction->type = BA_RETHINK;
int tuAuto = _attackAction->weapon->getRules()->getTUAuto();
int tuSnap = _attackAction->weapon->getRules()->getTUSnap();
int tuAimed = _attackAction->weapon->getRules()->getTUAimed();
int currentTU = _unit->getTimeUnits();
if (distance < 4)
{
if ( tuAuto && currentTU >= _unit->getActionTUs(BA_AUTOSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_AUTOSHOT;
return;
}
if ( !tuSnap || currentTU < _unit->getActionTUs(BA_SNAPSHOT, _attackAction->weapon) )
{
if ( tuAimed && currentTU >= _unit->getActionTUs(BA_AIMEDSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_AIMEDSHOT;
}
return;
}
_attackAction->type = BA_SNAPSHOT;
return;
}
if ( distance > 12 )
{
if ( tuAimed && currentTU >= _unit->getActionTUs(BA_AIMEDSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_AIMEDSHOT;
return;
}
if ( distance < 20
&& tuSnap
&& currentTU >= _unit->getActionTUs(BA_SNAPSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_SNAPSHOT;
return;
}
}
if ( tuSnap && currentTU >= _unit->getActionTUs(BA_SNAPSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_SNAPSHOT;
return;
}
if ( tuAimed && currentTU >= _unit->getActionTUs(BA_AIMEDSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_AIMEDSHOT;
return;
}
if ( tuAuto && currentTU >= _unit->getActionTUs(BA_AUTOSHOT, _attackAction->weapon) )
{
_attackAction->type = BA_AUTOSHOT;
}
}
/**
* Evaluates whether to throw a grenade at an enemy (or group of enemies) we can see.
*/
void AIModule::grenadeAction()
{
// do we have a grenade on our belt?
BattleItem *grenade = _unit->getGrenadeFromBelt();
int tu = 4; // 4TUs for picking up the grenade
tu += _unit->getActionTUs(BA_PRIME, grenade);
tu += _unit->getActionTUs(BA_THROW, grenade);
// do we have enough TUs to prime and throw the grenade?
if (tu <= _unit->getTimeUnits())
{
BattleAction action;
action.weapon = grenade;
action.type = BA_THROW;
action.actor = _unit;
if (explosiveEfficacy(_aggroTarget->getPosition(), _unit, grenade->getRules()->getExplosionRadius(), _attackAction->diff, true))
{
action.target = _aggroTarget->getPosition();
}
else if (!getNodeOfBestEfficacy(&action))
{
return;
}
Position originVoxel = _save->getTileEngine()->getOriginVoxel(action, 0);
Position targetVoxel = action.target * Position (16,16,24) + Position (8,8, (2 + -_save->getTile(action.target)->getTerrainLevel()));
// are we within range?
if (_save->getTileEngine()->validateThrow(action, originVoxel, targetVoxel))
{
_attackAction->weapon = grenade;
_attackAction->target = action.target;
_attackAction->type = BA_THROW;
_attackAction->TU = tu;
_rifle = false;
_melee = false;
}
}
}
/**
* Attempts a psionic attack on an enemy we "know of".
*
* Psionic targetting: pick from any of the "exposed" units.
* Exposed means they have been previously spotted, and are therefore "known" to the AI,
* regardless of whether we can see them or not, because we're psychic.
* @return True if a psionic attack is performed.
*/
bool AIModule::psiAction()
{
BattleItem *item = _unit->getSpecialWeapon(BT_PSIAMP);
if (!item)
{
return false;
}
RuleItem *psiWeaponRules = item->getRules();
int cost = psiWeaponRules->getTUUse();
if (!psiWeaponRules->getFlatRate())
{
cost = (int)floor(_unit->getBaseStats()->tu * cost / 100.0f);
}
bool LOSRequired = psiWeaponRules->isLOSRequired();
_aggroTarget = 0;
// don't let mind controlled soldiers mind control other soldiers.
if (_unit->getOriginalFaction() == _unit->getFaction()
// and we have the required 25 TUs and can still make it to cover
&& _unit->getTimeUnits() > _escapeTUs + cost
// and we didn't already do a psi action this round
&& !_didPsi)
{
int psiAttackStrength = _unit->getBaseStats()->psiSkill * _unit->getBaseStats()->psiStrength / 50;
int chanceToAttack = 0;
for (std::vector<BattleUnit*>::const_iterator i = _save->getUnits()->begin(); i != _save->getUnits()->end(); ++i)
{
// don't target tanks
if ((*i)->getArmor()->getSize() == 1 &&
validTarget(*i, true, false) &&
// they must be player units
(*i)->getOriginalFaction() == _targetFaction &&
(!LOSRequired ||
std::find(_unit->getVisibleUnits()->begin(), _unit->getVisibleUnits()->end(), *i) != _unit->getVisibleUnits()->end()))
{
int chanceToAttackMe = psiAttackStrength
+ (((*i)->getBaseStats()->psiSkill > 0) ? (*i)->getBaseStats()->psiSkill * -0.4 : 0)
- _save->getTileEngine()->distance((*i)->getPosition(), _unit->getPosition())
- ((*i)->getBaseStats()->psiStrength)
+ RNG::generate(55, 105);
if (chanceToAttackMe > chanceToAttack)
{
chanceToAttack = chanceToAttackMe;
_aggroTarget = *i;
}
}
}
if (!_aggroTarget || !chanceToAttack) return false;
if (_visibleEnemies && _attackAction->weapon && _attackAction->weapon->getAmmoItem())
{
if (_attackAction->weapon->getAmmoItem()->getRules()->getPower() >= chanceToAttack)
{
return false;
}
}
else if (RNG::generate(35, 155) >= chanceToAttack)
{
return false;
}
if (_traceAI)
{
Log(LOG_INFO) << "making a psionic attack this turn";
}
if (chanceToAttack >= 30)
{
int controlOdds = 40;
int morale = _aggroTarget->getMorale();
int bravery = (110 - _aggroTarget->getBaseStats()->bravery) / 10;
if (bravery > 6)
controlOdds -= 15;
if (bravery < 4)
controlOdds += 15;
if (morale >= 40)
{
if (morale - 10 * bravery < 50)
controlOdds -= 15;
}
else
{
controlOdds += 15;
}
if (!morale)
{
controlOdds = 100;
}
if (RNG::percent(controlOdds))
{
_psiAction->type = BA_MINDCONTROL;
_psiAction->target = _aggroTarget->getPosition();
_psiAction->weapon = item;
return true;
}
}
_psiAction->type = BA_PANIC;
_psiAction->target = _aggroTarget->getPosition();
_psiAction->weapon = item;
return true;
}
return false;
}
/**
* Performs a melee attack action.
*/
void AIModule::meleeAttack()
{
_unit->lookAt(_aggroTarget->getPosition() + Position(_unit->getArmor()->getSize()-1, _unit->getArmor()->getSize()-1, 0), false);
while (_unit->getStatus() == STATUS_TURNING)
_unit->turn();
if (_traceAI) { Log(LOG_INFO) << "Attack unit: " << _aggroTarget->getId(); }
_attackAction->target = _aggroTarget->getPosition();
_attackAction->type = BA_HIT;
_attackAction->weapon = _unit->getMeleeWeapon();
}
/**
* Validates a target.
* @param unit the target we want to validate.
* @param assessDanger do we care if this unit was previously targetted with a grenade?
* @param includeCivs do we include civilians in the threat assessment?
* @return whether this target is someone we would like to kill.
*/
bool AIModule::validTarget(BattleUnit *unit, bool assessDanger, bool includeCivs) const
{
// ignore units that are dead/unconscious
if (unit->isOut() ||
// they must be units that we "know" about
(_unit->getFaction() == FACTION_HOSTILE && _intelligence < unit->getTurnsSinceSpotted()) ||
// they haven't been grenaded
(assessDanger && unit->getTile()->getDangerous()) ||
// and they mustn't be on our side
unit->getFaction() == _unit->getFaction())
{
return false;
}
if (includeCivs)
{
return true;
}
return unit->getFaction() == _targetFaction;
}
/**
* Checks the alien's reservation setting.
* @return the reserve setting.
*/
BattleActionType AIModule::getReserveMode()
{
return _reserve;
}
/**
* We have a dichotomy on our hands: we have a ranged weapon and melee capability.
* let's make a determination on which one we'll be using this round.
*/
void AIModule::selectMeleeOrRanged()
{
RuleItem *rangedWeapon = _attackAction->weapon->getRules();
RuleItem *meleeWeapon = _unit->getMeleeWeapon() ? _unit->getMeleeWeapon()->getRules() : 0;
if (!meleeWeapon)
{
// no idea how we got here, but melee is definitely out of the question.
_melee = false;
return;
}
if (!rangedWeapon || _attackAction->weapon->getAmmoItem() == 0)
{
_rifle = false;
return;
}
int meleeOdds = 10;
int dmg = meleeWeapon->getPower();
if (meleeWeapon->isStrengthApplied())
{
dmg += _unit->getBaseStats()->strength;
}
dmg *= _aggroTarget->getArmor()->getDamageModifier(meleeWeapon->getDamageType());
if (dmg > 50)
{
meleeOdds += (dmg - 50) / 2;
}
if ( _visibleEnemies > 1 )
{
meleeOdds -= 20 * (_visibleEnemies - 1);
}
if (meleeOdds > 0 && _unit->getHealth() >= 2 * _unit->getBaseStats()->health / 3)
{
if (_unit->getAggression() == 0)
{
meleeOdds -= 20;
}
else if (_unit->getAggression() > 1)
{
meleeOdds += 10 * _unit->getAggression();
}
if (RNG::percent(meleeOdds))
{
_rifle = false;
_reachableWithAttack = _save->getPathfinding()->findReachable(_unit, _unit->getTimeUnits() - _unit->getActionTUs(BA_HIT, meleeWeapon));
return;
}
}
_melee = false;
}
/**
* Checks nearby nodes to see if they'd make good grenade targets
* @param action contains our details one weapon and user, and we set the target for it here.
* @return if we found a viable node or not.
*/
bool AIModule::getNodeOfBestEfficacy(BattleAction *action)
{
// i hate the player and i want him dead, but i don't want to piss him off.
if (_save->getTurn() < _save->getBattleState()->getGame()->getMod()->getTurnAIUseGrenade())
return false;
int bestScore = 2;
Position originVoxel = _save->getTileEngine()->getSightOriginVoxel(_unit);
Position targetVoxel;
for (std::vector<Node*>::const_iterator i = _save->getNodes()->begin(); i != _save->getNodes()->end(); ++i)
{
if ((*i)->isDummy())
{
continue;
}
int dist = _save->getTileEngine()->distance((*i)->getPosition(), _unit->getPosition());
if (dist <= 20 && dist > action->weapon->getRules()->getExplosionRadius() &&
_save->getTileEngine()->canTargetTile(&originVoxel, _save->getTile((*i)->getPosition()), O_FLOOR, &targetVoxel, _unit, false))
{
int nodePoints = 0;
for (std::vector<BattleUnit*>::const_iterator j = _save->getUnits()->begin(); j != _save->getUnits()->end(); ++j)
{
dist = _save->getTileEngine()->distance((*i)->getPosition(), (*j)->getPosition());
if (!(*j)->isOut() && dist < action->weapon->getRules()->getExplosionRadius())
{
Position targetOriginVoxel = _save->getTileEngine()->getSightOriginVoxel(*j);
if (_save->getTileEngine()->canTargetTile(&targetOriginVoxel, _save->getTile((*i)->getPosition()), O_FLOOR, &targetVoxel, *j, false))
{
if ((_unit->getFaction() == FACTION_HOSTILE && (*j)->getFaction() != FACTION_HOSTILE) ||
(_unit->getFaction() == FACTION_NEUTRAL && (*j)->getFaction() == FACTION_HOSTILE))
{
if ((*j)->getTurnsSinceSpotted() <= _intelligence)
{
nodePoints++;
}
}
else
{
nodePoints -= 2;
}
}
}
}
if (nodePoints > bestScore)
{
bestScore = nodePoints;
action->target = (*i)->getPosition();
}
}
}
return bestScore > 2;
}
BattleUnit* AIModule::getTarget()
{
return _aggroTarget;
}
}
| gpl-3.0 |
bizkut/BudakJahat | System/UI/Elements/Dropdown.lua | 4542 | local DiesalGUI = LibStub("DiesalGUI-1.0")
local DiesalTools = LibStub("DiesalTools-1.0")
function br.ui:createDropdown(parent, text, itemlist, default, tooltip, tooltipDrop, hideCheckbox)
-------------------------------
----Need to calculate Y Pos----
-------------------------------
local Y = -5
for i=1, #parent.children do
if parent.children[i].type ~= "Spinner" and parent.children[i].type ~= "Dropdown" then
Y = Y - parent.children[i].frame:GetHeight()*1.2
end
end
Y = DiesalTools.Round(Y)
-------------------------------
--------Create CheckBox--------
-------------------------------
checkBox = br.ui:createCheckbox(parent, text, tooltip)
if hideCheckbox then
local check = br.data.settings[br.selectedSpec][br.selectedProfile][text.."Check"]
if check == 0 then check = false end
if check == 1 then check = true end
if check == true then checkBox:SetChecked(false) end
checkBox:Disable()
checkBox:ReleaseTextures()
end
-------------------------------
-------------------------------
--------Create Dropdown--------
-------------------------------
local newDropdown = DiesalGUI:Create('Dropdown')
local default = default or 1
parent:AddChild(newDropdown)
newDropdown:SetParent(parent.content)
newDropdown:SetPoint("TOPRIGHT", parent.content, "TOPRIGHT", -10, Y)
newDropdown:SetHeight(12)
newDropdown:SetList(itemlist)
--------------
---BR Stuff---
--------------
-- Read from config or set default
if br.data.settings[br.selectedSpec][br.selectedProfile][text.."Drop"] == nil then br.data.settings[br.selectedSpec][br.selectedProfile][text.."Drop"] = default end
-- Add to UI Settings **Do not comment out or remove, will result in loss of settings**
if br.data.ui == nil then br.data.ui = {} end
br.data.ui[text.."Drop"] = br.data.settings[br.selectedSpec][br.selectedProfile][text.."Drop"]
local value = br.data.settings[br.selectedSpec][br.selectedProfile][text.."Drop"]
newDropdown:SetValue(value)
------------------
------Events------
------------------
-- Event: OnValueChange
newDropdown:SetEventListener('OnValueChanged', function(this, event, key, value, selection)
br.data.settings[br.selectedSpec][br.selectedProfile][text.."Drop"] = key
end)
-- Event: Tooltip
if tooltip or tooltipDrop then
local tooltip = tooltipDrop or tooltip
newDropdown:SetEventListener("OnEnter", function(this, event)
GameTooltip:SetOwner(Minimap, "ANCHOR_CURSOR", 50 , 50)
GameTooltip:SetText(tooltip, 214/255, 25/255, 25/255)
GameTooltip:Show()
end)
newDropdown:SetEventListener("OnLeave", function(this, event)
GameTooltip:Hide()
end)
end
----------------------
------END Events------
----------------------
newDropdown:ApplySettings()
----------------------------
--------END Dropdown--------
----------------------------
-- return newDropdown
end
function br.ui:createDropdownWithout(parent, text, itemlist, default, tooltip, tooltipDrop)
return br.ui:createDropdown(parent, text, itemlist, default, tooltip, tooltipDrop, true)
end
function br.ui:createProfileDropdown(parent)
-------------------------------
----Need to calculate Y Pos----
-------------------------------
local Y = -5
for i=1, #parent.children do
if parent.children[i].type ~= "Spinner" and parent.children[i].type ~= "Dropdown" then
Y = Y - parent.children[i].frame:GetHeight()*1.2
end
end
Y = DiesalTools.Round(Y)
local profiles = br.fetch(br.selectedSpec .. '_' .. 'profiles', {{key='default',text='Default'}})
local selectedProfile = br.fetch(br.selectedSpec .. '_' .. 'profile', 'default')
local profile_drop = DiesalGUI:Create('Dropdown')
parent:AddChild(profile_drop)
profile_drop:SetParent(parent.content)
profile_drop:SetPoint("TOPLEFT", parent.content, "TOPLEFT", 1, Y)
profile_drop:SetHeight(18)
profile_drop:SetWidth(200)
local list = { }
for i, value in pairs(profiles) do
list[value.key] = value.key
end
profile_drop:SetList(list)
profile_drop:SetValue(br.fetch(br.selectedSpec .. '_' .. 'profile', 'Default Profile'))
profile_drop:SetEventListener('OnValueChanged', function(this, event, key, value, selection)
br.profileDropValue = key
end)
end | gpl-3.0 |
CNR-ISMAR/rectifiedgrid | test/test_algebra.py | 385 | from rectifiedgrid.demo import get_demo_data
import numpy as np
class TestAlgebra(object):
def test_positive(self):
grid = get_demo_data()
grid.positive()
assert (grid.min(), grid.max()) == (0., 4.)
def test_gaussian_filter(self):
grid = get_demo_data('rg9x9')
grid.gaussian_filter(2.)
assert np.round(grid.sum(), 2) == 0.95
| gpl-3.0 |
Copona/copona | catalog/controller/extension/module/affiliate.php | 1843 | <?php
class ControllerExtensionModuleAffiliate extends Controller {
public function index() {
$this->load->language('extension/module/affiliate');
$data['heading_title'] = $this->language->get('heading_title');
$data['text_register'] = $this->language->get('text_register');
$data['text_login'] = $this->language->get('text_login');
$data['text_logout'] = $this->language->get('text_logout');
$data['text_forgotten'] = $this->language->get('text_forgotten');
$data['text_account'] = $this->language->get('text_account');
$data['text_edit'] = $this->language->get('text_edit');
$data['text_password'] = $this->language->get('text_password');
$data['text_payment'] = $this->language->get('text_payment');
$data['text_tracking'] = $this->language->get('text_tracking');
$data['text_transaction'] = $this->language->get('text_transaction');
$data['logged'] = $this->affiliate->isLogged();
$data['register'] = $this->url->link('affiliate/register', '', true);
$data['login'] = $this->url->link('affiliate/login', '', true);
$data['logout'] = $this->url->link('affiliate/logout', '', true);
$data['forgotten'] = $this->url->link('affiliate/forgotten', '', true);
$data['account'] = $this->url->link('affiliate/account', '', true);
$data['edit'] = $this->url->link('affiliate/edit', '', true);
$data['password'] = $this->url->link('affiliate/password', '', true);
$data['payment'] = $this->url->link('affiliate/payment', '', true);
$data['tracking'] = $this->url->link('affiliate/tracking', '', true);
$data['transaction'] = $this->url->link('affiliate/transaction', '', true);
return $this->load->view('extension/module/affiliate', $data);
}
} | gpl-3.0 |
MonokuroInzanaito/ygopro-777DIY | expansions/script/c60159218.lua | 5418 | --与笼中鸟的送别
function c60159218.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(60159218,1))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,60159218)
e1:SetTarget(c60159218.target)
e1:SetOperation(c60159218.operation)
c:RegisterEffect(e1)
--Activate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(60159218,2))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetCountLimit(1,60159218)
e2:SetTarget(c60159218.target2)
e2:SetOperation(c60159218.operation2)
c:RegisterEffect(e2)
--spsummon
local e7=Effect.CreateEffect(c)
e7:SetDescription(aux.Stringid(60159218,0))
e7:SetCategory(CATEGORY_SPECIAL_SUMMON)
e7:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e7:SetType(EFFECT_TYPE_QUICK_O)
e7:SetCode(EVENT_FREE_CHAIN)
e7:SetRange(LOCATION_GRAVE)
e7:SetCountLimit(1,60159218)
e7:SetCost(c60159218.spcost2)
e7:SetTarget(c60159218.sptg2)
e7:SetOperation(c60159218.spop2)
c:RegisterEffect(e7)
end
function c60159218.filter(c,e,tp)
return c:IsFaceup() and c:IsSetCard(0x5b25) and c:IsAbleToDeck() and not c:IsType(TYPE_FUSION+TYPE_SYNCHRO+TYPE_XYZ)
and Duel.IsExistingMatchingCard(c60159218.spfilter2,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil,e,tp)
end
function c60159218.spfilter2(c,e,tp)
return c:IsSetCard(0x5b25) and c:GetLevel()==4 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c60159218.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingTarget(c60159218.filter,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.Hint(HINT_OPSELECTED,1-tp,aux.Stringid(60159218,1))
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c60159218.filter,tp,LOCATION_MZONE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE)
end
function c60159218.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
if Duel.SendtoDeck(tc,nil,2,REASON_EFFECT)>0 then
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c60159218.spfilter2,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
end
end
function c60159218.filter2(c,e,tp)
return c:IsFaceup() and c:IsSetCard(0x5b25) and c:IsType(TYPE_FUSION+TYPE_SYNCHRO+TYPE_XYZ) and c:IsAbleToExtra()
and Duel.IsExistingMatchingCard(c60159218.spfilter22,tp,LOCATION_DECK+LOCATION_GRAVE,0,2,nil,e,tp)
end
function c60159218.spfilter22(c,e,tp)
return c:IsSetCard(0x5b25) and c:GetLevel()==4 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c60159218.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c60159218.filter2,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.Hint(HINT_OPSELECTED,1-tp,aux.Stringid(60159218,2))
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c60159218.filter2,tp,LOCATION_MZONE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE)
end
function c60159218.operation2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
if Duel.SendtoDeck(tc,nil,2,REASON_EFFECT)>0 then
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=1 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c60159218.spfilter22,tp,LOCATION_DECK+LOCATION_GRAVE,0,2,2,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
end
end
function c60159218.spcost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c60159218.spfilter(c,e,tp)
return c:IsSetCard(0x5b25) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c60159218.sptg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c60159218.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c60159218.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c60159218.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c60159218.spop2(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end
end | gpl-3.0 |
projectestac/alexandria | html/langpacks/ko/cachestore_static.php | 1053 | <?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Strings for component 'cachestore_static', language 'ko', version '3.11'.
*
* @package cachestore_static
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['pluginname'] = '정적 요청 캐시';
| gpl-3.0 |
ldbc/ldbc_driver | src/main/java/com/ldbc/driver/csv/charseeker/ThreadAheadReadable.java | 5006 | /**
* Copyright (c) 2002-2014 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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/>.
*/
package com.ldbc.driver.csv.charseeker;
import java.io.Closeable;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.locks.LockSupport;
import static java.lang.Math.min;
import static java.lang.System.arraycopy;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* Like an ordinary {@link CharReadable}, it's just that the reading happens in a separate thread, so when
* a consumer wants to {@link #read(char[], int, int)}} more data it's already available, merely a memcopy away.
*/
public class ThreadAheadReadable extends Thread implements CharReadable, Closeable {
private static final long PARK_TIME = MILLISECONDS.toNanos(100);
private final CharReadable actual;
private final Thread owner;
private final char[] readAheadArray;
private final CharBuffer readAheadBuffer;
private volatile boolean hasReadAhead;
private volatile boolean closed;
private volatile boolean eof;
private volatile IOException ioException;
private ThreadAheadReadable(CharReadable actual, int bufferSize) {
this.actual = actual;
this.owner = Thread.currentThread();
this.readAheadArray = new char[bufferSize];
this.readAheadBuffer = CharBuffer.wrap(readAheadArray);
this.readAheadBuffer.position(bufferSize);
setDaemon(true);
start();
}
/**
* The one calling read doesn't actually read, since reading is up to this guy. Instead the caller just
* waits for this thread to have fully read the next buffer.
*/
@Override
public int read(char[] buffer, int offset, int length) throws IOException {
// are we still healthy and all that?
assertHealthy();
// wait until thread has made data available
while (!hasReadAhead) {
parkAWhile();
assertHealthy();
}
if (eof) {
return -1;
}
// copy data from the read ahead buffer into the target buffer
int bytesToCopy = min(readAheadBuffer.remaining(), length);
arraycopy(readAheadArray, readAheadBuffer.position(), buffer, offset, bytesToCopy);
readAheadBuffer.position(readAheadBuffer.position() + bytesToCopy);
// wake up the reader... there's stuff to do, data to read
hasReadAhead = false;
LockSupport.unpark(this);
return bytesToCopy == 0 ? -1 : bytesToCopy;
}
private void assertHealthy() throws IOException {
if (ioException != null) {
throw new IOException("Error occured in read-ahead thread", ioException);
}
}
private void parkAWhile() {
LockSupport.parkNanos(PARK_TIME);
}
@Override
public void close() throws IOException {
closed = true;
try {
join();
} catch (InterruptedException e) {
throw new IOException(e);
} finally {
actual.close();
}
}
@Override
public void run() {
while (!closed) {
if (hasReadAhead || eof) { // We have already read ahead, sleep a little
parkAWhile();
} else { // We haven't read ahead, or the data we read ahead have been consumed
try {
readAheadBuffer.compact();
int read = actual.read(readAheadArray, readAheadBuffer.position(), readAheadBuffer.remaining());
if (read == -1) {
eof = true;
read = 0;
}
readAheadBuffer.limit(readAheadBuffer.position() + read);
readAheadBuffer.position(0);
hasReadAhead = true;
LockSupport.unpark(owner);
} catch (IOException e) {
ioException = e;
closed = true;
} catch (Throwable e) {
ioException = new IOException(e);
closed = true;
}
}
}
}
public static CharReadable threadAhead(CharReadable actual, int bufferSize) {
return new ThreadAheadReadable(actual, bufferSize);
}
} | gpl-3.0 |
Minestar/ConAir | src/main/java/de/minestar/conair/network/server/AbstractServerPacketHandler.java | 957 | /*
* Copyright (C) 2013 MineStar.de
*
* This file is part of ConAir.
*
* ConAir is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* ConAir 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 ConAir. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.conair.network.server;
import de.minestar.conair.network.packets.NetworkPacket;
public abstract class AbstractServerPacketHandler {
public abstract <P extends NetworkPacket> boolean handlePacket(ConnectedServerClient client, P packet);
}
| gpl-3.0 |
iceblow/beilaile | src/main/webapp/res/js/piecesPrint/distributeDetailedOrder.js | 3305 | /**
* 详单表
*/
var url = location.search; //获取url中"?"符后的字串
var str = location.search.substr(1);
$(function() {
// 分页
if(str.length==0){
loadPageDatas(1);
}else{
firstLoadData("/distributeDetailedOrder/distributeDetailedOrderBypage.do?orderId="+str, 1);
}
});
//分页
function loadPageDatas(index) {
firstLoadData("/distributeDetailedOrder/distributeDetailedOrderBypage.do", index);
}
// 分页查询以后前台页面打印
function loadData(mydata) {
getProces(mydata);
}
function getProces(mydata) {
$("tbody").empty();
$.each(mydata,function(index, op) {
var del=(op.status=="2"?"已发料":"<button class='btn btn-danger btn-sm delDetailedOrder' data-toggle='modal' href='javascript:;'>删 除</button></td>");
$("tbody").append(
"<tr>"
+"<input type='hidden' class='id' value='"+op.id+"'>"
+ "<td style='text-align: center;'>"
+ (op.wave==null?"":op.wave)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.printingFactory==null?"":op.printingFactory)
+ "</td>"
+ "<td style='text-align: center;'>"
+ "<img src='"+op.designImg+"' width='50px;' height='50px;'/>"
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code52==null||op.code52==0?"":op.code52)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code59==null||op.code59==0?"":op.code59)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code66==null||op.code66==0?"":op.code66)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code73==null||op.code73==0?"":op.code73)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code80==null||op.code80==0?"":op.code80)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code90==null||op.code90==0?"":op.code90)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code100==null||op.code100==0?"":op.code100)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code110==null||op.code110==0?"":op.code110)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code120==null||op.code120==0?"":op.code120)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code130==null||op.code130==0?"":op.code130)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code160==null||op.code160==0?"":op.code160)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.code170==null||op.code170==0?"":op.code170)
+ "</td>"
+ "<td style='text-align: center;'>"
+ (op.remark==null?"":op.remark)
+ "</td>"
+ "<td style='text-align: center; width:70px;'>"
+ del
+"</tr>");
});
// 修改
delProce();
}
function delProce(){
$(".delDetailedOrder").on("click",function(){
var id=$(this).parent().parent().find(".id").val();
if (confirm('确定要删除此条数据吗?')) {
$.ajax({
url:'distributeDetailedOrder/delDistributeDatailedOrder.do',
dataType:'json',
type:'post',
data:{
id:id
},success:function(data){
if(data!=1){
alert("删除失败!");
}
firstLoadData("distributeDetailedOrder/distributeDetailedOrderBypage.do?orderId="+str, $(".laypage_curr").text());
},error:function(){
alert("删除失败,系统错误!!");
}
});
}else{
return false;
}
});
} | gpl-3.0 |
GenaBitu/NIMP | src/Nodes/Sharpen.cpp | 185 | #include "Nodes/Sharpen.hpp"
Sharpen::Sharpen() : KernelConvolution{3}
{
kernel->set({0, -1, 0, -1, 5, -1, 0, -1, 0});
}
std::string Sharpen::nodeName()
{
return "Sharpen";
}
| gpl-3.0 |
fhaer/BPMN-XPDL-to-AristaFlow | src/de/bpmnaftool/model/aristaflow/graph/node/AndSplitNode.java | 728 | package de.bpmnaftool.model.aristaflow.graph.node;
/**
* An AndJoinSplit is used to start a new branch. In other words, from this
* AndJoinSplit on, there may be more than one outgoing edge. This allows all
* branches (outgoing edges) to be executed parallel.
* No activity can be assigned to this type of node.
*
* @author Felix Härer
*/
public class AndSplitNode extends NodeImpl {
/**
* String to describe the type of node. This should not be used for checking
* the type of an edge, the keyword instanceof can be used instead.
*/
public static final String nodeType = "NT_AND_SPLIT";
/**
* Constructor, sets node type
*/
public AndSplitNode() {
super(nodeType);
}
}
| gpl-3.0 |
martinrotter/textilosaurus | src/libtextosaurus/saurus/external-tools/predefinedtools.cpp | 11161 | // This file is distributed under GNU GPLv3 license. For full license text, see <project-git-repository-root-folder>/LICENSE.md.
#include "saurus/external-tools/predefinedtools.h"
#include "common/network-web/networkfactory.h"
#include "definitions/definitions.h"
#include "saurus/miscellaneous/application.h"
#include "saurus/miscellaneous/textapplication.h"
#include "saurus/miscellaneous/textapplicationsettings.h"
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QRegularExpression>
#include <QTemporaryFile>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
QString PredefinedTools::reverse(const QString& data, bool& ok) {
Q_UNUSED(ok)
QString rev;
for (auto chr = data.crbegin(); chr < data.crend(); chr++) {
rev.append(*chr);
}
return rev;
}
QString PredefinedTools::sendToHastebin(const QString& data, bool& ok) {
QByteArray output;
QString content = QString("%1").arg(data);
NetworkResult result = NetworkFactory::performNetworkOperation(PASTEBIN_HASTE_POST,
DOWNLOAD_TIMEOUT,
content.toUtf8(),
output,
QNetworkAccessManager::Operation::PostOperation);
if (result.first == QNetworkReply::NetworkError::NoError) {
ok = true;
QJsonDocument json_doc = QJsonDocument::fromJson(output);
return PASTEBIN_HASTE + json_doc.object()["key"].toString();
}
else {
ok = false;
return NetworkFactory::networkErrorText(result.first);
}
}
QString PredefinedTools::sendToClbin(const QString& data, bool& ok) {
QByteArray output;
QString content = QString("clbin=%1").arg(data);
NetworkResult result = NetworkFactory::performNetworkOperation(PASTEBIN_CLBIN,
DOWNLOAD_TIMEOUT,
content.toUtf8(),
output,
QNetworkAccessManager::Operation::PostOperation);
if (result.first == QNetworkReply::NetworkError::NoError) {
ok = true;
return QString(output).remove(QRegularExpression(QSL("\\s")));
}
else {
ok = false;
return NetworkFactory::networkErrorText(result.first);
}
}
QString PredefinedTools::sendToIxio(const QString& data, bool& ok) {
QByteArray output;
QString content = QString("f:1=%1").arg(data);
NetworkResult result = NetworkFactory::performNetworkOperation(PASTEBIN_IXIO,
DOWNLOAD_TIMEOUT,
content.toUtf8(),
output,
QNetworkAccessManager::Operation::PostOperation);
if (result.first == QNetworkReply::NetworkError::NoError) {
ok = true;
return QString(output).remove(QRegularExpression(QSL("\\s")));
}
else {
ok = false;
return NetworkFactory::networkErrorText(result.first);
}
}
QString PredefinedTools::jsonBeautify(const QString& data, bool& ok) {
QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
if (doc.isNull()) {
ok = false;
return QObject::tr("Parsing of JSON document failed.");
}
else {
ok = true;
return doc.toJson(QJsonDocument::JsonFormat::Indented);
}
}
QString PredefinedTools::jsonMinify(const QString& data, bool& ok) {
QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
if (doc.isNull()) {
ok = false;
return QObject::tr("Parsing of JSON document failed.");
}
else {
ok = true;
return doc.toJson(QJsonDocument::JsonFormat::Compact);
}
}
QString PredefinedTools::xmlCheck(const QString& data, bool& ok) {
QXmlStreamReader reader(data.toUtf8());
while (!reader.atEnd()) {
if (reader.hasError()) {
break;
}
reader.readNext();
}
ok = !reader.hasError();
return ok ? QObject::tr("XML is well-formed.") : reader.errorString();
}
QString PredefinedTools::xmlBeautify(const QString& data, bool& ok) {
QByteArray input = data.toUtf8();
QString xml_out;
QXmlStreamReader reader(input);
QXmlStreamWriter writer(&xml_out);
writer.setAutoFormatting(true);
writer.setAutoFormattingIndent(2);
while (!reader.atEnd()) {
reader.readNext();
if (reader.error() != QXmlStreamReader::Error::NoError) {
break;
}
if (!reader.isWhitespace() &&
reader.tokenType() != QXmlStreamReader::TokenType::Invalid &&
reader.tokenType() != QXmlStreamReader::TokenType::NoToken &&
reader.tokenType() != QXmlStreamReader::TokenType::StartDocument) {
writer.writeCurrentToken(reader);
}
}
if (reader.hasError()) {
ok = false;
return reader.errorString();
}
else {
ok = true;
return xml_out;
}
}
QString PredefinedTools::xmlBeautifyFile(const QString& xml_file, bool& ok) {
QFile file(xml_file);
QTemporaryFile file_out;
if (!file.open(QIODevice::OpenModeFlag::ReadWrite)) {
ok = false;
return file.errorString();
}
if (!file_out.open()) {
ok = false;
file.close();
return file_out.errorString();
}
QXmlStreamReader reader(&file);
QXmlStreamWriter writer(&file_out);
QString xml_encoding;
writer.setAutoFormatting(true);
writer.setAutoFormattingIndent(2);
while (!reader.atEnd()) {
reader.readNext();
if (reader.error() != QXmlStreamReader::Error::NoError) {
break;
}
if (reader.tokenType() == QXmlStreamReader::TokenType::StartDocument) {
xml_encoding = reader.documentEncoding().toString();
if (xml_encoding.isEmpty()) {
qWarning().noquote() << QSL("No XML encoding detected when beautifying XML file.");
}
else {
writer.setCodec(xml_encoding.toUtf8().data());
}
}
if (!reader.isWhitespace() &&
reader.tokenType() != QXmlStreamReader::TokenType::Invalid &&
reader.tokenType() != QXmlStreamReader::TokenType::NoToken) {
writer.writeCurrentToken(reader);
}
}
if (reader.hasError()) {
file.close();
file_out.close();
ok = false;
return reader.errorString();
}
else {
file.seek(0);
file_out.seek(0);
while (!file_out.atEnd()) {
file.write(file_out.readLine());
}
file.resize(file.pos());
file_out.close();
file.flush();
file.close();
ok = true;
return QString();
}
}
QString PredefinedTools::xmlLinearize(const QString& data, bool& ok) {
QByteArray input = data.toUtf8();
QString xml_out;
QXmlStreamReader reader(input);
QXmlStreamWriter writer(&xml_out);
writer.setAutoFormatting(false);
while (!reader.atEnd()) {
reader.readNext();
if (reader.error() != QXmlStreamReader::Error::NoError) {
break;
}
if (!reader.isWhitespace() &&
reader.tokenType() != QXmlStreamReader::TokenType::Invalid &&
reader.tokenType() != QXmlStreamReader::TokenType::NoToken) {
writer.writeCurrentToken(reader);
}
}
if (reader.hasError()) {
ok = false;
return reader.errorString();
}
else {
ok = true;
return xml_out;
}
}
QString PredefinedTools::currentDateTime(const QString& data, bool& ok) {
Q_UNUSED(data)
Q_UNUSED(ok)
return QLocale::system().toString(QDateTime::currentDateTime(),
QLocale::system().dateTimeFormat(QLocale::FormatType::ShortFormat));
}
QString PredefinedTools::currentDate(const QString& data, bool& ok) {
Q_UNUSED(data)
Q_UNUSED(ok)
return QLocale::system().toString(QDateTime::currentDateTime(),
QLocale::system().dateFormat(QLocale::FormatType::ShortFormat));
}
QString PredefinedTools::currentTime(const QString& data, bool& ok) {
Q_UNUSED(data)
Q_UNUSED(ok)
return QLocale::system().toString(QDateTime::currentDateTime(),
QLocale::system().timeFormat(QLocale::FormatType::ShortFormat));
}
QString PredefinedTools::formattedDateTime(const QString& data, bool& ok) {
Q_UNUSED(data)
Q_UNUSED(ok)
return QLocale::system().toString(QDateTime::currentDateTime(), qApp->textApplication()->settings()->dateTimeTimestampFormat());
}
QString PredefinedTools::toUrlEncoded(const QString& data, bool& ok) {
Q_UNUSED(ok)
return QUrl::toPercentEncoding(data);
}
QString PredefinedTools::fromUrlEncoded(const QString& data, bool& ok) {
Q_UNUSED(ok)
return QUrl::fromPercentEncoding(data.toUtf8());
}
QString PredefinedTools::toBase64(const QString& data, bool& ok) {
Q_UNUSED(ok)
return data.toUtf8().toBase64();
}
QString PredefinedTools::fromBase64(const QString& data, bool& ok) {
Q_UNUSED(ok)
return QByteArray::fromBase64(data.toUtf8());
}
QString PredefinedTools::toBase64Url(const QString& data, bool& ok) {
Q_UNUSED(ok)
return data.toUtf8().toBase64(QByteArray::Base64Option::Base64UrlEncoding);
}
QString PredefinedTools::fromBase64Url(const QString& data, bool& ok) {
Q_UNUSED(ok)
return QByteArray::fromBase64(data.toUtf8(), QByteArray::Base64Option::Base64UrlEncoding);
}
QString PredefinedTools::toLower(const QString& data, bool& ok) {
Q_UNUSED(ok)
return data.toLower();
}
QString PredefinedTools::toUpper(const QString& data, bool& ok) {
Q_UNUSED(ok)
return data.toUpper();
}
QString PredefinedTools::toTitleCase(const QString& data, bool& ok) {
Q_UNUSED(ok)
if (data.isEmpty()) {
return data;
}
else {
QString result = data;
QRegularExpression regexp(QSL("(\\s|^)([^\\s\\d])"));
QRegularExpressionMatchIterator match_iter = regexp.globalMatch(result);
while (match_iter.hasNext()) {
QRegularExpressionMatch next_match = match_iter.next();
QString capt = next_match.captured(2);
result[next_match.capturedStart(2)] = capt.at(0).toUpper();
}
return result;
}
}
QString PredefinedTools::toSentenceCase(const QString& data, bool& ok) {
Q_UNUSED(ok)
if (data.isEmpty()) {
return data;
}
else {
return data.at(0).toUpper() + data.mid(1);
}
}
QString PredefinedTools::invertCase(const QString& data, bool& ok) {
Q_UNUSED(ok)
if (data.isEmpty()) {
return data;
}
else {
QString result;
for (QChar chr : data) {
result += chr.isUpper() ? chr.toLower() : chr.toUpper();
}
return result;
}
}
QString PredefinedTools::toHtmlEscaped(const QString& data, bool& ok) {
Q_UNUSED(ok)
return data.toHtmlEscaped();
}
| gpl-3.0 |
sphenical/cqlite | src/cqlite/database.hpp | 4998 | /*
* LICENSE
*
* Copyright (c) 2016, David Daniel (dd), david@daniels.li
*
* database.hpp is free software copyrighted by David Daniel.
*
* 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
* 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/>.
*
* This program comes with ABSOLUTELY NO WARRANTY.
* This is free software, and you are welcome to redistribute it
* under certain conditions.
*/
#ifndef CQLITE_DATABASE_INC
#define CQLITE_DATABASE_INC
#include <cstdint>
#include <functional>
#include <map>
#include <string>
#include <utility>
#include <cqlite/cqlite_config.hpp>
#include <cqlite/cqlite_export.hpp>
#include <cqlite/error.hpp>
#include <cqlite/statement.hpp>
struct sqlite3;
namespace cqlite {
class DbError : public Error
{
public:
using Error::Error;
};
/**
* Represents a connection to a sqlite3 database file.
*/
class CQLITE_EXPORT Database
{
public:
enum class Operation
{
Insert,
Delete,
Update
};
/**
* The mode to open the database with.
* By default the database is opened in read-write mode and it is created if
* it does not already exist.
*/
enum Mode
{
/** No writing, very good for read-only initialization. */
ReadOnly = 0,
/** Read-write, the default */
ReadWrite = 1 << 0,
/** Create if not exist, default */
Create = 1 << 1,
/** Use a shared cache, so the connection shares the cache with other
* instances that also set this. */
Shared = 1 << 2,
/** Do not participate in a shared cache */
Private = 1 << 3,
/** Use URIs */
Uri = 1 << 4,
/** Use an in-memory database */
Memory = 1 << 5,
/** Multithreaded mode (one connection per thread) */
NoMutex = 1 << 6,
/** Serialized mode */
FullMutex = 1 << 7,
};
/**
* The callback that is triggered on every modifying database operation.
* @param op Insert, Delete, or Update
* @param db the name of the affected database (probably just "main")
* @param table the name of the affected table
* @param rowid the rowid of the affected row
*/
using UpdateHook = std::function<
void (Operation op, const std::string& db, const std::string& table,
std::int64_t rowid)>;
public:
Database ();
Database (const std::string&,
std::uint8_t = Mode::ReadWrite | Mode::Create | Mode::NoMutex);
~Database ();
Database (const Database&) = delete;
Database& operator= (const Database&) = delete;
Database (Database&&);
Database& operator= (Database&&);
Statement prepare (const std::string&);
Database& operator<< (const std::string&);
template<typename Hook>
Database& addUpdateHook (const std::string& table, Hook&& hook);
std::int64_t lastInsertId () const;
private:
static void static_update_hook (void*, int, char const*, char const*, std::int64_t);
private:
sqlite3* db_;
std::multimap<std::string, UpdateHook> hooks_;
};
/*!
* @brief Adds an update hook callback that gets called on every
* update/insert/delete on the given table.
*
* If "*" is given for \a table the hook is executed on every table.
*
* @tparam Hook Any callable that can be converted to an @ref UpdateHook
* @see UpdateHook
* @param table the name of the observed table
* @param hook the callback
* @return this database
*/
template<typename Hook>
inline Database& Database::addUpdateHook (const std::string& table, Hook&& hook)
{
hooks_.insert ({table, std::forward<Hook> (hook)});
return *this;
}
}
#endif /* CQLITE_DATABASE_INC */
| gpl-3.0 |
Securecom/Securecom-Messaging | src/com/securecomcode/messaging/dom/smil/SmilRegionElementImpl.java | 10137 | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.securecomcode.messaging.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
import android.util.Log;
public class SmilRegionElementImpl extends SmilElementImpl implements
SMILRegionElement {
/*
* Internal Interface
*/
private static final String HIDDEN_ATTRIBUTE = "hidden";
private static final String SLICE_ATTRIBUTE = "slice";
private static final String SCROLL_ATTRIBUTE = "scroll";
private static final String MEET_ATTRIBUTE = "meet";
private static final String FILL_ATTRIBUTE = "fill";
private static final String ID_ATTRIBUTE_NAME = "id";
private static final String WIDTH_ATTRIBUTE_NAME = "width";
private static final String TITLE_ATTRIBUTE_NAME = "title";
private static final String HEIGHT_ATTRIBUTE_NAME = "height";
private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor";
private static final String Z_INDEX_ATTRIBUTE_NAME = "z-index";
private static final String TOP_ATTRIBUTE_NAME = "top";
private static final String LEFT_ATTRIBUTE_NAME = "left";
private static final String RIGHT_ATTRIBUTE_NAME = "right";
private static final String BOTTOM_ATTRIBUTE_NAME = "bottom";
private static final String FIT_ATTRIBUTE_NAME = "fit";
private static final String TAG = "SmilRegionElementImpl";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
/*
* SMILRegionElement Interface
*/
public String getFit() {
String fit = getAttribute(FIT_ATTRIBUTE_NAME);
if (FILL_ATTRIBUTE.equalsIgnoreCase(fit)) {
return FILL_ATTRIBUTE;
} else if (MEET_ATTRIBUTE.equalsIgnoreCase(fit)) {
return MEET_ATTRIBUTE;
} else if (SCROLL_ATTRIBUTE.equalsIgnoreCase(fit)) {
return SCROLL_ATTRIBUTE;
} else if (SLICE_ATTRIBUTE.equalsIgnoreCase(fit)) {
return SLICE_ATTRIBUTE;
} else {
return HIDDEN_ATTRIBUTE;
}
}
public int getLeft() {
try {
return parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Left attribute is not set or incorrect.");
}
}
try {
int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
int right = parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true);
int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true);
return bbw - right - width;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Right or width attribute is not set or incorrect.");
}
}
return 0;
}
public int getTop() {
try {
return parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Top attribute is not set or incorrect.");
}
}
try {
int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
int bottom = parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false);
int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false);
return bbh - bottom - height;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Bottom or height attribute is not set or incorrect.");
}
}
return 0;
}
public int getZIndex() {
try {
return Integer.parseInt(this.getAttribute(Z_INDEX_ATTRIBUTE_NAME));
} catch (NumberFormatException _) {
return 0;
}
}
public void setFit(String fit) throws DOMException {
if (fit.equalsIgnoreCase(FILL_ATTRIBUTE)
|| fit.equalsIgnoreCase(MEET_ATTRIBUTE)
|| fit.equalsIgnoreCase(SCROLL_ATTRIBUTE)
|| fit.equalsIgnoreCase(SLICE_ATTRIBUTE)) {
this.setAttribute(FIT_ATTRIBUTE_NAME, fit.toLowerCase());
} else {
this.setAttribute(FIT_ATTRIBUTE_NAME, HIDDEN_ATTRIBUTE);
}
}
public void setLeft(int left) throws DOMException {
this.setAttribute(LEFT_ATTRIBUTE_NAME, String.valueOf(left));
}
public void setTop(int top) throws DOMException {
this.setAttribute(TOP_ATTRIBUTE_NAME, String.valueOf(top));
}
public void setZIndex(int zIndex) throws DOMException {
if (zIndex > 0) {
this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(zIndex));
} else {
this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(0));
}
}
public String getBackgroundColor() {
return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME);
}
public int getHeight() {
try {
final int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false);
return height == 0 ?
((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight() :
height;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Height attribute is not set or incorrect.");
}
}
int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
try {
bbh -= parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Top attribute is not set or incorrect.");
}
}
try {
bbh -= parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Bottom attribute is not set or incorrect.");
}
}
return bbh;
}
public String getTitle() {
return this.getAttribute(TITLE_ATTRIBUTE_NAME);
}
public int getWidth() {
try {
final int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true);
return width == 0 ?
((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth() :
width;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Width attribute is not set or incorrect.");
}
}
int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
try {
bbw -= parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Left attribute is not set or incorrect.");
}
}
try {
bbw -= parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Right attribute is not set or incorrect.");
}
}
return bbw;
}
public void setBackgroundColor(String backgroundColor) throws DOMException {
this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor);
}
public void setHeight(int height) throws DOMException {
this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px");
}
public void setTitle(String title) throws DOMException {
this.setAttribute(TITLE_ATTRIBUTE_NAME, title);
}
public void setWidth(int width) throws DOMException {
this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px");
}
/*
* SMILElement Interface
*/
@Override
public String getId() {
return this.getAttribute(ID_ATTRIBUTE_NAME);
}
@Override
public void setId(String id) throws DOMException {
this.setAttribute(ID_ATTRIBUTE_NAME, id);
}
/*
* Internal Interface
*/
private int parseRegionLength(String length, boolean horizontal) {
if (length.endsWith("px")) {
length = length.substring(0, length.indexOf("px"));
return Integer.parseInt(length);
} else if (length.endsWith("%")) {
double value = 0.01*Integer.parseInt(length.substring(0, length.length() - 1));
if (horizontal) {
value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
} else {
value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
}
return (int) Math.round(value);
} else {
return Integer.parseInt(length);
}
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString()
+ ": id=" + getId()
+ ", width=" + getWidth()
+ ", height=" + getHeight()
+ ", left=" + getLeft()
+ ", top=" + getTop();
}
}
| gpl-3.0 |
masterucm1617/botzzaroni | BotzzaroniDev/GATE_Developer_8.4/src/main/gate/gui/ontology/TransitivePropertyAction.java | 6515 | /*
* Copyright (c) 1995-2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* Niraj Aswani, 09/March/07
*
* $Id: TransitivePropertyAction.html,v 1.0 2007/03/09 16:13:01 niraj Exp $
*/
package gate.gui.ontology;
import gate.creole.ontology.*;
import gate.gui.MainFrame;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Action to create a new Transitive Property
*/
public class TransitivePropertyAction extends AbstractAction implements
TreeNodeSelectionListener {
private static final long serialVersionUID = 4049916060868227125L;
public TransitivePropertyAction(String s, Icon icon) {
super(s, icon);
mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(3, 3, 3, 3);
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(new JLabel("Name Space:"), gbc);
mainPanel.add(nameSpace = new JTextField(30), gbc);
gbc.gridy = 1;
mainPanel.add(new JLabel("Property Name:"), gbc);
mainPanel.add(propertyName = new JTextField(30), gbc);
mainPanel.add(domainButton = new JButton("Domain"), gbc);
mainPanel.add(rangeButton = new JButton("Range"), gbc);
domainAction = new ValuesSelectionAction();
domainButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionevent) {
String as[] = new String[ontologyClassesURIs.size()];
for(int i = 0; i < as.length; i++)
as[i] = ontologyClassesURIs.get(i);
ArrayList<String> arraylist = new ArrayList<String>();
for(int j = 0; j < selectedNodes.size(); j++) {
DefaultMutableTreeNode defaultmutabletreenode = selectedNodes.get(j);
if(((OResourceNode)defaultmutabletreenode.getUserObject())
.getResource() instanceof OClass)
arraylist.add((((OResourceNode)defaultmutabletreenode
.getUserObject()).getResource()).getONodeID().toString());
}
String as1[] = new String[arraylist.size()];
for(int k = 0; k < as1.length; k++)
as1[k] = arraylist.get(k);
domainAction.showGUI("Domain", as, as1, false,
MainFrame.getIcon("ontology-transitive-property"));
}
});
rangeAction = new ValuesSelectionAction();
rangeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionevent) {
String as[] = new String[ontologyClassesURIs.size()];
for(int i = 0; i < as.length; i++)
as[i] = ontologyClassesURIs.get(i);
rangeAction.showGUI("Range", as, new String[0], false,
MainFrame.getIcon("ontology-transitive-property"));
}
});
}
@Override
public void actionPerformed(ActionEvent actionevent) {
nameSpace.setText(ontology.getDefaultNameSpace() == null ?
"http://gate.ac.uk/example#" : ontology.getDefaultNameSpace());
@SuppressWarnings("serial")
JOptionPane pane = new JOptionPane(mainPanel, JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
MainFrame.getIcon("ontology-transitive-property")) {
@Override
public void selectInitialValue() {
propertyName.requestFocusInWindow();
propertyName.selectAll();
}
};
pane.createDialog(MainFrame.getInstance(),
"New Transitive Property").setVisible(true);
Object selectedValue = pane.getValue();
if (selectedValue != null
&& selectedValue instanceof Integer
&& (Integer) selectedValue == JOptionPane.OK_OPTION) {
String s = nameSpace.getText();
if(!Utils.isValidNameSpace(s)) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Invalid Name Space: " + s + "\nExample: http://gate.ac.uk/example#");
return;
}
if(!Utils.isValidOntologyResourceName(propertyName.getText())) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Invalid Property Name: " + propertyName.getText());
return;
}
if(Utils.getOResourceFromMap(ontology,s + propertyName.getText()) != null) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),"<html>" +
"Resource <b>" + s+propertyName.getText() + "</b> already exists.");
return;
}
String domainSelectedValues[] = domainAction.getSelectedValues();
HashSet<OClass> domainSet = new HashSet<OClass>();
for(int j = 0; j < domainSelectedValues.length; j++) {
OClass oclass = (OClass)
Utils.getOResourceFromMap(ontology,domainSelectedValues[j]);
domainSet.add(oclass);
}
String rangeSelectedValues[] = rangeAction.getSelectedValues();
HashSet<OClass> rangeSet = new HashSet<OClass>();
for(int j = 0; j < rangeSelectedValues.length; j++) {
OClass oclass = (OClass)Utils.getOResourceFromMap(
ontology,rangeSelectedValues[j]);
rangeSet.add(oclass);
}
ontology.addTransitiveProperty(ontology.createOURI(nameSpace.getText()
+ propertyName.getText()), domainSet, rangeSet);
}
}
public Ontology getOntology() {
return ontology;
}
public void setOntology(Ontology ontology) {
this.ontology = ontology;
}
@Override
public void selectionChanged(ArrayList<DefaultMutableTreeNode> arraylist) {
selectedNodes = arraylist;
}
public ArrayList<String> getOntologyClassesURIs() {
return ontologyClassesURIs;
}
public void setOntologyClassesURIs(ArrayList<String> arraylist) {
ontologyClassesURIs = arraylist;
}
protected JPanel mainPanel;
protected JTextField nameSpace;
protected JTextField propertyName;
protected JButton domainButton;
protected JButton rangeButton;
protected ValuesSelectionAction domainAction;
protected ValuesSelectionAction rangeAction;
protected ArrayList<String> ontologyClassesURIs;
protected ArrayList<DefaultMutableTreeNode> selectedNodes;
protected Ontology ontology;
}
| gpl-3.0 |
andreymal/mini_fiction | mini_fiction/logic/caching.py | 138 | from cachelib import BaseCache
from flask import current_app
def get_cache() -> BaseCache:
return current_app.cache # type: ignore
| gpl-3.0 |
eliteironlix/portaio2 | Core/Utility Ports/ActivatorSharp/Spells/Heals/imbue.cs | 1441 | using System;
using Activator.Base;
using LeagueSharp.Common;
using EloBuddy;
using LeagueSharp.Common;
namespace Activator.Spells.Heals
{
class imbue : CoreSpell
{
internal override string Name => "imbue";
internal override string DisplayName => "Imbue | Q";
internal override float Range => 750f;
internal override MenuType[] Category => new[] { MenuType.SelfLowHP, MenuType.SelfMinMP };
internal override int DefaultHP => 90;
internal override int DefaultMP => 55;
internal override int Priority => 4;
public override void OnTick(EventArgs args)
{
if (!Menu.Item("use" + Name).GetValue<bool>() || !IsReady())
return;
if (Player.Mana/Player.MaxMana * 100 <
Menu.Item("selfminmp" + Name + "pct").GetValue<Slider>().Value)
return;
foreach (var hero in Activator.Allies())
{
if (!Parent.Item(Parent.Name + "useon" + hero.Player.NetworkId).GetValue<bool>())
continue;
if (hero.Player.Distance(Player.ServerPosition) <= Range)
{
if (hero.Player.Health/hero.Player.MaxHealth * 100 <=
Menu.Item("selflowhp" + Name + "pct").GetValue<Slider>().Value)
UseSpellOn(hero.Player);
}
}
}
}
}
| gpl-3.0 |
erikgrinaker/BOUT-dev | tools/pylib/boututils/efit_analyzer.py | 10886 | # -*- coding: utf-8 -*-
#import matplotlib
#matplotlib.use('Qt4Agg')
#from pylab import *
from __future__ import absolute_import
from __future__ import division
from builtins import range
from past.utils import old_div
import numpy as np
from bunch import Bunch
from .radial_grid import radial_grid
from .analyse_equil_2 import analyse_equil
from pylab import figure, show, draw, plot, contour, setp, clabel, title, streamplot, cm, gca, annotate, subplot2grid, Rectangle, tight_layout, text, subplots_adjust, figaspect, setp, legend, tick_params
from boututils.closest_line import closest_line
from .ask import query_yes_no
from .read_geqdsk import read_geqdsk
from scipy import interpolate
def View2D(g, option=0):
# plot and check the field
fig=figure(num=2, figsize=(16, 6))
# fig.suptitle('Efit Analysis', fontsize=20)
ax = subplot2grid((3,3), (0,0), colspan=1, rowspan=3)
nlev = 100
minf = np.min(g.psi)
maxf = np.max(g.psi)
levels = np.arange(np.float(nlev))*(maxf-minf)/np.float(nlev-1) + minf
ax.contour(g.r,g.z,g.psi, levels=levels)
# ax.set_xlim([0,6])
ax.set_xlabel('R')
ax.set_ylabel('Z')
ax.yaxis.label.set_rotation('horizontal')
ax.set_aspect('equal')
# fig.suptitle('Efit Analysis', fontsize=20)
# title('Efit Analysis', fontsize=20)
text(0.5, 1.08, 'Efit Analysis',
horizontalalignment='center',
fontsize=20,
transform = ax.transAxes)
draw()
if option == 0 : show(block=False)
plot(g.xlim,g.ylim,'g-')
draw()
csb=contour( g.r, g.z, g.psi, levels=[g.sibdry])
clabel(csb, [g.sibdry], # label the level
inline=1,
fmt='%9.6f',
fontsize=14)
csb.collections[0].set_label('boundary')
# pl1=plot(g.rbdry,g.zbdry,'b-',marker='x', label='$\psi=$'+ np.str(g.sibdry))
# legend(bbox_to_anchor=(0., 1.05, 1., .105), loc='upper left')
draw()
# fig.set_tight_layout(True)
# show(block=False)
# Function fpol and qpsi are given between simagx (psi on the axis) and sibdry (
# psi on limiter or separatrix). So the toroidal field (fpol/R) and the q profile are within these boundaries
npsigrid=old_div(np.arange(np.size(g.pres)).astype(float),(np.size(g.pres)-1))
fpsi = np.zeros((2, np.size(g.fpol)), np.float64)
fpsi[0,:] = (g.simagx + npsigrid * ( g.sibdry -g.simagx ))
fpsi[1,:] = g.fpol
boundary = np.array([g.xlim, g.ylim])
rz_grid = Bunch(nr=g.nx, nz=g.ny, # Number of grid points
r=g.r[:,0], z=g.z[0,:], # R and Z as 1D arrays
simagx=g.simagx, sibdry=g.sibdry, # Range of psi
psi=g.psi, # Poloidal flux in Weber/rad on grid points
npsigrid=npsigrid, # Normalised psi grid for fpol, pres and qpsi
fpol=g.fpol, # Poloidal current function on uniform flux grid
pres=g.pres, # Plasma pressure in nt/m^2 on uniform flux grid
qpsi=g.qpsi, # q values on uniform flux grid
nlim=g.nlim, rlim=g.xlim, zlim=g.ylim) # Wall boundary
critical = analyse_equil(g.psi,g.r[:,0],g.z[0,:])
n_opoint = critical.n_opoint
n_xpoint = critical.n_xpoint
primary_opt = critical.primary_opt
inner_sep = critical.inner_sep
opt_ri = critical.opt_ri
opt_zi = critical.opt_zi
opt_f = critical.opt_f
xpt_ri = critical.xpt_ri
xpt_zi = critical.xpt_zi
xpt_f = critical.xpt_f
psi_inner=0.6
psi_outer=0.8,
nrad=68
npol=64
rad_peaking=[0.0]
pol_peaking=[0.0]
parweight=0.0
boundary = np.array([rz_grid.rlim, rz_grid.zlim])
# Psi normalisation factors
faxis = critical.opt_f[critical.primary_opt]
fnorm = critical.xpt_f[critical.inner_sep] - critical.opt_f[critical.primary_opt]
# From normalised psi, get range of f
f_inner = faxis + np.min(psi_inner)*fnorm
f_outer = faxis + np.max(psi_outer)*fnorm
fvals = radial_grid(nrad, f_inner, f_outer, 1, 1, [xpt_f[inner_sep]], rad_peaking)
## Create a starting surface
#sind = np.int(nrad / 2)
#start_f = 0. #fvals[sind]
# Find where we have rational surfaces
# define an interpolation of psi(q)
psiq = np.arange(np.float(g.qpsi.size))*(g.sibdry-g.simagx)/np.float(g.qpsi.size-1) + g.simagx
fpsiq=interpolate.interp1d(g.qpsi, psiq)
# Find how many rational surfaces we have within the boundary and locate x,y position of curves
nmax=g.qpsi.max().astype(int)
nmin=g.qpsi.min().astype(int)
nr=np.arange(nmin+1,nmax+1)
psi=fpsiq(nr)
cs=contour( g.r, g.z, g.psi, levels=psi)
labels = ['$q='+np.str(x)+'$\n' for x in range(nr[0],nr[-1]+1)]
for i in range(len(labels)):
cs.collections[i].set_label(labels[i])
style=['--', ':', '--', ':','-.' ]
# gca().set_color_cycle(col)
# proxy = [Rectangle((0,0),1,1, fc=col[:i+1])
# for pc in cs.collections]
#
# l2=legend(proxy, textstr[:i)
#
# gca().add_artist(l1)
x=[]
y=[]
for i in range(psi.size):
xx,yy=surface(cs, i, psi[i],opt_ri[primary_opt], opt_zi[primary_opt], style, option)
x.append(xx)
y.append(yy)
#props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
#textstr = ['$q='+np.str(x)+'$\n' for x in range(psi.size)]
#
#ax.text(0.85, 1.15, ''.join(textstr), transform=ax.transAxes, fontsize=14,
#verticalalignment='top', bbox=props)
legend(bbox_to_anchor=(-.8, 1), loc='upper left', borderaxespad=0.)
draw()
#compute B - field
Bp=np.gradient(g.psi)
dr=old_div((np.max(g.r[:,0])-np.min(g.r[:,0])),np.size(g.r[:,0]))
dz=old_div((np.max(g.z[0,:])-np.min(g.z[0,:])),np.size(g.z[0,:]))
dpsidr=Bp[0]
dpsidz=Bp[1]
Br=-dpsidz/dz/g.r
Bz=dpsidr/dr/g.r
Bprz=np.sqrt(Br*Br+Bz*Bz)
# plot Bp field
if option == 0 :
sm = query_yes_no("Overplot vector field")
if sm == 1 :
lw = 50*Bprz/Bprz.max()
streamplot(g.r.T,g.z.T, Br.T,Bz.T, color=Bprz, linewidth=2, cmap=cm.bone)#density =[.5, 1], color='k')#, linewidth=lw)
draw()
# plot toroidal field
ax = subplot2grid((3,3), (0,1), colspan=2, rowspan=1)
ax.plot(psiq,fpsi[1,:])
#ax.set_xlim([0,6])
#ax.set_xlabel('$\psi$')
ax.set_ylabel('$fpol$')
ax.yaxis.label.set_size(20)
#ax.xaxis.label.set_size(20)
ax.set_xticks([])
ax.yaxis.label.set_rotation('horizontal')
#ax.xaxis.labelpad = 10
ax.yaxis.labelpad = 20
#props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
#ax.text(0.85, 0.95, '$B_t$', transform=ax.transAxes, fontsize=14,
# verticalalignment='top', bbox=props)
#
draw()
# plot pressure
ax = subplot2grid((3,3), (1,1), colspan=2, rowspan=1)
ax.plot(psiq,g.pres)
#ax.set_xlim([0,6])
#ax.set_xlabel('$\psi$')
ax.set_ylabel('$P$')
ax.yaxis.label.set_size(20)
#ax.xaxis.label.set_size(20)
ax.set_xticks([])
ax.yaxis.label.set_rotation('horizontal')
#ax.xaxis.labelpad = 10
ax.yaxis.labelpad = 20
#props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
#ax.text(0.85, 0.95, '$B_t$', transform=ax.transAxes, fontsize=14,
# verticalalignment='top', bbox=props)
#
draw()
# plot qpsi
ax = subplot2grid((3,3), (2,1), colspan=2, rowspan=1)
ax.plot(psiq,g.qpsi)
ax.set_xlabel('$\psi$')
ax.set_ylabel('$q$')
ax.yaxis.label.set_rotation('horizontal')
ax.yaxis.label.set_size(20)
ax.xaxis.label.set_size(20)
ax.xaxis.labelpad = 10
ax.yaxis.labelpad = 20
tick_params(\
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='on', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='on')
draw()
# Compute and draw Jpar
#
# MU = 4.e-7*np.pi
#
# jpar0 = - Bxy * fprime / MU - Rxy*Btxy * dpdpsi / Bxy
#
# fig.set_tight_layout(True)
fig.subplots_adjust(left=0.2, top=0.9, hspace=0.1, wspace=0.5)
draw()
if option == 0 : show(block=False)
if option != 0:
return Br,Bz, x, y, psi
## output to files
#np.savetxt('../data.in', np.reshape([g.nx, g.ny],(1,2)), fmt='%i, %i')
#f_handle = open('../data.in', 'a')
#np.savetxt(f_handle,np.reshape([g.rmagx, g.zmagx],(1,2)), fmt='%e, %e')
#np.savetxt(f_handle, np.reshape([np.max(g.r),np.max(g.z)],(1,2)))
#np.savetxt(f_handle, np.reshape([g.bcentr,g.rcentr],(1,2)))
#f_handle.close()
#
#
#f_handle = open('../input.field', 'w')
#np.savetxt(f_handle, np.reshape([dx, dy],(1,2)))
#np.savetxt(f_handle, (g.r[:,0],g.z[0,:]))
#np.savetxt(f_handle, Bx) # fortran compatibility
#np.savetxt(f_handle, By)
#f_handle.close()
#
#np.savetxt('../tbound',[np.size(g.xlim)], fmt='%i')
#f_handle = open('../tbound', 'a')
#np.savetxt(f_handle, (g.xlim,g.ylim))
#f_handle.close()
#
#np.savetxt('../pbound',[np.size(g.rbdry)], fmt='%i')
#f_handle = open('../pbound', 'a')
#np.savetxt(f_handle, (g.rbdry,g.zbdry))
#f_handle.close()
def surface(cs, i, f, opt_ri, opt_zi, style, iplot=0):
# contour_lines( F, np.arange(nx).astype(float), np.arange(ny).astype(float), levels=[start_f])
# cs=contour( g.r, g.z, g.psi, levels=[f])
# proxy = [Rectangle((0,0),1,1,fc = 'b')
# for pc in cs.collections]
#
# legend(proxy, ["q="+np.str(i)])
p = cs.collections[i].get_paths()
#
# You might get more than one contours for the same start_f. We need to keep the closed one
vn=np.zeros(np.size(p))
# find the closed contour
for k in range(np.size(p)):
v=p[k].vertices
vx=v[:,0]
vy=v[:,1]
if [vx[0], vy[0]] == [vx[-1],vy[-1]] :
xx=vx
yy=vy
x=xx
y=yy
#v = p[0].vertices
#vn[0]=np.shape(v)[0]
#xx=v[:,0]
#yy=v[:,1]
#if np.shape(vn)[0] > 1:
# for i in xrange(1,np.shape(vn)[0]):
# v = p[i].vertices
# vn[i]=np.shape(v)[0]
# xx = [xx,v[:,0]]
# yy = [yy,v[:,1]]
#if np.shape(vn)[0] > 1 :
## Find the surface closest to the o-point
# ind = closest_line(np.size(xx), xx, yy, opt_ri, opt_zi)
# x=xx[ind]
# y=yy[ind]
#else:
# ind = 0
# x=xx
# y=yy
#
if(iplot == 0):
# plot the start_f line
zc = cs.collections[i]
setp(zc, linewidth=4, linestyle=style[i])
clabel(cs, [f], # label the level
inline=1,
fmt='%9.6f',
fontsize=14)
# annotate('q= '+np.str(i+1),(x[0]+.1,y[0]+.1))
draw()
show(block=False)
return x,y
if __name__ == '__main__':
path='../../tokamak_grids/pyGridGen/'
g=read_geqdsk(path+"g118898.03400")
View2D(g, option=0)
show()
| gpl-3.0 |
bizkut/BudakJahat | Rotations/Rogue/Subtlety/SubS0ul.lua | 72639 | local rotationName = "|cffFF6EB4 SubS0ul - 9.x"
local opener = true
local resetButton
local dotBlacklist = "135824|139057|129359|129448|134503|137458|139185|120651"
local stunSpellList = "274400|274383|257756|276292|268273|256897|272542|272888|269266|258317|258864|259711|258917|264038|253239|269931|270084|270482|270506|270507|267433|267354|268702|268846|268865|258908|264574|272659|272655|267237|265568|277567|265540"
---------------
--- Toggles ---
---------------
local function createToggles() -- Define custom toggles
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of enemies in range.", highlight = 1, icon = br.player.spell.shurikenStorm },
[2] = { mode = "Sing", value = 2 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 0, icon = br.player.spell.shadowstrike },
[3] = { mode = "Off", value = 3 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.stealth}
};
CreateButton("Rotation",1,0)
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.shadowBlades },
[2] = { mode = "On", value = 2 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.shadowBlades },
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.shadowBlades },
[4] = { mode = "Lust", value = 4 , overlay = "Cooldowns With Bloodlust", tip = "Cooldowns will be used with bloodlust or simlar effects.", highlight = 0, icon = br.player.spell.shadowBlades }
};
CreateButton("Cooldown",2,0)
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.evasion },
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.evasion }
};
CreateButton("Defensive",3,0)
InterruptModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.kick },
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.kick }
};
CreateButton("Interrupt",4,0)
AoeModes = {
[1] = { mode = "Std", value = 1 , overlay = "Standard AoE Rotation", tip = "Standard AoE Rotation.", highlight = 1, icon = br.player.spell.rupture },
[2] = { mode = "Prio", value = 2 , overlay = "Priority Target AoE Rotation", tip = "Priority Target AoE Rotation.", highlight = 1, icon = br.player.spell.eviscerate }
};
CreateButton("Aoe",5,0)
SDModes = {
[1] = { mode = "On", value = 1 , overlay = "Use Shadow Dance", tip = "Using Shadow Dance.", highlight = 1, icon = br.player.spell.shadowDance },
[2] = { mode = "Off", value = 2 , overlay = "Shadow Dance Disabled", tip = "Shadow Dance Disabled.", highlight = 0, icon = br.player.spell.shadowDance }
};
CreateButton("SD",6,0)
SoDModes = {
[1] = { mode = "On", value = 1 , overlay = "Use Symbols of Death", tip = "Using Symbols of Death.", highlight = 1, icon = br.player.spell.symbolsOfDeath },
[2] = { mode = "Off", value = 2 , overlay = "Symbols of Death Disabled", tip = "Symbols of Death Disabled.", highlight = 0, icon = br.player.spell.symbolsOfDeath }
};
CreateButton("SoD",7,0)
STModes = {
[1] = { mode = "On", value = 1 , overlay = "Use Secret Technique", tip = "Using Secret Technique.", highlight = 1, icon = br.player.spell.secretTechnique },
[2] = { mode = "Off", value = 2 , overlay = "Secret Technique Disabled", tip = "Secret Technique Disabled.", highlight = 0, icon = br.player.spell.secretTechnique }
};
CreateButton("ST",8,0)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
-----------------------
--- GENERAL OPTIONS --- -- Define General Options
-----------------------
section = br.ui:createSection(br.ui.window.profile, "General")
br.ui:createDropdown(section, "Poison", {"Instant","Wound",}, 1, "Poison to apply")
br.ui:createDropdown(section, "Auto Stealth", {"Always", "25 Yards"}, 1, "Auto stealth mode.")
br.ui:createDropdown(section, "Auto Tricks", {"Focus", "Tank"}, 1, "Tricks of the Trade target." )
br.ui:createCheckbox(section, "Auto Target", "Will auto change to a new target, if current target is dead.")
br.ui:createCheckbox(section, "Disable Auto Combat", "Will not auto attack out of stealth.")
br.ui:createCheckbox(section, "Dot Blacklist", "Check to ignore certain units when multidotting.")
br.ui:createCheckbox(section, "Auto Rupture HP Limit", "Will try to calculate if we should rupture units, based on their HP")
br.ui:createSpinnerWithout(section, "Multidot Limit", 3, 0, 8, 1, "Max units to dot with rupture.")
br.ui:createSpinner(section, "Shuriken Toss out of range", 90, 1, 100, 5, "Use Shuriken Toss out of range")
br.ui:createCheckbox(section, "Ignore Blacklist for SS", "Ignore blacklist for Shrukien Storm usage.")
br.ui:createSpinner(section, "Save SD Charges for CDs", 0.75, 0, 1, 0.05, "Shadow Dance charges to save for CDs. (Use toggle to disable SD for saving all)")
br.ui:createDropdownWithout(section, "MfD Target", {"Lowest TTD", "Always Target"}, 1, "MfD Target.")
br.ui:checkSectionState(section)
------------------------
--- COOLDOWN OPTIONS --- -- Define Cooldown Options
------------------------
section = br.ui:createSection(br.ui.window.profile, "Cooldowns")
br.ui:createCheckbox(section, "Racial", "Will use Racial")
br.ui:createCheckbox(section, "Essences", "Will use Essences")
br.ui:createSpinnerWithout(section, "Reaping DMG", 10, 1, 50, 1, "* 5k Put damage of your Reaping Flames")
br.ui:createCheckbox(section, "Trinkets", "Will use Trinkets")
br.ui:createDropdown(section, "Potion", {"Agility", "Unbridled Fury", "Focused Resolve"}, 3, "Potion with CDs")
br.ui:createCheckbox(section, "Vanish", "Will use Vanish")
br.ui:createCheckbox(section, "Shadow Blades", "Will use Shadow Blades")
br.ui:createCheckbox(section, "Precombat", "Will use items/pots on pulltimer")
br.ui:createSpinnerWithout(section, "CDs TTD Limit", 5, 0, 20, 1, "Time to die limit for using cooldowns.")
br.ui:checkSectionState(section)
-------------------------
--- DEFENSIVE OPTIONS --- -- Define Defensive Options
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Defensive")
br.ui:createSpinner(section, "Health Pot / Healthstone", 25, 0, 100, 5, "Health Percentage to use at.")
br.ui:createSpinner(section, "Heirloom Neck", 60, 0, 100, 5, "Health Percentage to use at.")
br.ui:createCheckbox(section, "Cloak of Shadows")
br.ui:createSpinner(section, "Crimson Vial", 40, 0, 100, 5, "Health Percentage to use at.")
br.ui:createSpinner(section, "Evasion", 50, 0, 100, 5, "Health Percentage to use at.")
br.ui:createSpinner(section, "Feint", 75, 0, 100, 5, "Health Percentage to use at.")
br.ui:createCheckbox(section, "Auto Defensive Unavoidables", "Will use feint/evasion on certain unavoidable boss abilities")
br.ui:createSpinnerWithout(section, "Evasion Unavoidables HP Limit", 85, 0, 100, 5, "Player HP to use evasion on unavoidables.")
br.ui:createCheckbox(section, "Cloak Unavoidables", "Will cloak on unavoidables")
br.ui:checkSectionState(section)
-------------------------
--- INTERRUPT OPTIONS --- -- Define Interrupt Options
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
br.ui:createCheckbox(section, "Kick")
br.ui:createCheckbox(section, "Kidney Shot/Cheap Shot")
br.ui:createCheckbox(section, "Blind")
br.ui:createSpinnerWithout(section, "Interrupt %", 0, 0, 95, 5, "Remaining Cast Percentage to interrupt at.")
br.ui:createCheckbox(section, "Stuns", "Auto stun mobs from whitelist")
br.ui:createSpinnerWithout(section, "Max CP For Stun", 3, 1, 6, 1, " Maximum number of combo points to stun")
br.ui:checkSectionState(section)
----------------------
--- TOGGLE OPTIONS --- -- Degine Toggle Options
----------------------
section = br.ui:createSection(br.ui.window.profile, "Toggle Keys")
br.ui:createDropdownWithout(section, "Rotation Mode", br.dropOptions.Toggle, 4)
br.ui:createDropdownWithout(section, "Cooldown Mode", br.dropOptions.Toggle, 3)
br.ui:createDropdownWithout(section, "Defensive Mode", br.dropOptions.Toggle, 6)
br.ui:createDropdownWithout(section, "Pause Mode", br.dropOptions.Toggle, 6)
br.ui:checkSectionState(section)
----------------------
-------- LISTS -------
----------------------
section = br.ui:createSection(br.ui.window.profile, "Lists")
br.ui:createScrollingEditBoxWithout(section,"Dot Blacklist Units", dotBlacklist, "List of units to blacklist when multidotting", 240, 40)
br.ui:createScrollingEditBoxWithout(section,"Stun Spells", stunSpellList, "List of spells to stun with auto stun function", 240, 50)
-- resetButton = br.ui:createButton(section, "Reset Lists")
-- resetButton:SetEventListener("OnClick", function()
-- local selectedProfile = br.data.settings[br.selectedSpec][br.selectedProfile]
-- selectedProfile["Dot Blacklist UnitsEditBox"] = dotBlacklist
-- selectedProfile["Stun SpellsEditBox"] = stunSpellList
-- br.rotationChanged = true
-- end)
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "Rotation Options",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
---------------
--- Toggles --- -- List toggles here in order to update when pressed
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("Interrupt",0.25)
br.player.ui.mode.aoe = br.data.settings[br.selectedSpec].toggles["Aoe"]
br.player.ui.mode.sd = br.data.settings[br.selectedSpec].toggles["SD"]
br.player.ui.mode.sod = br.data.settings[br.selectedSpec].toggles["SoD"]
br.player.ui.mode.st = br.data.settings[br.selectedSpec].toggles["ST"]
if not UnitAffectingCombat("player") then
if not br.player.talent.secretTechnique then
buttonST:Hide()
else
buttonST:Show()
end
end
--------------
--- Locals ---
--------------
local buff = br.player.buff
local talent = br.player.talent
local trait = br.player.traits
local essence = br.player.essence
-- local runeforge = br.player.runeforge
-- local conduit = br.player.conduit
local cast = br.player.cast
local php = br.player.health
local power, powmax, powgen = br.player.power, br.player.powerMax, br.player.powerRegen
local combo, comboDeficit, comboMax = br.player.power.comboPoints.amount(), br.player.power.comboPoints.deficit(), br.player.power.comboPoints.max()
local energy, energyDeficit, energyRegen = br.player.power.energy.amount(), br.player.power.energy.deficit(), br.player.power.energy.regen()
local cd = br.player.cd
local charges = br.player.charges
local debuff = br.player.debuff
local enemies = br.player.enemies
local gcd = br.player.gcd
local gcdMax = br.player.gcdMax
local has = br.player.has
local inCombat = br.player.inCombat
local level = br.player.level
local mode = br.player.ui.mode
local race = br.player.race
local racial = br.player.getRacial()
local spell = br.player.spell
local units = br.player.units
local use = br.player.use
local stealth = br.player.buff.stealth.exists()
local stealthedRogue = stealth or br.player.buff.vanish.exists() or br.player.buff.subterfuge.remain() > 0.2 or br.player.cast.last.vanish(1)
local stealthedAll = stealth or br.player.buff.vanish.exists() or br.player.buff.subterfuge.remain() > 0.2 or br.player.cast.last.vanish(1) or br.player.buff.shadowmeld.exists() or br.player.buff.shadowDance.exists() or br.player.cast.last.shadowDance(1)
local combatTime = getCombatTime()
local cdUsage = useCDs()
local falling, swimming, flying = getFallTime(), IsSwimming(), IsFlying()
local healPot = getHealthPot()
local moving = isMoving("player") ~= false or br.player.moving
local pullTimer = br.DBM:getPulltimer()
local thp = getHP("target")
local tickTime = 2 / (1 + (GetHaste()/100))
local validTarget = isValidUnit("target")
local inInstance = br.player.instance == "party" or br.player.instance == "scenario" or br.player.instance == "pvp" or br.player.instance == "arena" or br.player.instance == "none"
local inRaid = br.player.instance == "raid" or br.player.instance == "pvp" or br.player.instance == "arena" or br.player.instance == "none"
if leftCombat == nil then leftCombat = GetTime() end
if profileStop == nil then profileStop = false end
enemies.get(20)
enemies.get(20,"player",true)
enemies.get(25,"player", true) -- makes enemies.yards25nc
enemies.get(30)
if timersTable then
wipe(timersTable)
end
local tricksUnit
if isChecked("Auto Tricks") and GetSpellCooldown(spell.tricksOfTheTrade) == 0 and inCombat then
if getOptionValue("Auto Tricks") == 1 and GetUnitIsFriend("player", "focus") and getLineOfSight("player", "focus") then
tricksUnit = "focus"
elseif getOptionValue("Auto Tricks") == 2 then
for i = 1, #br.friend do
local thisUnit = br.friend[i].unit
if UnitGroupRolesAssigned(thisUnit) == "TANK" and not UnitIsDeadOrGhost(thisUnit) and getLineOfSight("player", thisUnit) then
tricksUnit = thisUnit
break
end
end
end
end
local function ttd(unit)
if UnitIsPlayer(unit) then return 999 end
local ttdSec = getTTD(unit)
if getOptionCheck("Enhanced Time to Die") then return ttdSec end
if ttdSec == -1 then return 999 end
return ttdSec
end
local function shallWeDot(unit)
if isChecked("Auto Rupture HP Limit") and ttd(unit) == 999 and not UnitIsPlayer(unit) and not isDummy(unit) then
local hpLimit = 0
if #br.friend == 1 then
if UnitHealth(unit) > UnitHealthMax("player") * 0.40 then
return true
end
return false
end
for i = 1, #br.friend do
local thisUnit = br.friend[i].unit
local thisHP = UnitHealthMax(thisUnit)
local thisRole = UnitGroupRolesAssigned(thisUnit)
if not UnitIsDeadOrGhost(thisUnit) and getDistance(unit, thisUnit) < 40 then
if thisRole == "TANK" then hpLimit = hpLimit + (thisHP * 0.15) end
if (thisRole == "DAMAGER" or thisRole == "NONE") then hpLimit = hpLimit + (thisHP * 0.3) end
end
end
if UnitHealth(unit) > hpLimit then return true end
return false
end
return true
end
local function isTotem(unit)
local eliteTotems = { -- totems we can dot
[125977] = "Reanimate Totem",
[127315] = "Reanimate Totem",
[146731] = "Zombie Dust Totem"
}
local creatureType = UnitCreatureType(unit)
local objectID = GetObjectID(unit)
if creatureType ~= nil and eliteTotems[objectID] == nil then
if creatureType == "Totem" or creatureType == "Tótem" or creatureType == "Totém" or creatureType == "Тотем" or creatureType == "토템" or creatureType == "图腾" or creatureType == "圖騰" then return true end
end
return false
end
local noDotUnits = {}
for i in string.gmatch(getOptionValue("Dot Blacklist Units"), "%d+") do
noDotUnits[tonumber(i)] = true
end
local function noDotCheck(unit)
if isChecked("Dot Blacklist") and (noDotUnits[GetObjectID(unit)] or UnitIsCharmed(unit)) then return true end
if isTotem(unit) then return true end
local unitCreator = UnitCreator(unit)
if unitCreator ~= nil and UnitIsPlayer(unitCreator) ~= nil and UnitIsPlayer(unitCreator) == true then return true end
if GetObjectID(unit) == 137119 and getBuffRemain(unit, 271965) > 0 then return true end
return false
end
local enemyTable30 = { }
local enemyTable10 = { }
local enemyTable5 = { }
local deadlyPoison10 = true
if #enemies.yards30 > 0 then
local highestHP
local lowestHP
for i = 1, #enemies.yards30 do
local thisUnit = enemies.yards30[i]
if (not noDotCheck(thisUnit) or GetUnitIsUnit(thisUnit, "target")) and not UnitIsDeadOrGhost(thisUnit) and (mode.rotation ~= 2 or (mode.rotation == 2 and GetUnitIsUnit(thisUnit, "target"))) then
local enemyUnit = {}
enemyUnit.unit = thisUnit
enemyUnit.ttd = ttd(thisUnit)
enemyUnit.distance = getDistance(thisUnit)
enemyUnit.hpabs = UnitHealth(thisUnit)
enemyUnit.facing = getFacing("player",thisUnit)
tinsert(enemyTable30, enemyUnit)
if highestHP == nil or highestHP < enemyUnit.hpabs then highestHP = enemyUnit.hpabs end
if lowestHP == nil or lowestHP > enemyUnit.hpabs then lowestHP = enemyUnit.hpabs end
if enemyTable30.lowestTTDUnit == nil or enemyTable30.lowestTTD > enemyUnit.ttd then
enemyTable30.lowestTTDUnit = enemyUnit.unit
enemyTable30.lowestTTD = enemyUnit.ttd
end
end
end
if #enemyTable30 > 1 then
for i = 1, #enemyTable30 do
local thisUnit = enemyTable30[i]
local hpNorm = (10-1)/(highestHP-lowestHP)*(thisUnit.hpabs-highestHP)+10 -- normalization of HP value, high is good
if hpNorm ~= hpNorm or tostring(hpNorm) == tostring(0/0) then hpNorm = 0 end -- NaN check
local enemyScore = hpNorm
if thisUnit.ttd > 1.5 then enemyScore = enemyScore + 10 end
if thisUnit.facing then enemyScore = enemyScore + 30 end
if thisUnit.distance <= 5 then enemyScore = enemyScore + 30 end
if GetUnitIsUnit(thisUnit.unit, "target") then enemyScore = enemyScore + 100 end
local raidTarget = GetRaidTargetIndex(thisUnit.unit)
if raidTarget ~= nil then
enemyScore = enemyScore + raidTarget * 3
if raidTarget == 8 then enemyScore = enemyScore + 5 end
end
thisUnit.enemyScore = enemyScore
end
table.sort(enemyTable30, function(x,y)
return x.enemyScore > y.enemyScore
end)
end
for i = 1, #enemyTable30 do
local thisUnit = enemyTable30[i]
local sStormIgnore = {
[120651]=true, -- Explosive
}
if thisUnit.distance <= 10 then
if sStormIgnore[thisUnit.objectID] == nil and not isTotem(thisUnit.unit) then
tinsert(enemyTable10, thisUnit)
end
if thisUnit.distance <= 5 then
tinsert(enemyTable5, thisUnit)
end
end
end
-- if #enemyTable5 > 1 then
-- table.sort(enemyTable5, function(x)
-- if GetUnitIsUnit(x.unit, "target") then
-- return true
-- else
-- return false
-- end
-- end)
-- end
if isChecked("Auto Target") and inCombat and #enemyTable30 > 0 and ((GetUnitExists("target") and UnitIsDeadOrGhost("target") and not GetUnitIsUnit(enemyTable30[1].unit, "target")) or not GetUnitExists("target")) then
TargetUnit(enemyTable30[1].unit)
end
end
--Just nil fixes
if enemyTable30.lowestTTD == nil then enemyTable30.lowestTTD = 999 end
--Variables
local dSEnabled, stEnabled, subterfugeActive, sRogue, darkShadowEnabled, nsEnabled, tfdActive, vEnabled, mosEnabled, sfEnabled, aEnabled, sndCondition
if talent.deeperStratagem then dSEnabled = 1 else dSEnabled = 0 end
if talent.darkShadow then darkShadowEnabled = 1 else darkShadowEnabled = 0 end
if talent.nightstalker then nsEnabled = 1 else nsEnabled = 0 end
if talent.secretTechnique then stEnabled = 1 else stEnabled = 0 end
if talent.vigor then vEnabled = 1 else vEnabled = 0 end
if talent.masterOfShadows then mosEnabled = 1 else mosEnabled = 0 end
if talent.shadowFocus then sfEnabled = 1 else sfEnabled = 0 end
if talent.aEnabled then aEnabled = 1 else aEnabled = 0 end
if talent.subterfuge then subterfugeActive = 1 else subterfugeActive = 0 end
if talent.gloomblade then gloombladeActive = 1 else gloombladeActive = 0 end
if trait.theFirstDance.active then tfdActive = 1 else tfdActive = 0 end
if trait.bladeInTheShadows.active then bitsActive = 1 else bitsActive = 0 end
if stealthedAll == true then sRogue = 1 else sRogue = 0 end
local enemies10 = #enemyTable10
local ruptureRemain = debuff.rupture.remain("target")
local ssThd = 0
if enemies10 >= 4 then ssThd = 1 end
-- # Used to determine whether cooldowns wait for SnD based on targets.
-- variable,name=snd_condition,value=buff.slice_and_dice.up|spell_targets.shuriken_storm>=6
if buff.sliceAndDice.exists() or enemies10 >= 6 then sndCondition = 1 else sndCondition = 0 end
-- # Only change rotation if we have priority_rotation set and multiple targets up.
-- actions+=/variable,name=use_priority_rotation,value=priority_rotation&spell_targets.shuriken_storm>=2
local priorityRotation = false
if mode.aoe == 2 and enemies10 >= 2 then priorityRotation = true end
if isChecked("Ignore Blacklist for SS") then
enemies10 = #enemies.get(10)
end
local targetDistance = getDistance("target")
--------------------
--- Action Lists ---
--------------------
local function actionList_Extra()
if not inCombat then
-- actions.precombat+=/apply_poison
if isChecked("Poison") then
if not moving and getOptionValue("Poison") == 1 and buff.instantPoison.remain() < 300 and not cast.last.instantPoison(1) then
if cast.instantPoison("player") then return true end
end
if not moving and getOptionValue("Poison") == 2 and buff.woundPoison.remain() < 300 and not cast.last.woundPoison(1) then
if cast.woundPoison("player") then return true end
end
if not moving and buff.cripplingPoison.remain() < 300 and not cast.last.cripplingPoison(1) then
if cast.cripplingPoison("player") then return true end
end
end
-- actions.precombat+=/stealth
if isChecked("Auto Stealth") and IsUsableSpell(GetSpellInfo(spell.stealth)) and not cast.last.vanish() and not IsResting() and
(botSpell ~= spell.stealth or (botSpellTime == nil or GetTime() - botSpellTime > 0.1)) then
if getOptionValue("Auto Stealth") == 1 then
if cast.stealth() then return end
end
if #enemies.yards25nc > 0 and getOptionValue("Auto Stealth") == 2 then
if cast.stealth() then return end
end
end
end
--Burn Units
local burnUnits = {
[120651]=true, -- Explosive
[141851]=true -- Infested
}
if GetObjectExists("target") and burnUnits[GetObjectID("target")] ~= nil then
if combo >= 4 then
if cast.eviscerate("target") then return true end
end
end
end
local function actionList_Defensive()
if useDefensive() then
if isChecked("Auto Defensive Unavoidables") then
--Powder Shot (2nd boss freehold)
local bossID = GetObjectID("boss1")
if bossID == 126848 and isCastingSpell(256979, "target") and GetUnitIsUnit("player", UnitTarget("target")) then
if talent.elusiveness then
if cast.feint() then return true end
elseif getOptionValue("Evasion Unavoidables HP Limit") >= php then
if cast.evasion() then return true end
end
end
--Azerite Powder Shot (1st boss freehold)
if bossID == 126832 and isCastingSpell(256106, "boss1") and getFacing("boss1", "player") then
if cast.feint() then return true end
end
--Spit gold (1st boss KR)
if bossID == 135322 and isCastingSpell(265773, "boss1") and GetUnitIsUnit("player", UnitTarget("boss1")) and isChecked("Cloak Unavoidables") then
if cast.cloakOfShadows() then return true end
end
if UnitDebuffID("player",265773) and getDebuffRemain("player",265773) <= 2 then
if cast.feint() then return true end
end
--Static Shock (1st boss Temple)
if (bossID == 133944 or GetObjectID("boss2") == 133944) and (isCastingSpell(263257, "boss1") or isCastingSpell(263257, "boss2")) then
if isChecked("Cloak Unavoidables") then
if cast.cloakOfShadows() then return true end
end
if not buff.cloakOfShadows.exists() then
if cast.feint() then return true end
end
end
--Noxious Breath (2nd boss temple)
if bossID == 133384 and isCastingSpell(263912, "boss1") and (select(5,UnitCastingInfo("boss1"))/1000-GetTime()) < 1.5 then
if cast.feint() then return true end
end
end
if isChecked("Heirloom Neck") and php <= getOptionValue("Heirloom Neck") and not inCombat then
if hasEquiped(122668) then
if GetItemCooldown(122668)==0 then
useItem(122668)
end
end
end
if isChecked("Health Pot / Healthstone") and (use.able.healthstone() or canUseItem(169451)) and php <= getOptionValue("Health Pot / Healthstone")
and inCombat and (hasItem(169451) or has.healthstone()) then
if use.able.healthstone() then
use.healthstone()
elseif canUseItem(156634) then
useItem(156634)
elseif canUseItem(169451) then
useItem(169451)
end
end
if isChecked("Cloak of Shadows") and canDispel("player",spell.cloakOfShadows) and inCombat then
if cast.cloakOfShadows() then return true end
end
if isChecked("Crimson Vial") and php < getOptionValue("Crimson Vial") then
if cast.crimsonVial() then return true end
end
if isChecked("Evasion") and php < getOptionValue("Evasion") and inCombat and not stealth then
if cast.evasion() then return true end
end
if isChecked("Feint") and php <= getOptionValue("Feint") and inCombat and not buff.feint.exists() then
if cast.feint() then return true end
end
end
end
local function actionList_Interrupts()
local stunList = {}
for i in string.gmatch(getOptionValue("Stun Spells"), "%d+") do
stunList[tonumber(i)] = true
end
if useInterrupts() and not stealthedAll then
for i=1, #enemies.yards20 do
local thisUnit = enemies.yards20[i]
local distance = getDistance(thisUnit)
if canInterrupt(thisUnit,getOptionValue("Interrupt %")) then
if isChecked("Kick") and distance < 5 then
if cast.kick(thisUnit) then return end
end
if cd.kick.remain() ~= 0 then
if isChecked("Kidney Shot/Cheap Shot") then
if stealthedAll then
if cast.cheapShot(thisUnit) then return true end
end
if cast.kidneyShot(thisUnit) then return true end
end
end
if isChecked("Blind") and (cd.kick.remain() ~= 0 or distance >= 5) then
if cast.blind(thisUnit) then return end
end
end
if isChecked("Stuns") and distance < 5 and combo > 0 and combo <= getOptionValue("Max CP For Stun") then
local interruptID, castStartTime
if UnitCastingInfo(thisUnit) then
castStartTime = select(4,UnitCastingInfo(thisUnit))
interruptID = select(9,UnitCastingInfo(thisUnit))
elseif UnitChannelInfo(thisUnit) then
castStartTime = select(4,UnitChannelInfo(thisUnit))
interruptID = select(7,GetSpellInfo(UnitChannelInfo(thisUnit)))
end
if interruptID ~=nil and stunList[interruptID] and (GetTime()-(castStartTime/1000)) > 0.1 then
if stealthedAll then
if cast.cheapShot(thisUnit) then return true end
end
if cast.kidneyShot(thisUnit) then return true end
end
end
end
end
end
local function actionList_Opener()
opener = true
end
local function actionList_PreCombat()
-- actions.precombat+=/potion
if isChecked("Precombat") and pullTimer <= 1.5 then
if getOptionValue("Potion") == 1 and use.able.superiorBattlePotionOfAgility() and not buff.superiorBattlePotionOfAgility.exists() then
use.superiorBattlePotionOfAgility()
return true
elseif getOptionValue("Potion") == 2 and use.able.potionOfUnbridledFury() and not buff.potionOfUnbridledFury.exists() then
use.potionOfUnbridledFury()
return true
elseif getOptionValue("Potion") == 3 and use.able.potionOfFocusedResolve() and not buff.potionOfFocusedResolve.exists() then
use.potionOfFocusedResolve()
return true
end
end
-- actions.precombat+=/marked_for_death,precombat_seconds=15
if isChecked("Precombat") and validTarget and pullTimer < 15 and stealth and comboDeficit > 2 and talent.markedForDeath and targetDistance < 25 then
if cast.markedForDeath("target") then return true end
end
-- actions.precombat+=/Slice and Dice, if=precombat_seconds=1
if isChecked("Precombat") and (pullTimer <= 1 or targetDistance < 10) and combo > 0 and buff.sliceAndDice.remain() < 6+(combo*3) then
if cast.sliceAndDice() then return true end
end
-- -- actions.precombat+=/shadowBlades, if=runeforge.mark_of_the_master_assassin.equipped
-- if isChecked("Precombat") and validTarget and cdUsage and targetDistance < 5 then -- and runeforge.markOfTheMasterAssassin.active()
-- if cast.shadowBlades("player") then return true end
-- end
end
local function actionList_CooldownsOGCD()
-- Slice and dice for opener
if enemies10 < 6 and ttd("target") > 6 and combo >= 2 and not buff.sliceAndDice.exists() and combatTime < 6 then
if cast.sliceAndDice("player") then return true end
end
-- # Use Dance off-gcd before the first Shuriken Storm from Tornado comes in.
-- actions.cds=shadow_dance,use_off_gcd=1,if=!buff.shadow_dance.up&buff.shuriken_tornado.up&buff.shuriken_tornado.remains<=3.5
if mode.sd == 1 and cdUsage and not buff.shadowDance.exists() and buff.shurikenTornado.exists() and buff.shurikenTornado.remain() <= 3.5 then
if cast.shadowDance("player") then return true end
end
-- # (Unless already up because we took Shadow Focus) use Symbols off-gcd before the first Shuriken Storm from Tornado comes in.
-- actions.cds+=/symbols_of_death,use_off_gcd=1,if=buff.shuriken_tornado.up&buff.shuriken_tornado.remains<=3.5
if mode.sod == 1 and (buff.shurikenTornado.exists() and buff.shurikenTornado.remain() <= 3.5 or not talent.shurikenTornado) and ttd("target") > getOptionValue("CDs TTD Limit") and combatTime > 1.5 then
if cast.symbolsOfDeath("player") then return true end
end
-- actions.cds+=/shadow_blades,if=variable.snd_condition&combo_points.deficit>=2
if cdUsage and sndCondition and not stealthedAll and comboDeficit >= 2 and isChecked("Shadow Blades") and ttd("target") > getOptionValue("CDs TTD Limit") and combatTime > 1.5 then
if cast.shadowBlades("player") then return true end
end
end
local function actionList_Cooldowns()
---------------------------- SHADOWLANDS
-- actions.cds+=/flagellation,if=variable.snd_condition&!stealthed.mantle"
-- if sndCondition and not buff.masterAssassinsInitiative.exists() then
-- if cast.flagellation("target") then return true end
-- end
-- actions.cds+=/flagellation_cleanse,if=debuff.flagellation.remains<2|debuff.flagellation.stack>=40
--if debuff.flagellation.remain("target") < 2 or debuff.flagellation.stack() >= 40 then
-- if cast.flagellation("target") then return true end
-- end
-- actions.cds+=/vanish,if=(runeforge.mark_of_the_master_assassin.equipped&combo_points.deficit<=3|runeforge.deathly_shadows.equipped&combo_points<1)&buff.symbols_of_death.up&buff.shadow_dance.up&master_assassin_remains=0&buff.deathly_shadows.down
-- if (runeforge.markOfTheMasterAssassin.active and comboDeficit <= 3 or runeforge.deathlyShadows.active and combo < 1) and buff.symbolsOfDeath.exists() and buff.shadowDance.exists() and not buff.masterAssassin.exists() and not buff.deathlyShadows.exists() then
-- if cast.vanish("player") then return true end
-- end
---------------------------- SHADOWLANDS
-- actions.cds+=/call_action_list,name=essences,if=!stealthed.all&variable.snd_condition|essence.breath_of_the_dying.major&time>=2
if isChecked("Essences") and not IsMounted() and not stealthedAll and sndCondition or cast.able.reapingFlames() and combatTime >= 2 then
-- actions.essences+=/blood_of_the_enemy,if=!cooldown.shadow_blades.up&cooldown.symbols_of_death.up|fight_remains<=10
if cast.able.bloodOfTheEnemy() and cd.shadowBlades.exists() and not cd.symbolsOfDeath.exists() and ttd("target") <= 10 then
if cast.bloodOfTheEnemy("player") then return true end
end
-- actions.essences+=/guardian_of_azeroth
if cast.able.guardianOfAzeroth() then
if cast.guardianOfAzeroth("player") then return true end
end
-- actions.essences+=/the_unbound_force,if=buff.reckless_force.up|buff.reckless_force_counter.stack<10
if cast.able.theUnboundForce() and (buff.recklessForce.exists() or buff.recklessForceCounter.stack() < 10)then
if cast.theUnboundForce("target") then return true end
end
-- actions.essences+=/ripple_in_space
if cast.able.rippleInSpace() then
if cast.rippleInSpace() then return true end
end
-- actions.essences+=/worldvein_resonance,if=cooldown.symbols_of_death.remains<5|fight_remains<18
if cast.able.worldveinResonance() and cd.symbolsOfDeath.remain < 5 or ttd("target") <= 18 then
if cast.worldveinResonance("player") then return true end
end
-- actions.essences+=/memory_of_lucid_dreams,if=energy<40&buff.symbols_of_death.up
if cast.able.memoryOfLucidDreams() and energy < 40 and buff.symbolsOfDeath.exists() then
if cast.memoryOfLucidDreams("player") then return true end
end
-- Essence: Reaping Flames
if cast.able.reapingFlames() then
local reapingDamage = buff.reapingFlames.exists("player") and getValue("Reaping DMG") * 5000 * 2 or getValue("Reaping DMG") * 5000
local reapingPercentage = 0
local thisHP = 0
local thisABSHP = 0
local thisABSHPmax = 0
local reapTarget, thisUnit, reap_execute, reap_hold, reap_fallback = false, false, false, false, false
local mob_count = #enemies.yards30
if mob_count > 10 then
mob_count = 10
end
if mob_count == 1 then
if ((br.player.essence.reapingFlames.rank >= 2 and getHP(enemies.yards30[1]) > 80) or getHP(enemies.yards30[1]) <= 20 or getTTD(enemies.yards30[1], 20) > 30) then
reapTarget = enemies.yards30[1]
end
elseif mob_count > 1 then
for i = 1, mob_count do
thisUnit = enemies.yards30[i]
if getTTD(thisUnit) ~= 999 then
thisHP = getHP(thisUnit)
thisABSHP = UnitHealth(thisUnit)
thisABSHPmax = UnitHealthMax(thisUnit)
reapingPercentage = round2(reapingDamage / UnitHealthMax(thisUnit), 2)
if UnitHealth(thisUnit) <= reapingDamage or getTTD(thisUnit) < 2.5 or getTTD(thisUnit, reapingPercentage) < 2 then
reap_execute = thisUnit
break
elseif getTTD(thisUnit, reapingPercentage) < 29 or getTTD(thisUnit, 20) > 30 and (getTTD(thisUnit, reapingPercentage) < 44) then
reap_hold = true
elseif (thisHP > 80 or thisHP <= 20) or getTTD(thisUnit, 20) > 30 then
reap_fallback = thisUnit
end
end
end
end
if reap_execute then
reapTarget = reap_execute
elseif not reap_hold and reap_fallback then
reapTarget = reap_fallback
end
if reapTarget ~= nil and not isExplosive(reapTarget) and getFacing("player",reapTarget) then
if cast.reapingFlames(reapTarget) then
return true
end
end
end
end
-- # Pool for Tornado pre-SoD with ShD ready when not running SF.
-- actions.cds+=/pool_resource,for_next=1,if=!talent.shadow_focus.enabled
if not talent.shadowFocus and cast.able.shurikenTornado() then
if cast.pool.shurikenTornado() then return true end
end
-- # Use Tornado pre SoD when we have the energy whether from pooling without SF or just generally.
-- actions.cds+=/shuriken_tornado,if=energy>=60&variable.snd_condition&cooldown.symbols_of_death.up&cooldown.shadow_dance.charges>=1
if energy >= 60 and sndCondition and not cd.symbolsOfDeath.exists() and charges.shadowDance.frac() >= 1 then
if cast.shurikenTornado("player") then return true end
end
-- actions.cds+=/serrated_bone_spike,cycle_targets=1,if=variable.snd_condition&!dot.serrated_bone_spike_dot.ticking|fight_remains<=5
-- if sndCondition and not debuff.serratedBoneSpike.exists(enemyTable30.lowestTTDUnit) or ttd("target") <= 5 then
-- if cast.serratedBoneSpike(enemyTable30.lowestTTDUnit) then return true end
-- end
-- # Use Symbols on cooldown (after first SnD) unless we are going to pop Tornado and do not have Shadow Focus. Low CP for The Rotten.
-- actions.cds+=/symbols_of_death,if=variable.snd_condition&!cooldown.shadow_blades.up&(talent.enveloping_shadows.enabled|cooldown.shadow_dance.charges>=1)&(!talent.shuriken_tornado.enabled|talent.shadow_focus.enabled|cooldown.shuriken_tornado.remains>2)&(!runeforge.the_rotten.equipped|combo_points<=2)&(!essence.blood_of_the_enemy.major|cooldown.blood_of_the_enemy.remains>2)
if mode.sod == 1 and sndCondition and cd.shadowBlades.exists() and (talent.envelopingShadows or charges.shadowDance.frac() >= 1) and
(not talent.shurikenTornado or talent.shadowFocus or cd.shurikenTornado.remain() > 2) and --and (not runeforge.theRotten.active or combo <= 2)
(not essence.bloodOfTheEnemy.active or cd.bloodOfTheEnemy.remain() > 2) and ttd("target") > getOptionValue("CDs TTD Limit") then
if cast.symbolsOfDeath("player") then return true end
end
-- # If adds are up, snipe the one with lowest TTD. Use when dying faster than CP deficit or not stealthed without any CP.
-- actions.cds+=/marked_for_death,target_if=min:target.time_to_die,if=raid_event.adds.up&(target.time_to_die<combo_points.deficit|!stealthed.all&combo_points.deficit>=cp_max_spend)
if getOptionValue("MfD Target") == 1 then
if #enemyTable30 > 1 and (enemyTable30.lowestTTD < comboDeficit or (not stealthedAll and comboDeficit >= comboMax)) then
if cast.markedForDeath(enemyTable30.lowestTTDUnit) then return true end
end
else
if #enemyTable30 > 1 and (ttd("target") < comboDeficit or (not stealthedAll and comboDeficit >= comboMax)) then
if cast.markedForDeath("target") then return true end
end
end
-- # If no adds will die within the next 30s, use MfD on boss without any CP and no stealth.
-- actions.cds+=/marked_for_death,if=raid_event.adds.in>30-raid_event.adds.duration&combo_points.deficit>=cp_max_spend
if #enemyTable30 == 1 and comboDeficit >= comboMax then
if cast.markedForDeath("target") then return true end
end
---------------------------- SHADOWLANDS
-- actions.cds+=/echoing_reprimand,if=variable.snd_condition&combo_points.deficit>=3&spell_targets.shuriken_storm<=4
-- if sndCondition and comboDeficit >= 3 and enemies10 <= 4 then
-- if cast.echoingReprimand("target") then return true end
-- end
-- -- # With SF, if not already done, use Tornado with SoD up.
-- -- actions.cds+=/shuriken_tornado,if=talent.shadow_focus.enabled&variable.snd_condition&buff.symbols_of_death.up
-- if talent.shadowFocus and sndCondition and buff.symbolsOfDeath.exists() then
-- if cast.shurikenTornado("player") then return true end
-- end
-- -- actions.cds+=/shadow_dance,if=!buff.shadow_dance.up&fight_remains<=8+talent.subterfuge.enabled
-- if mode.sd == 1 and cdUsage and not buff.shadowDance.exists() and ttd("target") <= (8 + subterfugeActive) and ttd("target") > getOptionValue("CDs TTD Limit") then
-- if cast.shadowDance("player") then return true end
-- end
-- -- actions.cds+=/shiv,if=level>=58&dot.rupture.ticking&(!equipped.azsharas_font_of_power|cooldown.vendetta.remains>10) --not buff.masterAssassin.exists() and
-- if (debuff.rupture.exists("target") or not shallWeDot("target")) and (buff.symbolsOfDeath.remain() > 8 or buff.shadowBlades.remain() > 9) and (ttd("target") > 3 or isBoss()) then
-- if cast.shiv("target") then return true end
-- end
-- actions.cds+=/potion,if=buff.bloodlust.react|buff.symbols_of_death.up&(buff.shadow_blades.up|cooldown.shadow_blades.remains<=10)
---------------------------- SHADOWLANDS
if cdUsage and ttd("target") > getOptionValue("CDs TTD Limit") and isChecked("Potion") and (hasBloodLust() or (buff.symbolsOfDeath.exists("target") and (buff.shadowBlades.exists() or cd.shadowBlades.remain() <= 10))) then
if getOptionValue("Potion") == 1 and use.able.superiorBattlePotionOfAgility() and not buff.superiorBattlePotionOfAgility.exists() then
use.superiorBattlePotionOfAgility()
return true
elseif getOptionValue("Potion") == 2 and use.able.potionOfUnbridledFury() and not buff.potionOfUnbridledFury.exists() then
use.potionOfUnbridledFury()
return true
elseif getOptionValue("Potion") == 3 and use.able.potionOfFocusedResolve() and not buff.potionOfFocusedResolve.exists() then
use.potionOfFocusedResolve()
return true
end
end
-- actions.cds+=/blood_fury,if=buff.symbols_of_death.up
-- actions.cds+=/berserking,if=buff.symbols_of_death.up
-- actions.cds+=/fireblood,if=buff.symbols_of_death.up
-- actions.cds+=/ancestral_call,if=buff.symbols_of_death.up
if cdUsage and isChecked("Racial") and buff.symbolsOfDeath.exists() and ttd("target") > getOptionValue("CDs TTD Limit") then
if race == "Orc" or race == "MagharOrc" or race == "DarkIronDwarf" or race == "Troll" then
if cast.racial("player") then return true end
end
end
-- # Specific trinktes
-- Very roughly rule of thumbified maths below: Use for Inkpod crit, otherwise with SoD at 25+ stacks or 15+ with also Blood up.
-- actions.cds+=/use_item,name=ashvanes_razor_coral,if=debuff.razor_coral_debuff.down|debuff.conductive_ink_debuff.up&target.health.pct<32&target.health.pct>=30|!debuff.conductive_ink_debuff.up&(debuff.razor_coral_debuff.stack>=25-10*debuff.blood_of_the_enemy.up|fight_remains<40)&buff.symbols_of_death.remains>8
local BotEBuffActive = 0
if buff.seethingRage.exists() then BotEBuffActive = 1 else BotEBuffActive = 0 end
if isChecked("Trinkets") and not stealthedRogue and not debuff.razorCoral.exists("target") or (debuff.conductiveInk.exists("target") and thp < 32 and thp >= 30) or not debuff.conductiveInk.exists("target") and (debuff.razorCoral.stack() >= 25 - 10 * BotEBuffActive or ttd("target") < 40) and buff.symbolsOfDeath.remain() > 8 or (isBoss() and ttd("target") < 20) then
if hasEquiped(169311, 13) and canUseItem(13) then
useItem(13)
end
if hasEquiped(169311, 14) and canUseItem(14) then
useItem(14)
end
end
-- actions.cds+=/use_items,if=buff.symbols_of_death.up|fight_remains<20
if cdUsage and isChecked("Trinkets") and (buff.symbolsOfDeath.exists() or not isChecked("Symbols of Death")) and ttd("target") > getOptionValue("CDs TTD Limit") or ttd("target") < 20 then
if canUseItem(13) and not (hasEquiped(169311, 13) or hasEquiped(169314, 13) or hasEquiped(159614, 13)) then
useItem(13)
end
if canUseItem(14) and not (hasEquiped(169311, 14) or hasEquiped(169314, 14) or hasEquiped(159614, 13)) then
useItem(14)
end
end
end
local function actionList_Finishers()
-- actions.finish=slice_and_dice,if=spell_targets.shuriken_storm<6&!buff.shadow_dance.up&buff.slice_and_dice.remains<fight_remains&buff.slice_and_dice.remains<(1+combo_points)*1.8
if enemies10 < 6 and not buff.shadowDance.exists() and buff.sliceAndDice.remain() < ttd("target") and buff.sliceAndDice.remain() < (1 + combo)*1.8 then
if cast.sliceAndDice() then return true end
end
-- # Helper Variable for Rupture. Skip during Master Assassin or during Dance with Dark and no Nightstalker.
-- actions.finish+=/variable,name=skip_rupture,value=master_assassin_remains>0|!talent.nightstalker.enabled&talent.dark_shadow.enabled&buff.shadow_dance.up|spell_targets.shuriken_storm>=6
local skipRupture = ((not talent.nightstalker and talent.darkShadow and buff.shadowDance.exists()) or enemies10 >= 6) or false -- buff.masterAssassin.exists() or
-- # Keep up Rupture if it is about to run out.
-- actions.finish+=/rupture,if=!variable.skip_rupture&target.time_to_die-remains>6&refreshable
if not skipRupture and ttd("target") > 6 and debuff.rupture.refresh("target") and shallWeDot("target") then
if cast.rupture("target") then return true end
end
-- actions.finish+=/secret_technique
if talent.secretTechnique then
if cast.secretTechnique("target") then return true end
end
-- # Multidotting targets that will live for the duration of Rupture, refresh during pandemic.
-- actions.finish+=/rupture,cycle_targets=1,if=!variable.skip_rupture&!variable.use_priority_rotation&spell_targets.shuriken_storm>=2&target.time_to_die>=(5+(2*combo_points))&refreshable
local ruptureCount = debuff.rupture.count()
if not skipRupture and not priorityRotation and enemies10 >= 2 and getSpellCD(spell.rupture) == 0 and ruptureCount <= getOptionValue("Multidot Limit") then
for i = 1, #enemyTable5 do
local thisUnit = enemyTable5[i].unit
if ttd(thisUnit) >= (5 + 2 * combo) and debuff.rupture.refresh(thisUnit) and shallWeDot(thisUnit) then
if cast.rupture(thisUnit) then return true end
end
end
end
-- # Refresh Rupture early if it will expire during Symbols. Do that refresh if SoD gets ready in the next 5s.
-- actions.finish+=/rupture,if=!variable.skip_rupture&remains<cooldown.symbols_of_death.remains+10&cooldown.symbols_of_death.remains<=5&target.time_to_die-remains>cooldown.symbols_of_death.remains+5
if not skipRupture and ruptureRemain < cd.symbolsOfDeath.remain() + 10 and cd.symbolsOfDeath.remain() <= 5 and shallWeDot("target") and ttd("target") - ruptureRemain > cd.symbolsOfDeath.remain()+5 then
if cast.rupture(thisUnit) then return true end
end
-- actions.finish+=/eviscerate
if cast.eviscerate("target") then return true end
end
local function actionList_StealthCD()
-- # Helper Variable
-- actions.stealth_cds=variable,name=shd_threshold,value=cooldown.shadow_dance.charges_fractional>=1.75
local shdThreshold = false
if charges.shadowDance.frac() >= 1.75 then shdThreshold = true else shdThreshold = false end
-- # Vanish if we are capping on Dance charges. Early before first dance if we have no Nightstalker but Dark Shadow in order to get Rupture up (no Master Assassin).
-- actions.stealth_cds+=/vanish,if=(!variable.shd_threshold|!talent.nightstalker.enabled&talent.dark_shadow.enabled)&combo_points.deficit>1&!runeforge.mark_of_the_master_assassin.equipped
if cdUsage and (not shdThreshold or not talent.nightstalker and talent.darkShadow) and comboDeficit > 1 and targetDistance < 5 and isChecked("Vanish") and ttd("target") > getOptionValue("CDs TTD Limit") then -- and not runeforge.markOfTheMasterAssassin.active
if cast.vanish("player") then return true end
end
---------------------------- SHADOWLANDS
-- actions.stealth_cds+=/sepsis
-- if cast.able.sepsis() then
-- if cast.sepsis("target") then return true end
-- end
---------------------------- SHADOWLANDS
-- # Pool for Shadowmeld + Shadowstrike unless we are about to cap on Dance charges. Only when Find Weakness is about to run out.
-- actions.stealth_cds+=/pool_resource,for_next=1,extra_amount=40
-- actions.stealth_cds+=/shadowmeld,if=energy>=40&energy.deficit>=10&!variable.shd_threshold&combo_points.deficit>1&debuff.find_weakness.remains<1
if cdUsage and isChecked("Racial") and race == "NightElf" and not cast.last.vanish() and not buff.vanish.exists() then
if (cast.pool.racial() or cast.able.racial()) and energy >= 40 and energyDeficit >= 10 and not shdThreshold
and comboDeficit > 1 and debuff.findWeakness.remain(units.dyn5) < 1 then
if cast.pool.racial() then return true end
if cast.able.racial() then
if cast.racial() then return true end
end
end
end
-- # CP requirement: Dance at low CP by default.
-- actions.stealth_cds+=/variable,name=shd_combo_points,value=combo_points.deficit>=4
-- # CP requirement: Dance only before finishers if we have priority rotation.
-- actions.stealth_cds+=/variable,name=shd_combo_points,value=combo_points.deficit<=1,if=variable.use_priority_rotation
local shdComboPoints
if comboDeficit >= 4 or (comboDeficit <= 1 and priorityRotation) then shdComboPoints = 1 else shdComboPoints = 0 end
-- # Dance during Symbols or above threshold.
-- actions.stealth_cds+=/shadow_dance,if=variable.shd_combo_points&(variable.shd_threshold|buff.symbols_of_death.remains>=1.2|spell_targets.shuriken_storm>=4&cooldown.symbols_of_death.remains>10)
if mode.sd == 1 and ttd("target") > 3 and cdUsage and (isChecked("Save SD Charges for CDs") and charges.shadowDance.frac() >= (getOptionValue("Save SD Charges for CDs") + 1)) or combatTime < 15 or not isChecked("Save SD Charges for CDs")
and shdComboPoints and (shdComboPoints or buff.symbolsOfDeath.remain() >= 1.2 or enemies10 >= 4 and cd.symbolsOfDeath.remain() > 10) then
if cast.shadowDance("player") then return true end
end
-- Burn remaining Dances before the fight ends if SoD won't be ready in time.
-- actions.stealth_cds+=/shadow_dance,if=variable.shd_combo_points&fight_remains<cooldown.symbols_of_death.remains
if mode.sd == 1 and cdUsage and shdComboPoints and ttd("target") < cd.symbolsOfDeath.remain() then
if cast.shadowDance("player") then return true end
end
end
local function actionList_Stealthed()
-- # If Stealth/vanish are up, use Shadowstrike to benefit from the passive bonus and Find Weakness, even if we are at max CP (from the precombat MfD).
-- actions.stealthed=shadowstrike,if=(buff.stealth.up|buff.vanish.up)
if (stealth or buff.vanish.exists() or buff.shadowmeld.exists()) and targetDistance < 5 then
if cast.shadowstrike("target") then return true end
end
-- # Finish at 3+ CP without DS / 4+ with DS with Shuriken Tornado buff up to avoid some CP waste situations.
-- actions.stealthed+=/call_action_list,name=finish,if=buff.shuriken_tornado.up&combo_points.deficit<=2
-- # Also safe to finish at 4+ CP with exactly 4 targets. (Same as outside stealth.)
-- actions.stealthed+=/call_action_list,name=finish,if=spell_targets.shuriken_storm=4&combo_points>=4
-- # Finish at 4+ CP without DS, 5+ with DS, and 6 with DS after Vanish
-- actions.stealthed+=/call_action_list,name=finish,if=combo_points.deficit<=1-(talent.deeper_stratagem.enabled&buff.vanish.up)
local finishThd = 0
if dSEnabled and (buff.vanish.exists() or cast.last.vanish(1)) then finishThd = 1 else finishThd = 0 end
if (buff.shurikenTornado.exists() and comboDeficit <= 2) or (enemies10 == 4 and combo >= 4) or (comboDeficit <= (1 - finishThd)) then
if actionList_Finishers() then return true end
end
-- # Up to 3 targets keep up Find Weakness by cycling Shadowstrike.
-- cycle_targets=1,if=debuff.find_weakness.remains<1&spell_targets.shuriken_storm<=3&target.time_to_die-remains>6
-- actions.stealthed+=/shadowstrike,cycle_targets=1,if=debuff.find_weakness.remains<1&spell_targets.shuriken_storm<=3&target.time_to_die-remains>6
if enemies10 <= 3 then
for i = 1, #enemyTable5 do
local thisUnit = enemyTable5[i].unit
if debuff.findWeakness.remain(thisUnit) < 1 and ttd(thisUnit) > 6 then
if cast.shadowstrike(thisUnit) then return true end
end
end
end
-- # Without Deeper Stratagem and 3 Ranks of Blade in the Shadows it is worth using Shadowstrike on 3 targets.
-- actions.stealthed+=/shadowstrike,if=!talent.deeper_stratagem.enabled&azerite.blade_in_the_shadows.rank=3&spell_targets.shuriken_storm=3
if not talent.deeperStratagem and trait.bladeInTheShadows.rank == 3 and enemies10 == 3 and targetDistance < 5 then
if cast.shadowstrike("target") then return true end
end
-- # For priority rotation, use Shadowstrike over Storm 1) with WM against up to 4 targets, 2) if FW is running off (on any amount of targets), or 3) to maximize SoD extension with Inevitability on 3 targets (4 with BitS).
-- actions.stealthed+=/shadowstrike,if=variable.use_priority_rotation&(debuff.find_weakness.remains<1|talent.weaponmaster.enabled&spell_targets.shuriken_storm<=4|azerite.inevitability.enabled&buff.symbols_of_death.up&spell_targets.shuriken_storm<=3+azerite.blade_in_the_shadows.enabled)
if priorityRotation and (debuff.findWeakness.remain("target")<1 or talent.weaponmaster and enemies10 <= 4 or triat.inevitability.active and buff.symbolsOfDeath.exists() and enemies10 <= 3+bitsActive) and targetDistance < 5 then
if cast.shadowstrike("target") then return true end
end
-- actions.stealthed+=/shuriken_storm,if=spell_targets>=3+(buff.premeditation.up|buff.the_rotten.up|runeforge.akaaris_soul_fragment.equipped&conduit.deeper_daggers.rank>=7)
local stealthedsStorm = 0
if buff.premeditation.exists() then stealthedsStorm = 1 else stealthedsStorm = 0 end -- or buff.theRotten.exists() or runeforge.akaarisSoulFragment.active and conduit.deeperDaggers.rank >= 7
if enemies10 >= 3 + stealthedsStorm then
if cast.shurikenStorm("player") then return true end
end
-- # Shadowstrike to refresh Find Weakness and to ensure we can carry over a full FW into the next SoD if possible.
-- actions.stealthed+=/shadowstrike,if=debuff.find_weakness.remains<=1|cooldown.symbols_of_death.remains<18&debuff.find_weakness.remains<cooldown.symbols_of_death.remains
if debuff.findWeakness.remain("target") <= 1 or cd.symbolsOfDeath.remain() < 1 and debuff.findWeakness.remain("target") < cd.symbolsOfDeath.remain() then
if cast.shadowstrike("target") then return true end
end
-- gloomblade
if cast.able.gloomblade() and talent.gloomblade then
if cast.gloomblade("target") then return end
end
---------------------------- SHADOWLANDS
-- -- actions.stealthed+=/gloomblade,if=!runeforge.akaaris_soul_fragment.equipped&buff.perforated_veins.stack>=3&conduit.perforated_veins.rank>=13-(9*conduit.deeper_dagger.enabled+conduit.deeper_dagger.rank)
-- if not runeforge.akaarisSoulFragment.active() and buff.perforatedVeins.stack() >= 3 and conduit.perforatedVeins.rank >= 13 - (9 * conduit.deeperDaggers + conduit.deeperDaggers.rank) then
-- if cast.gloomblade("target") then return true end
-- end
-- -- actions.stealthed+=/gloomblade,if=runeforge.akaaris_soul_fragment.equipped&buff.perforated_veins.stack>=3&(conduit.perforated_veins.rank+conduit.deeper_dagger.rank)>=16
-- if runeforge.akaarisSoulFragment.active() and buff.perforatedVeins.stack() >= 3 and (conduit.perforatedVeins.rank + conduit.deeperDaggers.rank) >= 16 then
-- if cast.gloomblade("target") then return true end
-- end
-- -- # Use Gloomblade over Shadowstrike and Storm with 2+ Perforate at 2 or less targets.
-- -- actions.stealthed+=/gloomblade,if=azerite.perforate.rank>=2&spell_targets.shuriken_storm<=2&position_back
-- if trait.perforate.rank >= 2 and enemies10 <= 2 then
-- for i = 1, #enemyTable5 do
-- local thisUnit = enemyTable5[i].unit
-- if not getFacing(thisUnit,"player") then
-- if cast.gloomblade(thisUnit) then return true end
-- end
-- end
-- end
---------------------------- SHADOWLANDS
-- actions.stealthed+=/shadowstrike
if targetDistance < 5 then
if cast.shadowstrike("target") then return true end
end
end
--Builders
local function actionList_Builders()
-- actions.build=shuriken_storm,if=spell_targets>=2+(talent.gloomblade.enabled&azerite.perforate.rank>=2&position_back)
local buildersStorm = 0
if talent.gloomblade and trait.perforate.rank >= 2 then buildersStorm = 1 else buildersStorm = 0 end
if enemies10 >= 2 + buildersStorm then
for i = 1, #enemyTable10 do
thisUnit = enemyTable10[i].unit
if not getFacing(thisUnit,"player") then
if cast.shurikenStorm("player") then return true end
end
end
end
-- actions.build+=/serrated_bone_spike,if=cooldown.serrated_bone_spike.charges_fractional>=2.75
-- if charges.serratedBoneSpike.frac() >= 2.75 then
-- if cast.serratedBoneSpike(enemyTable30.lowestTTDUnit) then return true end
-- end
-- actions.build+=/gloomblade
if talent.gloomblade then
if cast.gloomblade("target") then return true end
end
-- Sinister Strike
if level < 14 then
if cast.sinisterStrike("target") then return true end
end
-- actions.build+=/backstab
if cast.backstab("target") then return end
-- Use Shuriken Toss if we can't reach the target
if isChecked("Shuriken Toss out of range") and not stealthedRogue and #enemyTable5 == 0 and energy >= getOptionValue("Shuriken Toss out of range") and inCombat then
if cast.shurikenToss() then return true end
end
end
-----------------
--- Rotations ---
-----------------
-- Pause
if IsMounted() or IsFlying() or pause() or mode.rotation==3 then
return true
else
---------------------------------
--- Out Of Combat - Rotations ---
---------------------------------
if actionList_Extra() then return true end
if not inCombat and GetObjectExists("target") and not UnitIsDeadOrGhost("target") and UnitCanAttack("target", "player") then
if actionList_PreCombat() then return true end
end -- End Out of Combat Rotation
if actionList_Opener() then return true end
-----------------------------
--- In Combat - Rotations ---
-----------------------------
if (inCombat or (not isChecked("Disable Auto Combat") and (cast.last.vanish(1) or (targetDistance < 5)))) and opener == true then --validTarget and
if cast.last.vanish(1) then StopAttack() end
if actionList_Defensive() then return true end
if actionList_Interrupts() then return true end
--pre mfd
if stealth and validTarget and comboDeficit > 2 and talent.markedForDeath and targetDistance < 10 then
if cast.markedForDeath("target") then
combo = comboMax
comboDeficit = 0
end
end
--tricks
if tricksUnit ~= nil and validTarget and targetDistance < 5 then
cast.tricksOfTheTrade(tricksUnit)
end
-- # Restealth if possible (no vulnerable enemies in combat)
-- actions=stealth
if IsUsableSpell(GetSpellInfo(spell.stealth)) and not IsStealthed() and not inCombat and not cast.last.vanish() then
cast.stealth("player")
end
-- # Run fully switches to the Stealthed Rotation (by doing so, it forces pooling if nothing is available).
-- actions+=/run_action_list,name=stealthed,if=stealthed.all
if stealthedAll then
if actionList_Stealthed() then return true end
end
--start aa
if not stealthedRogue and validTarget and targetDistance < 5 and not IsCurrentSpell(6603) then
StartAttack("target")
end
-- Off GCD Cooldowns
if ttd("target") > getOptionValue("CDs TTD Limit") and validTarget and targetDistance < 5 then
if actionList_CooldownsOGCD() then return true end
end
if gcd < getLatency() and validTarget and combatTime > 1.5 then
-- # Check CDs at first
-- actions+=/call_action_list,name=cds
if validTarget and targetDistance < 5 then
if actionList_Cooldowns() then return true end
end
-- # Apply Slice and Dice at 2+ CP during the first 10 seconds, after that 4+ CP if it expires within the next GCD or is not up
-- actions+=/slice_and_dice, if=spell_targets.shuriken_storm<6&fight_remains>6&buff.slice_and_dice.remains<gcd.max&combo_points>=4-(time<10)*2
local cTime = 0
if combatTime < 10 then
cTime = 1
end
if enemies10 < 6 and ttd("target") > 6 and buff.sliceAndDice.remain() < gcdMax and combo >= 4-(cTime*2) and buff.sliceAndDice.remain() < 6+(combo*3) then
if cast.sliceAndDice("player") then return true end
end
-- # Priority Rotation? Let's give a crap about energy for the stealth CDs (builder still respect it). Yup, it can be that simple.
-- actions+=/call_action_list,name=stealth_cds,if=variable.use_priority_rotation
if priorityRotation and validTarget and not stealthedAll and targetDistance < 5 then
--print("Valid target: " .. (validTarget and 'true' or 'false'))
if actionList_StealthCD() then return true end
end
-- # Used to define when to use stealth CDs or builders
-- actions+=/variable,name=stealth_threshold,value=25+talent.vigor.enabled*20+talent.master_of_shadows.enabled*20+talent.shadow_focus.enabled*25+talent.alacrity.enabled*20+25*(spell_targets.shuriken_storm>=4)
local stealthThd = 25 + vEnabled * 20 + mosEnabled * 20 + sfEnabled * 25 + aEnabled * 20 + 25 * ssThd
-- # Consider using a Stealth CD when reaching the energy threshold
-- actions+=/call_action_list,name=stealth_cds,if=energy.deficit<=variable.stealth_threshold
if energyDeficit <= stealthThd and validTarget and not stealthedAll and targetDistance < 5 then
if actionList_StealthCD() then return true end
end
---------------------------- SHADOWLANDS
-- actions+=/call_action_list,name=finish,if=runeforge.deathly_shadows.equipped&dot.sepsis.ticking&dot.sepsis.remains<=2&combo_points>=2
-- if runeforge.deadlyShadows.active and debuff.sepsis.exists("target") and debuff.sepsis.remain("target") <= 2 and combo >= 2 then
-- if actionList_Finishers() then return true end
-- end
-- actions+=/call_action_list,name=finish,if=cooldown.symbols_of_death.remains<=2&combo_points>=2&runeforge.the_rotten.equipped
-- if cd.symbolsOfDeath.remain() <= 2 and combo >= 2 and runeforge.theRotten.active then
-- if actionList_Finishers() then return true end
-- end
-- actions+=/call_action_list,name=finish,if=combo_points=animacharged_cp
-- if combo == animachargedCP then
-- if actionList_Finishers() then return true end
-- end
---------------------------- SHADOWLANDS
-- # Finish at 4+ without DS, 5+ with DS (outside stealth)
-- actions+=/call_action_list,name=finish,if=combo_points.deficit<=1|fight_remains<=1&combo_points>=3
if comboDeficit <= 1 or (ttd("target") <= 1 and combo >= 3) then
if actionList_Finishers() then return true end
end
-- # With DS also finish at 4+ against exactly 4 targets (outside stealth)
-- actions+=/call_action_list,name=finish,if=spell_targets.shuriken_storm=4&combo_points>=4
if enemies10 == 4 and combo >= 4 then
if actionList_Finishers() then return true end
end
-- # Use a builder when reaching the energy threshold
-- actions+=/call_action_list,name=build,if=energy.deficit<=variable.stealth_threshold
if energyDeficit <= stealthThd then
if actionList_Builders() then return true end
end
-- # Lowest priority in all of the APL because it causes a GCD
-- actions+=/arcane_torrent,if=energy.deficit>=15+energy.regen
-- actions+=/arcane_pulse
-- actions+=/lights_judgment
-- actions+=/bag_of_tricks
if cdUsage and isChecked("Racial") and targetDistance < 5 then
if race == "BloodElf" and energyDeficit >= (15 + energyRegen) then
if cast.racial("player") then return true end
elseif race == "Nightborne" then
if cast.racial("player") then return true end
elseif race == "LightforgedDraenei" then
if cast.racial("target","ground") then return true end
end
end
end
end -- End In Combat Rotation
end -- Pause
end -- End runRotation
local id = 261 --Change to the spec id profile is for.
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
}) | gpl-3.0 |
nontster/lazybee | src/main/java/th/co/ais/enterprisecloud/domain/InterfaceTypeEnums.java | 101 | package th.co.ais.enterprisecloud.domain;
public enum InterfaceTypeEnums {
UPLINK, INTERNAL
}
| gpl-3.0 |
randi2/randi2 | src/test/java/de/randi2/simulation/unit/distribution/ConcreteDistributionTest.java | 2377 | package de.randi2.simulation.unit.distribution;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import de.randi2.simulation.distribution.ConcreteDistribution;
import de.randi2.utility.Pair;
public class ConcreteDistributionTest {
private int runsPerEntry = 1000;
private double limit = 0.05;
private void testConcreteDistribution(ConcreteDistribution<Integer> cd){
int all = 0;
for(int i : cd.getRatio()){
all+=i;
}
int runs = runsPerEntry*all;
int[] values = new int[cd.getElements().size()];
for(int i =0; i<runs;i++){
values[cd.getNextValue()]++;
}
for(int i = 0; i< values.length;i++){
double mean = (1.0 * values[i]) / runs;
double realMean = (1.0/all)*cd.getRatio()[i];
double limitL = realMean-limit;
double limitH = realMean+limit;
assertTrue("error: " + mean +" > " + limitL,(mean)>limitL);
assertTrue("error: " + mean +" < " +limitH,(mean)<limitH);
}
}
@SuppressWarnings("unchecked")
@Test
public void test1000Times(){
for(int i=0; i<1000;i++){
testConcreteDistribution(new ConcreteDistribution<Integer>(Arrays.asList(0,1,2,3), 2,5,2,1));
testConcreteDistribution(new ConcreteDistribution<Integer>(Arrays.asList(0,1),2,1));
testConcreteDistribution(new ConcreteDistribution<Integer>(Arrays.asList(0,1),1,2));
testConcreteDistribution(new ConcreteDistribution<Integer>(Arrays.asList(0,1),1,3));
testConcreteDistribution(new ConcreteDistribution<Integer>(Arrays.asList(0,1,2,3), 5,5,2,1));
testConcreteDistribution(new ConcreteDistribution<Integer>(Pair.of(0, 5),Pair.of(1, 5),Pair.of(2, 2),Pair.of(3, 1)));
}
}
@Test
public void testSeed(){
List<Integer> results = new ArrayList<Integer>();
ConcreteDistribution<Integer> cd = new ConcreteDistribution<Integer>(100, Arrays.asList(0,1,2,3), 2,5,2,1);
for(int i=0;i<1000;i++){
results.add(cd.getNextValue());
}
List<ConcreteDistribution<Integer>> cds = new ArrayList<ConcreteDistribution<Integer>>();
for(int i=0;i<100;i++){
cds.add(new ConcreteDistribution<Integer>(100, Arrays.asList(0,1,2,3), 2,5,2,1));
}
for(Integer result : results){
for(ConcreteDistribution<Integer> acd : cds){
assertEquals(result, acd.getNextValue());
}
}
}
}
| gpl-3.0 |
TobiasDanzeglocke/ToDoList-Maker | src/ToDoList-Maker/ToDoList-Maker/Persistence/PersistenceUnit.cs | 3370 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ToDoList_Maker.Model;
using ToDoList_Maker.Persistence.Validation;
namespace ToDoList_Maker.Persistence {
public abstract class PersistenceUnit : IPersistenceUnit {
#region Constructor + HelperMethods
protected readonly string DbPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ToDoList-Maker\\src\\db\\";
// protected readonly string DbPath = @"F:\Users\Tobit\github\ToDoList-Maker\src\db\";
protected PersistenceUnit() {
this.Init();
}
/// <summary>
/// Initialisation of the PersistenceUnit
/// Should Check whether database exists already, if not call CreateDatabase
/// </summary>
protected abstract void Init();
/// <summary>
/// Creates Database on filesystem and executes all ddl-statements
/// </summary>
protected abstract void CreateDatabase();
/// <summary>
/// Checks if omitted file path exists on the filesystem
/// true : file exists on filesystem
/// false : doesnt exist on filesystem
/// </summary>
/// <param name="filePath">String representing a file path</param>
/// <returns name="DoesFileExist">Boolean indicating if filePath corresponds to anything on the filesystem</returns>
protected bool Exists(string filePath)
{
return System.IO.File.Exists(filePath);
}
/// <summary>
/// Checks if <paramref name="toDoList"/> is valid or not
/// true : file exists on filesystem
/// false : doesnt exist on filesystem
/// </summary>
/// <param name="toDoList">ToDoList which should be validated</param>
/// <param name="context"></param>
/// <returns>Boolean describing if <paramref name="toDoList"/> is valid or not</returns>
protected bool Validate(ToDoList toDoList, ValidationContext context)
{
IValidator<ToDoList> validator = new ToDoListValidator();
return validator.Validate(toDoList, context);
}
/// <summary>
/// Checks if <paramref name="toDo"/> is valid or not
/// true : file exists on filesystem
/// false : doesnt exist on filesystem
/// </summary>
/// <param name="toDo">ToDo which should be validated</param>
/// <param name="context"></param>
/// <returns>Boolean describing if <paramref name="toDo"/> is valid or not</returns>
protected bool Validate(ToDo toDo, ValidationContext context)
{
IValidator<ToDo> validator = new ToDoValidator();
return validator.Validate(toDo, context);
}
#endregion
#region IPersistenceUnit
public abstract List<ToDoList> ReadToDoLists();
public abstract void Create(ref ToDoList toDoList);
public abstract void Update(ToDoList toDoList);
public abstract void Delete(ToDoList toDoList);
public abstract List<ToDo> ReadToDosFrom(ToDoList toDoList);
public abstract void Create(ref ToDo toDo);
public abstract void Update(ToDo toDo);
public abstract void Delete(ToDo toDo);
#endregion
}
}
| gpl-3.0 |
Fire-Proof/LoLVRSpectate | LoLVRSpectate/memorpy/Address.py | 3444 | # Author: Nicolas VERDIER
# This file is part of memorpy.
#
# memorpy 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.
#
# memorpy 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 memorpy. If not, see <http://www.gnu.org/licenses/>.
from LoLVRSpectate.memorpy import utils
class AddressException(Exception):
pass
class Address(object):
""" this class is used to have better representation of memory addresses """
def __init__(self, value, process, default_type = 'uint'):
self.value = int(value)
self.process = process
self.default_type = default_type
self.symbolic_name = None
def read(self, type = None, maxlen = None):
if maxlen is None:
try:
int(type)
maxlen = int(type)
type = None
except:
pass
if not type:
type = self.default_type
if not maxlen:
return self.process.read(self.value, _type=type)
else:
return self.process.read(self.value, _type=type, maxlen=maxlen)
def write(self, data, type = None):
if not type:
type = self.default_type
return self.process.write(self.value, data, type=type)
def symbol(self):
return self.process.get_symbolic_name(self.value)
def get_instruction(self):
return self.process.get_instruction(self.value)
def dump(self, ftype = 'bytes', size = 512, before = 32):
buf = self.process.read_bytes(self.value - before, size)
print(utils.hex_dump(buf, self.value - before, ftype=ftype))
def __nonzero__(self):
return self.value is not None and self.value != 0
def __add__(self, other):
return Address(self.value + int(other), self.process, self.default_type)
def __sub__(self, other):
return Address(self.value - int(other), self.process, self.default_type)
def __repr__(self):
if not self.symbolic_name:
self.symbolic_name = self.symbol()
return str('<Addr: %s' % self.symbolic_name + '>')
def __str__(self):
if not self.symbolic_name:
self.symbolic_name = self.symbol()
return str('<Addr: %s' % self.symbolic_name + ' : "%s" (%s)>' % (str(self.read()).encode('string_escape'), self.default_type))
def __int__(self):
return int(self.value)
def __hex__(self):
return hex(self.value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = int(value)
def __lt__(self, other):
return self.value < int(other)
def __le__(self, other):
return self.value <= int(other)
def __eq__(self, other):
return self.value == int(other)
def __ne__(self, other):
return self.value != int(other)
def __gt__(self, other):
return self.value > int(other)
def __ge__(self, other):
return self.value >= int(other)
| gpl-3.0 |
joancipria/Swallow | js/dom-drag.js | 4235 | /*
This file is part of Swallow.
Swallow 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.
Swallow 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 Swallow. If not, see <http://www.gnu.org/licenses/>.
*/
var Drag = {
obj : null,
init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
{
o.onmousedown = Drag.start;
o.hmode = bSwapHorzRef ? false : true ;
o.vmode = bSwapVertRef ? false : true ;
o.root = oRoot && oRoot != null ? oRoot : o ;
if (o.hmode && isNaN(parseInt(o.root.style.left ))) o.root.style.left = "0px";
if (o.vmode && isNaN(parseInt(o.root.style.top ))) o.root.style.top = "0px";
if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right = "0px";
if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";
o.minX = typeof minX != 'undefined' ? minX : null;
o.minY = typeof minY != 'undefined' ? minY : null;
o.maxX = typeof maxX != 'undefined' ? maxX : null;
o.maxY = typeof maxY != 'undefined' ? maxY : null;
o.xMapper = fXMapper ? fXMapper : null;
o.yMapper = fYMapper ? fYMapper : null;
o.root.onDragStart = new Function();
o.root.onDragEnd = new Function();
o.root.onDrag = new Function();
},
start : function(e)
{
var o = Drag.obj = this;
e = Drag.fixE(e);
var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom);
var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
o.root.onDragStart(x, y);
o.lastMouseX = e.clientX;
o.lastMouseY = e.clientY;
if (o.hmode) {
if (o.minX != null) o.minMouseX = e.clientX - x + o.minX;
if (o.maxX != null) o.maxMouseX = o.minMouseX + o.maxX - o.minX;
} else {
if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
}
if (o.vmode) {
if (o.minY != null) o.minMouseY = e.clientY - y + o.minY;
if (o.maxY != null) o.maxMouseY = o.minMouseY + o.maxY - o.minY;
} else {
if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
}
document.onmousemove = Drag.drag;
document.onmouseup = Drag.end;
return false;
},
drag : function(e)
{
e = Drag.fixE(e);
var o = Drag.obj;
var ey = e.clientY;
var ex = e.clientX;
var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom);
var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
var nx, ny;
if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);
nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));
if (o.xMapper) nx = o.xMapper(y)
else if (o.yMapper) ny = o.yMapper(x)
Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
Drag.obj.lastMouseX = ex;
Drag.obj.lastMouseY = ey;
Drag.obj.root.onDrag(nx, ny);
return false;
},
end : function()
{
document.onmousemove = null;
document.onmouseup = null;
Drag.obj.root.onDragEnd( parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
Drag.obj = null;
},
fixE : function(e)
{
if (typeof e == 'undefined') e = window.event;
if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
return e;
}
}; | gpl-3.0 |
mediathekview/MediathekView | src/main/java/mediathek/tool/cellrenderer/CellRendererPset.java | 2413 | package mediathek.tool.cellrenderer;
import mediathek.config.Icons;
import mediathek.daten.DatenPset;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
@SuppressWarnings("serial")
public class CellRendererPset extends DefaultTableCellRenderer {
private static final ImageIcon ja_16 = Icons.ICON_TABELLE_EIN;
private static final ImageIcon nein_12 = Icons.ICON_TABELLE_AUS;
private static final Logger logger = LogManager.getLogger();
public CellRendererPset() {
}
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
setBackground(null);
setForeground(null);
setFont(null);
setIcon(null);
setHorizontalAlignment(SwingConstants.LEADING);
super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
try {
int r = table.convertRowIndexToModel(row);
int c = table.convertColumnIndexToModel(column);
DatenPset datenPset = new DatenPset();
for (int i = 0; i < DatenPset.MAX_ELEM; ++i) {
datenPset.arr[i] = table.getModel().getValueAt(r, i).toString();
}
if (c == DatenPset.PROGRAMMSET_NAME) {
setForeground(datenPset.getFarbe());
}
if (c == DatenPset.PROGRAMMSET_IST_ABSPIELEN) {
setHorizontalAlignment(SwingConstants.CENTER);
setText(""); // nur das Icon anzeigen
if (datenPset.istAbspielen()) {
setIcon(ja_16);
} else {
setIcon(nein_12);
}
}
if (c == DatenPset.PROGRAMMSET_IST_SPEICHERN) {
setHorizontalAlignment(SwingConstants.CENTER);
setText(""); // nur das Icon anzeigen
if (datenPset.istSpeichern()) {
setIcon(ja_16);
} else {
setIcon(nein_12);
}
}
} catch (Exception ex) {
logger.error("getTableCellRendererComponent", ex);
}
return this;
}
}
| gpl-3.0 |
Hamlabs/phpMyAPRS | examples/comm.php | 415 | <?php
echo "boot...";
require_once('classes/aprsBootstrap.class.php');
aprsBootstrap::boot('config.ini');
echo "done.\n";
echo "APRS-IS...";
// Set up APRS-IS connection
$aprs = new aprsIsConnection();
echo "done.";
echo "fork tx...\n";
$aprs->forkTransmitSpooler();
echo "fork beacon...\n";
$aprs->forkBeaconSpooler();
echo "rx...\n";
while($rx = $aprs->rx()) {
echo ".";
//echo "RX: ";
//var_dump($rx);
}
| gpl-3.0 |
Better-Aether/Better-Aether | src/main/java/com/gildedgames/aether/client/ui/minecraft/viewing/MinecraftInputProvider.java | 3276 | package com.gildedgames.aether.client.ui.minecraft.viewing;
import com.gildedgames.aether.client.ui.data.rect.Rect;
import com.gildedgames.aether.client.ui.data.rect.RectHolder;
import com.gildedgames.aether.client.ui.input.InputProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
public class MinecraftInputProvider implements InputProvider
{
protected Minecraft mc;
protected float screenWidth, screenHeight, scaleFactor, xOffset, yOffset;
protected ScaledResolution resolution;
public MinecraftInputProvider(Minecraft mc)
{
this.mc = mc;
this.refreshResolution();
}
public void setScreen(float screenWidth, float screenHeight)
{
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
}
public void setScaleFactor(float scaleFactor)
{
this.scaleFactor = scaleFactor;
}
@Override
public void refreshResolution()
{
this.resolution = new ScaledResolution(this.mc);
}
@Override
public float getScreenWidth()
{
this.refreshResolution();
return this.resolution.getScaledWidth();
}
@Override
public float getScreenHeight()
{
this.refreshResolution();
return this.resolution.getScaledHeight();
}
@Override
public float getMouseX()
{
return (Mouse.getX() * this.getScreenWidth() / this.mc.displayWidth) - this.xOffset;
}
@Override
public float getMouseY()
{
return (this.getScreenHeight() - Mouse.getY() * this.getScreenHeight() / this.mc.displayHeight - 1) - this.yOffset;
}
@Override
public boolean isHovered(Rect dim)
{
if (dim == null)
{
return false;
}
return this.getMouseX() >= dim.x() && this.getMouseY() >= dim.y() && this.getMouseX() < dim.x() + dim.width() && this.getMouseY() < dim.y() + dim.height();
}
@Override
public float getScaleFactor()
{
return this.resolution.getScaleFactor();
}
@Override
public InputProvider copyWithMouseXOffset(float xOffset)
{
MinecraftInputProvider input = (MinecraftInputProvider) this.clone();
input.xOffset = xOffset;
return input;
}
@Override
public InputProvider copyWithMouseYOffset(float yOffset)
{
MinecraftInputProvider input = (MinecraftInputProvider) this.clone();
input.yOffset = yOffset;
return input;
}
@Override
public InputProvider clone()
{
MinecraftInputProvider input = new MinecraftInputProvider(this.mc);
input.screenWidth = this.screenWidth;
input.screenHeight = this.screenHeight;
input.scaleFactor = this.scaleFactor;
input.xOffset = this.xOffset;
input.yOffset = this.yOffset;
return input;
}
@Override
public boolean isHovered(RectHolder holder)
{
if (holder == null)
{
return false;
}
return this.isHovered(holder.dim());
}
@Override
public void setMouseX(float x)
{
Mouse.setCursorPosition(MathHelper.floor_float((x / this.getScreenWidth() * this.mc.displayWidth)), Mouse.getY());
}
@Override
public void setMouseY(float y)
{
Mouse.setCursorPosition(Mouse.getX(), Display.getHeight() - MathHelper.floor_float((y / this.getScreenHeight() * this.mc.displayHeight + 1)));
}
@Override
public void setMouse(float x, float y)
{
this.setMouseX(x);
this.setMouseY(y);
}
}
| gpl-3.0 |
confiscate/timetrack | app/src/main/java/com/henrystudios/henry/timetrack/StorageManager.java | 6358 | package com.henrystudios.henry.timetrack;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
/**
* Created by silvio on 4/25/15.
*/
public class StorageManager {
private static String TASK_STORE = "com.henrystudios.henry.TASK_STORE";
private static String NOTIFICATION_STORE = "com.henrystudios.henry.NOTIFICATION_STORE";
private static String NOTIFICATION_STORE_ON_OFF = "com.henrystudios.henry.NOTIFICATION_STORE_KEY";
private static String NOTIFICATION_STORE_HOURS = "com.henrystudios.henry.NOTIFICATION_STORE_HOURS";
// public CognitoSyncManager syncClient;
// private Dataset notificationDataset;
// private Dataset hourTaskDataset;
//
// public CognitoCachingCredentialsProvider credentialsProvider;
// stuff that is persisted in AWS
private HoursListItem[] hoursListItems = new HoursListItem[24];
public StorageManager() {
}
public HoursListItem[] getHoursListItems() {
return hoursListItems;
}
public HoursListItem getHoursListItem(int index) {
return hoursListItems[index];
}
public void setHoursListItem(int index, HoursListItem item) {
hoursListItems[index] = item;
}
public void setNotificationsActive(boolean notificationsActive, Context context) {
SharedPreferences.Editor notificationStoreEditor =
context.getSharedPreferences(NOTIFICATION_STORE, Context.MODE_PRIVATE)
.edit();
notificationStoreEditor.putBoolean(NOTIFICATION_STORE_ON_OFF, notificationsActive);
notificationStoreEditor.commit();
}
public boolean getNotificationsActive(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(
NOTIFICATION_STORE, Context.MODE_PRIVATE);
return sharedPref.getBoolean(NOTIFICATION_STORE_ON_OFF, false);
}
public void setNotificationPeriod(String minutes, Context context) {
SharedPreferences.Editor notificationStoreEditor =
context.getSharedPreferences(NOTIFICATION_STORE, Context.MODE_PRIVATE)
.edit();
notificationStoreEditor.putString(NOTIFICATION_STORE_HOURS, minutes);
notificationStoreEditor.commit();
}
public String getNotificationsPeriod(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(
NOTIFICATION_STORE, Context.MODE_PRIVATE);
return sharedPref.getString(NOTIFICATION_STORE_HOURS, "1");
}
public void pushTasksToStorage(Context context) {
SharedPreferences.Editor storeEditor =
context.getSharedPreferences(TASK_STORE, Context.MODE_PRIVATE)
.edit();
for (int i = 0; i < hoursListItems.length; i++) {
if (hoursListItems[i].getTaskDesc().trim().equals("")) {
storeEditor.remove(hoursListItems[i].getKey());
continue;
}
storeEditor.putString(hoursListItems[i].getKey(),
hoursListItems[i].getTaskDesc());
}
storeEditor.commit();
}
public void pullTasksFromStorage(MainActivity activity) {
activity.fillHoursLog();
SharedPreferences sharedPref = activity.getSharedPreferences(
TASK_STORE, Context.MODE_PRIVATE);
for (int i = 0; i < hoursListItems.length; i++) {
String taskDesc = sharedPref.getString(hoursListItems[i].getKey(), "");
if (taskDesc.trim().equals("")) {
continue;
}
hoursListItems[i].setTaskDesc(taskDesc);
}
}
public HoursListItem[] getAllListItems(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(
TASK_STORE, Context.MODE_PRIVATE);
ArrayList<HoursListItem> allPastItems = new ArrayList();
Map<String, ?> storedTasks = sharedPref.getAll();
for (Map.Entry<String, ?> entry : storedTasks.entrySet()) {
String taskDesc = entry.getValue().toString();
if (taskDesc.trim().equals("")) {
continue;
}
int separatorIndex = entry.getKey().lastIndexOf(' ');
if (separatorIndex <= 0) {
continue;
}
String hour = entry.getKey().substring(0, separatorIndex);
String date = entry.getKey().substring(separatorIndex + 1);
allPastItems.add(new HoursListItem(hour, date, taskDesc));
}
Collections.sort(allPastItems);
return allPastItems.toArray(new HoursListItem[allPastItems.size()]);
}
// private void authenticateAWS() {
// credentialsProvider = new CognitoCachingCredentialsProvider(
// this, // Context
// "", // Identity Pool ID
// Regions.US_EAST_1 // Region
// );
//
// // Initialize the Cognito Sync client
// syncClient = new CognitoSyncManager(
// this,
// Regions.US_EAST_1, // Region
// credentialsProvider);
//
// // Create a record in a dataset and synchronize with the server
// hourTaskDataset = syncClient.openOrCreateDataset("hourTaskDataset");
// synchronizeDataset(hourTaskDataset);
// notificationDataset = syncClient.openOrCreateDataset("notificationDataset");
// synchronizeDataset(notificationDataset);
// }
// private void synchronizeDataset(Dataset dataset) {
// dataset.synchronize(new DefaultSyncCallback() {
// @Override
// public void onSuccess(Dataset dataset, List newRecords) {
// }
// });
// }
// notificationDataset.put("on", on.toString());
// synchronizeDataset(notificationDataset);
// if (on) {
//
// }
// if (hourTaskDataset != null) {
// if (newTaskDesc.equals("")) {
// hourTaskDataset.remove(key);
// } else {
// hourTaskDataset.put(key, newTaskDesc);
// }
// hourTaskDataset.synchronize(new DefaultSyncCallback() {
// @Override
// public void onSuccess(Dataset dataset, List newRecords) {
// refreshList();
// }
// });
// }
}
| gpl-3.0 |
Pochwar/FishBlock | public/js/serie.js | 2064 | $(document).ready(function() {
$(".viewed").click(function(e) {
e.preventDefault();
var button = $("#" + e.target.id);
var data = {};
if (button.hasClass("btn-warning")) {
button.removeClass("btn-warning");
button.addClass("btn-success");
// button.html("✓ {{ __(\"VIEWED_TRUE\") }}");
$("#button-viewed-false").toggle();
$("#button-viewed-true").toggle();
data.episodeId = e.target.id;
data.remove = false;
} else {
button.removeClass("btn-success");
button.addClass("btn-warning");
// button.html("{{ __(VIEWED_FALSE) }}");
$("#button-viewed-false").toggle();
$("#button-viewed-true").toggle();
data.episodeId = e.target.id;
data.remove = true;
}
$.ajax({
url : '/user/episodes',
type : 'PUT',
data : data,
success: response => {
// console.log(response);
},
error: error => {
console.log(error);
}
});
});
$(".followed").click(function(e) {
e.preventDefault();
var buttonFollow = $("#" + e.target.id);
var data = {};
if (buttonFollow.hasClass("btn-warning")) {
buttonFollow.removeClass("btn-warning");
buttonFollow.addClass("btn-success");
// buttonFollow.html("✓ {{ __(\"FOLLOWED_TRUE\") }}");
$("#button-followed-false").toggle();
$("#button-followed-true").toggle();
data.serieId = e.target.id;
data.remove = false;
} else {
buttonFollow.removeClass("btn-success");
buttonFollow.addClass("btn-warning");
// buttonFollow.html(notFollowed);
$("#button-followed-true").toggle();
$("#button-followed-false").toggle();
data.serieId = e.target.id;
data.remove = true;
}
$.ajax({
url : '/user/series',
type : 'PUT',
data : data,
success: response => {
// console.log(response);
},
error: error => {
console.log(error);
}
});
$.ajax({
url : '/series/'+ e.target.id + '/follow',
type : 'PUT',
data : data,
success: response => {
// console.log(response);
},
error: error => {
console.log(error);
}
});
});
}); | gpl-3.0 |
Merg3D/Titan-Designer | src/ui/ScrollContainer.cpp | 1820 | #include "ScrollContainer.h"
#include "TextBox.h"
#include "graphics/Renderer.h"
ScrollContainer::ScrollContainer()
{
use_vert_slider(true);
}
ScrollContainer::~ScrollContainer()
{
}
//void ScrollContainer::init(const rect2 &p_render_area)
//{
// Container::init(p_render_area);
//}
void ScrollContainer::use_vert_slider(bool value)
{
if (value)
{
vert_slider = new Slider;
}
else
vert_slider = NULL;
}
//void ScrollContainer::resize(const rect2 &p_render_area)
//{
// area = p_render_area;
//
// if (vert_slider)
// {
// work_area = area.crop(0, 14, 0, 0);
// vert_slider_area = area.align_full_right(7);
//
// vert_slider->init(vert_slider_area);
// }
//
// Container::resize(work_area);
//
// set_position(vec2());
// visible_area = area;
//}
void ScrollContainer::draw()
{
if (vert_slider)
vert_slider->draw();
if (use_scissor)
RENDERER->use_scissor(area);
/*for (Control *c : children)
{
if (c->area.is_overlapping(visible_area))
c->draw();
}*/
if (use_scissor)
RENDERER->stop_scissor();
}
//Control* ScrollContainer::raycast(const vec2 &pos) const
//{
// if (work_area.is_in_box(pos))
// return Container::raycast(pos);
// else if (vert_slider_area.is_in_box(pos))
// return vert_slider;
// else
// return nullptr;
//}
void ScrollContainer::set_position(const vec2 &p_position)
{
position = p_position;
//vec2 o = (area - vec2(work_area.size.x, work_area.size.y) * 4.0) * position / 2.0;
vec2 prev_offset = offset;
//offset = vec2(o.x, o.y);
//vec2 translation = offset - prev_offset;
/*for (Control *c : children)
{
TextLine *tl = dynamic_cast<TextLine*>(c);
if (tl)
tl->translate(translation);
else
c->resize(rect2(c->area.pos + translation, c->area.size));
}*/
}
void ScrollContainer::set_use_scissor(bool value)
{
use_scissor = value;
} | gpl-3.0 |
eMoflon/emoflon-ibex | org.emoflon.ibex.gt.statemodel/src-gen/org/emoflon/ibex/gt/StateModel/impl/ComplexParameterImpl.java | 3527 | /**
*/
package org.emoflon.ibex.gt.StateModel.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.emoflon.ibex.gt.StateModel.ComplexParameter;
import org.emoflon.ibex.gt.StateModel.StateModelPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Complex Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.emoflon.ibex.gt.StateModel.impl.ComplexParameterImpl#getValue <em>Value</em>}</li>
* </ul>
*
* @generated
*/
public class ComplexParameterImpl extends ParameterImpl implements ComplexParameter {
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected EObject value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComplexParameterImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return StateModelPackage.Literals.COMPLEX_PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject getValue() {
if (value != null && value.eIsProxy()) {
InternalEObject oldValue = (InternalEObject) value;
value = eResolveProxy(oldValue);
if (value != oldValue) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE,
StateModelPackage.COMPLEX_PARAMETER__VALUE, oldValue, value));
}
}
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EObject basicGetValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setValue(EObject newValue) {
EObject oldValue = value;
value = newValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, StateModelPackage.COMPLEX_PARAMETER__VALUE, oldValue,
value));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case StateModelPackage.COMPLEX_PARAMETER__VALUE:
if (resolve)
return getValue();
return basicGetValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case StateModelPackage.COMPLEX_PARAMETER__VALUE:
setValue((EObject) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case StateModelPackage.COMPLEX_PARAMETER__VALUE:
setValue((EObject) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case StateModelPackage.COMPLEX_PARAMETER__VALUE:
return value != null;
}
return super.eIsSet(featureID);
}
} //ComplexParameterImpl
| gpl-3.0 |
ngageoint/elasticgeo | gt-elasticsearch/src/main/java/mil/nga/giat/data/elasticsearch/ElasticMappings.java | 924 | /*
* This file is hereby placed into the Public Domain. This means anyone is
* free to do whatever they wish with this file.
*/
package mil.nga.giat.data.elasticsearch;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@SuppressWarnings("unused")
class ElasticMappings {
private Map<String,Mapping> mappings;
public Map<String, Mapping> getMappings() {
return mappings;
}
public void setMappings(Map<String, Mapping> mappings) {
this.mappings = mappings;
}
@JsonIgnoreProperties(ignoreUnknown=true)
public static class Mapping {
private Map<String,Object> properties;
public Map<String, Object> getProperties() {
return properties;
}
}
public static class Untyped {
private Mapping mappings;
public Mapping getMappings() {
return mappings;
}
}
}
| gpl-3.0 |
milhcbt/OrthancMirror | Core/HttpServer/MongooseServer.cpp | 25199 | /**
* Orthanc - A Lightweight, RESTful DICOM Store
* Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
* Department, University Hospital of Liege, Belgium
*
* 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.
*
* In addition, as a special exception, the copyright holders of this
* program give permission to link the code of its release with the
* OpenSSL project's "OpenSSL" library (or with modified versions of it
* that use the same license as the "OpenSSL" library), and distribute
* the linked executables. You must obey the GNU General Public License
* in all respects for all of the code used other than "OpenSSL". If you
* modify file(s) with this exception, you may extend this exception to
* your version of the file(s), but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source files
* in the program, then also delete it here.
*
* 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/>.
**/
// http://en.highscore.de/cpp/boost/stringhandling.html
#include "../PrecompiledHeaders.h"
#include "MongooseServer.h"
#include "../Logging.h"
#include "../OrthancException.h"
#include "../ChunkedBuffer.h"
#include "HttpToolbox.h"
#include "mongoose.h"
#include <algorithm>
#include <string.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <boost/thread.hpp>
#if ORTHANC_SSL_ENABLED == 1
#include <openssl/opensslv.h>
#endif
#define ORTHANC_REALM "Orthanc Secure Area"
static const long LOCALHOST = (127ll << 24) + 1ll;
namespace Orthanc
{
static const char multipart[] = "multipart/form-data; boundary=";
static unsigned int multipartLength = sizeof(multipart) / sizeof(char) - 1;
namespace
{
// Anonymous namespace to avoid clashes between compilation modules
class MongooseOutputStream : public IHttpOutputStream
{
private:
struct mg_connection* connection_;
public:
MongooseOutputStream(struct mg_connection* connection) : connection_(connection)
{
}
virtual void Send(bool isHeader, const void* buffer, size_t length)
{
if (length > 0)
{
int status = mg_write(connection_, buffer, length);
if (status != static_cast<int>(length))
{
// status == 0 when the connection has been closed, -1 on error
throw OrthancException(ErrorCode_NetworkProtocol);
}
}
}
virtual void OnHttpStatusReceived(HttpStatus status)
{
// Ignore this
}
};
enum PostDataStatus
{
PostDataStatus_Success,
PostDataStatus_NoLength,
PostDataStatus_Pending,
PostDataStatus_Failure
};
}
// TODO Move this to external file
class ChunkedFile : public ChunkedBuffer
{
private:
std::string filename_;
public:
ChunkedFile(const std::string& filename) :
filename_(filename)
{
}
const std::string& GetFilename() const
{
return filename_;
}
};
class ChunkStore
{
private:
typedef std::list<ChunkedFile*> Content;
Content content_;
unsigned int numPlaces_;
boost::mutex mutex_;
std::set<std::string> discardedFiles_;
void Clear()
{
for (Content::iterator it = content_.begin();
it != content_.end(); ++it)
{
delete *it;
}
}
Content::iterator Find(const std::string& filename)
{
for (Content::iterator it = content_.begin();
it != content_.end(); ++it)
{
if ((*it)->GetFilename() == filename)
{
return it;
}
}
return content_.end();
}
void Remove(const std::string& filename)
{
Content::iterator it = Find(filename);
if (it != content_.end())
{
delete *it;
content_.erase(it);
}
}
public:
ChunkStore()
{
numPlaces_ = 10;
}
~ChunkStore()
{
Clear();
}
PostDataStatus Store(std::string& completed,
const char* chunkData,
size_t chunkSize,
const std::string& filename,
size_t filesize)
{
boost::mutex::scoped_lock lock(mutex_);
std::set<std::string>::iterator wasDiscarded = discardedFiles_.find(filename);
if (wasDiscarded != discardedFiles_.end())
{
discardedFiles_.erase(wasDiscarded);
return PostDataStatus_Failure;
}
ChunkedFile* f;
Content::iterator it = Find(filename);
if (it == content_.end())
{
f = new ChunkedFile(filename);
// Make some room
if (content_.size() >= numPlaces_)
{
discardedFiles_.insert(content_.front()->GetFilename());
delete content_.front();
content_.pop_front();
}
content_.push_back(f);
}
else
{
f = *it;
}
f->AddChunk(chunkData, chunkSize);
if (f->GetNumBytes() > filesize)
{
Remove(filename);
}
else if (f->GetNumBytes() == filesize)
{
f->Flatten(completed);
Remove(filename);
return PostDataStatus_Success;
}
return PostDataStatus_Pending;
}
/*void Print()
{
boost::mutex::scoped_lock lock(mutex_);
printf("ChunkStore status:\n");
for (Content::const_iterator i = content_.begin();
i != content_.end(); i++)
{
printf(" [%s]: %d\n", (*i)->GetFilename().c_str(), (*i)->GetNumBytes());
}
printf("-----\n");
}*/
};
struct MongooseServer::PImpl
{
struct mg_context *context_;
ChunkStore chunkStore_;
};
ChunkStore& MongooseServer::GetChunkStore()
{
return pimpl_->chunkStore_;
}
static PostDataStatus ReadBody(std::string& postData,
struct mg_connection *connection,
const IHttpHandler::Arguments& headers)
{
IHttpHandler::Arguments::const_iterator cs = headers.find("content-length");
if (cs == headers.end())
{
return PostDataStatus_NoLength;
}
int length;
try
{
length = boost::lexical_cast<int>(cs->second);
}
catch (boost::bad_lexical_cast)
{
return PostDataStatus_NoLength;
}
if (length < 0)
{
length = 0;
}
postData.resize(length);
size_t pos = 0;
while (length > 0)
{
int r = mg_read(connection, &postData[pos], length);
if (r <= 0)
{
return PostDataStatus_Failure;
}
assert(r <= length);
length -= r;
pos += r;
}
return PostDataStatus_Success;
}
static PostDataStatus ParseMultipartPost(std::string &completedFile,
struct mg_connection *connection,
const IHttpHandler::Arguments& headers,
const std::string& contentType,
ChunkStore& chunkStore)
{
std::string boundary = "--" + contentType.substr(multipartLength);
std::string postData;
PostDataStatus status = ReadBody(postData, connection, headers);
if (status != PostDataStatus_Success)
{
return status;
}
/*for (IHttpHandler::Arguments::const_iterator i = headers.begin(); i != headers.end(); i++)
{
std::cout << "Header [" << i->first << "] = " << i->second << "\n";
}
printf("CHUNK\n");*/
typedef IHttpHandler::Arguments::const_iterator ArgumentIterator;
ArgumentIterator requestedWith = headers.find("x-requested-with");
ArgumentIterator fileName = headers.find("x-file-name");
ArgumentIterator fileSizeStr = headers.find("x-file-size");
if (requestedWith != headers.end() &&
requestedWith->second != "XMLHttpRequest")
{
return PostDataStatus_Failure;
}
size_t fileSize = 0;
if (fileSizeStr != headers.end())
{
try
{
fileSize = boost::lexical_cast<size_t>(fileSizeStr->second);
}
catch (boost::bad_lexical_cast)
{
return PostDataStatus_Failure;
}
}
typedef boost::find_iterator<std::string::iterator> FindIterator;
typedef boost::iterator_range<char*> Range;
//chunkStore.Print();
try
{
FindIterator last;
for (FindIterator it =
make_find_iterator(postData, boost::first_finder(boundary));
it!=FindIterator();
++it)
{
if (last != FindIterator())
{
Range part(&last->back(), &it->front());
Range content = boost::find_first(part, "\r\n\r\n");
if (/*content != Range()*/!content.empty())
{
Range c(&content.back() + 1, &it->front() - 2);
size_t chunkSize = c.size();
if (chunkSize > 0)
{
const char* chunkData = &c.front();
if (fileName == headers.end())
{
// This file is stored in a single chunk
completedFile.resize(chunkSize);
if (chunkSize > 0)
{
memcpy(&completedFile[0], chunkData, chunkSize);
}
return PostDataStatus_Success;
}
else
{
return chunkStore.Store(completedFile, chunkData, chunkSize, fileName->second, fileSize);
}
}
}
}
last = it;
}
}
catch (std::length_error)
{
return PostDataStatus_Failure;
}
return PostDataStatus_Pending;
}
static bool IsAccessGranted(const MongooseServer& that,
const IHttpHandler::Arguments& headers)
{
bool granted = false;
IHttpHandler::Arguments::const_iterator auth = headers.find("authorization");
if (auth != headers.end())
{
std::string s = auth->second;
if (s.size() > 6 &&
s.substr(0, 6) == "Basic ")
{
std::string b64 = s.substr(6);
granted = that.IsValidBasicHttpAuthentication(b64);
}
}
return granted;
}
static std::string GetAuthenticatedUsername(const IHttpHandler::Arguments& headers)
{
IHttpHandler::Arguments::const_iterator auth = headers.find("authorization");
if (auth == headers.end())
{
return "";
}
std::string s = auth->second;
if (s.size() <= 6 ||
s.substr(0, 6) != "Basic ")
{
return "";
}
std::string b64 = s.substr(6);
std::string decoded;
Toolbox::DecodeBase64(decoded, b64);
size_t semicolons = decoded.find(':');
if (semicolons == std::string::npos)
{
// Bad-formatted request
return "";
}
else
{
return decoded.substr(0, semicolons);
}
}
static bool ExtractMethod(HttpMethod& method,
const struct mg_request_info *request,
const IHttpHandler::Arguments& headers,
const IHttpHandler::GetArguments& argumentsGET)
{
std::string overriden;
// Check whether some PUT/DELETE faking is done
// 1. Faking with Google's approach
IHttpHandler::Arguments::const_iterator methodOverride =
headers.find("x-http-method-override");
if (methodOverride != headers.end())
{
overriden = methodOverride->second;
}
else if (!strcmp(request->request_method, "GET"))
{
// 2. Faking with Ruby on Rail's approach
// GET /my/resource?_method=delete <=> DELETE /my/resource
for (size_t i = 0; i < argumentsGET.size(); i++)
{
if (argumentsGET[i].first == "_method")
{
overriden = argumentsGET[i].second;
break;
}
}
}
if (overriden.size() > 0)
{
// A faking has been done within this request
Toolbox::ToUpperCase(overriden);
LOG(INFO) << "HTTP method faking has been detected for " << overriden;
if (overriden == "PUT")
{
method = HttpMethod_Put;
return true;
}
else if (overriden == "DELETE")
{
method = HttpMethod_Delete;
return true;
}
else
{
return false;
}
}
// No PUT/DELETE faking was present
if (!strcmp(request->request_method, "GET"))
{
method = HttpMethod_Get;
}
else if (!strcmp(request->request_method, "POST"))
{
method = HttpMethod_Post;
}
else if (!strcmp(request->request_method, "DELETE"))
{
method = HttpMethod_Delete;
}
else if (!strcmp(request->request_method, "PUT"))
{
method = HttpMethod_Put;
}
else
{
return false;
}
return true;
}
static void ConfigureHttpCompression(HttpOutput& output,
const IHttpHandler::Arguments& headers)
{
// Look if the client wishes HTTP compression
// https://en.wikipedia.org/wiki/HTTP_compression
IHttpHandler::Arguments::const_iterator it = headers.find("accept-encoding");
if (it != headers.end())
{
std::vector<std::string> encodings;
Toolbox::TokenizeString(encodings, it->second, ',');
for (size_t i = 0; i < encodings.size(); i++)
{
std::string s = Toolbox::StripSpaces(encodings[i]);
if (s == "deflate")
{
output.SetDeflateAllowed(true);
}
else if (s == "gzip")
{
output.SetGzipAllowed(true);
}
}
}
}
static void InternalCallback(struct mg_connection *connection,
const struct mg_request_info *request)
{
MongooseServer* that = reinterpret_cast<MongooseServer*>(request->user_data);
MongooseOutputStream stream(connection);
HttpOutput output(stream, that->IsKeepAliveEnabled());
output.SetDescribeErrorsEnabled(that->IsDescribeErrorsEnabled());
// Check remote calls
if (!that->IsRemoteAccessAllowed() &&
request->remote_ip != LOCALHOST)
{
output.SendUnauthorized(ORTHANC_REALM);
return;
}
// Extract the HTTP headers
IHttpHandler::Arguments headers;
for (int i = 0; i < request->num_headers; i++)
{
std::string name = request->http_headers[i].name;
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
headers.insert(std::make_pair(name, request->http_headers[i].value));
}
if (that->IsHttpCompressionEnabled())
{
ConfigureHttpCompression(output, headers);
}
// Extract the GET arguments
IHttpHandler::GetArguments argumentsGET;
if (!strcmp(request->request_method, "GET"))
{
HttpToolbox::ParseGetArguments(argumentsGET, request->query_string);
}
// Compute the HTTP method, taking method faking into consideration
HttpMethod method = HttpMethod_Get;
if (!ExtractMethod(method, request, headers, argumentsGET))
{
output.SendStatus(HttpStatus_400_BadRequest);
return;
}
// Authenticate this connection
if (that->IsAuthenticationEnabled() && !IsAccessGranted(*that, headers))
{
output.SendUnauthorized(ORTHANC_REALM);
return;
}
// Apply the filter, if it is installed
char remoteIp[24];
sprintf(remoteIp, "%d.%d.%d.%d",
reinterpret_cast<const uint8_t*>(&request->remote_ip) [3],
reinterpret_cast<const uint8_t*>(&request->remote_ip) [2],
reinterpret_cast<const uint8_t*>(&request->remote_ip) [1],
reinterpret_cast<const uint8_t*>(&request->remote_ip) [0]);
std::string username = GetAuthenticatedUsername(headers);
const IIncomingHttpRequestFilter *filter = that->GetIncomingHttpRequestFilter();
if (filter != NULL)
{
if (!filter->IsAllowed(method, request->uri, remoteIp, username.c_str()))
{
output.SendUnauthorized(ORTHANC_REALM);
return;
}
}
// Extract the body of the request for PUT and POST
// TODO Avoid unneccessary memcopy of the body
std::string body;
if (method == HttpMethod_Post ||
method == HttpMethod_Put)
{
PostDataStatus status;
IHttpHandler::Arguments::const_iterator ct = headers.find("content-type");
if (ct == headers.end())
{
// No content-type specified. Assume no multi-part content occurs at this point.
status = ReadBody(body, connection, headers);
}
else
{
std::string contentType = ct->second;
if (contentType.size() >= multipartLength &&
!memcmp(contentType.c_str(), multipart, multipartLength))
{
status = ParseMultipartPost(body, connection, headers, contentType, that->GetChunkStore());
}
else
{
status = ReadBody(body, connection, headers);
}
}
switch (status)
{
case PostDataStatus_NoLength:
output.SendStatus(HttpStatus_411_LengthRequired);
return;
case PostDataStatus_Failure:
output.SendStatus(HttpStatus_400_BadRequest);
return;
case PostDataStatus_Pending:
output.AnswerEmpty();
return;
default:
break;
}
}
// Decompose the URI into its components
UriComponents uri;
try
{
Toolbox::SplitUriComponents(uri, request->uri);
}
catch (OrthancException)
{
output.SendStatus(HttpStatus_400_BadRequest);
return;
}
LOG(INFO) << EnumerationToString(method) << " " << Toolbox::FlattenUri(uri);
try
{
bool found = false;
try
{
if (that->HasHandler())
{
found = that->GetHandler().Handle(output, RequestOrigin_Http, remoteIp, username.c_str(),
method, uri, headers, argumentsGET, body.c_str(), body.size());
}
}
catch (boost::bad_lexical_cast&)
{
throw OrthancException(ErrorCode_BadParameterType, HttpStatus_400_BadRequest);
}
catch (std::runtime_error&)
{
// Presumably an error while parsing the JSON body
throw OrthancException(ErrorCode_BadRequest, HttpStatus_400_BadRequest);
}
if (!found)
{
throw OrthancException(ErrorCode_UnknownResource);
}
}
catch (OrthancException& e)
{
// Using this candidate handler results in an exception
LOG(ERROR) << "Exception in the HTTP handler: " << e.What();
Json::Value message = Json::objectValue;
message["HttpError"] = EnumerationToString(e.GetHttpStatus());
message["HttpStatus"] = e.GetHttpStatus();
message["Message"] = e.What();
message["Method"] = EnumerationToString(method);
message["OrthancError"] = EnumerationToString(e.GetErrorCode());
message["OrthancStatus"] = e.GetErrorCode();
message["Uri"] = request->uri;
std::string info = message.toStyledString();
try
{
output.SendStatus(e.GetHttpStatus(), info);
}
catch (OrthancException&)
{
// An exception here reflects the fact that the status code
// was already set by the HTTP handler.
}
return;
}
}
#if MONGOOSE_USE_CALLBACKS == 0
static void* Callback(enum mg_event event,
struct mg_connection *connection,
const struct mg_request_info *request)
{
if (event == MG_NEW_REQUEST)
{
InternalCallback(connection, request);
// Mark as processed
return (void*) "";
}
else
{
return NULL;
}
}
#elif MONGOOSE_USE_CALLBACKS == 1
static int Callback(struct mg_connection *connection)
{
struct mg_request_info *request = mg_get_request_info(connection);
InternalCallback(connection, request);
return 1; // Do not let Mongoose handle the request by itself
}
#else
#error Please set MONGOOSE_USE_CALLBACKS
#endif
bool MongooseServer::IsRunning() const
{
return (pimpl_->context_ != NULL);
}
MongooseServer::MongooseServer() : pimpl_(new PImpl)
{
pimpl_->context_ = NULL;
handler_ = NULL;
remoteAllowed_ = false;
authentication_ = false;
ssl_ = false;
port_ = 8000;
filter_ = NULL;
keepAlive_ = false;
httpCompression_ = true;
describeErrors_ = true;
#if ORTHANC_SSL_ENABLED == 1
// Check for the Heartbleed exploit
// https://en.wikipedia.org/wiki/OpenSSL#Heartbleed_bug
if (OPENSSL_VERSION_NUMBER < 0x1000107fL /* openssl-1.0.1g */ &&
OPENSSL_VERSION_NUMBER >= 0x1000100fL /* openssl-1.0.1 */)
{
LOG(WARNING) << "This version of OpenSSL is vulnerable to the Heartbleed exploit";
}
#endif
}
MongooseServer::~MongooseServer()
{
Stop();
}
void MongooseServer::SetPortNumber(uint16_t port)
{
Stop();
port_ = port;
}
void MongooseServer::Start()
{
if (!IsRunning())
{
std::string port = boost::lexical_cast<std::string>(port_);
if (ssl_)
{
port += "s";
}
const char *options[] = {
// Set the TCP port for the HTTP server
"listening_ports", port.c_str(),
// Optimization reported by Chris Hafey
// https://groups.google.com/d/msg/orthanc-users/CKueKX0pJ9E/_UCbl8T-VjIJ
"enable_keep_alive", (keepAlive_ ? "yes" : "no"),
// Set the SSL certificate, if any. This must be the last option.
ssl_ ? "ssl_certificate" : NULL,
certificate_.c_str(),
NULL
};
#if MONGOOSE_USE_CALLBACKS == 0
pimpl_->context_ = mg_start(&Callback, this, options);
#elif MONGOOSE_USE_CALLBACKS == 1
struct mg_callbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = Callback;
pimpl_->context_ = mg_start(&callbacks, this, options);
#else
#error Please set MONGOOSE_USE_CALLBACKS
#endif
if (!pimpl_->context_)
{
throw OrthancException(ErrorCode_HttpPortInUse);
}
}
}
void MongooseServer::Stop()
{
if (IsRunning())
{
mg_stop(pimpl_->context_);
pimpl_->context_ = NULL;
}
}
void MongooseServer::ClearUsers()
{
Stop();
registeredUsers_.clear();
}
void MongooseServer::RegisterUser(const char* username,
const char* password)
{
Stop();
std::string tag = std::string(username) + ":" + std::string(password);
std::string encoded;
Toolbox::EncodeBase64(encoded, tag);
registeredUsers_.insert(encoded);
}
void MongooseServer::SetSslEnabled(bool enabled)
{
Stop();
#if ORTHANC_SSL_ENABLED == 0
if (enabled)
{
throw OrthancException("Orthanc has been built without SSL support");
}
else
{
ssl_ = false;
}
#else
ssl_ = enabled;
#endif
}
void MongooseServer::SetKeepAliveEnabled(bool enabled)
{
Stop();
keepAlive_ = enabled;
LOG(WARNING) << "HTTP keep alive is " << (enabled ? "enabled" : "disabled");
}
void MongooseServer::SetAuthenticationEnabled(bool enabled)
{
Stop();
authentication_ = enabled;
}
void MongooseServer::SetSslCertificate(const char* path)
{
Stop();
certificate_ = path;
}
void MongooseServer::SetRemoteAccessAllowed(bool allowed)
{
Stop();
remoteAllowed_ = allowed;
}
void MongooseServer::SetHttpCompressionEnabled(bool enabled)
{
Stop();
httpCompression_ = enabled;
LOG(WARNING) << "HTTP compression is " << (enabled ? "enabled" : "disabled");
}
void MongooseServer::SetDescribeErrorsEnabled(bool enabled)
{
describeErrors_ = enabled;
LOG(INFO) << "Description of the errors in the HTTP answers is " << (enabled ? "enabled" : "disabled");
}
void MongooseServer::SetIncomingHttpRequestFilter(IIncomingHttpRequestFilter& filter)
{
Stop();
filter_ = &filter;
}
bool MongooseServer::IsValidBasicHttpAuthentication(const std::string& basic) const
{
return registeredUsers_.find(basic) != registeredUsers_.end();
}
void MongooseServer::Register(IHttpHandler& handler)
{
Stop();
handler_ = &handler;
}
IHttpHandler& MongooseServer::GetHandler() const
{
if (handler_ == NULL)
{
throw OrthancException(ErrorCode_InternalError);
}
return *handler_;
}
}
| gpl-3.0 |
scalexm/Desperion_legacy | Login/World.cpp | 4005 | /*
This file is part of Desperion.
Copyright 2010, 2011 LittleScaraby, Nekkro
Desperion 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.
Desperion 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 Desperion. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
template <> World * Singleton<World>::m_singleton = NULL;
// A poster dans l'io_service du Master, car c'est une méthode assez lourde
void World::RefreshGameServer(GameServer* G)
{
struct Count
{
uint8 count;
Count()
{ count = 0; }
};
std::tr1::unordered_map<int, Count> counts;
ResultPtr QR = Desperion::sDatabase->Query("SELECT \"accountGuid\" FROM \"character_counts\" WHERE \"serverId\"=%u;", G->GetID());
if(QR)
{
while(QR->NextRow())
{
Field* fields = QR->Fetch();
++counts[fields[0].GetInt32()].count;
}
}
boost::shared_lock<boost::shared_mutex> lock(SessionsMutex);
for(SessionMap::iterator it = Sessions.begin(); it != Sessions.end(); ++it)
{
it->second->Send(ServerStatusUpdateMessage(it->second->GetServerStatusMessage(G,
counts[it->second->GetData(FLAG_GUID).intValue].count)));
}
}
World::~World()
{
Sessions.clear();
GameSessions.clear();
for(GameServerMap::iterator it = GameServers.begin(); it != GameServers.end(); ++it)
delete it->second;
GameServers.clear();
}
void World::LoadGameServers()
{
uint32 time = getMSTime();
ResultPtr QR = Desperion::sDatabase->Query("SELECT * FROM \"game_servers\";");
if(!QR)
return;
while(QR->NextRow())
{
Field * fields = QR->Fetch();
uint16 id = fields[0].GetUInt16();
GameServer* g = new GameServer;
g->Init(id, fields[1].GetString(), fields[2].GetUInt16(), fields[3].GetUInt8(), fields[5].GetString(), fields[4].GetUInt16(), fields[6].GetUInt8());
GameServers[id] = g;
}
Log::Instance().OutNotice("World", "%u game servers loaded in %ums!", GameServers.size(), getMSTime() - time);
}
void World::Init()
{
Log::Instance().OutNotice("World", "Loading world...");
LoadGameServers();
Session::InitHandlersTable();
GameSession::InitHandlersTable();
Log::Instance().OutNotice("World", "World loaded!\n\n");
}
void World::AddSession(Session* s)
{
boost::unique_lock<boost::shared_mutex> lock(SessionsMutex);
Sessions[s->GetData(FLAG_GUID).intValue] = s;
if(Sessions.size() > m_maxPlayers)
m_maxPlayers = Sessions.size();
}
Session* World::GetSession(int guid)
{
boost::shared_lock<boost::shared_mutex> lock(SessionsMutex);
SessionMap::iterator it = Sessions.find(guid);
if(it != Sessions.end())
return it->second;
return NULL;
}
void World::DeleteSession(int guid)
{
boost::unique_lock<boost::shared_mutex> lock(SessionsMutex);
SessionMap::iterator it = Sessions.find(guid);
if(it != Sessions.end())
Sessions.erase(it);
}
GameServer* World::GetGameServer(uint16 Guid)
{
GameServerMap::iterator it = GameServers.find(Guid);
if(it != GameServers.end())
return it->second;
return NULL;
}
void World::AddGameSession(GameSession* s)
{
boost::unique_lock<boost::shared_mutex> lock(GameSessionsMutex);
GameSessions[s->GetServer()->GetID()] = s;
}
GameSession* World::GetGameSession(uint16 guid)
{
boost::shared_lock<boost::shared_mutex> lock(GameSessionsMutex);
GameSessionMap::iterator it = GameSessions.find(guid);
if(it != GameSessions.end())
return it->second;
return NULL;
}
void World::DeleteGameSession(uint16 guid)
{
boost::unique_lock<boost::shared_mutex> lock(GameSessionsMutex);
GameSessionMap::iterator it = GameSessions.find(guid);
if(it != GameSessions.end())
GameSessions.erase(it);
}
| gpl-3.0 |
alariq/mc2 | mclib/stuff/scalar.cpp | 3305 | //===========================================================================//
// File: scalar.cpp //
// Contents: Base information used by all MUNGA source files //
//---------------------------------------------------------------------------//
// Copyright (C) Microsoft Corporation. All rights reserved. //
//===========================================================================//
#include"stuffheaders.hpp"
int
Stuff::Round(Scalar value)
{
int whole_part = static_cast<int>(floor(value));
Scalar fractional_part = value - whole_part;
if (fractional_part >= 0.5)
{
return whole_part + 1;
}
else
{
return whole_part;
}
}
void
Stuff::Find_Roots(
Scalar a, // a*x*x + b*x + c = 0
Scalar b,
Scalar c,
Scalar *center,
Scalar *range
)
{
//
//---------------------------------
// See if the quadratic is solvable
//---------------------------------
//
*range = b*b - 4.0f*a*c;
if (*range < 0.0f || Small_Enough(a))
{
*range = -1.0f;
}
else
{
//
//---------------------------
// Solve the single root case
//---------------------------
//
a *= 2.0f;
*center = -b / a;
if (*range < SMALL)
{
*range = 0.0f;
}
//
//--------------------------
// Find the two-root extents
//--------------------------
//
else
{
*range = Sqrt(*range);
*range /= a;
}
}
}
DWORD
Stuff::Scaled_Float_To_Bits(float in, float min, float max, int bits)
{
Verify(bits < 32);
Verify(bits > 0);
Verify(min < max);
Verify(in <= max);
Verify(in >= min);
unsigned int biggest_number = (0xffffffff>>(32-bits));
float local_in = in - min;
float range = (max-min);
DWORD return_value = (DWORD)((local_in/range) * (float)biggest_number);
Verify((DWORD)return_value >= 0x00000000);
Verify((DWORD)return_value <= (DWORD)biggest_number);
return return_value;
}
float
Stuff::Scaled_Float_From_Bits(DWORD in, float min, float max, int bits)
{
Verify(bits < 32);
Verify(bits > 0);
Verify(min < max);
in &= (0xffffffff>>(32-bits));
unsigned int biggest_number = (0xffffffff>>(32-bits));
float ratio = in/(float)biggest_number;
float range = (max-min);
float return_value = (ratio * range)+min;
return return_value;
}
DWORD
Stuff::Scaled_Int_To_Bits(int in, int min, int max, int bits)
{
Verify(bits < 32);
Verify(bits > 0);
Verify(min < max);
Verify(in <= max);
Verify(in >= min);
unsigned int biggest_number = (0xffffffff>>(32-bits));
int local_in = in - min;
int range = (max-min);
DWORD return_value = (DWORD)(((float)local_in/(float)range) * (float)biggest_number);
Verify((DWORD)return_value >= 0x00000000);
Verify((DWORD)return_value < (DWORD)biggest_number);
return return_value;
}
int
Stuff::Scaled_Int_From_Bits(DWORD in, int min, int max, int bits)
{
Verify(bits < 32);
Verify(bits > 0);
Verify(min < max);
unsigned int biggest_number = (0xffffffff>>(32-bits));
float ratio = (float)in/(float)biggest_number;
int range = (max-min);
int return_value = ((int)(ratio * (float)range))+min;
return return_value;
}
| gpl-3.0 |
uhm-coe/kapa | db/migrate/20161013100421_add_user_id_index_on_timestamps.rb | 169 | class AddUserIdIndexOnTimestamps < ActiveRecord::Migration[4.2]
def change
change_table :timestamps, :bulk => true do |t|
t.index :user_id
end
end
end | gpl-3.0 |
rbournissent/accountant_duck | test.rb | 80 | require './tests/test_helper'
Dir["./tests/unit/*.rb"].each { |rb| require rb }
| gpl-3.0 |
FernandoTBarros/Werewolf | Werewolf for Telegram/Telegram.Bot/Types/CallbackQuery.cs | 2648 | using Newtonsoft.Json;
using Telegram.Bot.Types.InlineKeyboardButtons;
namespace Telegram.Bot.Types
{
/// <summary>
/// This object represents an incoming callback query from a <see cref="InlineKeyboardButton"/>. If the button that originated the query was attached to a <see cref="Message"/> sent by the bot, the field message will be presented. If the button was attached to a message sent via the bot (in inline mode), the field <see cref="InlineMessageId"/> will be presented.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class CallbackQuery
{
/// <summary>
/// Unique identifier for this query
/// </summary>
[JsonProperty("id", Required = Required.Always)]
public string Id { get; set; }
/// <summary>
/// Sender
/// </summary>
[JsonProperty("from", Required = Required.Always)]
public User From { get; set; }
/// <summary>
/// Optional. Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old
/// </summary>
[JsonProperty("message", Required = Required.Default)]
public Message Message { get; set; }
/// <summary>
/// Optional. Identifier of the message sent via the bot in inline mode, that originated the query
/// </summary>
[JsonProperty("inline_message_id", Required = Required.Default)]
public string InlineMessageId { get; set; }
/// <summary>
/// Identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.
/// </summary>
[JsonProperty("chat_instance", Required = Required.Always)]
public string ChatInstance { get; set; }
/// <summary>
/// Data associated with the callback button.
/// </summary>
/// <remarks>
/// Be aware that a bad client can send arbitrary data in this field.
/// </remarks>
[JsonProperty("data", Required = Required.Default)]
public string Data { get; set; }
/// <summary>
/// Optional. Short name of a <see cref="Game"/> to be returned, serves as the unique identifier for the game.
/// </summary>
[JsonProperty("game_short_name", Required = Required.Default)]
public string GameShortName { get; set; }
/// <summary>
/// Indicates if the User requests a Game
/// </summary>
[JsonIgnore]
public bool IsGameQuery => GameShortName != null;
}
}
| gpl-3.0 |
lindareijnhoudt/neo4j-ehri-plugin | ehri-frames/src/main/java/eu/ehri/project/models/events/SystemEventQueue.java | 1477 | package eu.ehri.project.models.events;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.frames.modules.javahandler.JavaHandler;
import com.tinkerpop.frames.modules.javahandler.JavaHandlerContext;
import com.tinkerpop.pipes.util.Pipeline;
import eu.ehri.project.definitions.Ontology;
import eu.ehri.project.models.EntityClass;
import eu.ehri.project.models.annotations.EntityType;
import eu.ehri.project.models.base.Frame;
import eu.ehri.project.models.utils.JavaHandlerUtils;
/**
* Class representing the system event queue node, of which
* there Will Be Only One.
*
* Perhaps we should enforce that somehow???
*/
@EntityType(EntityClass.SYSTEM)
public interface SystemEventQueue extends Frame {
public static final String STREAM_START = Ontology.ACTIONER_HAS_LIFECYCLE_ACTION + "Stream";
@JavaHandler
public Iterable<SystemEvent> getSystemEvents();
abstract class Impl implements JavaHandlerContext<Vertex>, SystemEventQueue {
public Iterable<SystemEvent> getSystemEvents() {
Pipeline<Vertex,Vertex> otherPipe = gremlin().as("n")
.out(Ontology.ACTIONER_HAS_LIFECYCLE_ACTION)
.loop("n", JavaHandlerUtils.noopLoopFunc, JavaHandlerUtils.noopLoopFunc);
return frameVertices(gremlin()
.out(STREAM_START).cast(Vertex.class)
.copySplit(gremlin(), otherPipe)
.exhaustMerge().cast(Vertex.class));
}
}
}
| gpl-3.0 |
lrpirlet/Marlin | Marlin/src/HAL/STM32/eeprom_if_iic.cpp | 1610 | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
/**
* Platform-independent Arduino functions for I2C EEPROM.
* Enable USE_SHARED_EEPROM if not supplied by the framework.
*/
#ifdef STM32F1
#include "../../inc/MarlinConfig.h"
#if ENABLED(IIC_BL24CXX_EEPROM)
#include "../../libs/BL24CXX.h"
#include "../shared/eeprom_if.h"
void eeprom_init() { BL24CXX::init(); }
// ------------------------
// Public functions
// ------------------------
void eeprom_write_byte(uint8_t *pos, uint8_t value) {
const unsigned eeprom_address = (unsigned)pos;
return BL24CXX::writeOneByte(eeprom_address, value);
}
uint8_t eeprom_read_byte(uint8_t *pos) {
const unsigned eeprom_address = (unsigned)pos;
return BL24CXX::readOneByte(eeprom_address);
}
#endif // IIC_BL24CXX_EEPROM
#endif // STM32F1
| gpl-3.0 |
TexasLoki/Piston | src/main/java/org/pistonmc/exception/protocol/ProtocolNotFoundException.java | 305 | package org.pistonmc.exception.protocol;
public class ProtocolNotFoundException extends ProtocolException {
private static final long serialVersionUID = 396294565259799441L;
public ProtocolNotFoundException(int version) {
super(version, "Could not find Protocol v" + version);
}
}
| gpl-3.0 |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/vhdlFile/test_use_clause.py | 702 | import os
import unittest
from vsg import vhdlFile
from vsg.tests import utils
sLrmUnit = 'use_clause'
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(os.path.dirname(__file__), sLrmUnit,'classification_test_input.vhd'))
oFile = vhdlFile.vhdlFile(lFile)
class test_token(unittest.TestCase):
def test_classification(self):
sTestDir = os.path.join(os.path.dirname(__file__), sLrmUnit)
lExpected = []
utils.read_file(os.path.join(sTestDir, 'classification_results.txt'), lExpected, False)
lActual = []
for oObject in utils.extract_objects(oFile, True):
lActual.append(str(oObject))
self.assertEqual(lExpected, lActual)
| gpl-3.0 |
TypedScroll/Lovercraft.Pixel.Dungeon | core/src/main/java/com/shatteredpixel/lovecraftpixeldungeon/sprites/ItemSpriteSheet.java | 24554 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2016 Evan Debenham
*
* Lovecraft Pixel Dungeon
* Copyright (C) 2016-2017 Leon Horn
*
* 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 eben the implied warranty of
* GNU General Public License for more details.
*
* You should have have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/
package com.shatteredpixel.lovecraftpixeldungeon.sprites;
import com.shatteredpixel.lovecraftpixeldungeon.Assets;
import com.watabou.noosa.TextureFilm;
public class ItemSpriteSheet {
private static final int WIDTH = 16;
public static TextureFilm film = new TextureFilm( Assets.ITEMS, 16, 16 );
private static int xy(int x, int y){
x -= 1; y -= 1;
return x + WIDTH*y;
}
private static final int PLACEHOLDERS = xy(1, 1); //8 slots
//null warning occupies space 0, should only show up if there's a bug.
public static final int NULLWARN = PLACEHOLDERS+0;
public static final int WEAPON_HOLDER = PLACEHOLDERS+1;
public static final int ARMOR_HOLDER = PLACEHOLDERS+2;
public static final int RING_HOLDER = PLACEHOLDERS+3;
public static final int SOMETHING = PLACEHOLDERS+4;
public static final int HELMET = PLACEHOLDERS+5;
static {
for (int i = PLACEHOLDERS; i < PLACEHOLDERS+8; i++)
assignItemRect(i, 16, 16);
}
private static final int UNCOLLECTIBLE = xy(9, 1); //8 slots
public static final int GOLD = UNCOLLECTIBLE+0;
public static final int DEWDROP = UNCOLLECTIBLE+1;
public static final int PETAL = UNCOLLECTIBLE+2;
public static final int SANDBAG = UNCOLLECTIBLE+3;
public static final int DBL_BOMB = UNCOLLECTIBLE+4;
public static final int GREEN_DEWDROP = UNCOLLECTIBLE+5;
static{
assignItemRect(GOLD, 15, 13);
assignItemRect(DEWDROP, 10, 10);
assignItemRect(PETAL, 8, 8);
assignItemRect(SANDBAG, 10, 10);
assignItemRect(DBL_BOMB, 14, 13);
assignItemRect(GREEN_DEWDROP,10, 10);
}
private static final int CONTAINERS = xy(1, 2); //16 slots
public static final int BONES = CONTAINERS+0;
public static final int REMAINS = CONTAINERS+1;
public static final int TOMB = CONTAINERS+2;
public static final int GRAVE = CONTAINERS+3;
public static final int CHEST = CONTAINERS+4;
public static final int LOCKED_CHEST = CONTAINERS+5;
public static final int CRYSTAL_CHEST = CONTAINERS+6;
public static final int GOO_DROP_YELLOW = CONTAINERS+7;
public static final int GOO_DROP_RED = CONTAINERS+8;
public static final int GOO_DROP_PURPLE = CONTAINERS+9;
public static final int MONEY10 = CONTAINERS+10;
public static final int MONEY50 = CONTAINERS+11;
public static final int MONEY100 = CONTAINERS+12;
public static final int MONEY500 = CONTAINERS+13;
public static final int MONEY1000 = CONTAINERS+14;
static{
assignItemRect(BONES, 14, 11);
assignItemRect(REMAINS, 14, 11);
assignItemRect(TOMB, 14, 15);
assignItemRect(GRAVE, 14, 15);
assignItemRect(CHEST, 16, 15);
assignItemRect(LOCKED_CHEST, 16, 15);
assignItemRect(CRYSTAL_CHEST, 16, 15);
assignItemRect(CHEST, 16, 15);
assignItemRect(LOCKED_CHEST, 16, 15);
assignItemRect(CRYSTAL_CHEST, 16, 15);
assignItemRect(GOO_DROP_YELLOW, 16, 12);
assignItemRect(GOO_DROP_RED, 16, 12);
assignItemRect(GOO_DROP_PURPLE, 16, 12);
assignItemRect(MONEY10, 16, 8);
assignItemRect(MONEY50, 16, 13);
assignItemRect(MONEY100, 16, 14);
assignItemRect(MONEY500, 16, 15);
assignItemRect(MONEY1000, 16, 16);
}
private static final int SINGLE_USE = xy(1, 3); //32 slots
public static final int ANKH = SINGLE_USE+0;
public static final int STYLUS = SINGLE_USE+1;
public static final int WEIGHT = SINGLE_USE+2;
public static final int SEAL = SINGLE_USE+3;
public static final int TORCH = SINGLE_USE+4;
public static final int BEACON = SINGLE_USE+5;
public static final int BOMB = SINGLE_USE+6;
public static final int HONEYPOT = SINGLE_USE+7;
public static final int SHATTPOT = SINGLE_USE+8;
public static final int IRON_KEY = SINGLE_USE+9;
public static final int GOLDEN_KEY = SINGLE_USE+10;
public static final int SKELETON_KEY = SINGLE_USE+11;
public static final int MASTERY = SINGLE_USE+12;
public static final int KIT = SINGLE_USE+13;
public static final int AMULET = SINGLE_USE+14;
public static final int BLESSED_ANKH = SINGLE_USE+15;
static{
assignItemRect(ANKH, 10, 16);
assignItemRect(STYLUS, 12, 13);
assignItemRect(WEIGHT, 14, 12);
assignItemRect(SEAL, 9, 15);
assignItemRect(TORCH, 12, 15);
assignItemRect(BEACON, 16, 15);
assignItemRect(BOMB, 10, 13);
assignItemRect(HONEYPOT, 14, 12);
assignItemRect(SHATTPOT, 14, 12);
assignItemRect(IRON_KEY, 8, 14);
assignItemRect(GOLDEN_KEY, 8, 14);
assignItemRect(SKELETON_KEY, 8, 14);
assignItemRect(MASTERY, 13, 16);
assignItemRect(KIT, 16, 15);
assignItemRect(AMULET, 16, 16);
assignItemRect(BLESSED_ANKH, 10, 16);
}
//32 free slots
private static final int WEP_TIER1 = xy(1, 7); //8 slots
public static final int WORN_SHORTSWORD = WEP_TIER1+0;
public static final int CUDGEL = WEP_TIER1+1;
public static final int KNUCKLEDUSTER = WEP_TIER1+2;
public static final int MIGOSWORD = WEP_TIER1+3;
public static final int DAGGER = WEP_TIER1+4;
public static final int MAGES_STAFF = WEP_TIER1+5;
static{
assignItemRect(WORN_SHORTSWORD, 13, 13);
assignItemRect(KNUCKLEDUSTER, 15, 10);
assignItemRect(DAGGER, 12, 13);
assignItemRect(MAGES_STAFF, 15, 16);
assignItemRect(MIGOSWORD, 13, 13);
}
private static final int WEP_TIER2 = xy(9, 7); //8 slots
public static final int SHORTSWORD = WEP_TIER2+0;
public static final int HAND_AXE = WEP_TIER2+1;
public static final int SPEAR = WEP_TIER2+2;
public static final int QUARTERSTAFF = WEP_TIER2+3;
public static final int DIRK = WEP_TIER2+4;
static{
assignItemRect(SHORTSWORD, 13, 13);
assignItemRect(HAND_AXE, 12, 14);
assignItemRect(SPEAR, 16, 16);
assignItemRect(QUARTERSTAFF, 16, 16);
assignItemRect(DIRK, 13, 14);
}
private static final int WEP_TIER3 = xy(1, 8); //8 slots
public static final int SWORD = WEP_TIER3+0;
public static final int MACE = WEP_TIER3+1;
public static final int SCIMITAR = WEP_TIER3+2;
public static final int ROUND_SHIELD = WEP_TIER3+3;
public static final int SAI = WEP_TIER3+4;
public static final int WHIP = WEP_TIER3+5;
public static final int SCYTHE = WEP_TIER3+6;
static{
assignItemRect(SWORD, 14, 14);
assignItemRect(MACE, 15, 15);
assignItemRect(SCIMITAR, 13, 16);
assignItemRect(ROUND_SHIELD, 16, 16);
assignItemRect(SAI, 16, 16);
assignItemRect(WHIP, 14, 14);
assignItemRect(SCYTHE, 16, 16);
}
private static final int WEP_TIER4 = xy(9, 8); //8 slots
public static final int LONGSWORD = WEP_TIER4+0;
public static final int BATTLE_AXE = WEP_TIER4+1;
public static final int FLAIL = WEP_TIER4+2;
public static final int RUNIC_BLADE = WEP_TIER4+3;
public static final int ASSASSINS_BLADE = WEP_TIER4+4;
static{
assignItemRect(LONGSWORD, 15, 15);
assignItemRect(BATTLE_AXE, 16, 16);
assignItemRect(FLAIL, 14, 14);
assignItemRect(RUNIC_BLADE, 14, 14);
assignItemRect(ASSASSINS_BLADE, 14, 15);
}
private static final int WEP_TIER5 = xy(1, 9); //8 slots
public static final int GREATSWORD = WEP_TIER5+0;
public static final int WAR_HAMMER = WEP_TIER5+1;
public static final int GLAIVE = WEP_TIER5+2;
public static final int GREATAXE = WEP_TIER5+3;
public static final int GREATSHIELD = WEP_TIER5+4;
static{
assignItemRect(GREATSWORD, 16, 16);
assignItemRect(WAR_HAMMER, 16, 16);
assignItemRect(GLAIVE, 16, 16);
assignItemRect(GREATAXE, 12, 16);
assignItemRect(GREATSHIELD, 12, 16);
}
//8 free slots
private static final int MISSILE_WEP = xy(1, 10); //16 slots
public static final int DART = MISSILE_WEP+0;
public static final int BOOMERANG = MISSILE_WEP+1;
public static final int INCENDIARY_DART = MISSILE_WEP+2;
public static final int SHURIKEN = MISSILE_WEP+3;
public static final int CURARE_DART = MISSILE_WEP+4;
public static final int JAVELIN = MISSILE_WEP+5;
public static final int TOMAHAWK = MISSILE_WEP+6;
static{
assignItemRect(DART, 15, 15);
assignItemRect(BOOMERANG, 14, 14);
assignItemRect(INCENDIARY_DART, 15, 15);
assignItemRect(SHURIKEN, 12, 12);
assignItemRect(CURARE_DART, 15, 15);
assignItemRect(JAVELIN, 16, 16);
assignItemRect(TOMAHAWK, 13, 13);
}
private static final int ARMOR = xy(1, 11); //16 slots
public static final int ARMOR_CLOTH = ARMOR+0;
public static final int ARMOR_LEATHER = ARMOR+1;
public static final int ARMOR_MAIL = ARMOR+2;
public static final int ARMOR_SCALE = ARMOR+3;
public static final int ARMOR_PLATE = ARMOR+4;
public static final int ARMOR_WARRIOR = ARMOR+5;
public static final int ARMOR_MAGE = ARMOR+6;
public static final int ARMOR_ROGUE = ARMOR+7;
public static final int ARMOR_HUNTRESS = ARMOR+8;
public static final int MIGOCAP = ARMOR+9;
public static final int GOOCAP = ARMOR+10;
public static final int TOOTHCAP = ARMOR+11;
public static final int HADESHELMET = ARMOR+12;
static{
assignItemRect(ARMOR_CLOTH, 15, 12);
assignItemRect(ARMOR_LEATHER, 14, 13);
assignItemRect(ARMOR_MAIL, 14, 12);
assignItemRect(ARMOR_SCALE, 14, 11);
assignItemRect(ARMOR_PLATE, 12, 12);
assignItemRect(ARMOR_WARRIOR, 12, 12);
assignItemRect(ARMOR_MAGE, 15, 15);
assignItemRect(ARMOR_ROGUE, 14, 12);
assignItemRect(ARMOR_HUNTRESS, 13, 15);
assignItemRect(MIGOCAP, 15, 13);
assignItemRect(GOOCAP, 15, 13);
assignItemRect(TOOTHCAP, 15, 13);
assignItemRect(HADESHELMET, 16, 16);
}
//32 free slots
private static final int WANDS = xy(1, 14); //16 slots
public static final int WAND_MAGIC_MISSILE = WANDS+0;
public static final int WAND_FIREBOLT = WANDS+1;
public static final int WAND_FROST = WANDS+2;
public static final int WAND_LIGHTNING = WANDS+3;
public static final int WAND_DISINTEGRATION = WANDS+4;
public static final int WAND_PRISMATIC_LIGHT= WANDS+5;
public static final int WAND_VENOM = WANDS+6;
public static final int WAND_LIVING_EARTH = WANDS+7;
public static final int WAND_BLAST_WAVE = WANDS+8;
public static final int WAND_CORRUPTION = WANDS+9;
public static final int WAND_WARDING = WANDS+10;
public static final int WAND_REGROWTH = WANDS+11;
public static final int WAND_TRANSFUSION = WANDS+12;
static {
for (int i = WANDS; i < WANDS+16; i++)
assignItemRect(i, 14, 14);
}
private static final int RINGS = xy(1, 15); //16 slots
public static final int RING_GARNET = RINGS+0;
public static final int RING_RUBY = RINGS+1;
public static final int RING_TOPAZ = RINGS+2;
public static final int RING_EMERALD = RINGS+3;
public static final int RING_ONYX = RINGS+4;
public static final int RING_OPAL = RINGS+5;
public static final int RING_TOURMALINE = RINGS+6;
public static final int RING_SAPPHIRE = RINGS+7;
public static final int RING_AMETHYST = RINGS+8;
public static final int RING_QUARTZ = RINGS+9;
public static final int RING_AGATE = RINGS+10;
public static final int RING_DIAMOND = RINGS+11;
public static final int RING_FIREOPAL = RINGS+12;
static {
for (int i = RINGS; i < RINGS+16; i++)
assignItemRect(i, 8, 10);
}
private static final int ARTIFACTS = xy(1, 16); //32 slots
public static final int ARTIFACT_CLOAK = ARTIFACTS+0;
public static final int ARTIFACT_ARMBAND = ARTIFACTS+1;
public static final int ARTIFACT_CAPE = ARTIFACTS+2;
public static final int ARTIFACT_TALISMAN = ARTIFACTS+3;
public static final int ARTIFACT_HOURGLASS = ARTIFACTS+4;
public static final int ARTIFACT_TOOLKIT = ARTIFACTS+5;
public static final int ARTIFACT_SPELLBOOK = ARTIFACTS+6;
public static final int ARTIFACT_BEACON = ARTIFACTS+7;
public static final int ARTIFACT_CHAINS = ARTIFACTS+8;
public static final int ARTIFACT_HORN1 = ARTIFACTS+9;
public static final int ARTIFACT_HORN2 = ARTIFACTS+10;
public static final int ARTIFACT_HORN3 = ARTIFACTS+11;
public static final int ARTIFACT_HORN4 = ARTIFACTS+12;
public static final int ARTIFACT_CHALICE1 = ARTIFACTS+13;
public static final int ARTIFACT_CHALICE2 = ARTIFACTS+14;
public static final int ARTIFACT_CHALICE3 = ARTIFACTS+15;
public static final int ARTIFACT_SANDALS = ARTIFACTS+16;
public static final int ARTIFACT_SHOES = ARTIFACTS+17;
public static final int ARTIFACT_BOOTS = ARTIFACTS+18;
public static final int ARTIFACT_GREAVES = ARTIFACTS+19;
public static final int ARTIFACT_ROSE1 = ARTIFACTS+20;
public static final int ARTIFACT_ROSE2 = ARTIFACTS+21;
public static final int ARTIFACT_ROSE3 = ARTIFACTS+22;
public static final int ARTIFACT_STATUEPEPE1= ARTIFACTS+23;
public static final int ARTIFACT_STATUEPEPE2= ARTIFACTS+24;
public static final int ARTIFACT_STATUEPEPE3= ARTIFACTS+25;
public static final int ARTIFACT_PIPE = ARTIFACTS+26;
public static final int ARTIFACT_GRINDER = ARTIFACTS+27;
static{
assignItemRect(ARTIFACT_CLOAK, 9, 15);
assignItemRect(ARTIFACT_ARMBAND, 16, 13);
assignItemRect(ARTIFACT_CAPE, 16, 14);
assignItemRect(ARTIFACT_TALISMAN, 15, 13);
assignItemRect(ARTIFACT_HOURGLASS, 13, 16);
assignItemRect(ARTIFACT_TOOLKIT, 15, 13);
assignItemRect(ARTIFACT_SPELLBOOK, 13, 16);
assignItemRect(ARTIFACT_BEACON, 16, 16);
assignItemRect(ARTIFACT_CHAINS, 16, 16);
assignItemRect(ARTIFACT_HORN1, 15, 15);
assignItemRect(ARTIFACT_HORN2, 15, 15);
assignItemRect(ARTIFACT_HORN3, 15, 15);
assignItemRect(ARTIFACT_HORN4, 15, 15);
assignItemRect(ARTIFACT_CHALICE1, 12, 15);
assignItemRect(ARTIFACT_CHALICE2, 12, 15);
assignItemRect(ARTIFACT_CHALICE3, 12, 15);
assignItemRect(ARTIFACT_SANDALS, 16, 5 );
assignItemRect(ARTIFACT_SHOES, 16, 6 );
assignItemRect(ARTIFACT_BOOTS, 16, 9 );
assignItemRect(ARTIFACT_GREAVES, 16, 14);
assignItemRect(ARTIFACT_ROSE1, 14, 14);
assignItemRect(ARTIFACT_ROSE2, 14, 14);
assignItemRect(ARTIFACT_ROSE3, 14, 14);
assignItemRect(ARTIFACT_STATUEPEPE1,16, 16);
assignItemRect(ARTIFACT_STATUEPEPE2,16, 16);
assignItemRect(ARTIFACT_STATUEPEPE3,16, 16);
assignItemRect(ARTIFACT_PIPE, 16, 16);
assignItemRect(ARTIFACT_GRINDER, 16, 16);
}
private static final int SHROOMS = xy(1, 19); //16 slots
public static final int SHROOM_LANTERN = SHROOMS+0;
public static final int SHROOM_EGG = SHROOMS+1;
public static final int SHROOM_GREENWEED = SHROOMS+2;
public static final int SHROOM_FLYAGARIC = SHROOMS+3;
public static final int SHROOM_BLUE = SHROOMS+4;
public static final int SHROOM_ORANGE = SHROOMS+5;
public static final int SHROOM_BLUEWHITE = SHROOMS+6;
public static final int SHROOM_GREENRED = SHROOMS+7;
public static final int SHROOM_PURPLE = SHROOMS+8;
public static final int SHROOM_RED = SHROOMS+9;
static {
for (int i = SHROOMS; i < SHROOMS+16; i++)
assignItemRect(i, 16, 16);
}
//32 free slots
private static final int SCROLLS = xy(1, 20); //16 slots
public static final int SCROLL_KAUNAN = SCROLLS+0;
public static final int SCROLL_SOWILO = SCROLLS+1;
public static final int SCROLL_LAGUZ = SCROLLS+2;
public static final int SCROLL_YNGVI = SCROLLS+3;
public static final int SCROLL_GYFU = SCROLLS+4;
public static final int SCROLL_RAIDO = SCROLLS+5;
public static final int SCROLL_ISAZ = SCROLLS+6;
public static final int SCROLL_ALGIZ = SCROLLS+7;
public static final int SCROLL_NAUDIZ = SCROLLS+8;
public static final int SCROLL_BERKANAN = SCROLLS+9;
public static final int SCROLL_ODAL = SCROLLS+10;
public static final int SCROLL_TIWAZ = SCROLLS+11;
public static final int SCROLL_JERA = SCROLLS+12;
public static final int SCROLL_DAGAZ = SCROLLS+13;
public static final int SCROLL_EHWAZ = SCROLLS+14;
public static final int SCROLL_MANNAZ = SCROLLS+15;
static {
for (int i = SCROLLS; i < SCROLLS+16; i++)
assignItemRect(i, 15, 14);
}
private static final int POTIONS = xy(1, 21); //16 slots
public static final int POTION_CRIMSON = POTIONS+0;
public static final int POTION_AMBER = POTIONS+1;
public static final int POTION_GOLDEN = POTIONS+2;
public static final int POTION_JADE = POTIONS+3;
public static final int POTION_TURQUOISE= POTIONS+4;
public static final int POTION_AZURE = POTIONS+5;
public static final int POTION_INDIGO = POTIONS+6;
public static final int POTION_MAGENTA = POTIONS+7;
public static final int POTION_BISTRE = POTIONS+8;
public static final int POTION_CHARCOAL = POTIONS+9;
public static final int POTION_SILVER = POTIONS+10;
public static final int POTION_IVORY = POTIONS+11;
public static final int POTION_SICKGREEN= POTIONS+12;
public static final int POTION_AQUA = POTIONS+13;
public static final int POTION_DARKGREEN= POTIONS+14;
public static final int POTION_BLOODY = POTIONS+15;
static {
for (int i = POTIONS; i < POTIONS+16; i++)
assignItemRect(i, 10, 14);
}
private static final int SEEDS = xy(1, 22); //16 slots
public static final int SEED_ROTBERRY = SEEDS+0;
public static final int SEED_FIREBLOOM = SEEDS+1;
public static final int SEED_STARFLOWER = SEEDS+2;
public static final int SEED_BLINDWEED = SEEDS+3;
public static final int SEED_SUNGRASS = SEEDS+4;
public static final int SEED_ICECAP = SEEDS+5;
public static final int SEED_STORMVINE = SEEDS+6;
public static final int SEED_SORROWMOSS = SEEDS+7;
public static final int SEED_DREAMFOIL = SEEDS+8;
public static final int SEED_EARTHROOT = SEEDS+9;
public static final int SEED_FADELEAF = SEEDS+10;
public static final int SEED_BLANDFRUIT = SEEDS+11;
public static final int SEED_DEWCATCHER = SEEDS+12;
public static final int SEED_AQUA = SEEDS+13;
public static final int SEED_DARKGREEN = SEEDS+14;
public static final int SEED_BONEBLOOM = SEEDS+15;
static{
for (int i = SEEDS; i < SEEDS+16; i++)
assignItemRect(i, 10, 10);
}
//32 free slots
private static final int FOOD = xy(1, 25); //16 slots
public static final int MEAT = FOOD+0;
public static final int STEAK = FOOD+1;
public static final int OVERPRICED = FOOD+2;
public static final int CARPACCIO = FOOD+3;
public static final int BLANDFRUIT = FOOD+4;
public static final int RATION = FOOD+5;
public static final int PASTY = FOOD+6;
public static final int PUMPKIN_PIE = FOOD+7;
public static final int CANDY_CANE = FOOD+8;
public static final int MIGOEGG = FOOD+9;
public static final int ROTTEN_FLESH= FOOD+10;
public static final int TOOTH = FOOD+11;
public static final int MONGOEGG = FOOD+12;
static{
assignItemRect(MEAT, 15, 11);
assignItemRect(STEAK, 15, 11);
assignItemRect(OVERPRICED, 14, 11);
assignItemRect(CARPACCIO, 15, 11);
assignItemRect(BLANDFRUIT, 9, 12);
assignItemRect(RATION, 16, 12);
assignItemRect(PASTY, 16, 11);
assignItemRect(PUMPKIN_PIE, 16, 12);
assignItemRect(CANDY_CANE, 13, 16);
assignItemRect(MIGOEGG, 16, 14);
assignItemRect(ROTTEN_FLESH,15, 11);
assignItemRect(TOOTH, 16, 16);
assignItemRect(MONGOEGG, 16, 14);
}
private static final int QUEST = xy(1, 26); //32 slots
public static final int SKULL = QUEST+0;
public static final int DUST = QUEST+1;
public static final int CANDLE = QUEST+2;
public static final int EMBER = QUEST+3;
public static final int PICKAXE = QUEST+4;
public static final int ORE = QUEST+5;
public static final int TOKEN = QUEST+6;
public static final int IRONORE = QUEST+7;
public static final int ADAMANTORE = QUEST+8;
public static final int URANIUMORE = QUEST+9;
public static final int COPPERORE = QUEST+10;
public static final int COBALTORE = QUEST+11;
public static final int STICK = QUEST+12;
public static final int MIGOSCALE = QUEST+13;
public static final int SHOGGOTHSCAL= QUEST+14;
public static final int IRONBAR = QUEST+15;
static{
assignItemRect(SKULL, 16, 11);
assignItemRect(DUST, 12, 11);
assignItemRect(CANDLE, 12, 12);
assignItemRect(EMBER, 12, 11);
assignItemRect(PICKAXE, 14, 14);
assignItemRect(ORE, 15, 15);
assignItemRect(TOKEN, 12, 12);
assignItemRect(IRONORE, 16, 16);
assignItemRect(ADAMANTORE, 16, 16);
assignItemRect(URANIUMORE, 16, 16);
assignItemRect(COPPERORE, 16, 16);
assignItemRect(COBALTORE, 16, 16);
assignItemRect(STICK, 16, 16);
assignItemRect(MIGOSCALE, 11, 13);
assignItemRect(SHOGGOTHSCAL,16, 12);
assignItemRect(IRONBAR, 16, 16);
}
private static final int BAGS = xy(1, 28); //16 slots
public static final int VIAL = BAGS+0;
public static final int POUCH = BAGS+1;
public static final int HOLDER = BAGS+2;
public static final int BANDOLIER = BAGS+3;
public static final int HOLSTER = BAGS+4;
public static final int FOODBAG = BAGS+5;
public static final int WEAPONBAG = BAGS+6;
public static final int VIALF1 = BAGS+7;
public static final int VIALF2 = BAGS+8;
public static final int VIALF3 = BAGS+9;
public static final int WATERBAG = BAGS+10;
static{
assignItemRect(VIAL, 12, 12);
assignItemRect(POUCH, 14, 15);
assignItemRect(HOLDER, 16, 16);
assignItemRect(BANDOLIER, 15, 16);
assignItemRect(HOLSTER, 15, 16);
assignItemRect(FOODBAG, 14, 15);
assignItemRect(WEAPONBAG, 16, 16);
assignItemRect(VIALF1, 12, 12);
assignItemRect(VIALF2, 12, 12);
assignItemRect(VIALF3, 12, 12);
assignItemRect(WATERBAG, 16, 16);
}
//64 free slots
private static void assignItemRect( int item, int width, int height){
int x = (item % WIDTH) * WIDTH;
int y = (item / WIDTH) * WIDTH;
film.add( item, x, y, x+width, y+height);
}
}
| gpl-3.0 |
EdoMacchi/OF-dev | src/dynamicMesh/meshCut/splitCell/splitCell.C | 3516 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "splitCell.H"
#include "error.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
// Construct from cell number and parent
Foam::splitCell::splitCell(const label cellI, splitCell* parent)
:
cellI_(cellI),
parent_(parent),
master_(NULL),
slave_(NULL)
{}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
Foam::splitCell::~splitCell()
{
splitCell* myParent = parent();
if (myParent)
{
// Make sure parent does not refer to me anymore.
if (myParent->master() == this)
{
myParent->master() = NULL;
}
else if (myParent->slave() == this)
{
myParent->slave() = NULL;
}
else
{
FatalErrorInFunction
<< " parent's master or slave pointer" << endl
<< "Cell:" << cellLabel() << abort(FatalError);
}
}
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
bool Foam::splitCell::isMaster() const
{
splitCell* myParent = parent();
if (!myParent)
{
FatalErrorInFunction
<< "Cell:" << cellLabel() << abort(FatalError);
return false;
}
else if (myParent->master() == this)
{
return true;
}
else if (myParent->slave() == this)
{
return false;
}
else
{
FatalErrorInFunction
<< " parent's master or slave pointer" << endl
<< "Cell:" << cellLabel() << abort(FatalError);
return false;
}
}
bool Foam::splitCell::isUnrefined() const
{
return !master() && !slave();
}
Foam::splitCell* Foam::splitCell::getOther() const
{
splitCell* myParent = parent();
if (!myParent)
{
FatalErrorInFunction
<< "Cell:" << cellLabel() << abort(FatalError);
return NULL;
}
else if (myParent->master() == this)
{
return myParent->slave();
}
else if (myParent->slave() == this)
{
return myParent->master();
}
else
{
FatalErrorInFunction
<< " parent's master or slave pointer" << endl
<< "Cell:" << cellLabel() << abort(FatalError);
return NULL;
}
}
// ************************************************************************* //
| gpl-3.0 |
CrossRef/cocytus | cocytus-input.py | 1368 | from rq import Queue
from redis import Redis
import compare_change
import crossref_push
import socketIO_client
import time
import signal
import logging
from config import REDIS_LOCATION, HEARTBEAT_INTERVAL
logging.basicConfig(filename='logs/input.log', level=logging.INFO, format='%(asctime)s %(message)s')
logging.info('cocytus-input launched')
redis_con = Redis(host=REDIS_LOCATION)
queue = Queue('changes', connection = redis_con)
logging.info('redis connected')
alarm_interval = HEARTBEAT_INTERVAL # 10 minutes, in prime seconds
def alarm_handle(signal_number, current_stack_frame):
queue.enqueue(crossref_push.heartbeat)
logging.info('enqueued heartbeat')
signal.alarm(alarm_interval)
signal.signal(signal.SIGALRM, alarm_handle)
signal.siginterrupt(signal.SIGALRM, False)
signal.alarm(alarm_interval)
class WikiNamespace(socketIO_client.BaseNamespace):
def on_change(self, change):
logging.info(u"enqueing "+str(change))
while True:
try:
queue.enqueue(compare_change.get_changes, change)
break
except Exception as e:
logging.error(e.message)
time.sleep(1.0)
def on_connect(self):
self.emit(u"subscribe", u"*")
while True:
socketIO = socketIO_client.SocketIO(u'stream.wikimedia.org', 80)
socketIO.define(WikiNamespace, u'/rc')
socketIO.wait(HEARTBEAT_INTERVAL + 2) # 10 minutes, in prime seconds
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtbase/src/corelib/xml/qxmlutils.cpp | 15419 | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qstring.h>
#include "qxmlutils_p.h"
QT_BEGIN_NAMESPACE
/* TODO:
* - isNameChar() doesn't have to be public, it's only needed in
* qdom.cpp -- refactor fixedXmlName() to use isNCName()
* - A lot of functions can be inlined.
*/
class QXmlCharRange
{
public:
ushort min;
ushort max;
};
typedef const QXmlCharRange *RangeIter;
/*!
Performs a binary search between \a begin and \a end inclusive, to check whether \a
c is contained. Remember that the QXmlCharRange instances must be in numeric order.
*/
bool QXmlUtils::rangeContains(RangeIter begin, RangeIter end, const QChar c)
{
const ushort cp(c.unicode());
// check the first two ranges "manually" as characters in that
// range are checked very often and we avoid the binary search below.
if (cp <= begin->max)
return cp >= begin->min;
++begin;
if (begin == end)
return false;
if (cp <= begin->max)
return cp >= begin->min;
while (begin != end) {
int delta = (end - begin) / 2;
RangeIter mid = begin + delta;
if (mid->min > cp)
end = mid;
else if (mid->max < cp)
begin = mid;
else
return true;
if (delta == 0)
break;
}
return false;
}
// [85] BaseChar ::= ...
static const QXmlCharRange g_base_begin[] =
{
{0x0041, 0x005A}, {0x0061, 0x007A}, {0x00C0, 0x00D6}, {0x00D8, 0x00F6}, {0x00F8, 0x00FF},
{0x0100, 0x0131}, {0x0134, 0x013E}, {0x0141, 0x0148}, {0x014A, 0x017E}, {0x0180, 0x01C3},
{0x01CD, 0x01F0}, {0x01F4, 0x01F5}, {0x01FA, 0x0217}, {0x0250, 0x02A8}, {0x02BB, 0x02C1},
{0x0386, 0x0386}, {0x0388, 0x038A}, {0x038C, 0x038C}, {0x038E, 0x03A1}, {0x03A3, 0x03CE},
{0x03D0, 0x03D6}, {0x03DA, 0x03DA}, {0x03DC, 0x03DC}, {0x03DE, 0x03DE}, {0x03E0, 0x03E0},
{0x03E2, 0x03F3}, {0x0401, 0x040C}, {0x040E, 0x044F}, {0x0451, 0x045C}, {0x045E, 0x0481},
{0x0490, 0x04C4}, {0x04C7, 0x04C8}, {0x04CB, 0x04CC}, {0x04D0, 0x04EB}, {0x04EE, 0x04F5},
{0x04F8, 0x04F9}, {0x0531, 0x0556}, {0x0559, 0x0559}, {0x0561, 0x0586}, {0x05D0, 0x05EA},
{0x05F0, 0x05F2}, {0x0621, 0x063A}, {0x0641, 0x064A}, {0x0671, 0x06B7}, {0x06BA, 0x06BE},
{0x06C0, 0x06CE}, {0x06D0, 0x06D3}, {0x06D5, 0x06D5}, {0x06E5, 0x06E6}, {0x0905, 0x0939},
{0x093D, 0x093D}, {0x0958, 0x0961}, {0x0985, 0x098C}, {0x098F, 0x0990}, {0x0993, 0x09A8},
{0x09AA, 0x09B0}, {0x09B2, 0x09B2}, {0x09B6, 0x09B9}, {0x09DC, 0x09DD}, {0x09DF, 0x09E1},
{0x09F0, 0x09F1}, {0x0A05, 0x0A0A}, {0x0A0F, 0x0A10}, {0x0A13, 0x0A28}, {0x0A2A, 0x0A30},
{0x0A32, 0x0A33}, {0x0A35, 0x0A36}, {0x0A38, 0x0A39}, {0x0A59, 0x0A5C}, {0x0A5E, 0x0A5E},
{0x0A72, 0x0A74}, {0x0A85, 0x0A8B}, {0x0A8D, 0x0A8D}, {0x0A8F, 0x0A91}, {0x0A93, 0x0AA8},
{0x0AAA, 0x0AB0}, {0x0AB2, 0x0AB3}, {0x0AB5, 0x0AB9}, {0x0ABD, 0x0ABD}, {0x0AE0, 0x0AE0},
{0x0B05, 0x0B0C}, {0x0B0F, 0x0B10}, {0x0B13, 0x0B28}, {0x0B2A, 0x0B30}, {0x0B32, 0x0B33},
{0x0B36, 0x0B39}, {0x0B3D, 0x0B3D}, {0x0B5C, 0x0B5D}, {0x0B5F, 0x0B61}, {0x0B85, 0x0B8A},
{0x0B8E, 0x0B90}, {0x0B92, 0x0B95}, {0x0B99, 0x0B9A}, {0x0B9C, 0x0B9C}, {0x0B9E, 0x0B9F},
{0x0BA3, 0x0BA4}, {0x0BA8, 0x0BAA}, {0x0BAE, 0x0BB5}, {0x0BB7, 0x0BB9}, {0x0C05, 0x0C0C},
{0x0C0E, 0x0C10}, {0x0C12, 0x0C28}, {0x0C2A, 0x0C33}, {0x0C35, 0x0C39}, {0x0C60, 0x0C61},
{0x0C85, 0x0C8C}, {0x0C8E, 0x0C90}, {0x0C92, 0x0CA8}, {0x0CAA, 0x0CB3}, {0x0CB5, 0x0CB9},
{0x0CDE, 0x0CDE}, {0x0CE0, 0x0CE1}, {0x0D05, 0x0D0C}, {0x0D0E, 0x0D10}, {0x0D12, 0x0D28},
{0x0D2A, 0x0D39}, {0x0D60, 0x0D61}, {0x0E01, 0x0E2E}, {0x0E30, 0x0E30}, {0x0E32, 0x0E33},
{0x0E40, 0x0E45}, {0x0E81, 0x0E82}, {0x0E84, 0x0E84}, {0x0E87, 0x0E88}, {0x0E8A, 0x0E8A},
{0x0E8D, 0x0E8D}, {0x0E94, 0x0E97}, {0x0E99, 0x0E9F}, {0x0EA1, 0x0EA3}, {0x0EA5, 0x0EA5},
{0x0EA7, 0x0EA7}, {0x0EAA, 0x0EAB}, {0x0EAD, 0x0EAE}, {0x0EB0, 0x0EB0}, {0x0EB2, 0x0EB3},
{0x0EBD, 0x0EBD}, {0x0EC0, 0x0EC4}, {0x0F40, 0x0F47}, {0x0F49, 0x0F69}, {0x10A0, 0x10C5},
{0x10D0, 0x10F6}, {0x1100, 0x1100}, {0x1102, 0x1103}, {0x1105, 0x1107}, {0x1109, 0x1109},
{0x110B, 0x110C}, {0x110E, 0x1112}, {0x113C, 0x113C}, {0x113E, 0x113E}, {0x1140, 0x1140},
{0x114C, 0x114C}, {0x114E, 0x114E}, {0x1150, 0x1150}, {0x1154, 0x1155}, {0x1159, 0x1159},
{0x115F, 0x1161}, {0x1163, 0x1163}, {0x1165, 0x1165}, {0x1167, 0x1167}, {0x1169, 0x1169},
{0x116D, 0x116E}, {0x1172, 0x1173}, {0x1175, 0x1175}, {0x119E, 0x119E}, {0x11A8, 0x11A8},
{0x11AB, 0x11AB}, {0x11AE, 0x11AF}, {0x11B7, 0x11B8}, {0x11BA, 0x11BA}, {0x11BC, 0x11C2},
{0x11EB, 0x11EB}, {0x11F0, 0x11F0}, {0x11F9, 0x11F9}, {0x1E00, 0x1E9B}, {0x1EA0, 0x1EF9},
{0x1F00, 0x1F15}, {0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, {0x1F48, 0x1F4D}, {0x1F50, 0x1F57},
{0x1F59, 0x1F59}, {0x1F5B, 0x1F5B}, {0x1F5D, 0x1F5D}, {0x1F5F, 0x1F7D}, {0x1F80, 0x1FB4},
{0x1FB6, 0x1FBC}, {0x1FBE, 0x1FBE}, {0x1FC2, 0x1FC4}, {0x1FC6, 0x1FCC}, {0x1FD0, 0x1FD3},
{0x1FD6, 0x1FDB}, {0x1FE0, 0x1FEC}, {0x1FF2, 0x1FF4}, {0x1FF6, 0x1FFC}, {0x2126, 0x2126},
{0x212A, 0x212B}, {0x212E, 0x212E}, {0x2180, 0x2182}, {0x3041, 0x3094}, {0x30A1, 0x30FA},
{0x3105, 0x312C}, {0xAC00, 0xD7A3}
};
static const RangeIter g_base_end = g_base_begin + sizeof(g_base_begin) / sizeof(QXmlCharRange);
static const QXmlCharRange g_ideographic_begin[] =
{
{0x3007, 0x3007}, {0x3021, 0x3029}, {0x4E00, 0x9FA5}
};
static const RangeIter g_ideographic_end = g_ideographic_begin + sizeof(g_ideographic_begin) / sizeof(QXmlCharRange);
bool QXmlUtils::isIdeographic(const QChar c)
{
return rangeContains(g_ideographic_begin, g_ideographic_end, c);
}
static const QXmlCharRange g_combining_begin[] =
{
{0x0300, 0x0345}, {0x0360, 0x0361}, {0x0483, 0x0486}, {0x0591, 0x05A1}, {0x05A3, 0x05B9},
{0x05BB, 0x05BD}, {0x05BF, 0x05BF}, {0x05C1, 0x05C2}, {0x05C4, 0x05C4}, {0x064B, 0x0652},
{0x0670, 0x0670}, {0x06D6, 0x06DC}, {0x06DD, 0x06DF}, {0x06E0, 0x06E4}, {0x06E7, 0x06E8},
{0x06EA, 0x06ED}, {0x0901, 0x0903}, {0x093C, 0x093C}, {0x093E, 0x094C}, {0x094D, 0x094D},
{0x0951, 0x0954}, {0x0962, 0x0963}, {0x0981, 0x0983}, {0x09BC, 0x09BC}, {0x09BE, 0x09BE},
{0x09BF, 0x09BF}, {0x09C0, 0x09C4}, {0x09C7, 0x09C8}, {0x09CB, 0x09CD}, {0x09D7, 0x09D7},
{0x09E2, 0x09E3}, {0x0A02, 0x0A02}, {0x0A3C, 0x0A3C}, {0x0A3E, 0x0A3E}, {0x0A3F, 0x0A3F},
{0x0A40, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D}, {0x0A70, 0x0A71}, {0x0A81, 0x0A83},
{0x0ABC, 0x0ABC}, {0x0ABE, 0x0AC5}, {0x0AC7, 0x0AC9}, {0x0ACB, 0x0ACD}, {0x0B01, 0x0B03},
{0x0B3C, 0x0B3C}, {0x0B3E, 0x0B43}, {0x0B47, 0x0B48}, {0x0B4B, 0x0B4D}, {0x0B56, 0x0B57},
{0x0B82, 0x0B83}, {0x0BBE, 0x0BC2}, {0x0BC6, 0x0BC8}, {0x0BCA, 0x0BCD}, {0x0BD7, 0x0BD7},
{0x0C01, 0x0C03}, {0x0C3E, 0x0C44}, {0x0C46, 0x0C48}, {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56},
{0x0C82, 0x0C83}, {0x0CBE, 0x0CC4}, {0x0CC6, 0x0CC8}, {0x0CCA, 0x0CCD}, {0x0CD5, 0x0CD6},
{0x0D02, 0x0D03}, {0x0D3E, 0x0D43}, {0x0D46, 0x0D48}, {0x0D4A, 0x0D4D}, {0x0D57, 0x0D57},
{0x0E31, 0x0E31}, {0x0E34, 0x0E3A}, {0x0E47, 0x0E4E}, {0x0EB1, 0x0EB1}, {0x0EB4, 0x0EB9},
{0x0EBB, 0x0EBC}, {0x0EC8, 0x0ECD}, {0x0F18, 0x0F19}, {0x0F35, 0x0F35}, {0x0F37, 0x0F37},
{0x0F39, 0x0F39}, {0x0F3E, 0x0F3E}, {0x0F3F, 0x0F3F}, {0x0F71, 0x0F84}, {0x0F86, 0x0F8B},
{0x0F90, 0x0F95}, {0x0F97, 0x0F97}, {0x0F99, 0x0FAD}, {0x0FB1, 0x0FB7}, {0x0FB9, 0x0FB9},
{0x20D0, 0x20DC}, {0x20E1, 0x20E1}, {0x302A, 0x302F}, {0x3099, 0x3099}, {0x309A, 0x309A}
};
static const RangeIter g_combining_end = g_combining_begin + sizeof(g_combining_begin) / sizeof(QXmlCharRange);
bool QXmlUtils::isCombiningChar(const QChar c)
{
return rangeContains(g_combining_begin, g_combining_end, c);
}
// [88] Digit ::= ...
static const QXmlCharRange g_digit_begin[] =
{
{0x0030, 0x0039}, {0x0660, 0x0669}, {0x06F0, 0x06F9}, {0x0966, 0x096F}, {0x09E6, 0x09EF},
{0x0A66, 0x0A6F}, {0x0AE6, 0x0AEF}, {0x0B66, 0x0B6F}, {0x0BE7, 0x0BEF}, {0x0C66, 0x0C6F},
{0x0CE6, 0x0CEF}, {0x0D66, 0x0D6F}, {0x0E50, 0x0E59}, {0x0ED0, 0x0ED9}, {0x0F20, 0x0F29}
};
static const RangeIter g_digit_end = g_digit_begin + sizeof(g_digit_begin) / sizeof(QXmlCharRange);
bool QXmlUtils::isDigit(const QChar c)
{
return rangeContains(g_digit_begin, g_digit_end, c);
}
// [89] Extender ::= ...
static const QXmlCharRange g_extender_begin[] =
{
{0x00B7, 0x00B7}, {0x02D0, 0x02D0}, {0x02D1, 0x02D1}, {0x0387, 0x0387}, {0x0640, 0x0640},
{0x0E46, 0x0E46}, {0x0EC6, 0x0EC6}, {0x3005, 0x3005}, {0x3031, 0x3035}, {0x309D, 0x309E},
{0x30FC, 0x30FE}
};
static const RangeIter g_extender_end = g_extender_begin + sizeof(g_extender_begin) / sizeof(QXmlCharRange);
bool QXmlUtils::isExtender(const QChar c)
{
return rangeContains(g_extender_begin, g_extender_end, c);
}
bool QXmlUtils::isBaseChar(const QChar c)
{
return rangeContains(g_base_begin, g_base_end, c);
}
/*!
\internal
Determines whether \a encName is a valid instance of production [81]EncName in the XML 1.0
specification. If it is, true is returned, otherwise false.
\sa {http://www.w3.org/TR/REC-xml/#NT-EncName},
{Extensible Markup Language (XML) 1.0 (Fourth Edition), [81] EncName}
*/
bool QXmlUtils::isEncName(const QString &encName)
{
// Valid encoding names are given by "[A-Za-z][A-Za-z0-9._\\-]*"
const ushort *c = encName.utf16();
int l = encName.length();
if (l < 1 || !((c[0] >= 'a' && c[0] <= 'z') || (c[0] >= 'A' && c[0] <= 'Z')))
return false;
for (int i = 1; i < l; ++i) {
if ((c[i] >= 'a' && c[i] <= 'z')
|| (c[i] >= 'A' && c[i] <= 'Z')
|| (c[i] >= '0' && c[i] <= '9')
|| c[i] == '.' || c[i] == '_' || c[i] == '-')
continue;
return false;
}
return true;
}
/*!
\internal
Determines whether \a c is a valid instance of production [84]Letter in the XML 1.0
specification. If it is, true is returned, otherwise false.
\sa {http://www.w3.org/TR/REC-xml/#NT-Letter},
{Extensible Markup Language (XML) 1.0 (Fourth Edition), [84] Letter}
*/
bool QXmlUtils::isLetter(const QChar c)
{
return isBaseChar(c) || isIdeographic(c);
}
/*!
\internal
Determines whether \a c is a valid instance of production [2]Char in the XML 1.0
specification. If it is, true is returned, otherwise false.
\sa {http://www.w3.org/TR/REC-xml/#NT-Char},
{Extensible Markup Language (XML) 1.0 (Fourth Edition), [2] Char}
*/
bool QXmlUtils::isChar(const QChar c)
{
return (c.unicode() >= 0x0020 && c.unicode() <= 0xD7FF)
|| c.unicode() == 0x0009
|| c.unicode() == 0x000A
|| c.unicode() == 0x000D
|| (c.unicode() >= 0xE000 && c.unicode() <= 0xFFFD);
}
/*!
\internal
Determines whether \a c is a valid instance of
production [4]NameChar in the XML 1.0 specification. If it
is, true is returned, otherwise false.
\sa {http://www.w3.org/TR/REC-xml/#NT-NameChar},
{Extensible Markup Language (XML) 1.0 (Fourth Edition), [4] NameChar}
*/
bool QXmlUtils::isNameChar(const QChar c)
{
return isBaseChar(c)
|| isDigit(c)
|| c.unicode() == '.'
|| c.unicode() == '-'
|| c.unicode() == '_'
|| c.unicode() == ':'
|| isCombiningChar(c)
|| isIdeographic(c)
|| isExtender(c);
}
/*!
\internal
Determines whether \a c is a valid instance of
production [12] PubidLiteral in the XML 1.0 specification. If it
is, true is returned, otherwise false.
\sa {http://www.w3.org/TR/REC-xml/#NT-PubidLiteral},
{Extensible Markup Language (XML) 1.0 (Fourth Edition), [12] PubidLiteral}
*/
bool QXmlUtils::isPublicID(const QString &candidate)
{
const int len = candidate.length();
for(int i = 0; i < len; ++i)
{
const ushort cp = candidate.at(i).unicode();
if ((cp >= 'a' && cp <= 'z')
|| (cp >= 'A' && cp <= 'Z')
|| (cp >= '0' && cp <= '9'))
{
continue;
}
switch (cp)
{
/* Fallthrough all these. */
case 0x20:
case 0x0D:
case 0x0A:
case '-':
case '\'':
case '(':
case ')':
case '+':
case ',':
case '.':
case '/':
case ':':
case '=':
case '?':
case ';':
case '!':
case '*':
case '#':
case '@':
case '$':
case '_':
case '%':
continue;
default:
return false;
}
}
return true;
}
/*!
\internal
Determines whether \a c is a valid instance of
production [4]NCName in the XML 1.0 Namespaces specification. If it
is, true is returned, otherwise false.
\sa {http://www.w3.org/TR/REC-xml-names/#NT-NCName},
{W3CNamespaces in XML 1.0 (Second Edition), [4] NCName}
*/
bool QXmlUtils::isNCName(const QStringRef &ncName)
{
if(ncName.isEmpty())
return false;
const QChar first(ncName.at(0));
if(!QXmlUtils::isLetter(first) && first.unicode() != '_' && first.unicode() != ':')
return false;
const int len = ncName.size();
for(int i = 0; i < len; ++i)
{
const QChar at = ncName.at(i);
if(!QXmlUtils::isNameChar(at) || at == QLatin1Char(':'))
return false;
}
return true;
}
QT_END_NAMESPACE
| gpl-3.0 |
MikeMatt16/Abide | Abide.Guerilla/Abide.Tag.Cache/Generated/ScenarioDetailObjectCollectionPaletteBlock.Generated.cs | 2346 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Abide.Tag.Cache.Generated
{
using System;
using Abide.HaloLibrary;
using Abide.Tag;
/// <summary>
/// Represents the generated scenario_detail_object_collection_palette_block tag block.
/// </summary>
public sealed class ScenarioDetailObjectCollectionPaletteBlock : Block
{
/// <summary>
/// Initializes a new instance of the <see cref="ScenarioDetailObjectCollectionPaletteBlock"/> class.
/// </summary>
public ScenarioDetailObjectCollectionPaletteBlock()
{
this.Fields.Add(new TagReferenceField("Name^", 1685021283));
this.Fields.Add(new PadField("", 32));
}
/// <summary>
/// Gets and returns the name of the scenario_detail_object_collection_palette_block tag block.
/// </summary>
public override string Name
{
get
{
return "scenario_detail_object_collection_palette_block";
}
}
/// <summary>
/// Gets and returns the display name of the scenario_detail_object_collection_palette_block tag block.
/// </summary>
public override string DisplayName
{
get
{
return "scenario_detail_object_collection_palette_block";
}
}
/// <summary>
/// Gets and returns the maximum number of elements allowed of the scenario_detail_object_collection_palette_block tag block.
/// </summary>
public override int MaximumElementCount
{
get
{
return 32;
}
}
/// <summary>
/// Gets and returns the alignment of the scenario_detail_object_collection_palette_block tag block.
/// </summary>
public override int Alignment
{
get
{
return 4;
}
}
}
}
| gpl-3.0 |
Sw24Softwares/StarkeVerben | app/src/main/java/org/sw24softwares/starkeverben/Core/Settings.java | 1009 | package org.sw24softwares.starkeverben.Core;
import java.util.Vector;
public class Settings {
protected Vector<Verb> mVerbs;
protected String[] mFormStrings = new String[6];
protected Boolean mDebug = false;
public Settings() {
}
// Setters
public void setVerbs(Vector<Verb> verbs) {
mVerbs = verbs;
}
public void setFormString(int i, String s) {
mFormStrings[i] = s;
}
public void setDebug(Boolean d) {
mDebug = d;
}
// Getters
public Vector<Verb> getVerbs() {
return mVerbs;
}
public Verb getVerb(int i) {
for (Verb v : mVerbs)
if (v.getIndex() == i)
return v;
return null;
}
public String getFormString(int i) {
return mFormStrings[i];
}
public Boolean isDebug() {
return mDebug;
}
static private Settings mSingleton = new Settings();
static public Settings getSingleton() {
return mSingleton;
}
}
| gpl-3.0 |
l2jserver2/l2jserver2 | l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/model/template/character/CharacterRace.java | 828 | package com.l2jserver.model.template.character;
import javax.xml.bind.annotation.XmlType;
/**
* Represents the character race.
*
* @author <a href="http://www.rogiel.com">Rogiel</a>
*/
@XmlType(name = "CharacterRaceType")
@SuppressWarnings("javadoc")
public enum CharacterRace {
HUMAN(0x00), ELF(0x01), DARK_ELF(0x02), ORC(0x03), DWARF(0x04), KAMAEL(0x05);
/**
* The numeric ID representing this race
*/
public final int id;
/**
* @param id
* the race numeric id
*/
CharacterRace(int id) {
this.id = id;
}
/**
* Finds the race based on the <tt>id</tt>
*
* @param id
* the id
* @return the race constant
*/
public static CharacterRace fromOption(int id) {
for (final CharacterRace race : values()) {
if (race.id == id)
return race;
}
return null;
}
} | gpl-3.0 |
bengotow/electron-RxDB | spec/runner/index.js | 432 | import {app, BrowserWindow} from 'electron';
import Coordinator from '../../src/browser/coordinator';
global.databaseCoordinator = new Coordinator();
function createMainWindow() {
const win = new BrowserWindow({
width: 600,
height: 400,
show: false,
});
win.loadURL(`file://${__dirname}/index.html`);
win.once('ready-to-show', () => {
win.show();
})
}
app.on('ready', () => {
createMainWindow();
});
| gpl-3.0 |
Anonrate/AqScripts | src/AqScripts/Framework/Interfaces/IAqPainter.java | 4288 | package AqScripts.Framework.Interfaces;
import java.awt.*;
/**
* IAqPainter
*
* IAqPainter is Created and Coded by Anonrate, and is to be used only with the project AqScripts.
*
* Created and Coded on 4/14/2015.
* @author Anonrate
*/
public interface IAqPainter
{
/**
* Gets the { @link Color } of the line for the mouse paint.
*
* @return Returns the { @link Color } of the line for the mouse paint.
*/
Color getMouseLineColor();
/**
* Gets the decoration { @link Color } of the line for the mouse paint.
*
* @return Returns the decoration { @link Color } of the line for the mouse paint.
*/
Color getMouseLineDecorColor();
/**
* Gets the { @link Color } of the mouse point.
*
* @return Returns the { @link Color } of the mouse point.
*/
Color getMousePointColor();
/**
* Gets the normal { @link Font } { @link Color }.
*
* @return Returns the normal { @link Font } { @link Color }.
*/
Color getNormalFontColor();
/**
* Gets the { @link Font } { @link Color } for the status label.
*
* @return Returns the { @link Font } { @link Color } for the status label.
*/
Color getStatusLabelFontColor();
/**
* Gets and Sets the new { @link Color } of the line for the mouse paint.
*
* @param color The { @link Color } to change line of the mouse paint too.
*
* @return Returns the updated { @link Color } of the line for the mouse paint.
*/
Color setMouseLineColor(Color color);
/**
* Gets and Sets the new decoration { @link Color } for the line of the mouse paint.
*
* @param color The { @link Color } to change the decorated line of the mouse paint too.
*
* @return Returns the updated decorated { @link Color } for the line of the mouse paint.
*/
Color setMouseLineDecorColor(Color color);
/**
* Gets and Sets the { @link Color } of the mouse point.
*
* @param color The { @link Color } to change the mouse point too.
*
* @return Returns the updated { @link Color } of the mouse point.
*/
Color setMousePointColor(Color color);
/**
* Gets and Sets the new { @link Color } of the normal { @link Font }.
*
* @param color The { @link Color } to change the normal { @link Font } too.
*
* @return Returns the updated { @link Color } of the normal { @link Font }.
*/
Color setNormalFontColor(Color color);
/**
* Gets and Sets the { @link Color } of the { @link Font } for the status label.
*
* @param color The { @link Color } to change the { @link Font } of the status label too.
*
* @return Returns the updated { @link Color } for the { @link Font } of the status label.
*/
Color setStatusLabelFontColor(Color color);
/**
* Gets the { @link Font } for the normal text.
*
* @return Returns the { @link Font } of the normal text.
*/
Font getNormalFont();
/**
* Gets the { @link Font } for the status label text.
*
* @return Returns the { @link Font } of the status label text.
*/
Font getStatusLabelFont();
/**
* Gets the current duration of the script in milliseconds.
*
* @return Returns the current duration of the script in milliseconds.
*/
long getRuntime();
/**
* Gets the current status of the script.
*
* @return Returns the current status of the script.
*/
String getStatus();
/**
* Gets and Sets the status of the script.
*
* @param status The status to updated to scripts status too.
*
* @return Returns the updated scripts status.
*/
String setStatus(String status);
/**
* Formats the given amount of milliseconds into a more readable time format.
*
* @param mS The total amount of milliseconds to be converted into a time format.
* @return Returns the total given amount of milliseconds converted into a time format.
*/
String msToTime(long mS);
/**
* Creates a chained { @link Graphics2D } to be used a base paint for the derived Script.
*
* @param g1 The chained { @link Graphics2D }.
*/
void paint(Graphics g1);
}
| gpl-3.0 |
christophertfoo/TextEx | test/pages/AddPage.java | 6457 | /*
* Copyright (C) 2013 Christopher Foo
*
* 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/>.
*/
package pages;
import static org.junit.Assert.assertTrue;
import org.fluentlenium.core.FluentPage;
import org.openqa.selenium.WebDriver;
/**
* A {@link FluentPage} used to facilitate the testing of the TextEx application's add book page.
*
* @author Christopher
*
*/
public class AddPage extends FluentPage {
/**
* The URL of this {@link AddPage}.
*/
private String url;
/**
* Creates a new {@link AddPage}.
*
* @param webDriver The {@link WebDriver} used by the AddPage.
* @param port The port of localhost.
*/
public AddPage(WebDriver webDriver, int port) {
super(webDriver);
this.url = "http://localhost:" + port + "/addbook";
}
/**
* Clears all of the fields of the add book form.
*/
private void addFormClear() {
clear("#isbnInput");
clear("#titleInput");
clear("#authorsInput");
clear("#publisherInput");
clear("#editionInput");
clear("#priceInput");
}
/**
* Checks that an error message is raised when the user tries to add a bad book.
*
* @param test The test that cause the failure.
*/
private void checkAddFail(String test) {
click("#addSubmit");
assertTrue("Should print error message when could not add book. " + test, this.pageSource()
.contains("Error: Could not add the book! Are there errors in the form?"));
}
/**
* Gets the URL of this {@link AddPage}.
*/
@Override
public String getUrl() {
return this.url;
}
/**
* Checks that the user can navigate to the search / browse books page from the add book page.
*/
public void gotoSearch() {
this.click("#searchNav");
assertTrue("Should be at search page.", this.title().equals("Browse Books"));
}
/**
* Tests that invalid books are not added and an error message is raised.
*/
public void invalidAdd() {
int numInDb = models.Book.find().findList().size();
// Missing ISBN
this.addFormClear();
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
fill("#priceInput").with("39.99");
this.checkAddFail("(missing isbn)");
// Duplicate ISBN
this.addFormClear();
fill("#isbnInput").with("222-222-2222");
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
fill("#priceInput").with("39.99");
this.checkAddFail("(duplicate isbn)");
// Missing Title
this.addFormClear();
fill("#isbnInput").with("333-333-3333");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
fill("#priceInput").with("39.99");
this.checkAddFail("(missing title)");
// Missing Authors
this.addFormClear();
fill("#isbnInput").with("333-333-3333");
fill("#titleInput").with("My Book");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
fill("#priceInput").with("39.99");
this.checkAddFail("(missing authors)");
// Missing Publisher
this.addFormClear();
fill("#isbnInput").with("333-333-3333");
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#editionInput").with("2");
fill("#priceInput").with("39.99");
this.checkAddFail("(missing publisher)");
// Missing Price
this.addFormClear();
fill("#isbnInput").with("333-333-3333");
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
this.checkAddFail("(missing price)");
// Bad Price
this.addFormClear();
fill("#isbnInput").with("333-333-3333");
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
fill("#priceInput").with("-1");
this.checkAddFail("(bad price)");
// Bad Edition
this.addFormClear();
fill("#isbnInput").with("333-333-3333");
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("0");
fill("#priceInput").with("39.99");
this.checkAddFail("(bad edition)");
assertTrue("Should still have 2 books in database.",
models.Book.find().findList().size() == numInDb);
}
/**
* Determines if this page is actually at the add book page.
*/
@Override
public void isAt() {
assert (this.title().equals("Add Book"));
}
/**
* Tests that valid books are successfully added.
*/
public void validAdd() {
// Test with edition
fill("#isbnInput").with("111-111-1111");
fill("#titleInput").with("My Book");
fill("#authorsInput").with("Me");
fill("#publisherInput").with("UHM");
fill("#editionInput").with("2");
fill("#priceInput").with("39.99");
click("#addSubmit");
assertTrue("Should have success message when book is added.",
this.pageSource().contains("Successfully added the book!"));
assertTrue("New book should be in database", models.Book.find().findList().size() == 1);
// Test without edition
fill("#isbnInput").with("222-222-2222");
fill("#titleInput").with("Your Book");
fill("#authorsInput").with("You");
fill("#publisherInput").with("UHM");
fill("#priceInput").with("12.98");
click("#addSubmit");
assertTrue("Should have success message when book is added. (no edition)", this.pageSource()
.contains("Successfully added the book!"));
assertTrue("New book should be in database", models.Book.find().findList().size() == 2);
}
}
| gpl-3.0 |
murat-o/weddingdress | sw/code/app/task/ButtonPollTask.cpp | 1081 | /**
* @file ButtonPollTask.cpp
*
* @details Contains the implementation of the ButtonPollTask class.
*
* @author Murat Ozkan
*
* Wedfestdress Firmware 2017
*/
#include "ButtonPollTask.h"
namespace app {
namespace task {
//
// ButtonPollTask Public Member Definitions
//
ButtonPollTask::ButtonPollTask(hal::Timing& timing,
uint32_t interval_ms,
hal::Button& user_button,
hal::Button::ReadValue& user_button_value)
: Task(timing, interval_ms),
user_button_(user_button),
user_button_value_(user_button_value) { }
ButtonPollTask::~ButtonPollTask() { }
//
// Private Member Definitions
//
void ButtonPollTask::RunTask(void) {
hal::Button::ReadValue button_value = user_button_.Read();
// Only set the externally visible button value of it is not idle. This
// requires the consumer of the button value to reset it.
if (button_value != hal::Button::ReadValue::kNoPress) {
user_button_value_ = button_value;
}
}
} // namespace task
} // namespace app
| gpl-3.0 |
Devwarlt/LR-v1 | wServer/realm/World.cs | 13469 | #region
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using db.data;
using log4net;
using terrain;
using wServer.realm.entities;
using wServer.realm.entities.player;
#endregion
namespace wServer.realm
{
public abstract class World
{
public const int TUT_ID = -1;
public const int NEXUS_ID = -2;
public const int RAND_REALM = -3;
public const int NEXUS_LIMBO = -4;
public const int VAULT_ID = -5;
public const int TEST_ID = -6;
public const int GAUNTLET = -7;
public const int WC = -8;
public const int ARENA = -9;
public const int SHOP = -10;
public const int GHALL = -11;
public const int MARKET = -12;
public const int ARENA_FREE = -13;
public const int ARENA_PAID = -14;
public const int PETYARD = -15;
public const int LAIROFDRACONIS = -25;
public const int MINI_ONE = -30;
public const int NEXUS_VIP = -38;
public const int WINELER = -39;
public const int ADM_ID = -60;
public const int TOURNAMENT_ID = -111;
private static readonly ILog log = LogManager.GetLogger(typeof (World));
public string ExtraVar = "Default";
private int entityInc;
private RealmManager manager;
protected World()
{
Players = new ConcurrentDictionary<int, Player>();
Enemies = new ConcurrentDictionary<int, Enemy>();
Quests = new ConcurrentDictionary<int, Enemy>();
Pets = new ConcurrentDictionary<int, Entity>();
Projectiles = new ConcurrentDictionary<Tuple<int, byte>, Projectile>();
StaticObjects = new ConcurrentDictionary<int, StaticObject>();
Timers = new List<WorldTimer>();
ClientXML = ExtraXML = Empty<string>.Array;
Map = new Wmap();
AllowTeleport = true;
ShowDisplays = true;
ExtraXML = XmlDatas.ServerXmls.ToArray();
}
public void SetMusic(params string[] music)
{
Music = music;
}
public string GetMusic(wRandom rand)
{
if (Music != null && Music.Length > 0)
return Music[rand.Next(0, Music.Length)];
else
return "None";
}
public bool IsLimbo { get; protected set; }
public RealmManager Manager
{
get { return manager; }
internal set
{
manager = value;
if (manager != null)
Init();
}
}
public int Id { get; internal set; }
public string Name { get; protected set; }
public string[] Music { get; protected set; }
public bool entered = false;
public ConcurrentDictionary<int, Player> Players { get; private set; }
public ConcurrentDictionary<int, Enemy> Enemies { get; private set; }
public ConcurrentDictionary<int, Entity> Pets { get; private set; }
public ConcurrentDictionary<Tuple<int, byte>, Projectile> Projectiles { get; private set; }
public ConcurrentDictionary<int, StaticObject> StaticObjects { get; private set; }
//public ConcurrentDictionary<int, NewPet> NewPets { get; }
public List<WorldTimer> Timers { get; private set; }
public int Background { get; protected set; }
public CollisionMap<Entity> EnemiesCollision { get; private set; }
public CollisionMap<Entity> PlayersCollision { get; private set; }
public byte[,] Obstacles { get; private set; }
public bool AllowTeleport { get; protected set; }
public bool ShowDisplays { get; protected set; }
public string[] ClientXML { get; protected set; }
public string[] ExtraXML { get; protected set; }
public Wmap Map { get; private set; }
public ConcurrentDictionary<int, Enemy> Quests { get; private set; }
public virtual World GetInstance(ClientProcessor psr)
{
return null;
}
public bool IsPassable(int x, int y)
{
var tile = Map[x, y];
ObjectDesc desc;
if (XmlDatas.TileDescs[tile.TileId].NoWalk)
return false;
if (XmlDatas.ObjectDescs.TryGetValue(tile.ObjType, out desc))
{
if (!desc.Static)
return false;
}
return true;
}
public int GetNextEntityId()
{
return Interlocked.Increment(ref entityInc);
}
public bool Delete()
{
lock (this)
{
if (!entered) return false;
if (Players.Count > 0) return false;
if (this.Name != "Undead Lair" && this.Name != "Abyss of Demons" && this.Name != "Sprite World" && this.Name != "Forest Sanctuary" && this.Name != "The Eternal Crucible" && this.Name != "Christmas Cellar" && this.Name != "Christmas Cellar" && this.Name != "Sheep Herding Minigame" && this.Name != "Ocean Trench" && this.Name != "Party Cellar" && this.Name != "Tomb of the Ancients" && this.Name != "Wine Cellar" && this.Name != "Turkey Hunting Grounds" && this.Name != "Zombies Minigame") return false;
if (this is worlds.GameWorld) return false;
Id = 0;
}
World dummy;
RealmManager.Worlds.TryRemove(Id, out dummy);
return true;
}
public virtual void BehaviorEvent(string type)
{
}
protected virtual void Init()
{
}
protected void FromWorldMap(Stream dat)
{
log.InfoFormat("Loading map for world {0}({1})...", Id, Name);
var map = new Wmap();
Map = map;
entityInc = 0;
entityInc += Map.Load(dat, 0);
int w = Map.Width, h = Map.Height;
Obstacles = new byte[w, h];
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
{
var tile = Map[x, y];
ObjectDesc desc;
if (XmlDatas.TileDescs[tile.TileId].NoWalk)
Obstacles[x, y] = 3;
if (XmlDatas.ObjectDescs.TryGetValue(tile.ObjType, out desc))
{
if (desc.Class == "Wall" ||
desc.Class == "ConnectedWall" ||
desc.Class == "CaveWall")
Obstacles[x, y] = 2;
else if (desc.OccupySquare || desc.EnemyOccupySquare)
Obstacles[x, y] = 3;
}
}
EnemiesCollision = new CollisionMap<Entity>(0, w, h);
PlayersCollision = new CollisionMap<Entity>(1, w, h);
Projectiles.Clear();
StaticObjects.Clear();
Enemies.Clear();
Players.Clear();
foreach (var i in Map.InstantiateEntities(Manager))
{
if (i.ObjectDesc != null &&
(i.ObjectDesc.OccupySquare || i.ObjectDesc.EnemyOccupySquare))
Obstacles[(int) (i.X - 0.5), (int) (i.Y - 0.5)] = 2;
EnterWorld(i);
}
}
public void FromJsonMap(string file)
{
if (File.Exists(file))
{
var wmap = Json2Wmap.Convert(File.ReadAllText(file));
FromWorldMap(new MemoryStream(wmap));
}
else
{
throw new FileNotFoundException("Json file not found!", file);
}
}
public void FromJsonStream(Stream dat)
{
byte[] data = {};
dat.Read(data, 0, (int) dat.Length);
var json = Encoding.ASCII.GetString(data);
var wmap = Json2Wmap.Convert(json);
FromWorldMap(new MemoryStream(wmap));
} //not working
public virtual int EnterWorld(Entity entity)
{
if (entity is Player)
{
entity.Id = GetNextEntityId();
entity.Init(this);
Players.TryAdd(entity.Id, entity as Player);
PlayersCollision.Insert(entity);
entered = true;
}
else if (entity is Enemy)
{
entity.Id = GetNextEntityId();
entity.Init(this);
Enemies.TryAdd(entity.Id, entity as Enemy);
EnemiesCollision.Insert(entity);
if (entity.ObjectDesc.Quest)
Quests.TryAdd(entity.Id, entity as Enemy);
if (entity.isPet)
{
Pets.TryAdd(entity.Id, entity);
}
}
else if (entity is Projectile)
{
entity.Init(this);
var prj = entity as Projectile;
Projectiles[new Tuple<int, byte>(prj.ProjectileOwner.Self.Id, prj.ProjectileId)] = prj;
}
else if (entity is StaticObject)
{
entity.Id = GetNextEntityId();
entity.Init(this);
StaticObjects.TryAdd(entity.Id, entity as StaticObject);
if (entity is Decoy)
PlayersCollision.Insert(entity);
else
EnemiesCollision.Insert(entity);
}
return entity.Id;
}
public virtual void LeaveWorld(Entity entity)
{
if (entity is Player)
{
Player dummy;
Players.TryRemove(entity.Id, out dummy);
PlayersCollision.Remove(entity);
}
else if (entity is Enemy)
{
Enemy dummy;
Enemies.TryRemove(entity.Id, out dummy);
EnemiesCollision.Remove(entity);
if (entity.ObjectDesc.Quest)
Quests.TryRemove(entity.Id, out dummy);
if (entity.isPet)
{
Entity dummy2;
Pets.TryRemove(entity.Id, out dummy2);
}
}
else if (entity is Projectile)
{
var p = entity as Projectile;
Projectiles.TryRemove(new Tuple<int, byte>(p.ProjectileOwner.Self.Id, p.ProjectileId), out p);
}
else if (entity is StaticObject)
{
StaticObject dummy;
StaticObjects.TryRemove(entity.Id, out dummy);
if (entity is Decoy)
PlayersCollision.Remove(entity);
else
EnemiesCollision.Remove(entity);
}
entity.Owner = null;
}
public Entity GetEntity(int id)
{
Player ret1;
if (Players.TryGetValue(id, out ret1)) return ret1;
Enemy ret2;
if (Enemies.TryGetValue(id, out ret2)) return ret2;
StaticObject ret3;
if (StaticObjects.TryGetValue(id, out ret3)) return ret3;
return null;
}
public Player GetUniqueNamedPlayer(string name)
{
foreach (var i in Players)
{
if (i.Value.NameChosen && i.Value.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
return i.Value;
}
return null;
}
public Player GetUniqueNamedPlayerRough(string name)
{
foreach (var i in Players)
{
if (i.Value.CompareName(name))
return i.Value;
}
return null;
}
public void BroadcastPacket(Packet pkt, Player exclude)
{
foreach (var i in Players)
if (i.Value != exclude)
i.Value.Client.SendPacket(pkt);
}
public void BroadcastPackets(IEnumerable<Packet> pkts, Player exclude)
{
foreach (var i in Players)
if (i.Value != exclude)
i.Value.Client.SendPackets(pkts);
}
public virtual void Tick(RealmTime time)
{
if (IsLimbo) return;
for (var i = 0; i < Timers.Count; i++)
if (Timers[i].Tick(this, time))
{
Timers.RemoveAt(i);
i--;
}
foreach (var i in Players)
i.Value.Tick(time);
if (EnemiesCollision != null)
{
foreach (var i in EnemiesCollision.GetActiveChunks(PlayersCollision))
i.Tick(time);
foreach (var i in StaticObjects.Where(x => x.Value is Decoy))
i.Value.Tick(time);
}
else
{
foreach (var i in Enemies)
i.Value.Tick(time);
foreach (var i in StaticObjects)
i.Value.Tick(time);
}
foreach (var i in Projectiles)
i.Value.Tick(time);
}
}
} | gpl-3.0 |
finkrer/Snake | src/com/snake/main/model/cell/Wall.java | 158 | package com.snake.main.model.cell;
public class Wall extends Cell {
public Wall(int x, int y) {
super(x, y);
isWalkable = false;
}
}
| gpl-3.0 |
AURIN/online-whatif-ui | src/main/webapp/js/wif/setup/allocation/config/GrowthPatternCard.js | 8197 | Ext.define('Wif.setup.allocation.config.GrowthPatternCard', {
extend : 'Ext.form.Panel',
requires: [
'Wif.setup.allocation.config.AllocationConfigWizard',
'Ext.data.*',
'Ext.grid.*',
'Ext.tree.*',
'Ext.ux.CheckColumn',
'Wif.RESTObject'
],
project : null,
title : 'Growth Pattern Control Fields',
storeDataNew : [],
isEditing: true,
isLoadingExisting: true,
scenarioRows :[],
comboDataNew :[],
constructor : function(config) {
var me = this;
//this.preconstruct();
Ext.apply(this, config);
var projectId = me.project.projectId;
var isnew = me.project.isnew;
me.isLoadingExisting = true;
this.gridfields = [];
var modelfields = [];
modelfields.push("label");
modelfields.push("associatedALUs");
var gfield_id = {
text : "label",
dataIndex : "label",
editor: {
xtype: 'textfield',
allowBlank: false
}
};
var delColumns =
{
xtype : 'actioncolumn',
width : 26,
header: '',
sortable : false,
items : [{
iconCls : 'wif-grid-row-delete',
tooltip : 'Delete',
handler : function(grid, rowIndex, colIndex) {
grid.store.removeAt(rowIndex);
}
}]
};
this.combostore = Ext.create('Ext.data.Store', {
fields : ["_id", "label"],
data: this.comboDataNew
});
this.assocLuCbox = Ext.create('Wif.setup.UnionAttrComboBox', {
autoLoad: false
, multiSelect: false
, editable: true
, allowBlank: false
, projectId: this.project.projectId
, listeners: {
change: function(cbox,newValue,oldValue,opts) {
me.changeUnionAttr(cbox,newValue);
}
}
, callback: function () {
//me.mask.hide();
}
});
//
// this.assocLuCbox = Ext.create('Aura.Util.RemoteComboBox', {
// extend : 'Ext.form.field.ComboBox',
// fields : ["_id", "label", "featureFieldName"],
// valueField : "label",
// displayField : "label",
// emptyText : "Select Existing Land Uses",
// multiSelect : false,
// forceSelection : true,
// typeAhead : false,
// editable : false,
// queryMode : 'local',
// displayTpl : '<tpl for=".">' + // for multiSelect
// '{label}<tpl if="xindex < xcount">,</tpl>' + '</tpl>',
// listConfig : {
// getInnerTpl : function() {
// return '<div class="x-combo-list-item"><img src="' + Ext.BLANK_IMAGE_URL + '" class="chkCombo-default-icon chkCombo" /> {label} </div>';
// }
// },
// serviceParams : {
// xdomain : "cors",
// url : Wif.endpoint + 'projects/' + projectId + '/unionAttributes/',
// method : "get",
// params : null,
// headers : {
// "X-AURIN-USER-ID" : Wif.userId
// }
// }
// });
var gfield = {
xtype: 'gridcolumn',
text : "field name",
flex : 2,
dataIndex : "associatedALUs",
editor: this.assocLuCbox
};
this.gridfields.push(gfield_id);
this.gridfields.push(gfield);
this.gridfields.push(delColumns);
this.model = Ext.define('User', {
extend: 'Ext.data.Model',
fields: modelfields
});
this.store = Ext.create('Ext.data.Store', {
model: this.model,
data : this.storeDataNew
});
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
clicksToEdit: 1
});
var cellEditor = Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit : 1
});
this.grid = Ext.create('Ext.grid.Panel', {
store: this.store,
//selType: 'cellmodel',
columns : this.gridfields,
height: 500,
width: 800,
flex: 1,
dockedItems: [{
xtype: 'toolbar',
items: [{
text:'Add New Item',
tooltip:'Add a new row',
handler : function() {
var grid = this.findParentByType('grid');
var store = grid.getStore();
var gridCount = store.getCount();
var datafield = {
"label" : "",
"associatedALUs" : [""]
};
store.insert(gridCount,datafield);
cellEditor.startEdit(gridCount, 0);
}
}],
}],
plugins: [cellEditor]
});
this.items = [this.grid];
this.callParent(arguments);
},
listeners : {
activate : function() {
_.log(this, 'activate');
this.build();
}
},
build : function() {
var me = this, projectId = this.project.projectId;
me.isLoadingExisting = true;
// me.assocLuCbox.serviceParams.url = Wif.endpoint + 'projects/' + projectId + '/unionAttributes/';
me.assocLuCbox.load(projectId);
me.loadRows( function () {
me.fillcombo(function () {
if (callback) { callback(); }
});
});
},
fillcombo : function(callback) {
var me = this;
me.storeDataNew = [];
var definition = me.project.getDefinition();
if (!(definition.growthPatternALUs == undefined))
{
var rows = definition.growthPatternALUs;
for (var i = 0; i< rows.length; i++)
{
var datafield = {
"label" : rows[i].label,
"associatedALUs" : rows[i].fieldName
};
me.storeDataNew.push(datafield);
}
}
for (var i = 0; i < me.scenarioRows.count(); i++)
{
var datacmb = {
"label" : me.scenarioRows[i].label
};
me.comboDataNew.push(datacmb);
// me.storeDataNew.push(datafield);
}
me.store.removeAll();
me.combostore.removeAll();
if (me.combostore.data.length==0)
{
me.combostore.loadData(me.comboDataNew);
}
me.store.loadData(me.storeDataNew);
this.grid.reconfigure(me.store, me.gridfields);
if (callback) { callback(); }
},
validate : function(callback) {
var me = this;
var cnt = me.store.data.length;
var indx = 1;
var str='[';
me.store.each(function(record,idx){
val = record.get('label');
val1 = record.get('associatedALUs');
plannedALUs =[];
str= str + '{' + '\"' + 'label' + '\"' + ':' + '\"' + val + '\"' + ',' + '\"' + 'fieldName' + '\"' + ':' + '\"' + val1 + '\"';
if (indx < cnt)
{
str= str + '},';
}
else
{
str= str + '}';
}
indx = indx + 1;
});
str = str +"]";
var definition = me.project.getDefinition();
Ext.merge(definition, {
growthPatternALUs : JSON.parse(str)
});
me.project.setDefinition(definition);
//allocationColumnsMap
var definition = me.project.getDefinition();
Ext.merge(definition, {
allocationColumnsMap : JSON.parse('{}')
});
me.project.setDefinition(definition);
//
//undevelopedLUsColumns
var definition = me.project.getDefinition();
Ext.merge(definition, {
undevelopedLUsColumns : JSON.parse('[]')
});
me.project.setDefinition(definition);
if (callback) {
callback();
}
},
loadRows: function (callback) {
_.log(me, '333333');
var me = this;
_.log(me, 'loading rows', me);
var serviceParams = {
xdomain: "cors"
, url: Wif.endpoint + 'projects/' + me.project.projectId + '/unionAttributes/'
, method: "get"
, headers: {
"X-AURIN-USER-ID": Wif.userId
}
};
function serviceHandler(data, status) {
_.log(me, 'loaded rows before', me);
me.scenarioRows = data;
_.log(me, 'loaded rows after', me.scenarioRows);
//me.show();
if (callback) { callback(); }
}
Aura.data.Consumer.getBridgedService(serviceParams, serviceHandler, 0);
}
});
| gpl-3.0 |
PengLiangWang/Scala | function/factorial.scala | 263 | object factorial{
def main(args: Array[String])
{
for(i <- 1 to 20)
println(i + "的阶乘为: " + fact(i));
}
def fact(n: BigInt) : BigInt = {
if(n < 1)
1
else
n * fact(n-1)
}
}
| gpl-3.0 |
grze/parentheses | clc/modules/cluster-manager/src/main/java/com/eucalyptus/compute/ComputeServiceException.java | 3625 | /*************************************************************************
* Copyright 2009-2013 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
************************************************************************
* @author chris grzegorczyk <grze@eucalyptus.com>
*/
package com.eucalyptus.compute;
import com.eucalyptus.ws.EucalyptusWebServiceException;
import com.eucalyptus.ws.Role;
public class ComputeServiceException extends EucalyptusWebServiceException {
public ComputeServiceException( String code, Role sender, String message ) {
super( code, sender, message );
}
}
| gpl-3.0 |
kozzeluc/dmlj | Eclipse CA IDMS Schema Diagram Editor/bundles/org.lh.dmlj.schema.editor.dictionary.tools/src/org/lh/dmlj/schema/editor/dictionary/tools/template/AreaProcedureListQueryTemplate.java | 2650 | package org.lh.dmlj.schema.editor.dictionary.tools.template;
public class AreaProcedureListQueryTemplate implements IQueryTemplate {
protected static String nl;
public static synchronized AreaProcedureListQueryTemplate create(String lineSeparator)
{
nl = lineSeparator;
AreaProcedureListQueryTemplate result = new AreaProcedureListQueryTemplate();
nl = null;
return result;
}
public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
protected final String TEXT_1 = "SELECT S_010.ROWID AS S_010_ROWID," + NL + " SA_018.ROWID AS SA_018_ROWID," + NL + " SACALL_020.ROWID AS SACALL_020_ROWID," + NL + " * " + NL + "FROM \"";
protected final String TEXT_2 = "\".\"S-010\" AS S_010," + NL + " \"";
protected final String TEXT_3 = "\".\"SA-018\" AS SA_018," + NL + " \"";
protected final String TEXT_4 = "\".\"SACALL-020\" AS SACALL_020" + NL + "WHERE S_NAM_010 = '";
protected final String TEXT_5 = "' AND S_SER_010 = ";
protected final String TEXT_6 = " AND " + NL + " \"S-SA\" AND" + NL + " \"SA-SACALL\"";
public String generate(Object argument)
{
final StringBuffer stringBuffer = new StringBuffer();
/**
* Copyright (C) 2014 Luc Hermans
*
* 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/>.
*
* Contact information: kozzeluc@gmail.com.
*/
Object[] args = (Object[]) argument;
String sysdirlSchema = (String) args[0];
String schemaName = (String) args[1];
int schemaVersion = ((Integer) args[2]).intValue();
stringBuffer.append(TEXT_1);
stringBuffer.append( sysdirlSchema );
stringBuffer.append(TEXT_2);
stringBuffer.append( sysdirlSchema );
stringBuffer.append(TEXT_3);
stringBuffer.append( sysdirlSchema );
stringBuffer.append(TEXT_4);
stringBuffer.append( schemaName );
stringBuffer.append(TEXT_5);
stringBuffer.append( schemaVersion );
stringBuffer.append(TEXT_6);
return stringBuffer.toString();
}
} | gpl-3.0 |
12307/BlackLight | app/src/main/java/us/shandian/blacklight/ui/common/MultiPicturePicker.java | 3141 | /*
* Copyright (C) 2014 Peter Cai
*
* This file is part of BlackLight
*
* BlackLight 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.
*
* BlackLight 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 BlackLight. If not, see <http://www.gnu.org/licenses/>.
*/
package us.shandian.blacklight.ui.common;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import java.util.ArrayList;
import us.shandian.blacklight.R;
import us.shandian.blacklight.model.GalleryModel;
import us.shandian.blacklight.support.Utility;
import us.shandian.blacklight.support.adapter.GalleryAdapter;
import static us.shandian.blacklight.BuildConfig.DEBUG;
public class MultiPicturePicker extends AbsActivity {
private static final String TAG = MultiPicturePicker.class.getSimpleName();
public static final int PICK_OK = 123456;
private GridView mGrid;
private GalleryAdapter mAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
mLayout = R.layout.img_picker;
super.onCreate(savedInstanceState);
// Views
mGrid = Utility.findViewById(this, R.id.picker_grid);
buildAdapter();
mGrid.setAdapter(mAdapter);
mGrid.setOnItemClickListener(mAdapter);
mGrid.setFastScrollEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.picker, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.pick_ok:
ArrayList<String> res = mAdapter.getChecked();
Intent i = new Intent();
i.putStringArrayListExtra("img", res);
setResult(PICK_OK, i);
finish();
default:
return super.onOptionsItemSelected(item);
}
}
private void buildAdapter() {
ArrayList<GalleryModel> model = new ArrayList<GalleryModel>();
try {
String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_ADDED};
String orderBy = MediaStore.Images.Media.DATE_ADDED + " DESC";
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GalleryModel m = new GalleryModel();
m.path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
if (DEBUG) {
Log.d(TAG, "m.path = " + m.path);
}
model.add(m);
}
}
} catch (Exception e) {
}
mAdapter = new GalleryAdapter(this, model);
}
}
| gpl-3.0 |
brangerbriz/webroutes | nw-app/telegeography-data/internetexchanges/internet-exchanges/inxs-munich-germany.js | 665 | {"address":["INXS (Munich, Germany)","Landsbergerstrasse 155","Munich, Germany, 80687"],"buildings":[{"latitude":"48.1403474","address":["Landsbergerstrasse 155","Munich, Germany, 80687"],"longitude":"11.5256034","offset":"background:url('images/markers.png') no-repeat -22px 0;","id":8119}],"name":"INXS (Munich, Germany)","id":"inxs-munich-germany","exchange_info":[{"onclick":null,"link":null,"value":"49 89 92699 111"},{"onclick":null,"link":"mailto:info@inxs.de","value":"info@inxs.de"},{"onclick":"window.open(this.href,'ix-new-window');return false;","link":"http://www.inxs.de","value":"Website"},{"onclick":null,"link":null,"value":"Online since: 1994"}]} | gpl-3.0 |
villagedefrance/OpenCart-Overclocked | upload/catalog/model/payment/pp_express.php | 15315 | <?php
class ModelPaymentPPExpress extends Model {
public function getMethod($address, $total) {
$this->language->load('payment/pp_express');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('pp_express_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('pp_express_total') > 0 && $this->config->get('pp_express_total') > $total) {
$status = false;
} elseif ($this->config->has('pp_express_total_max') && $this->config->get('pp_express_total_max') > 0 && $total > $this->config->get('pp_express_total_max')) {
$status = false;
} elseif (!$this->config->get('pp_express_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'pp_express',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('pp_express_sort_order')
);
}
return $method_data;
}
public function addOrder($order_data) {
// 1 to 1 relationship with order table (extends order info)
$this->db->query("INSERT INTO " . DB_PREFIX . "paypal_order SET "
. "order_id = " . (isset($order_data['order_id']) ? (int)$order_data['order_id'] : 0) . ", "
. "created = NOW(), "
. "modified = NOW(), "
. "capture_status = '" . (isset($order_data['capture_status']) ? $this->db->escape($order_data['capture_status']) : null) . "', "
. "currency_code = '" . (isset($order_data['currency_code']) ? $this->db->escape($order_data['currency_code']) : null) . "', "
. "total = " . (isset($order_data['total']) ? (double)$order_data['total'] : 0.0) . ", "
. "authorization_id = '" . (isset($order_data['authorization_id']) ? $this->db->escape($order_data['authorization_id']) : null) . "'");
return $this->db->getLastId();
}
public function addTransaction($transaction_data) {
$this->db->query("INSERT INTO " . DB_PREFIX . "paypal_order_transaction SET "
. "paypal_order_id = " . (isset($transaction_data['paypal_order_id']) ? (int)$transaction_data['paypal_order_id'] : 0) . ", "
. "transaction_id = '" . (isset($transaction_data['transaction_id']) ? $this->db->escape($transaction_data['transaction_id']) : null) . "', "
. "parent_transaction_id = '" . (isset($transaction_data['parent_transaction_id']) ? $this->db->escape($transaction_data['parent_transaction_id']) : null) . "', "
. "created = NOW(), "
. "note = '" . (isset($transaction_data['note']) ? $this->db->escape($transaction_data['note']) : null) . "', "
. "msgsubid = '" . (isset($transaction_data['msgsubid']) ? $this->db->escape($transaction_data['msgsubid']) : null) . "', "
. "receipt_id = '" . (isset($transaction_data['receipt_id']) ? $this->db->escape($transaction_data['receipt_id']) : null) . "', "
. "payment_type = '" . (isset($transaction_data['payment_type']) ? $this->db->escape($transaction_data['payment_type']) : null) . "', "
. "payment_status = '" . (isset($transaction_data['payment_status']) ? $this->db->escape($transaction_data['payment_status']) : null) . "', "
. "pending_reason = '" . (isset($transaction_data['pending_reason']) ? $this->db->escape($transaction_data['pending_reason']) : null) . "', "
. "transaction_entity = '" . (isset($transaction_data['transaction_entity']) ? $this->db->escape($transaction_data['transaction_entity']) : null) . "', "
. "amount = " . (isset($transaction_data['amount']) ? (double)$transaction_data['amount'] : 0.0) . ", "
. "debug_data = '" . (isset($transaction_data['debug_data']) ? $this->db->escape($transaction_data['debug_data']) : null) . "'");
}
public function paymentRequestInfo() {
$data['PAYMENTREQUEST_0_SHIPPINGAMT'] = '';
$data['PAYMENTREQUEST_0_CURRENCYCODE'] = $this->currency->getCode();
$data['PAYMENTREQUEST_0_PAYMENTACTION'] = $this->config->get('pp_express_transaction_method');
$i = 0;
$item_total = 0;
foreach ($this->cart->getProducts() as $item) {
$data['L_PAYMENTREQUEST_0_DESC' . $i] = '';
$option_count = 0;
foreach ($item['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['option_value'];
} else {
$filename = $this->encryption->decrypt($option['option_value']);
$value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
}
$data['L_PAYMENTREQUEST_0_DESC' . $i] .= ($option_count > 0 ? ', ' : '') . $option['name'] . ':' . (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value);
$option_count++;
}
$data['L_PAYMENTREQUEST_0_DESC' . $i] = substr($data['L_PAYMENTREQUEST_0_DESC' . $i], 0, 126);
$item_price = $this->currency->format($item['price'], false, false, false);
$data['L_PAYMENTREQUEST_0_NAME' . $i] = $item['name'];
$data['L_PAYMENTREQUEST_0_NUMBER' . $i] = $item['model'];
$data['L_PAYMENTREQUEST_0_AMT' . $i] = $item_price;
$item_total += number_format($item_price * $item['quantity'], 2, '.', '');
$data['L_PAYMENTREQUEST_0_QTY' . $i] = $item['quantity'];
$data['L_PAYMENTREQUEST_0_ITEMURL' . $i] = $this->url->link('product/product', 'product_id=' . $item['product_id'], 'SSL');
if ($this->config->get('config_cart_weight')) {
$weight = $this->weight->convert($item['weight'], $item['weight_class_id'], $this->config->get('config_weight_class_id'));
$data['L_PAYMENTREQUEST_0_ITEMWEIGHTVALUE' . $i] = number_format($weight / $item['quantity'], 2, '.', '');
$data['L_PAYMENTREQUEST_0_ITEMWEIGHTUNIT' . $i] = $this->weight->getUnit($this->config->get('config_weight_class_id'));
}
if ($item['length'] > 0 || $item['width'] > 0 || $item['height'] > 0) {
$unit = $this->length->getUnit($item['length_class_id']);
$data['L_PAYMENTREQUEST_0_ITEMLENGTHVALUE' . $i] = $item['length'];
$data['L_PAYMENTREQUEST_0_ITEMLENGTHUNIT' . $i] = $unit;
$data['L_PAYMENTREQUEST_0_ITEMWIDTHVALUE' . $i] = $item['width'];
$data['L_PAYMENTREQUEST_0_ITEMWIDTHUNIT' . $i] = $unit;
$data['L_PAYMENTREQUEST_0_ITEMHEIGHTVALUE' . $i] = $item['height'];
$data['L_PAYMENTREQUEST_0_ITEMHEIGHTUNIT' . $i] = $unit;
}
$i++;
}
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $voucher) {
$item_total += $this->currency->format($voucher['amount'], false, false, false);
$data['L_PAYMENTREQUEST_0_DESC' . $i] = '';
$data['L_PAYMENTREQUEST_0_NAME' . $i] = $voucher['description'];
$data['L_PAYMENTREQUEST_0_NUMBER' . $i] = 'VOUCHER';
$data['L_PAYMENTREQUEST_0_QTY' . $i] = 1;
$data['L_PAYMENTREQUEST_0_AMT' . $i] = $this->currency->format($voucher['amount'], false, false, false);
$i++;
}
}
// Totals
$this->load->model('setting/extension');
$total_data = array();
$taxes = $this->cart->getTaxes();
$total = 0;
// Display prices
if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('total/' . $result['code']);
$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
}
$sort_order = array();
foreach ($total_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $total_data);
}
}
foreach ($total_data as $total_row) {
if (!in_array($total_row['code'], array('total', 'sub_total'))) {
if ($total_row['value'] != 0) {
$item_price = $this->currency->format($total_row['value'], false, false, false);
$data['L_PAYMENTREQUEST_0_NUMBER' . $i] = $total_row['code'];
$data['L_PAYMENTREQUEST_0_NAME' . $i] = $total_row['title'];
$data['L_PAYMENTREQUEST_0_AMT' . $i] = $this->currency->format($total_row['value'], false, false, false);
$data['L_PAYMENTREQUEST_0_QTY' . $i] = 1;
$item_total = $item_total + $item_price;
$i++;
}
}
}
$data['PAYMENTREQUEST_0_ITEMAMT'] = number_format($item_total, 2, '.', '');
$data['PAYMENTREQUEST_0_AMT'] = number_format($item_total, 2, '.', '');
$z = 0;
$recurring_products = $this->cart->getRecurringProducts();
if (!empty($recurring_products)) {
$this->language->load('payment/pp_express');
foreach ($recurring_products as $item) {
$data['L_BILLINGTYPE' . $z] = 'RecurringPayments';
if ($item['recurring_trial'] == 1) {
$trial_amt = $this->currency->format($this->tax->calculate($item['recurring_trial_price'], $item['tax_class_id'], $this->config->get('config_tax')), false, false, false) * $item['quantity'] . ' ' . $this->currency->getCode();
$trial_text = sprintf($this->language->get('text_trial'), $trial_amt, $item['recurring_trial_cycle'], $item['recurring_trial_frequency'], $item['recurring_trial_duration']);
} else {
$trial_text = '';
}
$recurring_amt = $this->currency->format($this->tax->calculate($item['recurring_price'], $item['tax_class_id'], $this->config->get('config_tax')), false, false, false) * $item['quantity'] . ' ' . $this->currency->getCode();
$recurring_description = $trial_text . sprintf($this->language->get('text_recurring'), $recurring_amt, $item['recurring_cycle'], $item['recurring_frequency']);
if ($item['recurring_duration'] > 0) {
$recurring_description .= sprintf($this->language->get('text_length'), $item['recurring_duration']);
}
$data['L_BILLINGAGREEMENTDESCRIPTION' . $z] = $recurring_description;
$z++;
}
}
return $data;
}
public function getTotalCaptured($paypal_order_id) {
$query = $this->db->query("SELECT SUM(amount) AS total FROM " . DB_PREFIX . "paypal_order_transaction WHERE paypal_order_id = '" . (int)$paypal_order_id . "' AND pending_reason != 'authorization' AND pending_reason != 'paymentreview' AND (payment_status = 'Partially-Refunded' OR payment_status = 'Completed' OR payment_status = 'Pending') AND transaction_entity = 'payment'");
return $query->row['total'];
}
public function getTotalRefunded($paypal_order_id) {
$query = $this->db->query("SELECT SUM(amount) AS total FROM " . DB_PREFIX . "paypal_order_transaction WHERE paypal_order_id = '" . (int)$paypal_order_id . "' AND payment_status = 'Refunded'");
return $query->row['total'];
}
public function getTransactionRow($transaction_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "paypal_order_transaction pt LEFT JOIN " . DB_PREFIX . "paypal_order po ON (pt.paypal_order_id = po.paypal_order_id) WHERE pt.transaction_id = '" . $this->db->escape($transaction_id) . "' LIMIT 0,1");
if ($query->num_rows > 0) {
return $query->row;
} else {
return false;
}
}
public function updateTransactionStatus($transaction_id, $transaction_status) {
$this->db->query("UPDATE " . DB_PREFIX . "paypal_order_transaction SET payment_status = '" . $this->db->escape($transaction_status) . "' WHERE transaction_id = '" . $this->db->escape($transaction_id) . "' LIMIT 0,1");
}
public function updateTransactionPendingReason($transaction_id, $pending_reason) {
$this->db->query("UPDATE " . DB_PREFIX . "paypal_order_transaction SET pending_reason = '" . $this->db->escape($pending_reason) . "' WHERE transaction_id = '" . $this->db->escape($transaction_id) . "' LIMIT 0,1");
}
public function updateOrder($capture_status, $order_id) {
$this->db->query("UPDATE " . DB_PREFIX . "paypal_order SET modified = NOW(), capture_status = '" . $this->db->escape($capture_status) . "' WHERE order_id = '" . (int)$order_id . "'");
}
public function call($data) {
if ($this->config->get('pp_express_test') == 1) {
$api_endpoint = 'https://api-3t.sandbox.paypal.com/nvp';
$user = $this->config->get('pp_express_sandbox_username');
$password = $this->config->get('pp_express_sandbox_password');
$signature = $this->config->get('pp_express_sandbox_signature');
} else {
$api_endpoint = 'https://api-3t.paypal.com/nvp';
$user = $this->config->get('pp_express_username');
$password = $this->config->get('pp_express_password');
$signature = $this->config->get('pp_express_signature');
}
$default_parameters = array(
'USER' => $user,
'PWD' => $password,
'SIGNATURE' => $signature,
'VERSION' => '109.0',
'BUTTONSOURCE' => 'OpenCart_Cart_EC'
);
$call_parameters = array_merge($data, $default_parameters);
$this->log($call_parameters, 'Call data');
$options = array(
CURLOPT_POST => true,
CURLOPT_HEADER => false,
CURLOPT_URL => $api_endpoint,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1",
CURLOPT_FRESH_CONNECT => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FORBID_REUSE => true,
CURLOPT_TIMEOUT => 0,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_POSTFIELDS => http_build_query($call_parameters, '', '&')
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if (curl_errno($ch) != CURLE_OK) {
$log_data = array(
'curl_error' => curl_error($ch),
'curl_errno' => curl_errno($ch)
);
$this->log($log_data, 'cURL failed');
return false;
}
curl_close($ch);
$response = $this->cleanReturn($response);
$this->log($response, 'Response');
return $response;
}
public function recurringPayments() {
/*
* Used by the checkout to state the module
* supports recurring recurrings.
*/
return true;
}
public function createToken($len = 32) {
$base = 'ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
$max = strlen($base)-1;
$activate_code = '';
mt_srand((double)microtime() * 1000000);
while (strlen($activate_code) < $len + 1) {
$activate_code .= $base{mt_rand(0, $max)};
}
return $activate_code;
}
public function log($data, $title = null, $force = false) {
if ($this->config->get('pp_express_debug') || $force) {
$this->log->write('PayPal Express debug (' . $title . '): ' . json_encode($data));
}
}
public function cleanReturn($data) {
$data = explode('&', $data);
$arr = array();
foreach ($data as $k => $v) {
$tmp = explode('=', $v);
$arr[$tmp[0]] = isset($tmp[1]) ? urldecode($tmp[1]) : '';
}
return $arr;
}
public function recurringCancel($reference) {
$data = array(
'METHOD' => 'ManageRecurringPaymentsProfileStatus',
'PROFILEID' => $reference,
'ACTION' => 'Cancel'
);
return $this->call($data);
}
public function isMobile() {
// This will check the user agent and "try" to match if it is a mobile device
if (preg_match("/Mobile|Android|BlackBerry|iPhone|Windows Phone/", $this->request->server['HTTP_USER_AGENT'])) {
return true;
} else {
return false;
}
}
}
| gpl-3.0 |