code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package telinc.telicraft.util;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ChatMessageComponent;
import net.minecraft.util.StatCollector;
public class PetrifyDamageSource extends TelicraftDamageSource {
protected EntityLivingBase entity;
protected PetrifyDamageSource(EntityLivingBase par1EntityLivingBase) {
super("petrify");
this.setDamageAllowedInCreativeMode();
this.setDamageBypassesArmor();
this.entity = par1EntityLivingBase;
}
@Override
public Entity getEntity() {
return this.entity;
}
@Override
public ChatMessageComponent getDeathMessage(EntityLivingBase par1EntityLivingBase) {
EntityLivingBase attacker = par1EntityLivingBase.func_94060_bK();
String deathSelf = this.getRawDeathMessage();
String deathPlayer = deathSelf + ".player";
return attacker != null && StatCollector.func_94522_b(deathPlayer) ? ChatMessageComponent.func_111082_b(deathPlayer, new Object[]{par1EntityLivingBase.getTranslatedEntityName(), attacker.getTranslatedEntityName()}) : ChatMessageComponent.func_111082_b(deathSelf, new Object[]{par1EntityLivingBase.getTranslatedEntityName()});
}
}
| telinc1/Telicraft | telicraft_common/telinc/telicraft/util/PetrifyDamageSource.java | Java | gpl-3.0 | 1,253 |
<?php namespace Darryldecode\Cart;
/**
* Created by PhpStorm.
* User: darryl
* Date: 1/15/2015
* Time: 9:46 PM
*/
use Illuminate\Support\Collection;
class CartConditionCollection extends Collection {
} | vijaysebastian/bill | vendor/darryldecode/cart/src/Darryldecode/Cart/CartConditionCollection.php | PHP | gpl-3.0 | 210 |
package com.github.dozzatq.phoenix.advertising;
/**
* Created by Rodion Bartoshik on 04.07.2017.
*/
interface Reflector {
FactoryAd reflection();
int state();
}
| dozzatq/Phoenix | mylibrary/src/main/java/com/github/dozzatq/phoenix/advertising/Reflector.java | Java | gpl-3.0 | 173 |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 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.web.commands;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.web.JRInteractiveException;
/**
* @author Narcis Marcu (narcism@users.sourceforge.net)
*/
public class CommandException extends JRInteractiveException
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
public CommandException(String message) {
super(message);
}
public CommandException(Throwable t) {
super(t);
}
public CommandException(String message, Throwable t) {
super(message, t);
}
public CommandException(String messageKey, Object[] args, Throwable t)
{
super(messageKey, args, t);
}
public CommandException(String messageKey, Object[] args)
{
super(messageKey, args);
}
}
| aleatorio12/ProVentasConnector | jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/web/commands/CommandException.java | Java | gpl-3.0 | 1,750 |
#
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)
| rbtcollins/lmirror | l_mirror/tests/test_logging_support.py | Python | gpl-3.0 | 2,180 |
namespace _03BarracksWars.Contracts
{
public interface IRunnable
{
void Run();
}
}
| PlamenHP/Softuni | OOP Advanced/Reflection - Exercise/BarracksWars/Contracts/IRunnable.cs | C# | gpl-3.0 | 106 |
# -*- coding: utf8 -*-
###########################################################################
# This is the package latexparser
#
# 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/>.
###########################################################################
# copyright (c) Laurent Claessens, 2010,2012-2016
# email: laurent@claessens-donadello.eu
import codecs
from latexparser.InputPaths import InputPaths
class Occurrence(object):
"""
self.as_written : the code as it appears in the file, including \MyMacro, including the backslash.
self.position : the position at which this occurrence appears.
Example, if we look at the LatexCode
Hello word, \MyMacro{first}
and then \MyMacro{second}
the first occurrence of \MyMacro has position=12
"""
def __init__(self,name,arguments,as_written="",position=0):
self.arguments = arguments
self.number_of_arguments = len(arguments)
self.name = name
self.as_written = as_written
self.arguments_list = arguments
self.position = position
def configuration(self):
r"""
Return the way the arguments are separated in as_written.
Example, if we have
\MyMacro<space>{A}<tab>{B}
{C},
we return the list
["<space>","tab","\n"]
The following has to be true:
self.as_written == self.name+self.configuration()[0]+self.arguments_list[0]+etc.
"""
l=[]
a = self.as_written.split(self.name)[1]
for arg in self.arguments_list:
split = a.split("{"+arg+"}")
separator=split[0]
try:
a=split[1]
except IndexError:
print(self.as_written)
raise
l.append(separator)
return l
def change_argument(self,num,func):
r"""
Apply the function <func> to the <n>th argument of self. Then return a new object.
"""
n=num-1 # Internally, the arguments are numbered from 0.
arguments=self.arguments_list
configuration=self.configuration()
arguments[n]=func(arguments[n])
new_text=self.name
if len(arguments) != len(configuration):
print("Error : length of the configuration list has to be the same as the number of arguments")
raise ValueError
for i in range(len(arguments)):
new_text=new_text+configuration[i]+"{"+arguments[i]+"}"
return Occurrence(self.name,arguments,new_text,self.position)
def analyse(self):
return globals()["Occurrence_"+self.name[1:]](self) # We have to remove the initial "\" in the name of the macro.
def __getitem__(self,a):
return self.arguments[a]
def __str__(self):
return self.as_written
class Occurrence_newlabel(object):
r"""
takes an occurrence of \newlabel and creates an object which contains the information.
In the self.section_name we remove "\relax" from the string.
"""
def __init__(self,occurrence):
self.occurrence = occurrence
self.arguments = self.occurrence.arguments
if len(self.arguments) == 0 :
self.name = "Non interesting; probably the definition"
self.listoche = [None,None,None,None,None]
self.value,self.page,self.section_name,self.fourth,self.fifth=(None,None,None,None,None)
else :
self.name = self.arguments[0][0]
self.listoche = [a[0] for a in SearchArguments(self.arguments[1][0],5)[0]]
self.value = self.listoche[0]
self.page = self.listoche[1]
self.section_name = self.listoche[2].replace(r"\relax","")
self.fourth = self.listoche[3] # I don't know the role of the fourth argument of \newlabel
self.fifth = self.listoche[4] # I don't know the role of the fifth argument of \newlabel
class Occurrence_addInputPath(object):
def __init__(self,Occurrence):
self.directory=Occurrence[0]
class Occurrence_cite(object):
def __init__(self,occurrence):
self.label = occurrence[0]
def entry(self,codeBibtex):
return codeBibtex[self.label]
class Occurrence_newcommand(object):
def __init__(self,occurrence):
self.occurrence = occurrence
self.number_of_arguments = 0
if self.occurrence[1][1] == "[]":
self.number_of_arguments = self.occurrence[1][0]
self.name = self.occurrence[0][0]#[0]
self.definition = self.occurrence[-1][0]
class Occurrence_label(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_ref(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_eqref(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_input(Occurrence):
def __init__(self,occurrence):
Occurrence.__init__(self,occurrence.name,occurrence.arguments,as_written=occurrence.as_written,position=occurrence.position)
self.occurrence = occurrence
self.filename = self.occurrence[0]
self.input_paths=InputPaths()
self._file_content=None # Make file_content "lazy"
def file_content(self,input_paths=None):
r"""
return the content of the file corresponding to this occurrence of
\input.
This is not recursive.
- 'input_path' is the list of paths in which we can search for files.
See the macro `\addInputPath` in the file
https://github.com/LaurentClaessens/mazhe/blob/master/configuration.tex
"""
import os.path
# Memoize
if self._file_content is not None :
return self._file_content
# At least, we are searching in the current directory :
if input_paths is None :
raise # Just to know who should do something like that
# Creating the filename
filename=self.filename
strict_filename = filename
if "." not in filename:
strict_filename=filename+".tex"
# Searching for the correct file in the subdirectories
fn=input_paths.get_file(strict_filename)
try:
# Without [:-1] I got an artificial empty line at the end.
text = "".join( codecs.open(fn,"r",encoding="utf8") )[:-1]
except IOError :
print("Warning : file %s not found."%strict_filename)
raise
self._file_content=text
return self._file_content
| LaurentClaessens/LaTeXparser | Occurrence.py | Python | gpl-3.0 | 7,331 |
/********************************************************************************
Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org).
This file is part of MixERP.
MixERP 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.
MixERP 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 MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using MixERP.Net.Common.Helpers;
using MixERP.Net.Common.Models.Core;
using MixERP.Net.Common.Models.Transactions;
using System;
using System.Collections.ObjectModel;
namespace MixERP.Net.Core.Modules.Sales.Data.Transactions
{
public static class Delivery
{
public static long Add(DateTime valueDate, int storeId, string partyCode, int priceTypeId, int paymentTermId, Collection<StockMasterDetailModel> details, int shipperId, string shippingAddressCode, decimal shippingCharge, int costCenterId, string referenceNumber, int agentId, string statementReference, Collection<int> transactionIdCollection, Collection<AttachmentModel> attachments, bool nonTaxable)
{
StockMasterModel stockMaster = new StockMasterModel();
stockMaster.PartyCode = partyCode;
stockMaster.IsCredit = true;//Credit
stockMaster.PaymentTermId = paymentTermId;
stockMaster.PriceTypeId = priceTypeId;
stockMaster.ShipperId = shipperId;
stockMaster.ShippingAddressCode = shippingAddressCode;
stockMaster.ShippingCharge = shippingCharge;
stockMaster.SalespersonId = agentId;
stockMaster.CashRepositoryId = 0;//Credit
stockMaster.StoreId = storeId;
long transactionMasterId = GlTransaction.Add("Sales.Delivery", valueDate, SessionHelper.GetOfficeId(), SessionHelper.GetUserId(), SessionHelper.GetLogOnId(), costCenterId, referenceNumber, statementReference, stockMaster, details, attachments, nonTaxable);
TransactionGovernor.Autoverification.Autoverify.PassTransactionMasterId(transactionMasterId);
return transactionMasterId;
}
}
} | jacquet33/miERP | FrontEnd/MixERP.Net.FrontEnd/Modules/Sales.Data/Transactions/Delivery.cs | C# | gpl-3.0 | 2,573 |
import java.util.*;
public class Pali {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
StringBuffer buff=new StringBuffer(str).reverse();
String str1=buff.toString();
if(str.isequals(str1))
{
System.out.println("Palindrome");
}
else
{
System.out.println("Not a Palindrome");
}
}
| RaviVengatesh/Guvi_codes | Pali.java | Java | gpl-3.0 | 449 |
#!/usr/bin/env python
#
# MCP320x
#
# Author: Maurik Holtrop
#
# This module interfaces with the MCP300x or MCP320x family of chips. These
# are 10-bit and 12-bit ADCs respectively. The x number indicates the number
# of multiplexed analog inputs: 2 (MCP3202), 4 (MCP3204) or 8 (MCP3208)
# Communications with this chip are over the SPI protocol.
# See: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
#
# The version of the code has two SPI interfaces: the builtin hardware
# SPI interface on the RPI, or a "bit-banged" GPIO version.
#
# Bit-Bang GPIO:
# We emulate a SPI port in software using the GPIO lines.
# This is a bit slower than the hardware interface, but it is far more
# clear what is going on, plus the RPi has only one SPI device.
# Connections: RPi GPIO to MCP320x
# CS_bar_pin = CS/SHDN
# CLK_pin = CLK
# MOSI_pin = D_in
# MISO_pin = D_out
#
# Hardware SPI:
# This uses the builtin hardware on the RPi. You need to enable this with the
# raspi-config program first. The data rate can be up to 1MHz.
# Connections: RPi pins to MCP320x
# CE0 or CE1 = CS/SHDN (chip select) set CS_bar = 0 or 1
# SCK = CLK set CLK_pin = 1000000 (transfer speed)
# MOSI = D_in set MOSI_pin = 0
# MISO = D_out set MISO_pin = 0
# The SPI protocol simulated here is MODE=0, CPHA=0, which has a positive polarity clock,
# (the clock is 0 at rest, active at 1) and a positive phase (0 to 1 transition) for reading
# or writing the data. Thus corresponds to the specifications of the MCP320x chips.
#
# From MCP3208 datasheet:
# Outging data : MCU latches data to A/D converter on rising edges of SCLK
# Incoming data: Data is clocked out of A/D converter on falling edges, so should be read on rising edge.
try:
import RPi.GPIO as GPIO
except ImportError as error:
pass
try:
import Adafruit_BBIO as GPIO
except ImportError as error:
pass
try:
import spidev
except ImportError as error:
pass
from DevLib.MyValues import MyValues
class MCP320x:
"""This is an class that implements an interface to the MCP320x ADC chips.
Standard is the MCP3208, but is will also work wiht the MCP3202, MCP3204, MCP3002, MCP3004 and MCP3008."""
def __init__(self, cs_bar_pin, clk_pin=1000000, mosi_pin=0, miso_pin=0, chip='MCP3208',
channel_max=None, bit_length=None, single_ended=True):
"""Initialize the code and set the GPIO pins.
The last argument, ch_max, is 2 for the MCP3202, 4 for the
MCP3204 or 8 for the MCS3208."""
self._CLK = clk_pin
self._MOSI = mosi_pin
self._MISO = miso_pin
self._CS_bar = cs_bar_pin
chip_dictionary = {
"MCP3202": (2, 12),
"MCP3204": (4, 12),
"MCP3208": (8, 12),
"MCP3002": (2, 10),
"MCP3004": (4, 10),
"MCP3008": (8, 10)
}
if chip in chip_dictionary:
self._ChannelMax = chip_dictionary[chip][0]
self._BitLength = chip_dictionary[chip][1]
elif chip is None and (channel_max is not None) and (bit_length is not None):
self._ChannelMax = channel_max
self._BitLength = bit_length
else:
print("Unknown chip: {} - Please re-initialize.")
self._ChannelMax = 0
self._BitLength = 0
return
self._SingleEnded = single_ended
self._Vref = 3.3
self._values = MyValues(self.read_adc, self._ChannelMax)
self._volts = MyValues(self.read_volts, self._ChannelMax)
# This is used to speed up the SPIDEV communication. Send out MSB first.
# control[0] - bit7-3: upper 5 bits 0, because we can only send 8 bit sequences.
# - bit2 : Start bit - starts conversion in ADCs
# - bit1 : Select single_ended=1 or differential=0
# - bit0 : D2 high bit of channel select.
# control[1] - bit7 : D1 middle bit of channel select.
# - bit6 : D0 low bit of channel select.
# - bit5-0 : Don't care.
if self._SingleEnded:
self._control0 = [0b00000110, 0b00100000, 0] # Pre-compute part of the control word.
else:
self._control0 = [0b00000100, 0b00100000, 0] # Pre-compute part of the control word.
if self._MOSI > 0: # Bing Bang mode
assert self._MISO != 0 and self._CLK < 32
if GPIO.getmode() != 11:
GPIO.setmode(GPIO.BCM) # Use the BCM numbering scheme
GPIO.setup(self._CLK, GPIO.OUT) # Setup the ports for in and output
GPIO.setup(self._MOSI, GPIO.OUT)
GPIO.setup(self._MISO, GPIO.IN)
GPIO.setup(self._CS_bar, GPIO.OUT)
GPIO.output(self._CLK, 0) # Set the clock low.
GPIO.output(self._MOSI, 0) # Set the Master Out low
GPIO.output(self._CS_bar, 1) # Set the CS_bar high
else:
self._dev = spidev.SpiDev(0, self._CS_bar) # Start a SpiDev device
self._dev.mode = 0 # Set SPI mode (phase)
self._dev.max_speed_hz = self._CLK # Set the data rate
self._dev.bits_per_word = 8 # Number of bit per word. ALWAYS 8
def __del__(self):
""" Cleanup the GPIO before being destroyed """
if self._MOSI > 0:
GPIO.cleanup(self._CS_bar)
GPIO.cleanup(self._CLK)
GPIO.cleanup(self._MOSI)
GPIO.cleanup(self._MISO)
def get_channel_max(self):
"""Return the maximum number of channels"""
return self._ChannelMax
def get_bit_length(self):
"""Return the number of bits that will be read"""
return self._BitLength
def get_value_max(self):
"""Return the maximum value possible for an ADC read"""
return 2 ** self._BitLength - 1
def send_bit(self, bit):
""" Send out a single bit, and pulse clock."""
if self._MOSI == 0:
return
#
# The input is read on the rising edge of the clock.
#
GPIO.output(self._MOSI, bit) # Set the bit.
GPIO.output(self._CLK, 1) # Rising edge sends data
GPIO.output(self._CLK, 0) # Return clock to zero.
def read_bit(self):
""" Read a single bit from the ADC and pulse clock."""
if self._MOSI == 0:
return 0
#
# The output is going out on the falling edge of the clock,
# and is to be read on the rising edge of the clock.
# Clock should be already low, and data should already be set.
GPIO.output(self._CLK, 1) # Set the clock high. Ready to read.
bit = GPIO.input(self._MISO) # Read the bit.
GPIO.output(self._CLK, 0) # Return clock low, next bit will be set.
return bit
def read_adc(self, channel):
"""This reads the actual ADC value, after connecting the analog multiplexer to
the desired channel.
ADC value is returned at a n-bit integer value, with n=10 or 12 depending on the chip.
The value can be converted to a voltage with:
volts = data*Vref/(2**n-1)"""
if channel < 0 or channel >= self._ChannelMax:
print("Error - chip does not have channel = {}".format(channel))
if self._MOSI == 0:
# SPIdev Code
# This builds up the control word, which selects the channel
# and sets single/differential more.
control = [self._control0[0] + ((channel & 0b100) >> 2), self._control0[1]+((channel & 0b011) << 6), 0]
dat = self._dev.xfer(control)
value = (dat[1] << 8)+dat[2] # Unpack the two 8-bit words to a single integer.
return value
else:
# Bit Bang code.
# To read out this chip you need to send:
# 1 - start bit
# 2 - Single ended (1) or differential (0) mode
# 3 - Channel select: 1 bit for x=2 or 3 bits for x=4,8
# 4 - MSB first (1) or LSB first (0)
#
# Start of sequence sets CS_bar low, and sends sequence
#
GPIO.output(self._CLK, 0) # Make sure clock starts low.
GPIO.output(self._MOSI, 0)
GPIO.output(self._CS_bar, 0) # Select the chip.
self.send_bit(1) # Start bit = 1
self.send_bit(self._SingleEnded) # Select single or differential
if self._ChannelMax > 2:
self.send_bit(int((channel & 0b100) > 0)) # Send high bit of channel = DS2
self.send_bit(int((channel & 0b010) > 0)) # Send mid bit of channel = DS1
self.send_bit(int((channel & 0b001) > 0)) # Send low bit of channel = DS0
else:
self.send_bit(channel)
self.send_bit(0) # MSB First (for MCP3x02) or don't care.
# The clock is currently low, and the dummy bit = 0 is on the output of the ADC
#
self.read_bit() # Read the bit.
data = 0
for i in range(self._BitLength):
# Note you need to shift left first, or else you shift the last bit (bit 0)
# to the 1 position.
data <<= 1
bit = self.read_bit()
data += bit
GPIO.output(self._CS_bar, 1) # Unselect the chip.
return data
def read_volts(self, channel):
"""Read the ADC value from channel and convert to volts, assuming that Vref is set correctly. """
return self._Vref * self.read_adc(channel) / self.get_value_max()
def fast_read_adc0(self):
"""This reads the actual ADC value of channel 0, with as little overhead as possible.
Use with SPIDEV ONLY!!!!
returns: The ADC value as an n-bit integer value, with n=10 or 12 depending on the chip."""
dat = self._dev.xfer(self._control0)
value = (dat[1] << 8) + dat[2]
return value
@property
def values(self):
"""ADC values presented as a list."""
return self._values
@property
def volts(self):
"""ADC voltages presented as a list"""
return self._volts
@property
def accuracy(self):
"""The fractional voltage of the least significant bit. """
return self._Vref / float(self.get_value_max())
@property
def vref(self):
"""Reference voltage used by the chip. You need to set this. It defaults to 3.3V"""
return self._Vref
@vref.setter
def vref(self, vr):
self._Vref = vr
def main(argv):
"""Test code for the MCP320x driver. This assumes you are using a MCP3208
If no arguments are supplied, then use SPIdev for CE0 and read channel 0"""
if len(argv) < 3:
print("Args : ", argv)
cs_bar = 0
clk_pin = 1000000
mosi_pin = 0
miso_pin = 0
if len(argv) < 2:
channel = 0
else:
channel = int(argv[1])
elif len(argv) < 6:
print("Please supply: cs_bar_pin clk_pin mosi_pin miso_pin channel")
sys.exit(1)
else:
cs_bar = int(argv[1])
clk_pin = int(argv[2])
mosi_pin = int(argv[3])
miso_pin = int(argv[4])
channel = int(argv[5])
adc_chip = MCP320x(cs_bar, clk_pin, mosi_pin, miso_pin)
try:
while True:
value = adc_chip.read_adc(channel)
print("{:4d}".format(value))
time.sleep(0.1)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
import sys
import time
main(sys.argv)
| mholtrop/Phys605 | Python/DevLib/MCP320x.py | Python | gpl-3.0 | 11,971 |
/*
No-Babylon a job search engine with filtering ability
Copyright (C) 2012-2014 ferenc.jdev@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 org.laatusys.nobabylon.support;
import java.util.regex.Pattern;
public class ExcludeRegexpFilter implements Filter {
private final Pattern pattern;
public ExcludeRegexpFilter(String regexp, boolean caseSensitive) {
pattern = caseSensitive ? Pattern.compile(regexp) : Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
}
public ExcludeRegexpFilter(String regexp) {
this(regexp, false);
}
@Override
public boolean accept(String description) {
return !pattern.matcher(description).find();
}
}
| ferenc-jdev/no-babylon | src/main/java/org/laatusys/nobabylon/support/ExcludeRegexpFilter.java | Java | gpl-3.0 | 1,328 |
# __init__.py
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = '0.3.4'
| codendev/rapidwsgi | src/mako/__init__.py | Python | gpl-3.0 | 256 |
#!/usr/bin/python
import sys
print "divsum_analysis.py DivsumFile NumberOfNucleotides"
try:
file = sys.argv[1]
except:
file = raw_input("Introduce RepeatMasker's Divsum file: ")
try:
nucs = sys.argv[2]
except:
nucs = raw_input("Introduce number of analysed nucleotides: ")
nucs = int(nucs)
data = open(file).readlines()
s_matrix = data.index("Coverage for each repeat class and divergence (Kimura)\n")
matrix = []
elements = data[s_matrix+1]
elements = elements.split()
for element in elements[1:]:
matrix.append([element,[]])
n_el = len(matrix)
for line in data[s_matrix+2:]:
# print line
info = line.split()
info = info[1:]
for n in range(0,n_el):
matrix[n][1].append(int(info[n]))
abs = open(file+".abs", "w")
rel = open(file+".rel", "w")
for n in range(0,n_el):
abs.write("%s\t%s\n" % (matrix[n][0], sum(matrix[n][1])))
rel.write("%s\t%s\n" % (matrix[n][0], round(1.0*sum(matrix[n][1])/nucs,100)))
| fjruizruano/ngs-protocols | divsum_analysis.py | Python | gpl-3.0 | 974 |
/*
TShock, a server mod for Terraria
Copyright (C) 2011-2018 Pryaxis & TShock Contributors
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/>.
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using TShockAPI.DB;
using TerrariaApi.Server;
using TShockAPI.Hooks;
using Terraria.GameContent.Events;
using Microsoft.Xna.Framework;
using OTAPI.Tile;
using TShockAPI.Localization;
using System.Text.RegularExpressions;
namespace TShockAPI
{
public delegate void CommandDelegate(CommandArgs args);
public class CommandArgs : EventArgs
{
public string Message { get; private set; }
public TSPlayer Player { get; private set; }
public bool Silent { get; private set; }
/// <summary>
/// Parameters passed to the arguement. Does not include the command name.
/// IE '/kick "jerk face"' will only have 1 argument
/// </summary>
public List<string> Parameters { get; private set; }
public Player TPlayer
{
get { return Player.TPlayer; }
}
public CommandArgs(string message, TSPlayer ply, List<string> args)
{
Message = message;
Player = ply;
Parameters = args;
Silent = false;
}
public CommandArgs(string message, bool silent, TSPlayer ply, List<string> args)
{
Message = message;
Player = ply;
Parameters = args;
Silent = silent;
}
}
public class Command
{
/// <summary>
/// Gets or sets whether to allow non-players to use this command.
/// </summary>
public bool AllowServer { get; set; }
/// <summary>
/// Gets or sets whether to do logging of this command.
/// </summary>
public bool DoLog { get; set; }
/// <summary>
/// Gets or sets the help text of this command.
/// </summary>
public string HelpText { get; set; }
/// <summary>
/// Gets or sets an extended description of this command.
/// </summary>
public string[] HelpDesc { get; set; }
/// <summary>
/// Gets the name of the command.
/// </summary>
public string Name { get { return Names[0]; } }
/// <summary>
/// Gets the names of the command.
/// </summary>
public List<string> Names { get; protected set; }
/// <summary>
/// Gets the permissions of the command.
/// </summary>
public List<string> Permissions { get; protected set; }
private CommandDelegate commandDelegate;
public CommandDelegate CommandDelegate
{
get { return commandDelegate; }
set
{
if (value == null)
throw new ArgumentNullException();
commandDelegate = value;
}
}
public Command(List<string> permissions, CommandDelegate cmd, params string[] names)
: this(cmd, names)
{
Permissions = permissions;
}
public Command(string permissions, CommandDelegate cmd, params string[] names)
: this(cmd, names)
{
Permissions = new List<string> { permissions };
}
public Command(CommandDelegate cmd, params string[] names)
{
if (cmd == null)
throw new ArgumentNullException("cmd");
if (names == null || names.Length < 1)
throw new ArgumentException("names");
AllowServer = true;
CommandDelegate = cmd;
DoLog = true;
HelpText = "No help available.";
HelpDesc = null;
Names = new List<string>(names);
Permissions = new List<string>();
}
public bool Run(string msg, bool silent, TSPlayer ply, List<string> parms)
{
if (!CanRun(ply))
return false;
try
{
CommandDelegate(new CommandArgs(msg, silent, ply, parms));
}
catch (Exception e)
{
ply.SendErrorMessage("Command failed, check logs for more details.");
TShock.Log.Error(e.ToString());
}
return true;
}
public bool Run(string msg, TSPlayer ply, List<string> parms)
{
return Run(msg, false, ply, parms);
}
public bool HasAlias(string name)
{
return Names.Contains(name);
}
public bool CanRun(TSPlayer ply)
{
if (Permissions == null || Permissions.Count < 1)
return true;
foreach (var Permission in Permissions)
{
if (ply.HasPermission(Permission))
return true;
}
return false;
}
}
public static class Commands
{
public static List<Command> ChatCommands = new List<Command>();
public static ReadOnlyCollection<Command> TShockCommands = new ReadOnlyCollection<Command>(new List<Command>());
/// <summary>
/// The command specifier, defaults to "/"
/// </summary>
public static string Specifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; }
}
/// <summary>
/// The silent command specifier, defaults to "."
/// </summary>
public static string SilentSpecifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; }
}
private delegate void AddChatCommand(string permission, CommandDelegate command, params string[] names);
public static void InitCommands()
{
List<Command> tshockCommands = new List<Command>(100);
Action<Command> add = (cmd) =>
{
tshockCommands.Add(cmd);
ChatCommands.Add(cmd);
};
add(new Command(SetupToken, "setup")
{
AllowServer = false,
HelpText = "Used to authenticate as superadmin when first setting up TShock."
});
add(new Command(Permissions.user, ManageUsers, "user")
{
DoLog = false,
HelpText = "Manages user accounts."
});
#region Account Commands
add(new Command(Permissions.canlogin, AttemptLogin, "login")
{
AllowServer = false,
DoLog = false,
HelpText = "Logs you into an account."
});
add(new Command(Permissions.canlogout, Logout, "logout")
{
AllowServer = false,
DoLog = false,
HelpText = "Logs you out of your current account."
});
add(new Command(Permissions.canchangepassword, PasswordUser, "password")
{
AllowServer = false,
DoLog = false,
HelpText = "Changes your account's password."
});
add(new Command(Permissions.canregister, RegisterUser, "register")
{
AllowServer = false,
DoLog = false,
HelpText = "Registers you an account."
});
add(new Command(Permissions.checkaccountinfo, ViewAccountInfo, "accountinfo", "ai")
{
HelpText = "Shows information about a user."
});
#endregion
#region Admin Commands
add(new Command(Permissions.ban, Ban, "ban")
{
HelpText = "Manages player bans."
});
add(new Command(Permissions.broadcast, Broadcast, "broadcast", "bc", "say")
{
HelpText = "Broadcasts a message to everyone on the server."
});
add(new Command(Permissions.logs, DisplayLogs, "displaylogs")
{
HelpText = "Toggles whether you receive server logs."
});
add(new Command(Permissions.managegroup, Group, "group")
{
HelpText = "Manages groups."
});
add(new Command(Permissions.manageitem, ItemBan, "itemban")
{
HelpText = "Manages item bans."
});
add(new Command(Permissions.manageprojectile, ProjectileBan, "projban")
{
HelpText = "Manages projectile bans."
});
add(new Command(Permissions.managetile, TileBan, "tileban")
{
HelpText = "Manages tile bans."
});
add(new Command(Permissions.manageregion, Region, "region")
{
HelpText = "Manages regions."
});
add(new Command(Permissions.kick, Kick, "kick")
{
HelpText = "Removes a player from the server."
});
add(new Command(Permissions.mute, Mute, "mute", "unmute")
{
HelpText = "Prevents a player from talking."
});
add(new Command(Permissions.savessc, OverrideSSC, "overridessc", "ossc")
{
HelpText = "Overrides serverside characters for a player, temporarily."
});
add(new Command(Permissions.savessc, SaveSSC, "savessc")
{
HelpText = "Saves all serverside characters."
});
add(new Command(Permissions.uploaddata, UploadJoinData, "uploadssc")
{
HelpText = "Upload the account information when you joined the server as your Server Side Character data."
});
add(new Command(Permissions.settempgroup, TempGroup, "tempgroup")
{
HelpText = "Temporarily sets another player's group."
});
add(new Command(Permissions.su, SubstituteUser, "su")
{
HelpText = "Temporarily elevates you to Super Admin."
});
add(new Command(Permissions.su, SubstituteUserDo, "sudo")
{
HelpText = "Executes a command as the super admin."
});
add(new Command(Permissions.userinfo, GrabUserUserInfo, "userinfo", "ui")
{
HelpText = "Shows information about a player."
});
#endregion
#region Annoy Commands
add(new Command(Permissions.annoy, Annoy, "annoy")
{
HelpText = "Annoys a player for an amount of time."
});
add(new Command(Permissions.annoy, Confuse, "confuse")
{
HelpText = "Confuses a player for an amount of time."
});
add(new Command(Permissions.annoy, Rocket, "rocket")
{
HelpText = "Rockets a player upwards. Requires SSC."
});
add(new Command(Permissions.annoy, FireWork, "firework")
{
HelpText = "Spawns fireworks at a player."
});
#endregion
#region Configuration Commands
add(new Command(Permissions.maintenance, CheckUpdates, "checkupdates")
{
HelpText = "Checks for TShock updates."
});
add(new Command(Permissions.maintenance, Off, "off", "exit", "stop")
{
HelpText = "Shuts down the server while saving."
});
add(new Command(Permissions.maintenance, OffNoSave, "off-nosave", "exit-nosave", "stop-nosave")
{
HelpText = "Shuts down the server without saving."
});
add(new Command(Permissions.cfgreload, Reload, "reload")
{
HelpText = "Reloads the server configuration file."
});
add(new Command(Permissions.cfgpassword, ServerPassword, "serverpassword")
{
HelpText = "Changes the server password."
});
add(new Command(Permissions.maintenance, GetVersion, "version")
{
HelpText = "Shows the TShock version."
});
add(new Command(Permissions.whitelist, Whitelist, "whitelist")
{
HelpText = "Manages the server whitelist."
});
#endregion
#region Item Commands
add(new Command(Permissions.give, Give, "give", "g")
{
HelpText = "Gives another player an item."
});
add(new Command(Permissions.item, Item, "item", "i")
{
AllowServer = false,
HelpText = "Gives yourself an item."
});
#endregion
#region NPC Commands
add(new Command(Permissions.butcher, Butcher, "butcher")
{
HelpText = "Kills hostile NPCs or NPCs of a certain type."
});
add(new Command(Permissions.renamenpc, RenameNPC, "renamenpc")
{
HelpText = "Renames an NPC."
});
add(new Command(Permissions.invade, Invade, "invade")
{
HelpText = "Starts an NPC invasion."
});
add(new Command(Permissions.maxspawns, MaxSpawns, "maxspawns")
{
HelpText = "Sets the maximum number of NPCs."
});
add(new Command(Permissions.spawnboss, SpawnBoss, "spawnboss", "sb")
{
AllowServer = false,
HelpText = "Spawns a number of bosses around you."
});
add(new Command(Permissions.spawnmob, SpawnMob, "spawnmob", "sm")
{
AllowServer = false,
HelpText = "Spawns a number of mobs around you."
});
add(new Command(Permissions.spawnrate, SpawnRate, "spawnrate")
{
HelpText = "Sets the spawn rate of NPCs."
});
add(new Command(Permissions.clearangler, ClearAnglerQuests, "clearangler")
{
HelpText = "Resets the list of users who have completed an angler quest that day."
});
#endregion
#region TP Commands
add(new Command(Permissions.home, Home, "home")
{
AllowServer = false,
HelpText = "Sends you to your spawn point."
});
add(new Command(Permissions.spawn, Spawn, "spawn")
{
AllowServer = false,
HelpText = "Sends you to the world's spawn point."
});
add(new Command(Permissions.tp, TP, "tp")
{
AllowServer = false,
HelpText = "Teleports a player to another player."
});
add(new Command(Permissions.tpothers, TPHere, "tphere")
{
AllowServer = false,
HelpText = "Teleports a player to yourself."
});
add(new Command(Permissions.tpnpc, TPNpc, "tpnpc")
{
AllowServer = false,
HelpText = "Teleports you to an npc."
});
add(new Command(Permissions.tppos, TPPos, "tppos")
{
AllowServer = false,
HelpText = "Teleports you to tile coordinates."
});
add(new Command(Permissions.getpos, GetPos, "pos")
{
AllowServer = false,
HelpText = "Returns the user's or specified user's current position."
});
add(new Command(Permissions.tpallow, TPAllow, "tpallow")
{
AllowServer = false,
HelpText = "Toggles whether other people can teleport you."
});
#endregion
#region World Commands
add(new Command(Permissions.toggleexpert, ToggleExpert, "expert", "expertmode")
{
HelpText = "Toggles expert mode."
});
add(new Command(Permissions.antibuild, ToggleAntiBuild, "antibuild")
{
HelpText = "Toggles build protection."
});
add(new Command(Permissions.bloodmoon, Bloodmoon, "bloodmoon")
{
HelpText = "Sets a blood moon."
});
add(new Command(Permissions.grow, Grow, "grow")
{
AllowServer = false,
HelpText = "Grows plants at your location."
});
add(new Command(Permissions.dropmeteor, DropMeteor, "dropmeteor")
{
HelpText = "Drops a meteor somewhere in the world."
});
add(new Command(Permissions.eclipse, Eclipse, "eclipse")
{
HelpText = "Sets an eclipse."
});
add(new Command(Permissions.halloween, ForceHalloween, "forcehalloween")
{
HelpText = "Toggles halloween mode (goodie bags, pumpkins, etc)."
});
add(new Command(Permissions.xmas, ForceXmas, "forcexmas")
{
HelpText = "Toggles christmas mode (present spawning, santa, etc)."
});
add(new Command(Permissions.fullmoon, Fullmoon, "fullmoon")
{
HelpText = "Sets a full moon."
});
add(new Command(Permissions.hardmode, Hardmode, "hardmode")
{
HelpText = "Toggles the world's hardmode status."
});
add(new Command(Permissions.editspawn, ProtectSpawn, "protectspawn")
{
HelpText = "Toggles spawn protection."
});
add(new Command(Permissions.sandstorm, Sandstorm, "sandstorm")
{
HelpText = "Toggles sandstorms."
});
add(new Command(Permissions.rain, Rain, "rain")
{
HelpText = "Toggles the rain."
});
add(new Command(Permissions.worldsave, Save, "save")
{
HelpText = "Saves the world file."
});
add(new Command(Permissions.worldspawn, SetSpawn, "setspawn")
{
AllowServer = false,
HelpText = "Sets the world's spawn point to your location."
});
add(new Command(Permissions.dungeonposition, SetDungeon, "setdungeon")
{
AllowServer = false,
HelpText = "Sets the dungeon's position to your location."
});
add(new Command(Permissions.worldsettle, Settle, "settle")
{
HelpText = "Forces all liquids to update immediately."
});
add(new Command(Permissions.time, Time, "time")
{
HelpText = "Sets the world time."
});
add(new Command(Permissions.wind, Wind, "wind")
{
HelpText = "Changes the wind speed."
});
add(new Command(Permissions.worldinfo, WorldInfo, "world")
{
HelpText = "Shows information about the current world."
});
#endregion
#region Other Commands
add(new Command(Permissions.buff, Buff, "buff")
{
AllowServer = false,
HelpText = "Gives yourself a buff for an amount of time."
});
add(new Command(Permissions.clear, Clear, "clear")
{
HelpText = "Clears item drops or projectiles."
});
add(new Command(Permissions.buffplayer, GBuff, "gbuff", "buffplayer")
{
HelpText = "Gives another player a buff for an amount of time."
});
add(new Command(Permissions.godmode, ToggleGodMode, "godmode")
{
HelpText = "Toggles godmode on a player."
});
add(new Command(Permissions.heal, Heal, "heal")
{
HelpText = "Heals a player in HP and MP."
});
add(new Command(Permissions.kill, Kill, "kill")
{
HelpText = "Kills another player."
});
add(new Command(Permissions.cantalkinthird, ThirdPerson, "me")
{
HelpText = "Sends an action message to everyone."
});
add(new Command(Permissions.canpartychat, PartyChat, "party", "p")
{
AllowServer = false,
HelpText = "Sends a message to everyone on your team."
});
add(new Command(Permissions.whisper, Reply, "reply", "r")
{
HelpText = "Replies to a PM sent to you."
});
add(new Command(Rests.RestPermissions.restmanage, ManageRest, "rest")
{
HelpText = "Manages the REST API."
});
add(new Command(Permissions.slap, Slap, "slap")
{
HelpText = "Slaps a player, dealing damage."
});
add(new Command(Permissions.serverinfo, ServerInfo, "serverinfo")
{
HelpText = "Shows the server information."
});
add(new Command(Permissions.warp, Warp, "warp")
{
HelpText = "Teleports you to a warp point or manages warps."
});
add(new Command(Permissions.whisper, Whisper, "whisper", "w", "tell")
{
HelpText = "Sends a PM to a player."
});
add(new Command(Permissions.createdumps, CreateDumps, "dump-reference-data")
{
HelpText = "Creates a reference tables for Terraria data types and the TShock permission system in the server folder."
});
#endregion
add(new Command(Aliases, "aliases")
{
HelpText = "Shows a command's aliases."
});
add(new Command(Help, "help")
{
HelpText = "Lists commands or gives help on them."
});
add(new Command(Motd, "motd")
{
HelpText = "Shows the message of the day."
});
add(new Command(ListConnectedPlayers, "playing", "online", "who")
{
HelpText = "Shows the currently connected players."
});
add(new Command(Rules, "rules")
{
HelpText = "Shows the server's rules."
});
TShockCommands = new ReadOnlyCollection<Command>(tshockCommands);
}
public static bool HandleCommand(TSPlayer player, string text)
{
string cmdText = text.Remove(0, 1);
string cmdPrefix = text[0].ToString();
bool silent = false;
if (cmdPrefix == SilentSpecifier)
silent = true;
int index = -1;
for (int i = 0; i < cmdText.Length; i++)
{
if (IsWhiteSpace(cmdText[i]))
{
index = i;
break;
}
}
string cmdName;
if (index == 0) // Space after the command specifier should not be supported
{
player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
return true;
}
else if (index < 0)
cmdName = cmdText.ToLower();
else
cmdName = cmdText.Substring(0, index).ToLower();
List<string> args;
if (index < 0)
args = new List<string>();
else
args = ParseParameters(cmdText.Substring(index));
IEnumerable<Command> cmds = ChatCommands.FindAll(c => c.HasAlias(cmdName));
if (Hooks.PlayerHooks.OnPlayerCommand(player, cmdName, cmdText, args, ref cmds, cmdPrefix))
return true;
if (cmds.Count() == 0)
{
if (player.AwaitingResponse.ContainsKey(cmdName))
{
Action<CommandArgs> call = player.AwaitingResponse[cmdName];
player.AwaitingResponse.Remove(cmdName);
call(new CommandArgs(cmdText, player, args));
return true;
}
player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
return true;
}
foreach (Command cmd in cmds)
{
if (!cmd.CanRun(player))
{
TShock.Utils.SendLogs(string.Format("{0} tried to execute {1}{2}.", player.Name, Specifier, cmdText), Color.PaleVioletRed, player);
player.SendErrorMessage("You do not have access to this command.");
if (player.HasPermission(Permissions.su))
{
player.SendInfoMessage("You can use '{0}sudo {0}{1}' to override this check.", Specifier, cmdText);
}
}
else if (!cmd.AllowServer && !player.RealPlayer)
{
player.SendErrorMessage("You must use this command in-game.");
}
else
{
if (cmd.DoLog)
TShock.Utils.SendLogs(string.Format("{0} executed: {1}{2}.", player.Name, silent ? SilentSpecifier : Specifier, cmdText), Color.PaleVioletRed, player);
cmd.Run(cmdText, silent, player, args);
}
}
return true;
}
/// <summary>
/// Parses a string of parameters into a list. Handles quotes.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static List<String> ParseParameters(string str)
{
var ret = new List<string>();
var sb = new StringBuilder();
bool instr = false;
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c == '\\' && ++i < str.Length)
{
if (str[i] != '"' && str[i] != ' ' && str[i] != '\\')
sb.Append('\\');
sb.Append(str[i]);
}
else if (c == '"')
{
instr = !instr;
if (!instr)
{
ret.Add(sb.ToString());
sb.Clear();
}
else if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else if (IsWhiteSpace(c) && !instr)
{
if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else
sb.Append(c);
}
if (sb.Length > 0)
ret.Add(sb.ToString());
return ret;
}
private static bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t' || c == '\n';
}
#region Account commands
private static void AttemptLogin(CommandArgs args)
{
if (args.Player.LoginAttempts > TShock.Config.MaximumLoginAttempts && (TShock.Config.MaximumLoginAttempts != -1))
{
TShock.Log.Warn(String.Format("{0} ({1}) had {2} or more invalid login attempts and was kicked automatically.",
args.Player.IP, args.Player.Name, TShock.Config.MaximumLoginAttempts));
args.Player.Kick("Too many invalid login attempts.");
return;
}
if (args.Player.IsLoggedIn)
{
args.Player.SendErrorMessage("You are already logged in, and cannot login again.");
return;
}
UserAccount account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
string password = "";
bool usingUUID = false;
if (args.Parameters.Count == 0 && !TShock.Config.DisableUUIDLogin)
{
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, ""))
return;
usingUUID = true;
}
else if (args.Parameters.Count == 1)
{
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, args.Parameters[0]))
return;
password = args.Parameters[0];
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowLoginAnyUsername)
{
if (String.IsNullOrEmpty(args.Parameters[0]))
{
args.Player.SendErrorMessage("Bad login attempt.");
return;
}
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Parameters[0], args.Parameters[1]))
return;
account = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]);
password = args.Parameters[1];
}
else
{
args.Player.SendErrorMessage("Syntax: {0}login - Logs in using your UUID and character name", Specifier);
args.Player.SendErrorMessage(" {0}login <password> - Logs in using your password and character name", Specifier);
args.Player.SendErrorMessage(" {0}login <username> <password> - Logs in using your username and password", Specifier);
args.Player.SendErrorMessage("If you forgot your password, there is no way to recover it.");
return;
}
try
{
if (account == null)
{
args.Player.SendErrorMessage("A user account by that name does not exist.");
}
else if (account.VerifyPassword(password) ||
(usingUUID && account.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin &&
!String.IsNullOrWhiteSpace(args.Player.UUID)))
{
args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID);
var group = TShock.Groups.GetGroupByName(account.Group);
args.Player.Group = group;
args.Player.tempGroup = null;
args.Player.Account = account;
args.Player.IsLoggedIn = true;
args.Player.IsDisabledForSSC = false;
if (Main.ServerSideCharacter)
{
if (args.Player.HasPermission(Permissions.bypassssc))
{
args.Player.PlayerData.CopyCharacter(args.Player);
TShock.CharacterDB.InsertPlayerData(args.Player);
}
args.Player.PlayerData.RestoreCharacter(args.Player);
}
args.Player.LoginFailsBySsi = false;
if (args.Player.HasPermission(Permissions.ignorestackhackdetection))
args.Player.IsDisabledForStackDetection = false;
if (args.Player.HasPermission(Permissions.usebanneditem))
args.Player.IsDisabledForBannedWearable = false;
args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + account.Name + ".");
if ((args.Player.LoginHarassed) && (TShock.Config.RememberLeavePos))
{
if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero)
{
Vector2 pos = TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP);
args.Player.Teleport((int)pos.X * 16, (int)pos.Y * 16);
}
args.Player.LoginHarassed = false;
}
TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
}
else
{
if (usingUUID && !TShock.Config.DisableUUIDLogin)
{
args.Player.SendErrorMessage("UUID does not match this character!");
}
else
{
args.Player.SendErrorMessage("Invalid password!");
}
TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + account.Name + ".");
args.Player.LoginAttempts++;
}
}
catch (Exception ex)
{
args.Player.SendErrorMessage("There was an error processing your request.");
TShock.Log.Error(ex.ToString());
}
}
private static void Logout(CommandArgs args)
{
if (!args.Player.IsLoggedIn)
{
args.Player.SendErrorMessage("You are not logged in.");
return;
}
args.Player.Logout();
args.Player.SendSuccessMessage("You have been successfully logged out of your account.");
if (Main.ServerSideCharacter)
{
args.Player.SendWarningMessage("Server side characters are enabled. You need to be logged in to play.");
}
}
private static void PasswordUser(CommandArgs args)
{
try
{
if (args.Player.IsLoggedIn && args.Parameters.Count == 2)
{
string password = args.Parameters[0];
if (args.Player.Account.VerifyPassword(password))
{
try
{
args.Player.SendSuccessMessage("You changed your password!");
TShock.UserAccounts.SetUserAccountPassword(args.Player.Account, args.Parameters[1]); // SetUserPassword will hash it for you.
TShock.Log.ConsoleInfo(args.Player.IP + " named " + args.Player.Name + " changed the password of account " +
args.Player.Account.Name + ".");
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
}
}
else
{
args.Player.SendErrorMessage("You failed to change your password!");
TShock.Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for account: " +
args.Player.Account.Name + ".");
}
}
else
{
args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password <oldpassword> <newpassword>", Specifier);
}
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("PasswordUser returned an error: " + ex);
}
}
private static void RegisterUser(CommandArgs args)
{
try
{
var account = new UserAccount();
string echoPassword = "";
if (args.Parameters.Count == 1)
{
account.Name = args.Player.Name;
echoPassword = args.Parameters[0];
try
{
account.CreateBCryptHash(args.Parameters[0]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
{
account.Name = args.Parameters[0];
echoPassword = args.Parameters[1];
try
{
account.CreateBCryptHash(args.Parameters[1]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}register <password>", Specifier);
return;
}
account.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
account.UUID = args.Player.UUID;
if (TShock.UserAccounts.GetUserAccountByName(account.Name) == null && account.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user
{
args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", account.Name);
args.Player.SendSuccessMessage("Your password is {0}.", echoPassword);
TShock.UserAccounts.AddUserAccount(account);
TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, account.Name);
}
else
{
args.Player.SendErrorMessage("Sorry, " + account.Name + " was already taken by another person.");
args.Player.SendErrorMessage("Please try a different username.");
TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + account.Name);
}
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("RegisterUser returned an error: " + ex);
}
}
private static void ManageUsers(CommandArgs args)
{
// This guy needs to be here so that people don't get exceptions when they type /user
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
return;
}
string subcmd = args.Parameters[0];
// Add requires a username, password, and a group specified.
if (subcmd == "add" && args.Parameters.Count == 4)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
account.CreateBCryptHash(args.Parameters[2]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
account.Group = args.Parameters[3];
try
{
TShock.UserAccounts.AddUserAccount(account);
args.Player.SendSuccessMessage("Account " + account.Name + " has been added to group " + account.Group + "!");
TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + account.Name + " to group " + account.Group);
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("Group " + account.Group + " does not exist!");
}
catch (UserAccountExistsException)
{
args.Player.SendErrorMessage("User " + account.Name + " already exists!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("User " + account.Name + " could not be added, check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
// User deletion requires a username
else if (subcmd == "del" && args.Parameters.Count == 2)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.RemoveUserAccount(account);
args.Player.SendSuccessMessage("Account removed successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + ".");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("The user " + account.Name + " does not exist! Deleted nobody!");
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
TShock.Log.ConsoleError(ex.ToString());
}
}
// Password changing requires a username, and a new password to set
else if (subcmd == "password" && args.Parameters.Count == 3)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.SetUserAccountPassword(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + account.Name);
args.Player.SendSuccessMessage("Password change succeeded for " + account.Name + ".");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("Password change for " + account.Name + " failed! Check console!");
TShock.Log.ConsoleError(e.ToString());
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
}
}
// Group changing requires a username or IP address, and a new group to set
else if (subcmd == "group" && args.Parameters.Count == 3)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.SetUserGroup(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + account.Name + " to group " + args.Parameters[2] + ".");
args.Player.SendSuccessMessage("Account " + account.Name + " has been changed to group " + args.Parameters[2] + "!");
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("That group does not exist!");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("User " + account.Name + " could not be added. Check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
else if (subcmd == "help")
{
args.Player.SendInfoMessage("Use command help:");
args.Player.SendInfoMessage("{0}user add username password group -- Adds a specified user", Specifier);
args.Player.SendInfoMessage("{0}user del username -- Removes a specified user", Specifier);
args.Player.SendInfoMessage("{0}user password username newpassword -- Changes a user's password", Specifier);
args.Player.SendInfoMessage("{0}user group username newgroup -- Changes a user's group", Specifier);
}
else
{
args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
}
}
#endregion
#region Stupid commands
private static void ServerInfo(CommandArgs args)
{
args.Player.SendInfoMessage("Memory usage: " + Process.GetCurrentProcess().WorkingSet64);
args.Player.SendInfoMessage("Allocated memory: " + Process.GetCurrentProcess().VirtualMemorySize64);
args.Player.SendInfoMessage("Total processor time: " + Process.GetCurrentProcess().TotalProcessorTime);
args.Player.SendInfoMessage("WinVer: " + Environment.OSVersion);
args.Player.SendInfoMessage("Proc count: " + Environment.ProcessorCount);
args.Player.SendInfoMessage("Machine name: " + Environment.MachineName);
}
private static void WorldInfo(CommandArgs args)
{
args.Player.SendInfoMessage("World name: " + (TShock.Config.UseServerName ? TShock.Config.ServerName : Main.worldName));
args.Player.SendInfoMessage("World size: {0}x{1}", Main.maxTilesX, Main.maxTilesY);
args.Player.SendInfoMessage("World ID: " + Main.worldID);
}
#endregion
#region Player Management Commands
private static void GrabUserUserInfo(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}userinfo <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count < 1)
args.Player.SendErrorMessage("Invalid player.");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var message = new StringBuilder();
message.Append("IP Address: ").Append(players[0].IP);
if (players[0].Account != null && players[0].IsLoggedIn)
message.Append(" | Logged in as: ").Append(players[0].Account.Name).Append(" | Group: ").Append(players[0].Group.Name);
args.Player.SendSuccessMessage(message.ToString());
}
}
private static void ViewAccountInfo(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}accountinfo <username>", Specifier);
return;
}
string username = String.Join(" ", args.Parameters);
if (!string.IsNullOrWhiteSpace(username))
{
var account = TShock.UserAccounts.GetUserAccountByName(username);
if (account != null)
{
DateTime LastSeen;
string Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours.ToString("+#;-#");
if (DateTime.TryParse(account.LastAccessed, out LastSeen))
{
LastSeen = DateTime.Parse(account.LastAccessed).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", account.Name, LastSeen.ToShortDateString(),
LastSeen.ToShortTimeString(), Timezone);
}
if (args.Player.Group.HasPermission(Permissions.advaccountinfo))
{
List<string> KnownIps = JsonConvert.DeserializeObject<List<string>>(account.KnownIps?.ToString() ?? string.Empty);
string ip = KnownIps?[KnownIps.Count - 1] ?? "N/A";
DateTime Registered = DateTime.Parse(account.Registered).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s group is {1}.", account.Name, account.Group);
args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", account.Name, ip);
args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", account.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone);
}
}
else
args.Player.SendErrorMessage("User {0} does not exist.", username);
}
else args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}accountinfo <username>", Specifier);
}
private static void Kick(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}kick <player> [reason]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Missing player name.");
return;
}
string plStr = args.Parameters[0];
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
string reason = args.Parameters.Count > 1
? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1))
: "Misbehaviour.";
if (!players[0].Kick(reason, !args.Player.RealPlayer, false, args.Player.Name))
{
args.Player.SendErrorMessage("You can't kick another admin!");
}
}
}
private static void Ban(CommandArgs args)
{
string subcmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subcmd)
{
case "add":
#region Add Ban
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid command. Format: {0}ban add <player> [time] [reason]", Specifier);
args.Player.SendErrorMessage("Example: {0}ban add Shank 10d Hacking and cheating", Specifier);
args.Player.SendErrorMessage("Example: {0}ban add Ash", Specifier);
args.Player.SendErrorMessage("Use the time 0 (zero) for a permanent ban.");
return;
}
// Used only to notify if a ban was successful and who the ban was about
bool success = false;
string targetGeneralizedName = "";
// Effective ban target assignment
List<TSPlayer> players = TSPlayer.FindByNameOrID(args.Parameters[1]);
// Bad case: Players contains more than 1 person so we can't ban them
if (players.Count > 1)
{
//Fail fast
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
UserAccount offlineUserAccount = TShock.UserAccounts.GetUserAccountByName(args.Parameters[1]);
// Storage variable to determine if the command executor is the server console
// If it is, we assume they have full control and let them override permission checks
bool callerIsServerConsole = args.Player is TSServerPlayer;
// The ban reason the ban is going to have
string banReason = "Unknown.";
// The default ban length
// 0 is permanent ban, otherwise temp ban
int banLengthInSeconds = 0;
// Figure out if param 2 is a time or 0 or garbage
if (args.Parameters.Count >= 3)
{
bool parsedOkay = false;
if (args.Parameters[2] != "0")
{
parsedOkay = TShock.Utils.TryParseTime(args.Parameters[2], out banLengthInSeconds);
}
else
{
parsedOkay = true;
}
if (!parsedOkay)
{
args.Player.SendErrorMessage("Invalid time format. Example: 10d 5h 3m 2s.");
args.Player.SendErrorMessage("Use 0 (zero) for a permanent ban.");
return;
}
}
// If a reason exists, use the given reason.
if (args.Parameters.Count > 3)
{
banReason = String.Join(" ", args.Parameters.Skip(3));
}
// Good case: Online ban for matching character.
if (players.Count == 1)
{
TSPlayer target = players[0];
if (target.HasPermission(Permissions.immunetoban) && !callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", target.Name);
return;
}
targetGeneralizedName = target.Name;
success = TShock.Bans.AddBan(target.IP, target.Name, target.UUID, target.Account?.Name ?? "", banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
// Since this is an online ban, we need to dc the player and tell them now.
if (success)
{
if (banLengthInSeconds == 0)
{
target.Disconnect(String.Format("Permanently banned for {0}", banReason));
}
else
{
target.Disconnect(String.Format("Banned for {0} seconds for {1}", banLengthInSeconds, banReason));
}
}
}
// Case: Players & user are invalid, could be IP?
// Note: Order matters. If this method is above the online player check,
// This enables you to ban an IP even if the player exists in the database as a player.
// You'll get two bans for the price of one, in theory, because both IP and user named IP will be banned.
// ??? edge cases are weird, but this is going to happen
// The only way around this is to either segregate off the IP code or do something else.
if (players.Count == 0)
{
// If the target is a valid IP...
string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
if (r.IsMatch(args.Parameters[1]))
{
targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan(args.Parameters[1], "", "", "", banReason,
false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
if (success && offlineUserAccount != null)
{
args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
args.Player.SendErrorMessage("Note: An account named with this IP address also exists.");
args.Player.SendErrorMessage("Note: It will also be banned.");
}
}
else
{
// Apparently there is no way to not IP ban someone
// This means that where we would normally just ban a "character name" here
// We can't because it requires some IP as a primary key.
if (offlineUserAccount == null)
{
args.Player.SendErrorMessage("Unable to ban target {0}.", args.Parameters[1]);
args.Player.SendErrorMessage("Target is not a valid IP address, a valid online player, or a known offline user.");
return;
}
}
}
// Case: Offline ban
if (players.Count == 0 && offlineUserAccount != null)
{
// Catch: we don't know an offline player's last login character name
// This means that we're banning their *user name* on the assumption that
// user name == character name
// (which may not be true)
// This needs to be fixed in a future implementation.
targetGeneralizedName = offlineUserAccount.Name;
if (TShock.Groups.GetGroupByName(offlineUserAccount.Group).HasPermission(Permissions.immunetoban) &&
!callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
return;
}
if (offlineUserAccount.KnownIps == null)
{
args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName);
return;
}
string lastIP = JsonConvert.DeserializeObject<List<string>>(offlineUserAccount.KnownIps).Last();
success =
TShock.Bans.AddBan(lastIP,
"", offlineUserAccount.UUID, offlineUserAccount.Name, banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
}
if (success)
{
args.Player.SendSuccessMessage("{0} was successfully banned.", targetGeneralizedName);
args.Player.SendInfoMessage("Length: {0}", banLengthInSeconds == 0 ? "Permanent." : banLengthInSeconds + " seconds.");
args.Player.SendInfoMessage("Reason: {0}", banReason);
if (!args.Silent)
{
if (banLengthInSeconds == 0)
{
TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}",
targetGeneralizedName, args.Player.Account.Name, banReason);
}
else
{
TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}",
targetGeneralizedName, banLengthInSeconds, args.Player.Account.Name, banReason);
}
}
}
else
{
args.Player.SendErrorMessage("{0} was NOT banned due to a database error or other system problem.", targetGeneralizedName);
args.Player.SendErrorMessage("If this player is online, they have NOT been kicked.");
args.Player.SendErrorMessage("Check the system logs for details.");
}
return;
}
#endregion
case "del":
#region Delete ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban del <player>", Specifier);
return;
}
string plStr = args.Parameters[1];
Ban ban = TShock.Bans.GetBanByName(plStr, false);
if (ban != null)
{
if (TShock.Bans.RemoveBan(ban.Name, true))
args.Player.SendSuccessMessage("Unbanned {0} ({1}).", ban.Name, ban.IP);
else
args.Player.SendErrorMessage("Failed to unban {0} ({1}), check logs.", ban.Name, ban.IP);
}
else
args.Player.SendErrorMessage("No bans for {0} exist.", plStr);
}
#endregion
return;
case "delip":
#region Delete IP ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban delip <ip>", Specifier);
return;
}
string ip = args.Parameters[1];
Ban ban = TShock.Bans.GetBanByIp(ip);
if (ban != null)
{
if (TShock.Bans.RemoveBan(ban.IP, false))
args.Player.SendSuccessMessage("Unbanned IP {0} ({1}).", ban.IP, ban.Name);
else
args.Player.SendErrorMessage("Failed to unban IP {0} ({1}), check logs.", ban.IP, ban.Name);
}
else
args.Player.SendErrorMessage("IP {0} is not banned.", ip);
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <target> <time> [reason] - Bans a player or user account if the player is not online.",
"del <player> - Unbans a player.",
"delip <ip> - Unbans an IP.",
"list [page] - Lists all player bans.",
"listip [page] - Lists all IP bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}ban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
{
return;
}
List<Ban> bans = TShock.Bans.GetBans();
var nameBans = from ban in bans
where !String.IsNullOrEmpty(ban.Name)
select ban.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(nameBans),
new PaginationTools.Settings
{
HeaderFormat = "Bans ({0}/{1}):",
FooterFormat = "Type {0}ban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no bans."
});
}
#endregion
return;
case "listip":
#region List IP bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
{
return;
}
List<Ban> bans = TShock.Bans.GetBans();
var ipBans = from ban in bans
where String.IsNullOrEmpty(ban.Name)
select ban.IP;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(ipBans),
new PaginationTools.Settings
{
HeaderFormat = "IP Bans ({0}/{1}):",
FooterFormat = "Type {0}ban listip {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no IP bans."
});
}
#endregion
return;
default:
args.Player.SendErrorMessage("Invalid subcommand! Type {0}ban help for more information.", Specifier);
return;
}
}
private static void Whitelist(CommandArgs args)
{
if (args.Parameters.Count == 1)
{
using (var tw = new StreamWriter(FileTools.WhitelistPath, true))
{
tw.WriteLine(args.Parameters[0]);
}
args.Player.SendSuccessMessage("Added " + args.Parameters[0] + " to the whitelist.");
}
}
private static void DisplayLogs(CommandArgs args)
{
args.Player.DisplayLogs = (!args.Player.DisplayLogs);
args.Player.SendSuccessMessage("You will " + (args.Player.DisplayLogs ? "now" : "no longer") + " receive logs.");
}
private static void SaveSSC(CommandArgs args)
{
if (Main.ServerSideCharacter)
{
args.Player.SendSuccessMessage("SSC has been saved.");
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.IsLoggedIn && !player.IsDisabledPendingTrashRemoval)
{
TShock.CharacterDB.InsertPlayerData(player, true);
}
}
}
}
private static void OverrideSSC(CommandArgs args)
{
if (!Main.ServerSideCharacter)
{
args.Player.SendErrorMessage("Server Side Characters is disabled.");
return;
}
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Correct usage: {0}overridessc|{0}ossc <player name>", Specifier);
return;
}
string playerNameToMatch = string.Join(" ", args.Parameters);
var matchedPlayers = TSPlayer.FindByNameOrID(playerNameToMatch);
if (matchedPlayers.Count < 1)
{
args.Player.SendErrorMessage("No players matched \"{0}\".", playerNameToMatch);
return;
}
else if (matchedPlayers.Count > 1)
{
args.Player.SendMultipleMatchError(matchedPlayers.Select(p => p.Name));
return;
}
TSPlayer matchedPlayer = matchedPlayers[0];
if (matchedPlayer.IsLoggedIn)
{
args.Player.SendErrorMessage("Player \"{0}\" is already logged in.", matchedPlayer.Name);
return;
}
if (!matchedPlayer.LoginFailsBySsi)
{
args.Player.SendErrorMessage("Player \"{0}\" has to perform a /login attempt first.", matchedPlayer.Name);
return;
}
if (matchedPlayer.IsDisabledPendingTrashRemoval)
{
args.Player.SendErrorMessage("Player \"{0}\" has to reconnect first.", matchedPlayer.Name);
return;
}
TShock.CharacterDB.InsertPlayerData(matchedPlayer);
args.Player.SendSuccessMessage("SSC of player \"{0}\" has been overriden.", matchedPlayer.Name);
}
private static void UploadJoinData(CommandArgs args)
{
TSPlayer targetPlayer = args.Player;
if (args.Parameters.Count == 1 && args.Player.HasPermission(Permissions.uploadothersdata))
{
List<TSPlayer> players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else if (players.Count == 0)
{
args.Player.SendErrorMessage("No player was found matching'{0}'", args.Parameters[0]);
return;
}
else
{
targetPlayer = players[0];
}
}
else if (args.Parameters.Count == 1)
{
args.Player.SendErrorMessage("You do not have permission to upload another player's character data.");
return;
}
else if (args.Parameters.Count > 0)
{
args.Player.SendErrorMessage("Usage: /uploadssc [playername]");
return;
}
else if (args.Parameters.Count == 0 && args.Player is TSServerPlayer)
{
args.Player.SendErrorMessage("A console can not upload their player data.");
args.Player.SendErrorMessage("Usage: /uploadssc [playername]");
return;
}
if (targetPlayer.IsLoggedIn)
{
if (TShock.CharacterDB.InsertSpecificPlayerData(targetPlayer, targetPlayer.DataWhenJoined))
{
targetPlayer.DataWhenJoined.RestoreCharacter(targetPlayer);
targetPlayer.SendSuccessMessage("Your local character data has been uploaded to the server.");
args.Player.SendSuccessMessage("The player's character data was successfully uploaded.");
}
else
{
args.Player.SendErrorMessage("Failed to upload your character data, are you logged in to an account?");
}
}
else
{
args.Player.SendErrorMessage("The target player has not logged in yet.");
}
}
private static void ForceHalloween(CommandArgs args)
{
TShock.Config.ForceHalloween = !TShock.Config.ForceHalloween;
Main.checkHalloween();
if (args.Silent)
args.Player.SendInfoMessage("{0}abled halloween mode!", (TShock.Config.ForceHalloween ? "en" : "dis"));
else
TSPlayer.All.SendInfoMessage("{0} {1}abled halloween mode!", args.Player.Name, (TShock.Config.ForceHalloween ? "en" : "dis"));
}
private static void ForceXmas(CommandArgs args)
{
TShock.Config.ForceXmas = !TShock.Config.ForceXmas;
Main.checkXMas();
if (args.Silent)
args.Player.SendInfoMessage("{0}abled Christmas mode!", (TShock.Config.ForceXmas ? "en" : "dis"));
else
TSPlayer.All.SendInfoMessage("{0} {1}abled Christmas mode!", args.Player.Name, (TShock.Config.ForceXmas ? "en" : "dis"));
}
private static void TempGroup(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendInfoMessage("Invalid usage");
args.Player.SendInfoMessage("Usage: {0}tempgroup <username> <new group> [time]", Specifier);
return;
}
List<TSPlayer> ply = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (ply.Count < 1)
{
args.Player.SendErrorMessage("Could not find player {0}.", args.Parameters[0]);
return;
}
if (ply.Count > 1)
{
args.Player.SendMultipleMatchError(ply.Select(p => p.Account.Name));
}
if (!TShock.Groups.GroupExists(args.Parameters[1]))
{
args.Player.SendErrorMessage("Could not find group {0}", args.Parameters[1]);
return;
}
if (args.Parameters.Count > 2)
{
int time;
if (!TShock.Utils.TryParseTime(args.Parameters[2], out time))
{
args.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
args.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
return;
}
ply[0].tempGroupTimer = new System.Timers.Timer(time * 1000);
ply[0].tempGroupTimer.Elapsed += ply[0].TempGroupTimerElapsed;
ply[0].tempGroupTimer.Start();
}
Group g = TShock.Groups.GetGroupByName(args.Parameters[1]);
ply[0].tempGroup = g;
if (args.Parameters.Count < 3)
{
args.Player.SendSuccessMessage(String.Format("You have changed {0}'s group to {1}", ply[0].Name, g.Name));
ply[0].SendSuccessMessage(String.Format("Your group has temporarily been changed to {0}", g.Name));
}
else
{
args.Player.SendSuccessMessage(String.Format("You have changed {0}'s group to {1} for {2}",
ply[0].Name, g.Name, args.Parameters[2]));
ply[0].SendSuccessMessage(String.Format("Your group has been changed to {0} for {1}",
g.Name, args.Parameters[2]));
}
}
private static void SubstituteUser(CommandArgs args)
{
if (args.Player.tempGroup != null)
{
args.Player.tempGroup = null;
args.Player.tempGroupTimer.Stop();
args.Player.SendSuccessMessage("Your previous permission set has been restored.");
return;
}
else
{
args.Player.tempGroup = new SuperAdminGroup();
args.Player.tempGroupTimer = new System.Timers.Timer(600 * 1000);
args.Player.tempGroupTimer.Elapsed += args.Player.TempGroupTimerElapsed;
args.Player.tempGroupTimer.Start();
args.Player.SendSuccessMessage("Your account has been elevated to Super Admin for 10 minutes.");
return;
}
}
#endregion Player Management Commands
#region Server Maintenence Commands
// Executes a command as a superuser if you have sudo rights.
private static void SubstituteUserDo(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Usage: /sudo [command].");
args.Player.SendErrorMessage("Example: /sudo /ban add Shank 2d Hacking.");
return;
}
string replacementCommand = String.Join(" ", args.Parameters);
args.Player.tempGroup = new SuperAdminGroup();
HandleCommand(args.Player, replacementCommand);
args.Player.tempGroup = null;
return;
}
private static void Broadcast(CommandArgs args)
{
string message = string.Join(" ", args.Parameters);
TShock.Utils.Broadcast(
"(Server Broadcast) " + message,
Convert.ToByte(TShock.Config.BroadcastRGB[0]), Convert.ToByte(TShock.Config.BroadcastRGB[1]),
Convert.ToByte(TShock.Config.BroadcastRGB[2]));
}
private static void Off(CommandArgs args)
{
if (Main.ServerSideCharacter)
{
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.IsLoggedIn && !player.IsDisabledPendingTrashRemoval)
{
player.SaveServerCharacter();
}
}
}
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
TShock.Utils.StopServer(true, reason);
}
private static void OffNoSave(CommandArgs args)
{
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
TShock.Utils.StopServer(false, reason);
}
private static void CheckUpdates(CommandArgs args)
{
args.Player.SendInfoMessage("An update check has been queued.");
try
{
TShock.UpdateManager.UpdateCheckAsync(null);
}
catch (Exception)
{
//swallow the exception
return;
}
}
private static void ManageRest(CommandArgs args)
{
string subCommand = "help";
if (args.Parameters.Count > 0)
subCommand = args.Parameters[0];
switch (subCommand.ToLower())
{
case "listusers":
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
Dictionary<string, int> restUsersTokens = new Dictionary<string, int>();
foreach (Rests.SecureRest.TokenData tokenData in TShock.RestApi.Tokens.Values)
{
if (restUsersTokens.ContainsKey(tokenData.Username))
restUsersTokens[tokenData.Username]++;
else
restUsersTokens.Add(tokenData.Username, 1);
}
List<string> restUsers = new List<string>(
restUsersTokens.Select(ut => string.Format("{0} ({1} tokens)", ut.Key, ut.Value)));
PaginationTools.SendPage(
args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(restUsers), new PaginationTools.Settings
{
NothingToDisplayString = "There are currently no active REST users.",
HeaderFormat = "Active REST Users ({0}/{1}):",
FooterFormat = "Type {0}rest listusers {{0}} for more.".SFormat(Specifier)
}
);
break;
}
case "destroytokens":
{
TShock.RestApi.Tokens.Clear();
args.Player.SendSuccessMessage("All REST tokens have been destroyed.");
break;
}
default:
{
args.Player.SendInfoMessage("Available REST Sub-Commands:");
args.Player.SendMessage("listusers - Lists all REST users and their current active tokens.", Color.White);
args.Player.SendMessage("destroytokens - Destroys all current REST tokens.", Color.White);
break;
}
}
}
#endregion Server Maintenence Commands
#region Cause Events and Spawn Monsters Commands
private static void DropMeteor(CommandArgs args)
{
WorldGen.spawnMeteor = false;
WorldGen.dropMeteor();
if (args.Silent)
{
args.Player.SendInfoMessage("A meteor has been triggered.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} triggered a meteor.", args.Player.Name);
}
}
private static void Fullmoon(CommandArgs args)
{
TSPlayer.Server.SetFullMoon();
if (args.Silent)
{
args.Player.SendInfoMessage("Started a full moon.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} started a full moon.", args.Player.Name);
}
}
private static void Bloodmoon(CommandArgs args)
{
TSPlayer.Server.SetBloodMoon(!Main.bloodMoon);
if (args.Silent)
{
args.Player.SendInfoMessage("{0}ed a blood moon.", Main.bloodMoon ? "start" : "stopp");
}
else
{
TSPlayer.All.SendInfoMessage("{0} {1}ed a blood moon.", args.Player.Name, Main.bloodMoon ? "start" : "stopp");
}
}
private static void Eclipse(CommandArgs args)
{
TSPlayer.Server.SetEclipse(!Main.eclipse);
if (args.Silent)
{
args.Player.SendInfoMessage("{0}ed an eclipse.", Main.eclipse ? "start" : "stopp");
}
else
{
TSPlayer.All.SendInfoMessage("{0} {1}ed an eclipse.", args.Player.Name, Main.eclipse ? "start" : "stopp");
}
}
private static void Invade(CommandArgs args)
{
if (Main.invasionSize <= 0)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}invade <invasion type> [wave]", Specifier);
return;
}
int wave = 1;
switch (args.Parameters[0].ToLower())
{
case "goblin":
case "goblins":
TSPlayer.All.SendInfoMessage("{0} has started a goblin army invasion.", args.Player.Name);
TShock.Utils.StartInvasion(1);
break;
case "snowman":
case "snowmen":
TSPlayer.All.SendInfoMessage("{0} has started a snow legion invasion.", args.Player.Name);
TShock.Utils.StartInvasion(2);
break;
case "pirate":
case "pirates":
TSPlayer.All.SendInfoMessage("{0} has started a pirate invasion.", args.Player.Name);
TShock.Utils.StartInvasion(3);
break;
case "pumpkin":
case "pumpkinmoon":
if (args.Parameters.Count > 1)
{
if (!int.TryParse(args.Parameters[1], out wave) || wave <= 0)
{
args.Player.SendErrorMessage("Invalid wave!");
break;
}
}
TSPlayer.Server.SetPumpkinMoon(true);
Main.bloodMoon = false;
NPC.waveKills = 0f;
NPC.waveNumber = wave;
TSPlayer.All.SendInfoMessage("{0} started the pumpkin moon at wave {1}!", args.Player.Name, wave);
break;
case "frost":
case "frostmoon":
if (args.Parameters.Count > 1)
{
if (!int.TryParse(args.Parameters[1], out wave) || wave <= 0)
{
args.Player.SendErrorMessage("Invalid wave!");
return;
}
}
TSPlayer.Server.SetFrostMoon(true);
Main.bloodMoon = false;
NPC.waveKills = 0f;
NPC.waveNumber = wave;
TSPlayer.All.SendInfoMessage("{0} started the frost moon at wave {1}!", args.Player.Name, wave);
break;
case "martian":
case "martians":
TSPlayer.All.SendInfoMessage("{0} has started a martian invasion.", args.Player.Name);
TShock.Utils.StartInvasion(4);
break;
}
}
else if (DD2Event.Ongoing)
{
DD2Event.StopInvasion();
TSPlayer.All.SendInfoMessage("{0} has ended the Old One's Army event.", args.Player.Name);
}
else
{
TSPlayer.All.SendInfoMessage("{0} has ended the invasion.", args.Player.Name);
Main.invasionSize = 0;
}
}
private static void ClearAnglerQuests(CommandArgs args)
{
if (args.Parameters.Count > 0)
{
var result = Main.anglerWhoFinishedToday.RemoveAll(s => s.ToLower().Equals(args.Parameters[0].ToLower()));
if (result > 0)
{
args.Player.SendSuccessMessage("Removed {0} players from the angler quest completion list for today.", result);
foreach (TSPlayer ply in TShock.Players.Where(p => p != null && p.Active && p.TPlayer.name.ToLower().Equals(args.Parameters[0].ToLower())))
{
//this will always tell the client that they have not done the quest today.
ply.SendData((PacketTypes)74, "");
}
}
else
args.Player.SendErrorMessage("Failed to find any users by that name on the list.");
}
else
{
Main.anglerWhoFinishedToday.Clear();
NetMessage.SendAnglerQuest(-1);
args.Player.SendSuccessMessage("Cleared all users from the angler quest completion list for today.");
}
}
private static void ToggleExpert(CommandArgs args)
{
Main.expertMode = !Main.expertMode;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
args.Player.SendSuccessMessage("Expert mode is now {0}.", Main.expertMode ? "on" : "off");
}
private static void Hardmode(CommandArgs args)
{
if (Main.hardMode)
{
Main.hardMode = false;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
args.Player.SendSuccessMessage("Hardmode is now off.");
}
else if (!TShock.Config.DisableHardmode)
{
WorldGen.StartHardmode();
args.Player.SendSuccessMessage("Hardmode is now on.");
}
else
{
args.Player.SendErrorMessage("Hardmode is disabled via config.");
}
}
private static void SpawnBoss(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnboss <boss type> [amount]", Specifier);
return;
}
int amount = 1;
if (args.Parameters.Count == 2 && (!int.TryParse(args.Parameters[1], out amount) || amount <= 0))
{
args.Player.SendErrorMessage("Invalid boss amount!");
return;
}
NPC npc = new NPC();
switch (args.Parameters[0].ToLower())
{
case "*":
case "all":
int[] npcIds = { 4, 13, 35, 50, 125, 126, 127, 134, 222, 245, 262, 266, 370, 398 };
TSPlayer.Server.SetTime(false, 0.0);
foreach (int i in npcIds)
{
npc.SetDefaults(i);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
}
TSPlayer.All.SendSuccessMessage("{0} has spawned all bosses {1} time(s).", args.Player.Name, amount);
return;
case "brain":
case "brain of cthulhu":
npc.SetDefaults(266);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Brain of Cthulhu {1} time(s).", args.Player.Name, amount);
return;
case "destroyer":
npc.SetDefaults(134);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Destroyer {1} time(s).", args.Player.Name, amount);
return;
case "duke":
case "duke fishron":
case "fishron":
npc.SetDefaults(370);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Duke Fishron {1} time(s).", args.Player.Name, amount);
return;
case "eater":
case "eater of worlds":
npc.SetDefaults(13);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Eater of Worlds {1} time(s).", args.Player.Name, amount);
return;
case "eye":
case "eye of cthulhu":
npc.SetDefaults(4);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Eye of Cthulhu {1} time(s).", args.Player.Name, amount);
return;
case "golem":
npc.SetDefaults(245);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Golem {1} time(s).", args.Player.Name, amount);
return;
case "king":
case "king slime":
npc.SetDefaults(50);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned King Slime {1} time(s).", args.Player.Name, amount);
return;
case "plantera":
npc.SetDefaults(262);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Plantera {1} time(s).", args.Player.Name, amount);
return;
case "prime":
case "skeletron prime":
npc.SetDefaults(127);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron Prime {1} time(s).", args.Player.Name, amount);
return;
case "queen":
case "queen bee":
npc.SetDefaults(222);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Queen Bee {1} time(s).", args.Player.Name, amount);
return;
case "skeletron":
npc.SetDefaults(35);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron {1} time(s).", args.Player.Name, amount);
return;
case "twins":
TSPlayer.Server.SetTime(false, 0.0);
npc.SetDefaults(125);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
npc.SetDefaults(126);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Twins {1} time(s).", args.Player.Name, amount);
return;
case "wof":
case "wall of flesh":
if (Main.wof >= 0)
{
args.Player.SendErrorMessage("There is already a Wall of Flesh!");
return;
}
if (args.Player.Y / 16f < Main.maxTilesY - 205)
{
args.Player.SendErrorMessage("You must spawn the Wall of Flesh in hell!");
return;
}
NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
TSPlayer.All.SendSuccessMessage("{0} has spawned the Wall of Flesh.", args.Player.Name);
return;
case "moon":
case "moon lord":
npc.SetDefaults(398);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Moon Lord {1} time(s).", args.Player.Name, amount);
return;
default:
args.Player.SendErrorMessage("Invalid boss type!");
return;
}
}
private static void SpawnMob(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnmob <mob type> [amount]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
int amount = 1;
if (args.Parameters.Count == 2 && !int.TryParse(args.Parameters[1], out amount))
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnmob <mob type> [amount]", Specifier);
return;
}
amount = Math.Min(amount, Main.maxNPCs);
var npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
}
else
{
var npc = npcs[0];
if (npc.type >= 1 && npc.type < Main.maxNPCTypes && npc.type != 113)
{
TSPlayer.Server.SpawnNPC(npc.netID, npc.FullName, amount, args.Player.TileX, args.Player.TileY, 50, 20);
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned {0} {1} time(s).", npc.FullName, amount);
}
else
{
TSPlayer.All.SendSuccessMessage("{0} has spawned {1} {2} time(s).", args.Player.Name, npc.FullName, amount);
}
}
else if (npc.type == 113)
{
if (Main.wof >= 0 || (args.Player.Y / 16f < (Main.maxTilesY - 205)))
{
args.Player.SendErrorMessage("Can't spawn Wall of Flesh!");
return;
}
NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned Wall of Flesh!");
}
else
{
TSPlayer.All.SendSuccessMessage("{0} has spawned a Wall of Flesh!", args.Player.Name);
}
}
else
{
args.Player.SendErrorMessage("Invalid mob type!");
}
}
}
#endregion Cause Events and Spawn Monsters Commands
#region Teleport Commands
private static void Home(CommandArgs args)
{
args.Player.Spawn();
args.Player.SendSuccessMessage("Teleported to your spawnpoint.");
}
private static void Spawn(CommandArgs args)
{
if (args.Player.Teleport(Main.spawnTileX * 16, (Main.spawnTileY * 16) - 48))
args.Player.SendSuccessMessage("Teleported to the map's spawnpoint.");
}
private static void TP(CommandArgs args)
{
if (args.Parameters.Count != 1 && args.Parameters.Count != 2)
{
if (args.Player.HasPermission(Permissions.tpothers))
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tp <player> [player 2]", Specifier);
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tp <player>", Specifier);
return;
}
if (args.Parameters.Count == 1)
{
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var target = players[0];
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", target.Name);
return;
}
if (args.Player.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
args.Player.SendSuccessMessage("Teleported to {0}.", target.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported to you.", args.Player.Name);
}
}
}
else
{
if (!args.Player.HasPermission(Permissions.tpothers))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
var players1 = TSPlayer.FindByNameOrID(args.Parameters[0]);
var players2 = TSPlayer.FindByNameOrID(args.Parameters[1]);
if (players2.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players2.Count > 1)
args.Player.SendMultipleMatchError(players2.Select(p => p.Name));
else if (players1.Count == 0)
{
if (args.Parameters[0] == "*")
{
if (!args.Player.HasPermission(Permissions.tpallothers))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
var target = players2[0];
foreach (var source in TShock.Players.Where(p => p != null && p != args.Player))
{
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
continue;
if (source.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
if (args.Player != source)
{
if (args.Player.HasPermission(Permissions.tpsilent))
source.SendSuccessMessage("You were teleported to {0}.", target.Name);
else
source.SendSuccessMessage("{0} teleported you to {1}.", args.Player.Name, target.Name);
}
if (args.Player != target)
{
if (args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} was teleported to you.", source.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported {1} to you.", args.Player.Name, source.Name);
}
}
}
args.Player.SendSuccessMessage("Teleported everyone to {0}.", target.Name);
}
else
args.Player.SendErrorMessage("Invalid player!");
}
else if (players1.Count > 1)
args.Player.SendMultipleMatchError(players1.Select(p => p.Name));
else
{
var source = players1[0];
if (!source.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", source.Name);
return;
}
var target = players2[0];
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", target.Name);
return;
}
args.Player.SendSuccessMessage("Teleported {0} to {1}.", source.Name, target.Name);
if (source.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
if (args.Player != source)
{
if (args.Player.HasPermission(Permissions.tpsilent))
source.SendSuccessMessage("You were teleported to {0}.", target.Name);
else
source.SendSuccessMessage("{0} teleported you to {1}.", args.Player.Name, target.Name);
}
if (args.Player != target)
{
if (args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} was teleported to you.", source.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported {1} to you.", args.Player.Name, source.Name);
}
}
}
}
}
private static void TPHere(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
if (args.Player.HasPermission(Permissions.tpallothers))
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tphere <player|*>", Specifier);
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tphere <player>", Specifier);
return;
}
string playerName = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(playerName);
if (players.Count == 0)
{
if (playerName == "*")
{
if (!args.Player.HasPermission(Permissions.tpallothers))
{
args.Player.SendErrorMessage("You do not have permission to use this command.");
return;
}
for (int i = 0; i < Main.maxPlayers; i++)
{
if (Main.player[i].active && (Main.player[i] != args.TPlayer))
{
if (TShock.Players[i].Teleport(args.TPlayer.position.X, args.TPlayer.position.Y))
TShock.Players[i].SendSuccessMessage(String.Format("You were teleported to {0}.", args.Player.Name));
}
}
args.Player.SendSuccessMessage("Teleported everyone to yourself.");
}
else
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var plr = players[0];
if (plr.Teleport(args.TPlayer.position.X, args.TPlayer.position.Y))
{
plr.SendInfoMessage("You were teleported to {0}.", args.Player.Name);
args.Player.SendSuccessMessage("Teleported {0} to yourself.", plr.Name);
}
}
}
private static void TPNpc(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tpnpc <NPC>", Specifier);
return;
}
var npcStr = string.Join(" ", args.Parameters);
var matches = new List<NPC>();
foreach (var npc in Main.npc.Where(npc => npc.active))
{
var englishName = EnglishLanguage.GetNpcNameById(npc.netID);
if (string.Equals(npc.FullName, npcStr, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(englishName, npcStr, StringComparison.InvariantCultureIgnoreCase))
{
matches = new List<NPC> { npc };
break;
}
if (npc.FullName.ToLowerInvariant().StartsWith(npcStr.ToLowerInvariant()) ||
englishName?.StartsWith(npcStr, StringComparison.InvariantCultureIgnoreCase) == true)
matches.Add(npc);
}
if (matches.Count > 1)
{
args.Player.SendMultipleMatchError(matches.Select(n => $"{n.FullName}({n.whoAmI})"));
return;
}
if (matches.Count == 0)
{
args.Player.SendErrorMessage("Invalid NPC!");
return;
}
var target = matches[0];
args.Player.Teleport(target.position.X, target.position.Y);
args.Player.SendSuccessMessage("Teleported to the '{0}'.", target.FullName);
}
private static void GetPos(CommandArgs args)
{
var player = args.Player.Name;
if (args.Parameters.Count > 0)
{
player = String.Join(" ", args.Parameters);
}
var players = TSPlayer.FindByNameOrID(player);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
args.Player.SendSuccessMessage("Location of {0} is ({1}, {2}).", players[0].Name, players[0].TileX, players[0].TileY);
}
}
private static void TPPos(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tppos <tile x> <tile y>", Specifier);
return;
}
int x, y;
if (!int.TryParse(args.Parameters[0], out x) || !int.TryParse(args.Parameters[1], out y))
{
args.Player.SendErrorMessage("Invalid tile positions!");
return;
}
x = Math.Max(0, x);
y = Math.Max(0, y);
x = Math.Min(x, Main.maxTilesX - 1);
y = Math.Min(y, Main.maxTilesY - 1);
args.Player.Teleport(16 * x, 16 * y);
args.Player.SendSuccessMessage("Teleported to {0}, {1}!", x, y);
}
private static void TPAllow(CommandArgs args)
{
if (!args.Player.TPAllow)
args.Player.SendSuccessMessage("You have removed your teleportation protection.");
if (args.Player.TPAllow)
args.Player.SendSuccessMessage("You have enabled teleportation protection.");
args.Player.TPAllow = !args.Player.TPAllow;
}
private static void Warp(CommandArgs args)
{
bool hasManageWarpPermission = args.Player.HasPermission(Permissions.managewarp);
if (args.Parameters.Count < 1)
{
if (hasManageWarpPermission)
{
args.Player.SendInfoMessage("Invalid syntax! Proper syntax: {0}warp [command] [arguments]", Specifier);
args.Player.SendInfoMessage("Commands: add, del, hide, list, send, [warpname]");
args.Player.SendInfoMessage("Arguments: add [warp name], del [warp name], list [page]");
args.Player.SendInfoMessage("Arguments: send [player] [warp name], hide [warp name] [Enable(true/false)]");
args.Player.SendInfoMessage("Examples: {0}warp add foobar, {0}warp hide foobar true, {0}warp foobar", Specifier);
return;
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp [name] or {0}warp list <page>", Specifier);
return;
}
}
if (args.Parameters[0].Equals("list"))
{
#region List warps
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> warpNames = from warp in TShock.Warps.Warps
where !warp.IsPrivate
select warp.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(warpNames),
new PaginationTools.Settings
{
HeaderFormat = "Warps ({0}/{1}):",
FooterFormat = "Type {0}warp list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no warps defined."
});
#endregion
}
else if (args.Parameters[0].ToLower() == "add" && hasManageWarpPermission)
{
#region Add warp
if (args.Parameters.Count == 2)
{
string warpName = args.Parameters[1];
if (warpName == "list" || warpName == "hide" || warpName == "del" || warpName == "add")
{
args.Player.SendErrorMessage("Name reserved, use a different name.");
}
else if (TShock.Warps.Add(args.Player.TileX, args.Player.TileY, warpName))
{
args.Player.SendSuccessMessage("Warp added: " + warpName);
}
else
{
args.Player.SendErrorMessage("Warp " + warpName + " already exists.");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp add [name]", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "del" && hasManageWarpPermission)
{
#region Del warp
if (args.Parameters.Count == 2)
{
string warpName = args.Parameters[1];
if (TShock.Warps.Remove(warpName))
{
args.Player.SendSuccessMessage("Warp deleted: " + warpName);
}
else
args.Player.SendErrorMessage("Could not find the specified warp.");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp del [name]", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "hide" && hasManageWarpPermission)
{
#region Hide warp
if (args.Parameters.Count == 3)
{
string warpName = args.Parameters[1];
bool state = false;
if (Boolean.TryParse(args.Parameters[2], out state))
{
if (TShock.Warps.Hide(args.Parameters[1], state))
{
if (state)
args.Player.SendSuccessMessage("Warp " + warpName + " is now private.");
else
args.Player.SendSuccessMessage("Warp " + warpName + " is now public.");
}
else
args.Player.SendErrorMessage("Could not find specified warp.");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp hide [name] <true/false>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp hide [name] <true/false>", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "send" && args.Player.HasPermission(Permissions.tpothers))
{
#region Warp send
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp send [player] [warpname]", Specifier);
return;
}
var foundplr = TSPlayer.FindByNameOrID(args.Parameters[1]);
if (foundplr.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (foundplr.Count > 1)
{
args.Player.SendMultipleMatchError(foundplr.Select(p => p.Name));
return;
}
string warpName = args.Parameters[2];
var warp = TShock.Warps.Find(warpName);
var plr = foundplr[0];
if (warp.Position != Point.Zero)
{
if (plr.Teleport(warp.Position.X * 16, warp.Position.Y * 16))
{
plr.SendSuccessMessage(String.Format("{0} warped you to {1}.", args.Player.Name, warpName));
args.Player.SendSuccessMessage(String.Format("You warped {0} to {1}.", plr.Name, warpName));
}
}
else
{
args.Player.SendErrorMessage("Specified warp not found.");
}
#endregion
}
else
{
string warpName = String.Join(" ", args.Parameters);
var warp = TShock.Warps.Find(warpName);
if (warp != null)
{
if (args.Player.Teleport(warp.Position.X * 16, warp.Position.Y * 16))
args.Player.SendSuccessMessage("Warped to " + warpName + ".");
}
else
{
args.Player.SendErrorMessage("The specified warp was not found.");
}
}
}
#endregion Teleport Commands
#region Group Management
private static void Group(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add group
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group add <group name> [permissions]", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
string permissions = String.Join(",", args.Parameters);
try
{
TShock.Groups.AddGroup(groupName, null, permissions, TShockAPI.Group.defaultChatColor);
args.Player.SendSuccessMessage("The group was added successfully!");
}
catch (GroupExistsException)
{
args.Player.SendErrorMessage("That group already exists!");
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "addperm":
#region Add permissions
{
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group addperm <group name> <permissions...>", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
if (groupName == "*")
{
foreach (Group g in TShock.Groups)
{
TShock.Groups.AddPermissions(g.Name, args.Parameters);
}
args.Player.SendSuccessMessage("Modified all groups.");
return;
}
try
{
string response = TShock.Groups.AddPermissions(groupName, args.Parameters);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
return;
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <name> <permissions...> - Adds a new group.",
"addperm <group> <permissions...> - Adds permissions to a group.",
"color <group> <rrr,ggg,bbb> - Changes a group's chat color.",
"rename <group> <new name> - Changes a group's name.",
"del <group> - Deletes a group.",
"delperm <group> <permissions...> - Removes permissions from a group.",
"list [page] - Lists groups.",
"listperm <group> [page] - Lists a group's permissions.",
"parent <group> <parent group> - Changes a group's parent group.",
"prefix <group> <prefix> - Changes a group's prefix.",
"suffix <group> <suffix> - Changes a group's suffix."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Group Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}group help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "parent":
#region Parent
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group parent <group name> [new parent group name]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newParentGroupName = string.Join(" ", args.Parameters.Skip(2));
if (!string.IsNullOrWhiteSpace(newParentGroupName) && !TShock.Groups.GroupExists(newParentGroupName))
{
args.Player.SendErrorMessage("No such group \"{0}\".", newParentGroupName);
return;
}
try
{
TShock.Groups.UpdateGroup(groupName, newParentGroupName, group.Permissions, group.ChatColor, group.Suffix, group.Prefix);
if (!string.IsNullOrWhiteSpace(newParentGroupName))
args.Player.SendSuccessMessage("Parent of group \"{0}\" set to \"{1}\".", groupName, newParentGroupName);
else
args.Player.SendSuccessMessage("Removed parent of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (group.Parent != null)
args.Player.SendSuccessMessage("Parent of \"{0}\" is \"{1}\".", group.Name, group.Parent.Name);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no parent.", group.Name);
}
}
#endregion
return;
case "suffix":
#region Suffix
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group suffix <group name> [new suffix]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newSuffix = string.Join(" ", args.Parameters.Skip(2));
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, group.ChatColor, newSuffix, group.Prefix);
if (!string.IsNullOrWhiteSpace(newSuffix))
args.Player.SendSuccessMessage("Suffix of group \"{0}\" set to \"{1}\".", groupName, newSuffix);
else
args.Player.SendSuccessMessage("Removed suffix of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (!string.IsNullOrWhiteSpace(group.Suffix))
args.Player.SendSuccessMessage("Suffix of \"{0}\" is \"{1}\".", group.Name, group.Suffix);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no suffix.", group.Name);
}
}
#endregion
return;
case "prefix":
#region Prefix
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group prefix <group name> [new prefix]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newPrefix = string.Join(" ", args.Parameters.Skip(2));
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, group.ChatColor, group.Suffix, newPrefix);
if (!string.IsNullOrWhiteSpace(newPrefix))
args.Player.SendSuccessMessage("Prefix of group \"{0}\" set to \"{1}\".", groupName, newPrefix);
else
args.Player.SendSuccessMessage("Removed prefix of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (!string.IsNullOrWhiteSpace(group.Prefix))
args.Player.SendSuccessMessage("Prefix of \"{0}\" is \"{1}\".", group.Name, group.Prefix);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no prefix.", group.Name);
}
}
#endregion
return;
case "color":
#region Color
{
if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group color <group name> [new color(000,000,000)]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count == 3)
{
string newColor = args.Parameters[2];
String[] parts = newColor.Split(',');
byte r;
byte g;
byte b;
if (parts.Length == 3 && byte.TryParse(parts[0], out r) && byte.TryParse(parts[1], out g) && byte.TryParse(parts[2], out b))
{
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, newColor, group.Suffix, group.Prefix);
args.Player.SendSuccessMessage("Color of group \"{0}\" set to \"{1}\".", groupName, newColor);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
args.Player.SendErrorMessage("Invalid syntax for color, expected \"rrr,ggg,bbb\"");
}
}
else
{
args.Player.SendSuccessMessage("Color of \"{0}\" is \"{1}\".", group.Name, group.ChatColor);
}
}
#endregion
return;
case "rename":
#region Rename group
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group rename <group> <new name>", Specifier);
return;
}
string group = args.Parameters[1];
string newName = args.Parameters[2];
try
{
string response = TShock.Groups.RenameGroup(group, newName);
args.Player.SendSuccessMessage(response);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
#endregion
return;
case "del":
#region Delete group
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group del <group name>", Specifier);
return;
}
try
{
string response = TShock.Groups.DeleteGroup(args.Parameters[1]);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "delperm":
#region Delete permissions
{
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group delperm <group name> <permissions...>", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
if (groupName == "*")
{
foreach (Group g in TShock.Groups)
{
TShock.Groups.DeletePermissions(g.Name, args.Parameters);
}
args.Player.SendSuccessMessage("Modified all groups.");
return;
}
try
{
string response = TShock.Groups.DeletePermissions(groupName, args.Parameters);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
return;
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "list":
#region List groups
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var groupNames = from grp in TShock.Groups.groups
select grp.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(groupNames),
new PaginationTools.Settings
{
HeaderFormat = "Groups ({0}/{1}):",
FooterFormat = "Type {0}group list {{0}} for more.".SFormat(Specifier)
});
}
#endregion
return;
case "listperm":
#region List permissions
{
if (args.Parameters.Count == 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group listperm <group name> [page]", Specifier);
return;
}
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 2, args.Player, out pageNumber))
return;
if (!TShock.Groups.GroupExists(args.Parameters[1]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
Group grp = TShock.Groups.GetGroupByName(args.Parameters[1]);
List<string> permissions = grp.TotalPermissions;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(permissions),
new PaginationTools.Settings
{
HeaderFormat = "Permissions for " + grp.Name + " ({0}/{1}):",
FooterFormat = "Type {0}group listperm {1} {{0}} for more.".SFormat(Specifier, grp.Name),
NothingToDisplayString = "There are currently no permissions for " + grp.Name + "."
});
}
#endregion
return;
}
}
#endregion Group Management
#region Item Management
private static void ItemBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add item
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban add <item name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
TShock.Itembans.AddNewBan(EnglishLanguage.GetItemNameById(items[0].type));
args.Player.SendSuccessMessage("Banned " + items[0].Name + ".");
}
}
#endregion
return;
case "allow":
#region Allow group to item
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban allow <item name> <group name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ItemBan ban = TShock.Itembans.GetItemBanByName(EnglishLanguage.GetItemNameById(items[0].type));
if (ban == null)
{
args.Player.SendErrorMessage("{0} is not banned.", items[0].Name);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.Itembans.AllowGroup(EnglishLanguage.GetItemNameById(items[0].type), args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to use {1}.", args.Parameters[2], items[0].Name);
}
else
{
args.Player.SendWarningMessage("{0} is already allowed to use {1}.", args.Parameters[2], items[0].Name);
}
}
}
#endregion
return;
case "del":
#region Delete item
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban del <item name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
TShock.Itembans.RemoveBan(EnglishLanguage.GetItemNameById(items[0].type));
args.Player.SendSuccessMessage("Unbanned " + items[0].Name + ".");
}
}
#endregion
return;
case "disallow":
#region Disllow group from item
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban disallow <item name> <group name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ItemBan ban = TShock.Itembans.GetItemBanByName(EnglishLanguage.GetItemNameById(items[0].type));
if (ban == null)
{
args.Player.SendErrorMessage("{0} is not banned.", items[0].Name);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.Itembans.RemoveGroup(EnglishLanguage.GetItemNameById(items[0].type), args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed to use {1}.", args.Parameters[2], items[0].Name);
}
else
{
args.Player.SendWarningMessage("{0} is already disallowed to use {1}.", args.Parameters[2], items[0].Name);
}
}
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <item> - Adds an item ban.",
"allow <item> <group> - Allows a group to use an item.",
"del <item> - Deletes an item ban.",
"disallow <item> <group> - Disallows a group from using an item.",
"list [page] - Lists all item bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Item Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}itemban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List items
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> itemNames = from itemBan in TShock.Itembans.ItemBans
select itemBan.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(itemNames),
new PaginationTools.Settings
{
HeaderFormat = "Item bans ({0}/{1}):",
FooterFormat = "Type {0}itemban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned items."
});
}
#endregion
return;
}
}
#endregion Item Management
#region Projectile Management
private static void ProjectileBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add projectile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban add <proj id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
TShock.ProjectileBans.AddNewBan(id);
args.Player.SendSuccessMessage("Banned projectile {0}.", id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "allow":
#region Allow group to projectile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban allow <id> <group>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ProjectileBan ban = TShock.ProjectileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Projectile {0} is not banned.", id);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.ProjectileBans.AllowGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to use projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendWarningMessage("{0} is already allowed to use projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "del":
#region Delete projectile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban del <id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
TShock.ProjectileBans.RemoveBan(id);
args.Player.SendSuccessMessage("Unbanned projectile {0}.", id);
return;
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "disallow":
#region Disallow group from projectile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban disallow <id> <group name>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ProjectileBan ban = TShock.ProjectileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Projectile {0} is not banned.", id);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.ProjectileBans.RemoveGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed from using projectile {1}.", args.Parameters[2], id);
return;
}
else
args.Player.SendWarningMessage("{0} is already prevented from using projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <projectile ID> - Adds a projectile ban.",
"allow <projectile ID> <group> - Allows a group to use a projectile.",
"del <projectile ID> - Deletes an projectile ban.",
"disallow <projectile ID> <group> - Disallows a group from using a projectile.",
"list [page] - Lists all projectile bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Projectile Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}projban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List projectiles
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<Int16> projectileIds = from projectileBan in TShock.ProjectileBans.ProjectileBans
select projectileBan.ID;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(projectileIds),
new PaginationTools.Settings
{
HeaderFormat = "Projectile bans ({0}/{1}):",
FooterFormat = "Type {0}projban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned projectiles."
});
}
#endregion
return;
}
}
#endregion Projectile Management
#region Tile Management
private static void TileBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add tile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban add <tile id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
TShock.TileBans.AddNewBan(id);
args.Player.SendSuccessMessage("Banned tile {0}.", id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "allow":
#region Allow group to place tile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban allow <id> <group>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
TileBan ban = TShock.TileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Tile {0} is not banned.", id);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.TileBans.AllowGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to place tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendWarningMessage("{0} is already allowed to place tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "del":
#region Delete tile ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban del <id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
TShock.TileBans.RemoveBan(id);
args.Player.SendSuccessMessage("Unbanned tile {0}.", id);
return;
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "disallow":
#region Disallow group from placing tile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban disallow <id> <group name>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
TileBan ban = TShock.TileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Tile {0} is not banned.", id);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.TileBans.RemoveGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed from placing tile {1}.", args.Parameters[2], id);
return;
}
else
args.Player.SendWarningMessage("{0} is already prevented from placing tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <tile ID> - Adds a tile ban.",
"allow <tile ID> <group> - Allows a group to place a tile.",
"del <tile ID> - Deletes a tile ban.",
"disallow <tile ID> <group> - Disallows a group from place a tile.",
"list [page] - Lists all tile bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Tile Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}tileban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List tile bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<Int16> tileIds = from tileBan in TShock.TileBans.TileBans
select tileBan.ID;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(tileIds),
new PaginationTools.Settings
{
HeaderFormat = "Tile bans ({0}/{1}):",
FooterFormat = "Type {0}tileban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned tiles."
});
}
#endregion
return;
}
}
#endregion Tile Management
#region Server Config Commands
private static void SetSpawn(CommandArgs args)
{
Main.spawnTileX = args.Player.TileX + 1;
Main.spawnTileY = args.Player.TileY + 3;
SaveManager.Instance.SaveWorld(false);
args.Player.SendSuccessMessage("Spawn has now been set at your location.");
}
private static void SetDungeon(CommandArgs args)
{
Main.dungeonX = args.Player.TileX + 1;
Main.dungeonY = args.Player.TileY + 3;
SaveManager.Instance.SaveWorld(false);
args.Player.SendSuccessMessage("The dungeon's position has now been set at your location.");
}
private static void Reload(CommandArgs args)
{
TShock.Utils.Reload();
Hooks.GeneralHooks.OnReloadEvent(args.Player);
args.Player.SendSuccessMessage(
"Configuration, permissions, and regions reload complete. Some changes may require a server restart.");
}
private static void ServerPassword(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}serverpassword \"<new password>\"", Specifier);
return;
}
string passwd = args.Parameters[0];
TShock.Config.ServerPassword = passwd;
args.Player.SendSuccessMessage(string.Format("Server password has been changed to: {0}.", passwd));
}
private static void Save(CommandArgs args)
{
SaveManager.Instance.SaveWorld(false);
foreach (TSPlayer tsply in TShock.Players.Where(tsply => tsply != null))
{
tsply.SaveServerCharacter();
}
args.Player.SendSuccessMessage("Save succeeded.");
}
private static void Settle(CommandArgs args)
{
if (Liquid.panicMode)
{
args.Player.SendWarningMessage("Liquids are already settling!");
return;
}
Liquid.StartPanic();
args.Player.SendInfoMessage("Settling liquids.");
}
private static void MaxSpawns(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendInfoMessage("Current maximum spawns: {0}", TShock.Config.DefaultMaximumSpawns);
return;
}
if (String.Equals(args.Parameters[0], "default", StringComparison.CurrentCultureIgnoreCase))
{
TShock.Config.DefaultMaximumSpawns = NPC.defaultMaxSpawns = 5;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the maximum spawns to 5.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the maximum spawns to 5.", args.Player.Name);
}
return;
}
int maxSpawns = -1;
if (!int.TryParse(args.Parameters[0], out maxSpawns) || maxSpawns < 0 || maxSpawns > Main.maxNPCs)
{
args.Player.SendWarningMessage("Invalid maximum spawns! Acceptable range is {0} to {1}", 0, Main.maxNPCs);
return;
}
TShock.Config.DefaultMaximumSpawns = NPC.defaultMaxSpawns = maxSpawns;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the maximum spawns to {0}.", maxSpawns);
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the maximum spawns to {1}.", args.Player.Name, maxSpawns);
}
}
private static void SpawnRate(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendInfoMessage("Current spawn rate: {0}", TShock.Config.DefaultSpawnRate);
return;
}
if (String.Equals(args.Parameters[0], "default", StringComparison.CurrentCultureIgnoreCase))
{
TShock.Config.DefaultSpawnRate = NPC.defaultSpawnRate = 600;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the spawn rate to 600.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the spawn rate to 600.", args.Player.Name);
}
return;
}
int spawnRate = -1;
if (!int.TryParse(args.Parameters[0], out spawnRate) || spawnRate < 0)
{
args.Player.SendWarningMessage("Invalid spawn rate!");
return;
}
TShock.Config.DefaultSpawnRate = NPC.defaultSpawnRate = spawnRate;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the spawn rate to {0}.", spawnRate);
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the spawn rate to {1}.", args.Player.Name, spawnRate);
}
}
#endregion Server Config Commands
#region Time/PvpFun Commands
private static void Time(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
double time = Main.time / 3600.0;
time += 4.5;
if (!Main.dayTime)
time += 15.0;
time = time % 24.0;
args.Player.SendInfoMessage("The current time is {0}:{1:D2}.", (int)Math.Floor(time), (int)Math.Floor((time % 1.0) * 60.0));
return;
}
switch (args.Parameters[0].ToLower())
{
case "day":
TSPlayer.Server.SetTime(true, 0.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 4:30.", args.Player.Name);
break;
case "night":
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 19:30.", args.Player.Name);
break;
case "noon":
TSPlayer.Server.SetTime(true, 27000.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 12:00.", args.Player.Name);
break;
case "midnight":
TSPlayer.Server.SetTime(false, 16200.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 0:00.", args.Player.Name);
break;
default:
string[] array = args.Parameters[0].Split(':');
if (array.Length != 2)
{
args.Player.SendErrorMessage("Invalid time string! Proper format: hh:mm, in 24-hour time.");
return;
}
int hours;
int minutes;
if (!int.TryParse(array[0], out hours) || hours < 0 || hours > 23
|| !int.TryParse(array[1], out minutes) || minutes < 0 || minutes > 59)
{
args.Player.SendErrorMessage("Invalid time string! Proper format: hh:mm, in 24-hour time.");
return;
}
decimal time = hours + (minutes / 60.0m);
time -= 4.50m;
if (time < 0.00m)
time += 24.00m;
if (time >= 15.00m)
{
TSPlayer.Server.SetTime(false, (double)((time - 15.00m) * 3600.0m));
}
else
{
TSPlayer.Server.SetTime(true, (double)(time * 3600.0m));
}
TSPlayer.All.SendInfoMessage("{0} set the time to {1}:{2:D2}.", args.Player.Name, hours, minutes);
break;
}
}
private static void Sandstorm(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}sandstorm <stop/start>", Specifier);
return;
}
switch (args.Parameters[0].ToLowerInvariant())
{
case "start":
Terraria.GameContent.Events.Sandstorm.StartSandstorm();
TSPlayer.All.SendInfoMessage("{0} started a sandstorm.", args.Player.Name);
break;
case "stop":
Terraria.GameContent.Events.Sandstorm.StopSandstorm();
TSPlayer.All.SendInfoMessage("{0} stopped the sandstorm.", args.Player.Name);
break;
default:
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}sandstorm <stop/start>", Specifier);
break;
}
}
private static void Rain(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rain [slime] <stop/start>", Specifier);
return;
}
int switchIndex = 0;
if (args.Parameters.Count == 2 && args.Parameters[0].ToLowerInvariant() == "slime")
{
switchIndex = 1;
}
switch (args.Parameters[switchIndex].ToLower())
{
case "start":
if (switchIndex == 1)
{
Main.StartSlimeRain(false);
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} caused it to rain slime.", args.Player.Name);
}
else
{
Main.StartRain();
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} caused it to rain.", args.Player.Name);
}
break;
case "stop":
if (switchIndex == 1)
{
Main.StopSlimeRain(false);
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} ended the slimey downpour.", args.Player.Name);
}
else
{
Main.StopRain();
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} ended the downpour.", args.Player.Name);
}
break;
default:
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rain [slime] <stop/start>", Specifier);
break;
}
}
private static void Slap(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}slap <player> [damage]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
string plStr = args.Parameters[0];
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
int damage = 5;
if (args.Parameters.Count == 2)
{
int.TryParse(args.Parameters[1], out damage);
}
if (!args.Player.HasPermission(Permissions.kill))
{
damage = TShock.Utils.Clamp(damage, 15, 0);
}
plr.DamagePlayer(damage);
TSPlayer.All.SendInfoMessage("{0} slapped {1} for {2} damage.", args.Player.Name, plr.Name, damage);
TShock.Log.Info("{0} slapped {1} for {2} damage.", args.Player.Name, plr.Name, damage);
}
}
private static void Wind(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}wind <speed>", Specifier);
return;
}
int speed;
if (!int.TryParse(args.Parameters[0], out speed) || speed * 100 < 0)
{
args.Player.SendErrorMessage("Invalid wind speed!");
return;
}
Main.windSpeed = speed;
Main.windSpeedSet = speed;
Main.windSpeedSpeed = 0f;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} changed the wind speed to {1}.", args.Player.Name, speed);
}
#endregion Time/PvpFun Commands
#region Region Commands
private static void Region(CommandArgs args)
{
string cmd = "help";
if (args.Parameters.Count > 0)
{
cmd = args.Parameters[0].ToLower();
}
switch (cmd)
{
case "name":
{
{
args.Player.SendInfoMessage("Hit a block to get the name of the region");
args.Player.AwaitingName = true;
args.Player.AwaitingNameParameters = args.Parameters.Skip(1).ToArray();
}
break;
}
case "set":
{
int choice = 0;
if (args.Parameters.Count == 2 &&
int.TryParse(args.Parameters[1], out choice) &&
choice >= 1 && choice <= 2)
{
args.Player.SendInfoMessage("Hit a block to Set Point " + choice);
args.Player.AwaitingTempPoint = choice;
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /region set <1/2>");
}
break;
}
case "define":
{
if (args.Parameters.Count > 1)
{
if (!args.Player.TempPoints.Any(p => p == Point.Zero))
{
string regionName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
var x = Math.Min(args.Player.TempPoints[0].X, args.Player.TempPoints[1].X);
var y = Math.Min(args.Player.TempPoints[0].Y, args.Player.TempPoints[1].Y);
var width = Math.Abs(args.Player.TempPoints[0].X - args.Player.TempPoints[1].X);
var height = Math.Abs(args.Player.TempPoints[0].Y - args.Player.TempPoints[1].Y);
if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.Account.Name,
Main.worldID.ToString()))
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
args.Player.SendInfoMessage("Set region " + regionName);
}
else
{
args.Player.SendErrorMessage("Region " + regionName + " already exists");
}
}
else
{
args.Player.SendErrorMessage("Points not set up yet");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region define <name>", Specifier);
break;
}
case "protect":
{
if (args.Parameters.Count == 3)
{
string regionName = args.Parameters[1];
if (args.Parameters[2].ToLower() == "true")
{
if (TShock.Regions.SetRegionState(regionName, true))
args.Player.SendInfoMessage("Protected region " + regionName);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else if (args.Parameters[2].ToLower() == "false")
{
if (TShock.Regions.SetRegionState(regionName, false))
args.Player.SendInfoMessage("Unprotected region " + regionName);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region protect <name> <true/false>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /region protect <name> <true/false>", Specifier);
break;
}
case "delete":
{
if (args.Parameters.Count > 1)
{
string regionName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
if (TShock.Regions.DeleteRegion(regionName))
{
args.Player.SendInfoMessage("Deleted region \"{0}\".", regionName);
}
else
args.Player.SendErrorMessage("Could not find the specified region!");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region delete <name>", Specifier);
break;
}
case "clear":
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
args.Player.SendInfoMessage("Cleared temporary points.");
args.Player.AwaitingTempPoint = 0;
break;
}
case "allow":
{
if (args.Parameters.Count > 2)
{
string playerName = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.AddNewUser(regionName, playerName))
{
args.Player.SendInfoMessage("Added user " + playerName + " to " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Player " + playerName + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region allow <name> <region>", Specifier);
break;
}
case "remove":
if (args.Parameters.Count > 2)
{
string playerName = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.RemoveUser(regionName, playerName))
{
args.Player.SendInfoMessage("Removed user " + playerName + " from " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Player " + playerName + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region remove <name> <region>", Specifier);
break;
case "allowg":
{
if (args.Parameters.Count > 2)
{
string group = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.Groups.GroupExists(group))
{
if (TShock.Regions.AllowGroup(regionName, group))
{
args.Player.SendInfoMessage("Added group " + group + " to " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Group " + group + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region allowg <group> <region>", Specifier);
break;
}
case "removeg":
if (args.Parameters.Count > 2)
{
string group = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.Groups.GroupExists(group))
{
if (TShock.Regions.RemoveGroup(regionName, group))
{
args.Player.SendInfoMessage("Removed group " + group + " from " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Group " + group + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region removeg <group> <region>", Specifier);
break;
case "list":
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> regionNames = from region in TShock.Regions.Regions
where region.WorldID == Main.worldID.ToString()
select region.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(regionNames),
new PaginationTools.Settings
{
HeaderFormat = "Regions ({0}/{1}):",
FooterFormat = "Type {0}region list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no regions defined."
});
break;
}
case "info":
{
if (args.Parameters.Count == 1 || args.Parameters.Count > 4)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region info <region> [-d] [page]", Specifier);
break;
}
string regionName = args.Parameters[1];
bool displayBoundaries = args.Parameters.Skip(2).Any(
p => p.Equals("-d", StringComparison.InvariantCultureIgnoreCase)
);
Region region = TShock.Regions.GetRegionByName(regionName);
if (region == null)
{
args.Player.SendErrorMessage("Region \"{0}\" does not exist.", regionName);
break;
}
int pageNumberIndex = displayBoundaries ? 3 : 2;
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, pageNumberIndex, args.Player, out pageNumber))
break;
List<string> lines = new List<string>
{
string.Format("X: {0}; Y: {1}; W: {2}; H: {3}, Z: {4}", region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Z),
string.Concat("Owner: ", region.Owner),
string.Concat("Protected: ", region.DisableBuild.ToString()),
};
if (region.AllowedIDs.Count > 0)
{
IEnumerable<string> sharedUsersSelector = region.AllowedIDs.Select(userId =>
{
UserAccount account = TShock.UserAccounts.GetUserAccountByID(userId);
if (account != null)
return account.Name;
return string.Concat("{ID: ", userId, "}");
});
List<string> extraLines = PaginationTools.BuildLinesFromTerms(sharedUsersSelector.Distinct());
extraLines[0] = "Shared with: " + extraLines[0];
lines.AddRange(extraLines);
}
else
{
lines.Add("Region is not shared with any users.");
}
if (region.AllowedGroups.Count > 0)
{
List<string> extraLines = PaginationTools.BuildLinesFromTerms(region.AllowedGroups.Distinct());
extraLines[0] = "Shared with groups: " + extraLines[0];
lines.AddRange(extraLines);
}
else
{
lines.Add("Region is not shared with any groups.");
}
PaginationTools.SendPage(
args.Player, pageNumber, lines, new PaginationTools.Settings
{
HeaderFormat = string.Format("Information About Region \"{0}\" ({{0}}/{{1}}):", region.Name),
FooterFormat = string.Format("Type {0}region info {1} {{0}} for more information.", Specifier, regionName)
}
);
if (displayBoundaries)
{
Rectangle regionArea = region.Area;
foreach (Point boundaryPoint in Utils.Instance.EnumerateRegionBoundaries(regionArea))
{
// Preferring dotted lines as those should easily be distinguishable from actual wires.
if ((boundaryPoint.X + boundaryPoint.Y & 1) == 0)
{
// Could be improved by sending raw tile data to the client instead but not really
// worth the effort as chances are very low that overwriting the wire for a few
// nanoseconds will cause much trouble.
ITile tile = Main.tile[boundaryPoint.X, boundaryPoint.Y];
bool oldWireState = tile.wire();
tile.wire(true);
try
{
args.Player.SendTileSquare(boundaryPoint.X, boundaryPoint.Y, 1);
}
finally
{
tile.wire(oldWireState);
}
}
}
Timer boundaryHideTimer = null;
boundaryHideTimer = new Timer((state) =>
{
foreach (Point boundaryPoint in Utils.Instance.EnumerateRegionBoundaries(regionArea))
if ((boundaryPoint.X + boundaryPoint.Y & 1) == 0)
args.Player.SendTileSquare(boundaryPoint.X, boundaryPoint.Y, 1);
Debug.Assert(boundaryHideTimer != null);
boundaryHideTimer.Dispose();
},
null, 5000, Timeout.Infinite
);
}
break;
}
case "z":
{
if (args.Parameters.Count == 3)
{
string regionName = args.Parameters[1];
int z = 0;
if (int.TryParse(args.Parameters[2], out z))
{
if (TShock.Regions.SetZ(regionName, z))
args.Player.SendInfoMessage("Region's z is now " + z);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region z <name> <#>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region z <name> <#>", Specifier);
break;
}
case "resize":
case "expand":
{
if (args.Parameters.Count == 4)
{
int direction;
switch (args.Parameters[2])
{
case "u":
case "up":
{
direction = 0;
break;
}
case "r":
case "right":
{
direction = 1;
break;
}
case "d":
case "down":
{
direction = 2;
break;
}
case "l":
case "left":
{
direction = 3;
break;
}
default:
{
direction = -1;
break;
}
}
int addAmount;
int.TryParse(args.Parameters[3], out addAmount);
if (TShock.Regions.ResizeRegion(args.Parameters[1], addAmount, direction))
{
args.Player.SendInfoMessage("Region Resized Successfully!");
TShock.Regions.Reload();
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize <region> <u/d/l/r> <amount>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize <region> <u/d/l/r> <amount>", Specifier);
break;
}
case "rename":
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region rename <region> <new name>", Specifier);
break;
}
else
{
string oldName = args.Parameters[1];
string newName = args.Parameters[2];
if (oldName == newName)
{
args.Player.SendErrorMessage("Error: both names are the same.");
break;
}
Region oldRegion = TShock.Regions.GetRegionByName(oldName);
if (oldRegion == null)
{
args.Player.SendErrorMessage("Invalid region \"{0}\".", oldName);
break;
}
Region newRegion = TShock.Regions.GetRegionByName(newName);
if (newRegion != null)
{
args.Player.SendErrorMessage("Region \"{0}\" already exists.", newName);
break;
}
if(TShock.Regions.RenameRegion(oldName, newName))
{
args.Player.SendInfoMessage("Region renamed successfully!");
}
else
{
args.Player.SendErrorMessage("Failed to rename the region.");
}
}
break;
}
case "tp":
{
if (!args.Player.HasPermission(Permissions.tp))
{
args.Player.SendErrorMessage("You don't have the necessary permission to do that.");
break;
}
if (args.Parameters.Count <= 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region tp <region>.", Specifier);
break;
}
string regionName = string.Join(" ", args.Parameters.Skip(1));
Region region = TShock.Regions.GetRegionByName(regionName);
if (region == null)
{
args.Player.SendErrorMessage("Region \"{0}\" does not exist.", regionName);
break;
}
args.Player.Teleport(region.Area.Center.X * 16, region.Area.Center.Y * 16);
break;
}
case "help":
default:
{
int pageNumber;
int pageParamIndex = 0;
if (args.Parameters.Count > 1)
pageParamIndex = 1;
if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
return;
List<string> lines = new List<string> {
"set <1/2> - Sets the temporary region points.",
"clear - Clears the temporary region points.",
"define <name> - Defines the region with the given name.",
"delete <name> - Deletes the given region.",
"name [-u][-z][-p] - Shows the name of the region at the given point.",
"rename <region> <new name> - Renames the given region.",
"list - Lists all regions.",
"resize <region> <u/d/l/r> <amount> - Resizes a region.",
"allow <user> <region> - Allows a user to a region.",
"remove <user> <region> - Removes a user from a region.",
"allowg <group> <region> - Allows a user group to a region.",
"removeg <group> <region> - Removes a user group from a region.",
"info <region> [-d] - Displays several information about the given region.",
"protect <name> <true/false> - Sets whether the tiles inside the region are protected or not.",
"z <name> <#> - Sets the z-order of the region.",
};
if (args.Player.HasPermission(Permissions.tp))
lines.Add("tp <region> - Teleports you to the given region's center.");
PaginationTools.SendPage(
args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Available Region Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}region {{0}} for more sub-commands.".SFormat(Specifier)
}
);
break;
}
}
}
#endregion Region Commands
#region World Protection Commands
private static void ToggleAntiBuild(CommandArgs args)
{
TShock.Config.DisableBuild = !TShock.Config.DisableBuild;
TSPlayer.All.SendSuccessMessage(string.Format("Anti-build is now {0}.", (TShock.Config.DisableBuild ? "on" : "off")));
}
private static void ProtectSpawn(CommandArgs args)
{
TShock.Config.SpawnProtection = !TShock.Config.SpawnProtection;
TSPlayer.All.SendSuccessMessage(string.Format("Spawn is now {0}.", (TShock.Config.SpawnProtection ? "protected" : "open")));
}
#endregion World Protection Commands
#region General Commands
private static void Help(CommandArgs args)
{
if (args.Parameters.Count > 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}help <command/page>", Specifier);
return;
}
int pageNumber;
if (args.Parameters.Count == 0 || int.TryParse(args.Parameters[0], out pageNumber))
{
if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber))
{
return;
}
IEnumerable<string> cmdNames = from cmd in ChatCommands
where cmd.CanRun(args.Player) && (cmd.Name != "auth" || TShock.SetupToken != 0)
select Specifier + cmd.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cmdNames),
new PaginationTools.Settings
{
HeaderFormat = "Commands ({0}/{1}):",
FooterFormat = "Type {0}help {{0}} for more.".SFormat(Specifier)
});
}
else
{
string commandName = args.Parameters[0].ToLower();
if (commandName.StartsWith(Specifier))
{
commandName = commandName.Substring(1);
}
Command command = ChatCommands.Find(c => c.Names.Contains(commandName));
if (command == null)
{
args.Player.SendErrorMessage("Invalid command.");
return;
}
if (!command.CanRun(args.Player))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
args.Player.SendSuccessMessage("{0}{1} help: ", Specifier, command.Name);
if (command.HelpDesc == null)
{
args.Player.SendInfoMessage(command.HelpText);
return;
}
foreach (string line in command.HelpDesc)
{
args.Player.SendInfoMessage(line);
}
}
}
private static void GetVersion(CommandArgs args)
{
args.Player.SendInfoMessage("TShock: {0} ({1}).", TShock.VersionNum, TShock.VersionCodename);
}
private static void ListConnectedPlayers(CommandArgs args)
{
bool invalidUsage = (args.Parameters.Count > 2);
bool displayIdsRequested = false;
int pageNumber = 1;
if (!invalidUsage)
{
foreach (string parameter in args.Parameters)
{
if (parameter.Equals("-i", StringComparison.InvariantCultureIgnoreCase))
{
displayIdsRequested = true;
continue;
}
if (!int.TryParse(parameter, out pageNumber))
{
invalidUsage = true;
break;
}
}
}
if (invalidUsage)
{
args.Player.SendErrorMessage("Invalid usage, proper usage: {0}who [-i] [pagenumber]", Specifier);
return;
}
if (displayIdsRequested && !args.Player.HasPermission(Permissions.seeids))
{
args.Player.SendErrorMessage("You don't have the required permission to list player ids.");
return;
}
args.Player.SendSuccessMessage("Online Players ({0}/{1})", TShock.Utils.GetActivePlayerCount(), TShock.Config.MaxSlots);
var players = new List<string>();
foreach (TSPlayer ply in TShock.Players)
{
if (ply != null && ply.Active)
{
if (displayIdsRequested)
{
players.Add(String.Format("{0} (ID: {1}{2})", ply.Name, ply.Index, ply.Account != null ? ", ID: " + ply.Account.ID : ""));
}
else
{
players.Add(ply.Name);
}
}
}
PaginationTools.SendPage(
args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(players),
new PaginationTools.Settings
{
IncludeHeader = false,
FooterFormat = string.Format("Type {0}who {1}{{0}} for more.", Specifier, displayIdsRequested ? "-i " : string.Empty)
}
);
}
private static void SetupToken(CommandArgs args)
{
if (TShock.SetupToken == 0)
{
if (args.Player.Group.Name == new SuperAdminGroup().Name)
args.Player.SendInfoMessage("The initial setup system is already disabled.");
else
{
args.Player.SendWarningMessage("The initial setup system is disabled. This incident has been logged.");
TShock.Log.Warn("{0} attempted to use the initial setup system even though it's disabled.", args.Player.IP);
return;
}
}
// If the user account is already a superadmin (permanent), disable the system
if (args.Player.IsLoggedIn && args.Player.tempGroup == null)
{
args.Player.SendSuccessMessage("Your new account has been verified, and the {0}setup system has been turned off.", Specifier);
args.Player.SendSuccessMessage("You can always use the {0}user command to manage players.", Specifier);
args.Player.SendSuccessMessage("The setup system will remain disabled as long as a superadmin exists (even if you delete setup.lock).");
args.Player.SendSuccessMessage("Share your server, talk with other admins, and more on our forums -- https://tshock.co/");
args.Player.SendSuccessMessage("Thank you for using TShock for Terraria!");
FileTools.CreateFile(Path.Combine(TShock.SavePath, "setup.lock"));
File.Delete(Path.Combine(TShock.SavePath, "setup-code.txt"));
TShock.SetupToken = 0;
return;
}
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("You must provide a setup code!");
return;
}
int givenCode;
if (!Int32.TryParse(args.Parameters[0], out givenCode) || givenCode != TShock.SetupToken)
{
args.Player.SendErrorMessage("Incorrect setup code. This incident has been logged.");
TShock.Log.Warn(args.Player.IP + " attempted to use an incorrect setup code.");
return;
}
if (args.Player.Group.Name != "superadmin")
args.Player.tempGroup = new SuperAdminGroup();
args.Player.SendInfoMessage("Temporary system access has been given to you, so you can run one command.");
args.Player.SendInfoMessage("Please use the following to create a permanent account for you.");
args.Player.SendInfoMessage("{0}user add <username> <password> owner", Specifier);
args.Player.SendInfoMessage("Creates: <username> with the password <password> as part of the owner group.");
args.Player.SendInfoMessage("Please use {0}login <username> <password> after this process.", Specifier);
args.Player.SendInfoMessage("If you understand, please {0}login <username> <password> now, and then type {0}setup.", Specifier);
return;
}
private static void ThirdPerson(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}me <text>", Specifier);
return;
}
if (args.Player.mute)
args.Player.SendErrorMessage("You are muted.");
else
TSPlayer.All.SendMessage(string.Format("*{0} {1}", args.Player.Name, String.Join(" ", args.Parameters)), 205, 133, 63);
}
private static void PartyChat(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}p <team chat text>", Specifier);
return;
}
int playerTeam = args.Player.Team;
if (args.Player.mute)
args.Player.SendErrorMessage("You are muted.");
else if (playerTeam != 0)
{
string msg = string.Format("<{0}> {1}", args.Player.Name, String.Join(" ", args.Parameters));
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active && player.Team == playerTeam)
player.SendMessage(msg, Main.teamColor[playerTeam].R, Main.teamColor[playerTeam].G, Main.teamColor[playerTeam].B);
}
}
else
args.Player.SendErrorMessage("You are not in a party!");
}
private static void Mute(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}mute <player> [reason]", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else if (players[0].HasPermission(Permissions.mute))
{
args.Player.SendErrorMessage("You cannot mute this player.");
}
else if (players[0].mute)
{
var plr = players[0];
plr.mute = false;
TSPlayer.All.SendInfoMessage("{0} has been unmuted by {1}.", plr.Name, args.Player.Name);
}
else
{
string reason = "No reason specified.";
if (args.Parameters.Count > 1)
reason = String.Join(" ", args.Parameters.ToArray(), 1, args.Parameters.Count - 1);
var plr = players[0];
plr.mute = true;
TSPlayer.All.SendInfoMessage("{0} has been muted by {1} for {2}.", plr.Name, args.Player.Name, reason);
}
}
private static void Motd(CommandArgs args)
{
args.Player.SendFileTextAsMessage(FileTools.MotdPath);
}
private static void Rules(CommandArgs args)
{
args.Player.SendFileTextAsMessage(FileTools.RulesPath);
}
private static void Whisper(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}whisper <player> <text>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else if (args.Player.mute)
{
args.Player.SendErrorMessage("You are muted.");
}
else
{
var plr = players[0];
var msg = string.Join(" ", args.Parameters.ToArray(), 1, args.Parameters.Count - 1);
plr.SendMessage(String.Format("<From {0}> {1}", args.Player.Name, msg), Color.MediumPurple);
args.Player.SendMessage(String.Format("<To {0}> {1}", plr.Name, msg), Color.MediumPurple);
plr.LastWhisper = args.Player;
args.Player.LastWhisper = plr;
}
}
private static void Reply(CommandArgs args)
{
if (args.Player.mute)
{
args.Player.SendErrorMessage("You are muted.");
}
else if (args.Player.LastWhisper != null)
{
var msg = string.Join(" ", args.Parameters);
args.Player.LastWhisper.SendMessage(String.Format("<From {0}> {1}", args.Player.Name, msg), Color.MediumPurple);
args.Player.SendMessage(String.Format("<To {0}> {1}", args.Player.LastWhisper.Name, msg), Color.MediumPurple);
}
else
{
args.Player.SendErrorMessage("You haven't previously received any whispers. Please use {0}whisper to whisper to other people.", Specifier);
}
}
private static void Annoy(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}annoy <player> <seconds to annoy>", Specifier);
return;
}
int annoy = 5;
int.TryParse(args.Parameters[1], out annoy);
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
args.Player.SendSuccessMessage("Annoying " + ply.Name + " for " + annoy + " seconds.");
(new Thread(ply.Whoopie)).Start(annoy);
}
}
private static void Confuse(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}confuse <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
ply.Confused = !ply.Confused;
args.Player.SendSuccessMessage("{0} is {1} confused.", ply.Name, ply.Confused ? "now" : "no longer");
}
}
private static void Rocket(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rocket <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
if (ply.IsLoggedIn && Main.ServerSideCharacter)
{
ply.TPlayer.velocity.Y = -50;
TSPlayer.All.SendData(PacketTypes.PlayerUpdate, "", ply.Index);
args.Player.SendSuccessMessage("Rocketed {0}.", ply.Name);
}
else
{
args.Player.SendErrorMessage("Failed to rocket player: Not logged in or not SSC mode.");
}
}
}
private static void FireWork(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}firework <player> [red|green|blue|yellow]", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
int type = 167;
if (args.Parameters.Count > 1)
{
if (args.Parameters[1].ToLower() == "green")
type = 168;
else if (args.Parameters[1].ToLower() == "blue")
type = 169;
else if (args.Parameters[1].ToLower() == "yellow")
type = 170;
}
var ply = players[0];
int p = Projectile.NewProjectile(ply.TPlayer.position.X, ply.TPlayer.position.Y - 64f, 0f, -8f, type, 0, (float)0);
Main.projectile[p].Kill();
args.Player.SendSuccessMessage("Launched Firework on {0}.", ply.Name);
}
}
private static void Aliases(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}aliases <command or alias>", Specifier);
return;
}
string givenCommandName = string.Join(" ", args.Parameters);
if (string.IsNullOrWhiteSpace(givenCommandName))
{
args.Player.SendErrorMessage("Please enter a proper command name or alias.");
return;
}
string commandName;
if (givenCommandName[0] == Specifier[0])
commandName = givenCommandName.Substring(1);
else
commandName = givenCommandName;
bool didMatch = false;
foreach (Command matchingCommand in ChatCommands.Where(cmd => cmd.Names.IndexOf(commandName) != -1))
{
if (matchingCommand.Names.Count > 1)
args.Player.SendInfoMessage(
"Aliases of {0}{1}: {0}{2}", Specifier, matchingCommand.Name, string.Join(", {0}".SFormat(Specifier), matchingCommand.Names.Skip(1)));
else
args.Player.SendInfoMessage("{0}{1} defines no aliases.", Specifier, matchingCommand.Name);
didMatch = true;
}
if (!didMatch)
args.Player.SendErrorMessage("No command or command alias matching \"{0}\" found.", givenCommandName);
}
private static void CreateDumps(CommandArgs args)
{
TShock.Utils.DumpPermissionMatrix("PermissionMatrix.txt");
TShock.Utils.Dump(false);
args.Player.SendSuccessMessage("Your reference dumps have been created in the server folder.");
return;
}
#endregion General Commands
#region Cheat Commands
private static void Clear(CommandArgs args)
{
if (args.Parameters.Count != 1 && args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}clear <item/npc/projectile> [radius]", Specifier);
return;
}
int radius = 50;
if (args.Parameters.Count == 2)
{
if (!int.TryParse(args.Parameters[1], out radius) || radius <= 0)
{
args.Player.SendErrorMessage("Invalid radius.");
return;
}
}
switch (args.Parameters[0].ToLower())
{
case "item":
case "items":
{
int cleared = 0;
for (int i = 0; i < Main.maxItems; i++)
{
float dX = Main.item[i].position.X - args.Player.X;
float dY = Main.item[i].position.Y - args.Player.Y;
if (Main.item[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.item[i].active = false;
TSPlayer.All.SendData(PacketTypes.ItemDrop, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} items within a radius of {1}.", cleared, radius);
}
break;
case "npc":
case "npcs":
{
int cleared = 0;
for (int i = 0; i < Main.maxNPCs; i++)
{
float dX = Main.npc[i].position.X - args.Player.X;
float dY = Main.npc[i].position.Y - args.Player.Y;
if (Main.npc[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.npc[i].active = false;
Main.npc[i].type = 0;
TSPlayer.All.SendData(PacketTypes.NpcUpdate, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} NPCs within a radius of {1}.", cleared, radius);
}
break;
case "proj":
case "projectile":
case "projectiles":
{
int cleared = 0;
for (int i = 0; i < Main.maxProjectiles; i++)
{
float dX = Main.projectile[i].position.X - args.Player.X;
float dY = Main.projectile[i].position.Y - args.Player.Y;
if (Main.projectile[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.projectile[i].active = false;
Main.projectile[i].type = 0;
TSPlayer.All.SendData(PacketTypes.ProjectileNew, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} projectiles within a radius of {1}.", cleared, radius);
}
break;
default:
args.Player.SendErrorMessage("Invalid clear option!");
break;
}
}
private static void Kill(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}kill <player>", Specifier);
return;
}
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
plr.KillPlayer();
args.Player.SendSuccessMessage(string.Format("You just killed {0}!", plr.Name));
plr.SendErrorMessage("{0} just killed you!", args.Player.Name);
}
}
private static void Butcher(CommandArgs args)
{
if (args.Parameters.Count > 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}butcher [mob type]", Specifier);
return;
}
int npcId = 0;
if (args.Parameters.Count == 1)
{
var npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
return;
}
else
{
npcId = npcs[0].netID;
}
}
int kills = 0;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && ((npcId == 0 && !Main.npc[i].townNPC && Main.npc[i].netID != NPCID.TargetDummy) || Main.npc[i].netID == npcId))
{
TSPlayer.Server.StrikeNPC(i, (int)(Main.npc[i].life + (Main.npc[i].defense * 0.6)), 0, 0);
kills++;
}
}
TSPlayer.All.SendInfoMessage("{0} butchered {1} NPCs.", args.Player.Name, kills);
}
private static void Item(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}item <item name/id> [item amount] [prefix id/name]", Specifier);
return;
}
int amountParamIndex = -1;
int itemAmount = 0;
for (int i = 1; i < args.Parameters.Count; i++)
{
if (int.TryParse(args.Parameters[i], out itemAmount))
{
amountParamIndex = i;
break;
}
}
string itemNameOrId;
if (amountParamIndex == -1)
itemNameOrId = string.Join(" ", args.Parameters);
else
itemNameOrId = string.Join(" ", args.Parameters.Take(amountParamIndex));
Item item;
List<Item> matchedItems = TShock.Utils.GetItemByIdOrName(itemNameOrId);
if (matchedItems.Count == 0)
{
args.Player.SendErrorMessage("Invalid item type!");
return;
}
else if (matchedItems.Count > 1)
{
args.Player.SendMultipleMatchError(matchedItems.Select(i => $"{i.Name}({i.netID})"));
return;
}
else
{
item = matchedItems[0];
}
if (item.type < 1 && item.type >= Main.maxItemTypes)
{
args.Player.SendErrorMessage("The item type {0} is invalid.", itemNameOrId);
return;
}
int prefixId = 0;
if (amountParamIndex != -1 && args.Parameters.Count > amountParamIndex + 1)
{
string prefixidOrName = args.Parameters[amountParamIndex + 1];
var prefixIds = TShock.Utils.GetPrefixByIdOrName(prefixidOrName);
if (item.accessory && prefixIds.Contains(PrefixID.Quick))
{
prefixIds.Remove(PrefixID.Quick);
prefixIds.Remove(PrefixID.Quick2);
prefixIds.Add(PrefixID.Quick2);
}
else if (!item.accessory && prefixIds.Contains(PrefixID.Quick))
prefixIds.Remove(PrefixID.Quick2);
if (prefixIds.Count > 1)
{
args.Player.SendMultipleMatchError(prefixIds.Select(p => p.ToString()));
return;
}
else if (prefixIds.Count == 0)
{
args.Player.SendErrorMessage("No prefix matched \"{0}\".", prefixidOrName);
return;
}
else
{
prefixId = prefixIds[0];
}
}
if (args.Player.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184)
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
if (args.Player.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefixId))
{
item.prefix = (byte)prefixId;
args.Player.SendSuccessMessage("Gave {0} {1}(s).", itemAmount, item.AffixName());
}
else
{
args.Player.SendErrorMessage("You cannot spawn banned items.");
}
}
else
{
args.Player.SendErrorMessage("Your inventory seems full.");
}
}
private static void RenameNPC(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}renameNPC <guide, nurse, etc.> <newname>", Specifier);
return;
}
int npcId = 0;
if (args.Parameters.Count == 2)
{
List<NPC> npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
return;
}
else if (args.Parameters[1].Length > 200)
{
args.Player.SendErrorMessage("New name is too large!");
return;
}
else
{
npcId = npcs[0].netID;
}
}
int done = 0;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && ((npcId == 0 && !Main.npc[i].townNPC) || (Main.npc[i].netID == npcId && Main.npc[i].townNPC)))
{
Main.npc[i].GivenName = args.Parameters[1];
NetMessage.SendData(56, -1, -1, NetworkText.FromLiteral(args.Parameters[1]), i, 0f, 0f, 0f, 0);
done++;
}
}
if (done > 0)
{
TSPlayer.All.SendInfoMessage("{0} renamed the {1}.", args.Player.Name, args.Parameters[0]);
}
else
{
args.Player.SendErrorMessage("Could not rename {0}!", args.Parameters[0]);
}
}
private static void Give(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage(
"Invalid syntax! Proper syntax: {0}give <item type/id> <player> [item amount] [prefix id/name]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Missing item name/id.");
return;
}
if (args.Parameters[1].Length == 0)
{
args.Player.SendErrorMessage("Missing player name.");
return;
}
int itemAmount = 0;
int prefix = 0;
var items = TShock.Utils.GetItemByIdOrName(args.Parameters[0]);
args.Parameters.RemoveAt(0);
string plStr = args.Parameters[0];
args.Parameters.RemoveAt(0);
if (args.Parameters.Count == 1)
int.TryParse(args.Parameters[0], out itemAmount);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item type!");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
var item = items[0];
if (args.Parameters.Count == 2)
{
int.TryParse(args.Parameters[0], out itemAmount);
var prefixIds = TShock.Utils.GetPrefixByIdOrName(args.Parameters[1]);
if (item.accessory && prefixIds.Contains(PrefixID.Quick))
{
prefixIds.Remove(PrefixID.Quick);
prefixIds.Remove(PrefixID.Quick2);
prefixIds.Add(PrefixID.Quick2);
}
else if (!item.accessory && prefixIds.Contains(PrefixID.Quick))
prefixIds.Remove(PrefixID.Quick2);
if (prefixIds.Count == 1)
prefix = prefixIds[0];
}
if (item.type >= 1 && item.type < Main.maxItemTypes)
{
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
if (plr.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184)
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
if (plr.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefix))
{
args.Player.SendSuccessMessage(string.Format("Gave {0} {1} {2}(s).", plr.Name, itemAmount, item.Name));
plr.SendSuccessMessage(string.Format("{0} gave you {1} {2}(s).", args.Player.Name, itemAmount, item.Name));
}
else
{
args.Player.SendErrorMessage("You cannot spawn banned items.");
}
}
else
{
args.Player.SendErrorMessage("Player does not have free slots!");
}
}
}
else
{
args.Player.SendErrorMessage("Invalid item type!");
}
}
}
private static void Heal(CommandArgs args)
{
TSPlayer playerToHeal;
if (args.Parameters.Count > 0)
{
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else
{
playerToHeal = players[0];
}
}
else if (!args.Player.RealPlayer)
{
args.Player.SendErrorMessage("You can't heal yourself!");
return;
}
else
{
playerToHeal = args.Player;
}
playerToHeal.Heal();
if (playerToHeal == args.Player)
{
args.Player.SendSuccessMessage("You just got healed!");
}
else
{
args.Player.SendSuccessMessage(string.Format("You just healed {0}", playerToHeal.Name));
playerToHeal.SendSuccessMessage(string.Format("{0} just healed you!", args.Player.Name));
}
}
private static void Buff(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}buff <buff id/name> [time(seconds)]", Specifier);
return;
}
int id = 0;
int time = 60;
if (!int.TryParse(args.Parameters[0], out id))
{
var found = TShock.Utils.GetBuffByName(args.Parameters[0]);
if (found.Count == 0)
{
args.Player.SendErrorMessage("Invalid buff name!");
return;
}
else if (found.Count > 1)
{
args.Player.SendMultipleMatchError(found.Select(f => Lang.GetBuffName(f)));
return;
}
id = found[0];
}
if (args.Parameters.Count == 2)
int.TryParse(args.Parameters[1], out time);
if (id > 0 && id < Main.maxBuffTypes)
{
if (time < 0 || time > short.MaxValue)
time = 60;
args.Player.SetBuff(id, time * 60);
args.Player.SendSuccessMessage(string.Format("You have buffed yourself with {0}({1}) for {2} seconds!",
TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)));
}
else
args.Player.SendErrorMessage("Invalid buff ID!");
}
private static void GBuff(CommandArgs args)
{
if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}gbuff <player> <buff id/name> [time(seconds)]", Specifier);
return;
}
int id = 0;
int time = 60;
var foundplr = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (foundplr.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (foundplr.Count > 1)
{
args.Player.SendMultipleMatchError(foundplr.Select(p => p.Name));
return;
}
else
{
if (!int.TryParse(args.Parameters[1], out id))
{
var found = TShock.Utils.GetBuffByName(args.Parameters[1]);
if (found.Count == 0)
{
args.Player.SendErrorMessage("Invalid buff name!");
return;
}
else if (found.Count > 1)
{
args.Player.SendMultipleMatchError(found.Select(b => Lang.GetBuffName(b)));
return;
}
id = found[0];
}
if (args.Parameters.Count == 3)
int.TryParse(args.Parameters[2], out time);
if (id > 0 && id < Main.maxBuffTypes)
{
if (time < 0 || time > short.MaxValue)
time = 60;
foundplr[0].SetBuff(id, time * 60);
args.Player.SendSuccessMessage(string.Format("You have buffed {0} with {1}({2}) for {3} seconds!",
foundplr[0].Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)));
foundplr[0].SendSuccessMessage(string.Format("{0} has buffed you with {1}({2}) for {3} seconds!",
args.Player.Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)));
}
else
args.Player.SendErrorMessage("Invalid buff ID!");
}
}
private static void Grow(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}grow <tree/epictree/mushroom/cactus/herb>", Specifier);
return;
}
var name = "Fail";
var x = args.Player.TileX;
var y = args.Player.TileY + 3;
if (!TShock.Regions.CanBuild(x, y, args.Player))
{
args.Player.SendErrorMessage("You're not allowed to change tiles here!");
return;
}
switch (args.Parameters[0].ToLower())
{
case "tree":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 2;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
WorldGen.GrowTree(x, y);
name = "Tree";
break;
case "epictree":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 2;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
Main.tile[x, y - 1].liquid = 0;
Main.tile[x, y - 1].active(true);
WorldGen.GrowEpicTree(x, y);
name = "Epic Tree";
break;
case "mushroom":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 70;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
WorldGen.GrowShroom(x, y);
name = "Mushroom";
break;
case "cactus":
Main.tile[x, y].type = 53;
WorldGen.GrowCactus(x, y);
name = "Cactus";
break;
case "herb":
Main.tile[x, y].active(true);
Main.tile[x, y].frameX = 36;
Main.tile[x, y].type = 83;
WorldGen.GrowAlch(x, y);
name = "Herb";
break;
default:
args.Player.SendErrorMessage("Unknown plant!");
return;
}
args.Player.SendTileSquare(x, y);
args.Player.SendSuccessMessage("Tried to grow a " + name + ".");
}
private static void ToggleGodMode(CommandArgs args)
{
TSPlayer playerToGod;
if (args.Parameters.Count > 0)
{
if (!args.Player.HasPermission(Permissions.godmodeother))
{
args.Player.SendErrorMessage("You do not have permission to god mode another player!");
return;
}
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else
{
playerToGod = players[0];
}
}
else if (!args.Player.RealPlayer)
{
args.Player.SendErrorMessage("You can't god mode a non player!");
return;
}
else
{
playerToGod = args.Player;
}
playerToGod.GodMode = !playerToGod.GodMode;
if (playerToGod == args.Player)
{
args.Player.SendSuccessMessage(string.Format("You are {0} in god mode.", args.Player.GodMode ? "now" : "no longer"));
}
else
{
args.Player.SendSuccessMessage(string.Format("{0} is {1} in god mode.", playerToGod.Name, playerToGod.GodMode ? "now" : "no longer"));
playerToGod.SendSuccessMessage(string.Format("You are {0} in god mode.", playerToGod.GodMode ? "now" : "no longer"));
}
}
#endregion Cheat Comamnds
}
}
| ProfessorXZ/TShock | TShockAPI/Commands.cs | C# | gpl-3.0 | 183,890 |
package com.sk89q.craftbook.cart;
import java.util.ArrayList;
import java.util.Arrays;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.sk89q.craftbook.util.RailUtil;
import com.sk89q.craftbook.util.RedstoneUtil.Power;
import com.sk89q.craftbook.util.RegexUtil;
public class CartDeposit extends CartMechanism {
@Override
public void impact(Minecart cart, CartMechanismBlocks blocks, boolean minor) {
// validate
if (cart == null) return;
// care?
if (minor) return;
if (!(cart instanceof StorageMinecart)) return;
Inventory cartinventory = ((StorageMinecart) cart).getInventory();
// enabled?
if (Power.OFF == isActive(blocks.rail, blocks.base, blocks.sign)) return;
// collect/deposit set?
if (blocks.sign == null) return;
if (!blocks.matches("collect") && !blocks.matches("deposit")) return;
boolean collecting = blocks.matches("collect");
// search for containers
ArrayList<Chest> containers = RailUtil.getNearbyChests(blocks.base);
// are there any containers?
if (containers.isEmpty()) return;
// go
ArrayList<ItemStack> leftovers = new ArrayList<ItemStack>();
int itemID = -1;
byte itemData = -1;
try {
String[] splitLine = RegexUtil.COLON_PATTERN.split(((Sign) blocks.sign.getState()).getLine(2));
itemID = Integer.parseInt(splitLine[0]);
itemData = Byte.parseByte(splitLine[1]);
} catch (Exception ignored) {
}
if (collecting) {
// collecting
ArrayList<ItemStack> transferItems = new ArrayList<ItemStack>();
if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) {
for (ItemStack item : cartinventory.getContents()) {
if (item == null) {
continue;
}
if (itemID < 0 || itemID == item.getTypeId()) {
if (itemData < 0 || itemData == item.getDurability()) {
transferItems.add(new ItemStack(item.getTypeId(), item.getAmount(), item.getDurability()));
cartinventory.remove(item);
}
}
}
} else {
transferItems.addAll(Arrays.asList(cartinventory.getContents()));
cartinventory.clear();
}
while (transferItems.remove(null)) {
}
// is cart non-empty?
if (transferItems.isEmpty()) return;
// System.out.println("collecting " + transferItems.size() + " item stacks");
// for (ItemStack stack: transferItems) System.out.println("collecting " + stack.getAmount() + " items of
// type " + stack.getType().toString());
for (Chest container : containers) {
if (transferItems.isEmpty()) {
break;
}
Inventory containerinventory = container.getInventory();
leftovers.addAll(containerinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()
])).values());
transferItems.clear();
transferItems.addAll(leftovers);
leftovers.clear();
container.update();
}
// System.out.println("collected items. " + transferItems.size() + " stacks left over.");
leftovers.addAll(cartinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()])).values
());
transferItems.clear();
transferItems.addAll(leftovers);
leftovers.clear();
// System.out.println("collection done. " + transferItems.size() + " stacks wouldn't fit back.");
} else {
// depositing
ArrayList<ItemStack> transferitems = new ArrayList<ItemStack>();
for (Chest container : containers) {
Inventory containerinventory = container.getInventory();
if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) {
for (ItemStack item : containerinventory.getContents()) {
if (item == null) {
continue;
}
if (itemID < 0 || itemID == item.getTypeId())
if (itemData < 0 || itemData == item.getDurability()) {
transferitems.add(new ItemStack(item.getTypeId(), item.getAmount(),
item.getDurability()));
containerinventory.remove(item);
}
}
} else {
transferitems.addAll(Arrays.asList(containerinventory.getContents()));
containerinventory.clear();
}
container.update();
}
while (transferitems.remove(null)) {
}
// are chests empty?
if (transferitems.isEmpty()) return;
// System.out.println("depositing " + transferitems.size() + " stacks");
// for (ItemStack stack: transferitems) System.out.println("depositing " + stack.getAmount() + " items of
// type " + stack.getType().toString());
leftovers.addAll(cartinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()])).values
());
transferitems.clear();
transferitems.addAll(leftovers);
leftovers.clear();
// System.out.println("deposited, " + transferitems.size() + " items left over.");
for (Chest container : containers) {
if (transferitems.isEmpty()) {
break;
}
Inventory containerinventory = container.getInventory();
leftovers.addAll(containerinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()
])).values());
transferitems.clear();
transferitems.addAll(leftovers);
leftovers.clear();
}
// System.out.println("deposit done. " + transferitems.size() + " items wouldn't fit back.");
}
}
@Override
public String getName() {
return "Deposit";
}
@Override
public String[] getApplicableSigns() {
return new String[] {"Collect", "Deposit"};
}
} | wizjany/craftbook | src/main/java/com/sk89q/craftbook/cart/CartDeposit.java | Java | gpl-3.0 | 7,011 |
<?php
// This file is part of Moodle - http://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 <http://www.gnu.org/licenses/>.
/**
* Lang strings for course_overview block
*
* @package block_course_overview
* @copyright 2012 Adam Olley <adam.olley@netspot.com.au>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['activityoverview'] = 'You have {$a}s that need attention';
$string['alwaysshowall'] = 'Always show all';
$string['collapseall'] = 'Collapse all course lists';
$string['configotherexpanded'] = 'If enabled, other courses will be expanded by default unless overriden by user preferences.';
$string['configpreservestates'] = 'If enabled, the collapsed/expanded states set by the user are stored and used on each load.';
$string['course_overview:addinstance'] = 'Add a new course overview block';
$string['course_overview:myaddinstance'] = 'Add a new course overview block to My home';
$string['defaultmaxcourses'] = 'Default maximum courses';
$string['defaultmaxcoursesdesc'] = 'Maximum courses which should be displayed on course overview block, 0 will show all courses';
$string['expandall'] = 'Expand all course lists';
$string['forcedefaultmaxcourses'] = 'Force maximum courses';
$string['forcedefaultmaxcoursesdesc'] = 'If set then user will not be able to change his/her personal setting';
$string['hiddencoursecount'] = 'You have {$a} hidden course';
$string['hiddencoursecountplural'] = 'You have {$a} hidden courses';
$string['hiddencoursecountwithshowall'] = 'You have {$a->coursecount} hidden course ({$a->showalllink})';
$string['hiddencoursecountwithshowallplural'] = 'You have {$a->coursecount} hidden courses ({$a->showalllink})';
$string['message'] = 'message';
$string['messages'] = 'messages';
$string['movecourse'] = 'Move course: {$a}';
$string['movecoursehere'] = 'Move course here';
$string['movetofirst'] = 'Move {$a} course to top';
$string['moveafterhere'] = 'Move {$a->movingcoursename} course after {$a->currentcoursename}';
$string['movingcourse'] = 'You are moving: {$a->fullname} ({$a->cancellink})';
$string['numtodisplay'] = 'Number of courses to display: ';
$string['otherexpanded'] = 'Other courses expanded';
$string['pluginname'] = 'Assigned Courses';
$string['preservestates'] = 'Preserve expanded states';
$string['shortnameprefix'] = 'Includes {$a}';
$string['shortnamesufixsingular'] = ' (and {$a} other)';
$string['shortnamesufixprural'] = ' (and {$a} others)';
$string['showchildren'] = 'Show children';
$string['showchildrendesc'] = 'Should child courses be listed underneath the main course title?';
$string['showwelcomearea'] = 'Show welcome area';
$string['showwelcomeareadesc'] = 'Show the welcome area above the course list?';
$string['view_edit_profile'] = '(View and edit your profile.)';
$string['welcome'] = 'Welcome {$a}';
$string['youhavemessages'] = 'You have {$a} unread ';
$string['youhavenomessages'] = 'You have no unread ';
| sumitnegi933/GWL_MOODLE | blocks/course_overview/lang/en/block_course_overview.php | PHP | gpl-3.0 | 3,501 |
<?php
session_start();
include("../connect.php");
include("../function.php");
//session_start();
if($_REQUEST['cat_id'])
{
$data="";
$count=0;
$select_list_data="select * from users_data where int_fid in(".$_REQUEST['cat_id'].") and int_del_status='0'";
$result_list_data=mysql_query($select_list_data) or die(mysql_error());
$data.="<br>";
$data.="<table style='width: 270px;' id='alternatecolor' class='altrowstable1' >";
while($fetch_list_data=mysql_fetch_array($result_list_data))
{ $count++;
$imgsrc="../".$fetch_list_data['txt_real_path'];
$data.="<tr >";
$data.="<td style='padding-left:5px;'>";
$data.="<div style='width:240px;overflow:hidden;'>".$fetch_list_data['txt_file_name']."</div>";
$data.="</td>";
$data.="<td >";
$data.="<img src='images/play-icon.png' style='cursor:pointer;' title='Play Item' onclick='go(\"$imgsrc\");'>";
$data.="</td>";
$data.="</tr>";
//$main_data="<a href='javascript:load_data(\"".$fetch_list_data['txt_file_name']."\");'>".$fetch_list_data['txt_file_name']."</a>";
//$data=$data.$main_data;
//$data.="</br></br>";
}
$data.="</table>";
echo $data;
}
?> | aroramanish63/bulmail_app | Live Backup/databagg 30 jan backup/user/ajax_load_list_11_7.php | PHP | gpl-3.0 | 1,421 |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// Implementation file
//
// Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
// zmoelnig@iem.kug.ac.at
// For information on usage and redistribution, and for a DISCLAIMER
// * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS"
//
// this file has been generated...
////////////////////////////////////////////////////////
#include "GEMglTexCoord3s.h"
CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglTexCoord3s , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// GEMglViewport
//
/////////////////////////////////////////////////////////
// Constructor
//
GEMglTexCoord3s :: GEMglTexCoord3s (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) :
s(static_cast<GLshort>(arg0)),
t(static_cast<GLshort>(arg1)),
r(static_cast<GLshort>(arg2))
{
m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("s"));
m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("t"));
m_inlet[2] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("r"));
}
/////////////////////////////////////////////////////////
// Destructor
//
GEMglTexCoord3s :: ~GEMglTexCoord3s () {
inlet_free(m_inlet[0]);
inlet_free(m_inlet[1]);
inlet_free(m_inlet[2]);
}
/////////////////////////////////////////////////////////
// Render
//
void GEMglTexCoord3s :: render(GemState *state) {
glTexCoord3s (s, t, r);
}
/////////////////////////////////////////////////////////
// Variables
//
void GEMglTexCoord3s :: sMess (t_float arg1) { // FUN
s = static_cast<GLshort>(arg1);
setModified();
}
void GEMglTexCoord3s :: tMess (t_float arg1) { // FUN
t = static_cast<GLshort>(arg1);
setModified();
}
void GEMglTexCoord3s :: rMess (t_float arg1) { // FUN
r = static_cast<GLshort>(arg1);
setModified();
}
/////////////////////////////////////////////////////////
// static member functions
//
void GEMglTexCoord3s :: obj_setupCallback(t_class *classPtr) {
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::sMessCallback), gensym("s"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::tMessCallback), gensym("t"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::rMessCallback), gensym("r"), A_DEFFLOAT, A_NULL);
};
void GEMglTexCoord3s :: sMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->sMess ( static_cast<t_float>(arg0));
}
void GEMglTexCoord3s :: tMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->tMess ( static_cast<t_float>(arg0));
}
void GEMglTexCoord3s :: rMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->rMess ( static_cast<t_float>(arg0));
}
| rvega/morphasynth | vendors/pd-extended-0.43.4/externals/Gem/src/openGL/GEMglTexCoord3s.cpp | C++ | gpl-3.0 | 2,880 |
/*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 Victor Spirin
*
* CRISIS 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.
*
* CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.crisis_economics.abm.markets.nonclearing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import eu.crisis_economics.abm.markets.Party;
import eu.crisis_economics.abm.markets.nonclearing.DefaultFilters.Filter;
/**
* Represents relationships between banks in the interbank market
*
* @author Victor Spirin
*/
public class InterbankNetwork {
private final Map<Party, Set<Party>> adj = new HashMap<Party, Set<Party>>();
/**
* Adds a new node to the graph. If the node already exists, this
* function is a no-op.
*
* @param node The node to add.
* @return Whether or not the node was added.
*/
private boolean addNode(Party node) {
/* If the node already exists, don't do anything. */
if (adj.containsKey(node))
return false;
/* Otherwise, add the node with an empty set of outgoing edges. */
adj.put(node, new HashSet<Party>());
return true;
}
// protected
/**
* Generates a filter from the network. This allows the network class to be used
* with a Limit Order Book.
*
* @param a Bank, for which we want to generate a filter
* @return Returns a Limit Order Book filter for the given bank. If the bank is not in the network, returns an empty filter.
*/
protected Filter generateFilter(Party party) {
if (!adj.containsKey(party))
return DefaultFilters.only(party);
return DefaultFilters.only((Party[]) adj.get(party).toArray());
}
// public interface
/**
* Adds a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, also adds them to the network.
*
* @param a Bank a
* @param b Bank b
*/
public void addRelationship(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a))
addNode(a);
if (!adj.containsKey(b))
addNode(b);
/* Add the edge in both directions. */
adj.get(a).add(b);
adj.get(b).add(a);
}
/**
* Removes a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, throws a NoSuchElementException
*
* @param a Bank a
* @param b Bank b
*/
public void removeRelationship(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a) || !adj.containsKey(b))
throw new NoSuchElementException("Both banks must be in the network.");
/* Remove the edges from both adjacency lists. */
adj.get(a).remove(b);
adj.get(b).remove(a);
}
/**
* Returns true if there is a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, throws a NoSuchElementException
*
* @param a Bank a
* @param b Bank b
* @return Returns true if there is a relationship between banks 'a' and 'b'
*/
public boolean isRelated(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a) || !adj.containsKey(b))
throw new NoSuchElementException("Both banks must be in the network.");
/* Network is symmetric, so we can just check either endpoint. */
return adj.get(a).contains(b);
}
}
| crisis-economics/CRISIS | CRISIS/src/eu/crisis_economics/abm/markets/nonclearing/InterbankNetwork.java | Java | gpl-3.0 | 4,215 |
<?php
# server running the wolframe daemon
$WOLFRAME_SERVER = "localhost";
# wolframe daemon port
$WOLFRAME_PORT = 7962;
# for SSL secured communication, a file with combined client certificate
# and client key
$WOLFRAME_COMBINED_CERTS = "certs/combinedcert.pem";
# which user agents should use client XSLT
$BROWSERS_USING_CLIENT_XSLT = array(
# "op12", "ie8", "ie9", "ie10", "moz23", "webkit27", "webkit28", "moz11"
);
| Wolframe/wolfzilla | phpclient/config.php | PHP | gpl-3.0 | 425 |
/**
*
*/
/**
* @author dewan
*
*/
package gradingTools.comp401f16.assignment11.testcases; | pdewan/Comp401LocalChecks | src/gradingTools/comp401f16/assignment11/testcases/package-info.java | Java | gpl-3.0 | 95 |
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Int())
fmt.Println(rand.Float64())
}
| alsotoes/MCS_programmingLanguages | go/slides/code/imports.go | GO | gpl-3.0 | 152 |
package mcid.anubisset.letsmodreboot.block;
import mcid.anubisset.letsmodreboot.creativetab.CreativeTabLMRB;
/**
* Created by Luke on 30/08/2014.
*/
public class BlockFlag extends BlockLMRB
{
public BlockFlag()
{
super();
this.setBlockName("flag");
this.setBlockTextureName("flag");
}
}
| AnubisSet/LetsModReboot | src/main/java/mcid/anubisset/letsmodreboot/block/BlockFlag.java | Java | gpl-3.0 | 327 |
require 'package'
class Libxau < Package
description 'xau library for libX11'
homepage 'https://x.org'
version '1.0.8'
source_url 'https://www.x.org/archive/individual/lib/libXau-1.0.8.tar.gz'
source_sha256 'c343b4ef66d66a6b3e0e27aa46b37ad5cab0f11a5c565eafb4a1c7590bc71d7b'
depends_on 'xproto'
def self.build
system "./configure"
system "make"
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end
| richard-fisher/chromebrew | packages/libxau.rb | Ruby | gpl-3.0 | 466 |
/*
* Copyright 2011 kubtek <kubtek@mail.com>
*
* This file is part of StarDict.
*
* StarDict 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.
*
* StarDict 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 StarDict. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "pluginmanagedlg.h"
#include "desktop.h"
#include <glib/gi18n.h>
#include "stardict.h"
PluginManageDlg::PluginManageDlg()
:
window(NULL),
treeview(NULL),
detail_label(NULL),
pref_button(NULL),
plugin_tree_model(NULL),
dict_changed_(false),
order_changed_(false)
{
}
PluginManageDlg::~PluginManageDlg()
{
g_assert(!window);
g_assert(!treeview);
g_assert(!detail_label);
g_assert(!pref_button);
g_assert(!plugin_tree_model);
}
void PluginManageDlg::response_handler (GtkDialog *dialog, gint res_id, PluginManageDlg *oPluginManageDlg)
{
if (res_id == GTK_RESPONSE_HELP) {
show_help("stardict-plugins");
} else if (res_id == STARDICT_RESPONSE_CONFIGURE) {
GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(oPluginManageDlg->treeview));
GtkTreeModel *model;
GtkTreeIter iter;
if (! gtk_tree_selection_get_selected (selection, &model, &iter))
return;
if (!gtk_tree_model_iter_has_child(model, &iter)) {
gchar *filename;
StarDictPlugInType plugin_type;
gtk_tree_model_get (model, &iter, 4, &filename, 5, &plugin_type, -1);
gpAppFrame->oStarDictPlugins->configure_plugin(filename, plugin_type);
g_free(filename);
}
}
}
static gboolean get_disable_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
if (!gtk_tree_model_iter_has_child(model, iter)) {
gboolean enable;
gtk_tree_model_get (model, iter, 1, &enable, -1);
if (!enable) {
gchar *filename;
gtk_tree_model_get (model, iter, 4, &filename, -1);
std::list<std::string> *disable_list = (std::list<std::string> *)data;
disable_list->push_back(filename);
g_free(filename);
}
}
return FALSE;
}
void PluginManageDlg::on_plugin_enable_toggled (GtkCellRendererToggle *cell, gchar *path_str, PluginManageDlg *oPluginManageDlg)
{
GtkTreeModel *model = GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model);
GtkTreePath *path = gtk_tree_path_new_from_string (path_str);
GtkTreeIter iter;
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gboolean enable;
gchar *filename;
StarDictPlugInType plugin_type;
gboolean can_configure;
gtk_tree_model_get (model, &iter, 1, &enable, 4, &filename, 5, &plugin_type, 6, &can_configure, -1);
enable = !enable;
gtk_tree_store_set (GTK_TREE_STORE (model), &iter, 1, enable, -1);
if (enable) {
gpAppFrame->oStarDictPlugins->load_plugin(filename);
} else {
gpAppFrame->oStarDictPlugins->unload_plugin(filename, plugin_type);
}
g_free(filename);
if (enable)
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, can_configure);
else
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
if (plugin_type == StarDictPlugInType_VIRTUALDICT
|| plugin_type == StarDictPlugInType_NETDICT) {
oPluginManageDlg->dict_changed_ = true;
} else if (plugin_type == StarDictPlugInType_TTS) {
gpAppFrame->oMidWin.oToolWin.UpdatePronounceMenu();
}
std::list<std::string> disable_list;
gtk_tree_model_foreach(model, get_disable_list, &disable_list);
#ifdef _WIN32
{
std::list<std::string> disable_list_rel;
rel_path_to_data_dir(disable_list, disable_list_rel);
std::swap(disable_list, disable_list_rel);
}
#endif
conf->set_strlist("/apps/stardict/manage_plugins/plugin_disable_list", disable_list);
}
struct plugininfo_ParseUserData {
gchar *info_str;
gchar *detail_str;
std::string filename;
std::string name;
std::string version;
std::string short_desc;
std::string long_desc;
std::string author;
std::string website;
};
static void plugininfo_parse_start_element(GMarkupParseContext *context, const gchar *element_name, const gchar **attribute_names, const gchar **attribute_values, gpointer user_data, GError **error)
{
if (strcmp(element_name, "plugin_info")==0) {
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
Data->name.clear();
Data->version.clear();
Data->short_desc.clear();
Data->long_desc.clear();
Data->author.clear();
Data->website.clear();
}
}
static void plugininfo_parse_end_element(GMarkupParseContext *context, const gchar *element_name, gpointer user_data, GError **error)
{
if (strcmp(element_name, "plugin_info")==0) {
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
Data->info_str = g_markup_printf_escaped("<b>%s</b> %s\n%s", Data->name.c_str(), Data->version.c_str(), Data->short_desc.c_str());
Data->detail_str = g_markup_printf_escaped(_("%s\n\n<b>Author:</b>\t%s\n<b>Website:</b>\t%s\n<b>Filename:</b>\t%s"), Data->long_desc.c_str(), Data->author.c_str(), Data->website.c_str(), Data->filename.c_str());
}
}
static void plugininfo_parse_text(GMarkupParseContext *context, const gchar *text, gsize text_len, gpointer user_data, GError **error)
{
const gchar *element = g_markup_parse_context_get_element(context);
if (!element)
return;
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
if (strcmp(element, "name")==0) {
Data->name.assign(text, text_len);
} else if (strcmp(element, "version")==0) {
Data->version.assign(text, text_len);
} else if (strcmp(element, "short_desc")==0) {
Data->short_desc.assign(text, text_len);
} else if (strcmp(element, "long_desc")==0) {
Data->long_desc.assign(text, text_len);
} else if (strcmp(element, "author")==0) {
Data->author.assign(text, text_len);
} else if (strcmp(element, "website")==0) {
Data->website.assign(text, text_len);
}
}
static void add_tree_model(GtkTreeStore *tree_model, GtkTreeIter*parent, const std::list<StarDictPluginInfo> &infolist)
{
plugininfo_ParseUserData Data;
GMarkupParser parser;
parser.start_element = plugininfo_parse_start_element;
parser.end_element = plugininfo_parse_end_element;
parser.text = plugininfo_parse_text;
parser.passthrough = NULL;
parser.error = NULL;
GtkTreeIter iter;
for (std::list<StarDictPluginInfo>::const_iterator i = infolist.begin(); i != infolist.end(); ++i) {
Data.info_str = NULL;
Data.detail_str = NULL;
Data.filename = i->filename;
GMarkupParseContext* context = g_markup_parse_context_new(&parser, (GMarkupParseFlags)0, &Data, NULL);
g_markup_parse_context_parse(context, i->info_xml.c_str(), -1, NULL);
g_markup_parse_context_end_parse(context, NULL);
g_markup_parse_context_free(context);
gtk_tree_store_append(tree_model, &iter, parent);
bool loaded = gpAppFrame->oStarDictPlugins->get_loaded(i->filename.c_str());
gtk_tree_store_set(tree_model, &iter, 0, true, 1, loaded, 2, Data.info_str, 3, Data.detail_str, 4, i->filename.c_str(), 5, i->plugin_type, 6, i->can_configure, -1);
g_free(Data.info_str);
g_free(Data.detail_str);
}
}
static void init_tree_model(GtkTreeStore *tree_model)
{
std::list<std::pair<StarDictPlugInType, std::list<StarDictPluginInfo> > > plugin_list;
{
#ifdef _WIN32
std::list<std::string> plugin_order_list;
const std::list<std::string>& plugin_order_list_rel
= conf->get_strlist("/apps/stardict/manage_plugins/plugin_order_list");
abs_path_to_data_dir(plugin_order_list_rel, plugin_order_list);
#else
const std::list<std::string>& plugin_order_list
= conf->get_strlist("/apps/stardict/manage_plugins/plugin_order_list");
#endif
gpAppFrame->oStarDictPlugins->get_plugin_list(plugin_order_list, plugin_list);
}
GtkTreeIter iter;
for (std::list<std::pair<StarDictPlugInType, std::list<StarDictPluginInfo> > >::iterator i = plugin_list.begin(); i != plugin_list.end(); ++i) {
switch (i->first) {
case StarDictPlugInType_VIRTUALDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Virtual Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_NETDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Network Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_SPECIALDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Special Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_TTS:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>TTS Engine</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_PARSEDATA:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Data Parsing Engine</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_MISC:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Misc</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
default:
break;
}
}
}
void PluginManageDlg::on_plugin_treeview_selection_changed(GtkTreeSelection *selection, PluginManageDlg *oPluginManageDlg)
{
GtkTreeModel *model;
GtkTreeIter iter;
if (! gtk_tree_selection_get_selected (selection, &model, &iter))
return;
if (gtk_tree_model_iter_has_child(model, &iter)) {
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
} else {
gboolean loaded;
gchar *detail;
gboolean can_configure;
gtk_tree_model_get (model, &iter, 1, &loaded, 3, &detail, 6, &can_configure, -1);
gtk_label_set_markup(GTK_LABEL(oPluginManageDlg->detail_label), detail);
g_free(detail);
if (loaded)
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, can_configure);
else
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
}
}
gboolean PluginManageDlg::on_treeview_button_press(GtkWidget * widget, GdkEventButton * event, PluginManageDlg *oPluginManageDlg)
{
if (event->type==GDK_2BUTTON_PRESS) {
if (gtk_widget_get_sensitive(GTK_WIDGET(oPluginManageDlg->pref_button)))
gtk_dialog_response(GTK_DIALOG(oPluginManageDlg->window), STARDICT_RESPONSE_CONFIGURE);
return true;
} else {
return false;
}
}
static void add_order_list(std::list<std::string> &order_list, GtkTreeModel *now_tree_model, GtkTreeIter *parent)
{
gboolean have_iter;
GtkTreeIter iter;
have_iter = gtk_tree_model_iter_children(now_tree_model, &iter, parent);
gchar *filename;
while (have_iter) {
gtk_tree_model_get (now_tree_model, &iter, 4, &filename, -1);
order_list.push_back(filename);
g_free(filename);
have_iter = gtk_tree_model_iter_next(now_tree_model, &iter);
}
}
void PluginManageDlg::write_order_list()
{
std::list<std::string> order_list;
GtkTreeModel *now_tree_model = GTK_TREE_MODEL(plugin_tree_model);
gboolean have_iter;
GtkTreeIter iter;
have_iter = gtk_tree_model_get_iter_first(now_tree_model, &iter);
while (have_iter) {
if (gtk_tree_model_iter_has_child(now_tree_model, &iter)) {
add_order_list(order_list, now_tree_model, &iter);
}
have_iter = gtk_tree_model_iter_next(now_tree_model, &iter);
}
#ifdef _WIN32
{
std::list<std::string> order_list_rel;
rel_path_to_data_dir(order_list, order_list_rel);
std::swap(order_list, order_list_rel);
}
#endif
conf->set_strlist("/apps/stardict/manage_plugins/plugin_order_list", order_list);
}
void PluginManageDlg::drag_data_get_cb(GtkWidget *widget, GdkDragContext *ctx, GtkSelectionData *data, guint info, guint time, PluginManageDlg *oPluginManageDlg)
{
if (gtk_selection_data_get_target(data) == gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE)) {
GtkTreeRowReference *ref;
GtkTreePath *source_row;
ref = (GtkTreeRowReference *)g_object_get_data(G_OBJECT(ctx), "gtk-tree-view-source-row");
source_row = gtk_tree_row_reference_get_path(ref);
if (source_row == NULL)
return;
GtkTreeIter iter;
gtk_tree_model_get_iter(GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model), &iter, source_row);
gtk_selection_data_set(data, gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE), 8, (const guchar *)&iter, sizeof(iter));
gtk_tree_path_free(source_row);
}
}
void PluginManageDlg::drag_data_received_cb(GtkWidget *widget, GdkDragContext *ctx, guint x, guint y, GtkSelectionData *sd, guint info, guint t, PluginManageDlg *oPluginManageDlg)
{
if (gtk_selection_data_get_target(sd) == gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE) && gtk_selection_data_get_data(sd)) {
GtkTreePath *path = NULL;
GtkTreeViewDropPosition position;
GtkTreeIter drag_iter;
memcpy(&drag_iter, gtk_selection_data_get_data(sd), sizeof(drag_iter));
if (gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(widget), x, y, &path, &position)) {
GtkTreeIter iter;
GtkTreeModel *model = GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model);
gtk_tree_model_get_iter(model, &iter, path);
if (gtk_tree_model_iter_has_child(model, &iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
if (gtk_tree_model_iter_has_child(model, &drag_iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
GtkTreeIter parent_iter;
if (!gtk_tree_model_iter_parent(model, &parent_iter, &iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
GtkTreeIter drag_parent_iter;
if (!gtk_tree_model_iter_parent(model, &drag_parent_iter, &drag_iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
char *iter_str, *drag_iter_str;
iter_str = gtk_tree_model_get_string_from_iter(model, &parent_iter);
drag_iter_str = gtk_tree_model_get_string_from_iter(model, &drag_parent_iter);
if (strcmp(iter_str, drag_iter_str) != 0) {
g_free(iter_str);
g_free(drag_iter_str);
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
g_free(iter_str);
g_free(drag_iter_str);
switch (position) {
case GTK_TREE_VIEW_DROP_AFTER:
case GTK_TREE_VIEW_DROP_INTO_OR_AFTER:
gtk_tree_store_move_after(GTK_TREE_STORE(model), &drag_iter, &iter);
break;
case GTK_TREE_VIEW_DROP_BEFORE:
case GTK_TREE_VIEW_DROP_INTO_OR_BEFORE:
gtk_tree_store_move_before(GTK_TREE_STORE(model), &drag_iter, &iter);
break;
default: {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
}
oPluginManageDlg->write_order_list();
oPluginManageDlg->order_changed_ = true;
gtk_drag_finish (ctx, TRUE, FALSE, t);
}
}
}
GtkWidget *PluginManageDlg::create_plugin_list()
{
GtkWidget *sw;
sw = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), GTK_SHADOW_IN);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
plugin_tree_model = gtk_tree_store_new(7, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_BOOLEAN);
init_tree_model(plugin_tree_model);
treeview = gtk_tree_view_new_with_model (GTK_TREE_MODEL(plugin_tree_model));
g_object_unref (G_OBJECT (plugin_tree_model));
#if GTK_MAJOR_VERSION >= 3
#else
gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview), TRUE);
#endif
g_signal_connect (G_OBJECT (treeview), "button_press_event", G_CALLBACK (on_treeview_button_press), this);
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
g_signal_connect (selection, "changed", G_CALLBACK (on_plugin_treeview_selection_changed), this);
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
renderer = gtk_cell_renderer_toggle_new ();
g_signal_connect (renderer, "toggled", G_CALLBACK (on_plugin_enable_toggled), this);
column = gtk_tree_view_column_new_with_attributes (_("Enable"), renderer, "visible", 0, "active", 1, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN (column), FALSE);
gtk_tree_view_column_set_clickable (GTK_TREE_VIEW_COLUMN (column), FALSE);
renderer = gtk_cell_renderer_text_new ();
g_object_set (G_OBJECT (renderer), "xalign", 0.0, NULL);
column = gtk_tree_view_column_new_with_attributes (_("Plug-in Name"), renderer, "markup", 2, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN (column), TRUE);
gtk_tree_view_column_set_clickable (GTK_TREE_VIEW_COLUMN (column), FALSE);
GtkTargetEntry gte[] = {{(gchar *)"STARDICT_PLUGINMANAGE", GTK_TARGET_SAME_APP, 0}};
gtk_tree_view_enable_model_drag_source(GTK_TREE_VIEW(treeview), GDK_BUTTON1_MASK, gte, 1, GDK_ACTION_COPY);
gtk_tree_view_enable_model_drag_dest(GTK_TREE_VIEW(treeview), gte, 1, (GdkDragAction)(GDK_ACTION_COPY | GDK_ACTION_MOVE));
g_signal_connect(G_OBJECT(treeview), "drag-data-received", G_CALLBACK(drag_data_received_cb), this);
g_signal_connect(G_OBJECT(treeview), "drag-data-get", G_CALLBACK(drag_data_get_cb), this);
gtk_tree_view_expand_all(GTK_TREE_VIEW (treeview));
gtk_container_add (GTK_CONTAINER (sw), treeview);
return sw;
}
bool PluginManageDlg::ShowModal(GtkWindow *parent_win, bool &dict_changed, bool &order_changed)
{
window = gtk_dialog_new();
oStarDictPluginSystemInfo.pluginwin = window;
gtk_window_set_transient_for(GTK_WINDOW(window), parent_win);
//gtk_dialog_set_has_separator(GTK_DIALOG(window), false);
gtk_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_HELP, GTK_RESPONSE_HELP);
pref_button = gtk_dialog_add_button(GTK_DIALOG(window), _("Configure Pl_ug-in"), STARDICT_RESPONSE_CONFIGURE);
gtk_widget_set_sensitive(pref_button, FALSE);
gtk_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
gtk_dialog_set_default_response(GTK_DIALOG(window), GTK_RESPONSE_CLOSE);
g_signal_connect(G_OBJECT(window), "response", G_CALLBACK(response_handler), this);
GtkWidget *vbox;
#if GTK_MAJOR_VERSION >= 3
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
#else
vbox = gtk_vbox_new (FALSE, 5);
#endif
gtk_container_set_border_width (GTK_CONTAINER (vbox), 2);
GtkWidget *pluginlist = create_plugin_list();
gtk_box_pack_start (GTK_BOX (vbox), pluginlist, true, true, 0);
GtkWidget *expander = gtk_expander_new (_("<b>Plug-in Details</b>"));
gtk_expander_set_use_markup(GTK_EXPANDER(expander), TRUE);
gtk_box_pack_start (GTK_BOX (vbox), expander, false, false, 0);
detail_label = gtk_label_new (NULL);
gtk_label_set_line_wrap(GTK_LABEL(detail_label), TRUE);
gtk_label_set_selectable(GTK_LABEL (detail_label), TRUE);
gtk_container_add (GTK_CONTAINER (expander), detail_label);
gtk_box_pack_start (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG (window))), vbox, true, true, 0);
gtk_widget_show_all (gtk_dialog_get_content_area(GTK_DIALOG (window)));
gtk_window_set_title (GTK_WINDOW (window), _("Manage Plugins"));
gtk_window_set_default_size(GTK_WINDOW(window), 250, 350);
dict_changed_ = false;
order_changed_ = false;
gint result;
while (true) {
result = gtk_dialog_run(GTK_DIALOG(window));
if (result ==GTK_RESPONSE_HELP || result == STARDICT_RESPONSE_CONFIGURE) {
} else {
break;
}
}
/* When do we get GTK_RESPONSE_NONE response? Unable to reproduce. */
if (result != GTK_RESPONSE_NONE) {
dict_changed = dict_changed_;
order_changed = order_changed_;
gtk_widget_destroy(GTK_WIDGET(window));
}
window = NULL;
treeview = NULL;
detail_label = NULL;
pref_button = NULL;
plugin_tree_model = NULL;
oStarDictPluginSystemInfo.pluginwin = NULL;
return result == GTK_RESPONSE_NONE;
}
| huzheng001/stardict-3 | dict/src/pluginmanagedlg.cpp | C++ | gpl-3.0 | 20,060 |
package tmp.generated_people;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public abstract class Element_ol extends GenASTNode {
protected Element_ol(Property[] p, Token firstToken, Token lastToken) { super(p, firstToken, lastToken); }
protected Element_ol(Property[] p, IToken firstToken, IToken lastToken) { super(p, firstToken, lastToken); }
}
| ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_people/Element_ol.java | Java | gpl-3.0 | 404 |
"""
Copyright 2014 Jason Heeris, jason.heeris@gmail.com
This file is part of the dungeon excavator web interface ("webcavate").
Webcavate 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.
Webcavate 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
webcavate. If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
import uuid
from flask import Flask, render_template, request, make_response, redirect, url_for, flash
from dungeon.excavate import render_room
HELP_TEXT = """\
Web interface to the dungeon excavator."""
app = Flask('dungeon.web')
app.secret_key = str(uuid.uuid4())
@app.route("/")
def root():
""" Web interface landing page. """
return render_template('index.html')
@app.route("/error")
def error():
""" Display errors. """
return render_template('error.html')
def make_map(request, format):
tile_size = int(request.form['size'])
wall_file = request.files['walls']
floor_file = request.files['floor']
floorplan_file = request.files['floorplan']
try:
room_data, content_type = render_room(
floor_file.read(),
wall_file.read(),
floorplan_file.read(),
tile_size,
format
)
except ValueError as ve:
flash(str(ve))
return redirect(url_for('error'))
# Create response
response = make_response(room_data)
response.headers['Content-Type'] = content_type
return response
@app.route("/map.svg", methods=['POST'])
def map_svg():
return make_map(request, format='svg')
@app.route("/map.png", methods=['POST'])
def map_png():
return make_map(request, format='png')
@app.route("/map.jpg", methods=['POST'])
def map_jpg():
return make_map(request, format='jpg')
@app.route("/map", methods=['POST'])
def process():
""" Process submitted form data. """
format = request.form['format']
try:
node = {
'png': 'map_png',
'svg': 'map_svg',
'jpg': 'map_jpg',
}[format]
except KeyError:
flash("The output format you selected is not supported.")
return redirect(url_for('error'))
else:
return redirect(url_for(node, _method='POST'), code=307)
def main():
""" Parse arguments and get things going for the web interface """
parser = argparse.ArgumentParser(description=HELP_TEXT)
parser.add_argument(
'-p', '--port',
help="Port to serve the interface on.",
type=int,
default=5050
)
parser.add_argument(
'-a', '--host',
help="Host to server the interface on.",
)
args = parser.parse_args()
app.run(port=args.port, host=args.host, debug=False)
| detly/webcavate | webcavate/app.py | Python | gpl-3.0 | 3,132 |
//# BaselineSelection.cc: Class to handle the baseline selection
//# Copyright (C) 2012
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite is free software: you can redistribute it and/or
//# modify it under the terms of the GNU General Public License as published
//# by the Free Software Foundation, either version 3 of the License, or
//# (at your option) any later version.
//#
//# The LOFAR software suite is distributed in the hope that it will be useful,
//# but WITHOUT ANY WARRANTY; without even the implied warranty of
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//# GNU General Public License for more details.
//#
//# You should have received a copy of the GNU General Public License along
//# with the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id$
//#
//# @author Ger van Diepen
#include <lofar_config.h>
#include <DPPP/BaselineSelection.h>
#include <DPPP/DPLogger.h>
#include <MS/BaselineSelect.h>
#include <Common/ParameterSet.h>
#include <Common/ParameterValue.h>
#include <Common/LofarLogger.h>
#include <Common/StreamUtil.h>
using namespace casa;
using namespace std;
namespace LOFAR {
namespace DPPP {
BaselineSelection::BaselineSelection()
{}
BaselineSelection::BaselineSelection (const ParameterSet& parset,
const string& prefix,
bool minmax,
const string& defaultCorrType,
const string& defaultBaseline)
: itsStrBL (parset.getString (prefix + "baseline", defaultBaseline)),
itsCorrType (parset.getString (prefix + "corrtype", defaultCorrType)),
itsRangeBL (parset.getDoubleVector (prefix + "blrange",
vector<double>()))
{
if (minmax) {
double minbl = parset.getDouble (prefix + "blmin", -1);
double maxbl = parset.getDouble (prefix + "blmax", -1);
if (minbl > 0) {
itsRangeBL.push_back (0.);
itsRangeBL.push_back (minbl);
}
if (maxbl > 0) {
itsRangeBL.push_back (maxbl);
itsRangeBL.push_back (1e30);
}
}
ASSERTSTR (itsRangeBL.size()%2 == 0,
"NDPPP error: uneven number of lengths in baseline range");
}
bool BaselineSelection::hasSelection() const
{
return !((itsStrBL.empty() || itsStrBL == "[]") &&
itsCorrType.empty() && itsRangeBL.empty());
}
void BaselineSelection::show (ostream& os, const string& blanks) const
{
os << " Baseline selection:" << std::endl;
os << " baseline: " << blanks << itsStrBL << std::endl;
os << " corrtype: " << blanks << itsCorrType << std::endl;
os << " blrange: " << blanks << itsRangeBL << std::endl;
}
Matrix<bool> BaselineSelection::apply (const DPInfo& info) const
{
// Size and initialize the selection matrix.
int nant = info.antennaNames().size();
Matrix<bool> selectBL(nant, nant, true);
// Apply the various parts if given.
if (! itsStrBL.empty() && itsStrBL != "[]") {
handleBL (selectBL, info);
}
if (! itsCorrType.empty()) {
handleCorrType (selectBL);
}
if (! itsRangeBL.empty()) {
handleLength (selectBL, info);
}
return selectBL;
}
Vector<bool> BaselineSelection::applyVec (const DPInfo& info) const
{
Matrix<bool> sel = apply(info);
Vector<bool> vec;
vec.resize (info.nbaselines());
for (uint i=0; i<info.nbaselines(); ++i) {
vec[i] = sel(info.getAnt1()[i], info.getAnt2()[i]);
}
return vec;
}
void BaselineSelection::handleBL (Matrix<bool>& selectBL,
const DPInfo& info) const
{
// Handle the value(s) in the baseline selection string.
ParameterValue pvBL(itsStrBL);
// The value can be a vector or an MSSelection string.
// Alas the ParameterValue vector test cannot be used, because
// the first character of a MSSelection string can also be [.
// So if the first is [ and a ] is found before the end and before
// another [, it must be a MSSelection string.
bool mssel = true;
if (itsStrBL[0] == '[') {
String::size_type rb = itsStrBL.find (']');
ASSERTSTR (rb != string::npos,
"Baseline selection " + itsStrBL +
" has no ending ]");
if (rb == itsStrBL.size()-1) {
mssel = false;
} else {
String::size_type lb = itsStrBL.find ('[', 1);
mssel = (lb == string::npos || lb > rb);
}
}
if (!mssel) {
// Specified as a vector of antenna name patterns.
selectBL = selectBL && handleBLVector (pvBL, info.antennaNames());
} else {
// Specified in casacore's MSSelection format.
string msName = info.msName();
ASSERT (! msName.empty());
Matrix<bool> sel(BaselineSelect::convert (msName, itsStrBL));
// The resulting matrix can be smaller because new stations might have
// been added that are not present in the MS's ANTENNA table.
if (sel.nrow() == selectBL.nrow()) {
selectBL = selectBL && sel;
} else {
// Only and the subset.
Matrix<bool> selBL = selectBL(IPosition(2,0),
IPosition(2,sel.nrow()-1));
selBL = selBL && sel;
}
}
}
Matrix<bool> BaselineSelection::handleBLVector (const ParameterValue& pvBL,
const Vector<String>& antNames) const
{
Matrix<Bool> sel(antNames.size(), antNames.size());
sel = false;
vector<ParameterValue> pairs = pvBL.getVector();
// Each ParameterValue can be a single value (antenna) or a pair of
// values (a baseline).
// Note that [ant1,ant2] is somewhat ambiguous; it means two antennae,
// but one might think it means a baseline [[ant1,ant2]].
if (pairs.size() == 2 &&
!(pairs[0].isVector() || pairs[1].isVector())) {
LOG_WARN_STR ("PreFlagger baseline " << pvBL.get()
<< " means two antennae, but is somewhat ambigious; "
<< "it's more clear to use [[ant1],[ant2]]");
}
for (uint i=0; i<pairs.size(); ++i) {
vector<string> bl = pairs[i].getStringVector();
if (bl.size() == 1) {
// Turn the given antenna name pattern into a regex.
Regex regex(Regex::fromPattern (bl[0]));
int nmatch = 0;
// Loop through all antenna names and set matrix for matching ones.
for (uint i2=0; i2<antNames.size(); ++i2) {
if (antNames[i2].matches (regex)) {
nmatch++;
// Antenna matches, so set all corresponding flags.
for (uint j=0; j<antNames.size(); ++j) {
sel(i2,j) = true;
sel(j,i2) = true;
}
}
}
if (nmatch == 0) {
DPLOG_WARN_STR ("PreFlagger: no matches for antenna name pattern ["
<< bl[0] << "]");
}
} else {
ASSERTSTR (bl.size() == 2, "PreFlagger baseline " << bl <<
" should contain 1 or 2 antenna name patterns");
// Turn the given antenna name pattern into a regex.
Regex regex1(Regex::fromPattern (bl[0]));
Regex regex2(Regex::fromPattern (bl[1]));
int nmatch = 0;
// Loop through all antenna names and set matrix for matching ones.
for (uint i2=0; i2<antNames.size(); ++i2) {
if (antNames[i2].matches (regex2)) {
// Antenna2 matches, now try Antenna1.
for (uint i1=0; i1<antNames.size(); ++i1) {
if (antNames[i1].matches (regex1)) {
nmatch++;
sel(i1,i2) = true;
sel(i2,i1) = true;
}
}
}
}
if (nmatch == 0) {
DPLOG_WARN_STR ("PreFlagger: no matches for baseline name pattern ["
<< bl[0] << ',' << bl[1] << "]");
}
}
}
return sel;
}
void BaselineSelection::handleCorrType (Matrix<bool>& selectBL) const
{
// Process corrtype if given.
string corrType = toLower(itsCorrType);
ASSERTSTR (corrType == "auto" || corrType == "cross",
"NDPPP corrType " << corrType
<< " is invalid; must be auto, cross, or empty string");
if (corrType == "auto") {
Vector<bool> diag = selectBL.diagonal().copy();
selectBL = false;
selectBL.diagonal() = diag;
} else {
selectBL.diagonal() = false;
}
}
void BaselineSelection::handleLength (Matrix<bool>& selectBL,
const DPInfo& info) const
{
// Get baseline lengths.
const vector<double>& blength = info.getBaselineLengths();
const Vector<Int>& ant1 = info.getAnt1();
const Vector<Int>& ant2 = info.getAnt2();
for (uint i=0; i<ant1.size(); ++i) {
// Clear selection if no range matches.
bool match = false;
for (uint j=0; j<itsRangeBL.size(); j+=2) {
if (blength[i] >= itsRangeBL[j] && blength[i] <= itsRangeBL[j+1]) {
match = true;
break;
}
}
if (!match) {
int a1 = ant1[i];
int a2 = ant2[i];
selectBL(a1,a2) = false;
selectBL(a2,a1) = false;
}
}
}
} //# end namespace
}
| jjdmol/LOFAR | CEP/DP3/DPPP/src/BaselineSelection.cc | C++ | gpl-3.0 | 9,934 |
//
//---------------------------------------------------------------------------
//
// Copyright(C) 2005-2016 Christoph Oelckers
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//--------------------------------------------------------------------------
//
/*
** r_opengl.cpp
**
** OpenGL system interface
**
*/
#include "gl/system/gl_system.h"
#include "tarray.h"
#include "doomtype.h"
#include "m_argv.h"
#include "zstring.h"
#include "version.h"
#include "i_system.h"
#include "v_text.h"
#include "r_data/r_translate.h"
#include "gl/system/gl_interface.h"
#include "gl/system/gl_cvars.h"
void gl_PatchMenu();
static TArray<FString> m_Extensions;
RenderContext gl;
//==========================================================================
//
//
//
//==========================================================================
static void CollectExtensions()
{
const char *extension;
int max = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &max);
if (0 == max)
{
// Try old method to collect extensions
const char *supported = (char *)glGetString(GL_EXTENSIONS);
if (nullptr != supported)
{
char *extensions = new char[strlen(supported) + 1];
strcpy(extensions, supported);
char *extension = strtok(extensions, " ");
while (extension)
{
m_Extensions.Push(FString(extension));
extension = strtok(nullptr, " ");
}
delete [] extensions;
}
}
else
{
// Use modern method to collect extensions
for (int i = 0; i < max; i++)
{
extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
m_Extensions.Push(FString(extension));
}
}
}
//==========================================================================
//
//
//
//==========================================================================
static bool CheckExtension(const char *ext)
{
for (unsigned int i = 0; i < m_Extensions.Size(); ++i)
{
if (m_Extensions[i].CompareNoCase(ext) == 0) return true;
}
return false;
}
//==========================================================================
//
//
//
//==========================================================================
static void InitContext()
{
gl.flags=0;
}
//==========================================================================
//
//
//
//==========================================================================
#define FUDGE_FUNC(name, ext) if (_ptrc_##name == NULL) _ptrc_##name = _ptrc_##name##ext;
void gl_LoadExtensions()
{
InitContext();
CollectExtensions();
const char *version = Args->CheckValue("-glversion");
const char *glversion = (const char*)glGetString(GL_VERSION);
if (version == NULL)
{
version = glversion;
}
else
{
double v1 = strtod(version, NULL);
double v2 = strtod(glversion, NULL);
if (v2 < v1) version = glversion;
else Printf("Emulating OpenGL v %s\n", version);
}
float gl_version = (float)strtod(version, NULL) + 0.01f;
// Don't even start if it's lower than 2.0 or no framebuffers are available (The framebuffer extension is needed for glGenerateMipmapsEXT!)
if ((gl_version < 2.0f || !CheckExtension("GL_EXT_framebuffer_object")) && gl_version < 3.0f)
{
I_FatalError("Unsupported OpenGL version.\nAt least OpenGL 2.0 with framebuffer support is required to run " GAMENAME ".\n");
}
// add 0.01 to account for roundoff errors making the number a tad smaller than the actual version
gl.glslversion = strtod((char*)glGetString(GL_SHADING_LANGUAGE_VERSION), NULL) + 0.01f;
gl.vendorstring = (char*)glGetString(GL_VENDOR);
// first test for optional features
if (CheckExtension("GL_ARB_texture_compression")) gl.flags |= RFL_TEXTURE_COMPRESSION;
if (CheckExtension("GL_EXT_texture_compression_s3tc")) gl.flags |= RFL_TEXTURE_COMPRESSION_S3TC;
if ((gl_version >= 3.3f || CheckExtension("GL_ARB_sampler_objects")) && !Args->CheckParm("-nosampler"))
{
gl.flags |= RFL_SAMPLER_OBJECTS;
}
// The minimum requirement for the modern render path are GL 3.0 + uniform buffers. Also exclude the Linux Mesa driver at GL 3.0 because it errors out on shader compilation.
if (gl_version < 3.0f || (gl_version < 3.1f && (!CheckExtension("GL_ARB_uniform_buffer_object") || strstr(gl.vendorstring, "X.Org") != nullptr)))
{
gl.legacyMode = true;
gl.lightmethod = LM_LEGACY;
gl.buffermethod = BM_LEGACY;
gl.glslversion = 0;
gl.flags |= RFL_NO_CLIP_PLANES;
}
else
{
gl.legacyMode = false;
gl.lightmethod = LM_DEFERRED;
gl.buffermethod = BM_DEFERRED;
if (gl_version < 4.f)
{
#ifdef _WIN32
if (strstr(gl.vendorstring, "ATI Tech"))
{
gl.flags |= RFL_NO_CLIP_PLANES; // gl_ClipDistance is horribly broken on ATI GL3 drivers for Windows.
}
#endif
}
else if (gl_version < 4.5f)
{
// don't use GL 4.x features when running a GL 3.x context.
if (CheckExtension("GL_ARB_buffer_storage"))
{
// work around a problem with older AMD drivers: Their implementation of shader storage buffer objects is piss-poor and does not match uniform buffers even closely.
// Recent drivers, GL 4.4 don't have this problem, these can easily be recognized by also supporting the GL_ARB_buffer_storage extension.
if (CheckExtension("GL_ARB_shader_storage_buffer_object"))
{
// Shader storage buffer objects are broken on current Intel drivers.
if (strstr(gl.vendorstring, "Intel") == NULL)
{
gl.flags |= RFL_SHADER_STORAGE_BUFFER;
}
}
gl.flags |= RFL_BUFFER_STORAGE;
gl.lightmethod = LM_DIRECT;
gl.buffermethod = BM_PERSISTENT;
}
}
else
{
// Assume that everything works without problems on GL 4.5 drivers where these things are core features.
gl.flags |= RFL_SHADER_STORAGE_BUFFER | RFL_BUFFER_STORAGE;
gl.lightmethod = LM_DIRECT;
gl.buffermethod = BM_PERSISTENT;
}
if (gl_version >= 4.3f || CheckExtension("GL_ARB_invalidate_subdata")) gl.flags |= RFL_INVALIDATE_BUFFER;
if (gl_version >= 4.3f || CheckExtension("GL_KHR_debug")) gl.flags |= RFL_DEBUG;
const char *lm = Args->CheckValue("-lightmethod");
if (lm != NULL)
{
if (!stricmp(lm, "deferred") && gl.lightmethod == LM_DIRECT) gl.lightmethod = LM_DEFERRED;
}
lm = Args->CheckValue("-buffermethod");
if (lm != NULL)
{
if (!stricmp(lm, "deferred") && gl.buffermethod == BM_PERSISTENT) gl.buffermethod = BM_DEFERRED;
}
}
int v;
if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER))
{
glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &v);
gl.maxuniforms = v;
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &v);
gl.maxuniformblock = v;
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &v);
gl.uniformblockalignment = v;
}
else
{
gl.maxuniforms = 0;
gl.maxuniformblock = 0;
gl.uniformblockalignment = 0;
}
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl.max_texturesize);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
if (gl.legacyMode)
{
// fudge a bit with the framebuffer stuff to avoid redundancies in the main code. Some of the older cards do not have the ARB stuff but the calls are nearly identical.
FUDGE_FUNC(glGenerateMipmap, EXT);
FUDGE_FUNC(glGenFramebuffers, EXT);
FUDGE_FUNC(glBindFramebuffer, EXT);
FUDGE_FUNC(glDeleteFramebuffers, EXT);
FUDGE_FUNC(glFramebufferTexture2D, EXT);
FUDGE_FUNC(glGenerateMipmap, EXT);
FUDGE_FUNC(glGenFramebuffers, EXT);
FUDGE_FUNC(glBindFramebuffer, EXT);
FUDGE_FUNC(glDeleteFramebuffers, EXT);
FUDGE_FUNC(glFramebufferTexture2D, EXT);
FUDGE_FUNC(glFramebufferRenderbuffer, EXT);
FUDGE_FUNC(glGenRenderbuffers, EXT);
FUDGE_FUNC(glDeleteRenderbuffers, EXT);
FUDGE_FUNC(glRenderbufferStorage, EXT);
FUDGE_FUNC(glBindRenderbuffer, EXT);
FUDGE_FUNC(glCheckFramebufferStatus, EXT);
gl_PatchMenu();
}
}
//==========================================================================
//
//
//
//==========================================================================
void gl_PrintStartupLog()
{
int v = 0;
if (!gl.legacyMode) glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &v);
Printf ("GL_VENDOR: %s\n", glGetString(GL_VENDOR));
Printf ("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
Printf ("GL_VERSION: %s (%s profile)\n", glGetString(GL_VERSION), (v & GL_CONTEXT_CORE_PROFILE_BIT)? "Core" : "Compatibility");
Printf ("GL_SHADING_LANGUAGE_VERSION: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
Printf (PRINT_LOG, "GL_EXTENSIONS:");
for (unsigned i = 0; i < m_Extensions.Size(); i++)
{
Printf(PRINT_LOG, " %s", m_Extensions[i].GetChars());
}
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &v);
Printf("\nMax. texture size: %d\n", v);
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &v);
Printf ("Max. texture units: %d\n", v);
glGetIntegerv(GL_MAX_VARYING_FLOATS, &v);
Printf ("Max. varying: %d\n", v);
if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER))
{
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &v);
Printf ("Max. uniform block size: %d\n", v);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &v);
Printf ("Uniform block alignment: %d\n", v);
}
if (gl.flags & RFL_SHADER_STORAGE_BUFFER)
{
glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, &v);
Printf("Max. combined shader storage blocks: %d\n", v);
glGetIntegerv(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS, &v);
Printf("Max. vertex shader storage blocks: %d\n", v);
}
// For shader-less, the special alphatexture translation must be changed to actually set the alpha, because it won't get translated by a shader.
if (gl.legacyMode)
{
FRemapTable *remap = translationtables[TRANSLATION_Standard][8];
for (int i = 0; i < 256; i++)
{
remap->Remap[i] = i;
remap->Palette[i] = PalEntry(i, 255, 255, 255);
}
}
}
| Saican/Whitman | src/gl/system/gl_interface.cpp | C++ | gpl-3.0 | 10,215 |
/*******************************************************************************
* Copyright (c) 2008, 2010 Xuggle Inc. All rights reserved.
*
* This file is part of Xuggle-Utils.
*
* Xuggle-Utils 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.
*
* Xuggle-Utils 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 Xuggle-Utils. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/**
* Provides convenience methods for registering, and
* special implementations of,
* {@link com.xuggle.utils.event.IEventHandler}.
* <p>
* There are certain types of {@link com.xuggle.utils.event.IEventHandler}
* implementations that are very common. For example, sometimes
* you want to forward an event from one
* {@link com.xuggle.utils.event.IEventDispatcher}
* to another.
* Sometimes you only want
* a {@link com.xuggle.utils.event.IEventHandler} to execute if the
* {@link com.xuggle.utils.event.IEvent#getSource()} is equal to
* a given source.
* Sometimes you only
* want to handler to execute a maximum number of times.
* </p>
* <p>
* This class tries to provide some of those implementations for you.
* </p>
* <p>
* Use the {@link com.xuggle.utils.event.handler.Handler} class to find
* Factory methods for the special handlers you want.
* </p>
* @see com.xuggle.utils.event.handler.Handler
*
*/
package com.xuggle.utils.event.handler;
| artclarke/xuggle-utils | src/main/java/com/xuggle/utils/event/handler/package-info.java | Java | gpl-3.0 | 1,917 |
class CreatePasswords < ActiveRecord::Migration
def change
create_table :passwords do |p|
p.string :url
p.string :user
p.string :password
#p.timestamps null: false
end
end
end
| webgoal/minhas-senhas-1 | db/migrate/20160408001709_create_tests.rb | Ruby | gpl-3.0 | 213 |
/*
Copyright (c) 1993-2008, Cognitive Technologies
All rights reserved.
Разрешается повторное распространение и использование как в виде исходного кода,
так и в двоичной форме, с изменениями или без, при соблюдении следующих условий:
* При повторном распространении исходного кода должны оставаться указанное
выше уведомление об авторском праве, этот список условий и последующий
отказ от гарантий.
* При повторном распространении двоичного кода в документации и/или в
других материалах, поставляемых при распространении, должны сохраняться
указанная выше информация об авторском праве, этот список условий и
последующий отказ от гарантий.
* Ни название Cognitive Technologies, ни имена ее сотрудников не могут
быть использованы в качестве средства поддержки и/или продвижения
продуктов, основанных на этом ПО, без предварительного письменного
разрешения.
ЭТА ПРОГРАММА ПРЕДОСТАВЛЕНА ВЛАДЕЛЬЦАМИ АВТОРСКИХ ПРАВ И/ИЛИ ДРУГИМИ ЛИЦАМИ "КАК
ОНА ЕСТЬ" БЕЗ КАКОГО-ЛИБО ВИДА ГАРАНТИЙ, ВЫРАЖЕННЫХ ЯВНО ИЛИ ПОДРАЗУМЕВАЕМЫХ,
ВКЛЮЧАЯ ГАРАНТИИ КОММЕРЧЕСКОЙ ЦЕННОСТИ И ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ, НО НЕ
ОГРАНИЧИВАЯСЬ ИМИ. НИ ВЛАДЕЛЕЦ АВТОРСКИХ ПРАВ И НИ ОДНО ДРУГОЕ ЛИЦО, КОТОРОЕ
МОЖЕТ ИЗМЕНЯТЬ И/ИЛИ ПОВТОРНО РАСПРОСТРАНЯТЬ ПРОГРАММУ, НИ В КОЕМ СЛУЧАЕ НЕ
НЕСЁТ ОТВЕТСТВЕННОСТИ, ВКЛЮЧАЯ ЛЮБЫЕ ОБЩИЕ, СЛУЧАЙНЫЕ, СПЕЦИАЛЬНЫЕ ИЛИ
ПОСЛЕДОВАВШИЕ УБЫТКИ, СВЯЗАННЫЕ С ИСПОЛЬЗОВАНИЕМ ИЛИ ПОНЕСЕННЫЕ ВСЛЕДСТВИЕ
НЕВОЗМОЖНОСТИ ИСПОЛЬЗОВАНИЯ ПРОГРАММЫ (ВКЛЮЧАЯ ПОТЕРИ ДАННЫХ, ИЛИ ДАННЫЕ,
СТАВШИЕ НЕГОДНЫМИ, ИЛИ УБЫТКИ И/ИЛИ ПОТЕРИ ДОХОДОВ, ПОНЕСЕННЫЕ ИЗ-ЗА ДЕЙСТВИЙ
ТРЕТЬИХ ЛИЦ И/ИЛИ ОТКАЗА ПРОГРАММЫ РАБОТАТЬ СОВМЕСТНО С ДРУГИМИ ПРОГРАММАМИ,
НО НЕ ОГРАНИЧИВАЯСЬ ЭТИМИ СЛУЧАЯМИ), НО НЕ ОГРАНИЧИВАЯСЬ ИМИ, ДАЖЕ ЕСЛИ ТАКОЙ
ВЛАДЕЛЕЦ ИЛИ ДРУГОЕ ЛИЦО БЫЛИ ИЗВЕЩЕНЫ О ВОЗМОЖНОСТИ ТАКИХ УБЫТКОВ И ПОТЕРЬ.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Cognitive Technologies nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
/* interface my */
#include "gystogra.h"
/* interface our util */
#include "skew1024.h"
using namespace cf;
/*---------------------------------------------------------------------------*/
Bool MakeTopBotGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, i, End;
long dy, ddy;
int32_t x, yBeg, yEnd;
int32_t SkewSquar;
int *pBegSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
x = (pRc[0].left + pRc[0].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[0].top;
yEnd = pRc[0].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
MinBeg = yBeg;
MaxBeg = yBeg;
MinEnd = yEnd;
MaxEnd = yEnd;
for (i = 1; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
if (MinBeg > yBeg)
MinBeg = yBeg;
if (MaxBeg < yBeg)
MaxBeg = yBeg;
if (MinEnd > yEnd)
MinEnd = yEnd;
if (MaxEnd < yEnd)
MaxEnd = yEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
pBegSig[yBeg - MinBeg]++;
pEndSig[yEnd - MinEnd]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeLefRigGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, i, End;
long dx, ddx;
int32_t y, xBeg, xEnd;
int32_t SkewSquar;
int *pBegSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
y = (pRc[0].top + pRc[0].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[0].left;
xEnd = pRc[0].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
MinBeg = xBeg;
MaxBeg = xBeg;
MinEnd = xEnd;
MaxEnd = xEnd;
for (i = 1; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
if (MinBeg > xBeg)
MinBeg = xBeg;
if (MaxBeg < xBeg)
MaxBeg = xBeg;
if (MinEnd > xEnd)
MinEnd = xEnd;
if (MaxEnd < xEnd)
MaxEnd = xEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
pBegSig[xBeg - MinBeg]++;
pEndSig[xEnd - MinEnd]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeTopMidBotGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pMidGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinMid, MaxMid, MinEnd, MaxEnd, i, End;
long dy, ddy;
int32_t x, yBeg, yMid, yEnd;
int32_t SkewSquar;
int *pBegSig, *pMidSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pMidGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pMidSig = pMidGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
x = (pRc[0].left + pRc[0].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[0].top;
yMid = (pRc[0].top + pRc[0].bottom + 1) / 2;
yEnd = pRc[0].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yMid + 0x100000) >> 21);
yMid += dy;
yMid -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
MinBeg = yBeg;
MaxBeg = yBeg;
MinMid = yMid;
MaxMid = yMid;
MinEnd = yEnd;
MaxEnd = yEnd;
for (i = 1; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yMid = (pRc[i].top + pRc[i].bottom + 1) / 2;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yMid + 0x100000) >> 21);
yMid += dy;
yMid -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
if (MinBeg > yBeg)
MinBeg = yBeg;
if (MaxBeg < yBeg)
MaxBeg = yBeg;
if (MinMid > yMid)
MinMid = yMid;
if (MaxMid < yMid)
MaxMid = yMid;
if (MinEnd > yEnd)
MinEnd = yEnd;
if (MaxEnd < yEnd)
MaxEnd = yEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxMid - MinMid >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pMidGt->Shift = MinMid;
pMidGt->End = MaxMid - MinMid;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pMidGt->End)
End = pMidGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pMidSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yMid = (pRc[i].top + pRc[i].bottom + 1) / 2;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yMid + 0x100000) >> 21);
yMid += dy;
yMid -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
pBegSig[yBeg - MinBeg]++;
pMidSig[yMid - MinMid]++;
pEndSig[yEnd - MinEnd]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeLefMidRigGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pMidGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinMid, MaxMid, MinEnd, MaxEnd, i, End;
long dx, ddx;
int32_t y, xBeg, xMid, xEnd;
int32_t SkewSquar;
int *pBegSig, *pMidSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pMidGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pMidSig = pMidGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
y = (pRc[0].top + pRc[0].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[0].left;
xMid = (pRc[0].left + pRc[0].right + 1) / 2;
xEnd = pRc[0].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xMid + 0x100000) >> 21);
xMid -= dx;
xMid -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
MinBeg = xBeg;
MaxBeg = xBeg;
MinMid = xMid;
MaxMid = xMid;
MinEnd = xEnd;
MaxEnd = xEnd;
for (i = 1; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xMid = (pRc[i].left + pRc[i].right + 1) / 2;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xMid + 0x100000) >> 21);
xMid -= dx;
xMid -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
if (MinBeg > xBeg)
MinBeg = xBeg;
if (MaxBeg < xBeg)
MaxBeg = xBeg;
if (MinMid > xMid)
MinMid = xMid;
if (MaxMid < xMid)
MaxMid = xMid;
if (MinEnd > xEnd)
MinEnd = xEnd;
if (MaxEnd < xEnd)
MaxEnd = xEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxMid - MinMid >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pMidGt->Shift = MinMid;
pMidGt->End = MaxMid - MinMid;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pMidGt->End)
End = pMidGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pMidSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xMid = (pRc[i].left + pRc[i].right + 1) / 2;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xMid + 0x100000) >> 21);
xMid -= dx;
xMid -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
pBegSig[xBeg - MinBeg]++;
pMidSig[xMid - MinMid]++;
pEndSig[xEnd - MinEnd]++;
}
return TRUE;
}
int ScoreComp(const Rect16 *pRcReg, const int32_t Skew, const Rect16 *pRc,
const int nRc) {
int i, k;
Point PosIdeal;
k = 0;
for (i = 0; i < nRc; i++) {
if (pRc[i].right - pRc[i].left < 2)
continue;
if (pRc[i].right - pRc[i].left > 100)
continue;
if (pRc[i].bottom - pRc[i].top < 2)
continue;
if (pRc[i].bottom - pRc[i].top > 100)
continue;
PosIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
PosIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
PosIdeal.deskew(-Skew);
if (PosIdeal.x() > pRcReg->right)
continue;
if (PosIdeal.x() < pRcReg->left)
continue;
if (PosIdeal.y() > pRcReg->bottom)
continue;
if (PosIdeal.y() < pRcReg->top)
continue;
k++;
}
return k;
}
/*---------------------------------------------------------------------------*/
void MakeNormVertGyst(const Rect16 *pRcReg, const int32_t Skew,
const Rect16 *pRc, const int nRc, int *Sig) {
int i, k;
Point BegDirIdeal;
Point EndDirIdeal;
for (i = 0; i < nRc; i++) {
if (pRc[i].right - pRc[i].left < 2)
continue;
if (pRc[i].right - pRc[i].left > 100)
continue;
if (pRc[i].bottom - pRc[i].top < 2)
continue;
if (pRc[i].bottom - pRc[i].top > 100)
continue;
BegDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
BegDirIdeal.ry() = pRc[i].top;
BegDirIdeal.deskew(-Skew);
if (BegDirIdeal.x() > pRcReg->right)
continue;
if (BegDirIdeal.x() < pRcReg->left)
continue;
if (BegDirIdeal.y() >= pRcReg->bottom)
continue;
if (BegDirIdeal.y() < pRcReg->top)
BegDirIdeal.ry() = pRcReg->top;
EndDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
EndDirIdeal.ry() = pRc[i].bottom;
EndDirIdeal.deskew(-Skew);
if (EndDirIdeal.y() <= pRcReg->top)
continue;
if (EndDirIdeal.y() > pRcReg->bottom)
EndDirIdeal.ry() = pRcReg->bottom;
for (k = BegDirIdeal.y(); k <= EndDirIdeal.y(); k++)
Sig[k - pRcReg->top]++;
}
}
/*---------------------------------------------------------------------------*/
Bool MakeVertGysts(Rect16 *pRc, int nRc, int32_t Skew, int Amnist, int MaxSize,
Un_GYST *pVerGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
Point BegDirIdeal;
Point EndDirIdeal;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
BegDirIdeal.rx() = (int) (.5 * (pRc[iFirst].left + pRc[iFirst].right + 1));
BegDirIdeal.ry() = pRc[iFirst].top;
BegDirIdeal.deskew(-Skew);
MinBeg = BegDirIdeal.y();
MaxBeg = BegDirIdeal.y();
EndDirIdeal.rx() = (int) (.5 * (pRc[iFirst].left + pRc[iFirst].right + 1));
EndDirIdeal.ry() = pRc[iFirst].bottom;
EndDirIdeal.deskew(-Skew);
MinEnd = EndDirIdeal.y();
MaxEnd = EndDirIdeal.y();
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
BegDirIdeal.ry() = pRc[i].top;
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.y();
EndDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
EndDirIdeal.ry() = pRc[i].bottom;
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.y();
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pVerGt->Shift = MinBeg;
pVerGt->End = MaxEnd - MinBeg;
pVerGt->nElem = nRc;
End = pVerGt->End;
for (i = 0; i <= End; i++) {
pVerGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
BegDirIdeal.ry() = pRc[i].top;
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.y();
EndDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
EndDirIdeal.ry() = pRc[i].bottom;
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.y();
for (k = CurBeg + Amnist; k <= CurEnd - Amnist; k++)
pVerGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
void MakeNormHoriGyst(const Rect16 *pRcReg, const int32_t Skew,
const Rect16 *pRc, const int nRc, int *Sig) {
int i, k;
Point BegDirIdeal;
Point EndDirIdeal;
for (i = 0; i < nRc; i++) {
if (pRc[i].right - pRc[i].left < 2)
continue;
if (pRc[i].right - pRc[i].left > 100)
continue;
if (pRc[i].bottom - pRc[i].top < 2)
continue;
if (pRc[i].bottom - pRc[i].top > 100)
continue;
BegDirIdeal.rx() = pRc[i].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
BegDirIdeal.deskew(-Skew);
if (BegDirIdeal.y() > pRcReg->bottom)
continue;
if (BegDirIdeal.y() < pRcReg->top)
continue;
if (BegDirIdeal.x() >= pRcReg->right)
continue;
if (BegDirIdeal.x() < pRcReg->left)
BegDirIdeal.rx() = pRcReg->left;
EndDirIdeal.rx() = pRc[i].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
EndDirIdeal.deskew(-Skew);
if (EndDirIdeal.x() <= pRcReg->left)
continue;
if (EndDirIdeal.x() > pRcReg->right)
EndDirIdeal.rx() = pRcReg->right;
for (k = BegDirIdeal.x(); k <= EndDirIdeal.x(); k++)
Sig[k - pRcReg->left]++;
}
}
/*---------------------------------------------------------------------------*/
Bool MakeHoriGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pHorGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
Point BegDirIdeal;
Point EndDirIdeal;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
BegDirIdeal.rx() = pRc[iFirst].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[iFirst].top + pRc[iFirst].bottom + 1));
BegDirIdeal.deskew(-Skew);
MinBeg = BegDirIdeal.x();
MaxBeg = BegDirIdeal.x();
EndDirIdeal.rx() = pRc[iFirst].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[iFirst].top + pRc[iFirst].bottom + 1));
EndDirIdeal.deskew(-Skew);
MinEnd = EndDirIdeal.x();
MaxEnd = EndDirIdeal.x();
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = pRc[i].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.x();
EndDirIdeal.rx() = pRc[i].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.x();
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pHorGt->Shift = MinBeg;
pHorGt->End = MaxEnd - MinBeg;
pHorGt->nElem = nRc;
End = pHorGt->End;
for (i = 0; i <= End; i++) {
pHorGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = pRc[i].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.x();
EndDirIdeal.rx() = pRc[i].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.x();
for (k = CurBeg; k <= CurEnd; k++)
pHorGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeHoriSrez(Rect16 *pRcId, int nRc, int BegSrez, int EndSrez,
int MaxSize, Un_GYST *pHorGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
MinBeg = pRcId[iFirst].left;
MaxBeg = MinBeg;
MinEnd = pRcId[iFirst].right;
MaxEnd = MinEnd;
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
CurBeg = pRcId[i].left;
CurEnd = pRcId[i].right;
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pHorGt->Shift = MinBeg;
pHorGt->End = MaxEnd - MinBeg;
pHorGt->nElem = nRc;
End = pHorGt->End;
for (i = 0; i <= End; i++) {
pHorGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
if (pRcId[i].top >= EndSrez)
continue;
if (pRcId[i].bottom <= BegSrez)
continue;
CurBeg = pRcId[i].left;
CurEnd = pRcId[i].right;
for (k = CurBeg; k <= CurEnd; k++)
pHorGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeVertSrez(Rect16 *pRcId, int nRc, int BegSrez, int EndSrez,
int MaxSize, Un_GYST *pVerGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
MinBeg = pRcId[iFirst].top;
MaxBeg = MinBeg;
MinEnd = pRcId[iFirst].bottom;
MaxEnd = MinEnd;
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
CurBeg = pRcId[i].top;
CurEnd = pRcId[i].bottom;
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pVerGt->Shift = MinBeg;
pVerGt->End = MaxEnd - MinBeg;
pVerGt->nElem = nRc;
End = pVerGt->End;
for (i = 0; i <= End; i++) {
pVerGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
if (pRcId[i].left >= EndSrez)
continue;
if (pRcId[i].right <= BegSrez)
continue;
CurBeg = pRcId[i].top;
CurEnd = pRcId[i].bottom;
for (k = CurBeg; k <= CurEnd; k++)
pVerGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool FindNextHole(Un_GYST *pDarkGt, int Beg, int End, int *NewBeg, int *NewEnd) {
int i;
Bool ret;
if (Beg > End)
return FALSE;
ret = FALSE;
for (i = Beg; i <= End; i++) {
if (i < pDarkGt->Shift)
continue;
if (i > pDarkGt->Shift + pDarkGt->End)
break;
if (pDarkGt->Signal[i - pDarkGt->Shift] > 0)
continue;
*NewBeg = i;
ret = TRUE;
break;
}
if (!ret)
return FALSE;
for (i = *NewBeg; i <= End; i++) {
if (i > pDarkGt->Shift + pDarkGt->End)
break;
if (pDarkGt->Signal[i - pDarkGt->Shift] > 0)
break;
*NewEnd = i;
continue;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool FindNextHoleWithBound(int MaxSig, Un_GYST *pDarkGt, int Beg, int End,
int *NewBeg, int *NewEnd, int MinLent) {
int i, Beg_C, End_C;
Bool ret;
if (Beg > End)
return FALSE;
Beg_C = Beg;
if (Beg_C < pDarkGt->Shift)
Beg_C = pDarkGt->Shift;
End_C = End;
if (End_C > pDarkGt->Shift + pDarkGt->End)
End_C = pDarkGt->Shift + pDarkGt->End;
if (Beg_C > End_C)
return FALSE;
while (Beg_C <= End_C) {
ret = FALSE;
for (i = Beg_C; i <= End_C; i++) {
if (pDarkGt->Signal[i - pDarkGt->Shift] > MaxSig)
continue;
*NewBeg = i;
ret = TRUE;
break;
}
if (!ret)
return FALSE;
*NewEnd = *NewBeg;
for (i = *NewBeg; i <= End_C; i++) {
if (pDarkGt->Signal[i - pDarkGt->Shift] > MaxSig)
break;
*NewEnd = i;
continue;
}
if (*NewEnd - *NewBeg >= MinLent)
return TRUE;
Beg_C = *NewEnd + 1;
}
return FALSE;
}
/*---------------------------------------------------------------------------*/
Bool FindNormNextHoleWithBound(int *pSig, int LenSig, int Beg, int End,
int *NewBeg, int *NewEnd, int MaxSig, int MinLent) {
int i, Beg_C, End_C;
Bool ret;
if (Beg > End)
return FALSE;
Beg_C = Beg;
if (Beg_C < 0)
Beg_C = 0;
End_C = End;
if (End_C > LenSig - 1)
End_C = LenSig - 1;
if (Beg_C > End_C)
return FALSE;
while (Beg_C <= End_C) {
ret = FALSE;
for (i = Beg_C; i <= End_C; i++) {
if (pSig[i] > MaxSig)
continue;
*NewBeg = i;
ret = TRUE;
break;
}
if (!ret)
return FALSE;
*NewEnd = *NewBeg;
for (i = *NewBeg; i <= End_C; i++) {
if (pSig[i] > MaxSig)
break;
*NewEnd = i;
continue;
}
if (*NewEnd - *NewBeg >= MinLent)
return TRUE;
Beg_C = *NewEnd + 1;
}
return FALSE;
}
/*---------------------------------------------------------------------------*/
Bool FindMainHole(int Beg, int End, int MaxSig, Un_GYST *pOrtGt, int *NewBeg,
int *NewEnd, int *NewMax) {
int CurBeg, CurEnd, i, BegPos;
Bool ret;
ret = FindNextHoleWithBound(MaxSig, pOrtGt, Beg, End, &CurBeg, &CurEnd, 0);
if (!ret)
return FALSE;
*NewBeg = CurBeg;
*NewEnd = CurEnd;
BegPos = *NewEnd + 1;
while (1) {
ret = FindNextHoleWithBound(MaxSig, pOrtGt, BegPos, End, &CurBeg,
&CurEnd, 0);
if (!ret)
break;
BegPos = CurEnd + 1;
if (*NewEnd - *NewBeg > CurEnd - CurBeg)
continue;
*NewBeg = CurBeg;
*NewEnd = CurEnd;
}
*NewMax = pOrtGt->Signal[*NewBeg - pOrtGt->Shift];
for (i = *NewBeg; i <= *NewEnd; i++)
if (*NewMax < pOrtGt->Signal[i - pOrtGt->Shift])
*NewMax = pOrtGt->Signal[i - pOrtGt->Shift];
return TRUE;
}
/*---------------------------------------------------------------------------*/
| uliss/quneiform | src/usage/gystogra.cpp | C++ | gpl-3.0 | 28,504 |
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2021 IntellectualSites
*
* 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/>.
*/
package com.plotsquared.core.command;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import java.util.concurrent.CompletableFuture;
/**
* SubCommand class
*
* @see Command#Command(Command, boolean)
* @deprecated In favor of normal Command class
*/
public abstract class SubCommand extends Command {
public SubCommand() {
super(MainCommand.getInstance(), true);
}
public SubCommand(Argument<?>... arguments) {
this();
setRequiredArguments(arguments);
}
@Override
public CompletableFuture<Boolean> execute(
PlotPlayer<?> player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone
) {
return CompletableFuture.completedFuture(onCommand(player, args));
}
public abstract boolean onCommand(PlotPlayer<?> player, String[] args);
}
| IntellectualCrafters/PlotSquared | Core/src/main/java/com/plotsquared/core/command/SubCommand.java | Java | gpl-3.0 | 2,321 |
package com.github.sandokandias.payments.interfaces.rest.model;
import com.github.sandokandias.payments.infrastructure.util.i18n.I18nMessage;
import lombok.Data;
import java.util.Set;
@Data
public class ErrorResponse {
private Set<I18nMessage> errors;
}
| sandokandias/spring-boot-ddd | src/main/java/com/github/sandokandias/payments/interfaces/rest/model/ErrorResponse.java | Java | gpl-3.0 | 262 |
package pt.uminho.sysbio.biosynthframework.integration.model;
import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.MetaboliteMajorLabel;
public interface IntegrationEngine {
public IntegrationMap<String, MetaboliteMajorLabel> integrate(IntegrationMap<String, MetaboliteMajorLabel> imap);
}
| Fxe/biosynth-framework | biosynth-integration/src/main/java/pt/uminho/sysbio/biosynthframework/integration/model/IntegrationEngine.java | Java | gpl-3.0 | 299 |
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"math/big"
"github.com/ghostnetwrk/ghostnet/eth"
"github.com/ghostnetwrk/ghostnet/rpc/codec"
"github.com/ghostnetwrk/ghostnet/rpc/shared"
"github.com/ghostnetwrk/ghostnet/xeth"
)
const (
ShhApiVersion = "1.0"
)
var (
// mapping between methods and handlers
shhMapping = map[string]shhhandler{
"shh_version": (*shhApi).Version,
"shh_post": (*shhApi).Post,
"shh_hasIdentity": (*shhApi).HasIdentity,
"shh_newIdentity": (*shhApi).NewIdentity,
"shh_newFilter": (*shhApi).NewFilter,
"shh_uninstallFilter": (*shhApi).UninstallFilter,
"shh_getMessages": (*shhApi).GetMessages,
"shh_getFilterChanges": (*shhApi).GetFilterChanges,
}
)
func newWhisperOfflineError(method string) error {
return shared.NewNotAvailableError(method, "whisper offline")
}
// net callback handler
type shhhandler func(*shhApi, *shared.Request) (interface{}, error)
// shh api provider
type shhApi struct {
xeth *xeth.XEth
ethereum *eth.Ethereum
methods map[string]shhhandler
codec codec.ApiCoder
}
// create a new whisper api instance
func NewShhApi(xeth *xeth.XEth, eth *eth.Ethereum, coder codec.Codec) *shhApi {
return &shhApi{
xeth: xeth,
ethereum: eth,
methods: shhMapping,
codec: coder.New(nil),
}
}
// collection with supported methods
func (self *shhApi) Methods() []string {
methods := make([]string, len(self.methods))
i := 0
for k := range self.methods {
methods[i] = k
i++
}
return methods
}
// Execute given request
func (self *shhApi) Execute(req *shared.Request) (interface{}, error) {
if callback, ok := self.methods[req.Method]; ok {
return callback(self, req)
}
return nil, shared.NewNotImplementedError(req.Method)
}
func (self *shhApi) Name() string {
return shared.ShhApiName
}
func (self *shhApi) ApiVersion() string {
return ShhApiVersion
}
func (self *shhApi) Version(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
return w.Version(), nil
}
func (self *shhApi) Post(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
args := new(WhisperMessageArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
err := w.Post(args.Payload, args.To, args.From, args.Topics, args.Priority, args.Ttl)
if err != nil {
return false, err
}
return true, nil
}
func (self *shhApi) HasIdentity(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
args := new(WhisperIdentityArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return w.HasIdentity(args.Identity), nil
}
func (self *shhApi) NewIdentity(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
return w.NewIdentity(), nil
}
func (self *shhApi) NewFilter(req *shared.Request) (interface{}, error) {
args := new(WhisperFilterArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
id := self.xeth.NewWhisperFilter(args.To, args.From, args.Topics)
return newHexNum(big.NewInt(int64(id)).Bytes()), nil
}
func (self *shhApi) UninstallFilter(req *shared.Request) (interface{}, error) {
args := new(FilterIdArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return self.xeth.UninstallWhisperFilter(args.Id), nil
}
func (self *shhApi) GetFilterChanges(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
// Retrieve all the new messages arrived since the last request
args := new(FilterIdArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return self.xeth.WhisperMessagesChanged(args.Id), nil
}
func (self *shhApi) GetMessages(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
// Retrieve all the cached messages matching a specific, existing filter
args := new(FilterIdArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return self.xeth.WhisperMessages(args.Id), nil
}
| ghostnetwrk/ghostnet | rpc/api/shh.go | GO | gpl-3.0 | 5,209 |
package vrml.external.field;
import vrml.external.field.FieldTypes;
import vrml.external.Browser;
import java.awt.*;
import java.math.BigInteger;
public class EventInSFImage extends EventIn {
public EventInSFImage() { EventType = FieldTypes.SFIMAGE; }
public void setValue(int width, int height, int components, byte[] pixels) throws IllegalArgumentException {
int count;
int pixcount;
String val;
BigInteger newval;
byte xx[];
if (pixels.length != (width*height*components)) {
throw new IllegalArgumentException();
}
if ((components < 1) || (components > 4)) {
throw new IllegalArgumentException();
}
// use BigInt to ensure sign bit does not frick us up.
xx = new byte[components+1];
xx[0] = (byte) 0; // no sign bit here!
val = new String("" + width + " " + height + " " + components);
if (pixels== null) { pixcount = 0;} else {pixcount=pixels.length;}
if (components == 1) {
for (count = 0; count < pixcount; count++) {
xx[1] = pixels[count];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
if (components == 2) {
for (count = 0; count < pixcount; count+=2) {
xx[1] = pixels[count]; xx[2] = pixels[count+1];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
if (components == 3) {
for (count = 0; count < pixcount; count+=3) {
xx[1] = pixels[count]; xx[2] = pixels[count+1]; xx[3]=pixels[count+2];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
if (components == 4) {
for (count = 0; count < pixcount; count+=4) {
xx[1] = pixels[count]; xx[2] = pixels[count+1]; xx[3]=pixels[count+2]; xx[4]=pixels[count+3];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
//System.out.println ("sending " + val);
Browser.newSendEvent (this, val.length() + ":" + val + " ");
return;
}
}
| cbuehler/freewrl | src/java/vrml/external/field/EventInSFImage.java | Java | gpl-3.0 | 2,162 |
#include <cstdio>
template<typename T>
auto kitten(T x) __attribute__((noinline));
template<class T>
auto kitten(T t)
{
static T x = 0;
return (x += 1) + t;
}
int main()
{
printf("%d\n", kitten(1));
printf("%g\n", kitten(3.14));
}
| Lester-Dowling/studies | C++/CppCon/2015/Arthur-ODwyer-Lambdas-from-First-Principles/kitten-static-T.cpp | C++ | gpl-3.0 | 238 |
import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddress = []
executionTime = 0
def __init__(self,fromIp,toIp):
startTime = time.time()
self.fromIp = fromIp # from 192.168.1.x
self.toIp = toIp # to 192.168.x.x
self.__checkIfIpIsValid(fromIp)
self.__checkIfIpIsValid(toIp)
self.__getRange(fromIp,toIp)
self.__shellToQueue()
#self.__checkIfUp() # run by the shellToQueue queue organizer
self.__computerInfoInQueue()
endTime = time.time()
self.executionTime = round(endTime - startTime,3)
def __checkIfIpIsValid(self,ip):
def validateRange(val):
# valid range => 1 <-> 255
try:
val = int(val)
if val < 0 or val > 255:
print "Invalid IP Range ("+str(val)+")"
sys.exit(0)
except:
print "Invalid IP"
sys.exit(0)
ip = ip.split(".")
firstVal = validateRange(ip[0])
secondVal = validateRange(ip[1])
thirdVal = validateRange(ip[2])
fourthVal = validateRange(ip[3])
return True
def __getRange(self,fromIp,toIp):
fromIp = fromIp.split(".")
toIp = toIp.split(".")
# toIp must be > fromIp
def ip3chars(ipBlock):
# input 1; output 001
ipBlock = str(ipBlock)
while len(ipBlock) != 3:
ipBlock = "0"+ipBlock
return ipBlock
fromIpRaw = ip3chars(fromIp[0])+ip3chars(fromIp[1])+ip3chars(fromIp[2])+ip3chars(fromIp[3])
toIpRaw = ip3chars(toIp[0])+ip3chars(toIp[1])+ip3chars(toIp[2])+ip3chars(toIp[3])
if fromIpRaw > toIpRaw:
# if from is bigger switch the order
temp = fromIp
fromIp = toIp
toIp = temp
currentIp = [0,0,0,0]
# all to integers
currentIp0 = int(fromIp[0])
currentIp1 = int(fromIp[1])
currentIp2 = int(fromIp[2])
currentIp3 = int(fromIp[3])
toIp0 = int(toIp[0])
toIp1 = int(toIp[1])
toIp2 = int(toIp[2])
toIp3 = int(toIp[3])
firstIp = str(currentIp0)+"."+str(currentIp1)+"."+str(currentIp2)+"."+str(currentIp3)
self.__ipsToCheck = [firstIp]
while currentIp3 != toIp3 or currentIp2 != toIp2 or currentIp1 != toIp1 or currentIp0 != toIp0:
currentIp3 += 1
if currentIp3 > 255:
currentIp3 = 0
currentIp2 += 1
if currentIp2 > 255:
currentIp2 = 0
currentIp1 += 1
if currentIp1 > 255:
currentIp1 = 0
currentIp0 += 1
addIp = str(currentIp0)+"."+str(currentIp1)+"."+str(currentIp2)+"."+str(currentIp3)
self.__ipsToCheck.append(addIp)
def __shellToQueue(self):
# write them in the shell queue
maxPingsAtOnce = 200
currentQueuedPings = 0
for pingIp in self.__ipsToCheck:
proc = subprocess.Popen(['ping','-n','1',pingIp],stdout=subprocess.PIPE,shell=True)
self.__shellPings.append(proc)
currentQueuedPings += 1
if currentQueuedPings >= maxPingsAtOnce:
#execute shells
self.__checkIfUp()
currentQueuedPings = 0
self.__shellPings = []
self.__checkIfUp() # execute last queue
def __checkIfUp(self):
# execute the shells & determine whether the host is up or not
for shellInQueue in self.__shellPings:
pingResult = ""
shellInQueue.wait()
while True:
line = shellInQueue.stdout.readline()
if line != "":
pingResult += line
else:
break;
self.checkedIps += 1
if 'unreachable' in pingResult:
self.unreachable += 1
elif 'timed out' in pingResult:
self.timedOut += 1
else:
self.onlineIps += 1
currentIp = self.__ipsToCheck[self.checkedIps-1]
self.upIpsAddress.append(currentIp)
def __computerInfoInQueue(self):
# shell queue for online hosts
maxShellsAtOnce = 255
currentQueuedNbst = 0
for onlineIp in self.upIpsAddress:
proc = subprocess.Popen(['\\Windows\\sysnative\\nbtstat.exe','-a',onlineIp],stdout=subprocess.PIPE,shell=True)
self.__shell2Nbst.append(proc)
currentQueuedNbst += 1
if currentQueuedNbst >= maxShellsAtOnce:
# execute shells
self.__gatherComputerInfo()
currentQueuedNbst = 0
self.__shell2Nbst = []
self.__gatherComputerInfo() # execute last queue
def __gatherComputerInfo(self):
# execute the shells and find host Name and MAC
for shellInQueue in self.__shell2Nbst:
nbstResult = ""
shellInQueue.wait()
computerNameLine = ""
macAddressLine = ""
computerName = ""
macAddress = ""
while True:
line = shellInQueue.stdout.readline()
if line != "":
if '<00>' in line and 'UNIQUE' in line:
computerNameLine = line
if 'MAC Address' in line:
macAddressLine = line
else:
break;
computerName = re.findall('([ ]+)(.*?)([ ]+)<00>', computerNameLine)
macAddress = re.findall('([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)',macAddressLine)
try:
self.computerName.append(computerName[0][1])
except:
self.computerName.append("")
completeMacAddress = ""
firstMacElement = 0
try:
for macEach in macAddress[0]:
if firstMacElement == 0:
firstMacElement += 1
else:
completeMacAddress += ":"
completeMacAddress += macEach
firstMacElement = 0
except:
completeMacAddress = ""
self.completeMacAddress.append(completeMacAddress)
def readValue(self):
# debugging use only
ips = []
for ip in self.completeMacAddress:
ips.append(ip)
return ips
print "\t\t---LANScanner v1.0---\n"
# brief tutorial
print "Sample input data:"
print "FromIP: 192.168.1.50"
print "ToIP: 192.168.1.20"
print "---"
# input
fromIp = raw_input("From: ")
toIp = raw_input("To: ")
# enter values to class
userRange = checkIfUp(fromIp,toIp)
# read class values
print ""
#print userRange.readValue() # debugging use only
print "Checked",userRange.checkedIps,"IPs"
print ""
print "Online:",str(userRange.onlineIps)+"/"+str(userRange.checkedIps)
print "Unreachable:",userRange.unreachable,"Timed out:",userRange.timedOut
print "" # newline
print "Online IPs:"
print "IP\t\tNAME\t\tMAC"
counter = 0
for onlineIp in userRange.upIpsAddress:
print onlineIp+"\t"+userRange.computerName[counter]+"\t"+userRange.completeMacAddress[counter]
counter += 1
print ""
print "Took",userRange.executionTime,"seconds" | mixedup4x4/Speedy | Contents/LanScan.py | Python | gpl-3.0 | 7,956 |
/*
* AJDebug.java
*
* This file is part of Tritonus: http://www.tritonus.org/
*/
/*
* Copyright (c) 1999 - 2002 by Matthias Pfisterer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
package org.tritonus.debug;
import org.aspectj.lang.JoinPoint;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import org.tritonus.core.TMidiConfig;
import org.tritonus.core.TInit;
import org.tritonus.share.TDebug;
import org.tritonus.share.midi.TSequencer;
import org.tritonus.midi.device.alsa.AlsaSequencer;
import org.tritonus.midi.device.alsa.AlsaSequencer.PlaybackAlsaMidiInListener;
import org.tritonus.midi.device.alsa.AlsaSequencer.RecordingAlsaMidiInListener;
import org.tritonus.midi.device.alsa.AlsaSequencer.AlsaSequencerReceiver;
import org.tritonus.midi.device.alsa.AlsaSequencer.AlsaSequencerTransmitter;
import org.tritonus.midi.device.alsa.AlsaSequencer.LoaderThread;
import org.tritonus.midi.device.alsa.AlsaSequencer.MasterSynchronizer;
import org.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream;
/** Debugging output aspect.
*/
public aspect AJDebug
extends Utils
{
pointcut allExceptions(): handler(Throwable+);
// TAudioConfig, TMidiConfig, TInit
pointcut TMidiConfigCalls(): execution(* TMidiConfig.*(..));
pointcut TInitCalls(): execution(* TInit.*(..));
// share
// midi
pointcut MidiSystemCalls(): execution(* MidiSystem.*(..));
pointcut Sequencer(): execution(TSequencer+.new(..)) ||
execution(* TSequencer+.*(..)) ||
execution(* PlaybackAlsaMidiInListener.*(..)) ||
execution(* RecordingAlsaMidiInListener.*(..)) ||
execution(* AlsaSequencerReceiver.*(..)) ||
execution(* AlsaSequencerTransmitter.*(..)) ||
execution(LoaderThread.new(..)) ||
execution(* LoaderThread.*(..)) ||
execution(MasterSynchronizer.new(..)) ||
execution(* MasterSynchronizer.*(..));
// audio
pointcut AudioSystemCalls(): execution(* AudioSystem.*(..));
pointcut sourceDataLine():
call(* SourceDataLine+.*(..));
// OLD
// pointcut playerStates():
// execution(private void TPlayer.setState(int));
// currently not used
pointcut printVelocity(): execution(* JavaSoundToneGenerator.playTone(..)) && call(JavaSoundToneGenerator.ToneThread.new(..));
// pointcut tracedCall(): execution(protected void JavaSoundAudioPlayer.doRealize() throws Exception);
///////////////////////////////////////////////////////
//
// ACTIONS
//
///////////////////////////////////////////////////////
before(): MidiSystemCalls()
{
if (TDebug.TraceMidiSystem) outEnteringJoinPoint(thisJoinPoint);
}
after(): MidiSystemCalls()
{
if (TDebug.TraceSequencer) outLeavingJoinPoint(thisJoinPoint);
}
before(): Sequencer()
{
if (TDebug.TraceSequencer) outEnteringJoinPoint(thisJoinPoint);
}
after(): Sequencer()
{
if (TDebug.TraceSequencer) outLeavingJoinPoint(thisJoinPoint);
}
before(): TInitCalls()
{
if (TDebug.TraceInit) outEnteringJoinPoint(thisJoinPoint);
}
after(): TInitCalls()
{
if (TDebug.TraceInit) outLeavingJoinPoint(thisJoinPoint);
}
before(): TMidiConfigCalls()
{
if (TDebug.TraceMidiConfig) outEnteringJoinPoint(thisJoinPoint);
}
after(): TMidiConfigCalls()
{
if (TDebug.TraceMidiConfig) outLeavingJoinPoint(thisJoinPoint);
}
// execution(* TAsynchronousFilteredAudioInputStream.read(..))
before(): execution(* TAsynchronousFilteredAudioInputStream.read())
{
if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint);
}
after(): execution(* TAsynchronousFilteredAudioInputStream.read())
{
if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint);
}
before(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[]))
{
if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint);
}
after(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[]))
{
if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint);
}
before(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int))
{
if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint);
}
after(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int))
{
if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint);
}
after() returning(int nBytes): call(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int))
{
if (TDebug.TraceAudioConverter) TDebug.out("returning bytes: " + nBytes);
}
// before(int nState): playerStates() && args(nState)
// {
// // if (TDebug.TracePlayerStates)
// // {
// // TDebug.out("TPlayer.setState(): " + nState);
// // }
// }
// before(): playerStateTransitions()
// {
// // if (TDebug.TracePlayerStateTransitions)
// // {
// // TDebug.out("Entering: " + thisJoinPoint);
// // }
// }
// Synthesizer around(): call(* MidiSystem.getSynthesizer())
// {
// // Synthesizer s = proceed();
// // if (TDebug.TraceToneGenerator)
// // {
// // TDebug.out("MidiSystem.getSynthesizer() gives: " + s);
// // }
// // return s;
// // only to get no compilation errors
// return null;
// }
// TODO: v gives an error; find out what to do
// before(int v): printVelocity() && args(nVelocity)
// {
// if (TDebug.TraceToneGenerator)
// {
// TDebug.out("velocity: " + v);
// }
// }
before(Throwable t): allExceptions() && args(t)
{
if (TDebug.TraceAllExceptions) TDebug.out(t);
}
}
/*** AJDebug.java ***/
| srnsw/xena | plugins/audio/ext/src/tritonus/src/classes/org/tritonus/debug/AJDebug.java | Java | gpl-3.0 | 6,383 |
# Game
class GameResult < ActiveRecord::Base
attr_accessible :question, :question_id, :user, :issues, :answer, :same, :skip
belongs_to :user
belongs_to :question
has_and_belongs_to_many :issues, :join_table => "game_results_issues", :autosave => true
after_initialize :default_values
private
def default_values
self.skip = false if (self.has_attribute? :skip) && self.skip.nil?
self.same = false if (self.has_attribute? :same) && self.same.nil?
end
def self.pick_result(uId)
@game_result = GameResult.new
question_randomizing_prob = 0.70
problem_randomizing_prob = 0.70
epsilon = 0.00000001
played_games = GameResult.select{|g| g.user_id == uId && g.skip == false}
#played_games = GameResult.select{|g| g.user_id == uId && g.skip == false}
if rand() < question_randomizing_prob && played_games != nil
question_list = Question.all.map{|q| q.id}
next_question_id = question_list.sort_by{|q| played_games.select{|g| g.question_id == q}.count}.first
else
question_list = Question.all.map{|q| q.id}
next_question_id = question_list[rand(question_list.size)]
end
# TODO: This needs to be modified at some point to not only ask a single question excessively/heavily when a new one is added to the mix
@game_result.question = Question.offset(next_question_id-1).first
game_info_for_single_question = played_games.select{|pg| pg.question_id == next_question_id}
problem_pairs = game_info_for_single_question.map{|pg| pg.issue_ids.sort}.uniq.sort
game_results_with_flags = FlaggedIssues.select{|f| f.issue_id > 0}
remove_flags = []
game_results_with_flags.select{|grwf| GameResult.find{|g| g.user_id == uId && g.id == grwf.game_result_id }}.each do |gr|
remove_flags << gr.issue_id
end
remove_same = played_games.select{|g| g.same }.map{|q| q.issue_ids-[q.answer]}.flatten
#Probs is all of the problems that we could potentially ask the user
probs = Issue.all.map{|r| r.id} - remove_flags - remove_same
probs_focus = probs.sort_by{|p| -problem_pairs.flatten.count(p)}[0..14]
probs_left = probs - probs_focus
#TODO: FIX this code to accommodate more than 2 problems
choice = rand()+epsilon
if choice < problem_randomizing_prob || probs_left == [] || probs_left == nil
problem_choices = probs_focus.combination(2).to_a.map{|a| a.sort}-problem_pairs
if problem_choices == []
remove_same_flag_problems = probs_focus.combination(2).to_a.map{|a| a.sort}
next_issues = remove_same_flag_problems[rand(remove_same_flag_problems.length)]
else
next_issues = problem_choices[rand(problem_choices.length)]
end
else
problem_choices = probs_left.combination(2).to_a.map{|a| a.sort}-problem_pairs
if problem_choices == []
remove_same_flag_problems = probs_focus.combination(2).to_a.map{|a| a.sort}
next_issues = remove_same_flag_problems[rand(remove_same_flag_problems.length)]
else
next_issues = problem_choices[rand(problem_choices.length)]
end
end
#puts next_issues
a = next_issues[0]-1
b = next_issues[1]-1
if rand(2).to_i == 1
@game_result.issues << Issue.offset(a).first
@game_result.issues << Issue.offset(b).first
else
@game_result.issues << Issue.offset(b).first
@game_result.issues << Issue.offset(a).first
end
return @game_result
end
end
| causeroot/causeroot | app/models/game_result.rb | Ruby | gpl-3.0 | 3,463 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
* Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
********************************************************************************/
class SavedWorkflowsUtilTest extends WorkflowBaseTest
{
public $freeze = false;
public function setup()
{
parent::setUp();
$freeze = false;
if (RedBeanDatabase::isFrozen())
{
RedBeanDatabase::unfreeze();
$freeze = true;
}
$this->freeze = $freeze;
}
public function teardown()
{
if ($this->freeze)
{
RedBeanDatabase::freeze();
}
parent::teardown();
}
public function testResolveProcessDateTimeByWorkflowAndModel()
{
//Test Date
$model = new WorkflowModelTestItem();
$model->date = '2007-02-02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, 86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-02-03 00:00:00', $processDateTime);
//Test Date with negative duration
$model = new WorkflowModelTestItem();
$model->date = '2007-02-02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, -86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-02-01 00:00:00', $processDateTime);
//Test DateTime
$model = new WorkflowModelTestItem();
$model->dateTime = '2007-05-02 04:00:02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, 86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-05-03 04:00:02', $processDateTime);
//Test DateTime with negative duration
$model = new WorkflowModelTestItem();
$model->dateTime = '2007-05-02 04:00:02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, -86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-05-01 04:00:02', $processDateTime);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModel
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithNullDate()
{
$model = new WorkflowModelTestItem();
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithNullDate
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDate()
{
$model = new WorkflowModelTestItem();
$model->dateTime = '0000-00-00';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDate
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithNullDateTime()
{
$model = new WorkflowModelTestItem();
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithNullDateTime
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDateTime()
{
$model = new WorkflowModelTestItem();
$model->dateTime = '0000-00-00 00:00:00';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDateTime
*/
public function testResolveOrder()
{
$this->assertCount(0, SavedWorkflow::getAll());
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(1, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId1 = $savedWorkflow->id;
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 2';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data 2'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(2, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId2 = $savedWorkflow->id;
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 3';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data 2'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(3, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId3 = $savedWorkflow->id;
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 4';
$savedWorkflow->moduleClassName = 'ContactsModule';
$savedWorkflow->serializedData = serialize(array('some data'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(1, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId4 = $savedWorkflow->id;
$savedWorkflow = SavedWorkflow::getById($savedWorkflowId2);
$this->assertEquals(2, $savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(2, $savedWorkflow->order);
//Change the moduleClassName to opportunities, it should show 1
$savedWorkflow->moduleClassName = 'OpportunitiesModule';
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(1, $savedWorkflow->order);
//Delete the workflow. When creating a new AccountsWorkflow, it should show order 4 since the max
//is still 3.
$deleted = $savedWorkflow->delete();
$this->assertTrue($deleted);
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 5';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data 2'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(4, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
}
/**
* @depends testResolveOrder
*/
public function testResolveBeforeSaveByModel()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_ON_SAVE);
$workflow->setTriggersStructure('1');
//Add trigger
$trigger = new TriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'string';
$trigger->value = 'aValue';
$trigger->operator = 'equals';
$workflow->addTrigger($trigger);
//Add action
$action = new ActionForWorkflowForm('WorkflowModelTestItem', Workflow::TYPE_ON_SAVE);
$action->type = ActionForWorkflowForm::TYPE_UPDATE_SELF;
$attributes = array('string' => array('shouldSetValue' => '1',
'type' => WorkflowActionAttributeForm::TYPE_STATIC,
'value' => 'jason'));
$action->setAttributes(array(ActionForWorkflowForm::ACTION_ATTRIBUTES => $attributes));
$workflow->addAction($action);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
//Confirm that the workflow processes and the attribute gets updated
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
SavedWorkflowsUtil::resolveBeforeSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals('jason', $model->string);
$this->assertTrue($model->id < 0);
//Change the workflow to inactive
$savedWorkflow->isActive = false;
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
SavedWorkflowsUtil::resolveBeforeSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals('aValue', $model->string);
$this->assertTrue($model->id < 0);
}
/**
* @depends testResolveBeforeSaveByModel
*/
public function testResolveBeforeSaveByModelForByTime()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_BY_TIME);
$workflow->setTriggersStructure('1');
$workflow->setIsActive(true);
//Add time trigger
$trigger = new TimeTriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'date';
$trigger->durationSeconds = '500';
$trigger->valueType = 'Is Time For';
$workflow->setTimeTrigger($trigger);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
//Confirm that the workflow processes and the attribute gets updated
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
$model->date = '2013-02-02';
$this->assertEquals(0, count($model->getWorkflowsToProcessAfterSave()));
SavedWorkflowsUtil::resolveBeforeSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals(1, count($model->getWorkflowsToProcessAfterSave()));
$this->assertTrue($model->id < 0);
}
/**
* @depends testResolveBeforeSaveByModelForByTime
*/
public function testResolveAfterSaveByModel()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_ON_SAVE);
$workflow->setTriggersStructure('1');
$workflow->setIsActive(true);
//Add trigger
$trigger = new TriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'string';
$trigger->value = 'aValue';
$trigger->operator = 'equals';
$workflow->addTrigger($trigger);
//Add action
$action = new ActionForWorkflowForm('WorkflowModelTestItem', Workflow::TYPE_ON_SAVE);
$action->type = ActionForWorkflowForm::TYPE_CREATE;
$action->relation = 'hasOne';
$attributes = array('name' => array('shouldSetValue' => '1',
'type' => WorkflowActionAttributeForm::TYPE_STATIC,
'value' => 'jason'));
$action->setAttributes(array(ActionForWorkflowForm::ACTION_ATTRIBUTES => $attributes));
$workflow->addAction($action);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$model->addWorkflowToProcessAfterSave($workflow);
$this->assertEquals(0, count(WorkflowModelTestItem2::getAll()));
SavedWorkflowsUtil::resolveAfterSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals(1, count(WorkflowModelTestItem2::getAll()));
}
/**
* @depends testResolveAfterSaveByModel
*/
public function testResolveAfterSaveByModelForByTime()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_BY_TIME);
$workflow->setTriggersStructure('1');
$workflow->setIsActive(true);
//Add time trigger
$trigger = new TimeTriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'date';
$trigger->durationSeconds = '500';
$trigger->valueType = 'Is Time For';
$workflow->setTimeTrigger($trigger);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$workflow->setId($savedWorkflow->id); //set Id back.
$model = new WorkflowModelTestItem();
$model->lastName = 'something';
$model->string = 'aValue';
$model->date = '2013-03-03';
$saved = $model->save();
$this->assertTrue($saved);
$model->addWorkflowToProcessAfterSave($workflow);
$this->assertEquals(0, count(ByTimeWorkflowInQueue::getAll()));
SavedWorkflowsUtil::resolveAfterSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals(1, count(ByTimeWorkflowInQueue::getAll()));
}
}
?> | deep9/zurmo | app/protected/modules/workflows/tests/unit/SavedWorkflowsUtilTest.php | PHP | gpl-3.0 | 20,437 |
////////////////////////////////////////////////////////////////////////////
// Atol file manager project <http://atol.sf.net>
//
// This code is licensed under BSD license.See "license.txt" for more details.
//
// File: TOFIX
////////////////////////////////////////////////////////////////////////////
/*
* console.c: various interactive-prompt routines shared between
* the console PuTTY tools
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "putty.h"
#include "storage.h"
#include "ssh.h"
int console_batch_mode = FALSE;
/*
* Clean up and exit.
*/
void cleanup_exit(int code)
{
/*
* Clean up.
*/
//TOFIX
//sk_cleanup();
//WSACleanup();
if (cfg.protocol == PROT_SSH) {
random_save_seed();
#ifdef MSCRYPTOAPI
crypto_wrapup();
#endif
}
//exit(code);
}
void verify_ssh_host_key(CSshSession &session, char *host, int port, char *keytype, char *keystr, char *fingerprint)
{
int ret, choice = 0;
//HANDLE hin;
//DWORD savemode, i;
static const char absentmsg_batch[] =
"The server's host key is not cached in the registry. You\n"
"have no guarantee that the server is the computer you\n"
"think it is.\n"
"The server's key fingerprint is:\n"
"%s\n"
"Connection abandoned.\n";
static const char absentmsg[] =
"The server's host key is not cached in the registry. You\n"
"have no guarantee that the server is the computer you\n"
"think it is.\n"
"The server's key fingerprint is:\n"
"%s\n"
"If you trust this host, press \"Yes\" to add the key to\n"
"PuTTY's cache and carry on connecting.\n"
"If you want to carry on connecting just once, without\n"
"adding the key to the cache, press \"No\".\n"
"If you do not trust this host, press \"Cancel\" to abandon the\n"
"connection.\n"
"Store key in cache? (y/n) ";
static const char wrongmsg_batch[] =
"WARNING - POTENTIAL SECURITY BREACH!\n"
"The server's host key does not match the one PuTTY has\n"
"cached in the registry. This means that either the\n"
"server administrator has changed the host key, or you\n"
"have actually connected to another computer pretending\n"
"to be the server.\n"
"The new key fingerprint is:\n"
"%s\n"
"Connection abandoned.\n";
static const char wrongmsg[] =
"WARNING - POTENTIAL SECURITY BREACH!\n"
"The server's host key does not match the one PuTTY has\n"
"cached in the registry. This means that either the\n"
"server administrator has changed the host key, or you\n"
"have actually connected to another computer pretending\n"
"to be the server.\n"
"The new key fingerprint is:\n"
"%s\n"
"If you were expecting this change and trust the new key,\n"
"press \"Yes\" to update Atol cache and continue connecting.\n"
"If you want to carry on connecting but without updating\n"
"the cache, press \"No\".\n"
"If you want to abandon the connection completely, press\n"
"\"Cancel\". Pressing \"Cancel\" is the ONLY guaranteed\n"
"safe choice.\n"
"Update cached key? (y/n, \"Cancel\" cancels connection) ";
static const char abandoned[] = "Connection abandoned.\n";
// char line[32];
/*
* Verify the key against the registry.
*/
ret = verify_host_key(host, port, keytype, keystr);
if (ret == 0) /* success - key matched OK */
return;
char szBuffer[512];
if (ret == 2) { /* key was different */
if (console_batch_mode) {
//TOFIX fprintf(stderr, wrongmsg_batch, fingerprint);
sprintf(szBuffer, wrongmsg_batch, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, wrongmsg, fingerprint);
//TOFIX fflush(stderr);
sprintf(szBuffer, wrongmsg, fingerprint);
if(session.m_fnKeyWarning)
choice = session.m_fnKeyWarning(szBuffer, 1, session.m_fnKeyData);
}
if (ret == 1) { /* key was absent */
if (console_batch_mode) {
//TOFIX fprintf(stderr, absentmsg_batch, fingerprint);
sprintf(szBuffer, absentmsg_batch, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, absentmsg, fingerprint);
//TOFIX fflush(stderr);
sprintf(szBuffer, absentmsg, fingerprint);
if(session.m_fnKeyWarning)
choice = session.m_fnKeyWarning(szBuffer, 1, session.m_fnKeyData);
}
//hin = GetStdHandle(STD_INPUT_HANDLE);
//if(hin)
{
//GetConsoleMode(hin, &savemode);
//SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
// ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
//ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
//SetConsoleMode(hin, savemode);
//if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
if(choice > 0){
//if (line[0] == 'y' || line[0] == 'Y')
if(1 == choice)
store_host_key(host, port, keytype, keystr);
} else {
//TOFIX fprintf(stderr, abandoned);
sprintf(szBuffer, abandoned, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(0);
}
}
}
/*
* Ask whether the selected cipher is acceptable (since it was
* below the configured 'warn' threshold).
* cs: 0 = both ways, 1 = client->server, 2 = server->client
*/
void askcipher(char *ciphername, int cs)
{
HANDLE hin;
DWORD savemode, i;
static const char msg[] =
"The first %scipher supported by the server is\n"
"%s, which is below the configured warning threshold.\n"
"Continue with connection? (y/n) ";
static const char msg_batch[] =
"The first %scipher supported by the server is\n"
"%s, which is below the configured warning threshold.\n"
"Connection abandoned.\n";
static const char abandoned[] = "Connection abandoned.\n";
char line[32];
if (console_batch_mode) {
//TOFIX fprintf(stderr, msg_batch,
//TOFIX (cs == 0) ? "" :
//TOFIX (cs == 1) ? "client-to-server " : "server-to-client ",
//TOFIX ciphername);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, msg,
//TOFIX (cs == 0) ? "" :
//TOFIX (cs == 1) ? "client-to-server " : "server-to-client ",
//TOFIX ciphername);
//fflush(stderr);
hin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hin, &savemode);
SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if (line[0] == 'y' || line[0] == 'Y') {
return;
} else {
//TOFIX fprintf(stderr, abandoned);
cleanup_exit(0);
}
}
/*
* Ask whether to wipe a session log file before writing to it.
* Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
*/
int askappend(char *filename)
{
HANDLE hin;
DWORD savemode, i;
static const char msgtemplate[] =
"The session log file \"%.*s\" already exists.\n"
"You can overwrite it with a new session log,\n"
"append your session log to the end of it,\n"
"or disable session logging for this session.\n"
"Enter \"y\" to wipe the file, \"n\" to append to it,\n"
"or just press Return to disable logging.\n"
"Wipe the log file? (y/n, Return cancels logging) ";
static const char msgtemplate_batch[] =
"The session log file \"%.*s\" already exists.\n"
"Logging will not be enabled.\n";
char line[32];
if (cfg.logxfovr != LGXF_ASK) {
return ((cfg.logxfovr == LGXF_OVR) ? 2 : 1);
}
if (console_batch_mode) {
//TOFIX fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename);
//TOFIX fflush(stderr);
return 0;
}
//TOFIX fprintf(stderr, msgtemplate, FILENAME_MAX, filename);
//fflush(stderr);
hin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hin, &savemode);
SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if (line[0] == 'y' || line[0] == 'Y')
return 2;
else if (line[0] == 'n' || line[0] == 'N')
return 1;
else
return 0;
}
/*
* Warn about the obsolescent key file format.
*/
void old_keyfile_warning(void)
{
static const char message[] =
"You are loading an SSH 2 private key which has an\n"
"old version of the file format. This means your key\n"
"file is not fully tamperproof. Future versions of\n"
"PuTTY may stop supporting this private key format,\n"
"so we recommend you convert your key to the new\n"
"format.\n"
"\n"
"Once the key is loaded into PuTTYgen, you can perform\n"
"this conversion simply by saving it again.\n";
fputs(message, stderr);
}
//TOFIX move to CSshSession
void logevent(CSshSession &session, char *string)
{
if(session.m_dbgFn)
session.m_dbgFn(string, session.m_dwDbgData);
}
char *console_password = NULL;
int console_get_line(const char *prompt, char *str,
int maxlen, int is_pw)
{
HANDLE hin, hout;
DWORD savemode, newmode, i;
if (is_pw && console_password) {
static int tried_once = 0;
if (tried_once) {
return 0;
} else {
strncpy(str, console_password, maxlen);
str[maxlen - 1] = '\0';
tried_once = 1;
return 1;
}
}
if (console_batch_mode) {
if (maxlen > 0)
str[0] = '\0';
} else {
hin = GetStdHandle(STD_INPUT_HANDLE);
hout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
//TOFIX fprintf(stderr, "Cannot get standard input/output handles\n");
cleanup_exit(1);
}
if (hin == NULL || hout == NULL)
return 1;
GetConsoleMode(hin, &savemode);
newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
if (is_pw)
newmode &= ~ENABLE_ECHO_INPUT;
else
newmode |= ENABLE_ECHO_INPUT;
SetConsoleMode(hin, newmode);
WriteFile(hout, prompt, strlen(prompt), &i, NULL);
ReadFile(hin, str, maxlen - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if ((int) i > maxlen)
i = maxlen - 1;
else
i = i - 2;
str[i] = '\0';
if (is_pw)
WriteFile(hout, "\r\n", 2, &i, NULL);
}
return 1;
}
| chriskmanx/qmole | QMOLEDEV/atol-0.7.3/src/core/_sftp/Console.cpp | C++ | gpl-3.0 | 10,402 |
/*
Copyright 2011-2014 Red Hat, Inc
This file is part of PressGang CCMS.
PressGang CCMS 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.
PressGang CCMS 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 PressGang CCMS. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jboss.pressgang.ccms.rest.v1.query;
import java.util.ArrayList;
import java.util.List;
import org.jboss.pressgang.ccms.rest.v1.constants.CommonFilterConstants;
import org.jboss.pressgang.ccms.rest.v1.query.base.RESTBaseQueryBuilderV1;
import org.jboss.pressgang.ccms.utils.structures.Pair;
public class RESTPropertyCategoryQueryBuilderV1 extends RESTBaseQueryBuilderV1 {
private static List<Pair<String, String>> filterPairs = new ArrayList<Pair<String, String>>() {
private static final long serialVersionUID = -8638470044710698912L;
{
add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR,
CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR_DESC));
add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR,
CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR_DESC));
add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR,
CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR_DESC));
}
};
public static List<Pair<String, String>> getFilterInfo() {
return filterPairs;
}
public static String getFilterDesc(final String varName) {
if (varName == null) return null;
final List<Pair<String, String>> filterInfo = getFilterInfo();
for (final Pair<String, String> varInfo : filterInfo) {
if (varInfo.getFirst().equals(varName)) {
return varInfo.getSecond();
}
}
return null;
}
public List<Integer> getPropertyCategoryIds() {
final String propertyCategoryIdsString = get(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR);
return getIntegerList(propertyCategoryIdsString);
}
public void setPropertyCategoryIds(final List<Integer> propertyCategoryIds) {
put(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR, propertyCategoryIds);
}
public String getPropertyCategoryName() {
return get(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR);
}
public void setPropertyCategoryName(final String propertyCategoryName) {
put(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR, propertyCategoryName);
}
public String getPropertyCategoryDescription() {
return get(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR);
}
public void setPropertyCategoryDescription(final String propertyCategoryDescription) {
put(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR, propertyCategoryDescription);
}
} | pressgang-ccms/PressGangCCMSRESTv1Common | src/main/java/org/jboss/pressgang/ccms/rest/v1/query/RESTPropertyCategoryQueryBuilderV1.java | Java | gpl-3.0 | 3,394 |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition 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.
*
* OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @package core
* @copyright (C) OXID eSales AG 2003-2013
* @version OXID eShop CE
* @version SVN: $Id: oxnews.php 48786 2012-08-17 10:20:42Z tomas $
*/
/**
* News manager.
* Performs news text collection. News may be sorted by user categories (only
* these user may read news), etc.
*
* @package model
*/
class oxNews extends oxI18n
{
/**
* User group object (default null).
*
* @var object
*/
protected $_oGroups = null;
/**
* Current class name
*
* @var string
*/
protected $_sClassName = 'oxnews';
/**
* Class constructor, initiates parent constructor (parent::oxI18n()).
*
* @return null
*/
public function __construct()
{
parent::__construct();
$this->init('oxnews');
}
/**
* Assigns object data.
*
* @param string $dbRecord database record to be assigned
*
* @return null
*/
public function assign( $dbRecord )
{
parent::assign( $dbRecord );
// convert date's to international format
if ($this->oxnews__oxdate) {
$this->oxnews__oxdate->setValue( oxRegistry::get("oxUtilsDate")->formatDBDate( $this->oxnews__oxdate->value ) );
}
}
/**
* Returns list of user groups assigned to current news object
*
* @return oxlist
*/
public function getGroups()
{
if ( $this->_oGroups == null && $sOxid = $this->getId() ) {
// usergroups
$this->_oGroups = oxNew( 'oxlist', 'oxgroups' );
$sViewName = getViewName( "oxgroups", $this->getLanguage() );
$sSelect = "select {$sViewName}.* from {$sViewName}, oxobject2group ";
$sSelect .= "where oxobject2group.oxobjectid='$sOxid' ";
$sSelect .= "and oxobject2group.oxgroupsid={$sViewName}.oxid ";
$this->_oGroups->selectString( $sSelect );
}
return $this->_oGroups;
}
/**
* Checks if this object is in group, returns true on success.
*
* @param string $sGroupID user group ID
*
* @return bool
*/
public function inGroup( $sGroupID )
{
$blResult = false;
$aGroups = $this->getGroups();
foreach ( $aGroups as $oObject ) {
if ( $oObject->_sOXID == $sGroupID ) {
$blResult = true;
break;
}
}
return $blResult;
}
/**
* Deletes object information from DB, returns true on success.
*
* @param string $sOxid Object ID (default null)
*
* @return bool
*/
public function delete( $sOxid = null )
{
if ( !$sOxid ) {
$sOxid = $this->getId();
}
if ( !$sOxid ) {
return false;
}
if ( $blDelete = parent::delete( $sOxid ) ) {
$oDb = oxDb::getDb();
$oDb->execute( "delete from oxobject2group where oxobject2group.oxobjectid = ".$oDb->quote( $sOxid ) );
}
return $blDelete;
}
/**
* Updates object information in DB.
*
* @return null
*/
protected function _update()
{
$this->oxnews__oxdate->setValue( oxRegistry::get("oxUtilsDate")->formatDBDate( $this->oxnews__oxdate->value, true ) );
parent::_update();
}
/**
* Inserts object details to DB, returns true on success.
*
* @return bool
*/
protected function _insert()
{
if ( !$this->oxnews__oxdate || oxRegistry::get("oxUtilsDate")->isEmptyDate( $this->oxnews__oxdate->value ) ) {
// if date field is empty, assigning current date
$this->oxnews__oxdate = new oxField( date( 'Y-m-d' ) );
} else {
$this->oxnews__oxdate = new oxField( oxRegistry::get("oxUtilsDate")->formatDBDate( $this->oxnews__oxdate->value, true ) );
}
return parent::_insert();
}
/**
* Sets data field value
*
* @param string $sFieldName index OR name (eg. 'oxarticles__oxtitle') of a data field to set
* @param string $sValue value of data field
* @param int $iDataType field type
*
* @return null
*/
protected function _setFieldData( $sFieldName, $sValue, $iDataType = oxField::T_TEXT)
{
switch (strtolower($sFieldName)) {
case 'oxlongdesc':
case 'oxnews__oxlongdesc':
$iDataType = oxField::T_RAW;
break;
}
return parent::_setFieldData($sFieldName, $sValue, $iDataType);
}
/**
* get long description, parsed through smarty
*
* @return string
*/
public function getLongDesc()
{
return oxRegistry::get("oxUtilsView")->parseThroughSmarty( $this->oxnews__oxlongdesc->getRawValue(), $this->getId().$this->getLanguage() );
}
}
| NikolayPetrenko/oxid | application/models/oxnews.php | PHP | gpl-3.0 | 5,714 |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'del_from_mail_list'=>'Izbriši sa newsletter liste',
'del_key'=>'Kod za brisanje',
'delete'=>'Izbriši',
'deletion_key'=>'Kod za brisanje',
'email_not_valid'=>'Vaš e-mail nije ispravno upisan!',
'lost_deletion_key'=>'Izgubili ste kod za brisanje?',
'mail_adress'=>'E-mail adresa',
'mail_pw_didnt_match'=>'E-mail/lozinka se ne podudaraju.',
'mail_not_in_db'=>'Upisana e-mail adresa ne postoji u našoj bazi.',
'newsletter'=>'newsletter',
'newsletter_registration'=>'Registracija za newsletter',
'no_such_mail_adress'=>'Ne postoji takva e-mail adresa.',
'password_had_been_send'=>'Lozinka je poslana.',
'register_newsletter'=>'Registriraj se za newsletter',
'request_mail'=>'<b>Treba Vam vaš kod za brisanje!</b><br /><br />Da bi maknuli Vaš e-mail sa liste mailova za newsletter kliknite <a href="http://%homepage_url%/index.php?site=newsletter&mail=%mail%&pass=%delete_key%">ovdje</a><br />Vaša lozinka za brisanje s liste: %delete_key%<br /><br />Vidimo se na %homepage_url%',
'send'=>'Pošalji',
'submit'=>'Spremi',
'success_mail'=>'<b>Hvala Vam na registraciji!</b><br /><br />Da bi maknuli Vaš e-mail sa liste mailova za newsletter kliknite <a href="http://%homepage_url%/index.php?site=newsletter&mail=%mail%&pass=%delete_key%">ovdje</a><br />Vaša lozinka za brisanje s liste: %delete_key%<br /><br />Vidimo se na %homepage_url%',
'thank_you_for_registration'=>'Hvala Vam na registraciji.',
'you_are_already_registered'=>'Već ste registrirani.',
'your_mail_adress'=>'Vaš e-mail',
'your_mail_adress_deleted'=>'Vaš e-mail je maknut s liste.'
);
?> | webSPELL/webSPELL | languages/hr/newsletter.php | PHP | gpl-3.0 | 3,435 |
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* 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.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
package com.iver.cit.gvsig.fmap.layers;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PrintQuality;
import org.apache.log4j.Logger;
import org.cresques.cts.ICoordTrans;
import org.gvsig.tools.file.PathGenerator;
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
import com.hardcode.gdbms.engine.data.DataSourceFactory;
import com.hardcode.gdbms.engine.data.NoSuchTableException;
import com.hardcode.gdbms.engine.data.driver.DriverException;
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
import com.iver.cit.gvsig.exceptions.layers.ReprojectLayerException;
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
import com.iver.cit.gvsig.fmap.MapContext;
import com.iver.cit.gvsig.fmap.MapControl;
import com.iver.cit.gvsig.fmap.ViewPort;
import com.iver.cit.gvsig.fmap.core.CartographicSupport;
import com.iver.cit.gvsig.fmap.core.FPoint2D;
import com.iver.cit.gvsig.fmap.core.FShape;
import com.iver.cit.gvsig.fmap.core.IFeature;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.core.ILabelable;
import com.iver.cit.gvsig.fmap.core.IRow;
import com.iver.cit.gvsig.fmap.core.symbols.IMultiLayerSymbol;
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
import com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol;
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
import com.iver.cit.gvsig.fmap.drivers.featureiterators.JoinFeatureIterator;
import com.iver.cit.gvsig.fmap.edition.AfterFieldEditEvent;
import com.iver.cit.gvsig.fmap.edition.AfterRowEditEvent;
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
import com.iver.cit.gvsig.fmap.edition.BeforeFieldEditEvent;
import com.iver.cit.gvsig.fmap.edition.BeforeRowEditEvent;
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
import com.iver.cit.gvsig.fmap.edition.IEditionListener;
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
import com.iver.cit.gvsig.fmap.edition.IWriteable;
import com.iver.cit.gvsig.fmap.edition.IWriter;
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
import com.iver.cit.gvsig.fmap.edition.VectorialEditableDBAdapter;
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
import com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData;
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData;
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialXMLItem;
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
import com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor;
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
import com.iver.cit.gvsig.fmap.rendering.IClassifiedVectorLegend;
import com.iver.cit.gvsig.fmap.rendering.ILegend;
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
import com.iver.cit.gvsig.fmap.rendering.LegendClearEvent;
import com.iver.cit.gvsig.fmap.rendering.LegendContentsChangedListener;
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
import com.iver.cit.gvsig.fmap.rendering.SymbolLegendEvent;
import com.iver.cit.gvsig.fmap.rendering.ZSort;
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.AttrInTableLabelingStrategy;
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.ILabelingStrategy;
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.LabelingFactory;
import com.iver.cit.gvsig.fmap.spatialindex.IPersistentSpatialIndex;
import com.iver.cit.gvsig.fmap.spatialindex.ISpatialIndex;
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeGt2;
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
import com.iver.cit.gvsig.fmap.spatialindex.SpatialIndexException;
import com.iver.utiles.FileUtils;
import com.iver.utiles.IPersistence;
import com.iver.utiles.NotExistInXMLEntity;
import com.iver.utiles.PostProcessSupport;
import com.iver.utiles.XMLEntity;
import com.iver.utiles.swing.threads.Cancellable;
import com.iver.utiles.swing.threads.CancellableMonitorable;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.TopologyException;
/**
* Capa básica Vectorial.
*
* @author Fernando González Cortés
*/
public class FLyrVect extends FLyrDefault implements ILabelable,
ClassifiableVectorial, SingleLayer, VectorialData, RandomVectorialData,
AlphanumericData, InfoByPoint, SelectionListener, IEditionListener, LegendContentsChangedListener {
private static Logger logger = Logger.getLogger(FLyrVect.class.getName());
/** Leyenda de la capa vectorial */
private IVectorLegend legend;
private int typeShape = -1;
private ReadableVectorial source;
private SelectableDataSource sds;
private SpatialCache spatialCache = new SpatialCache();
private boolean spatialCacheEnabled = false;
/**
* An implementation of gvSIG spatial index
*/
protected ISpatialIndex spatialIndex = null;
private boolean bHasJoin = false;
private XMLEntity orgXMLEntity = null;
private XMLEntity loadSelection = null;
private IVectorLegend loadLegend = null;
//Lo añado. Características de HyperEnlace (LINK)
private FLyrVectLinkProperties linkProperties=new FLyrVectLinkProperties();
//private ArrayList linkProperties=null;
private boolean waitTodraw=false;
private static PathGenerator pathGenerator=PathGenerator.getInstance();
public boolean isWaitTodraw() {
return waitTodraw;
}
public void setWaitTodraw(boolean waitTodraw) {
this.waitTodraw = waitTodraw;
}
/**
* Devuelve el VectorialAdapater de la capa.
*
* @return VectorialAdapter.
*/
public ReadableVectorial getSource() {
if (!this.isAvailable()) return null;
return source;
}
/**
* If we use a persistent spatial index associated with this layer, and the
* index is not intrisic to the layer (for example spatial databases) this
* method looks for existent spatial index, and loads it.
*
*/
private void loadSpatialIndex() {
//FIXME: Al abrir el indice en fichero...
//¿Cómo lo liberamos? un metodo Layer.shutdown()
ReadableVectorial source = getSource();
//REVISAR QUE PASA CON LOS DRIVERS DXF, DGN, etc.
//PUES SON VECTORIALFILEADAPTER
if (!(source instanceof VectorialFileAdapter)) {
// we are not interested in db adapters
return;
}
VectorialDriver driver = source.getDriver();
if (!(driver instanceof BoundedShapes)) {
// we dont spatially index layers that are not bounded
return;
}
File file = ((VectorialFileAdapter) source).getFile();
String fileName = file.getAbsolutePath();
File sptFile = new File(fileName + ".qix");
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
// before to exit, look for it in temp path
String tempPath = System.getProperty("java.io.tmpdir");
fileName = tempPath + File.separator + sptFile.getName();
sptFile = new File(fileName);
// it doesnt exists, must to create
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
return;
}// if
}// if
try {
source.start();
spatialIndex = new QuadtreeGt2(FileUtils.getFileWithoutExtension(sptFile),
"NM", source.getFullExtent(), source.getShapeCount(), false);
source.setSpatialIndex(spatialIndex);
} catch (SpatialIndexException e) {
spatialIndex = null;
e.printStackTrace();
return;
} catch (ReadDriverException e) {
spatialIndex = null;
e.printStackTrace();
return;
}
}
/**
* Checks if it has associated an external spatial index
* (an spatial index file).
*
* It looks for it in main file path, or in temp system path.
* If main file is rivers.shp, it looks for a file called
* rivers.shp.qix.
* @return
*/
public boolean isExternallySpatiallyIndexed() {
/*
* FIXME (AZABALA): Independizar del tipo de fichero de índice
* con el que se trabaje (ahora mismo considera la extension .qix,
* pero esto dependerá del tipo de índice)
* */
ReadableVectorial source = getSource();
if (!(source instanceof VectorialFileAdapter)) {
// we are not interested in db adapters.
// think in non spatial dbs, like HSQLDB
return false;
}
File file = ((VectorialFileAdapter) source).getFile();
String fileName = file.getAbsolutePath();
File sptFile = new File(fileName + ".qix");
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
// before to exit, look for it in temp path
// it doesnt exists, must to create
String tempPath = System.getProperty("java.io.tmpdir");
fileName = tempPath + File.separator + sptFile.getName();
sptFile = new File(fileName);
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
return false;
}// if
}// if
return true;
}
/**
* Inserta el VectorialAdapter a la capa.
*
* @param va
* VectorialAdapter.
*/
public void setSource(ReadableVectorial rv) {
source = rv;
// azabala: we check if this layer could have a file spatial index
// and load it if it exists
loadSpatialIndex();
}
public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
Rectangle2D rAux;
source.start();
rAux = (Rectangle2D)source.getFullExtent().clone();
source.stop();
// Si existe reproyección, reproyectar el extent
if (!(this.getProjection()!=null &&
this.getMapContext().getProjection()!=null &&
this.getProjection().getAbrev().equals(this.getMapContext().getProjection().getAbrev()))){
ICoordTrans ct = getCoordTrans();
try{
if (ct != null) {
Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
pt1 = ct.convert(pt1, null);
pt2 = ct.convert(pt2, null);
rAux = new Rectangle2D.Double();
rAux.setFrameFromDiagonal(pt1, pt2);
}
}catch (IllegalStateException e) {
this.setAvailable(false);
this.addError(new ReprojectLayerException(getName(), e));
}
}
//Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
if (rAux.getWidth()==0 && rAux.getHeight()==0) {
rAux=new Rectangle2D.Double(0,0,100,100);
}
return rAux;
}
/**
* Draws using IFeatureIterator. This method will replace the old draw(...) one.
* @autor jaume dominguez faus - jaume.dominguez@iver.es
* @param image
* @param g
* @param viewPort
* @param cancel
* @param scale
* @throws ReadDriverException
*/
private void _draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale) throws ReadDriverException {
boolean bDrawShapes = true;
if (legend instanceof SingleSymbolLegend) {
bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
}
Point2D offset = viewPort.getOffset();
double dpi = MapContext.getScreenDPI();
if (bDrawShapes) {
boolean cacheFeatures = isSpatialCacheEnabled();
SpatialCache cache = null;
if (cacheFeatures) {
getSpatialCache().clearAll();
cache = getSpatialCache();
}
try {
ArrayList<String> fieldList = new ArrayList<String>();
// fields from legend
String[] aux = null;
if (legend instanceof IClassifiedVectorLegend) {
aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
if (aux!=null) {
for (int i = 0; i < aux.length; i++) {
// check fields exists
if (sds.getFieldIndexByName(aux[i]) == -1) {
logger.warn("Error en leyenda de " + getName() +
". El campo " + aux[i] + " no está.");
legend = LegendFactory.createSingleSymbolLegend(getShapeType());
break;
}
fieldList.add(aux[i]);
}
}
}
// Get the iterator over the visible features
IFeatureIterator it = null;
if (isJoined()) {
it = new JoinFeatureIterator(this, viewPort,
fieldList.toArray(new String[fieldList.size()]));
}
else {
ReadableVectorial rv=getSource();
// rv.start();
it = rv.getFeatureIterator(
viewPort.getAdjustedExtent(),
fieldList.toArray(new String[fieldList.size()]),
viewPort.getProjection(),
true);
// rv.stop();
}
ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
boolean bSymbolLevelError = false;
// if layer has map levels it will use a ZSort
boolean useZSort = zSort != null && zSort.isUsingZSort();
// -- visual FX stuff
long time = System.currentTimeMillis();
BufferedImage virtualBim;
Graphics2D virtualGraphics;
// render temporary map each screenRefreshRate milliseconds;
int screenRefreshDelay = (int) ((1D/MapControl.getDrawFrameRate())*3*1000);
BufferedImage[] imageLevels = null;
Graphics2D[] graphics = null;
if (useZSort) {
imageLevels = new BufferedImage[zSort.getLevelCount()];
graphics = new Graphics2D[imageLevels.length];
for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
imageLevels[i] = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
graphics[i] = imageLevels[i].createGraphics();
graphics[i].setTransform(g.getTransform());
graphics[i].setRenderingHints(g.getRenderingHints());
}
}
// -- end visual FX stuff
boolean isInMemory = false;
if (getSource().getDriverAttributes() != null){
isInMemory = getSource().getDriverAttributes().isLoadedInMemory();
}
SelectionSupport selectionSupport=getSelectionSupport();
// Iteration over each feature
while ( !cancel.isCanceled() && it.hasNext()) {
IFeature feat = it.next();
IGeometry geom = null;
if (isInMemory){
geom = feat.getGeometry().cloneGeometry();
}else{
geom = feat.getGeometry();
}
if (cacheFeatures) {
if (cache.getMaxFeatures() >= cache.size()) {
// already reprojected
cache.insert(geom.getBounds2D(), geom);
}
}
// retrieve the symbol associated to such feature
ISymbol sym = legend.getSymbolByFeature(feat);
if (sym == null) continue;
//Código para poder acceder a los índices para ver si está seleccionado un Feature
ReadableVectorial rv=getSource();
int selectionIndex=-1;
if (rv instanceof ISpatialDB){
selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat);
}else{
selectionIndex = Integer.parseInt(feat.getID());
}
if (selectionIndex!=-1) {
if (selectionSupport.isSelected(selectionIndex)) {
sym = sym.getSymbolForSelection();
}
}
// Check if this symbol is sized with CartographicSupport
CartographicSupport csSym = null;
int symbolType = sym.getSymbolType();
boolean bDrawCartographicSupport = false;
if ( symbolType == FShape.POINT
|| symbolType == FShape.LINE
|| sym instanceof CartographicSupport) {
// patch
if (!sym.getClass().equals(FSymbol.class)) {
csSym = (CartographicSupport) sym;
bDrawCartographicSupport = (csSym.getUnit() != -1);
}
}
int x = -1;
int y = -1;
int[] xyCoords = new int[2];
// Check if size is a pixel
boolean onePoint = bDrawCartographicSupport ?
isOnePoint(g.getTransform(), viewPort, MapContext.getScreenDPI(), csSym, geom, xyCoords) :
isOnePoint(g.getTransform(), viewPort, geom, xyCoords);
// Avoid out of bounds exceptions
if (onePoint) {
x = xyCoords[0];
y = xyCoords[1];
if (x<0 || y<0 || x>= viewPort.getImageWidth() || y>=viewPort.getImageHeight()) continue;
}
if (useZSort) {
// Check if this symbol is a multilayer
int[] symLevels = zSort.getLevels(sym);
if (sym instanceof IMultiLayerSymbol) {
// if so, treat each of its layers as a single symbol
// in its corresponding map level
IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
ISymbol mySym = mlSym.getLayer(i);
int symbolLevel = 0;
if (symLevels != null) {
symbolLevel = symLevels[i];
} else {
/* an error occured when managing symbol levels.
* some of the legend changed events regarding the
* symbols did not finish satisfactory and the legend
* is now inconsistent. For this drawing, it will finish
* as it was at the bottom (level 0) but, when done, the
* ZSort will be reset to avoid app crashes. This is
* a bug that has to be fixed.
*/
bSymbolLevelError = true;
}
if (onePoint) {
if (x<0 || y<0 || x>= imageLevels[symbolLevel].getWidth() || y>=imageLevels[symbolLevel].getHeight()) continue;
imageLevels[symbolLevel].setRGB(x, y, mySym.getOnePointRgb());
} else {
if (!bDrawCartographicSupport) {
geom.drawInts(graphics[symbolLevel], viewPort, mySym, cancel);
} else {
geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) mySym, cancel);
}
}
}
} else {
// else, just draw the symbol in its level
int symbolLevel = 0;
if (symLevels != null) {
symbolLevel=symLevels[0];
} else {
/* If symLevels == null
* an error occured when managing symbol levels.
* some of the legend changed events regarding the
* symbols did not finish satisfactory and the legend
* is now inconsistent. For this drawing, it will finish
* as it was at the bottom (level 0). This is
* a bug that has to be fixed.
*/
// bSymbolLevelError = true;
}
if (!bDrawCartographicSupport) {
geom.drawInts(graphics[symbolLevel], viewPort, sym, cancel);
} else {
geom.drawInts(graphics[symbolLevel], viewPort, dpi, csSym, cancel);
}
}
// -- visual FX stuff
// Cuando el offset!=0 se está dibujando sobre el Layout y por tanto no tiene que ejecutar el siguiente código.
if (offset.getX()==0 && offset.getY()==0)
if ((System.currentTimeMillis() - time) > screenRefreshDelay) {
virtualBim = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB);
virtualGraphics = virtualBim.createGraphics();
virtualGraphics.drawImage(image,0,0, null);
for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
virtualGraphics.drawImage(imageLevels[i],0,0, null);
}
g.clearRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(virtualBim, 0, 0, null);
time = System.currentTimeMillis();
}
// -- end visual FX stuff
} else {
// no ZSort, so there is only a map level, symbols are
// just drawn.
if (onePoint) {
if (x<0 || y<0 || x>= image.getWidth() || y>=image.getHeight()) continue;
image.setRGB(x, y, sym.getOnePointRgb());
} else {
if (!bDrawCartographicSupport) {
geom.drawInts(g, viewPort, sym, cancel);
} else {
geom.drawInts(g, viewPort, dpi, csSym,
cancel);
}
}
}
}
if (useZSort) {
g.drawImage(image, (int)offset.getX(), (int)offset.getY(), null);
g.translate(offset.getX(), offset.getY());
for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
g.drawImage(imageLevels[i],0,0, null);
imageLevels[i] = null;
graphics[i] = null;
}
g.translate(-offset.getX(), -offset.getY());
imageLevels = null;
graphics = null;
}
it.closeIterator();
if (bSymbolLevelError) {
((IVectorLegend) getLegend()).setZSort(null);
}
} catch (ReadDriverException e) {
this.setVisible(false);
this.setActive(false);
throw e;
}
}
}
public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale) throws ReadDriverException {
if (isWaitTodraw()) {
return;
}
if (getStrategy() != null) {
getStrategy().draw(image, g, viewPort, cancel);
}
else {
_draw(image, g, viewPort, cancel, scale);
}
}
public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
double scale, PrintRequestAttributeSet properties, boolean highlight) throws ReadDriverException {
boolean bDrawShapes = true;
boolean cutGeom = true;
if (legend instanceof SingleSymbolLegend) {
bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
}
if (bDrawShapes) {
try {
double dpi = 72;
PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
if (resolution.equals(PrintQuality.NORMAL)){
dpi = 300;
} else if (resolution.equals(PrintQuality.HIGH)){
dpi = 600;
} else if (resolution.equals(PrintQuality.DRAFT)){
dpi = 72;
}
ArrayList<String> fieldList = new ArrayList<String>();
String[] aux;
// fields from legend
if (legend instanceof IClassifiedVectorLegend) {
aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
for (int i = 0; i < aux.length; i++) {
fieldList.add(aux[i]);
}
}
//
// // fields from labeling
// if (isLabeled()) {
// aux = getLabelingStrategy().getUsedFields();
// for (int i = 0; i < aux.length; i++) {
// fieldList.add(aux[i]);
// }
// }
ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
// if layer has map levels it will use a ZSort
boolean useZSort = zSort != null && zSort.isUsingZSort();
int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
// Get the iterator over the visible features
// IFeatureIterator it = getSource().getFeatureIterator(
// viewPort.getAdjustedExtent(),
// fieldList.toArray(new String[fieldList.size()]),
// viewPort.getProjection(),
// true);
IFeatureIterator it = null;
if (isJoined()) {
it = new JoinFeatureIterator(this, viewPort,
fieldList.toArray(new String[fieldList.size()]));
}
else {
it = getSource().getFeatureIterator(
viewPort.getAdjustedExtent(),
fieldList.toArray(new String[fieldList.size()]),
viewPort.getProjection(),
true);
}
// Iteration over each feature
while ( !cancel.isCanceled() && it.hasNext()) {
IFeature feat = it.next();
IGeometry geom = feat.getGeometry();
// retreive the symbol associated to such feature
ISymbol sym = legend.getSymbolByFeature(feat);
if (sym == null) {
continue;
}
SelectionSupport selectionSupport=getSelectionSupport();
if (highlight) {
//Código para poder acceder a los índices para ver si está seleccionado un Feature
ReadableVectorial rv=getSource();
int selectionIndex=-1;
if (rv instanceof ISpatialDB){
selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat);
} else {
selectionIndex = Integer.parseInt(feat.getID());
}
if (selectionIndex!=-1) {
if (selectionSupport.isSelected(selectionIndex)) {
sym = sym.getSymbolForSelection();
}
}
}
if (useZSort) {
int[] symLevels = zSort.getLevels(sym);
if(symLevels != null){
// Check if this symbol is a multilayer
if (sym instanceof IMultiLayerSymbol) {
// if so, get the layer corresponding to the current
// level. If none, continue to next iteration
IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
for (int i = 0; i < mlSym.getLayerCount(); i++) {
ISymbol mySym = mlSym.getLayer(i);
if (symLevels[i] == mapPass) {
sym = mySym;
break;
}
System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
}
} else {
// else, just draw the symbol in its level
if (symLevels[0] != mapPass) {
System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
continue;
}
}
}
}
// Check if this symbol is sized with CartographicSupport
CartographicSupport csSym = null;
int symbolType = sym.getSymbolType();
if (symbolType == FShape.POINT
|| symbolType == FShape.LINE
|| sym instanceof CartographicSupport) {
csSym = (CartographicSupport) sym;
if (sym instanceof SimpleLineSymbol) {
SimpleLineSymbol lineSym = new SimpleLineSymbol();
lineSym.setXMLEntity(sym.getXMLEntity());
if (((SimpleLineSymbol) sym).getLineStyle()
.getArrowDecorator() != null) {
// Lines with decorators should not be cut
// because the decorators would be drawn in
// the wrong places
cutGeom = false;
if (!((SimpleLineSymbol) sym)
.getLineStyle().getArrowDecorator()
.isScaleArrow()) {
// Hack for increasing non-scaled arrow
// marker size, which usually looks
// smaller when printing
lineSym.getLineStyle()
.getArrowDecorator()
.getMarker()
.setSize(
lineSym.getLineStyle()
.getArrowDecorator()
.getMarker()
.getSize() * 3);
}
} else {
// Make default lines slightly thinner when
// printing
lineSym.setLineWidth(lineSym.getLineWidth() * 0.75);
}
csSym = lineSym;
}
}
//System.err.println("passada "+mapPass+" pinte símboll "+sym.getDescription());
// We check if the geometry seems to intersect with the
// view extent
Rectangle2D extent = viewPort.getExtent();
IGeometry geomToPrint = null;
if (cutGeom) {
try {
if (geom.fastIntersects(extent.getX(),
extent.getY(), extent.getWidth(),
extent.getHeight())) {
// If it does, then we create a rectangle
// based on
// the view extent and cut the geometries by
// it
// before drawing them
GeometryFactory geomF = new GeometryFactory();
Geometry intersection = geom
.toJTSGeometry()
.intersection(
new Polygon(
geomF.createLinearRing(new Coordinate[] {
new Coordinate(
extent.getMinX(),
extent.getMaxY()),
new Coordinate(
extent.getMaxX(),
extent.getMaxY()),
new Coordinate(
extent.getMaxX(),
extent.getMinY()),
new Coordinate(
extent.getMinX(),
extent.getMinY()),
new Coordinate(
extent.getMinX(),
extent.getMaxY()) }),
null, geomF));
if (!intersection.isEmpty()) {
geomToPrint = FConverter
.jts_to_igeometry(intersection);
}
}
} catch (TopologyException e) {
logger.warn(
"Some error happened while trying to cut a polygon with the view extent before printing (layer '"
+ this.getName()
+ "' / feature id "
+ feat.getID()
+ "). The whole polygon will be drawn. ",
e);
geomToPrint = geom;
}
} else {
geomToPrint = geom;
}
if (geomToPrint != null) {
if (csSym == null) {
geomToPrint.drawInts(g, viewPort, sym, null);
} else {
geomToPrint.drawInts(g, viewPort, dpi, csSym,
cancel);
}
}
}
it.closeIterator();
}
} catch (ReadDriverException e) {
this.setVisible(false);
this.setActive(false);
throw e;
}
}
}
public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
print(g, viewPort, cancel, scale, properties, false);
}
public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
double scale, PrintRequestAttributeSet properties, boolean highlight) throws ReadDriverException {
if (isVisible() && isWithinScale(scale)) {
_print(g, viewPort, cancel, scale, properties, highlight);
}
}
public void deleteSpatialIndex() {
//must we delete possible spatial indexes files?
spatialIndex = null;
}
/**
* <p>
* Creates an spatial index associated to this layer.
* The spatial index will used
* the native projection of the layer, so if the layer is reprojected, it will
* be ignored.
* </p>
* @param cancelMonitor instance of CancellableMonitorable that allows
* to monitor progress of spatial index creation, and cancel the process
*/
public void createSpatialIndex(CancellableMonitorable cancelMonitor){
// FJP: ESTO HABRÁ QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
// QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
// para que acepten recorrer sin geometria, solo con rectangulos.
//If this vectorial layer is based in a spatial database, the spatial
//index is already implicit. We only will index file drivers
ReadableVectorial va = getSource();
//We must think in non spatial databases, like HSQLDB
if(!(va instanceof VectorialFileAdapter)){
return;
}
if (!(va.getDriver() instanceof BoundedShapes)) {
return;
}
File file = ((VectorialFileAdapter) va).getFile();
String fileName = file.getAbsolutePath();
ISpatialIndex localCopy = null;
try {
va.start();
localCopy = new QuadtreeGt2(fileName, "NM", va.getFullExtent(),
va.getShapeCount(), true);
} catch (SpatialIndexException e1) {
// Probably we dont have writing permissions
String directoryName = System.getProperty("java.io.tmpdir");
File newFile = new File(directoryName +
File.separator +
file.getName());
String newFileName = newFile.getName();
try {
localCopy = new QuadtreeGt2(newFileName, "NM", va.getFullExtent(),
va.getShapeCount(), true);
} catch (SpatialIndexException e) {
// if we cant build a file based spatial index, we'll build
// a pure memory spatial index
localCopy = new QuadtreeJts();
} catch (ReadDriverException e) {
localCopy = new QuadtreeJts();
}
} catch(Exception e){
e.printStackTrace();
}//try
BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
try {
for (int i=0; i < va.getShapeCount(); i++)
{
if(cancelMonitor != null){
if(cancelMonitor.isCanceled())
return;
cancelMonitor.reportStep();
}
Rectangle2D r = shapeBounds.getShapeBounds(i);
if(r != null)
localCopy.insert(r, i);
} // for
va.stop();
if(localCopy instanceof IPersistentSpatialIndex)
((IPersistentSpatialIndex) localCopy).flush();
spatialIndex = localCopy;
//vectorial adapter needs a reference to the spatial index, to solve
//request for feature iteration based in spatial queries
source.setSpatialIndex(spatialIndex);
} catch (ReadDriverException e) {
e.printStackTrace();
}
}
public void createSpatialIndex() {
createSpatialIndex(null);
}
public void process(FeatureVisitor visitor, FBitSet subset)
throws ReadDriverException, ExpansionFileReadException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
s.process(visitor, subset);
}
public void process(FeatureVisitor visitor) throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
s.process(visitor);
}
public void process(FeatureVisitor visitor, Rectangle2D rect)
throws ReadDriverException, ExpansionFileReadException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
s.process(visitor, rect);
}
public FBitSet queryByRect(Rectangle2D rect) throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
return s.queryByRect(rect);
}
public FBitSet queryByPoint(Point2D p, double tolerance)
throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
return s.queryByPoint(p, tolerance);
}
public FBitSet queryByShape(IGeometry g, int relationship)
throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
return s.queryByShape(g, relationship);
}
public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException, VisitorException {
Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
FBitSet bs = queryByPoint(pReal, tolerance);
VectorialXMLItem[] item = new VectorialXMLItem[1];
item[0] = new VectorialXMLItem(bs, this);
return item;
}
public void setLegend(IVectorLegend r) throws LegendLayerException {
if (this.legend == r){
return;
}
if (this.legend != null && this.legend.equals(r)){
return;
}
IVectorLegend oldLegend = legend;
/*
* Parche para discriminar las leyendas clasificadas cuyos campos de
* clasificación no están en la fuente de la capa.
*
* Esto puede ocurrir porque en versiones anteriores se admitían
* leyendas clasificadas en capas que se han unido a una tabla
* por campos que pertenecían a la tabla y no sólo a la capa.
*
*/
// if(r instanceof IClassifiedVectorLegend){
// IClassifiedVectorLegend classifiedLegend = (IClassifiedVectorLegend)r;
// String[] fieldNames = classifiedLegend.getClassifyingFieldNames();
//
// for (int i = 0; i < fieldNames.length; i++) {
// try {
// if(this.getRecordset().getFieldIndexByName(fieldNames[i]) == -1){
//// if(this.getSource().getRecordset().getFieldIndexByName(fieldNames[i]) == -1){
// logger.warn("Some fields of the classification of the legend doesn't belong with the source of the layer.");
// if (this.legend == null){
// r = LegendFactory.createSingleSymbolLegend(this.getShapeType());
// } else {
// return;
// }
// }
// } catch (ReadDriverException e1) {
// throw new LegendLayerException(getName(),e1);
// }
// }
// }
/* Fin del parche */
legend = r;
try {
legend.setDataSource(getRecordset());
} catch (FieldNotFoundException e1) {
throw new LegendLayerException(getName(),e1);
} catch (ReadDriverException e1) {
throw new LegendLayerException(getName(),e1);
} finally{
this.updateDrawVersion();
}
if (oldLegend != null){
oldLegend.removeLegendListener(this);
}
if (legend != null){
legend.addLegendListener(this);
}
LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
oldLegend, legend);
e.setLayer(this);
callLegendChanged(e);
}
/**
* Devuelve la Leyenda de la capa.
*
* @return Leyenda.
*/
public ILegend getLegend() {
return legend;
}
/**
* Devuelve el tipo de shape que contiene la capa.
*
* @return tipo de shape.
*
* @throws DriverException
*/
public int getShapeType() throws ReadDriverException {
if (typeShape == -1) {
getSource().start();
typeShape = getSource().getShapeType();
getSource().stop();
}
return typeShape;
}
public XMLEntity getXMLEntity() throws XMLException {
if (!this.isAvailable() && this.orgXMLEntity != null) {
return this.orgXMLEntity;
}
XMLEntity xml = super.getXMLEntity();
if (getLegend()!=null)
xml.addChild(getLegend().getXMLEntity());
try {
if (getRecordset()!=null)
xml.addChild(getRecordset().getSelectionSupport().getXMLEntity());
} catch (ReadDriverException e1) {
e1.printStackTrace();
throw new XMLException(e1);
}
// Repongo el mismo ReadableVectorial más abajo para cuando se guarda el proyecto.
ReadableVectorial rv=getSource();
xml.putProperty("type", "vectorial");
if (source instanceof VectorialEditableAdapter) {
setSource(((VectorialEditableAdapter) source).getOriginalAdapter());
}
if (source instanceof VectorialFileAdapter) {
xml.putProperty("type", "vectorial");
xml.putProperty("absolutePath",((VectorialFileAdapter) source)
.getFile().getAbsolutePath());
xml.putProperty("file", pathGenerator.getPath(((VectorialFileAdapter) source)
.getFile().getAbsolutePath()));
try {
xml.putProperty("recordset-name", source.getRecordset()
.getName());
} catch (ReadDriverException e) {
throw new XMLException(e);
} catch (RuntimeException e) {
e.printStackTrace();
}
} else if (source instanceof VectorialDBAdapter) {
xml.putProperty("type", "vectorial");
IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source
.getDriver();
// Guardamos el nombre del driver para poder recuperarlo
// con el DriverManager de Fernando.
xml.putProperty("db", dbDriver.getName());
try {
xml.putProperty("recordset-name", source.getRecordset()
.getName());
} catch (ReadDriverException e) {
throw new XMLException(e);
} catch (RuntimeException e) {
e.printStackTrace();
}
xml.addChild(dbDriver.getXMLEntity()); // Tercer child. Antes hemos
// metido la leyenda y el
// selection support
} else if (source instanceof VectorialAdapter) {
// Se supone que hemos hecho algo genérico.
xml.putProperty("type", "vectorial");
VectorialDriver driver = source.getDriver();
// Guardamos el nombre del driver para poder recuperarlo
// con el DriverManager de Fernando.
xml.putProperty("other", driver.getName());
// try {
try {
xml.putProperty("recordset-name", source.getRecordset()
.getName());
} catch (ReadDriverException e) {
throw new XMLException(e);
} catch (RuntimeException e) {
e.printStackTrace();
}
if (driver instanceof IPersistence) {
// xml.putProperty("className", driver.getClass().getName());
IPersistence persist = (IPersistence) driver;
xml.addChild(persist.getXMLEntity()); // Tercer child. Antes
// hemos metido la
// leyenda y el
// selection support
}
}
if (rv!=null)
setSource(rv);
xml.putProperty("driverName", source.getDriver().getName());
if (bHasJoin)
xml.putProperty("hasJoin", "true");
// properties from ILabelable
xml.putProperty("isLabeled", isLabeled);
if (strategy != null) {
XMLEntity strategyXML = strategy.getXMLEntity();
strategyXML.putProperty("Strategy", strategy.getClassName());
xml.addChild(strategy.getXMLEntity());
}
xml.addChild(getLinkProperties().getXMLEntity());
return xml;
}
/*
* @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
*/
public void setXMLEntity(XMLEntity xml) throws XMLException {
try {
super.setXMLEntity(xml);
XMLEntity legendXML = xml.getChild(0);
IVectorLegend leg = LegendFactory.createFromXML(legendXML);
try {
getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
// JMVIVO: Esto sirve para algo????
/*
* Jaume: si, para restaurar el selectable datasource cuando se
* clona la capa, cuando se carga de un proyecto. Si no esta ya
* no se puede ni hacer consultas sql, ni hacer selecciones,
* ni usar la mayor parte de las herramientas.
*
* Lo vuelvo a poner.
*/
String recordsetName = xml.getStringProperty("recordset-name");
LayerFactory.getDataSourceFactory().changeDataSourceName(
getSource().getRecordset().getName(), recordsetName);
SelectableDataSource sds = new SelectableDataSource(LayerFactory
.getDataSourceFactory().createRandomDataSource(
recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
} catch (NoSuchTableException e1) {
this.setAvailable(false);
throw new XMLException(e1);
} catch (ReadDriverException e1) {
this.setAvailable(false);
throw new XMLException(e1);
}
// Si tiene una unión, lo marcamos para que no se cree la leyenda hasta
// el final
// de la lectura del proyecto
if (xml.contains("hasJoin")) {
setIsJoined(true);
PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
} else {
try {
setLegend(leg);
} catch (LegendLayerException e) {
throw new XMLException(e);
}
}
//Por compatibilidad con proyectos anteriores a la 1.0
boolean containsIsLabeled = xml.contains("isLabeled");
if (containsIsLabeled){
isLabeled = xml.getBooleanProperty("isLabeled");
}
// set properties for ILabelable
XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy");
if (labelingXML!= null) {
if(!containsIsLabeled){
isLabeled = true;
}
try {
ILabelingStrategy labeling = LabelingFactory.createStrategyFromXML(labelingXML, this);
if (isJoined()) {
PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1);
}
else
this.setLabelingStrategy(labeling);
} catch (NotExistInXMLEntity neXMLEX) {
// no strategy was set, just continue;
logger.warn("Reached what should be unreachable code");
}
} else if (legendXML.contains("labelFieldName")|| legendXML.contains("labelfield")) {
/* (jaume) begin patch;
* for backward compatibility purposes. Since gvSIG v1.1 labeling is
* no longer managed by the Legend but by the ILabelingStrategy. The
* following allows restoring older projects' labelings.
*/
String labelTextField = null;
if (legendXML.contains("labelFieldName")){
labelTextField = legendXML.getStringProperty("labelFieldName");
if (labelTextField != null) {
AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
labeling.setLayer(this);
int unit = 1;
boolean useFixedSize = false;
String labelFieldHeight = legendXML.getStringProperty("labelHeightFieldName");
labeling.setTextField(labelTextField);
if(labelFieldHeight!=null){
labeling.setHeightField(labelFieldHeight);
} else {
double size = -1;
for(int i=0; i<legendXML.getChildrenCount();i++){
XMLEntity xmlChild = legendXML.getChild(i);
if(xmlChild.contains("m_FontSize")){
double childFontSize = xmlChild.getDoubleProperty("m_FontSize");
if(size<0){
size = childFontSize;
useFixedSize = true;
} else {
useFixedSize = useFixedSize && (size==childFontSize);
}
if(xmlChild.contains("m_bUseFontSize")){
if(xmlChild.getBooleanProperty("m_bUseFontSize")){
unit = -1;
} else {
unit = 1;
}
}
}
}
labeling.setFixedSize(size/1.4);//Factor de corrección que se aplicaba antes en el etiquetado
}
labeling.setUsesFixedSize(useFixedSize);
labeling.setUnit(unit);
labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
if (isJoined()) {
PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1);
}
else
this.setLabelingStrategy(labeling);
this.setIsLabeled(true);
}
}else{
labelTextField = legendXML.getStringProperty("labelfield");
if (labelTextField != null) {
AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
labeling.setLayer(this);
int unit = 1;
boolean useFixedSize = false;
String labelFieldHeight = legendXML.getStringProperty("labelFieldHeight");
labeling.setTextField(labelTextField);
if(labelFieldHeight!=null){
labeling.setHeightField(labelFieldHeight);
} else {
double size = -1;
for(int i=0; i<legendXML.getChildrenCount();i++){
XMLEntity xmlChild = legendXML.getChild(i);
if(xmlChild.contains("m_FontSize")){
double childFontSize = xmlChild.getDoubleProperty("m_FontSize");
if(size<0){
size = childFontSize;
useFixedSize = true;
} else {
useFixedSize = useFixedSize && (size==childFontSize);
}
if(xmlChild.contains("m_bUseFontSize")){
if(xmlChild.getBooleanProperty("m_bUseFontSize")){
unit = -1;
} else {
unit = 1;
}
}
}
}
labeling.setFixedSize(size/1.4);//Factor de corrección que se aplicaba antes en el etiquetado
}
labeling.setUsesFixedSize(useFixedSize);
labeling.setUnit(unit);
labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
if (isJoined()) {
PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1);
}
else
this.setLabelingStrategy(labeling);
this.setIsLabeled(true);
}
}
}else if(!containsIsLabeled){
isLabeled = false;
}
// compatibility with hyperlink from 1.9 alpha version... do we really need to be compatible with alpha versions??
XMLEntity xmlLinkProperties=xml.firstChild("typeChild", "linkProperties");
if (xmlLinkProperties != null){
try {
String fieldName=xmlLinkProperties.getStringProperty("fieldName");
xmlLinkProperties.remove("fieldName");
String extName = xmlLinkProperties.getStringProperty("extName");
xmlLinkProperties.remove("extName");
int typeLink = xmlLinkProperties.getIntProperty("typeLink");
xmlLinkProperties.remove("typeLink");
if (fieldName!=null) {
setProperty("legacy.hyperlink.selectedField", fieldName);
setProperty("legacy.hyperlink.type", new Integer(typeLink));
if (extName!=null) {
setProperty("legacy.hyperlink.extension", extName);
}
}
}
catch (NotExistInXMLEntity ex) {
logger.warn("Error getting old hyperlink configuration", ex);
}
}
} catch (XMLException e) {
this.setAvailable(false);
this.orgXMLEntity = xml;
} catch (Exception e) {
e.printStackTrace();
this.setAvailable(false);
this.orgXMLEntity = xml;
}
}
public void setXMLEntityNew(XMLEntity xml) throws XMLException {
try {
super.setXMLEntity(xml);
XMLEntity legendXML = xml.getChild(0);
IVectorLegend leg = LegendFactory.createFromXML(legendXML);
/* (jaume) begin patch;
* for backward compatibility purposes. Since gvSIG v1.1 labeling is
* no longer managed by the Legend but by the ILabelingStrategy. The
* following allows restoring older projects' labelings.
*/
if (legendXML.contains("labelFieldHeight")) {
AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
labeling.setLayer(this);
labeling.setTextField(legendXML.getStringProperty("labelFieldHeight"));
labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
this.setLabelingStrategy(labeling);
this.setIsLabeled(true);
}
/* end patch */
try {
getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
this.setLoadSelection(xml.getChild(1));
} catch (ReadDriverException e1) {
this.setAvailable(false);
throw new XMLException(e1);
}
// Si tiene una unión, lo marcamos para que no se cree la leyenda hasta
// el final
// de la lectura del proyecto
if (xml.contains("hasJoin")) {
setIsJoined(true);
PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
} else {
this.setLoadLegend(leg);
}
} catch (XMLException e) {
this.setAvailable(false);
this.orgXMLEntity = xml;
} catch (Exception e) {
this.setAvailable(false);
this.orgXMLEntity = xml;
}
}
/**
* Sobreimplementación del método toString para que las bases de datos
* identifiquen la capa.
*
* @return DOCUMENT ME!
*/
public String toString() {
/*
* Se usa internamente para que la parte de datos identifique de forma
* unívoca las tablas
*/
String ret = super.toString();
return "layer" + ret.substring(ret.indexOf('@') + 1);
}
public boolean isJoined() {
return bHasJoin;
}
/**
* Returns if a layer is spatially indexed
*
* @return if this layer has the ability to proces spatial queries without
* secuential scans.
*/
public boolean isSpatiallyIndexed() {
ReadableVectorial source = getSource();
if (source instanceof ISpatialDB)
return true;
//FIXME azabala
/*
* Esto es muy dudoso, y puede cambiar.
* Estoy diciendo que las que no son fichero o no son
* BoundedShapes estan indexadas. Esto es mentira, pero
* así quien pregunte no querrá generar el indice.
* Esta por ver si interesa generar el indice para capas
* HSQLDB, WFS, etc.
*/
if(!(source instanceof VectorialFileAdapter)){
return true;
}
if (!(source.getDriver() instanceof BoundedShapes)) {
return true;
}
if (getISpatialIndex() != null)
return true;
return false;
}
public void setIsJoined(boolean hasJoin) {
bHasJoin = hasJoin;
}
/**
* @return Returns the spatialIndex.
*/
public ISpatialIndex getISpatialIndex() {
return spatialIndex;
}
/**
* Sets the spatial index. This could be useful if, for some
* reasons, you want to work with a distinct spatial index
* (for example, a spatial index which could makes nearest
* neighbour querys)
* @param spatialIndex
*/
public void setISpatialIndex(ISpatialIndex spatialIndex){
this.spatialIndex = spatialIndex;
}
public SelectableDataSource getRecordset() throws ReadDriverException {
if (!this.isAvailable()) return null;
if (sds == null) {
SelectableDataSource ds = source.getRecordset();
if (ds == null) {
return null;
}
sds = ds;
getSelectionSupport().addSelectionListener(this);
}
return sds;
}
public void setEditing(boolean b) throws StartEditionLayerException {
super.setEditing(b);
try {
if (b) {
VectorialEditableAdapter vea = null;
// TODO: Qué pasa si hay más tipos de adapters?
// FJP: Se podría pasar como argumento el
// VectorialEditableAdapter
// que se quiera usar para evitar meter código aquí de este
// estilo.
if (getSource() instanceof VectorialDBAdapter) {
vea = new VectorialEditableDBAdapter();
} else if (this instanceof FLyrAnnotation) {
vea = new AnnotationEditableAdapter(
(FLyrAnnotation) this);
} else {
vea = new VectorialEditableAdapter();
}
vea.addEditionListener(this);
vea.setOriginalVectorialAdapter(getSource());
// azo: implementations of readablevectorial need
//references of projection and spatial index
vea.setProjection(getProjection());
vea.setSpatialIndex(spatialIndex);
// /vea.setSpatialIndex(getSpatialIndex());
// /vea.setFullExtent(getFullExtent());
vea.setCoordTrans(getCoordTrans());
vea.startEdition(EditionEvent.GRAPHIC);
setSource(vea);
getRecordset().setSelectionSupport(
vea.getOriginalAdapter().getRecordset()
.getSelectionSupport());
} else {
VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
vea.removeEditionListener(this);
setSource(vea.getOriginalAdapter());
}
// Si tenemos una leyenda, hay que pegarle el cambiazo a su
// recordset
setRecordset(getSource().getRecordset());
if (getLegend() instanceof IVectorLegend) {
IVectorLegend ley = (IVectorLegend) getLegend();
ley.setDataSource(getSource().getRecordset());
// Esto lo pongo para evitar que al dibujar sobre un
// dxf, dwg, o dgn no veamos nada. Es debido al checkbox
// de la leyenda de textos "dibujar solo textos".
//jaume
// if (!(getSource().getDriver() instanceof IndexedShpDriver)){
// FSymbol symbol=new FSymbol(getShapeType());
// symbol.setFontSizeInPixels(false);
// symbol.setFont(new Font("SansSerif", Font.PLAIN, 9));
// Color color=symbol.getColor();
// int alpha=symbol.getColor().getAlpha();
// if (alpha>250) {
// symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100));
// }
// ley.setDefaultSymbol(symbol);
// }
//jaume//
ley.useDefaultSymbol(true);
}
} catch (ReadDriverException e) {
throw new StartEditionLayerException(getName(),e);
} catch (FieldNotFoundException e) {
throw new StartEditionLayerException(getName(),e);
} catch (StartWriterVisitorException e) {
throw new StartEditionLayerException(getName(),e);
}
setSpatialCacheEnabled(b);
callEditionChanged(LayerEvent
.createEditionChangedEvent(this, "edition"));
}
/**
* Para cuando haces una unión, sustituyes el recorset por el nuevo. De esta
* forma, podrás poner leyendas basadas en el nuevo recordset
*
* @param newSds
*/
public void setRecordset(SelectableDataSource newSds) {
// TODO: Deberiamos hacer comprobaciones del cambio
sds = newSds;
getSelectionSupport().addSelectionListener(this);
this.updateDrawVersion();
}
public void clearSpatialCache()
{
spatialCache.clearAll();
}
public boolean isSpatialCacheEnabled() {
return spatialCacheEnabled;
}
public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
this.spatialCacheEnabled = spatialCacheEnabled;
}
public SpatialCache getSpatialCache() {
return spatialCache;
}
/**
* Siempre es un numero mayor de 1000
* @param maxFeatures
*/
public void setMaxFeaturesInEditionCache(int maxFeatures) {
if (maxFeatures > spatialCache.maxFeatures)
spatialCache.setMaxFeatures(maxFeatures);
}
/**
* This method returns a boolean that is used by the FPopMenu
* to make visible the properties menu or not. It is visible by
* default, and if a later don't have to show this menu only
* has to override this method.
* @return
* If the properties menu is visible (or not)
*/
public boolean isPropertiesMenuVisible(){
return true;
}
public void reload() throws ReloadLayerException {
if(this.isEditing()){
throw new ReloadLayerException(getName());
}
this.setAvailable(true);
super.reload();
this.updateDrawVersion();
try {
this.source.getDriver().reload();
if (this.getLegend() == null) {
if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
this.setLegend((IVectorLegend) aux.getDefaultLegend());
this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
} else {
this.setLegend(LegendFactory.createSingleSymbolLegend(
this.getShapeType()));
}
}
} catch (LegendLayerException e) {
this.setAvailable(false);
throw new ReloadLayerException(getName(),e);
} catch (ReadDriverException e) {
this.setAvailable(false);
throw new ReloadLayerException(getName(),e);
}
}
protected void setLoadSelection(XMLEntity xml) {
this.loadSelection = xml;
}
protected void setLoadLegend(IVectorLegend legend) {
this.loadLegend = legend;
}
protected void putLoadSelection() throws XMLException {
if (this.loadSelection == null) return;
try {
this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
} catch (ReadDriverException e) {
throw new XMLException(e);
}
this.loadSelection = null;
}
protected void putLoadLegend() throws LegendLayerException {
if (this.loadLegend == null) return;
this.setLegend(this.loadLegend);
this.loadLegend = null;
}
protected void cleanLoadOptions() {
this.loadLegend = null;
this.loadSelection = null;
}
public boolean isWritable() {
VectorialDriver drv = getSource().getDriver();
if (!drv.isWritable())
return false;
if (drv instanceof IWriteable)
{
IWriter writer = ((IWriteable)drv).getWriter();
if (writer != null)
{
if (writer instanceof ISpatialWriter)
return true;
}
}
return false;
}
public FLayer cloneLayer() throws Exception {
FLyrVect clonedLayer = new FLyrVect();
clonedLayer.setSource(getSource());
if (isJoined()) {
clonedLayer.setIsJoined(true);
clonedLayer.setRecordset(getRecordset());
}
clonedLayer.setVisible(isVisible());
clonedLayer.setISpatialIndex(getISpatialIndex());
clonedLayer.setName(getName());
clonedLayer.setCoordTrans(getCoordTrans());
clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
clonedLayer.setIsLabeled(isLabeled());
ILabelingStrategy labelingStrategy=getLabelingStrategy();
if (labelingStrategy!=null)
clonedLayer.setLabelingStrategy(labelingStrategy);
return clonedLayer;
}
public SelectionSupport getSelectionSupport() {
try {
return getRecordset().getSelectionSupport();
} catch (ReadDriverException e) {
e.printStackTrace();
}
return null;
}
protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, double dpi, CartographicSupport csSym, IGeometry geom, int[] xyCoords) {
return isOnePoint(graphicsTransform, viewPort, geom, xyCoords) && csSym.getCartographicSize(viewPort, dpi, (FShape)geom.getInternalShape()) <= 1;
}
protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, IGeometry geom, int[] xyCoords) {
boolean onePoint = false;
int type=geom.getGeometryType() % FShape.Z;
if (type!=FShape.POINT && type!=FShape.MULTIPOINT && type!=FShape.NULL) {
Rectangle2D geomBounds = geom.getBounds2D();
// ICoordTrans ct = getCoordTrans();
// Se supone que la geometria ya esta
// repoyectada y no hay que hacer
// ninguna transformacion
// if (ct!=null) {
//// geomBounds = ct.getInverted().convert(geomBounds);
// geomBounds = ct.convert(geomBounds);
// }
double dist1Pixel = viewPort.getDist1pixel();
onePoint = (geomBounds.getWidth() <= dist1Pixel
&& geomBounds.getHeight() <= dist1Pixel);
if (onePoint) {
// avoid out of range exceptions
FPoint2D p = new FPoint2D(geomBounds.getMinX(), geomBounds.getMinY());
p.transform(viewPort.getAffineTransform());
p.transform(graphicsTransform);
xyCoords[0] = (int) p.getX();
xyCoords[1] = (int) p.getY();
}
}
return onePoint;
}
/*
* jaume. Stuff from ILabeled.
*/
private boolean isLabeled;
private ILabelingStrategy strategy;
public boolean isLabeled() {
return isLabeled;
}
public void setIsLabeled(boolean isLabeled) {
this.isLabeled = isLabeled;
}
public ILabelingStrategy getLabelingStrategy() {
return strategy;
}
public void setLabelingStrategy(ILabelingStrategy strategy) {
this.strategy = strategy;
try {
strategy.setLayer(this);
} catch (ReadDriverException e) {
e.printStackTrace();
}
}
public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale, double dpi) throws ReadDriverException {
if (strategy!=null && isWithinScale(scale)) {
strategy.draw(image, g, viewPort, cancel, dpi);
}
}
public void printLabels(Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
if (strategy!=null) {
strategy.print(g, viewPort, cancel, properties);
}
}
//Métodos para el uso de HyperLinks en capas FLyerVect
/**
* Return true, because a Vectorial Layer supports HyperLink
*/
public boolean allowLinks()
{
return true;
}
/**
* Returns an instance of AbstractLinkProperties that contains the information
* of the HyperLink
* @return Abstra
*/
public AbstractLinkProperties getLinkProperties()
{
return linkProperties;
}
/**
* Provides an array with URIs. Returns one URI by geometry that includes the point
* in its own geometry limits with a allowed tolerance.
* @param layer, the layer
* @param point, the point to check that is contained or not in the geometries in the layer
* @param tolerance, the tolerance allowed. Allowed margin of error to detect if the point
* is contained in some geometries of the layer
* @return
*/
public URI[] getLink(Point2D point, double tolerance)
{
//return linkProperties.getLink(this)
return linkProperties.getLink(this,point,tolerance);
}
public void selectionChanged(SelectionEvent e) {
this.updateDrawVersion();
}
public void afterFieldEditEvent(AfterFieldEditEvent e) {
this.updateDrawVersion();
}
public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
this.updateDrawVersion();
}
public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
}
public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
}
public void processEvent(EditionEvent e) {
if (e.getChangeType()== e.ROW_EDITION){
this.updateDrawVersion();
}
}
public void legendCleared(LegendClearEvent event) {
this.updateDrawVersion();
LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
legend, legend);
this.callLegendChanged(e);
}
public boolean symbolChanged(SymbolLegendEvent e) {
this.updateDrawVersion();
LegendChangedEvent event = LegendChangedEvent.createLegendChangedEvent(
legend, legend);
this.callLegendChanged(event);
return true;
}
public String getTypeStringVectorLayer() throws ReadDriverException {
String typeString="";
int typeShape=this.getShapeType();
if (FShape.MULTI==typeShape){
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
if ((geom.getGeometryType() & FShape.Z) == FShape.Z){
typeString="Geometries3D";
}else{
typeString="Geometries2D";
}
}
}else{
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
int type=geom.getGeometryType();
if (FShape.POINT == type){
typeString="Point2D";
} else if (FShape.LINE == type){
typeString="Line2D";
} else if (FShape.POLYGON == type){
typeString="Polygon2D";
} else if (FShape.MULTIPOINT == type){
typeString="MultiPint2D";
} else if ((FShape.POINT | FShape.Z) == type ){
typeString="Point3D";
} else if ((FShape.LINE | FShape.Z) == type ){
typeString="Line3D";
} else if ((FShape.POLYGON | FShape.Z) == type ){
typeString="Polygon3D";
} else if ((FShape.MULTIPOINT | FShape.Z) == type ){
typeString="MultiPoint3D";
} else if ((FShape.POINT | FShape.M) == type ){
typeString="PointM";
} else if ((FShape.LINE | FShape.M) == type ){
typeString="LineM";
} else if ((FShape.POLYGON | FShape.M) == type ){
typeString="PolygonM";
} else if ((FShape.MULTIPOINT | FShape.M) == type ){
typeString="MultiPointM";
} else if ((FShape.MULTI | FShape.M) == type ){
typeString="M";
}
}
return typeString;
}
return "";
}
public int getTypeIntVectorLayer() throws ReadDriverException {
int typeInt=0;
int typeShape=this.getShapeType();
if (FShape.MULTI==typeShape){
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
if ((geom.getGeometryType() & FShape.Z) == FShape.Z){
typeInt=FShape.MULTI | FShape.Z;
}else{
typeInt=FShape.MULTI;
}
}
}else{
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
int type=geom.getGeometryType();
typeInt=type;
}
return typeInt;
}
return typeInt;
}
} | iCarto/siga | libFMap/src/com/iver/cit/gvsig/fmap/layers/FLyrVect.java | Java | gpl-3.0 | 77,323 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2019 Evan Debenham
*
* 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 com.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.darts;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Adrenaline;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
public class AdrenalineDart extends TippedDart {
{
image = ItemSpriteSheet.ADRENALINE_DART;
}
@Override
public int proc(Char attacker, Char defender, int damage) {
Buff.prolong( defender, Adrenaline.class, Adrenaline.DURATION);
if (attacker.alignment == defender.alignment){
return 0;
}
return super.proc(attacker, defender, damage);
}
}
| 00-Evan/shattered-pixel-dungeon-gdx | core/src/com/shatteredpixel/shatteredpixeldungeon/items/weapon/missiles/darts/AdrenalineDart.java | Java | gpl-3.0 | 1,505 |
Bitrix 16.5 Business Demo = 16d7a678d19259b91107fcffd1fa68c9
| gohdan/DFC | known_files/hashes/bitrix/modules/sender/lang/ru/admin/mailing_edit.php | PHP | gpl-3.0 | 61 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppointmentsManagement.Classes;
namespace AppointmentsManagement.Forms
{
public partial class wfnSrvcOffrdForm : WeifenLuo.WinFormsUI.Docking.DockContent
{
#region "GLOBAL VARIABLES..."
//Records;
cadmaFunctions.NavFuncs myNav = new cadmaFunctions.NavFuncs();
bool beenToCheckBx = false;
long rec_cur_indx = 0;
bool is_last_rec = false;
long totl_rec = 0;
long last_rec_num = 0;
public string rec_SQL = "";
public string recDt_SQL = "";
bool obey_evnts = false;
bool autoLoad = false;
public bool txtChngd = false;
public string srchWrd = "%";
bool addRec = false;
bool editRec = false;
bool someLinesFailed = false;
bool vwRecs = false;
bool addRecs = false;
bool editRecs = false;
bool delRecs = false;
//Line Dtails;
long ldt_cur_indx = 0;
bool is_last_ldt = false;
long totl_ldt = 0;
long last_ldt_num = 0;
bool obey_ldt_evnts = false;
public int curid = -1;
public string curCode = "";
#endregion
public wfnSrvcOffrdForm()
{
InitializeComponent();
}
private void wfnGLIntfcForm_Load(object sender, EventArgs e)
{
Color[] clrs = Global.mnFrm.cmCde.getColors();
this.BackColor = clrs[0];
this.tabPage1.BackColor = clrs[0];
this.disableFormButtons();
this.curid = Global.mnFrm.cmCde.getOrgFuncCurID(Global.mnFrm.cmCde.Org_id);
this.curCode = Global.mnFrm.cmCde.getPssblValNm(this.curid);
this.loadPanel();
}
public void disableFormButtons()
{
bool vwSQL = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[5]);
bool rcHstry = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[6]);
this.vwRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[4]);
this.addRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[10]);
this.editRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[11]);
this.delRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[12]);
this.vwSQLButton.Enabled = vwSQL;
this.rcHstryButton.Enabled = rcHstry;
this.vwSQLDtButton.Enabled = vwSQL;
this.rcHstryDtButton.Enabled = rcHstry;
this.saveButton.Enabled = false;
this.addButton.Enabled = this.addRecs;
this.editButton.Enabled = this.editRecs;
this.addDtButton.Enabled = this.editRecs;
this.delDtButton.Enabled = this.editRecs;
this.delButton.Enabled = this.delRecs;
}
#region "SERVICE TYPES..."
public void loadPanel()
{
Cursor.Current = Cursors.Default;
this.obey_evnts = false;
if (this.searchInComboBox.SelectedIndex < 0)
{
this.searchInComboBox.SelectedIndex = 1;
}
if (searchForTextBox.Text.Contains("%") == false)
{
this.searchForTextBox.Text = "%" + this.searchForTextBox.Text.Replace(" ", "%") + "%";
}
if (this.searchForTextBox.Text == "%%")
{
this.searchForTextBox.Text = "%";
}
int dsply = 0;
if (this.dsplySizeComboBox.Text == ""
|| int.TryParse(this.dsplySizeComboBox.Text, out dsply) == false)
{
this.dsplySizeComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
}
this.is_last_rec = false;
this.totl_rec = Global.mnFrm.cmCde.Big_Val;
this.getPnlData();
this.obey_evnts = true;
this.srvcsOffrdListView.Focus();
}
private void getPnlData()
{
this.updtTotals();
this.populateSrvsTypListVw();
this.updtNavLabels();
}
private void updtTotals()
{
Global.mnFrm.cmCde.navFuncts.FindNavigationIndices(
long.Parse(this.dsplySizeComboBox.Text), this.totl_rec);
if (this.rec_cur_indx >= Global.mnFrm.cmCde.navFuncts.totalGroups)
{
this.rec_cur_indx = Global.mnFrm.cmCde.navFuncts.totalGroups - 1;
}
if (this.rec_cur_indx < 0)
{
this.rec_cur_indx = 0;
}
Global.mnFrm.cmCde.navFuncts.currentNavigationIndex = this.rec_cur_indx;
}
private void updtNavLabels()
{
this.moveFirstButton.Enabled = Global.mnFrm.cmCde.navFuncts.moveFirstBtnStatus();
this.movePreviousButton.Enabled = Global.mnFrm.cmCde.navFuncts.movePrevBtnStatus();
this.moveNextButton.Enabled = Global.mnFrm.cmCde.navFuncts.moveNextBtnStatus();
this.moveLastButton.Enabled = Global.mnFrm.cmCde.navFuncts.moveLastBtnStatus();
this.positionTextBox.Text = Global.mnFrm.cmCde.navFuncts.displayedRecordsNumbers();
if (this.is_last_rec == true ||
this.totl_rec != Global.mnFrm.cmCde.Big_Val)
{
this.totalRecsLabel.Text = Global.mnFrm.cmCde.navFuncts.totalRecordsLabel();
}
else
{
this.totalRecsLabel.Text = "of Total";
}
}
private void populateSrvsTypListVw()
{
this.obey_evnts = false;
DataSet dtst = Global.get_SrvcTyps(this.searchForTextBox.Text,
this.searchInComboBox.Text, this.rec_cur_indx,
int.Parse(this.dsplySizeComboBox.Text), Global.mnFrm.cmCde.Org_id);
this.srvcsOffrdListView.Items.Clear();
this.clearDtInfo();
this.loadDtPanel();
if (!this.editRec)
{
this.disableDtEdit();
}
//System.Windows.Forms.Application.DoEvents();
for (int i = 0; i < dtst.Tables[0].Rows.Count; i++)
{
this.last_rec_num = Global.mnFrm.cmCde.navFuncts.startIndex() + i;
ListViewItem nwItem = new ListViewItem(new string[] {
(Global.mnFrm.cmCde.navFuncts.startIndex() + i).ToString(),
dtst.Tables[0].Rows[i][1].ToString(),
dtst.Tables[0].Rows[i][0].ToString()});
this.srvcsOffrdListView.Items.Add(nwItem);
}
this.correctNavLbls(dtst);
if (this.srvcsOffrdListView.Items.Count > 0)
{
this.obey_evnts = true;
this.srvcsOffrdListView.Items[0].Selected = true;
}
else
{
}
this.obey_evnts = true;
}
private void populateDt(int HdrID)
{
//Global.mnFrm.cmCde.minimizeMemory();
this.clearDtInfo();
//System.Windows.Forms.Application.DoEvents();
if (this.editRec == false)
{
this.disableDtEdit();
}
this.obey_evnts = false;
DataSet dtst = Global.get_One_ServTypeDt(HdrID);
for (int i = 0; i < dtst.Tables[0].Rows.Count; i++)
{
this.serviceTypeIDTextBox.Text = dtst.Tables[0].Rows[i][0].ToString();
this.serviceNameTextBox.Text = dtst.Tables[0].Rows[i][1].ToString();
this.servTypeDescTextBox.Text = dtst.Tables[0].Rows[i][2].ToString();
this.salesItemIDTextBox.Text = dtst.Tables[0].Rows[i][4].ToString();
this.salesItemTextBox.Text = Global.get_InvItemNm(
int.Parse(dtst.Tables[0].Rows[i][4].ToString()));
this.priceCurLabel.Text = this.curCode;
this.priceLabel.Text = Global.get_InvItemPrice(int.Parse(dtst.Tables[0].Rows[i][4].ToString())).ToString("#,##0.00");
string orgnlItm = dtst.Tables[0].Rows[i][5].ToString();
this.srvcTypeComboBox.Items.Clear();
this.srvcTypeComboBox.Items.Add(orgnlItm);
if (this.editRec == false)
{
}
this.srvcTypeComboBox.SelectedItem = orgnlItm;
this.isEnabledCheckBox.Checked = Global.mnFrm.cmCde.cnvrtBitStrToBool(dtst.Tables[0].Rows[i][3].ToString());
}
this.loadDtPanel();
this.obey_evnts = true;
}
private void correctNavLbls(DataSet dtst)
{
long totlRecs = dtst.Tables[0].Rows.Count;
if (this.rec_cur_indx == 0 && totlRecs == 0)
{
this.is_last_rec = true;
this.totl_rec = 0;
this.last_rec_num = 0;
this.rec_cur_indx = 0;
this.updtTotals();
this.updtNavLabels();
}
else if (this.totl_rec == Global.mnFrm.cmCde.Big_Val
&& totlRecs < long.Parse(this.dsplySizeComboBox.Text))
{
this.totl_rec = this.last_rec_num;
if (totlRecs == 0)
{
this.rec_cur_indx -= 1;
this.updtTotals();
this.populateSrvsTypListVw();
}
else
{
this.updtTotals();
}
}
}
private bool shdObeyEvts()
{
return this.obey_evnts;
}
private void PnlNavButtons(object sender, System.EventArgs e)
{
System.Windows.Forms.ToolStripButton sentObj = (System.Windows.Forms.ToolStripButton)sender;
this.totalRecsLabel.Text = "";
if (sentObj.Name.ToLower().Contains("first"))
{
this.is_last_rec = false;
this.rec_cur_indx = 0;
}
else if (sentObj.Name.ToLower().Contains("previous"))
{
this.is_last_rec = false;
this.rec_cur_indx -= 1;
}
else if (sentObj.Name.ToLower().Contains("next"))
{
this.is_last_rec = false;
this.rec_cur_indx += 1;
}
else if (sentObj.Name.ToLower().Contains("last"))
{
this.is_last_rec = true;
this.totl_rec = Global.get_Ttl_SrvsTyps(this.searchForTextBox.Text,
this.searchInComboBox.Text, Global.mnFrm.cmCde.Org_id);
this.updtTotals();
this.rec_cur_indx = Global.mnFrm.cmCde.navFuncts.totalGroups - 1;
}
this.getPnlData();
}
private void clearDtInfo()
{
this.obey_evnts = false;
//
this.serviceTypeIDTextBox.Text = "-1";
this.serviceNameTextBox.Text = "";
this.servTypeDescTextBox.Text = "";
this.isEnabledCheckBox.Checked = false;
this.salesItemIDTextBox.Text = "-1";
this.salesItemTextBox.Text = "";
this.priceLabel.Text = "0.00";
this.priceCurLabel.Text = this.curCode;
if (this.editRec == false)
{
this.srvcTypeComboBox.Items.Clear();
}
this.obey_evnts = true;
}
private void prpareForDtEdit()
{
this.obey_evnts = false;
this.saveButton.Enabled = true;
this.serviceNameTextBox.ReadOnly = false;
this.serviceNameTextBox.BackColor = Color.FromArgb(255, 255, 128);
this.servTypeDescTextBox.ReadOnly = false;
this.servTypeDescTextBox.BackColor = Color.White;
this.salesItemTextBox.ReadOnly = false;
this.salesItemTextBox.BackColor = Color.White;// FromArgb(255, 255, 128);
string brgtSQL = "";
bool isDynmc = false;
DataSet dtst = Global.mnFrm.cmCde.getLovValues("%", "Both", 0, 5000,
ref brgtSQL, Global.mnFrm.cmCde.getLovID("System Codes for Appointment Services"),
ref isDynmc, -1, "", "", "");
object orgnlItm = null;
if (this.srvcTypeComboBox.SelectedIndex >= 0)
{
orgnlItm = this.srvcTypeComboBox.SelectedItem;
}
if (this.addRec)
{
this.srvcTypeComboBox.Items.Clear();
for (int i = 0; i < dtst.Tables[0].Rows.Count; i++)
{
this.srvcTypeComboBox.Items.Add(dtst.Tables[0].Rows[i][0].ToString());
}
}
if (orgnlItm != null)
{
this.srvcTypeComboBox.SelectedItem = orgnlItm;
}
this.srvcTypeComboBox.BackColor = Color.FromArgb(255, 255, 128);
this.obey_evnts = true;
}
private void disableDtEdit()
{
if (this.editButton.Text == "STOP")
{
EventArgs e = new EventArgs();
this.editButton_Click(this.editButton, e);
}
this.addRec = false;
this.editRec = false;
this.saveButton.Enabled = false;
this.editButton.Enabled = this.editRecs;
this.addButton.Enabled = this.addRecs;
this.serviceNameTextBox.ReadOnly = true;
this.serviceNameTextBox.BackColor = Color.WhiteSmoke;
this.servTypeDescTextBox.ReadOnly = true;
this.servTypeDescTextBox.BackColor = Color.WhiteSmoke;
this.salesItemTextBox.ReadOnly = true;
this.salesItemTextBox.BackColor = Color.WhiteSmoke;
if (this.srvcTypeComboBox.SelectedIndex >= 0)
{
object orgnlItm = this.srvcTypeComboBox.SelectedItem;
this.srvcTypeComboBox.Items.Clear();
this.srvcTypeComboBox.Items.Add(orgnlItm);
this.srvcTypeComboBox.SelectedItem = orgnlItm;
}
else
{
this.srvcTypeComboBox.Items.Clear();
}
this.srvcTypeComboBox.BackColor = Color.WhiteSmoke;
}
private void searchForTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
this.goButton.PerformClick();
}
}
private void positionTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Up)
{
this.PnlNavButtons(this.movePreviousButton, ex);
}
else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Down)
{
this.PnlNavButtons(this.moveNextButton, ex);
}
}
private void goButton_Click(object sender, EventArgs e)
{
this.loadPanel();
}
#endregion
private void srvcsOffrdListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.obey_evnts == false || this.srvcsOffrdListView.SelectedItems.Count > 1)
{
return;
}
//this.populateDt(-100000);
if (this.srvcsOffrdListView.SelectedItems.Count == 1)
{
this.populateDt(int.Parse(this.srvcsOffrdListView.SelectedItems[0].SubItems[2].Text));
}
else if (this.addRec == false)
{
this.clearDtInfo();
this.disableDtEdit();
this.disableLnsEdit();
this.dataDefDataGridView.Rows.Clear();
}
}
private void loadDtPanel()
{
this.changeGridVw();
this.obey_ldt_evnts = false;
if (this.searchInDtComboBox.SelectedIndex < 0)
{
this.searchInDtComboBox.SelectedIndex = 2;
}
if (this.searchForDtTextBox.Text.Contains("%") == false)
{
this.searchForDtTextBox.Text = "%" + this.searchForDtTextBox.Text.Replace(" ", "%") + "%";
}
if (this.searchForDtTextBox.Text == "%%")
{
this.searchForDtTextBox.Text = "%";
}
int dsply = 0;
if (this.dsplySizeDtComboBox.Text == ""
|| int.TryParse(this.dsplySizeDtComboBox.Text, out dsply) == false)
{
this.dsplySizeDtComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
}
//this.groupBox8.Height = this.g.Bottom - this.toolStrip4.Bottom - 50;
this.ldt_cur_indx = 0;
this.is_last_ldt = false;
this.last_ldt_num = 0;
this.totl_ldt = Global.mnFrm.cmCde.Big_Val;
this.getldtPnlData();
//this.dataDefDataGridView.Focus();
this.obey_ldt_evnts = true;
//SendKeys.Send("{TAB}");
//System.Windows.Forms.Application.DoEvents();
//SendKeys.Send("{HOME}");
//System.Windows.Forms.Application.DoEvents();
}
private void getldtPnlData()
{
this.updtldtTotals();
this.populateDtLines(int.Parse(this.serviceTypeIDTextBox.Text));
this.updtldtNavLabels();
}
private void updtldtTotals()
{
int dsply = 0;
if (this.dsplySizeDtComboBox.Text == ""
|| int.TryParse(this.dsplySizeDtComboBox.Text, out dsply) == false)
{
this.dsplySizeDtComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
}
this.myNav.FindNavigationIndices(
long.Parse(this.dsplySizeDtComboBox.Text), this.totl_ldt);
if (this.ldt_cur_indx >= this.myNav.totalGroups)
{
this.ldt_cur_indx = this.myNav.totalGroups - 1;
}
if (this.ldt_cur_indx < 0)
{
this.ldt_cur_indx = 0;
}
this.myNav.currentNavigationIndex = this.ldt_cur_indx;
}
private void updtldtNavLabels()
{
this.moveFirstDtButton.Enabled = this.myNav.moveFirstBtnStatus();
this.movePreviousDtButton.Enabled = this.myNav.movePrevBtnStatus();
this.moveNextDtButton.Enabled = this.myNav.moveNextBtnStatus();
this.moveLastDtButton.Enabled = this.myNav.moveLastBtnStatus();
this.positionDtTextBox.Text = this.myNav.displayedRecordsNumbers();
if (this.is_last_ldt == true ||
this.totl_ldt != Global.mnFrm.cmCde.Big_Val)
{
this.totalRecsDtLabel.Text = this.myNav.totalRecordsLabel();
}
else
{
this.totalRecsDtLabel.Text = "of Total";
}
}
private void populateDtLines(int HdrID)
{
this.dataDefDataGridView.Rows.Clear();
if (HdrID > 0 && this.addRec == false && this.editRec == false)
{
this.disableLnsEdit();
}
this.obey_ldt_evnts = false;
//System.Windows.Forms.Application.DoEvents();
DataSet dtst = Global.get_datadfntns(HdrID,
this.searchForDtTextBox.Text,
this.searchInDtComboBox.Text,
this.ldt_cur_indx,
int.Parse(this.dsplySizeDtComboBox.Text));
int rwcnt = dtst.Tables[0].Rows.Count;
for (int i = 0; i < rwcnt; i++)
{
this.last_ldt_num = this.myNav.startIndex() + i;
//System.Windows.Forms.Application.DoEvents();
this.dataDefDataGridView.RowCount += 1;//, this.apprvlStatusTextBox.Text.Insert(this.rgstrDtDataGridView.RowCount - 1, 1);
int rowIdx = this.dataDefDataGridView.RowCount - 1;
this.dataDefDataGridView.Rows[rowIdx].HeaderCell.Value = (i + 1).ToString();
//Object[] cellDesc = new Object[27];
this.dataDefDataGridView.Rows[rowIdx].Cells[0].Value = dtst.Tables[0].Rows[i][2].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[1].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[2].Value = dtst.Tables[0].Rows[i][3].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[3].Value = dtst.Tables[0].Rows[i][4].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[4].Value = dtst.Tables[0].Rows[i][5].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[5].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[6].Value = dtst.Tables[0].Rows[i][6].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[7].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[8].Value = Global.mnFrm.cmCde.cnvrtBitStrToBool(dtst.Tables[0].Rows[i][7].ToString());
this.dataDefDataGridView.Rows[rowIdx].Cells[9].Value = dtst.Tables[0].Rows[i][0].ToString();
}
this.correctldtNavLbls(dtst);
this.obey_ldt_evnts = true;
System.Windows.Forms.Application.DoEvents();
}
private void correctldtNavLbls(DataSet dtst)
{
long totlRecs = dtst.Tables[0].Rows.Count;
if (this.totl_ldt == Global.mnFrm.cmCde.Big_Val
&& totlRecs < long.Parse(this.dsplySizeDtComboBox.Text))
{
this.totl_ldt = this.last_ldt_num;
if (totlRecs == 0)
{
this.ldt_cur_indx -= 1;
this.updtldtTotals();
this.populateDtLines(int.Parse(this.serviceTypeIDTextBox.Text));
}
else
{
this.updtldtTotals();
}
}
}
private bool shdObeyldtEvts()
{
return this.obey_ldt_evnts;
}
private void DtPnlNavButtons(object sender, System.EventArgs e)
{
System.Windows.Forms.ToolStripButton sentObj = (System.Windows.Forms.ToolStripButton)sender;
this.totalRecsDtLabel.Text = "";
if (sentObj.Name.ToLower().Contains("first"))
{
this.is_last_ldt = false;
this.ldt_cur_indx = 0;
}
else if (sentObj.Name.ToLower().Contains("previous"))
{
this.is_last_ldt = false;
this.ldt_cur_indx -= 1;
}
else if (sentObj.Name.ToLower().Contains("next"))
{
this.is_last_ldt = false;
this.ldt_cur_indx += 1;
}
else if (sentObj.Name.ToLower().Contains("last"))
{
this.is_last_ldt = true;
this.totl_ldt = Global.get_ttl_datadfntns(int.Parse(this.serviceTypeIDTextBox.Text),
this.searchForDtTextBox.Text,
this.searchInDtComboBox.Text);
this.updtldtTotals();
this.ldt_cur_indx = this.myNav.totalGroups - 1;
}
this.getldtPnlData();
}
private void prpareForLnsEdit()
{
this.saveButton.Enabled = true;
this.dataDefDataGridView.ReadOnly = false;
this.dataDefDataGridView.Columns[0].ReadOnly = false;
this.dataDefDataGridView.Columns[0].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 128);
this.dataDefDataGridView.Columns[2].ReadOnly = false;
this.dataDefDataGridView.Columns[2].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 128);
this.dataDefDataGridView.Columns[3].ReadOnly = false;
this.dataDefDataGridView.Columns[3].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 128);
this.dataDefDataGridView.Columns[4].ReadOnly = false;
this.dataDefDataGridView.Columns[4].DefaultCellStyle.BackColor = Color.White;
this.dataDefDataGridView.Columns[6].ReadOnly = false;
this.dataDefDataGridView.Columns[6].DefaultCellStyle.BackColor = Color.White;
this.dataDefDataGridView.Columns[8].ReadOnly = false;
this.dataDefDataGridView.Columns[8].DefaultCellStyle.BackColor = Color.White;
this.dataDefDataGridView.Columns[9].ReadOnly = true;
this.dataDefDataGridView.Columns[9].DefaultCellStyle.BackColor = Color.Gainsboro;
}
private void disableLnsEdit()
{
this.addRec = false;
this.editRec = false;
this.saveButton.Enabled = false;
this.dataDefDataGridView.ReadOnly = true;
this.dataDefDataGridView.Columns[0].ReadOnly = true;
this.dataDefDataGridView.Columns[0].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[2].ReadOnly = true;
this.dataDefDataGridView.Columns[2].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[3].ReadOnly = true;
this.dataDefDataGridView.Columns[3].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[4].ReadOnly = true;
this.dataDefDataGridView.Columns[4].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[6].ReadOnly = true;
this.dataDefDataGridView.Columns[6].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[8].ReadOnly = true;
this.dataDefDataGridView.Columns[8].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[9].ReadOnly = true;
this.dataDefDataGridView.Columns[9].DefaultCellStyle.BackColor = Color.Gainsboro;
System.Windows.Forms.Application.DoEvents();
}
private void vwSQLDtButton_Click(object sender, EventArgs e)
{
Global.mnFrm.cmCde.showSQL(this.recDt_SQL, 5);
}
private void rcHstryDtButton_Click(object sender, EventArgs e)
{
if (this.dataDefDataGridView.CurrentCell != null
&& this.dataDefDataGridView.SelectedRows.Count <= 0)
{
this.dataDefDataGridView.Rows[this.dataDefDataGridView.CurrentCell.RowIndex].Selected = true;
}
if (this.dataDefDataGridView.SelectedRows.Count <= 0)
{
Global.mnFrm.cmCde.showMsg("Please select a Record First!", 0);
return;
}
Global.mnFrm.cmCde.showRecHstry(
Global.get_DT_Rec_Hstry(int.Parse(this.dataDefDataGridView.SelectedRows[0].Cells[9].Value.ToString())), 6);
}
private void vwSQLButton_Click(object sender, EventArgs e)
{
Global.mnFrm.cmCde.showSQL(this.rec_SQL, 5);
}
private void rcHstryButton_Click(object sender, EventArgs e)
{
if (this.serviceTypeIDTextBox.Text == "-1"
|| this.serviceTypeIDTextBox.Text == "")
{
Global.mnFrm.cmCde.showMsg("Please select a Record First!", 0);
return;
}
Global.mnFrm.cmCde.showRecHstry(
Global.get_Rec_Hstry(int.Parse(this.serviceTypeIDTextBox.Text)), 6);
}
private void positionDtTextBox_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Up)
{
this.DtPnlNavButtons(this.movePreviousDtButton, ex);
}
else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Down)
{
this.DtPnlNavButtons(this.moveNextDtButton, ex);
}
}
private void dsplySizeDtComboBox_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
this.loadDtPanel();
}
}
private void resetButton_Click(object sender, EventArgs e)
{
Global.mnFrm.cmCde.minimizeMemory();
this.searchInComboBox.SelectedIndex = 1;
this.searchForTextBox.Text = "%";
this.searchInDtComboBox.SelectedIndex = 2;
this.searchForDtTextBox.Text = "%";
this.dsplySizeComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
this.dsplySizeDtComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
this.rec_cur_indx = 0;
this.ldt_cur_indx = 0;
this.loadPanel();
}
private void addButton_Click(object sender, EventArgs e)
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[10]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
if (this.editButton.Text == "STOP")
{
this.editButton.PerformClick();
}
//this.editGBVButton.Enabled = false;
this.clearDtInfo();
this.dataDefDataGridView.Rows.Clear();
this.addRec = true;
this.editRec = false;
this.prpareForDtEdit();
ToolStripButton mybtn = (ToolStripButton)sender;
this.changeGridVw();
this.prpareForLnsEdit();
this.serviceNameTextBox.Focus();
this.editButton.Enabled = false;
this.addButton.Enabled = false;
this.addDtButton.PerformClick();
//this.addPriceButton.PerformClick();
}
private void editButton_Click(object sender, EventArgs e)
{
if (this.editButton.Text == "EDIT")
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[8]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
if (this.serviceTypeIDTextBox.Text == "" || this.serviceTypeIDTextBox.Text == "-1")
{
Global.mnFrm.cmCde.showMsg("No record to Edit!", 0);
return;
}
this.addRec = false;
this.editRec = true;
this.prpareForDtEdit();
this.prpareForLnsEdit();
//this.addGBVButton.Enabled = false;
this.editButton.Text = "STOP";
this.serviceNameTextBox.Focus();
//this.editMenuItem.Text = "STOP EDITING";
}
else
{
this.saveButton.Enabled = false;
this.addRec = false;
this.editRec = false;
this.addButton.Enabled = this.addRecs;
this.editButton.Enabled = this.editRecs;
this.addDtButton.Enabled = this.editRecs;
this.delDtButton.Enabled = this.editRecs;
this.editButton.Text = "EDIT";
//this.editMenuItem.Text = "Edit Item";
this.disableDtEdit();
this.disableLnsEdit();
System.Windows.Forms.Application.DoEvents();
//this.loadPanel();
}
System.Windows.Forms.Application.DoEvents();
}
private void delButton_Click(object sender, EventArgs e)
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[9]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
if (this.serviceTypeIDTextBox.Text == "" || this.serviceTypeIDTextBox.Text == "-1")
{
Global.mnFrm.cmCde.showMsg("Please select the Record to DELETE!", 0);
return;
}
if (Global.isSrvsTypInUse(int.Parse(this.serviceTypeIDTextBox.Text)) == true)
{
Global.mnFrm.cmCde.showMsg("This Service Type is in Use!", 0);
return;
}
if (Global.mnFrm.cmCde.showMsg("Are you sure you want to DELETE the selected Record?" +
"\r\nThis action cannot be undone!", 1) == DialogResult.No)
{
//Global.mnFrm.cmCde.showMsg("Operation Cancelled!", 4);
return;
}
Global.deleteSrvsTyp(int.Parse(this.serviceTypeIDTextBox.Text), this.serviceNameTextBox.Text);
this.loadPanel();
}
private void delDtButton_Click(object sender, EventArgs e)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
return;
}
if (this.dataDefDataGridView.CurrentCell != null
&& this.dataDefDataGridView.SelectedRows.Count <= 0)
{
this.dataDefDataGridView.Rows[this.dataDefDataGridView.CurrentCell.RowIndex].Selected = true;
}
if (this.dataDefDataGridView.SelectedRows.Count <= 0)
{
Global.mnFrm.cmCde.showMsg("Please select the Record(s) to Delete!", 0);
return;
}
if (Global.mnFrm.cmCde.showMsg("Are you sure you want to DELETE the selected Line?" +
"\r\nThis action cannot be undone!", 1) == DialogResult.No)
{
//Global.mnFrm.cmCde.showMsg("Operation Cancelled!", 4);
return;
}
int cnt = this.dataDefDataGridView.SelectedRows.Count;
for (int i = 0; i < cnt; i++)
{
if (this.dataDefDataGridView.SelectedRows[0].Cells[2].Value == null)
{
this.dataDefDataGridView.SelectedRows[0].Cells[2].Value = string.Empty;
}
long lnID = -1;
long.TryParse(this.dataDefDataGridView.SelectedRows[0].Cells[9].Value.ToString(), out lnID);
if (lnID > 0)
{
if (Global.isSrvcDataCaptureInUse(lnID))
{
Global.mnFrm.cmCde.showMsg("The Record at Row(" + (i + 1) + ") has been Used hence cannot be Deleted!", 0);
continue;
}
Global.deleteSrvsTypLn(lnID, this.dataDefDataGridView.SelectedRows[0].Cells[2].Value.ToString());
}
this.dataDefDataGridView.Rows.RemoveAt(this.dataDefDataGridView.SelectedRows[0].Index);
}
//this.loadDtPanel();
}
private void salesItemTextBox_TextChanged(object sender, EventArgs e)
{
if (!this.obey_evnts)
{
return;
}
this.txtChngd = true;
}
private void salesItemTextBox_Leave(object sender, EventArgs e)
{
if (this.txtChngd == false)
{
return;
}
this.txtChngd = false;
TextBox mytxt = (TextBox)sender;
this.obey_evnts = false;
this.srchWrd = mytxt.Text;
if (!mytxt.Text.Contains("%"))
{
this.srchWrd = "%" + this.srchWrd.Replace(" ", "%") + "%";
}
if (mytxt.Name == "salesItemTextBox")
{
this.salesItemTextBox.Text = "";
this.salesItemIDTextBox.Text = "-1";
this.salesItemButton_Click(this.salesItemButton, e);
}
this.srchWrd = "%";
this.obey_evnts = true;
this.txtChngd = false;
}
private void salesItemButton_Click(object sender, EventArgs e)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
return;
}
string[] selVals = new string[1];
selVals[0] = this.salesItemIDTextBox.Text;
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Inventory Items"), ref selVals,
true, false, Global.mnFrm.cmCde.Org_id,
this.srchWrd, "Both", true);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.salesItemIDTextBox.Text = selVals[i];
this.salesItemTextBox.Text = Global.get_InvItemNm
(int.Parse(selVals[i]));
this.priceLabel.Text = Global.get_InvItemPrice(int.Parse(selVals[i])).ToString("#,##0.00");
}
}
}
private void saveButton_Click(object sender, EventArgs e)
{
if (this.addRec == true)
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[10]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
}
else
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[11]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
}
if (this.serviceNameTextBox.Text == "")
{
Global.mnFrm.cmCde.showMsg("Please enter a Service Name!", 0);
return;
}
long oldRecID = Global.getSrvsTypID(this.serviceNameTextBox.Text,
Global.mnFrm.cmCde.Org_id);
if (oldRecID > 0
&& this.addRec == true)
{
Global.mnFrm.cmCde.showMsg("Service Name is already in use in this Organisation!", 0);
return;
}
if (oldRecID > 0
&& this.editRec == true
&& oldRecID.ToString() !=
this.serviceTypeIDTextBox.Text)
{
Global.mnFrm.cmCde.showMsg("New Service Name is already in use in this Organisation!", 0);
return;
}
if (this.srvcTypeComboBox.Text == "")
{
Global.mnFrm.cmCde.showMsg("Type of Service cannot be empty!", 0);
return;
}
if (this.addRec == true)
{
Global.createSrvsTyp(this.serviceNameTextBox.Text,
this.servTypeDescTextBox.Text, int.Parse(this.salesItemIDTextBox.Text),
this.isEnabledCheckBox.Checked, this.srvcTypeComboBox.Text,
Global.mnFrm.cmCde.Org_id);
//this.saveGBVButton.Enabled = false;
//this.addgbv = false;
//this.editgbv = true;
this.editButton.Enabled = this.editRecs;
this.addButton.Enabled = this.addRecs;
//Global.mnFrm.cmCde.showMsg("Record Saved!", 3);
System.Windows.Forms.Application.DoEvents();
this.serviceTypeIDTextBox.Text = Global.getSrvsTypID(this.serviceNameTextBox.Text,
Global.mnFrm.cmCde.Org_id).ToString();
this.someLinesFailed = false;
this.saveGridView(int.Parse(this.serviceTypeIDTextBox.Text));
if (this.someLinesFailed == false)
{
this.loadPanel();
}
else
{
this.editRec = true;
this.addRec = false;
this.saveButton.Enabled = true;
}
this.someLinesFailed = false;
}
else if (this.editRec == true)
{
Global.updateSrvsTyp(int.Parse(this.serviceTypeIDTextBox.Text), this.serviceNameTextBox.Text,
this.servTypeDescTextBox.Text, int.Parse(this.salesItemIDTextBox.Text),
this.isEnabledCheckBox.Checked, this.srvcTypeComboBox.Text);
this.someLinesFailed = false;
this.saveGridView(int.Parse(this.serviceTypeIDTextBox.Text));
if (this.someLinesFailed == false)
{
//this.loadPanel();
if (this.srvcsOffrdListView.SelectedItems.Count > 0)
{
this.srvcsOffrdListView.SelectedItems[0].SubItems[1].Text = this.serviceNameTextBox.Text;
}
}
else
{
this.editRec = true;
this.saveButton.Enabled = true;
}
this.someLinesFailed = false;
// Global.mnFrm.cmCde.showMsg("Record Saved!", 3);
}
}
private bool checkDtRqrmnts(int rwIdx)
{
this.dfltFill(rwIdx);
if (this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value.ToString() == "")
{
return false;
}
int dataDefID = int.Parse(this.dataDefDataGridView.Rows[rwIdx].Cells[9].Value.ToString());
string dataCtgry = this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value.ToString();
string dataLabel = this.dataDefDataGridView.Rows[rwIdx].Cells[2].Value.ToString();
if (dataCtgry == "")
{
Global.mnFrm.cmCde.showMsg("Data Category cannot be Empty!", 0);
return false;
}
if (dataLabel == "")
{
Global.mnFrm.cmCde.showMsg("Data Label cannot be Empty!", 0);
return false;
}
long oldDataDefID = Global.getSrvcsDataDefID(dataLabel, dataCtgry, int.Parse(this.serviceTypeIDTextBox.Text));
if (oldDataDefID > 0
&& dataDefID <= 0)
{
Global.mnFrm.cmCde.showMsg("Data Definition Category & Label Combination is already Defined in this Service!", 0);
return false;
}
if (oldDataDefID > 0
&& dataDefID > 0
&& oldDataDefID != dataDefID)
{
Global.mnFrm.cmCde.showMsg("New Data Definition Category & Label Combination is already Defined in this Service!", 0);
return false;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[3].Value.ToString() == "")
{
Global.mnFrm.cmCde.showMsg("Data Label cannot be Empty!", 0);
return false;
}
return true;
}
private void saveGridView(int srvcTypHdrID)
{
int svd = 0;
if (this.dataDefDataGridView.Rows.Count > 0)
{
this.dataDefDataGridView.EndEdit();
//this.itemsDataGridView.Rows[0].Cells[1].Selected = true;
System.Windows.Forms.Application.DoEvents();
}
for (int i = 0; i < this.dataDefDataGridView.Rows.Count; i++)
{
if (!this.checkDtRqrmnts(i))
{
this.dataDefDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(255, 100, 100);
this.someLinesFailed = true;
continue;
}
else
{
//Check if Doc Ln Rec Exists
//Create if not else update
int hdrID = int.Parse(this.serviceTypeIDTextBox.Text);
long dataDefID = int.Parse(this.dataDefDataGridView.Rows[i].Cells[9].Value.ToString());
string dataCtgry = this.dataDefDataGridView.Rows[i].Cells[0].Value.ToString();
string dataLabel = this.dataDefDataGridView.Rows[i].Cells[2].Value.ToString();
string dataType = this.dataDefDataGridView.Rows[i].Cells[3].Value.ToString();
string dataValLov = this.dataDefDataGridView.Rows[i].Cells[4].Value.ToString();
string dataValLovDesc = this.dataDefDataGridView.Rows[i].Cells[6].Value.ToString();
bool enbld = (bool)this.dataDefDataGridView.Rows[i].Cells[8].Value;
if (dataDefID <= 0)
{
dataDefID = Global.getNewDataDefID();
Global.createDataDefntn(hdrID, dataCtgry, dataLabel, enbld, dataType, dataValLov, dataValLovDesc);
this.dataDefDataGridView.Rows[i].Cells[9].Value = dataDefID;
}
else
{
Global.updateDataDefntn(dataDefID, dataCtgry, dataLabel, enbld, dataType, dataValLov, dataValLovDesc);
}
svd++;
this.dataDefDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.Lime;
}
}
this.dataDefDataGridView.EndEdit();
Global.mnFrm.cmCde.showMsg(svd + " Line(s) Saved Successfully!", 3);
}
private void dfltFill(int rwIdx)
{
if (this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[2].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[2].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[3].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[3].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[4].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[4].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[6].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[6].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[8].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[8].Value = false;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[9].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[9].Value = "-1";
}
}
private void isEnabledCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.shdObeyEvts() == false || beenToCheckBx == true)
{
beenToCheckBx = false;
return;
}
beenToCheckBx = true;
if (this.addRec == false && this.editRec == false)
{
this.isEnabledCheckBox.Checked = !this.isEnabledCheckBox.Checked;
}
}
private void addDtButton_Click(object sender, EventArgs e)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
return;
}
this.createDtRows(1);
this.prpareForLnsEdit();
}
private void changeGridVw()
{
/*
* Room/Hall
Field/Yard
Restaurant Table
Gym/Sport Subscription,
Rental Item
*/
}
public void createDtRows(int num)
{
this.dataDefDataGridView.DefaultCellStyle.ForeColor = Color.Black;
this.obey_ldt_evnts = false;
for (int i = 0; i < num; i++)
{
this.dataDefDataGridView.Rows.Insert(0, 1);
int rowIdx = 0;// this.dataDefDataGridView.RowCount - 1;
this.dataDefDataGridView.Rows[rowIdx].Cells[0].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[1].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[2].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[3].Value = "TEXT";
this.dataDefDataGridView.Rows[rowIdx].Cells[4].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[5].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[6].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[7].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[8].Value = false;
this.dataDefDataGridView.Rows[rowIdx].Cells[9].Value = "-1";
}
this.obey_ldt_evnts = true;
}
private void serviceTypesForm_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.Control && e.KeyCode == Keys.S)
{
if (this.saveButton.Enabled == true)
{
this.saveButton_Click(this.saveButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.N)
{
if (this.addButton.Enabled == true)
{
this.addButton_Click(this.addButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.E)
{
if (this.editButton.Enabled == true)
{
this.editButton_Click(this.editButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.R)
{
this.resetButton.PerformClick();
}
else if ((e.Control && e.KeyCode == Keys.F) || e.KeyCode == Keys.F5)
{
if (this.goButton.Enabled == true)
{
this.goButton_Click(this.goButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.Delete)
{
if (this.delButton.Enabled == true)
{
this.delButton_Click(this.delButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else
{
e.Handled = false;
e.SuppressKeyPress = false;
if (this.serviceNameTextBox.Focused)
{
//Global.mnFrm.cmCde.listViewKeyDown(this.serviceNameTextBox.Text, e);
}
}
}
private void searchForTextBox_Click(object sender, EventArgs e)
{
this.searchForTextBox.SelectAll();
}
private void srvcTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
this.changeGridVw();
}
private void dataDefDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e == null || this.obey_ldt_evnts == false)
{
return;
}
if (e.RowIndex < 0 || e.ColumnIndex < 0)
{
return;
}
bool prv = this.obey_ldt_evnts;
this.obey_ldt_evnts = false;
this.dfltFill(e.RowIndex);
if (e.ColumnIndex == 1
|| e.ColumnIndex == 5
|| e.ColumnIndex == 7)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
this.obey_ldt_evnts = true;
return;
}
}
if (e.ColumnIndex == 1)
{
int[] selVals = new int[1];
selVals[0] = Global.mnFrm.cmCde.getPssblValID(
this.dataDefDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString(),
Global.mnFrm.cmCde.getLovID("Appointment Data Capture Category"));
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Appointment Data Capture Category"), ref selVals,
true, false,
this.srchWrd, "Both", this.autoLoad);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.dataDefDataGridView.Rows[e.RowIndex].Cells[0].Value = Global.mnFrm.cmCde.getPssblValNm(
selVals[i]);
}
this.obey_ldt_evnts = true;
}
}
else if (e.ColumnIndex == 5)
{
//LOV Names
string[] selVals = new string[1];
selVals[0] = Global.mnFrm.cmCde.getLovID(this.dataDefDataGridView.Rows[e.RowIndex].Cells[4].Value.ToString()).ToString();
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Non-Dynamic LOV Names"), ref selVals, true, false,
this.srchWrd, "Both", this.autoLoad);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.dataDefDataGridView.Rows[e.RowIndex].Cells[4].Value = Global.mnFrm.cmCde.getLovNm(int.Parse(selVals[i]));
}
}
}
else if (e.ColumnIndex == 7)
{
//LOV Names
string[] selVals = new string[1];
selVals[0] = Global.mnFrm.cmCde.getLovID(this.dataDefDataGridView.Rows[e.RowIndex].Cells[6].Value.ToString()).ToString();
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Non-Dynamic LOV Names"), ref selVals, true, false,
this.srchWrd, "Both", this.autoLoad);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.dataDefDataGridView.Rows[e.RowIndex].Cells[6].Value = Global.mnFrm.cmCde.getLovNm(int.Parse(selVals[i]));
}
}
}
this.obey_ldt_evnts = true;
}
private void dataDefDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e == null || this.obey_ldt_evnts == false)
{
return;
}
if (e.RowIndex < 0 || e.ColumnIndex < 0)
{
return;
}
this.dfltFill(e.RowIndex);
bool prv = this.obey_ldt_evnts;
this.obey_ldt_evnts = false;
if (e.ColumnIndex == 0)
{
this.autoLoad = true;
DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(1, e.RowIndex);
this.obey_ldt_evnts = true;
this.dataDefDataGridView_CellContentClick(this.dataDefDataGridView, e1);
this.autoLoad = false;
}
else if (e.ColumnIndex == 4)
{
this.autoLoad = true;
DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(5, e.RowIndex);
this.obey_ldt_evnts = true;
this.dataDefDataGridView_CellContentClick(this.dataDefDataGridView, e1);
this.autoLoad = false;
}
else if (e.ColumnIndex == 6)
{
this.autoLoad = true;
DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(7, e.RowIndex);
this.obey_ldt_evnts = true;
this.dataDefDataGridView_CellContentClick(this.dataDefDataGridView, e1);
this.autoLoad = false;
}
this.obey_ldt_evnts = true;
}
private void rfrshDtButton_Click(object sender, EventArgs e)
{
this.loadDtPanel();
}
private void searchForDtTextBox_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
this.rfrshDtButton.PerformClick();
}
}
}
}
| rhomicom-systems-tech-gh/Rhomicom-ERP-Desktop | AppointmentsManagement/AppointmentsManagement/Forms/wfnSrvcOffrdForm.cs | C# | gpl-3.0 | 49,317 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 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/>.
Class
Foam::geomDecomp
Description
Geometrical domain decomposition
SourceFiles
geomDecomp.C
\*---------------------------------------------------------------------------*/
#ifndef geomDecomp_H
#define geomDecomp_H
#include "OpenFOAM-2.1.x/src/parallel/decompose/decompositionMethods/decompositionMethod/decompositionMethod.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/primitives/Vector/Vector.H"
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class geomDecomp Declaration
\*---------------------------------------------------------------------------*/
class geomDecomp
:
public decompositionMethod
{
protected:
// Protected data
const dictionary& geomDecomDict_;
Vector<label> n_;
scalar delta_;
tensor rotDelta_;
public:
// Constructors
//- Construct given the decomposition dictionary
// and the derived type name
geomDecomp
(
const dictionary& decompositionDict,
const word& derivedType
);
//- Return for every coordinate the wanted processor number.
virtual labelList decompose
(
const pointField& points,
const scalarField& pointWeights
) = 0;
//- Like decompose but with uniform weights on the points
virtual labelList decompose(const pointField&) = 0;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| kempj/OpenFOAM-win | src/parallel/decompose/decompositionMethods/geomDecomp/geomDecomp.H | C++ | gpl-3.0 | 2,796 |
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "base58.h"
#include "clientversion.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "core_io.h"
#include "keystore.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include <univalue.h>
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
static bool fCreateBlank;
static std::map<std::string,UniValue> registers;
static const int CONTINUE_EXECUTION=-1;
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRawTx(int argc, char* argv[])
{
//
// Parameters
//
gArgs.ParseParameters(argc, argv);
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
fCreateBlank = gArgs.GetBoolArg("-create", false);
if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help"))
{
// First part of help message is specific to this utility
std::string strUsage = strprintf(_("%s berycoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" berycoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded berycoin transaction") + "\n" +
" berycoin-tx [options] -create [commands] " + _("Create hex-encoded berycoin transaction") + "\n" +
"\n";
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
strUsage += HelpMessageOpt("-json", _("Select JSON output"));
strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
AppendParamsHelpMessages(strUsage);
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Commands:"));
strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
strUsage += HelpMessageOpt("replaceable(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)"));
strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
_("This command requires JSON registers:") +
_("prevtxs=JSON object") + ", " +
_("privatekeys=JSON object") + ". " +
_("See signrawtransaction docs for format of sighash flags, JSON objects."));
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Register Commands:"));
strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void RegisterSetJson(const std::string& key, const std::string& rawJson)
{
UniValue val;
if (!val.read(rawJson)) {
std::string strErr = "Cannot parse JSON for key " + key;
throw std::runtime_error(strErr);
}
registers[key] = val;
}
static void RegisterSet(const std::string& strInput)
{
// separate NAME:VALUE in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register input requires NAME:VALUE");
std::string key = strInput.substr(0, pos);
std::string valStr = strInput.substr(pos + 1, std::string::npos);
RegisterSetJson(key, valStr);
}
static void RegisterLoad(const std::string& strInput)
{
// separate NAME:FILENAME in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register load requires NAME:FILENAME");
std::string key = strInput.substr(0, pos);
std::string filename = strInput.substr(pos + 1, std::string::npos);
FILE *f = fopen(filename.c_str(), "r");
if (!f) {
std::string strErr = "Cannot open file " + filename;
throw std::runtime_error(strErr);
}
// load file chunks into one big buffer
std::string valStr;
while ((!feof(f)) && (!ferror(f))) {
char buf[4096];
int bread = fread(buf, 1, sizeof(buf), f);
if (bread <= 0)
break;
valStr.insert(valStr.size(), buf, bread);
}
int error = ferror(f);
fclose(f);
if (error) {
std::string strErr = "Error reading file " + filename;
throw std::runtime_error(strErr);
}
// evaluate as JSON buffer register
RegisterSetJson(key, valStr);
}
static CAmount ExtractAndValidateValue(const std::string& strValue)
{
CAmount value;
if (!ParseMoney(strValue, value))
throw std::runtime_error("invalid TX output value");
return value;
}
static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newVersion = atoi64(cmdVal);
if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
throw std::runtime_error("Invalid TX version requested");
tx.nVersion = (int) newVersion;
}
static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newLocktime = atoi64(cmdVal);
if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
throw std::runtime_error("Invalid TX locktime requested");
tx.nLockTime = (unsigned int) newLocktime;
}
static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
}
// set the nSequence to MAX_INT - 2 (= RBF opt in flag)
int cnt = 0;
for (CTxIn& txin : tx.vin) {
if (strInIdx == "" || cnt == inIdx) {
if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
}
}
++cnt;
}
}
static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
{
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// separate TXID:VOUT in string
if (vStrInputParts.size()<2)
throw std::runtime_error("TX input missing separator");
// extract and validate TXID
std::string strTxid = vStrInputParts[0];
if ((strTxid.size() != 64) || !IsHex(strTxid))
throw std::runtime_error("invalid TX input txid");
uint256 txid(uint256S(strTxid));
static const unsigned int minTxOutSz = 9;
static const unsigned int maxVout = dgpMaxBlockSize / minTxOutSz;
// extract and validate vout
std::string strVout = vStrInputParts[1];
int vout = atoi(strVout);
if ((vout < 0) || (vout > (int)maxVout))
throw std::runtime_error("invalid TX input vout");
// extract the optional sequence number
uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
if (vStrInputParts.size() > 2)
nSequenceIn = std::stoul(vStrInputParts[2]);
// append to transaction input list
CTxIn txin(txid, vout, CScript(), nSequenceIn);
tx.vin.push_back(txin);
}
static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:ADDRESS
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() != 2)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate ADDRESS
std::string strAddr = vStrInputParts[1];
CBitcoinAddress addr(strAddr);
if (!addr.IsValid())
throw std::runtime_error("invalid TX output address");
// build standard output script via GetScriptForDestination()
CScript scriptPubKey = GetScriptForDestination(addr.Get());
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:PUBKEY[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract and validate PUBKEY
CPubKey pubkey(ParseHex(vStrInputParts[1]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
// Extract and validate FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts[2];
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
if (bSegWit) {
if (!pubkey.IsCompressed()) {
throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
}
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
// Get the address for the redeem script, then call
// GetScriptForDestination() to construct a P2SH scriptPubKey.
CBitcoinAddress redeemScriptAddr(scriptPubKey);
scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// Check that there are enough parameters
if (vStrInputParts.size()<3)
throw std::runtime_error("Not enough multisig parameters");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract REQUIRED
uint32_t required = stoul(vStrInputParts[1]);
// Extract NUMKEYS
uint32_t numkeys = stoul(vStrInputParts[2]);
// Validate there are the correct number of pubkeys
if (vStrInputParts.size() < numkeys + 3)
throw std::runtime_error("incorrect number of multisig pubkeys");
if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
throw std::runtime_error("multisig parameter mismatch. Required " \
+ std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
// extract and validate PUBKEYs
std::vector<CPubKey> pubkeys;
for(int pos = 1; pos <= int(numkeys); pos++) {
CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
pubkeys.push_back(pubkey);
}
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == numkeys + 4) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
else if (vStrInputParts.size() > numkeys + 4) {
// Validate that there were no more parameters passed
throw std::runtime_error("Too many parameters");
}
CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
if (bSegWit) {
for (CPubKey& pubkey : pubkeys) {
if (!pubkey.IsCompressed()) {
throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
}
}
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
throw std::runtime_error(strprintf(
"redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
}
// Get the address for the redeem script, then call
// GetScriptForDestination() to construct a P2SH scriptPubKey.
CBitcoinAddress addr(scriptPubKey);
scriptPubKey = GetScriptForDestination(addr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
{
CAmount value = 0;
// separate [VALUE:]DATA in string
size_t pos = strInput.find(':');
if (pos==0)
throw std::runtime_error("TX output value not specified");
if (pos != std::string::npos) {
// Extract and validate VALUE
value = ExtractAndValidateValue(strInput.substr(0, pos));
}
// extract and validate DATA
std::string strData = strInput.substr(pos + 1, std::string::npos);
if (!IsHex(strData))
throw std::runtime_error("invalid TX output data");
std::vector<unsigned char> data = ParseHex(strData);
CTxOut txout(value, CScript() << OP_RETURN << data);
tx.vout.push_back(txout);
}
static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
{
// separate VALUE:SCRIPT[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2)
throw std::runtime_error("TX output missing separator");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate script
std::string strScript = vStrInputParts[1];
CScript scriptPubKey = ParseScript(strScript);
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
throw std::runtime_error(strprintf(
"script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
}
if (bSegWit) {
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
throw std::runtime_error(strprintf(
"redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
}
CBitcoinAddress addr(scriptPubKey);
scriptPubKey = GetScriptForDestination(addr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested deletion index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
std::string strErr = "Invalid TX input index '" + strInIdx + "'";
throw std::runtime_error(strErr.c_str());
}
// delete input from transaction
tx.vin.erase(tx.vin.begin() + inIdx);
}
static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
{
// parse requested deletion index
int outIdx = atoi(strOutIdx);
if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
throw std::runtime_error(strErr.c_str());
}
// delete output from transaction
tx.vout.erase(tx.vout.begin() + outIdx);
}
static const unsigned int N_SIGHASH_OPTS = 6;
static const struct {
const char *flagStr;
int flags;
} sighashOptions[N_SIGHASH_OPTS] = {
{"ALL", SIGHASH_ALL},
{"NONE", SIGHASH_NONE},
{"SINGLE", SIGHASH_SINGLE},
{"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
{"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
};
static bool findSighashFlags(int& flags, const std::string& flagStr)
{
flags = 0;
for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
if (flagStr == sighashOptions[i].flagStr) {
flags = sighashOptions[i].flags;
return true;
}
}
return false;
}
static CAmount AmountFromValue(const UniValue& value)
{
if (!value.isNum() && !value.isStr())
throw std::runtime_error("Amount is not a number or string");
CAmount amount;
if (!ParseFixedPoint(value.getValStr(), 8, &amount))
throw std::runtime_error("Invalid amount");
if (!MoneyRange(amount))
throw std::runtime_error("Amount out of range");
return amount;
}
static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
{
int nHashType = SIGHASH_ALL;
if (flagStr.size() > 0)
if (!findSighashFlags(nHashType, flagStr))
throw std::runtime_error("unknown sighash flag/sign option");
std::vector<CTransaction> txVariants;
txVariants.push_back(tx);
// mergedTx will end up with all the signatures; it
// starts as a clone of the raw tx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
if (!registers.count("privatekeys"))
throw std::runtime_error("privatekeys register variable must be set.");
CBasicKeyStore tempKeystore;
UniValue keysObj = registers["privatekeys"];
for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
if (!keysObj[kidx].isStr())
throw std::runtime_error("privatekey not a std::string");
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
if (!fGood)
throw std::runtime_error("privatekey not valid");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
// Add previous txouts given in the RPC call:
if (!registers.count("prevtxs"))
throw std::runtime_error("prevtxs register variable must be set.");
UniValue prevtxsObj = registers["prevtxs"];
{
for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
UniValue prevOut = prevtxsObj[previdx];
if (!prevOut.isObject())
throw std::runtime_error("expected prevtxs internal object");
std::map<std::string, UniValue::VType> types = {
{"txid", UniValue::VSTR},
{"vout", UniValue::VNUM},
{"scriptPubKey", UniValue::VSTR},
};
if (!prevOut.checkObject(types))
throw std::runtime_error("prevtxs internal object typecheck fail");
uint256 txid = ParseHashUV(prevOut["txid"], "txid");
int nOut = atoi(prevOut["vout"].getValStr());
if (nOut < 0)
throw std::runtime_error("vout must be positive");
COutPoint out(txid, nOut);
std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw std::runtime_error(err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
if (prevOut.exists("amount")) {
newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
}
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// if redeemScript given and private keys given,
// add redeemScript to the tempKeystore so it can be signed:
if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
prevOut.exists("redeemScript")) {
UniValue v = prevOut["redeemScript"];
std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
const CKeyStore& keystore = tempKeystore;
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
const CAmount& amount = coin.out.nValue;
SignatureData sigdata;
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
// ... and merge in other signatures:
for (const CTransaction& txv : txVariants)
sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
UpdateTransaction(mergedTx, i, sigdata);
if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
fComplete = false;
}
if (fComplete) {
// do nothing... for now
// perhaps store this for later optional JSON output
}
tx = mergedTx;
}
class Secp256k1Init
{
ECCVerifyHandle globalVerifyHandle;
public:
Secp256k1Init() {
ECC_Start();
}
~Secp256k1Init() {
ECC_Stop();
}
};
static void MutateTx(CMutableTransaction& tx, const std::string& command,
const std::string& commandVal)
{
std::unique_ptr<Secp256k1Init> ecc;
if (command == "nversion")
MutateTxVersion(tx, commandVal);
else if (command == "locktime")
MutateTxLocktime(tx, commandVal);
else if (command == "replaceable") {
MutateTxRBFOptIn(tx, commandVal);
}
else if (command == "delin")
MutateTxDelInput(tx, commandVal);
else if (command == "in")
MutateTxAddInput(tx, commandVal);
else if (command == "delout")
MutateTxDelOutput(tx, commandVal);
else if (command == "outaddr")
MutateTxAddOutAddr(tx, commandVal);
else if (command == "outpubkey") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxAddOutPubKey(tx, commandVal);
} else if (command == "outmultisig") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxAddOutMultiSig(tx, commandVal);
} else if (command == "outscript")
MutateTxAddOutScript(tx, commandVal);
else if (command == "outdata")
MutateTxAddOutData(tx, commandVal);
else if (command == "sign") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxSign(tx, commandVal);
}
else if (command == "load")
RegisterLoad(commandVal);
else if (command == "set")
RegisterSet(commandVal);
else
throw std::runtime_error("unknown command");
}
static void OutputTxJSON(const CTransaction& tx)
{
UniValue entry(UniValue::VOBJ);
TxToUniv(tx, uint256(), entry);
std::string jsonOutput = entry.write(4);
fprintf(stdout, "%s\n", jsonOutput.c_str());
}
static void OutputTxHash(const CTransaction& tx)
{
std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
fprintf(stdout, "%s\n", strHexHash.c_str());
}
static void OutputTxHex(const CTransaction& tx)
{
std::string strHex = EncodeHexTx(tx);
fprintf(stdout, "%s\n", strHex.c_str());
}
static void OutputTx(const CTransaction& tx)
{
if (gArgs.GetBoolArg("-json", false))
OutputTxJSON(tx);
else if (gArgs.GetBoolArg("-txid", false))
OutputTxHash(tx);
else
OutputTxHex(tx);
}
static std::string readStdin()
{
char buf[4096];
std::string ret;
while (!feof(stdin)) {
size_t bread = fread(buf, 1, sizeof(buf), stdin);
ret.append(buf, bread);
if (bread < sizeof(buf))
break;
}
if (ferror(stdin))
throw std::runtime_error("error reading stdin");
boost::algorithm::trim_right(ret);
return ret;
}
static int CommandLineRawTx(int argc, char* argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches; Permit common stdin convention "-"
while (argc > 1 && IsSwitchChar(argv[1][0]) &&
(argv[1][1] != 0)) {
argc--;
argv++;
}
CMutableTransaction tx;
int startArg;
if (!fCreateBlank) {
// require at least one param
if (argc < 2)
throw std::runtime_error("too few parameters");
// param: hex-encoded bitcoin transaction
std::string strHexTx(argv[1]);
if (strHexTx == "-") // "-" implies standard input
strHexTx = readStdin();
if (!DecodeHexTx(tx, strHexTx, true))
throw std::runtime_error("invalid transaction encoding");
startArg = 2;
} else
startArg = 1;
for (int i = startArg; i < argc; i++) {
std::string arg = argv[i];
std::string key, value;
size_t eqpos = arg.find('=');
if (eqpos == std::string::npos)
key = arg;
else {
key = arg.substr(0, eqpos);
value = arg.substr(eqpos + 1);
}
MutateTx(tx, key, value);
}
OutputTx(tx);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRawTx()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
int ret = AppInitRawTx(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRawTx()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitRawTx()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRawTx(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRawTx()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRawTx()");
}
return ret;
}
| berycoin-project/berycoin | src/bitcoin-tx.cpp | C++ | gpl-3.0 | 30,448 |
package net.minecraft.src;
public class BlockJukeBox extends BlockContainer
{
protected BlockJukeBox(int par1)
{
super(par1, Material.wood);
this.setCreativeTab(CreativeTabs.tabDecorations);
}
/**
* Called upon block activation (right click on the block.)
*/
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
{
if (par1World.getBlockMetadata(par2, par3, par4) == 0)
{
return false;
}
else
{
this.ejectRecord(par1World, par2, par3, par4);
return true;
}
}
/**
* Insert the specified music disc in the jukebox at the given coordinates
*/
public void insertRecord(World par1World, int par2, int par3, int par4, ItemStack par5ItemStack)
{
if (!par1World.isRemote)
{
TileEntityRecordPlayer var6 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4);
if (var6 != null)
{
var6.func_96098_a(par5ItemStack.copy());
par1World.setBlockMetadata(par2, par3, par4, 1, 2);
}
}
}
/**
* Ejects the current record inside of the jukebox.
*/
public void ejectRecord(World par1World, int par2, int par3, int par4)
{
if (!par1World.isRemote)
{
TileEntityRecordPlayer var5 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4);
if (var5 != null)
{
ItemStack var6 = var5.func_96097_a();
if (var6 != null)
{
par1World.playAuxSFX(1005, par2, par3, par4, 0);
par1World.playRecord((String)null, par2, par3, par4);
var5.func_96098_a((ItemStack)null);
par1World.setBlockMetadata(par2, par3, par4, 0, 2);
float var7 = 0.7F;
double var8 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
double var10 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.2D + 0.6D;
double var12 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
ItemStack var14 = var6.copy();
EntityItem var15 = new EntityItem(par1World, (double)par2 + var8, (double)par3 + var10, (double)par4 + var12, var14);
var15.delayBeforeCanPickup = 10;
par1World.spawnEntityInWorld(var15);
}
}
}
}
/**
* ejects contained items into the world, and notifies neighbours of an update, as appropriate
*/
public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6)
{
this.ejectRecord(par1World, par2, par3, par4);
super.breakBlock(par1World, par2, par3, par4, par5, par6);
}
/**
* Drops the block items with a specified chance of dropping the specified items
*/
public void dropBlockAsItemWithChance(World par1World, int par2, int par3, int par4, int par5, float par6, int par7)
{
if (!par1World.isRemote)
{
super.dropBlockAsItemWithChance(par1World, par2, par3, par4, par5, par6, 0);
}
}
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
public TileEntity createNewTileEntity(World par1World)
{
return new TileEntityRecordPlayer();
}
/**
* If this returns true, then comparators facing away from this block will use the value from
* getComparatorInputOverride instead of the actual redstone signal strength.
*/
public boolean hasComparatorInputOverride()
{
return true;
}
/**
* If hasComparatorInputOverride returns true, the return value from this is used instead of the redstone signal
* strength when this block inputs to a comparator.
*/
public int getComparatorInputOverride(World par1World, int par2, int par3, int par4, int par5)
{
ItemStack var6 = ((TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4)).func_96097_a();
return var6 == null ? 0 : var6.itemID + 1 - Item.record13.itemID;
}
}
| herpingdo/Hakkit | net/minecraft/src/BlockJukeBox.java | Java | gpl-3.0 | 4,434 |
from bottle import route, template, error, request, static_file, get, post
from index import get_index
from bmarks import get_bmarks
from tags import get_tags
from add import add_tags
from bmarklet import get_bmarklet
from account import get_account
from edit_tags import get_edit_tags
from importbm import get_import_bm
from edit import do_edit
from login import do_login
from register import do_register
@route('/')
def myroot():
return_data = get_index()
return return_data
@route('/account', method=['GET', 'POST'])
def bmarks():
return_data = get_bmarklet()
return return_data
@route('/add', method=['GET', 'POST'])
def bmarks():
return_data = add_tags()
return return_data
@route('/bmarklet')
def bmarks():
return_data = get_bmarklet()
return return_data
@route('/bmarks')
def bmarks():
return_data = get_bmarks()
return return_data
@route('/edit', method=['GET', 'POST'])
def bmarks():
return_data = do_edit()
return return_data
@route('/edit_tags', method=['GET', 'POST'])
def bmarks():
return_data = get_edit_tags()
return return_data
@route('/import', method=['GET', 'POST'])
def bmarks():
return_data = get_import_bm()
return return_data
@route('/login', method=['GET', 'POST'])
def bmarks():
return_data = do_login()
return return_data
@route('/register', method=['GET', 'POST'])
def bmarks():
return_data = do_register()
return return_data
@route('/tags')
def bmarks():
return_data = get_tags()
return return_data
# serve css
@get('/<filename:re:.*\.css>')
def send_css(filename):
return static_file(filename, root='css')
# serve javascript
@get('/<filename:re:.*\.js>')
def send_js(filename):
return static_file(filename, root='js')
# serve images
@get('<filename:re:.*\.png>')
def send_img(filename):
return static_file(filename, root='images')
# serve fonts
@get('<filename:re:.*\.(woff|woff2)>')
def send_font(filename):
return static_file(filename, root='fonts')
@error(404)
def handle404(error):
return '<H1>Ooops, its not here<BR>'
@error(500)
def handle500(error):
return '<H1>Oops, its broken: {}<BR>'.format(error)
| netllama/tastipy | tastiapp.py | Python | gpl-3.0 | 2,172 |
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLJPanel;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.glu.GLU;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import static com.jogamp.opengl.GL.GL_COLOR_BUFFER_BIT;
import static com.jogamp.opengl.GL.GL_DEPTH_BUFFER_BIT;
/**
* This program demonstrates geometric primitives and their attributes.
*
* @author Kiet Le (Java port) Ported to JOGL 2.x by Claudio Eduardo Goes
*/
public class LinesDemo//
// extends GLSkeleton<GLJPanel>
implements GLEventListener, KeyListener {
private GLU glu;
// public static void main(String[] args) {
// final GLCanvas glcanvas = createCanvas();
//
// final JFrame frame = new JFrame("Basic Frame");
//
// frame.getContentPane().add(glcanvas);
// frame.setSize(frame.getContentPane().getPreferredSize());
// frame.setVisible(true);
//
// frame.repaint();
// }
// public static GLCanvas createCanvas() {
// final GLProfile profile = GLProfile.get(GLProfile.GL2);
// GLCapabilities capabilities = new GLCapabilities(profile);
//
// final GLCanvas glcanvas = new GLCanvas(capabilities);
// LinesDemo b = new LinesDemo();
// glcanvas.addGLEventListener(b);
//// glcanvas.setSize(screenSize, screenSize);
//
// return glcanvas;
// }
// @Override
protected GLJPanel createDrawable() {
GLCapabilities caps = new GLCapabilities(null);
//
GLJPanel panel = new GLJPanel(caps);
panel.addGLEventListener(this);
panel.addKeyListener(this);
return panel;
}
public void run() {
GLJPanel demo = createDrawable();
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("LinesDemo");
frame.setSize(400, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(demo);
frame.setVisible(true);
demo.requestFocusInWindow();
}
public static void main(String[] args) {
new LinesDemo().run();
}
public void init(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
glu = new GLU();
//
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glShadeModel(GL2.GL_FLAT);
}
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
//
int i;
float coordinateSize = 300;
// gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// gl.glClearColor(1f, 1f, 1f, 1f);
// gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
// gl.glLoadIdentity();
// gl.glOrtho(-coordinateSize, coordinateSize, -coordinateSize, coordinateSize, -1, 1);
/* select white for all LinesDemo */
gl.glColor3f(1.0f, 1.0f, 1.0f);
/* in 1st row, 3 LinesDemo, each with a different stipple */
gl.glEnable(GL2.GL_LINE_STIPPLE);
gl.glEnable(GL2.GL_POINT_SMOOTH);
gl.glBegin(GL2.GL_POINTS);
gl.glPointSize(10e5f);
gl.glVertex2i(200, 200);
gl.glEnd();
gl.glDisable(GL2.GL_POINT_SMOOTH);
gl.glLineStipple(1, (short) 0x0101); /* dotted */
drawOneLine(gl, 50.0f, 125.0f, 150.0f, 125.0f);
gl.glLineStipple(1, (short) 0x00FF); /* dashed */
drawOneLine(gl, 150.0f, 125.0f, 250.0f, 125.0f);
drawOneLine(gl, 150.0f, 125.0f, 250.0f, 200f);
gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */
drawOneLine(gl, 250.0f, 125.0f, 350.0f, 125.0f);
/* in 2nd row, 3 wide LinesDemo, each with different stipple */
gl.glLineWidth(5.0f);
gl.glLineStipple(1, (short) 0x0101); /* dotted */
drawOneLine(gl, 50.0f, 100.0f, 150.0f, 100.f);
gl.glLineStipple(1, (short) 0x00FF); /* dashed */
drawOneLine(gl, 150.0f, 100.0f, 250.0f, 100.0f);
gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */
drawOneLine(gl, 250.0f, 100.0f, 350.0f, 100.0f);
gl.glLineWidth(1.0f);
/* in 3rd row, 6 LinesDemo, with dash/dot/dash stipple */
/* as part of a single connected line strip */
gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */
gl.glBegin(GL.GL_LINE_STRIP);
for (i = 0; i < 7; i++)
gl.glVertex2f(50.0f + ((float) i * 50.0f), 75.0f);
gl.glEnd();
/* in 4th row, 6 independent LinesDemo with same stipple */
for (i = 0; i < 6; i++) {
drawOneLine(gl, 50.0f + ((float) i * 50.0f), 50.0f,
50.0f + ((float) (i + 1) * 50.0f), 50.0f);
}
/* in 5th row, 1 line, with dash/dot/dash stipple */
/* and a stipple repeat factor of 5 */
gl.glLineStipple(5, (short) 0x1C47); /* dash/dot/dash */
drawOneLine(gl, 50.0f, 25.0f, 350.0f, 25.0f);
gl.glDisable(GL2.GL_LINE_STIPPLE);
gl.glFlush();
}
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
GL2 gl = drawable.getGL().getGL2();
//
gl.glViewport(0, 0, w, h);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluOrtho2D(0.0, (double) w, 0.0, (double) h);
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged,
boolean deviceChanged) {
}
private void drawOneLine(GL2 gl, float x1, float y1, float x2, float y2) {
// gl.glBegin(GL.GL_LINES);
gl.glVertex2f((x1), (y1));
gl.glVertex2f((x2), (y2));
// gl.glEnd();
}
public void keyTyped(KeyEvent key) {
}
public void keyPressed(KeyEvent key) {
switch (key.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
System.exit(0);
break;
default:
break;
}
}
public void keyReleased(KeyEvent key) {
}
public void dispose(GLAutoDrawable arg0) {
}
} | Tiofx/semester_6 | CG/src/LinesDemo.java | Java | gpl-3.0 | 6,151 |
<?php
// This file is part of Moodle - http://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 <http://www.gnu.org/licenses/>.
/**
* @package mod
* @subpackage coursework
* @copyright 2011 University of London Computer Centre {@link ulcc.ac.uk}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(__FILE__) . '/../../../../config.php');
global $CFG, $USER;
$submissionid = required_param('submissionid', PARAM_INT);
$cmid = optional_param('cmid', 0, PARAM_INT);
$feedbackid = optional_param('feedbackid', 0, PARAM_INT);
$assessorid = optional_param('assessorid', $USER->id, PARAM_INT);
$stage_identifier = optional_param('stage_identifier', 'uh-oh', PARAM_RAW);
$params = array(
'submissionid' => $submissionid,
'cmid' => $cmid,
'feedbackid' => $feedbackid,
'assessorid' => $assessorid,
'stage_identifier' => $stage_identifier,
);
$controller = new mod_coursework\controllers\feedback_controller($params);
$controller->new_feedback(); | universityofglasgow/moodle | mod/coursework/actions/feedbacks/new.php | PHP | gpl-3.0 | 1,574 |
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ofte.services.MetaDataCreations;
/**
* Servlet implementation class ScheduledTransferRemoteasDestination
*/
@SuppressWarnings("serial")
@WebServlet("/ScheduledTransferRemoteasDestination")
public class ScheduledTransferRemoteasDestination extends HttpServlet {
// private static final long serialVersionUID = 1L;
HashMap<String, String> hashMap = new HashMap<String, String>();
// com.ofte.services.MetaDataCreations metaDataCreations = new
// MetaDataCreations();
MetaDataCreations metaDataCreations = new MetaDataCreations();
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// read form fields
String schedulername = request.getParameter("schedulername");
// String jobName = request.getParameter("jname");
String sourceDirectory = request.getParameter("sd");
String sourceTriggerPattern = request.getParameter("stp");
String sourceFilePattern = request.getParameter("sfp");
String destinationDirectory = request.getParameter("dd");
String destinationFilePattern = request.getParameter("dfp");
String destinationTriggerPattern = request.getParameter("dtp");
String hostIp = request.getParameter("hostip");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String port = request.getParameter("port");
String pollUnits = request.getParameter("pu");
String pollInterval = request.getParameter("pi");
// String XMLFilePath = request.getParameter("xmlfilename");
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("-sn", schedulername);
// hashMap.put("-jn", jobName);
hashMap.put("-sd", sourceDirectory);
hashMap.put("-tr", sourceTriggerPattern);
hashMap.put("-sfp", sourceFilePattern);
hashMap.put("-sftp-d", destinationDirectory);
hashMap.put("-trd", destinationTriggerPattern);
hashMap.put("-hi", hostIp);
hashMap.put("-un", userName);
hashMap.put("-pw", password);
hashMap.put("-po", port);
hashMap.put("-pu", pollUnits);
hashMap.put("-pi", pollInterval);
hashMap.put("-dfp", destinationFilePattern);
// hashMap.put("-gt", XMLFilePath);
// System.out.println(hashMap);
// System.out.println("username: " + username);
// System.out.println("password: " + password);
// String str[] = {"-mn "+monitorName,"-jn "+jobName,"-sd
// "+sourceDirectory,"-tr "+sourceTriggerPattern,"-sfp
// "+sourceFilePattern,"-dd
// "+destinationDirectory,destinationFilePattern,"-trd
// "+destinationTriggerPattern,"-pu "+pollUnits,"-pi "+pollInterval,"-gt
// "+XMLFilePath};
// for(int i=0;i<str.length;i++) {
// System.out.println(str[i]);
// }
try {
// metaDataCreations.fetchingUIDetails(hashMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// String string = "-mn "+monitorName+",-jn "+jobName+",-pi
// "+pollInterval+",-pu "+pollUnits+",-dd "+destinationDirectory+" "+
// sourceDirectory+",-tr "+sourceTriggerPattern+",-trd
// "+destinationTriggerPattern+",-gt "+XMLFilePath+",-sfp
// "+sourceFilePattern;
// FileWriter fileWriter = new FileWriter("D:\\UIDetails.txt");
// fileWriter.write(string);
// fileWriter.close();
Runnable r = new Runnable() {
public void run() {
// runYourBackgroundTaskHere();
try {
metaDataCreations.fetchingUIDetails(hashMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(r).start();
// Example example = new Example();
// hashMap.put("monitorName", monitorName);
// example.result("-mn "+monitorName+" -jn "+jobName+" -pi
// "+pollInterval+" -pu "+pollUnits+" -dd "+destinationDirectory+" "+
// sourceDirectory+" -tr "+sourceTriggerPattern+" -trd
// "+destinationTriggerPattern+" -gt "+XMLFilePath+" -sfp
// "+sourceFilePattern);
// do some processing here...
// get response writer
// PrintWriter writer = response.getWriter();
// build HTML code
// String htmlRespone = "<html>";
// htmlRespone += "<h2>Your username is: " + username + "<br/>";
// htmlRespone += "Your password is: " + password + "</h2>";
// htmlRespone += "</html>";
// return response
// writer.println(htmlRespone);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('successfully submited');");
out.println(
"window.open('http://localhost:8080/TestingUI/Open_OFTE_Scheduled_Transfers_Page.html','_self')");
out.println("</script>");
}
}
| MithunThadi/OFTE | SourceCode/new ofte with del monitor/servlet/ScheduledTransferRemoteasDestination.java | Java | gpl-3.0 | 5,035 |
package xde.lincore.mcscript.math;
public enum RoundingMethod {
Round, Floor, Ceil, CastInt;
public int round(final double value) {
switch (this) {
case Round:
return (int) Math.round(value);
case Floor:
return (int) Math.floor(value);
case Ceil:
return (int) Math.ceil(value);
case CastInt:
return (int) value;
default:
throw new UnsupportedOperationException();
}
}
public long roundToLong(final double value) {
switch (this) {
case Round:
return Math.round(value);
case Floor:
return (long) Math.floor(value);
case Ceil:
return (long) Math.ceil(value);
case CastInt:
return (long) value;
default:
throw new UnsupportedOperationException();
}
}
}
| lincore81/mcscript | ScriptMod/src/xde/lincore/mcscript/math/RoundingMethod.java | Java | gpl-3.0 | 741 |
package com.baselet.gwt.client.view;
import java.util.List;
import com.baselet.control.basics.geom.Rectangle;
import com.baselet.control.config.SharedConfig;
import com.baselet.control.enums.ElementId;
import com.baselet.element.Selector;
import com.baselet.element.interfaces.GridElement;
import com.baselet.gwt.client.element.ComponentGwt;
import com.baselet.gwt.client.element.ElementFactoryGwt;
import com.baselet.gwt.client.resources.HelptextFactory;
import com.baselet.gwt.client.resources.HelptextResources;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.user.client.ui.FocusWidget;
public class DrawCanvas {
private final Canvas canvas = Canvas.createIfSupported();
/*
setScaling can be used to set the size the canvas for the next time draw() is used
DISCLAIMER: if scaling is set to anything other than 1, this WILL break the way selected elements are viewed,
furthermore the dragging will still remain the same and will not update to the new scale.
This function is solely meant to be used for high-res exporting of the diagram
*/
private double scaling = 1.0d;
private boolean scaleHasChangedSinceLastDraw = false;
public void setScaling(double scaling) {
this.scaling = scaling;
scaleHasChangedSinceLastDraw = true;
}
void draw(boolean drawEmptyInfo, List<GridElement> gridElements, Selector selector, boolean forceRedraw) {
if (SharedConfig.getInstance().isDev_mode()) {
CanvasUtils.drawGridOn(getContext2d());
}
if (drawEmptyInfo && gridElements.isEmpty()) {
drawEmptyInfoText(getScaling());
}
else {
// if (tryOptimizedDrawing()) return;
for (GridElement ge : gridElements) {
if (forceRedraw) {
((ComponentGwt) ge.getComponent()).afterModelUpdate();
}
((ComponentGwt) ge.getComponent()).drawOn(getContext2d(), selector.isSelected(ge), getScaling());
}
}
if (selector instanceof SelectorNew && ((SelectorNew) selector).isLassoActive()) {
((SelectorNew) selector).drawLasso(getContext2d());
}
}
public void draw(boolean drawEmptyInfo, List<GridElement> gridElements, Selector selector) {
if (isScaleHasChangedSinceLastDraw()) {
draw(drawEmptyInfo, gridElements, selector, true);
setScaleHasChangedSinceLastDraw(false);
}
else {
draw(drawEmptyInfo, gridElements, selector, false);
}
}
public double getScaling() {
return scaling;
}
public boolean isScaleHasChangedSinceLastDraw() {
return scaleHasChangedSinceLastDraw;
}
public void setScaleHasChangedSinceLastDraw(boolean scaleHasChangedSinceLastDraw) {
this.scaleHasChangedSinceLastDraw = scaleHasChangedSinceLastDraw;
}
public Context2dWrapper getContext2d() {
return new Context2dGwtWrapper(canvas.getContext2d());
}
public void clearAndSetSize(int width, int height) {
// setCoordinateSpace always clears the canvas. To avoid that see https://groups.google.com/d/msg/google-web-toolkit/dpc84mHeKkA/3EKxrlyFCEAJ
canvas.setCoordinateSpaceWidth(width);
canvas.setCoordinateSpaceHeight(height);
}
public String toDataUrl(String type) {
return canvas.toDataUrl(type);
}
public void drawEmptyInfoText(double scaling) {
double elWidth = 440;
double elHeight = 246;
double elXPos = getWidth() / 2.0 - elWidth / 2;
double elYPos = getHeight() / 2.0 - elHeight / 2;
HelptextFactory factory = GWT.create(HelptextFactory.class);
HelptextResources resources = factory.getInstance();
String helptext = resources.helpText().getText();
GridElement emptyElement = ElementFactoryGwt.create(ElementId.Text, new Rectangle(elXPos, elYPos, elWidth, elHeight), helptext, "", null);
((ComponentGwt) emptyElement.getComponent()).drawOn(getContext2d(), false, scaling);
}
/* used to display temporal invalid if vs code passes a wrong uxf */
void drawInvalidDiagramInfo() {
double elWidth = 440;
double elHeight = 246;
double elXPos = getWidth() / 2.0 - elWidth / 2;
double elYPos = getHeight() / 2.0 - elHeight / 2;
String invalidDiagramText = "valign=center\n" +
"halign=center\n" +
".uxf file is currently invalid and can't be displayed.\n" +
"Please revert changes or load a valid file";
GridElement emptyElement = ElementFactoryGwt.create(ElementId.Text, new Rectangle(elXPos, elYPos, elWidth, elHeight), invalidDiagramText, "", null);
((ComponentGwt) emptyElement.getComponent()).drawOn(getContext2d(), false, getScaling());
}
public int getWidth() {
return canvas.getCoordinateSpaceWidth();
}
public int getHeight() {
return canvas.getCoordinateSpaceHeight();
}
public CanvasElement getCanvasElement() {
return canvas.getCanvasElement();
}
public FocusWidget getWidget() {
return canvas;
}
// TODO would not work because canvas gets always resized and therefore cleaned -> so everything must be redrawn
// private boolean tryOptimizedDrawing() {
// List<GridElement> geToRedraw = new ArrayList<GridElement>();
// for (GridElement ge : gridElements) {
// if(((GwtComponent) ge.getComponent()).isRedrawNecessary()) {
// for (GridElement geRedraw : geToRedraw) {
// if (geRedraw.getRectangle().intersects(ge.getRectangle())) {
// return false;
// }
// }
// geToRedraw.add(ge);
// }
// }
//
// for (GridElement ge : gridElements) {
// elementCanvas.getContext2d().clearRect(0, 0, ge.getRectangle().getWidth(), ge.getRectangle().getHeight());
// ((GwtComponent) ge.getComponent()).drawOn(elementCanvas.getContext2d());
// }
// return true;
// }
}
| umlet/umlet | umlet-gwt/src/main/java/com/baselet/gwt/client/view/DrawCanvas.java | Java | gpl-3.0 | 5,538 |
#!/usr/bin/env python
class Message(object):
"""
Base type of a message sent through the pipeline.
Define some attributes and methods to form your message.
I suggest you don't alter this class. You're are free to do so, of course. It's your own decision.
Though, I suggest you create your own message type and let it inherit from this class.
"""
pass
| lumannnn/pypifi | pypifi/message.py | Python | gpl-3.0 | 397 |
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.internal.registry;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An abstract implementation of a factory for internal usage.
*
* @param <E> the element that the factory returns
*/
public abstract class AbstractFactory<E> {
protected final WorldEdit worldEdit;
protected final List<InputParser<E>> parsers = new ArrayList<InputParser<E>>();
/**
* Create a new factory.
*
* @param worldEdit the WorldEdit instance
*/
protected AbstractFactory(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
}
public E parseFromInput(String input, ParserContext context) throws InputParseException {
E match;
for (InputParser<E> parser : parsers) {
match = parser.parseFromInput(input, context);
if (match != null) {
return match;
}
}
throw new NoMatchException("No match for '" + input + "'");
}
}
| UnlimitedFreedom/UF-WorldEdit | worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/AbstractFactory.java | Java | gpl-3.0 | 2,120 |
# Install dependencies of the cloud_controller component
package "libmysqlclient-dev" do
action :install
end
| Altoros/cf-vagrant-installer | chef/cloudfoundry/recipes/cloud_controller.rb | Ruby | gpl-3.0 | 112 |
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CampaignBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Mautic\ApiBundle\Serializer\Driver\ApiMetadataDriver;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use Mautic\FormBundle\Entity\Form;
use Mautic\LeadBundle\Entity\LeadList;
use Mautic\LeadBundle\Form\Validator\Constraints\LeadListAccess;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* Class Campaign
*
* @package Mautic\CampaignBundle\Entity
*/
class Campaign extends FormEntity
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $description;
/**
* @var null|\DateTime
*/
private $publishUp;
/**
* @var null|\DateTime
*/
private $publishDown;
/**
* @var \Mautic\CategoryBundle\Entity\Category
**/
private $category;
/**
* @var ArrayCollection
*/
private $events;
/**
* @var ArrayCollection
*/
private $leads;
/**
* @var ArrayCollection
*/
private $lists;
/**
* @var ArrayCollection
*/
private $forms;
/**
* @var array
*/
private $canvasSettings = array();
/**
* Constructor
*/
public function __construct ()
{
$this->events = new ArrayCollection();
$this->leads = new ArrayCollection();
$this->lists = new ArrayCollection();
$this->forms = new ArrayCollection();
}
/**
*
*/
public function __clone()
{
$this->leads = new ArrayCollection();
$this->events = new ArrayCollection();
$this->lists = new ArrayCollection();
$this->forms = new ArrayCollection();
$this->id = null;
parent::__clone();
}
/**
* @param ORM\ClassMetadata $metadata
*/
public static function loadMetadata (ORM\ClassMetadata $metadata)
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable('campaigns')
->setCustomRepositoryClass('Mautic\CampaignBundle\Entity\CampaignRepository');
$builder->addIdColumns();
$builder->addPublishDates();
$builder->addCategory();
$builder->createOneToMany('events', 'Event')
->setIndexBy('id')
->setOrderBy(array('order' => 'ASC'))
->mappedBy('campaign')
->cascadeAll()
->fetchExtraLazy()
->build();
$builder->createOneToMany('leads', 'Lead')
->setIndexBy('id')
->mappedBy('campaign')
->fetchExtraLazy()
->build();
$builder->createManyToMany('lists', 'Mautic\LeadBundle\Entity\LeadList')
->setJoinTable('campaign_leadlist_xref')
->setIndexBy('id')
->addInverseJoinColumn('leadlist_id', 'id', false, false, 'CASCADE')
->addJoinColumn('campaign_id', 'id', true, false, 'CASCADE')
->build();
$builder->createManyToMany('forms', 'Mautic\FormBundle\Entity\Form')
->setJoinTable('campaign_form_xref')
->setIndexBy('id')
->addInverseJoinColumn('form_id', 'id', false, false, 'CASCADE')
->addJoinColumn('campaign_id', 'id', true, false, 'CASCADE')
->build();
$builder->createField('canvasSettings', 'array')
->columnName('canvas_settings')
->nullable()
->build();
}
/**
* @param ClassMetadata $metadata
*/
public static function loadValidatorMetadata (ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new Assert\NotBlank(array(
'message' => 'mautic.core.name.required'
)));
}
/**
* Prepares the metadata for API usage
*
* @param $metadata
*/
public static function loadApiMetadata(ApiMetadataDriver $metadata)
{
$metadata->setGroupPrefix('campaign')
->addListProperties(
array(
'id',
'name',
'category',
'description'
)
)
->addProperties(
array(
'publishUp',
'publishDown',
'events',
'leads',
'forms',
'lists',
'canvasSettings'
)
)
->build();
}
/**
* @return array
*/
public function convertToArray ()
{
return get_object_vars($this);
}
/**
* @param string $prop
* @param mixed $val
*
* @return void
*/
protected function isChanged ($prop, $val)
{
$getter = "get" . ucfirst($prop);
$current = $this->$getter();
if ($prop == 'category') {
$currentId = ($current) ? $current->getId() : '';
$newId = ($val) ? $val->getId() : null;
if ($currentId != $newId) {
$this->changes[$prop] = array($currentId, $newId);
}
} elseif ($current != $val) {
$this->changes[$prop] = array($current, $val);
}
}
/**
* Get id
*
* @return integer
*/
public function getId ()
{
return $this->id;
}
/**
* Set description
*
* @param string $description
*
* @return Campaign
*/
public function setDescription ($description)
{
$this->isChanged('description', $description);
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription ()
{
return $this->description;
}
/**
* Set name
*
* @param string $name
*
* @return Campaign
*/
public function setName ($name)
{
$this->isChanged('name', $name);
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName ()
{
return $this->name;
}
/**
* Add events
*
* @param $key
* @param \Mautic\CampaignBundle\Entity\Event $event
*
* @return Campaign
*/
public function addEvent ($key, Event $event)
{
if ($changes = $event->getChanges()) {
$this->changes['events']['added'][$key] = array($key, $changes);
}
$this->events[$key] = $event;
return $this;
}
/**
* Remove events
*
* @param \Mautic\CampaignBundle\Entity\Event $event
*/
public function removeEvent (\Mautic\CampaignBundle\Entity\Event $event)
{
$this->changes['events']['removed'][$event->getId()] = $event->getName();
$this->events->removeElement($event);
}
/**
* Get events
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getEvents ()
{
return $this->events;
}
/**
* Set publishUp
*
* @param \DateTime $publishUp
*
* @return Campaign
*/
public function setPublishUp ($publishUp)
{
$this->isChanged('publishUp', $publishUp);
$this->publishUp = $publishUp;
return $this;
}
/**
* Get publishUp
*
* @return \DateTime
*/
public function getPublishUp ()
{
return $this->publishUp;
}
/**
* Set publishDown
*
* @param \DateTime $publishDown
*
* @return Campaign
*/
public function setPublishDown ($publishDown)
{
$this->isChanged('publishDown', $publishDown);
$this->publishDown = $publishDown;
return $this;
}
/**
* Get publishDown
*
* @return \DateTime
*/
public function getPublishDown ()
{
return $this->publishDown;
}
/**
* @return mixed
*/
public function getCategory ()
{
return $this->category;
}
/**
* @param mixed $category
*/
public function setCategory ($category)
{
$this->isChanged('category', $category);
$this->category = $category;
}
/**
* Add lead
*
* @param $key
* @param \Mautic\CampaignBundle\Entity\Lead $lead
*
* @return Campaign
*/
public function addLead ($key, Lead $lead)
{
$action = ($this->leads->contains($lead)) ? 'updated' : 'added';
$leadEntity = $lead->getLead();
$this->changes['leads'][$action][$leadEntity->getId()] = $leadEntity->getPrimaryIdentifier();
$this->leads[$key] = $lead;
return $this;
}
/**
* Remove lead
*
* @param Lead $lead
*/
public function removeLead (Lead $lead)
{
$leadEntity = $lead->getLead();
$this->changes['leads']['removed'][$leadEntity->getId()] = $leadEntity->getPrimaryIdentifier();
$this->leads->removeElement($lead);
}
/**
* Get leads
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getLeads ()
{
return $this->leads;
}
/**
* @return ArrayCollection
*/
public function getLists ()
{
return $this->lists;
}
/**
* Add list
*
* @param LeadList $list
* @return Campaign
*/
public function addList(LeadList $list)
{
$this->lists[] = $list;
$this->changes['lists']['added'][$list->getId()] = $list->getName();
return $this;
}
/**
* Remove list
*
* @param LeadList $list
*/
public function removeList(LeadList $list)
{
$this->changes['lists']['removed'][$list->getId()] = $list->getName();
$this->lists->removeElement($list);
}
/**
* @return ArrayCollection
*/
public function getForms()
{
return $this->forms;
}
/**
* Add form
*
* @param Form $form
*
* @return Campaign
*/
public function addForm(Form $form)
{
$this->forms[] = $form;
$this->changes['forms']['added'][$form->getId()] = $form->getName();
return $this;
}
/**
* Remove form
*
* @param Form $form
*/
public function removeForm(Form $form)
{
$this->changes['forms']['removed'][$form->getId()] = $form->getName();
$this->forms->removeElement($form);
}
/**
* @return mixed
*/
public function getCanvasSettings ()
{
return $this->canvasSettings;
}
/**
* @param array $canvasSettings
*/
public function setCanvasSettings (array $canvasSettings)
{
$this->canvasSettings = $canvasSettings;
}
}
| mqueme/mautic | app/bundles/CampaignBundle/Entity/Campaign.php | PHP | gpl-3.0 | 11,416 |
package com.derpgroup.livefinder.manager;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class TwitchFollowedStreamsResponse {
private TwitchStream[] streams;
public TwitchStream[] getStreams() {
return streams.clone();
}
public void setStreams(TwitchStream[] streams) {
this.streams = streams.clone();
}
@Override
public String toString() {
return "TwitchFollowedStreamsResponse [streams=" + Arrays.toString(streams)
+ "]";
}
}
| DERP-Group/LiveFinder | service/src/main/java/com/derpgroup/livefinder/manager/TwitchFollowedStreamsResponse.java | Java | gpl-3.0 | 563 |
// Copyright 2015 ThoughtWorks, Inc.
//
// This file is part of Gauge-CSharp.
//
// Gauge-CSharp 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.
//
// Gauge-CSharp 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 Gauge-CSharp. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using Gauge.CSharp.Lib;
using Gauge.CSharp.Runner.Models;
using Gauge.CSharp.Runner.Strategy;
namespace Gauge.CSharp.Runner
{
public interface ISandbox
{
// Used only from tests.
// Don't return Assembly here! assembly instance returned on sandbox side
// would be replaced by assembly instance on runner side, thus making any asserts on it useless.
string TargetLibAssemblyVersion { get; }
ExecutionResult ExecuteMethod(GaugeMethod gaugeMethod, params string[] args);
bool TryScreenCapture(out byte[] screenShotBytes);
List<GaugeMethod> GetStepMethods();
void InitializeDataStore(string dataStoreType);
IEnumerable<string> GetStepTexts(GaugeMethod gaugeMethod);
List<string> GetAllStepTexts();
void ClearObjectCache();
IEnumerable<string> GetAllPendingMessages();
IEnumerable<byte[]> GetAllPendingScreenshots();
void StartExecutionScope(string tag);
void CloseExectionScope();
ExecutionResult ExecuteHooks(string hookType, IHooksStrategy strategy, IList<string> applicableTags, object executionContext);
IEnumerable<string> Refactor(GaugeMethod methodInfo, IList<Tuple<int, int>> parameterPositions,
IList<string> parametersList, string newStepValue);
}
} | getgauge/gauge-csharp | Runner/ISandbox.cs | C# | gpl-3.0 | 2,096 |
<?php
/*
* This file is part of PHP-FFmpeg.
*
* (c) Alchemy <info@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FFMpeg\Media;
use Alchemy\BinaryDriver\Exception\ExecutionFailureException;
use FFMpeg\Filters\Audio\AudioFilters;
use FFMpeg\Format\FormatInterface;
use FFMpeg\Filters\Audio\SimpleFilter;
use FFMpeg\Exception\RuntimeException;
use FFMpeg\Exception\InvalidArgumentException;
use FFMpeg\Filters\Audio\AudioFilterInterface;
use FFMpeg\Filters\FilterInterface;
use FFMpeg\Format\ProgressableInterface;
class Audio extends AbstractStreamableMedia
{
/**
* {@inheritdoc}
*
* @return AudioFilters
*/
public function filters()
{
return new AudioFilters($this);
}
/**
* {@inheritdoc}
*
* @return Audio
*/
public function addFilter(FilterInterface $filter)
{
if (!$filter instanceof AudioFilterInterface) {
throw new InvalidArgumentException('Audio only accepts AudioFilterInterface filters');
}
$this->filters->add($filter);
return $this;
}
/**
* Exports the audio in the desired format, applies registered filters.
*
* @param FormatInterface $format
* @param string $outputPathfile
* @return Audio
* @throws RuntimeException
*/
public function save(FormatInterface $format, $outputPathfile)
{
$listeners = null;
if ($format instanceof ProgressableInterface) {
$listeners = $format->createProgressListener($this, $this->ffprobe, 1, 1, 0);
}
$commands = $this->buildCommand($format, $outputPathfile);
try {
$this->driver->command($commands, false, $listeners);
} catch (ExecutionFailureException $e) {
$this->cleanupTemporaryFile($outputPathfile);
throw new RuntimeException('Encoding failed', $e->getCode(), $e);
}
return $this;
}
/**
* Returns the final command as a string, useful for debugging purposes.
*
* @param FormatInterface $format
* @param string $outputPathfile
* @return string
* @since 0.11.0
*/
public function getFinalCommand(FormatInterface $format, $outputPathfile) {
return implode(' ', $this->buildCommand($format, $outputPathfile));
}
/**
* Builds the command which will be executed with the provided format
*
* @param FormatInterface $format
* @param string $outputPathfile
* @return string[] An array which are the components of the command
* @since 0.11.0
*/
protected function buildCommand(FormatInterface $format, $outputPathfile) {
$commands = array('-y', '-i', $this->pathfile);
$filters = clone $this->filters;
$filters->add(new SimpleFilter($format->getExtraParams(), 10));
if ($this->driver->getConfiguration()->has('ffmpeg.threads')) {
$filters->add(new SimpleFilter(array('-threads', $this->driver->getConfiguration()->get('ffmpeg.threads'))));
}
if (null !== $format->getAudioCodec()) {
$filters->add(new SimpleFilter(array('-acodec', $format->getAudioCodec())));
}
foreach ($filters as $filter) {
$commands = array_merge($commands, $filter->apply($this, $format));
}
if (null !== $format->getAudioKiloBitrate()) {
$commands[] = '-b:a';
$commands[] = $format->getAudioKiloBitrate() . 'k';
}
if (null !== $format->getAudioChannels()) {
$commands[] = '-ac';
$commands[] = $format->getAudioChannels();
}
$commands[] = $outputPathfile;
return $commands;
}
/**
* Gets the waveform of the video.
*
* @param integer $width
* @param integer $height
* @param array $colors Array of colors for ffmpeg to use. Color format is #000000 (RGB hex string with #)
* @return Waveform
*/
public function waveform($width = 640, $height = 120, $colors = array(Waveform::DEFAULT_COLOR))
{
return new Waveform($this, $this->driver, $this->ffprobe, $width, $height, $colors);
}
/**
* Concatenates a list of audio files into one unique audio file.
*
* @param array $sources
* @return Concat
*/
public function concat($sources)
{
return new Concat($sources, $this->driver, $this->ffprobe);
}
}
| vfremaux/moodle-mod_mplayer | extralib/PHP-FFMpeg-master/src/FFMpeg/Media/Audio.php | PHP | gpl-3.0 | 4,582 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import itertools
import json
import erpnext
import frappe
import copy
from erpnext.controllers.item_variant import (ItemVariantExistsError,
copy_attributes_to_variant, get_variant, make_variant_item_code, validate_item_variant_attributes)
from erpnext.setup.doctype.item_group.item_group import (get_parent_item_groups, invalidate_cache_for)
from frappe import _, msgprint
from frappe.utils import (cint, cstr, flt, formatdate, get_timestamp, getdate,
now_datetime, random_string, strip)
from frappe.utils.html_utils import clean_html
from frappe.website.doctype.website_slideshow.website_slideshow import \
get_slideshow
from frappe.website.render import clear_cache
from frappe.website.website_generator import WebsiteGenerator
from six import iteritems
class DuplicateReorderRows(frappe.ValidationError):
pass
class StockExistsForTemplate(frappe.ValidationError):
pass
class InvalidBarcode(frappe.ValidationError):
pass
class Item(WebsiteGenerator):
website = frappe._dict(
page_title_field="item_name",
condition_field="show_in_website",
template="templates/generators/item.html",
no_cache=1
)
def onload(self):
super(Item, self).onload()
self.set_onload('stock_exists', self.stock_ledger_created())
self.set_asset_naming_series()
def set_asset_naming_series(self):
if not hasattr(self, '_asset_naming_series'):
from erpnext.assets.doctype.asset.asset import get_asset_naming_series
self._asset_naming_series = get_asset_naming_series()
self.set_onload('asset_naming_series', self._asset_naming_series)
def autoname(self):
if frappe.db.get_default("item_naming_by") == "Naming Series":
if self.variant_of:
if not self.item_code:
template_item_name = frappe.db.get_value("Item", self.variant_of, "item_name")
self.item_code = make_variant_item_code(self.variant_of, template_item_name, self)
else:
from frappe.model.naming import set_name_by_naming_series
set_name_by_naming_series(self)
self.item_code = self.name
self.item_code = strip(self.item_code)
self.name = self.item_code
def before_insert(self):
if not self.description:
self.description = self.item_name
# if self.is_sales_item and not self.get('is_item_from_hub'):
# self.publish_in_hub = 1
def after_insert(self):
'''set opening stock and item price'''
if self.standard_rate:
for default in self.item_defaults:
self.add_price(default.default_price_list)
if self.opening_stock:
self.set_opening_stock()
def validate(self):
self.get_doc_before_save()
super(Item, self).validate()
if not self.item_name:
self.item_name = self.item_code
if not self.description:
self.description = self.item_name
self.validate_uom()
self.validate_description()
self.add_default_uom_in_conversion_factor_table()
self.validate_conversion_factor()
self.validate_item_type()
self.check_for_active_boms()
self.fill_customer_code()
self.check_item_tax()
self.validate_barcode()
self.validate_warehouse_for_reorder()
self.update_bom_item_desc()
self.synced_with_hub = 0
self.validate_has_variants()
self.validate_stock_exists_for_template_item()
self.validate_attributes()
self.validate_variant_attributes()
self.validate_variant_based_on_change()
self.validate_website_image()
self.make_thumbnail()
self.validate_fixed_asset()
self.validate_retain_sample()
self.validate_uom_conversion_factor()
self.validate_item_defaults()
self.update_defaults_from_item_group()
self.validate_stock_for_has_batch_and_has_serial()
if not self.get("__islocal"):
self.old_item_group = frappe.db.get_value(self.doctype, self.name, "item_group")
self.old_website_item_groups = frappe.db.sql_list("""select item_group
from `tabWebsite Item Group`
where parentfield='website_item_groups' and parenttype='Item' and parent=%s""", self.name)
def on_update(self):
invalidate_cache_for_item(self)
self.validate_name_with_item_group()
self.update_variants()
self.update_item_price()
self.update_template_item()
def validate_description(self):
'''Clean HTML description if set'''
if cint(frappe.db.get_single_value('Stock Settings', 'clean_description_html')):
self.description = clean_html(self.description)
def add_price(self, price_list=None):
'''Add a new price'''
if not price_list:
price_list = (frappe.db.get_single_value('Selling Settings', 'selling_price_list')
or frappe.db.get_value('Price List', _('Standard Selling')))
if price_list:
item_price = frappe.get_doc({
"doctype": "Item Price",
"price_list": price_list,
"item_code": self.name,
"currency": erpnext.get_default_currency(),
"price_list_rate": self.standard_rate
})
item_price.insert()
def set_opening_stock(self):
'''set opening stock'''
if not self.is_stock_item or self.has_serial_no or self.has_batch_no:
return
if not self.valuation_rate and self.standard_rate:
self.valuation_rate = self.standard_rate
if not self.valuation_rate:
frappe.throw(_("Valuation Rate is mandatory if Opening Stock entered"))
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
# default warehouse, or Stores
for default in self.item_defaults:
default_warehouse = (default.default_warehouse
or frappe.db.get_single_value('Stock Settings', 'default_warehouse')
or frappe.db.get_value('Warehouse', {'warehouse_name': _('Stores')}))
if default_warehouse:
stock_entry = make_stock_entry(item_code=self.name, target=default_warehouse, qty=self.opening_stock,
rate=self.valuation_rate, company=default.company)
stock_entry.add_comment("Comment", _("Opening Stock"))
def make_route(self):
if not self.route:
return cstr(frappe.db.get_value('Item Group', self.item_group,
'route')) + '/' + self.scrub((self.item_name if self.item_name else self.item_code) + '-' + random_string(5))
def validate_website_image(self):
if frappe.flags.in_import:
return
"""Validate if the website image is a public file"""
auto_set_website_image = False
if not self.website_image and self.image:
auto_set_website_image = True
self.website_image = self.image
if not self.website_image:
return
# find if website image url exists as public
file_doc = frappe.get_all("File", filters={
"file_url": self.website_image
}, fields=["name", "is_private"], order_by="is_private asc", limit_page_length=1)
if file_doc:
file_doc = file_doc[0]
if not file_doc:
if not auto_set_website_image:
frappe.msgprint(_("Website Image {0} attached to Item {1} cannot be found").format(self.website_image, self.name))
self.website_image = None
elif file_doc.is_private:
if not auto_set_website_image:
frappe.msgprint(_("Website Image should be a public file or website URL"))
self.website_image = None
def make_thumbnail(self):
if frappe.flags.in_import:
return
"""Make a thumbnail of `website_image`"""
import requests.exceptions
if not self.is_new() and self.website_image != frappe.db.get_value(self.doctype, self.name, "website_image"):
self.thumbnail = None
if self.website_image and not self.thumbnail:
file_doc = None
try:
file_doc = frappe.get_doc("File", {
"file_url": self.website_image,
"attached_to_doctype": "Item",
"attached_to_name": self.name
})
except frappe.DoesNotExistError:
pass
# cleanup
frappe.local.message_log.pop()
except requests.exceptions.HTTPError:
frappe.msgprint(_("Warning: Invalid attachment {0}").format(self.website_image))
self.website_image = None
except requests.exceptions.SSLError:
frappe.msgprint(
_("Warning: Invalid SSL certificate on attachment {0}").format(self.website_image))
self.website_image = None
# for CSV import
if self.website_image and not file_doc:
try:
file_doc = frappe.get_doc({
"doctype": "File",
"file_url": self.website_image,
"attached_to_doctype": "Item",
"attached_to_name": self.name
}).insert()
except IOError:
self.website_image = None
if file_doc:
if not file_doc.thumbnail_url:
file_doc.make_thumbnail()
self.thumbnail = file_doc.thumbnail_url
def validate_fixed_asset(self):
if self.is_fixed_asset:
if self.is_stock_item:
frappe.throw(_("Fixed Asset Item must be a non-stock item."))
if not self.asset_category:
frappe.throw(_("Asset Category is mandatory for Fixed Asset item"))
if self.stock_ledger_created():
frappe.throw(_("Cannot be a fixed asset item as Stock Ledger is created."))
if not self.is_fixed_asset:
asset = frappe.db.get_all("Asset", filters={"item_code": self.name, "docstatus": 1}, limit=1)
if asset:
frappe.throw(_('"Is Fixed Asset" cannot be unchecked, as Asset record exists against the item'))
def validate_retain_sample(self):
if self.retain_sample and not frappe.db.get_single_value('Stock Settings', 'sample_retention_warehouse'):
frappe.throw(_("Please select Sample Retention Warehouse in Stock Settings first"))
if self.retain_sample and not self.has_batch_no:
frappe.throw(_(" {0} Retain Sample is based on batch, please check Has Batch No to retain sample of item").format(
self.item_code))
def get_context(self, context):
context.show_search = True
context.search_link = '/product_search'
context.parents = get_parent_item_groups(self.item_group)
self.set_variant_context(context)
self.set_attribute_context(context)
self.set_disabled_attributes(context)
return context
def set_variant_context(self, context):
if self.has_variants:
context.no_cache = True
# load variants
# also used in set_attribute_context
context.variants = frappe.get_all("Item",
filters={"variant_of": self.name, "show_variant_in_website": 1},
order_by="name asc")
variant = frappe.form_dict.variant
if not variant and context.variants:
# the case when the item is opened for the first time from its list
variant = context.variants[0]
if variant:
context.variant = frappe.get_doc("Item", variant)
for fieldname in ("website_image", "web_long_description", "description",
"website_specifications"):
if context.variant.get(fieldname):
value = context.variant.get(fieldname)
if isinstance(value, list):
value = [d.as_dict() for d in value]
context[fieldname] = value
if self.slideshow:
if context.variant and context.variant.slideshow:
context.update(get_slideshow(context.variant))
else:
context.update(get_slideshow(self))
def set_attribute_context(self, context):
if self.has_variants:
attribute_values_available = {}
context.attribute_values = {}
context.selected_attributes = {}
# load attributes
for v in context.variants:
v.attributes = frappe.get_all("Item Variant Attribute",
fields=["attribute", "attribute_value"],
filters={"parent": v.name})
for attr in v.attributes:
values = attribute_values_available.setdefault(attr.attribute, [])
if attr.attribute_value not in values:
values.append(attr.attribute_value)
if v.name == context.variant.name:
context.selected_attributes[attr.attribute] = attr.attribute_value
# filter attributes, order based on attribute table
for attr in self.attributes:
values = context.attribute_values.setdefault(attr.attribute, [])
if cint(frappe.db.get_value("Item Attribute", attr.attribute, "numeric_values")):
for val in sorted(attribute_values_available.get(attr.attribute, []), key=flt):
values.append(val)
else:
# get list of values defined (for sequence)
for attr_value in frappe.db.get_all("Item Attribute Value",
fields=["attribute_value"],
filters={"parent": attr.attribute}, order_by="idx asc"):
if attr_value.attribute_value in attribute_values_available.get(attr.attribute, []):
values.append(attr_value.attribute_value)
context.variant_info = json.dumps(context.variants)
def set_disabled_attributes(self, context):
"""Disable selection options of attribute combinations that do not result in a variant"""
if not self.attributes or not self.has_variants:
return
context.disabled_attributes = {}
attributes = [attr.attribute for attr in self.attributes]
def find_variant(combination):
for variant in context.variants:
if len(variant.attributes) < len(attributes):
continue
if "combination" not in variant:
ref_combination = []
for attr in variant.attributes:
idx = attributes.index(attr.attribute)
ref_combination.insert(idx, attr.attribute_value)
variant["combination"] = ref_combination
if not (set(combination) - set(variant["combination"])):
# check if the combination is a subset of a variant combination
# eg. [Blue, 0.5] is a possible combination if exists [Blue, Large, 0.5]
return True
for i, attr in enumerate(self.attributes):
if i == 0:
continue
combination_source = []
# loop through previous attributes
for prev_attr in self.attributes[:i]:
combination_source.append([context.selected_attributes.get(prev_attr.attribute)])
combination_source.append(context.attribute_values[attr.attribute])
for combination in itertools.product(*combination_source):
if not find_variant(combination):
context.disabled_attributes.setdefault(attr.attribute, []).append(combination[-1])
def add_default_uom_in_conversion_factor_table(self):
uom_conv_list = [d.uom for d in self.get("uoms")]
if self.stock_uom not in uom_conv_list:
ch = self.append('uoms', {})
ch.uom = self.stock_uom
ch.conversion_factor = 1
to_remove = []
for d in self.get("uoms"):
if d.conversion_factor == 1 and d.uom != self.stock_uom:
to_remove.append(d)
[self.remove(d) for d in to_remove]
def update_template_tables(self):
template = frappe.get_doc("Item", self.variant_of)
# add item taxes from template
for d in template.get("taxes"):
self.append("taxes", {"tax_type": d.tax_type, "tax_rate": d.tax_rate})
# copy re-order table if empty
if not self.get("reorder_levels"):
for d in template.get("reorder_levels"):
n = {}
for k in ("warehouse", "warehouse_reorder_level",
"warehouse_reorder_qty", "material_request_type"):
n[k] = d.get(k)
self.append("reorder_levels", n)
def validate_conversion_factor(self):
check_list = []
for d in self.get('uoms'):
if cstr(d.uom) in check_list:
frappe.throw(
_("Unit of Measure {0} has been entered more than once in Conversion Factor Table").format(d.uom))
else:
check_list.append(cstr(d.uom))
if d.uom and cstr(d.uom) == cstr(self.stock_uom) and flt(d.conversion_factor) != 1:
frappe.throw(
_("Conversion factor for default Unit of Measure must be 1 in row {0}").format(d.idx))
def validate_item_type(self):
if self.has_serial_no == 1 and self.is_stock_item == 0 and not self.is_fixed_asset:
msgprint(_("'Has Serial No' can not be 'Yes' for non-stock item"), raise_exception=1)
if self.has_serial_no == 0 and self.serial_no_series:
self.serial_no_series = None
def check_for_active_boms(self):
if self.default_bom:
bom_item = frappe.db.get_value("BOM", self.default_bom, "item")
if bom_item not in (self.name, self.variant_of):
frappe.throw(
_("Default BOM ({0}) must be active for this item or its template").format(bom_item))
def fill_customer_code(self):
""" Append all the customer codes and insert into "customer_code" field of item table """
cust_code = []
for d in self.get('customer_items'):
cust_code.append(d.ref_code)
self.customer_code = ','.join(cust_code)
def check_item_tax(self):
"""Check whether Tax Rate is not entered twice for same Tax Type"""
check_list = []
for d in self.get('taxes'):
if d.tax_type:
account_type = frappe.db.get_value("Account", d.tax_type, "account_type")
if account_type not in ['Tax', 'Chargeable', 'Income Account', 'Expense Account']:
frappe.throw(
_("Item Tax Row {0} must have account of type Tax or Income or Expense or Chargeable").format(d.idx))
else:
if d.tax_type in check_list:
frappe.throw(_("{0} entered twice in Item Tax").format(d.tax_type))
else:
check_list.append(d.tax_type)
def validate_barcode(self):
from stdnum import ean
if len(self.barcodes) > 0:
for item_barcode in self.barcodes:
options = frappe.get_meta("Item Barcode").get_options("barcode_type").split('\n')
if item_barcode.barcode:
duplicate = frappe.db.sql(
"""select parent from `tabItem Barcode` where barcode = %s and parent != %s""", (item_barcode.barcode, self.name))
if duplicate:
frappe.throw(_("Barcode {0} already used in Item {1}").format(
item_barcode.barcode, duplicate[0][0]), frappe.DuplicateEntryError)
item_barcode.barcode_type = "" if item_barcode.barcode_type not in options else item_barcode.barcode_type
if item_barcode.barcode_type and item_barcode.barcode_type.upper() in ('EAN', 'UPC-A', 'EAN-13', 'EAN-8'):
if not ean.is_valid(item_barcode.barcode):
frappe.throw(_("Barcode {0} is not a valid {1} code").format(
item_barcode.barcode, item_barcode.barcode_type), InvalidBarcode)
def validate_warehouse_for_reorder(self):
'''Validate Reorder level table for duplicate and conditional mandatory'''
warehouse = []
for d in self.get("reorder_levels"):
if not d.warehouse_group:
d.warehouse_group = d.warehouse
if d.get("warehouse") and d.get("warehouse") not in warehouse:
warehouse += [d.get("warehouse")]
else:
frappe.throw(_("Row {0}: An Reorder entry already exists for this warehouse {1}")
.format(d.idx, d.warehouse), DuplicateReorderRows)
if d.warehouse_reorder_level and not d.warehouse_reorder_qty:
frappe.throw(_("Row #{0}: Please set reorder quantity").format(d.idx))
def stock_ledger_created(self):
if not hasattr(self, '_stock_ledger_created'):
self._stock_ledger_created = len(frappe.db.sql("""select name from `tabStock Ledger Entry`
where item_code = %s limit 1""", self.name))
return self._stock_ledger_created
def validate_name_with_item_group(self):
# causes problem with tree build
if frappe.db.exists("Item Group", self.name):
frappe.throw(
_("An Item Group exists with same name, please change the item name or rename the item group"))
def update_item_price(self):
frappe.db.sql("""update `tabItem Price` set item_name=%s,
item_description=%s, brand=%s where item_code=%s""",
(self.item_name, self.description, self.brand, self.name))
def on_trash(self):
super(Item, self).on_trash()
frappe.db.sql("""delete from tabBin where item_code=%s""", self.name)
frappe.db.sql("delete from `tabItem Price` where item_code=%s", self.name)
for variant_of in frappe.get_all("Item", filters={"variant_of": self.name}):
frappe.delete_doc("Item", variant_of.name)
def before_rename(self, old_name, new_name, merge=False):
if self.item_name == old_name:
frappe.db.set_value("Item", old_name, "item_name", new_name)
if merge:
# Validate properties before merging
if not frappe.db.exists("Item", new_name):
frappe.throw(_("Item {0} does not exist").format(new_name))
field_list = ["stock_uom", "is_stock_item", "has_serial_no", "has_batch_no"]
new_properties = [cstr(d) for d in frappe.db.get_value("Item", new_name, field_list)]
if new_properties != [cstr(self.get(fld)) for fld in field_list]:
frappe.throw(_("To merge, following properties must be same for both items")
+ ": \n" + ", ".join([self.meta.get_label(fld) for fld in field_list]))
def after_rename(self, old_name, new_name, merge):
if self.route:
invalidate_cache_for_item(self)
clear_cache(self.route)
frappe.db.set_value("Item", new_name, "item_code", new_name)
if merge:
self.set_last_purchase_rate(new_name)
self.recalculate_bin_qty(new_name)
for dt in ("Sales Taxes and Charges", "Purchase Taxes and Charges"):
for d in frappe.db.sql("""select name, item_wise_tax_detail from `tab{0}`
where ifnull(item_wise_tax_detail, '') != ''""".format(dt), as_dict=1):
item_wise_tax_detail = json.loads(d.item_wise_tax_detail)
if isinstance(item_wise_tax_detail, dict) and old_name in item_wise_tax_detail:
item_wise_tax_detail[new_name] = item_wise_tax_detail[old_name]
item_wise_tax_detail.pop(old_name)
frappe.db.set_value(dt, d.name, "item_wise_tax_detail",
json.dumps(item_wise_tax_detail), update_modified=False)
def set_last_purchase_rate(self, new_name):
last_purchase_rate = get_last_purchase_details(new_name).get("base_rate", 0)
frappe.db.set_value("Item", new_name, "last_purchase_rate", last_purchase_rate)
def recalculate_bin_qty(self, new_name):
from erpnext.stock.stock_balance import repost_stock
frappe.db.auto_commit_on_many_writes = 1
existing_allow_negative_stock = frappe.db.get_value("Stock Settings", None, "allow_negative_stock")
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
repost_stock_for_warehouses = frappe.db.sql_list("""select distinct warehouse
from tabBin where item_code=%s""", new_name)
# Delete all existing bins to avoid duplicate bins for the same item and warehouse
frappe.db.sql("delete from `tabBin` where item_code=%s", new_name)
for warehouse in repost_stock_for_warehouses:
repost_stock(new_name, warehouse)
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", existing_allow_negative_stock)
frappe.db.auto_commit_on_many_writes = 0
def copy_specification_from_item_group(self):
self.set("website_specifications", [])
if self.item_group:
for label, desc in frappe.db.get_values("Item Website Specification",
{"parent": self.item_group}, ["label", "description"]):
row = self.append("website_specifications")
row.label = label
row.description = desc
def update_bom_item_desc(self):
if self.is_new():
return
if self.db_get('description') != self.description:
frappe.db.sql("""
update `tabBOM`
set description = %s
where item = %s and docstatus < 2
""", (self.description, self.name))
frappe.db.sql("""
update `tabBOM Item`
set description = %s
where item_code = %s and docstatus < 2
""", (self.description, self.name))
frappe.db.sql("""
update `tabBOM Explosion Item`
set description = %s
where item_code = %s and docstatus < 2
""", (self.description, self.name))
def update_template_item(self):
"""Set Show in Website for Template Item if True for its Variant"""
if self.variant_of:
if self.show_in_website:
self.show_variant_in_website = 1
self.show_in_website = 0
if self.show_variant_in_website:
# show template
template_item = frappe.get_doc("Item", self.variant_of)
if not template_item.show_in_website:
template_item.show_in_website = 1
template_item.flags.dont_update_variants = True
template_item.flags.ignore_permissions = True
template_item.save()
def validate_item_defaults(self):
companies = list(set([row.company for row in self.item_defaults]))
if len(companies) != len(self.item_defaults):
frappe.throw(_("Cannot set multiple Item Defaults for a company."))
def update_defaults_from_item_group(self):
"""Get defaults from Item Group"""
if self.item_group and not self.item_defaults:
item_defaults = frappe.db.get_values("Item Default", {"parent": self.item_group},
['company', 'default_warehouse','default_price_list','buying_cost_center','default_supplier',
'expense_account','selling_cost_center','income_account'], as_dict = 1)
if item_defaults:
for item in item_defaults:
self.append('item_defaults', {
'company': item.company,
'default_warehouse': item.default_warehouse,
'default_price_list': item.default_price_list,
'buying_cost_center': item.buying_cost_center,
'default_supplier': item.default_supplier,
'expense_account': item.expense_account,
'selling_cost_center': item.selling_cost_center,
'income_account': item.income_account
})
else:
warehouse = ''
defaults = frappe.defaults.get_defaults() or {}
# To check default warehouse is belong to the default company
if defaults.get("default_warehouse") and frappe.db.exists("Warehouse",
{'name': defaults.default_warehouse, 'company': defaults.company}):
warehouse = defaults.default_warehouse
self.append("item_defaults", {
"company": defaults.get("company"),
"default_warehouse": warehouse
})
def update_variants(self):
if self.flags.dont_update_variants or \
frappe.db.get_single_value('Item Variant Settings', 'do_not_update_variants'):
return
if self.has_variants:
variants = frappe.db.get_all("Item", fields=["item_code"], filters={"variant_of": self.name})
if variants:
if len(variants) <= 30:
update_variants(variants, self, publish_progress=False)
frappe.msgprint(_("Item Variants updated"))
else:
frappe.enqueue("erpnext.stock.doctype.item.item.update_variants",
variants=variants, template=self, now=frappe.flags.in_test, timeout=600)
def validate_has_variants(self):
if not self.has_variants and frappe.db.get_value("Item", self.name, "has_variants"):
if frappe.db.exists("Item", {"variant_of": self.name}):
frappe.throw(_("Item has variants."))
def validate_stock_exists_for_template_item(self):
if self.stock_ledger_created() and self._doc_before_save:
if (cint(self._doc_before_save.has_variants) != cint(self.has_variants)
or self._doc_before_save.variant_of != self.variant_of):
frappe.throw(_("Cannot change Variant properties after stock transaction. You will have to make a new Item to do this.").format(self.name),
StockExistsForTemplate)
if self.has_variants or self.variant_of:
if not self.is_child_table_same('attributes'):
frappe.throw(
_('Cannot change Attributes after stock transaction. Make a new Item and transfer stock to the new Item'))
def validate_variant_based_on_change(self):
if not self.is_new() and (self.variant_of or (self.has_variants and frappe.get_all("Item", {"variant_of": self.name}))):
if self.variant_based_on != frappe.db.get_value("Item", self.name, "variant_based_on"):
frappe.throw(_("Variant Based On cannot be changed"))
def validate_uom(self):
if not self.get("__islocal"):
check_stock_uom_with_bin(self.name, self.stock_uom)
if self.has_variants:
for d in frappe.db.get_all("Item", filters={"variant_of": self.name}):
check_stock_uom_with_bin(d.name, self.stock_uom)
if self.variant_of:
template_uom = frappe.db.get_value("Item", self.variant_of, "stock_uom")
if template_uom != self.stock_uom:
frappe.throw(_("Default Unit of Measure for Variant '{0}' must be same as in Template '{1}'")
.format(self.stock_uom, template_uom))
def validate_uom_conversion_factor(self):
if self.uoms:
for d in self.uoms:
value = get_uom_conv_factor(d.uom, self.stock_uom)
if value:
d.conversion_factor = value
def validate_attributes(self):
if not (self.has_variants or self.variant_of):
return
if not self.variant_based_on:
self.variant_based_on = 'Item Attribute'
if self.variant_based_on == 'Item Attribute':
attributes = []
if not self.attributes:
frappe.throw(_("Attribute table is mandatory"))
for d in self.attributes:
if d.attribute in attributes:
frappe.throw(
_("Attribute {0} selected multiple times in Attributes Table".format(d.attribute)))
else:
attributes.append(d.attribute)
def validate_variant_attributes(self):
if self.is_new() and self.variant_of and self.variant_based_on == 'Item Attribute':
args = {}
for d in self.attributes:
if cstr(d.attribute_value).strip() == '':
frappe.throw(_("Please specify Attribute Value for attribute {0}").format(d.attribute))
args[d.attribute] = d.attribute_value
variant = get_variant(self.variant_of, args, self.name)
if variant:
frappe.throw(_("Item variant {0} exists with same attributes")
.format(variant), ItemVariantExistsError)
validate_item_variant_attributes(self, args)
def validate_stock_for_has_batch_and_has_serial(self):
if self.stock_ledger_created():
for value in ["has_batch_no", "has_serial_no"]:
if frappe.db.get_value("Item", self.name, value) != self.get_value(value):
frappe.throw(_("Cannot change {0} as Stock Transaction for Item {1} exist.".format(value, self.name)))
def get_timeline_data(doctype, name):
'''returns timeline data based on stock ledger entry'''
out = {}
items = dict(frappe.db.sql('''select posting_date, count(*)
from `tabStock Ledger Entry` where item_code=%s
and posting_date > date_sub(curdate(), interval 1 year)
group by posting_date''', name))
for date, count in iteritems(items):
timestamp = get_timestamp(date)
out.update({timestamp: count})
return out
def validate_end_of_life(item_code, end_of_life=None, disabled=None, verbose=1):
if (not end_of_life) or (disabled is None):
end_of_life, disabled = frappe.db.get_value("Item", item_code, ["end_of_life", "disabled"])
if end_of_life and end_of_life != "0000-00-00" and getdate(end_of_life) <= now_datetime().date():
msg = _("Item {0} has reached its end of life on {1}").format(item_code, formatdate(end_of_life))
_msgprint(msg, verbose)
if disabled:
_msgprint(_("Item {0} is disabled").format(item_code), verbose)
def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
if not is_stock_item:
is_stock_item = frappe.db.get_value("Item", item_code, "is_stock_item")
if is_stock_item != 1:
msg = _("Item {0} is not a stock Item").format(item_code)
_msgprint(msg, verbose)
def validate_cancelled_item(item_code, docstatus=None, verbose=1):
if docstatus is None:
docstatus = frappe.db.get_value("Item", item_code, "docstatus")
if docstatus == 2:
msg = _("Item {0} is cancelled").format(item_code)
_msgprint(msg, verbose)
def _msgprint(msg, verbose):
if verbose:
msgprint(msg, raise_exception=True)
else:
raise frappe.ValidationError(msg)
def get_last_purchase_details(item_code, doc_name=None, conversion_rate=1.0):
"""returns last purchase details in stock uom"""
# get last purchase order item details
last_purchase_order = frappe.db.sql("""\
select po.name, po.transaction_date, po.conversion_rate,
po_item.conversion_factor, po_item.base_price_list_rate,
po_item.discount_percentage, po_item.base_rate
from `tabPurchase Order` po, `tabPurchase Order Item` po_item
where po.docstatus = 1 and po_item.item_code = %s and po.name != %s and
po.name = po_item.parent
order by po.transaction_date desc, po.name desc
limit 1""", (item_code, cstr(doc_name)), as_dict=1)
# get last purchase receipt item details
last_purchase_receipt = frappe.db.sql("""\
select pr.name, pr.posting_date, pr.posting_time, pr.conversion_rate,
pr_item.conversion_factor, pr_item.base_price_list_rate, pr_item.discount_percentage,
pr_item.base_rate
from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pr_item
where pr.docstatus = 1 and pr_item.item_code = %s and pr.name != %s and
pr.name = pr_item.parent
order by pr.posting_date desc, pr.posting_time desc, pr.name desc
limit 1""", (item_code, cstr(doc_name)), as_dict=1)
purchase_order_date = getdate(last_purchase_order and last_purchase_order[0].transaction_date
or "1900-01-01")
purchase_receipt_date = getdate(last_purchase_receipt and
last_purchase_receipt[0].posting_date or "1900-01-01")
if (purchase_order_date > purchase_receipt_date) or \
(last_purchase_order and not last_purchase_receipt):
# use purchase order
last_purchase = last_purchase_order[0]
purchase_date = purchase_order_date
elif (purchase_receipt_date > purchase_order_date) or \
(last_purchase_receipt and not last_purchase_order):
# use purchase receipt
last_purchase = last_purchase_receipt[0]
purchase_date = purchase_receipt_date
else:
return frappe._dict()
conversion_factor = flt(last_purchase.conversion_factor)
out = frappe._dict({
"base_price_list_rate": flt(last_purchase.base_price_list_rate) / conversion_factor,
"base_rate": flt(last_purchase.base_rate) / conversion_factor,
"discount_percentage": flt(last_purchase.discount_percentage),
"purchase_date": purchase_date
})
conversion_rate = flt(conversion_rate) or 1.0
out.update({
"price_list_rate": out.base_price_list_rate / conversion_rate,
"rate": out.base_rate / conversion_rate,
"base_rate": out.base_rate
})
return out
def invalidate_cache_for_item(doc):
invalidate_cache_for(doc, doc.item_group)
website_item_groups = list(set((doc.get("old_website_item_groups") or [])
+ [d.item_group for d in doc.get({"doctype": "Website Item Group"}) if d.item_group]))
for item_group in website_item_groups:
invalidate_cache_for(doc, item_group)
if doc.get("old_item_group") and doc.get("old_item_group") != doc.item_group:
invalidate_cache_for(doc, doc.old_item_group)
def check_stock_uom_with_bin(item, stock_uom):
if stock_uom == frappe.db.get_value("Item", item, "stock_uom"):
return
matched = True
ref_uom = frappe.db.get_value("Stock Ledger Entry",
{"item_code": item}, "stock_uom")
if ref_uom:
if cstr(ref_uom) != cstr(stock_uom):
matched = False
else:
bin_list = frappe.db.sql("select * from tabBin where item_code=%s", item, as_dict=1)
for bin in bin_list:
if (bin.reserved_qty > 0 or bin.ordered_qty > 0 or bin.indented_qty > 0
or bin.planned_qty > 0) and cstr(bin.stock_uom) != cstr(stock_uom):
matched = False
break
if matched and bin_list:
frappe.db.sql("""update tabBin set stock_uom=%s where item_code=%s""", (stock_uom, item))
if not matched:
frappe.throw(
_("Default Unit of Measure for Item {0} cannot be changed directly because you have already made some transaction(s) with another UOM. You will need to create a new Item to use a different Default UOM.").format(item))
def get_item_defaults(item_code, company):
item = frappe.get_cached_doc('Item', item_code)
out = item.as_dict()
for d in item.item_defaults:
if d.company == company:
row = copy.deepcopy(d.as_dict())
row.pop("name")
out.update(row)
return out
def set_item_default(item_code, company, fieldname, value):
item = frappe.get_cached_doc('Item', item_code)
for d in item.item_defaults:
if d.company == company:
if not d.get(fieldname):
frappe.db.set_value(d.doctype, d.name, fieldname, value)
return
# no row found, add a new row for the company
d = item.append('item_defaults', {fieldname: value, "company": company})
d.db_insert()
item.clear_cache()
@frappe.whitelist()
def get_uom_conv_factor(uom, stock_uom):
uoms = [uom, stock_uom]
value = ""
uom_details = frappe.db.sql("""select to_uom, from_uom, value from `tabUOM Conversion Factor`\
where to_uom in ({0})
""".format(', '.join(['"' + frappe.db.escape(i, percent=False) + '"' for i in uoms])), as_dict=True)
for d in uom_details:
if d.from_uom == stock_uom and d.to_uom == uom:
value = 1/flt(d.value)
elif d.from_uom == uom and d.to_uom == stock_uom:
value = d.value
if not value:
uom_stock = frappe.db.get_value("UOM Conversion Factor", {"to_uom": stock_uom}, ["from_uom", "value"], as_dict=1)
uom_row = frappe.db.get_value("UOM Conversion Factor", {"to_uom": uom}, ["from_uom", "value"], as_dict=1)
if uom_stock and uom_row:
if uom_stock.from_uom == uom_row.from_uom:
value = flt(uom_stock.value) * 1/flt(uom_row.value)
return value
@frappe.whitelist()
def get_item_attribute(parent, attribute_value=''):
if not frappe.has_permission("Item"):
frappe.msgprint(_("No Permission"), raise_exception=1)
return frappe.get_all("Item Attribute Value", fields = ["attribute_value"],
filters = {'parent': parent, 'attribute_value': ("like", "%%%s%%" % attribute_value)})
def update_variants(variants, template, publish_progress=True):
count=0
for d in variants:
variant = frappe.get_doc("Item", d)
copy_attributes_to_variant(template, variant)
variant.save()
count+=1
if publish_progress:
frappe.publish_progress(count*100/len(variants), title = _("Updating Variants..."))
| shubhamgupta123/erpnext | erpnext/stock/doctype/item/item.py | Python | gpl-3.0 | 36,632 |
// ************************************************************************** //
// 24 Bomb //
// By: rcargou <rcargou@student.42.fr> ::: :::::::: //
// By: nmohamed <nmohamed@student.42.fr> :+: :+: :+: //
// By: adjivas <adjivas@student.42.fr> +:+ +:+ +:+ //
// By: vjacquie <vjacquie@student.42.fr> +#+ +:+ +#+ //
// By: jmoiroux <jmoiroux@student.42.fr> +#+#+#+#+#+ +#+ //
// Created: 2015/10/16 17:03:20 by rcargou #+# #+# //
// Updated: 2015/10/27 14:00:02 by rcargou ### ########.fr //
// //
// ************************************************************************** //
#include <mapparser.class.hpp>
#include <entity.class.hpp>
#include <wall.class.hpp>
#include <bomb.class.hpp>
#include <fire.class.hpp>
#include <player.class.hpp>
#include <enemy.class.hpp>
#include <boss.class.hpp>
#include <globject.class.hpp>
#include <event.class.hpp>
Entity *** Mapparser::map_from_file( char *map_path ) {
if (NULL != main_event->map)
Mapparser::free_old_map();
Entity *** tmp = Mapparser::map_alloc();
Entity * elem = NULL;
std::fstream file;
std::string line;
std::string casemap;
int i = 0,
j = globject::mapY_size - 1,
x = 0;
Mapparser::valid_map(map_path);
file.open(map_path , std::fstream::in);
for (int x = 0; x < 3; x++)
std::getline(file, line);
while (j >= 0) {
i = ((globject::mapX_size - 1) * 4 );
x = globject::mapX_size - 1;
std::getline(file, line);
while (i >= 0) {
casemap += line[i];
casemap += line[i + 1];
casemap += line[i + 2];
elem = Mapparser::get_entity_from_map( casemap, (float)x, (float)j );
if (elem->type == PLAYER || elem->type == ENEMY || elem->type == BOSS) {
tmp[j][x] = Factory::create_empty((int)x, (int)j);
main_event->char_list.push_back(elem);
}
else
tmp[j][x] = elem;
casemap.clear();
i -= 4;
x--;
if ( i < 0 )
break;
}
j--;
}
main_event->w_log("Mapparser::map_from_file LOADED");
return tmp;
}
Entity * Mapparser::get_entity_from_map( std::string & casemap, float x, float y) {
Entity * tmp = NULL;
if ( g_mapcase.count(casemap) == 0) {
main_event->w_error("Map file Case Syntax error/doesn't exist");
throw std::exception();
}
else {
switch (g_mapcase.at(casemap)) {
case EMPTY: return static_cast<Entity*>( Factory::create_empty(x, y) );
case WALL_INDESTRUCTIBLE: return static_cast<Entity*>( Factory::create_wall(WALL_INDESTRUCTIBLE, x, y, WALL_INDESTRUCTIBLE) );
case WALL_HP_1: return static_cast<Entity*>( Factory::create_wall(WALL_HP_1, x, y, WALL_HP_1) );
case WALL_HP_2: return static_cast<Entity*>( Factory::create_wall(WALL_HP_2, x, y, WALL_HP_2) );
case WALL_HP_3: return static_cast<Entity*>( Factory::create_wall(WALL_HP_3, x, y, WALL_HP_3) );
case WALL_HP_4: return static_cast<Entity*>( Factory::create_wall(WALL_HP_4, x, y, WALL_HP_4) );
case ENEMY1: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY1) );
case ENEMY2: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY2) );
case ENEMY3: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY3) );
case ENEMY4: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY4) );
case ENEMY5: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY5) );
case BOSS_A: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_A, BOSS_A) );
case BOSS_B: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_B, BOSS_B) );
case BOSS_C: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_C, BOSS_C) );
case BOSS_D: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_C, BOSS_D) );
case PLAYER1: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER1) );
case PLAYER2: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER2) );
case PLAYER3: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER3) );
case PLAYER4: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER4) );
case PLAYER5: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER5) );
case PLAYER6: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER6) );
case PLAYER7: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER7) );
case PLAYER8: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER8) );
case PLAYER9: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER9) );
case PLAYER10: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER10) );
case BONUS_POWER_UP: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_POWER_UP) );
case BONUS_PLUS_ONE: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_PLUS_ONE) );
case BONUS_KICK: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_KICK) );
case BONUS_CHANGE: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_CHANGE) );
case BONUS_REMOTE_BOMB: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_REMOTE_BOMB) );
case BONUS_SPEED_UP: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_SPEED_UP) );
default: return static_cast<Entity*>( Factory::create_empty(x, y) );
}
}
return tmp;
}
int Mapparser::valid_map( char const *map_path ) {
std::fstream file;
std::string line;
int x = 0,
y = 0,
j = 0;
if( access( map_path, F_OK ) < 0 ) {
main_event->w_error("Mapparser::valid_map file access error");
throw std::exception();
}
file.open(map_path , std::fstream::in);
if (!file.is_open()) {
main_event->w_error("Mapparser::valid_map file open error");
throw std::exception();
}
std::getline(file, line); // y: 20
if (line.length() >= 4)
x = std::stoi(&line[3]);
else
main_event->w_exception("map line 1 error");
std::getline(file, line); // x: 20
if (line.length() >= 4)
y = std::stoi(&line[3]);
else
main_event->w_exception("map line 2 error");
std::getline(file, line); // <-- MAP -->
j = 0;
while ( std::getline(file, line) ) {
if ((int)line.length() != (4 * x - 1) ) {
main_event->w_exception("width doesn't correspond");
}
if (j >= y - 1)
break;
j++;
}
if (j != y - 1)
main_event->w_exception("Map height doesn't correspond");
file.close();
return 0;
}
Entity *** Mapparser::map_alloc() { // return map 2d without entity
int y = 0;
Entity *** new_map = NULL;
// TO DELETE SI SEGFAULT
// if (main_event->map != NULL) {
// while (y < globject::mapY_size) {
// std::free(main_event->map[y]);
// main_event->map[y] = NULL;
// y++;
// }
// std::free(main_event->map);
// main_event->map = NULL;
// }
/////////////////////
new_map = (Entity ***)std::malloc(sizeof(Entity **) * globject::mapY_size);
if (new_map == NULL) {
main_event->w_error("Mapparser::map_alloc() new_map Allocation error");
throw std::exception();
}
y = 0;
while (y < globject::mapY_size) {
new_map[y] = NULL;
new_map[y] = (Entity **)std::malloc(sizeof(Entity *) * globject::mapX_size);
if (new_map[y] == NULL) {
main_event->w_error("Mapparser::map_alloc() new_map[y] Allocation error");
throw std::exception();
}
y++;
}
return new_map;
}
void Mapparser::free_old_map() {
int y = 0;
while (y < globject::mapY_size) {
if (NULL != main_event->map[y])
std::free( main_event->map[y]);
y++;
}
if (NULL != main_event->map)
std::free(main_event->map);
main_event->map = NULL;
}
void Mapparser::get_error() const {
if (NULL != Mapparser::error)
std::cerr << Mapparser::error;
}
std::string * Mapparser::error = NULL;
Mapparser::Mapparser() {}
Mapparser::~Mapparser() {}
Mapparser::Mapparser( Mapparser const & src ) {
*this = src;
}
Mapparser & Mapparser::operator=( Mapparser const & rhs ) {
if (this != &rhs) {
this->error = rhs.error;
}
return *this;
}
| noxsnono/Bomberman_42 | src/map/mapparser.class.cpp | C++ | gpl-3.0 | 9,453 |
package osberbot.bo;
/**
* TODO: Description
*
* @author Tititesouris
* @since 2016/03/20
*/
public class ViewerBO {
private Integer id;
private String name;
private Boolean moderator;
private RankBO rank;
public ViewerBO(Integer id, String name, RankBO rank) {
this.id = id;
this.name = name;
this.rank = rank;
}
public boolean hasPower(PowerBO power) {
if (rank != null)
return rank.hasPower(power);
return moderator;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public RankBO getRank() {
return rank;
}
public void setRank(RankBO rank) {
this.rank = rank;
}
}
| Tititesouris/OsberBot | src/osberbot/bo/ViewerBO.java | Java | gpl-3.0 | 900 |
from datetime import datetime
import factory
from zds.forum.factories import PostFactory, TopicFactory
from zds.gallery.factories import GalleryFactory, UserGalleryFactory
from zds.utils.factories import LicenceFactory, SubCategoryFactory
from zds.utils.models import Licence
from zds.tutorialv2.models.database import PublishableContent, Validation, ContentReaction
from zds.tutorialv2.models.versioned import Container, Extract
from zds.tutorialv2.publication_utils import publish_content
from zds.tutorialv2.utils import init_new_repo
text_content = "Ceci est un texte bidon, **avec markown**"
tricky_text_content = (
"Ceci est un texte contenant plein d'images, pour la publication. Le modifier affectera le test !\n\n"
"# Les images\n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"# Et donc ...\n\n"
"Voilà :)"
)
class PublishableContentFactory(factory.django.DjangoModelFactory):
"""
Factory that creates a PublishableContent.
"""
class Meta:
model = PublishableContent
title = factory.Sequence("Mon contenu No{}".format)
description = factory.Sequence("Description du contenu No{}".format)
type = "TUTORIAL"
creation_date = datetime.now()
pubdate = datetime.now()
@classmethod
def _generate(cls, create, attrs):
# These parameters are only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (they are removed from attrs).
light = attrs.pop("light", True)
author_list = attrs.pop("author_list", None)
add_license = attrs.pop("add_license", True)
add_category = attrs.pop("add_category", True)
# This parameter will be saved in the database,
# which is why we use attrs.get() (it stays in attrs).
licence = attrs.get("licence", None)
auths = author_list or []
if add_license:
given_licence = licence or Licence.objects.first()
if isinstance(given_licence, str) and given_licence:
given_licence = Licence.objects.filter(title=given_licence).first() or Licence.objects.first()
licence = given_licence or LicenceFactory()
text = text_content
if not light:
text = tricky_text_content
publishable_content = super()._generate(create, attrs)
publishable_content.gallery = GalleryFactory()
publishable_content.licence = licence
for auth in auths:
publishable_content.authors.add(auth)
if add_category:
publishable_content.subcategory.add(SubCategoryFactory())
publishable_content.save()
for author in publishable_content.authors.all():
UserGalleryFactory(user=author, gallery=publishable_content.gallery, mode="W")
init_new_repo(publishable_content, text, text)
return publishable_content
class ContainerFactory(factory.Factory):
"""
Factory that creates a Container.
"""
class Meta:
model = Container
title = factory.Sequence(lambda n: "Mon container No{}".format(n + 1))
@classmethod
def _generate(cls, create, attrs):
# These parameters are only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (they are removed from attrs).
db_object = attrs.pop("db_object", None)
light = attrs.pop("light", True)
# This parameter will be saved in the database,
# which is why we use attrs.get() (it stays in attrs).
parent = attrs.get("parent", None)
# Needed because we use container.title later
container = super()._generate(create, attrs)
text = text_content
if not light:
text = tricky_text_content
sha = parent.repo_add_container(container.title, text, text)
container = parent.children[-1]
if db_object:
db_object.sha_draft = sha
db_object.save()
return container
class ExtractFactory(factory.Factory):
"""
Factory that creates a Extract.
"""
class Meta:
model = Extract
title = factory.Sequence(lambda n: "Mon extrait No{}".format(n + 1))
@classmethod
def _generate(cls, create, attrs):
# These parameters are only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (they are removed from attrs).
light = attrs.pop("light", True)
db_object = attrs.pop("db_object", None)
# This parameter will be saved in the database,
# which is why we use attrs.get() (it stays in attrs).
container = attrs.get("container", None)
# Needed because we use extract.title later
extract = super()._generate(create, attrs)
parent = container
text = text_content
if not light:
text = tricky_text_content
sha = parent.repo_add_extract(extract.title, text)
extract = parent.children[-1]
if db_object:
db_object.sha_draft = sha
db_object.save()
return extract
class ContentReactionFactory(factory.django.DjangoModelFactory):
"""
Factory that creates a ContentReaction.
"""
class Meta:
model = ContentReaction
ip_address = "192.168.3.1"
text = "Bonjour, je me présente, je m'appelle l'homme au texte bidonné"
@classmethod
def _generate(cls, create, attrs):
note = super()._generate(create, attrs)
note.pubdate = datetime.now()
note.save()
note.related_content.last_note = note
note.related_content.save()
return note
class BetaContentFactory(PublishableContentFactory):
"""
Factory that creates a PublishableContent with a beta version and a beta topic.
"""
@classmethod
def _generate(cls, create, attrs):
# This parameter is only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (it is removed from attrs).
beta_forum = attrs.pop("forum", None)
# Creates the PublishableContent (see PublishableContentFactory._generate() for more info)
publishable_content = super()._generate(create, attrs)
if publishable_content.authors.count() > 0 and beta_forum is not None:
beta_topic = TopicFactory(
title="[beta]" + publishable_content.title, author=publishable_content.authors.first(), forum=beta_forum
)
publishable_content.sha_beta = publishable_content.sha_draft
publishable_content.beta_topic = beta_topic
publishable_content.save()
PostFactory(topic=beta_topic, position=1, author=publishable_content.authors.first())
beta_topic.save()
return publishable_content
class PublishedContentFactory(PublishableContentFactory):
"""
Factory that creates a PublishableContent and the publish it.
"""
@classmethod
def _generate(cls, create, attrs):
# This parameter is only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (it is removed from attrs).
is_major_update = attrs.pop("is_major_update", True)
# Creates the PublishableContent (see PublishableContentFactory._generate() for more info)
content = super()._generate(create, attrs)
published = publish_content(content, content.load_version(), is_major_update)
content.sha_public = content.sha_draft
content.public_version = published
content.save()
return content
class ValidationFactory(factory.django.DjangoModelFactory):
"""
Factory that creates a Validation.
"""
class Meta:
model = Validation
| ChantyTaguan/zds-site | zds/tutorialv2/factories.py | Python | gpl-3.0 | 8,840 |
package miscellaneous;
import java.util.Arrays;
public class Gen {
private static int greyCode(int n1){
return n1 ^ (n1 >> 1);
}
/*
* Advances l1 to next lexicographical higher combination.
* cap is the largest value allowed for one index.
* return false
*/
public static boolean nextComb(int[] l1, int cap){
for (int ptr = l1.length-1;;){
if (ptr < 0) return false;
if (l1[ptr] == cap - 1){
l1[ptr] = 0;
ptr--;
}
else {
l1[ptr]++;
break;
}
}
return true;
}
/*
* Advances l1 to next lexicographical higher permutation.
* 1
* Find the highest index i such that s[i] < s[i+1].
* If no such index exists, the permutation is the last permutation.
* 2
* Find the highest index j > i such that s[j] > s[i].
* Such a j must exist, since i+1 is such an index.
* 3
* Swap s[i] with s[j].
* 4
* Reverse all the order of all of the elements after index i
*/
public static void swap(int[] l1, int a, int b){
int k1 = l1[a];l1[a]=l1[b];l1[b]=k1;
}
public static void rev(int[] l1, int a, int b){
for (int i = 0; i < (b-a+1)/2;i++) swap(l1,a+i,b-i);
}
public static boolean nextPerm(int[] l1) {
for (int i = l1.length- 2; i >=0; i--) {
if (l1[i] < l1[i + 1]){
for (int k = l1.length - 1; k>=0;k--){
if (l1[k]>=l1[i]){
swap(l1,i,k);
rev(l1,i+1,l1.length-1);
return true;
}
}
}
}
rev(l1,0,l1.length-1);
return false;
}
public static int[] permInv(int[] l1){
int[] fin = new int[l1.length];
for (int i = 0; i< l1.length;i++){
fin[l1[i]]=i;
}
return fin;
}
} | cs6096/contest-library | src/miscellaneous/Gen.java | Java | gpl-3.0 | 1,729 |
#
# -*- coding: utf-8 -*-
# Dia Group Resize Plugin
# Copyright (c) 2015, Alexandre Machado <axmachado@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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/>.
#
import sys, dia
import os
import pygtk
pygtk.require("2.0")
import gtk
import locale
class ResizeWindow(object):
def __init__(self, group, data):
self.group = group
self.data = data
self.initWindow()
def initWindow(self):
self.dlg = gtk.Dialog()
self.dlg.set_title('Group Resize')
self.dlg.set_border_width(6)
self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5)
self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY)
self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
self.dlg.set_has_separator(True)
self.dlg.set_modal(False)
self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None)
self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None)
def dimensionsFrame(self, label):
frame = gtk.Frame(label)
table = gtk.Table(rows=4, columns=2)
ignore = gtk.RadioButton(group=None, label="do not change")
ignore.show()
smallest = gtk.RadioButton(group=ignore, label="shrink to smallest")
smallest.show()
largest = gtk.RadioButton(group=ignore, label="enlarge to largest")
largest.show()
specify = gtk.RadioButton(group=ignore, label="resize to:")
specify.show()
value = gtk.Entry()
value.show()
specify.connect("toggled", self.enableValueEntry, value)
self.enableValueEntry(specify, value)
table.attach (ignore, 0, 1, 0, 1)
table.attach (smallest, 0, 1, 1, 2)
table.attach (largest, 0, 1, 2, 3)
table.attach (specify, 0, 1, 3, 4)
table.attach (value, 1, 2, 3, 4)
frame.add(table)
table.show()
frame.show()
options = {
'ignore': ignore,
'smallest': smallest,
'largest': largest,
'specify': specify,
'value': value
}
return frame, options
def enableValueEntry(self, radioSpecify, entrySpecify, *args):
entrySpecify.set_sensitive(radioSpecify.get_active())
def contentsFrameWidth(self):
frame, self.widthOptions = self.dimensionsFrame('Width')
return frame
def contentsFrameHeight(self):
frame, self.heightOptions = self.dimensionsFrame('Height')
return frame
def dialogContents(self):
contents = gtk.VBox(spacing=5)
contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True)
contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True)
contents.show()
return contents
def getSelectedGroupOption(self, options):
value = options['value'].get_text()
for opt in 'ignore', 'smallest', 'largest', 'specify':
if options[opt].get_active():
return (opt,value)
return ('ignore',value)
def getValue(self, opt, value, elProperty):
if opt == 'specify':
return self.toFloat(value)
else:
values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ]
if opt == 'smallest':
return min(values)
else:
return max(values)
def adjustWidth(self, value):
for obj in self.group:
pos = obj.properties['obj_pos'].value
if obj.properties.has_key("elem_width"):
difference = value - obj.properties['elem_width'].value
handleLeft = obj.handles[3]
handleRight = obj.handles[4]
amount = difference/2
obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0)
obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0)
obj.move(pos.x, pos.y)
def adjustHeight(self, value):
for obj in self.group:
pos = obj.properties['obj_pos'].value
if obj.properties.has_key("elem_height"):
difference = value - obj.properties['elem_height'].value
handleTop = obj.handles[1]
handleBottom = obj.handles[6]
amount = difference/2
obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0)
obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0)
obj.move(pos.x, pos.y)
def toFloat(self, valor):
return locale.atof(valor)
def clickAplicar(self, *args):
optWidth = self.getSelectedGroupOption(self.widthOptions)
optHeight = self.getSelectedGroupOption(self.heightOptions)
try:
if optWidth[0] != 'ignore':
width = self.getValue(optWidth[0], optWidth[1], 'elem_width')
self.adjustWidth(width)
if optHeight[0] != 'ignore':
height = self.getValue(optHeight[0], optHeight[1], 'elem_height')
self.adjustHeight(height)
if dia.active_display():
diagram = dia.active_display().diagram
for obj in self.group:
diagram.update_connections(obj)
except Exception,e:
dia.message(gtk.MESSAGE_ERROR, repr(e))
if dia.active_display():
dia.active_display().add_update_all()
dia.active_display().flush()
def show(self):
self.dlg.show()
def hide(self, *args):
self.dlg.hide()
def run(self):
return self.dlg.run()
def dia_group_resize_db (data,flags):
diagram = dia.active_display().diagram
group = diagram.get_sorted_selected()
if len(group) > 0:
win = ResizeWindow(group, data)
win.show()
else:
dia.message(gtk.MESSAGE_INFO, "Please select a group of objects")
dia.register_action("ObjectGroupResize", "Group Resize",
"/DisplayMenu/Objects/ObjectsExtensionStart",
dia_group_resize_db)
| axmachado/dia-group-resize | group_resize.py | Python | gpl-3.0 | 6,960 |
package com.xcode.bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@ManagedBean
@SessionScoped
public class UserAuth implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4027678448802658446L;
private String email;
public UserAuth() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();
email = auth.getName();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| georgematos/ocaert | src/com/xcode/bean/UserAuth.java | Java | gpl-3.0 | 838 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2016-2019 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/>.
Class
Foam::distributionModels::massRosinRammler
Description
Mass-based Rosin-Rammler distributionModel.
Corrected form of the Rosin-Rammler distribution taking into account the
varying number of particles per parcel for for fixed-mass parcels. This
distribution should be used when
\verbatim
parcelBasisType mass;
\endverbatim
See equation 10 in reference:
\verbatim
Yoon, S. S., Hewson, J. C., DesJardin, P. E., Glaze, D. J.,
Black, A. R., & Skaggs, R. R. (2004).
Numerical modeling and experimental measurements of a high speed
solid-cone water spray for use in fire suppression applications.
International Journal of Multiphase Flow, 30(11), 1369-1388.
\endverbatim
SourceFiles
massRosinRammler.C
\*---------------------------------------------------------------------------*/
#ifndef massRosinRammler_H
#define massRosinRammler_H
#include "distributionModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace distributionModels
{
/*---------------------------------------------------------------------------*\
Class massRosinRammler Declaration
\*---------------------------------------------------------------------------*/
class massRosinRammler
:
public distributionModel
{
// Private Data
//- Distribution minimum
scalar minValue_;
//- Distribution maximum
scalar maxValue_;
//- Characteristic droplet size
scalar d_;
//- Empirical dimensionless constant to specify the distribution width,
// sometimes referred to as the dispersion coefficient
scalar n_;
public:
//- Runtime type information
TypeName("massRosinRammler");
// Constructors
//- Construct from components
massRosinRammler(const dictionary& dict, Random& rndGen);
//- Construct copy
massRosinRammler(const massRosinRammler& p);
//- Construct and return a clone
virtual autoPtr<distributionModel> clone() const
{
return autoPtr<distributionModel>(new massRosinRammler(*this));
}
//- Destructor
virtual ~massRosinRammler();
// Member Functions
//- Sample the distributionModel
virtual scalar sample() const;
//- Return the minimum value
virtual scalar minValue() const;
//- Return the maximum value
virtual scalar maxValue() const;
//- Return the mean value
virtual scalar meanValue() const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace distributionModels
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| will-bainbridge/OpenFOAM-dev | src/lagrangian/distributionModels/massRosinRammler/massRosinRammler.H | C++ | gpl-3.0 | 4,039 |
/*
meowbot
Copyright (C) 2008-2009 Park Jeong Min <pjm0616_at_gmail_d0t_com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 <iostream>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <time.h>
#include <pcrecpp.h>
#include "defs.h"
#include "ircbot.h"
#include "luacpp.h"
/*
Lua는 다른 언어와 달리 기본적으로 순수한 언어로서의 기능만 제공하며,
기타 시스템 접근은 별도 라이브러리를 로드해서 사용.
따라서 시스템 접근이 가능한 라이브러리만 로드하지 않으면 안전.
예외인 루아 파일을 로드하는 dofile, loadfile 2가지 함수는
코드 실행 전에 삭제.
*/
///FIXME: 대충 만듬=_= 수정 필요
static int lua_safeeval_child(const char *code)
{
lua_State *L = luaL_newstate();
// 기본 라이브러리 로드
#define LOADLIB(name, func) \
lua_pushcfunction(L, func); \
lua_pushstring(L, name); \
lua_call(L, 1, 0);
LOADLIB("", luaopen_base)
LOADLIB("table", luaopen_table)
LOADLIB("string", luaopen_string)
LOADLIB("math", luaopen_math)
#undef LOADLIB
luaopen_libluapcre(L);
luaopen_libluautf8(L);
luaopen_libluahangul(L);
// 파일에 접근할 수 있는 함수 삭제
#define SETNIL(name) \
lua_pushliteral(L, name); \
lua_pushnil(L); \
lua_rawset(L, LUA_GLOBALSINDEX);
SETNIL("dofile");
SETNIL("loadfile");
#undef SETNIL
// 코드 실행
std::string codebuf(code);
codebuf += '\n';
int ret = luaL_loadstring(L, codebuf.c_str());
if(ret)
{
const char *errmsg = lua_tostring(L, -1);
printf("Error: %s\n", errmsg);
lua_pop(L, 1);
}
else
{
ret = lua_pcall(L, 0, 0, 0);
if(ret != 0)
{
const char *errmsg = lua_tostring(L, -1);
printf("Error: %s\n", errmsg);
lua_pop(L, 1);
}
}
lua_close(L);
return 0;
}
static void luaeval_child_signal_handler(int sig)
{
if(sig == SIGALRM)
puts("Timeout");
else
printf("Recieved signal %d\n", sig);
exit(1);
}
static int lua_safeeval(ircbot_conn *isrv, irc_privmsg &pmsg,
irc_msginfo &mdest, const char *code, const char *cparam)
{
int rdpipe[2];
pipe(rdpipe);
int pid = fork();
if(pid < 0)
{
close(rdpipe[0]);
close(rdpipe[1]);
return -1;
}
else if(pid == 0)
{
close(0);
dup2(rdpipe[1], 1);
dup2(rdpipe[1], 2);
close(rdpipe[0]);
signal(SIGALRM, luaeval_child_signal_handler);
alarm(2);
lua_safeeval_child(code);
exit(0);
}
else
{
close(rdpipe[1]);
int status, ret;
ret = waitpid(pid, &status, 0);
char buf[512*3+1];
ret = read(rdpipe[0], buf, sizeof(buf)-1);
close(rdpipe[0]);
if(ret < 0)
return -1;
buf[ret] = 0;
char *pp, *p = strtok_r(buf, "\n", &pp);
if(!p)
{
isrv->privmsg(mdest, "(No output)");
}
else
{
int lines = 3;
do
{
isrv->privmsg_nh(mdest, p);
} while((p = strtok_r(NULL, "\n", &pp)) && --lines);
}
}
return 0;
}
int cmd_cb_luaeval(ircbot_conn *isrv, irc_privmsg &pmsg,
irc_msginfo &mdest, std::string &cmd, std::string &carg, void *)
{
if(carg.empty())
{
isrv->privmsg(mdest, "사용법: !" + cmd + " <코드>");
}
else
{
lua_safeeval(isrv, pmsg, mdest, carg.c_str(), NULL);
}
return HANDLER_FINISHED;
}
#if 0
int cmd_cb_memeval(ircbot_conn *isrv, irc_privmsg &pmsg,
irc_msginfo &mdest, std::string &cmd, std::string &carg, void *)
{
(void)cmd;
std::string mname, marg;
if(!pcrecpp::RE("([^ ]+) ?(.*)").FullMatch(carg, &mname, &marg))
{
isrv->privmsg(mdest,
"사용법: !기억해 <기억 이름> !perl <코드> 등으로 기억시킨 후, "
"!기억실행 <기억 이름> 또는 !기억실행 <기억 이름> <파라미터> 로 실행 (단축: !.)");
isrv->privmsg(mdest,
" %nick%은 닉네임으로, %param%는 파라미터로 치환됩니다. "
"C,C++에서는 int nparam, const char *params[] 전역변수가 제공됩니다.");
}
else
{
const std::string &nick = pmsg.getnick();
// FIXME: use getremdb_v2
std::pair<std::string, std::string> (*getremdb_fxn)(const std::string &word);
getremdb_fxn = (std::pair<std::string, std::string> (*)(const std::string &))
isrv->bot->modules.dlsym("mod_remember", "getremdb");
if(!getremdb_fxn)
{
isrv->privmsg(mdest, "내부 오류: 이 명령에 필요한 모듈이 로드되지 않았습니다.");
return 0;
}
std::pair<std::string, std::string> data = getremdb_fxn(mname);
std::string cmd2, carg2;
if(data.first.empty())
{
isrv->privmsg(mdest, "오류: " + data.second);
}
else if(pcrecpp::RE("^!([^ ]+) (.+)").FullMatch(data.second, &cmd2, &carg2))
{
irc_cmd_eval_code(isrv, mdest, nick, cmd2, carg2, marg);
}
else
{
isrv->privmsgf_nh(mdest, "올바른 형식이 아닙니다: %s", data.second.c_str());
}
}
return HANDLER_FINISHED;
}
#endif
#include "main.h"
int mod_luaeval_init(ircbot *bot)
{
//bot->register_cmd("기억실행", cmd_cb_memeval);
//bot->register_cmd(".", cmd_cb_memeval);
bot->register_cmd("luaeval", cmd_cb_luaeval);
return 0;
}
int mod_luaeval_cleanup(ircbot *bot)
{
//bot->unregister_cmd("기억실행");
//bot->unregister_cmd(".");
bot->unregister_cmd("luaeval");
return 0;
}
MODULE_INFO(mod_luaeval, mod_luaeval_init, mod_luaeval_cleanup)
| pjm0616/meowbot-pub | modules/mod_luaeval.cpp | C++ | gpl-3.0 | 5,984 |
import { NgModule } from "@angular/core";
import { SamplesModule } from "samples/samples.module";
import { SamplesRoutingModule } from "./samples.routing.module";
@NgModule({
imports: [
SamplesModule,
SamplesRoutingModule
]
})
export class SamplesFeatureModule {}
| SciCatProject/catanie | src/app/app-routing/lazy/samples-routing/samples.feature.module.ts | TypeScript | gpl-3.0 | 277 |
package Yogibear617.mods.FuturisticCraft.CreativeTabs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
public class FCSBModCreativeTab extends CreativeTabs {
public FCSBModCreativeTab(int par1, String par2Str) {
super(par1, par2Str);
}
@SideOnly(Side.CLIENT)
public int getTabIconItemIndex() {
return Block.stoneBrick.blockID;
}
}
| Yogibear617/Futuristic_Craft | fc_common/Yogibear617/mods/FuturisticCraft/CreativeTabs/FCSBModCreativeTab.java | Java | gpl-3.0 | 455 |
from ..models import Album
from ..resource import SingleResource, ListResource
from ..schemas import AlbumSchema
class SingleAlbum(SingleResource):
schema = AlbumSchema()
routes = ('/album/<int:id>/',)
model = Album
class ListAlbums(ListResource):
schema = AlbumSchema(many=True)
routes = ('/album/', '/tracklist/')
model = Album
| justanr/owa | owa/api/album.py | Python | gpl-3.0 | 358 |
package com.eveningoutpost.dexdrip.Models;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
// from package info.nightscout.client.utils;
/**
* Created by mike on 30.12.2015.
*/
/**
* The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj
* with TZ
*/
public class DateUtil {
private static final String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // eg 2017-03-24T22:03:27Z
private static final String FORMAT_DATE_ISO2 = "yyyy-MM-dd'T'HH:mm:ssZ"; // eg 2017-03-27T17:38:14+0300
private static final String FORMAT_DATE_ISO3 = "yyyy-MM-dd'T'HH:mmZ"; // eg 2017-05-12T08:16-0400
/**
* Takes in an ISO date string of the following format:
* yyyy-mm-ddThh:mm:ss.ms+HoMo
*
* @param isoDateString the iso date string
* @return the date
* @throws Exception the exception
*/
private static Date fromISODateString(String isoDateString)
throws Exception {
SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.parse(isoDateString);
}
private static Date fromISODateString3(String isoDateString)
throws Exception {
SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO3);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.parse(isoDateString);
}
private static Date fromISODateString2(String isoDateString)
throws Exception {
try {
SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO2);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.parse(isoDateString);
} catch (java.text.ParseException e) {
return fromISODateString3(isoDateString);
}
}
public static Date tolerantFromISODateString(String isoDateString)
throws Exception {
try {
return fromISODateString(isoDateString.replaceFirst("\\.[0-9][0-9][0-9]Z$", "Z"));
} catch (java.text.ParseException e) {
return fromISODateString2(isoDateString);
}
}
/**
* Render date
*
* @param date the date obj
* @param format - if not specified, will use FORMAT_DATE_ISO
* @param tz - tz to set to, if not specified uses local timezone
* @return the iso-formatted date string
*/
public static String toISOString(Date date, String format, TimeZone tz) {
if (format == null) format = FORMAT_DATE_ISO;
if (tz == null) tz = TimeZone.getDefault();
DateFormat f = new SimpleDateFormat(format);
f.setTimeZone(tz);
return f.format(date);
}
public static String toISOString(Date date) {
return toISOString(date, FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC"));
}
public static String toISOString(long date) {
return toISOString(new Date(date), FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC"));
}
public static String toNightscoutFormat(long date) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
} | TecMunky/xDrip | app/src/main/java/com/eveningoutpost/dexdrip/Models/DateUtil.java | Java | gpl-3.0 | 3,340 |
"""
System plugin
Copyright (C) 2016 Walid Benghabrit
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/>.
"""
from accmon.plugins.plugin import *
class System(Plugin):
def __init__(self):
super().__init__()
def handle_request(self, request):
res = super(System, self).handle_request(request)
if res is not None: return res
| hkff/AccMon | accmon/plugins/system.py | Python | gpl-3.0 | 920 |
/*
* Copyright (C) 2017 GedMarc
*
* 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 com.jwebmp.core.htmlbuilder.css.displays;
import com.jwebmp.core.base.client.CSSVersions;
import com.jwebmp.core.htmlbuilder.css.CSSEnumeration;
import com.jwebmp.core.htmlbuilder.css.annotations.CSSAnnotationType;
/**
* Definition and Usage
* <p>
* The display property defines how a certain HTML element should be displayed.
* Default value: inline Inherited: no Version:
* CSS1 JavaScript syntax: object.style.display="inline"
*
* @author GedMarc
* @version 1.0
* @since 2013/01/22
*/
@CSSAnnotationType
public enum Displays
implements CSSEnumeration<Displays>
{
/**
* Default value. Displays an element as an inline element (like <span>)
*/
Inline,
/**
* Displays an element as a block element (like
* <p>
* )
*/
Block,
/**
* Displays an element as an block_level flex container. New in CSS3
*/
Flex,
/**
* Displays an element as an inline_level flex container. New in CSS3
*/
Inline_flex,
/**
* The element is displayed as an inline_level table
*/
Inline_table,
/**
* Let the element behave like a <li> element
*/
List_item,
/**
* Displays an element as either block or inline, depending on context
*/
Run_in,
/**
* Let the element behave like a <table> element
*/
Table,
/**
* Let the element behave like a <caption> element
*/
Table_caption,
/**
* Let the element behave like a <colgroup> element
*/
Table_column_group,
/**
* Let the element behave like a <thead> element
*/
Table_header_group,
/**
* Let the element behave like a <tfoot> element
*/
Table_footer_group,
/**
* Let the element behave like a <tbody> element
*/
Table_row_group,
/**
* Let the element behave like a <td> element
*/
Table_cell,
/**
* Let the element behave like a <col> element
*/
Table_column,
/**
* Let the element behave like a <tr> element
*/
Table_row,
/**
* The element will not be displayed at all (has no effect on layout)
*/
None,
/**
* Sets this property to its default value. Read about initial
*/
Initial,
/**
* Inherits this property from its parent element. Read about inherit;
*/
Inherit,
/**
* Sets this field as not set
*/
Unset;
@Override
public String getJavascriptSyntax()
{
return "style.display";
}
@Override
public CSSVersions getCSSVersion()
{
return CSSVersions.CSS1;
}
@Override
public String getValue()
{
return name();
}
@Override
public Displays getDefault()
{
return Unset;
}
@Override
public String toString()
{
return super.toString()
.toLowerCase()
.replaceAll("_", "-");
}
}
| GedMarc/JWebSwing | src/main/java/com/jwebmp/core/htmlbuilder/css/displays/Displays.java | Java | gpl-3.0 | 3,363 |
package com.projectreddog.machinemod.container;
import com.projectreddog.machinemod.inventory.SlotBlazePowder;
import com.projectreddog.machinemod.inventory.SlotNotBlazePowder;
import com.projectreddog.machinemod.inventory.SlotOutputOnlyTurobFurnace;
import com.projectreddog.machinemod.tileentities.TileEntityTurboFurnace;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
;
public class ContainerTurboFurnace extends Container {
protected TileEntityTurboFurnace turbofurnace;
protected int lastFuleBurnTimeRemaining = 0;
protected int lastProcessingTimeRemaining = 0;
public ContainerTurboFurnace(InventoryPlayer inventoryPlayer, TileEntityTurboFurnace turbofurnace) {
this.turbofurnace = turbofurnace;
lastFuleBurnTimeRemaining = -1;
lastProcessingTimeRemaining = -1;
// for (int i = 0; i < 1; i++) {
// for (int j = 0; j < 3; j++) {
addSlotToContainer(new SlotNotBlazePowder(turbofurnace, 0, 47, 34));
addSlotToContainer(new SlotOutputOnlyTurobFurnace(inventoryPlayer.player, turbofurnace, 1, 110, 53));
addSlotToContainer(new SlotBlazePowder(turbofurnace, 2, 47, 74));
// }
// }
// commonly used vanilla code that adds the player's inventory
bindPlayerInventory(inventoryPlayer);
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return turbofurnace.isUsableByPlayer(player);
}
protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 9; j++) {
addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 139 + i * 18));
}
}
for (int i = 0; i < 9; i++) {
addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 197));
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slot) {
ItemStack stack = ItemStack.EMPTY;
Slot slotObject = (Slot) inventorySlots.get(slot);
// null checks and checks if the item can be stacked (maxStackSize > 1)
if (slotObject != null && slotObject.getHasStack()) {
ItemStack stackInSlot = slotObject.getStack();
stack = stackInSlot.copy();
// merges the item into player inventory since its in the Entity
if (slot < 3) {
if (!this.mergeItemStack(stackInSlot, 3, this.inventorySlots.size(), true)) {
return ItemStack.EMPTY;
}
slotObject.onSlotChange(stackInSlot, stack);
}
// places it into the tileEntity is possible since its in the player
// inventory
else if (!this.mergeItemStack(stackInSlot, 0, 3, false)) {
return ItemStack.EMPTY;
}
if (stackInSlot.getCount() == 0) {
slotObject.putStack(ItemStack.EMPTY);
} else {
slotObject.onSlotChanged();
}
if (stackInSlot.getCount() == stack.getCount()) {
return ItemStack.EMPTY;
}
slotObject.onTake(player, stackInSlot);
}
return stack;
}
/**
* Looks for changes made in the container, sends them to every listener.
*/
public void detectAndSendChanges() {
super.detectAndSendChanges();
for (int i = 0; i < this.listeners.size(); ++i) {
IContainerListener icrafting = (IContainerListener) this.listeners.get(i);
if (this.lastFuleBurnTimeRemaining != this.turbofurnace.getField(0)) {
icrafting.sendWindowProperty(this, 0, this.turbofurnace.getField(0));
}
if (this.lastProcessingTimeRemaining != this.turbofurnace.getField(1)) {
icrafting.sendWindowProperty(this, 1, this.turbofurnace.getField(1));
}
}
this.lastFuleBurnTimeRemaining = this.turbofurnace.getField(0);
this.lastProcessingTimeRemaining = this.turbofurnace.getField(1);
}
@SideOnly(Side.CLIENT)
public void updateProgressBar(int id, int data) {
this.turbofurnace.setField(id, data);
}
}
| TechStack/TechStack-s-HeavyMachineryMod | src/main/java/com/projectreddog/machinemod/container/ContainerTurboFurnace.java | Java | gpl-3.0 | 3,980 |
/**
Copyright (c) 2014-2015 "M-Way Solutions GmbH"
FruityMesh - Bluetooth Low Energy mesh protocol [http://mwaysolutions.com/]
This file is part of FruityMesh
FruityMesh 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 <adv_packets.h>
#include <AdvertisingController.h>
#include <AdvertisingModule.h>
#include <Logger.h>
#include <Utility.h>
#include <Storage.h>
extern "C"{
#include <app_error.h>
}
//This module allows a number of advertising messages to be configured.
//These will be broadcasted periodically
/*
TODO: Who's responsible for restoring the mesh-advertising packet? This module or the Node?
* */
AdvertisingModule::AdvertisingModule(u8 moduleId, Node* node, ConnectionManager* cm, const char* name, u16 storageSlot)
: Module(moduleId, node, cm, name, storageSlot)
{
//Register callbacks n' stuff
//Save configuration to base class variables
//sizeof configuration must be a multiple of 4 bytes
configurationPointer = &configuration;
configurationLength = sizeof(AdvertisingModuleConfiguration);
//Start module configuration loading
LoadModuleConfiguration();
}
void AdvertisingModule::ConfigurationLoadedHandler()
{
//Does basic testing on the loaded configuration
Module::ConfigurationLoadedHandler();
//Version migration can be added here
if(configuration.moduleVersion == 1){/* ... */};
//Do additional initialization upon loading the config
//Start the Module...
logt("ADVMOD", "Config set");
}
void AdvertisingModule::TimerEventHandler(u16 passedTime, u32 appTimer)
{
//Do stuff on timer...
}
void AdvertisingModule::ResetToDefaultConfiguration()
{
//Set default configuration values
configuration.moduleId = moduleId;
configuration.moduleActive = true;
configuration.moduleVersion = 1;
memset(configuration.messageData[0].messageData, 0, 31);
advStructureFlags flags;
advStructureName name;
flags.len = SIZEOF_ADV_STRUCTURE_FLAGS-1;
flags.type = BLE_GAP_AD_TYPE_FLAGS;
flags.flags = BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
name.len = SIZEOF_ADV_STRUCTURE_NAME-1;
name.type = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME;
name.name[0] = 'A';
name.name[1] = 'B';
configuration.advertisingIntervalMs = 100;
configuration.messageCount = 1;
configuration.messageData[0].messageLength = 31;
memcpy(configuration.messageData[0].messageData, &flags, SIZEOF_ADV_STRUCTURE_FLAGS);
memcpy(configuration.messageData[0].messageData+SIZEOF_ADV_STRUCTURE_FLAGS, &name, SIZEOF_ADV_STRUCTURE_NAME);
}
void AdvertisingModule::NodeStateChangedHandler(discoveryState newState)
{
if(newState == discoveryState::BACK_OFF || newState == discoveryState::DISCOVERY_OFF){
//Activate our advertising
//This is a small packet for debugging a node's state
if(Config->advertiseDebugPackets){
u8 buffer[31];
memset(buffer, 0, 31);
advStructureFlags* flags = (advStructureFlags*)buffer;
flags->len = SIZEOF_ADV_STRUCTURE_FLAGS-1;
flags->type = BLE_GAP_AD_TYPE_FLAGS;
flags->flags = BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
advStructureManufacturer* manufacturer = (advStructureManufacturer*)(buffer+3);
manufacturer->len = 26;
manufacturer->type = BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA;
manufacturer->companyIdentifier = 0x24D;
AdvertisingModuleDebugMessage* msg = (AdvertisingModuleDebugMessage*)(buffer+7);
msg->debugPacketIdentifier = 0xDE;
msg->senderId = node->persistentConfig.nodeId;
msg->connLossCounter = node->persistentConfig.connectionLossCounter;
for(int i=0; i<Config->meshMaxConnections; i++){
if(cm->connections[i]->handshakeDone()){
msg->partners[i] = cm->connections[i]->partnerId;
msg->rssiVals[i] = cm->connections[i]->rssiAverage;
msg->droppedVals[i] = cm->connections[i]->droppedPackets;
} else {
msg->partners[i] = 0;
msg->rssiVals[i] = 0;
msg->droppedVals[i] = 0;
}
}
char strbuffer[200];
Logger::getInstance().convertBufferToHexString(buffer, 31, strbuffer, 200);
logt("ADVMOD", "ADV set to %s", strbuffer);
u32 err = sd_ble_gap_adv_data_set(buffer, 31, NULL, 0);
if(err != NRF_SUCCESS){
logt("ADVMOD", "Debug Packet corrupt");
}
AdvertisingController::SetAdvertisingState(advState::ADV_STATE_HIGH);
}
else if(configuration.messageCount > 0){
u32 err = sd_ble_gap_adv_data_set(configuration.messageData[0].messageData, configuration.messageData[0].messageLength, NULL, 0);
if(err != NRF_SUCCESS){
logt("ADVMOD", "Adv msg corrupt");
}
char buffer[200];
Logger::getInstance().convertBufferToHexString((u8*)configuration.messageData[0].messageData, 31, buffer, 200);
logt("ADVMOD", "ADV set to %s", buffer);
if(configuration.messageData[0].forceNonConnectable)
{
AdvertisingController::SetNonConnectable();
}
//Now, start advertising
//TODO: Use advertising parameters from config to advertise
AdvertisingController::SetAdvertisingState(advState::ADV_STATE_HIGH);
}
} else if (newState == discoveryState::DISCOVERY) {
//Do not trigger custom advertisings anymore, reset to node's advertising
node->UpdateJoinMePacket();
}
}
bool AdvertisingModule::TerminalCommandHandler(string commandName, vector<string> commandArgs)
{
if(commandArgs.size() >= 2 && commandArgs[1] == moduleName)
{
if(commandName == "action")
{
if(commandArgs[1] != moduleName) return false;
if(commandArgs[2] == "broadcast_debug")
{
Config->advertiseDebugPackets = !Config->advertiseDebugPackets;
logt("ADVMOD", "Debug Packets are now set to %u", Config->advertiseDebugPackets);
return true;
}
}
}
//Must be called to allow the module to get and set the config
return Module::TerminalCommandHandler(commandName, commandArgs);
}
| Informatic/fruitymesh | src/modules/AdvertisingModule.cpp | C++ | gpl-3.0 | 6,350 |
/*
* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R)
* products and how to contact NNL Technology AB.
*
* 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.
*/
// $Id: Info.java,v 1.6 2004/09/22 14:31:39 jesper Exp $
package com.supermap.desktop.ui.docking.info;
import com.supermap.desktop.ui.docking.DockingWindowsReleaseInfo;
import net.infonode.gui.ReleaseInfoDialog;
import net.infonode.gui.laf.InfoNodeLookAndFeelReleaseInfo;
import net.infonode.tabbedpanel.TabbedPanelReleaseInfo;
import net.infonode.util.ReleaseInfo;
/**
* Program that shows InfoNode Docking Windows release information in a dialog.
*
* @author $Author: jesper $
* @version $Revision: 1.6 $
*/
public class Info {
private Info() {
}
public static final void main(String[] args) {
ReleaseInfoDialog.showDialog(new ReleaseInfo[]{DockingWindowsReleaseInfo.getReleaseInfo(),
TabbedPanelReleaseInfo.getReleaseInfo(),
InfoNodeLookAndFeelReleaseInfo.getReleaseInfo()},
null);
System.exit(0);
}
}
| highsad/iDesktop-Cross | Controls/src/com/supermap/desktop/ui/docking/info/Info.java | Java | gpl-3.0 | 1,846 |
<?php
/**
* @package Joomla.Plugin
* @subpackage Content.Jtf
*
* @author Guido De Gobbis <support@joomtools.de>
* @copyright (c) 2017 JoomTools.de - All rights reserved.
* @license GNU General Public License version 3 or later
*/
defined('_JEXEC') or die;
extract($displayData);
/**
* Make thing clear
*
* @var JForm $form The form instance for render the section
* @var string $basegroup The base group name
* @var string $group Current group name
* @var string $unique_subform_id Unique subform id
* @var array $buttons Array of the buttons that will be rendered
*/
$subformClass = !empty($form->getAttribute('class')) ? ' ' . $form->getAttribute('class') : ' uk-width-1-1 uk-width-1-2@s uk-width-1-4@m'; ?>
<div class="subform-repeatable-group uk-margin-large-bottom<?php echo $subformClass; ?> subform-repeatable-group-<?php echo $unique_subform_id; ?>"
data-base-name="<?php echo $basegroup; ?>" data-group="<?php echo $group; ?>">
<?php foreach ($form->getGroup('') as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
<?php if (!empty($buttons)) : ?>
<div class="uk-margin-top uk-width-1-1 uk-text-right">
<div class="uk-button-group">
<?php if (!empty($buttons['add'])) : ?><a
class="group-add uk-button uk-button-small uk-button-secondary group-add-<?php echo $unique_subform_id; ?>"
aria-label="<?php echo JText::_('JGLOBAL_FIELD_ADD'); ?>"><span uk-icon="plus"></span>
</a><?php endif; ?>
<?php if (!empty($buttons['remove'])) : ?><a
class="group-remove uk-button uk-button-small uk-button-danger group-remove-<?php echo $unique_subform_id; ?>"
aria-label="<?php echo JText::_('JGLOBAL_FIELD_REMOVE'); ?>"><span uk-icon="minus"></span>
</a><?php endif; ?>
<?php if (!empty($buttons['move'])) : ?><a
class="group-move uk-button uk-button-small uk-button-primary group-move-<?php echo $unique_subform_id; ?>"
aria-label="<?php echo JText::_('JGLOBAL_FIELD_MOVE'); ?>"><span uk-icon="move"></span>
</a><?php endif; ?>
</div>
</div>
<?php endif; ?>
</div>
| JoomTools/plg_content_jtf | src/plugins/content/jtf/layouts/joomla/form/field/subform/repeatable/section.uikit3.php | PHP | gpl-3.0 | 2,183 |
package net.seabears.game.entities.normalmap;
import static java.util.stream.IntStream.range;
import java.io.IOException;
import java.util.List;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import net.seabears.game.entities.Entity;
import net.seabears.game.entities.Light;
import net.seabears.game.shadows.ShadowShader;
import net.seabears.game.textures.ModelTexture;
import net.seabears.game.util.TransformationMatrix;
public class NormalMappingShader extends ShadowShader {
public static final int TEXTURE_SHADOW = 2;
private final int lights;
private int locationClippingPlane;
private int locationModelTexture;
private int locationNormalMap;
private int[] locationLightAttenuation;
private int[] locationLightColor;
private int[] locationLightPosition;
private int locationProjectionMatrix;
private int locationReflectivity;
private int locationShineDamper;
private int locationSkyColor;
private int locationTextureRows;
private int locationTextureOffset;
private int locationTransformationMatrix;
private int locationViewMatrix;
public NormalMappingShader(int lights) throws IOException {
super(SHADER_ROOT + "normalmap/", TEXTURE_SHADOW);
this.lights = lights;
}
@Override
protected void bindAttributes() {
super.bindAttribute(ATTR_POSITION, "position");
super.bindAttribute(ATTR_TEXTURE, "textureCoords");
super.bindAttribute(ATTR_NORMAL, "normal");
super.bindAttribute(ATTR_TANGENT, "tangent");
}
@Override
protected void getAllUniformLocations() {
super.getAllUniformLocations();
locationClippingPlane = super.getUniformLocation("clippingPlane");
locationModelTexture = super.getUniformLocation("modelTexture");
locationNormalMap = super.getUniformLocation("normalMap");
locationLightAttenuation = super.getUniformLocations("attenuation", lights);
locationLightColor = super.getUniformLocations("lightColor", lights);
locationLightPosition = super.getUniformLocations("lightPosition", lights);
locationProjectionMatrix = super.getUniformLocation("projectionMatrix");
locationReflectivity = super.getUniformLocation("reflectivity");
locationShineDamper = super.getUniformLocation("shineDamper");
locationSkyColor = super.getUniformLocation("skyColor");
locationTextureRows = super.getUniformLocation("textureRows");
locationTextureOffset = super.getUniformLocation("textureOffset");
locationTransformationMatrix = super.getUniformLocation("transformationMatrix");
locationViewMatrix = super.getUniformLocation("viewMatrix");
}
public void loadClippingPlane(Vector4f plane) {
this.loadFloat(locationClippingPlane, plane);
}
public void loadLights(final List<Light> lights, Matrix4f viewMatrix) {
range(0, this.lights)
.forEach(i -> loadLight(i < lights.size() ? lights.get(i) : OFF_LIGHT, i, viewMatrix));
}
private void loadLight(Light light, int index, Matrix4f viewMatrix) {
super.loadFloat(locationLightAttenuation[index], light.getAttenuation());
super.loadFloat(locationLightColor[index], light.getColor());
super.loadFloat(locationLightPosition[index],
getEyeSpacePosition(light.getPosition(), viewMatrix));
}
public void loadProjectionMatrix(Matrix4f matrix) {
super.loadMatrix(locationProjectionMatrix, matrix);
}
public void loadSky(Vector3f color) {
super.loadFloat(locationSkyColor, color);
}
public void loadNormalMap() {
// refers to texture units
// TEXTURE_SHADOW occupies one unit
super.loadInt(locationModelTexture, 0);
super.loadInt(locationNormalMap, 1);
}
public void loadTexture(ModelTexture texture) {
super.loadFloat(locationReflectivity, texture.getReflectivity());
super.loadFloat(locationShineDamper, texture.getShineDamper());
super.loadFloat(locationTextureRows, texture.getRows());
}
public void loadEntity(Entity entity) {
loadTransformationMatrix(
new TransformationMatrix(entity.getPosition(), entity.getRotation(), entity.getScale())
.toMatrix());
super.loadFloat(locationTextureOffset, entity.getTextureOffset());
}
public void loadTransformationMatrix(Matrix4f matrix) {
super.loadMatrix(locationTransformationMatrix, matrix);
}
public void loadViewMatrix(Matrix4f matrix) {
super.loadMatrix(locationViewMatrix, matrix);
}
private static Vector3f getEyeSpacePosition(Vector3f position, Matrix4f viewMatrix) {
final Vector4f eyeSpacePos = new Vector4f(position.x, position.y, position.z, 1.0f);
viewMatrix.transform(eyeSpacePos);
return new Vector3f(eyeSpacePos.x, eyeSpacePos.y, eyeSpacePos.z);
}
}
| cberes/game | engine/src/main/java/net/seabears/game/entities/normalmap/NormalMappingShader.java | Java | gpl-3.0 | 4,691 |
'use strict'
// untuk status uploader
const STATUS_INITIAL = 0
const STATUS_SAVING = 1
const STATUS_SUCCESS = 2
const STATUS_FAILED = 3
// base url api
const BASE_URL = 'http://localhost:3000'
const app = new Vue({
el: '#app',
data: {
message: 'Hello',
currentStatus: null,
uploadError: null,
uploadFieldName: 'image',
uploadedFiles: [],
files:[]
},
computed: {
isInitial() {
return this.currentStatus === STATUS_INITIAL;
},
isSaving() {
return this.currentStatus === STATUS_SAVING;
},
isSuccess() {
return this.currentStatus === STATUS_SUCCESS;
},
isFailed() {
return this.currentStatus === STATUS_FAILED;
}
}, // computed
methods: {
// reset form to initial state
getAllFile () {
let self = this
axios.get(`${BASE_URL}/files`)
.then(response => {
self.files = response.data
})
}, // getAllFile()
deleteFile (id) {
axios.delete(`${BASE_URL}/files/${id}`)
.then(r => {
this.files.splice(id, 1)
})
},
reset() {
this.currentStatus = STATUS_INITIAL;
this.uploadedFiles = [];
this.uploadError = null;
}, // reset()
// upload data to the server
save(formData) {
console.log('save')
console.log('form data', formData)
this.currentStatus = STATUS_SAVING;
axios.post(`${BASE_URL}/files/add`, formData)
.then(up => {
// console.log('up', up)
this.uploadedFiles = [].concat(up)
this.currentStatus = STATUS_SUCCESS
})
.catch(e => {
console.log(e.response.data)
this.currentStatus = STATUS_FAILED
})
}, // save()
filesChange(fieldName, fileList) {
// handle file changes
const formData = new FormData();
formData.append('image', fileList[0])
console.log(formData)
this.save(formData);
} // filesChange()
}, // methods
mounted () {
this.reset()
},
created () {
this.getAllFile()
}
})
| hariantara/rapid-share-clone | client/assets/lib/upload.js | JavaScript | gpl-3.0 | 2,046 |
Simpla CMS 2.3.8 = f8952829bab201835e255735de3774f0
| gohdan/DFC | known_files/hashes/Smarty/libs/sysplugins/smarty_internal_compile_extends.php | PHP | gpl-3.0 | 52 |
#include "../header/Base.h"
#include "../header/Decorator.h"
Decorator::Decorator() {
}
Decorator::Decorator(Base* node) {
}
Decorator::~Decorator() {
}
| ksemelka/rshell | src/Decorator.cpp | C++ | gpl-3.0 | 156 |
/*
* Copyright (C) 2010-2021 JPEXS
*
* 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 com.jpexs.decompiler.flash.gui.timeline;
import com.jpexs.decompiler.flash.configuration.Configuration;
import com.jpexs.decompiler.flash.tags.base.CharacterTag;
import com.jpexs.decompiler.flash.tags.base.MorphShapeTag;
import com.jpexs.decompiler.flash.timeline.DepthState;
import com.jpexs.decompiler.flash.timeline.Timeline;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.SystemColor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
import org.pushingpixels.substance.api.ColorSchemeAssociationKind;
import org.pushingpixels.substance.api.ComponentState;
import org.pushingpixels.substance.api.DecorationAreaType;
import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.internal.utils.SubstanceColorUtilities;
/**
*
* @author JPEXS
*/
public class TimelineBodyPanel extends JPanel implements MouseListener, KeyListener {
private final Timeline timeline;
public static final Color shapeTweenColor = new Color(0x59, 0xfe, 0x7c);
public static final Color motionTweenColor = new Color(0xd1, 0xac, 0xf1);
//public static final Color frameColor = new Color(0xbd, 0xd8, 0xfc);
public static final Color borderColor = Color.black;
public static final Color emptyBorderColor = new Color(0xbd, 0xd8, 0xfc);
public static final Color keyColor = Color.black;
public static final Color aColor = Color.black;
public static final Color stopColor = Color.white;
public static final Color stopBorderColor = Color.black;
public static final Color borderLinesColor = new Color(0xde, 0xde, 0xde);
//public static final Color selectedColor = new Color(113, 174, 235);
public static final int borderLinesLength = 2;
public static final float fontSize = 10.0f;
private final List<FrameSelectionListener> listeners = new ArrayList<>();
public Point cursor = null;
private enum BlockType {
EMPTY, NORMAL, MOTION_TWEEN, SHAPE_TWEEN
}
public static Color getEmptyFrameColor() {
return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.7);
}
public static Color getEmptyFrameSecondColor() {
return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.9);
}
public static Color getSelectedColor() {
if (Configuration.useRibbonInterface.get()) {
return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ROLLOVER_SELECTED).getBackgroundFillColor();
} else {
return SystemColor.textHighlight;
}
}
private static Color getControlColor() {
if (Configuration.useRibbonInterface.get()) {
return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ENABLED).getBackgroundFillColor();
} else {
return SystemColor.control;
}
}
public static Color getFrameColor() {
return SubstanceColorUtilities.getDarkerColor(getControlColor(), 0.1);
}
public void addFrameSelectionListener(FrameSelectionListener l) {
listeners.add(l);
}
public void removeFrameSelectionListener(FrameSelectionListener l) {
listeners.remove(l);
}
public TimelineBodyPanel(Timeline timeline) {
this.timeline = timeline;
Dimension dim = new Dimension(TimelinePanel.FRAME_WIDTH * timeline.getFrameCount() + 1, TimelinePanel.FRAME_HEIGHT * timeline.getMaxDepth());
setSize(dim);
setPreferredSize(dim);
addMouseListener(this);
addKeyListener(this);
setFocusable(true);
}
@Override
protected void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(TimelinePanel.getBackgroundColor());
g.fillRect(0, 0, getWidth(), getHeight());
Rectangle clip = g.getClipBounds();
int frameWidth = TimelinePanel.FRAME_WIDTH;
int frameHeight = TimelinePanel.FRAME_HEIGHT;
int start_f = clip.x / frameWidth;
int start_d = clip.y / frameHeight;
int end_f = (clip.x + clip.width) / frameWidth;
int end_d = (clip.y + clip.height) / frameHeight;
int max_d = timeline.getMaxDepth();
if (max_d < end_d) {
end_d = max_d;
}
int max_f = timeline.getFrameCount() - 1;
if (max_f < end_f) {
end_f = max_f;
}
if (end_d - start_d + 1 < 0) {
return;
}
// draw background
for (int f = start_f; f <= end_f; f++) {
g.setColor((f + 1) % 5 == 0 ? getEmptyFrameSecondColor() : getEmptyFrameColor());
g.fillRect(f * frameWidth, start_d * frameHeight, frameWidth, (end_d - start_d + 1) * frameHeight);
g.setColor(emptyBorderColor);
for (int d = start_d; d <= end_d; d++) {
g.drawRect(f * frameWidth, d * frameHeight, frameWidth, frameHeight);
}
}
// draw selected cell
if (cursor != null) {
g.setColor(getSelectedColor());
g.fillRect(cursor.x * frameWidth + 1, cursor.y * frameHeight + 1, frameWidth - 1, frameHeight - 1);
}
g.setColor(aColor);
g.setFont(getFont().deriveFont(fontSize));
int awidth = g.getFontMetrics().stringWidth("a");
for (int f = start_f; f <= end_f; f++) {
if (!timeline.getFrame(f).actions.isEmpty()) {
g.drawString("a", f * frameWidth + frameWidth / 2 - awidth / 2, frameHeight / 2 + fontSize / 2);
}
}
Map<Integer, Integer> depthMaxFrames = timeline.getDepthMaxFrame();
for (int d = start_d; d <= end_d; d++) {
int maxFrame = depthMaxFrames.containsKey(d) ? depthMaxFrames.get(d) : -1;
if (maxFrame < 0) {
continue;
}
int end_f2 = Math.min(end_f, maxFrame);
int start_f2 = Math.min(start_f, end_f2);
// find the start frame number of the current block
DepthState dsStart = timeline.getFrame(start_f2).layers.get(d);
for (; start_f2 >= 1; start_f2--) {
DepthState ds = timeline.getFrame(start_f2 - 1).layers.get(d);
if (((dsStart == null) != (ds == null))
|| (ds != null && dsStart.characterId != ds.characterId)) {
break;
}
}
for (int f = start_f2; f <= end_f2; f++) {
DepthState fl = timeline.getFrame(f).layers.get(d);
boolean motionTween = fl == null ? false : fl.motionTween;
DepthState flNext = f < max_f ? timeline.getFrame(f + 1).layers.get(d) : null;
DepthState flPrev = f > 0 ? timeline.getFrame(f - 1).layers.get(d) : null;
CharacterTag cht = fl == null ? null : timeline.swf.getCharacter(fl.characterId);
boolean shapeTween = cht != null && (cht instanceof MorphShapeTag);
boolean motionTweenStart = !motionTween && (flNext != null && flNext.motionTween);
boolean motionTweenEnd = !motionTween && (flPrev != null && flPrev.motionTween);
//boolean shapeTweenStart = shapeTween && (flPrev == null || flPrev.characterId != fl.characterId);
//boolean shapeTweenEnd = shapeTween && (flNext == null || flNext.characterId != fl.characterId);
/*if (motionTweenStart || motionTweenEnd) {
motionTween = true;
}*/
int draw_f = f;
int num_frames = 1;
Color backColor;
BlockType blockType;
if (fl == null) {
for (; f + 1 < timeline.getFrameCount(); f++) {
fl = timeline.getFrame(f + 1).layers.get(d);
if (fl != null && fl.characterId != -1) {
break;
}
num_frames++;
}
backColor = getEmptyFrameColor();
blockType = BlockType.EMPTY;
} else {
for (; f + 1 < timeline.getFrameCount(); f++) {
fl = timeline.getFrame(f + 1).layers.get(d);
if (fl == null || fl.key) {
break;
}
num_frames++;
}
backColor = shapeTween ? shapeTweenColor : motionTween ? motionTweenColor : getFrameColor();
blockType = shapeTween ? BlockType.SHAPE_TWEEN : motionTween ? BlockType.MOTION_TWEEN : BlockType.NORMAL;
}
drawBlock(g, backColor, d, draw_f, num_frames, blockType);
}
}
if (cursor != null && cursor.x >= start_f && cursor.x <= end_f) {
g.setColor(TimelinePanel.selectedBorderColor);
g.drawLine(cursor.x * frameWidth + frameWidth / 2, 0, cursor.x * frameWidth + frameWidth / 2, getHeight());
}
}
private void drawBlock(Graphics2D g, Color backColor, int depth, int frame, int num_frames, BlockType blockType) {
int frameWidth = TimelinePanel.FRAME_WIDTH;
int frameHeight = TimelinePanel.FRAME_HEIGHT;
g.setColor(backColor);
g.fillRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight);
g.setColor(borderColor);
g.drawRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight);
boolean selected = false;
if (cursor != null && frame <= cursor.x && (frame + num_frames) > cursor.x && depth == cursor.y) {
selected = true;
}
if (selected) {
g.setColor(getSelectedColor());
g.fillRect(cursor.x * frameWidth + 1, depth * frameHeight + 1, frameWidth - 1, frameHeight - 1);
}
boolean isTween = blockType == BlockType.MOTION_TWEEN || blockType == BlockType.SHAPE_TWEEN;
g.setColor(keyColor);
if (isTween) {
g.drawLine(frame * frameWidth, depth * frameHeight + frameHeight * 3 / 4,
frame * frameWidth + num_frames * frameWidth - frameWidth / 2, depth * frameHeight + frameHeight * 3 / 4
);
}
if (blockType == BlockType.EMPTY) {
g.drawOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2);
} else {
g.fillOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2);
}
if (num_frames > 1) {
int endFrame = frame + num_frames - 1;
if (isTween) {
g.fillOval(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2);
} else {
g.setColor(stopColor);
g.fillRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2);
g.setColor(stopBorderColor);
g.drawRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2);
}
g.setColor(borderLinesColor);
for (int n = frame + 1; n < frame + num_frames; n++) {
g.drawLine(n * frameWidth, depth * frameHeight + 1, n * frameWidth, depth * frameHeight + borderLinesLength);
g.drawLine(n * frameWidth, depth * frameHeight + frameHeight - 1, n * frameWidth, depth * frameHeight + frameHeight - borderLinesLength);
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
public void frameSelect(int frame, int depth) {
if (cursor != null && cursor.x == frame && (cursor.y == depth || depth == -1)) {
return;
}
if (depth == -1 && cursor != null) {
depth = cursor.y;
}
cursor = new Point(frame, depth);
for (FrameSelectionListener l : listeners) {
l.frameSelected(frame, depth);
}
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
p.x = p.x / TimelinePanel.FRAME_WIDTH;
p.y = p.y / TimelinePanel.FRAME_HEIGHT;
if (p.x >= timeline.getFrameCount()) {
p.x = timeline.getFrameCount() - 1;
}
int maxDepth = timeline.getMaxDepth();
if (p.y > maxDepth) {
p.y = maxDepth;
}
frameSelect(p.x, p.y);
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 37: //left
if (cursor.x > 0) {
frameSelect(cursor.x - 1, cursor.y);
}
break;
case 39: //right
if (cursor.x < timeline.getFrameCount() - 1) {
frameSelect(cursor.x + 1, cursor.y);
}
break;
case 38: //up
if (cursor.y > 0) {
frameSelect(cursor.x, cursor.y - 1);
}
break;
case 40: //down
if (cursor.y < timeline.getMaxDepth()) {
frameSelect(cursor.x, cursor.y + 1);
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| jindrapetrik/jpexs-decompiler | src/com/jpexs/decompiler/flash/gui/timeline/TimelineBodyPanel.java | Java | gpl-3.0 | 15,335 |
//===========================================================================//
// File: memblock.hh //
// Contents: Interface specification of the memory block class //
//---------------------------------------------------------------------------//
// Copyright (C) Microsoft Corporation. All rights reserved. //
//===========================================================================//
#pragma once
#include"stuff.hpp"
namespace Stuff {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockHeader ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryBlockHeader
{
public:
MemoryBlockHeader
*nextBlock;
size_t
blockSize;
void
TestInstance()
{}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockBase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryBlockBase
#if defined(_ARMOR)
: public Stuff::Signature
#endif
{
public:
void
TestInstance()
{Verify(blockMemory != NULL);}
static void
UsageReport();
static void
CollapseBlocks();
protected:
const char
*blockName;
MemoryBlockHeader
*blockMemory; // the first record block allocated
size_t
blockSize, // size in bytes of the current record block
recordSize, // size in bytes of the individual record
deltaSize; // size in bytes of the growth blocks
BYTE
*firstHeaderRecord, // the beginning of useful free space
*freeRecord, // the next address to allocate from the block
*deletedRecord; // the next record to reuse
MemoryBlockBase(
size_t rec_size,
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
);
~MemoryBlockBase();
void*
Grow();
HGOSHEAP
blockHeap;
private:
static MemoryBlockBase
*firstBlock;
MemoryBlockBase
*nextBlock,
*previousBlock;
void
Collapse();
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlock ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryBlock:
public MemoryBlockBase
{
public:
static bool
TestClass();
MemoryBlock(
size_t rec_size,
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
):
MemoryBlockBase(rec_size, start, delta, name, parent)
{}
void*
New();
void
Delete(void *Where);
void*
operator[](size_t Index);
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockOf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T> class MemoryBlockOf:
public MemoryBlock
{
public:
MemoryBlockOf(
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
):
MemoryBlock(sizeof(T), start, delta, name, parent)
{}
T*
New()
{return Cast_Pointer(T*, MemoryBlock::New());}
void
Delete(void *where)
{MemoryBlock::Delete(where);}
T*
operator[](size_t index)
{return Cast_Pointer(T*, MemoryBlock::operator[](index));}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryStack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryStack:
public MemoryBlockBase
{
public:
static bool
TestClass();
protected:
BYTE
*topOfStack;
MemoryStack(
size_t rec_size,
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
):
MemoryBlockBase(rec_size, start, delta, name, parent)
{topOfStack = NULL;}
void*
Push(const void *What);
void*
Push();
void*
Peek()
{return topOfStack;}
void
Pop();
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryStackOf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T> class MemoryStackOf:
public MemoryStack
{
public:
MemoryStackOf(
size_t start,
size_t delta,
const char *name,
HGOSHEAP parent = ParentClientHeap
):
MemoryStack(sizeof(T), start, delta, name, parent)
{}
T*
Push(const T *what)
{return Cast_Pointer(T*, MemoryStack::Push(what));}
T*
Peek()
{return static_cast<T*>(MemoryStack::Peek());}
void
Pop()
{MemoryStack::Pop();}
};
}
| alariq/mc2 | mclib/stuff/memoryblock.hpp | C++ | gpl-3.0 | 4,175 |
#!/usr/bin/env python
import turtle
import random
def bloom(radius):
turtle.colormode(255)
for rad in range(40, 10, -5):
for looper in range(360//rad):
turtle.up()
turtle.circle(radius+rad, rad)
turtle.begin_fill()
turtle.fillcolor((200+random.randint(0, rad),
200+random.randint(0, rad),
200+random.randint(0, rad)))
turtle.down()
turtle.circle(-rad)
turtle.end_fill()
def main():
"""Simple flower, using global turtle instance"""
turtle.speed(0)
turtle.colormode(1.0)
bloom(5)
turtle.exitonclick()
###
if __name__ == "__main__":
main()
| mpclemens/python-explore | turtle/bloom.py | Python | gpl-3.0 | 728 |
/*
* Orbit, a versatile image analysis software for biological image-based quantification.
* Copyright (C) 2009 - 2017 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, CH-4123 Allschwil, Switzerland.
*
* 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 com.actelion.research.orbit.imageprovider.tree;
import com.actelion.research.orbit.beans.RawData;
import com.actelion.research.orbit.imageprovider.ImageProviderOmero;
import com.actelion.research.orbit.utils.Logger;
import java.util.ArrayList;
import java.util.List;
public class TreeNodeProject extends AbstractOrbitTreeNode {
private static Logger logger = Logger.getLogger(TreeNodeProject.class);
private RawData project = null;
private ImageProviderOmero imageProviderOmero;
public TreeNodeProject(ImageProviderOmero imageProviderOmero, RawData project) {
this.imageProviderOmero = imageProviderOmero;
this.project = project;
}
@Override
public synchronized List<TreeNodeProject> getNodes(AbstractOrbitTreeNode parent) {
List<TreeNodeProject> nodeList = new ArrayList<>();
int group = -1;
if (parent!=null && parent instanceof TreeNodeGroup) {
TreeNodeGroup groupNode = (TreeNodeGroup) parent;
RawData rdGroup = (RawData) groupNode.getIdentifier();
group = rdGroup.getRawDataId();
}
List<RawData> rdList = loadProjects(group);
for (RawData rd : rdList) {
nodeList.add(new TreeNodeProject(imageProviderOmero, rd));
}
return nodeList;
}
@Override
public boolean isChildOf(Object parent) {
return parent instanceof TreeNodeGroup;
}
@Override
public Object getIdentifier() {
return project;
}
@Override
public String toString() {
return project != null ? project.getBioLabJournal() : "";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TreeNodeProject that = (TreeNodeProject) o;
return project != null ? project.equals(that.project) : that.project == null;
}
@Override
public int hashCode() {
return project != null ? project.hashCode() : 0;
}
private List<RawData> loadProjects(int group) {
return imageProviderOmero.loadProjects(group);
}
}
| mstritt/image-provider-omero | src/main/java/com/actelion/research/orbit/imageprovider/tree/TreeNodeProject.java | Java | gpl-3.0 | 3,070 |
/**
*
* Copyright 2014 Martijn Brekhof
*
* This file is part of Catch Da Stars.
*
* Catch Da Stars 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.
*
* Catch Da Stars 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 Catch Da Stars. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.strategames.engine.gameobject.types;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.strategames.engine.gameobject.GameObject;
import com.strategames.engine.gameobject.StaticBody;
import com.strategames.engine.utils.ConfigurationItem;
import com.strategames.engine.utils.Textures;
public class Door extends StaticBody {
public final static float WIDTH = 0.35f;
public final static float HEIGHT = 0.35f;
private Wall wall;
private boolean open;
private int[] entryLevel = new int[2]; // level this door provides access too
private int[] exitLevel = new int[2]; // level this door can be accessed from
public Door() {
super(new Vector2(WIDTH, HEIGHT));
}
@Override
protected TextureRegion createImage() {
return Textures.getInstance().passageToNextLevel;
}
@Override
protected void setupBody(Body body) {
Vector2 leftBottom = new Vector2(0, 0);
Vector2 rightBottom = new Vector2(WIDTH, 0);
Vector2 rightTop = new Vector2(WIDTH, HEIGHT);
Vector2 leftTop = new Vector2(0, HEIGHT);
ChainShape chain = new ChainShape();
chain.createLoop(new Vector2[] {leftBottom, rightBottom, rightTop, leftTop});
Fixture fixture = body.createFixture(chain, 0.0f);
fixture.setSensor(true);
}
@Override
protected void writeValues(Json json) {
json.writeArrayStart("nextLevelPosition");
json.writeValue(entryLevel[0]);
json.writeValue(entryLevel[1]);
json.writeArrayEnd();
}
@Override
protected void readValue(JsonValue jsonData) {
String name = jsonData.name();
if( name.contentEquals("nextLevelPosition")) {
this.entryLevel = jsonData.asIntArray();
}
}
@Override
public GameObject copy() {
Door door = (Door) newInstance();
door.setPosition(getX(), getY());
int[] pos = getAccessToPosition();
door.setAccessTo(pos[0], pos[1]);
return door;
}
@Override
protected GameObject newInstance() {
return new Door();
}
@Override
protected ArrayList<ConfigurationItem> createConfigurationItems() {
return null;
}
@Override
public void increaseSize() {
}
@Override
public void decreaseSize() {
}
@Override
protected void destroyAction() {
}
@Override
public void handleCollision(Contact contact, ContactImpulse impulse,
GameObject gameObject) {
}
@Override
public void loadSounds() {
}
public Wall getWall() {
return wall;
}
public void setWall(Wall wall) {
this.wall = wall;
}
public boolean isOpen() {
return open;
}
/**
* Sets the level position this door provides access too
* @param x
* @param y
*/
public void setAccessTo(int x, int y) {
this.entryLevel[0] = x;
this.entryLevel[1] = y;
}
/**
* Returns the level position this door provides access too
* @return
*/
public int[] getAccessToPosition() {
return entryLevel;
}
/**
* Sets the level position from which this door is accessible
* @param exitLevel
*/
public void setExitLevel(int[] exitLevel) {
this.exitLevel = exitLevel;
}
/**
* Returns the level position this door is accessible from
* @return
*/
public int[] getAccessFromPosition() {
return exitLevel;
}
@Override
public String toString() {
return super.toString() + ", nextLevelPosition="+entryLevel[0]+","+entryLevel[1];
}
@Override
public boolean equals(Object obj) {
Door door;
if( obj instanceof Door ) {
door = (Door) obj;
} else {
return false;
}
int[] pos = door.getAccessToPosition();
return pos[0] == entryLevel[0] && pos[1] == entryLevel[1] &&
super.equals(obj);
}
public void open() {
Gdx.app.log("Door", "open");
this.open = true;
}
public void close(){
this.open = false;
}
}
| poisdeux/catchdastars | core/src/com/strategames/engine/gameobject/types/Door.java | Java | gpl-3.0 | 4,823 |
/*
Buffer.cpp - This file is part of Element
Copyright (C) 2014 Kushview, LLC. All rights reserved.
*/
#if ELEMENT_BUFFER_FACTORY
Buffer::Buffer (DataType dataType_, uint32 subType_)
: factory (nullptr),
refs (0),
dataType (dataType_),
subType (subType_),
capacity (0),
next (nullptr)
{ }
Buffer::~Buffer() { }
void Buffer::attach (BufferFactory* owner)
{
jassert (factory == nullptr && owner != nullptr);
factory = owner;
}
void Buffer::recycle()
{
if (isManaged())
factory->recycle (this);
}
void intrusive_ptr_add_ref (Buffer* b)
{
if (b->isManaged())
++b->refs;
}
void intrusive_ptr_release (Buffer* b)
{
if (b->isManaged())
if (--b->refs == 0)
b->recycle();
}
#endif
| kushview/element | experimental/Buffer.cpp | C++ | gpl-3.0 | 780 |
/*
* Decompiled with CFR 0_115.
*
* Could not load the following classes:
* android.content.BroadcastReceiver
* android.content.Context
* android.content.Intent
* android.content.IntentFilter
*/
package com.buzzfeed.android.vcr.util;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import com.buzzfeed.android.vcr.VCRConfig;
import com.buzzfeed.toolkit.util.EZUtil;
public final class VCRBitrateLimitingReceiver {
private final Context mContext;
private final BroadcastReceiver mReceiver;
public VCRBitrateLimitingReceiver(@NonNull Context context) {
this.mContext = EZUtil.checkNotNull(context, "Context must not be null.");
this.mReceiver = new ConnectivityReceiver();
}
public void register() {
this.mContext.registerReceiver(this.mReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
public void unregister() {
this.mContext.unregisterReceiver(this.mReceiver);
}
private final class ConnectivityReceiver
extends BroadcastReceiver {
private ConnectivityReceiver() {
}
public void onReceive(Context context, Intent intent) {
VCRConfig.getInstance().setAdaptiveBitrateLimitForConnection(context);
}
}
}
| SPACEDAC7/TrabajoFinalGrado | uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/buzzfeed/android/vcr/util/VCRBitrateLimitingReceiver.java | Java | gpl-3.0 | 1,401 |
namespace SandbarWorkbench
{
partial class frmOptions
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmOptions));
this.cmdOK = new System.Windows.Forms.Button();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.txtInstallationGuid = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rdo5Digits = new System.Windows.Forms.RadioButton();
this.rdo4Digits = new System.Windows.Forms.RadioButton();
this.cboStartupView = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.chkLoadLastDatabase = new System.Windows.Forms.CheckBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.txtMasterDatabase = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtMasterPassword = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtMasterUserName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.txtMasterServer = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.grdFolderPaths = new System.Windows.Forms.DataGridView();
this.tabPage4 = new System.Windows.Forms.TabPage();
this.button1 = new System.Windows.Forms.Button();
this.txtMainPy = new System.Windows.Forms.TextBox();
this.label17 = new System.Windows.Forms.Label();
this.valBenchmark = new System.Windows.Forms.NumericUpDown();
this.label16 = new System.Windows.Forms.Label();
this.valIncrement = new System.Windows.Forms.NumericUpDown();
this.label15 = new System.Windows.Forms.Label();
this.cmdBrowseGDALWarp = new System.Windows.Forms.Button();
this.txtGDALWarp = new System.Windows.Forms.TextBox();
this.label14 = new System.Windows.Forms.Label();
this.cmdBrowseCompExtents = new System.Windows.Forms.Button();
this.txtCompExtents = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.txtSpatialReference = new System.Windows.Forms.TextBox();
this.cboInterpolation = new System.Windows.Forms.ComboBox();
this.label8 = new System.Windows.Forms.Label();
this.valDefaultOutputCellSize = new System.Windows.Forms.NumericUpDown();
this.valDefaultInputCellSize = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.tabPage5 = new System.Windows.Forms.TabPage();
this.cmdTestAWS = new System.Windows.Forms.Button();
this.txtErrorLoggingKey = new System.Windows.Forms.TextBox();
this.lblStreamName = new System.Windows.Forms.Label();
this.chkAWSLoggingEnabled = new System.Windows.Forms.CheckBox();
this.tabPage6 = new System.Windows.Forms.TabPage();
this.cboAuditFieldDates = new System.Windows.Forms.ComboBox();
this.label12 = new System.Windows.Forms.Label();
this.cboSurveyDates = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.cboTripDates = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.tabPage7 = new System.Windows.Forms.TabPage();
this.txtPython = new System.Windows.Forms.TextBox();
this.cmdHelp = new System.Windows.Forms.Button();
this.tt = new System.Windows.Forms.ToolTip(this.components);
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdFolderPaths)).BeginInit();
this.tabPage4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.valBenchmark)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.valIncrement)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.valDefaultOutputCellSize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.valDefaultInputCellSize)).BeginInit();
this.tabPage5.SuspendLayout();
this.tabPage6.SuspendLayout();
this.tabPage7.SuspendLayout();
this.SuspendLayout();
//
// cmdOK
//
this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.cmdOK.Location = new System.Drawing.Point(491, 373);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(75, 23);
this.cmdOK.TabIndex = 0;
this.cmdOK.Text = "Close";
this.cmdOK.UseVisualStyleBackColor = true;
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// tabControl1
//
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage4);
this.tabControl1.Controls.Add(this.tabPage5);
this.tabControl1.Controls.Add(this.tabPage6);
this.tabControl1.Controls.Add(this.tabPage7);
this.tabControl1.Location = new System.Drawing.Point(12, 12);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(554, 355);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.txtInstallationGuid);
this.tabPage1.Controls.Add(this.label9);
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Controls.Add(this.cboStartupView);
this.tabPage1.Controls.Add(this.label1);
this.tabPage1.Controls.Add(this.chkLoadLastDatabase);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(546, 329);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Start Up";
this.tabPage1.UseVisualStyleBackColor = true;
//
// txtInstallationGuid
//
this.txtInstallationGuid.Location = new System.Drawing.Point(122, 171);
this.txtInstallationGuid.MaxLength = 256;
this.txtInstallationGuid.Name = "txtInstallationGuid";
this.txtInstallationGuid.ReadOnly = true;
this.txtInstallationGuid.Size = new System.Drawing.Size(292, 20);
this.txtInstallationGuid.TabIndex = 5;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(29, 175);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(87, 13);
this.label9.TabIndex = 4;
this.label9.Text = "Installation GUID";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rdo5Digits);
this.groupBox1.Controls.Add(this.rdo4Digits);
this.groupBox1.Location = new System.Drawing.Point(29, 80);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(385, 79);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Sandbar Folder Identification";
//
// rdo5Digits
//
this.rdo5Digits.AutoSize = true;
this.rdo5Digits.Location = new System.Drawing.Point(27, 49);
this.rdo5Digits.Name = "rdo5Digits";
this.rdo5Digits.Size = new System.Drawing.Size(145, 17);
this.rdo5Digits.TabIndex = 1;
this.rdo5Digits.Text = "5 digit codes (e.g. 0003L)";
this.rdo5Digits.UseVisualStyleBackColor = true;
//
// rdo4Digits
//
this.rdo4Digits.AutoSize = true;
this.rdo4Digits.Checked = true;
this.rdo4Digits.Location = new System.Drawing.Point(27, 25);
this.rdo4Digits.Name = "rdo4Digits";
this.rdo4Digits.Size = new System.Drawing.Size(139, 17);
this.rdo4Digits.TabIndex = 0;
this.rdo4Digits.TabStop = true;
this.rdo4Digits.Text = "4 digit codes (e.g. 003L)";
this.rdo4Digits.UseVisualStyleBackColor = true;
//
// cboStartupView
//
this.cboStartupView.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboStartupView.FormattingEnabled = true;
this.cboStartupView.Location = new System.Drawing.Point(149, 44);
this.cboStartupView.Name = "cboStartupView";
this.cboStartupView.Size = new System.Drawing.Size(265, 21);
this.cboStartupView.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(26, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Open view at start up";
//
// chkLoadLastDatabase
//
this.chkLoadLastDatabase.AutoSize = true;
this.chkLoadLastDatabase.Location = new System.Drawing.Point(25, 16);
this.chkLoadLastDatabase.Name = "chkLoadLastDatabase";
this.chkLoadLastDatabase.Size = new System.Drawing.Size(116, 17);
this.chkLoadLastDatabase.TabIndex = 0;
this.chkLoadLastDatabase.Text = "Load last database";
this.chkLoadLastDatabase.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.txtMasterDatabase);
this.tabPage2.Controls.Add(this.label5);
this.tabPage2.Controls.Add(this.txtMasterPassword);
this.tabPage2.Controls.Add(this.label4);
this.tabPage2.Controls.Add(this.txtMasterUserName);
this.tabPage2.Controls.Add(this.label3);
this.tabPage2.Controls.Add(this.txtMasterServer);
this.tabPage2.Controls.Add(this.label2);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(546, 329);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Master Database";
this.tabPage2.UseVisualStyleBackColor = true;
//
// txtMasterDatabase
//
this.txtMasterDatabase.Location = new System.Drawing.Point(98, 50);
this.txtMasterDatabase.Name = "txtMasterDatabase";
this.txtMasterDatabase.Size = new System.Drawing.Size(433, 20);
this.txtMasterDatabase.TabIndex = 3;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(37, 54);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 13);
this.label5.TabIndex = 2;
this.label5.Text = "Database";
//
// txtMasterPassword
//
this.txtMasterPassword.Location = new System.Drawing.Point(98, 114);
this.txtMasterPassword.Name = "txtMasterPassword";
this.txtMasterPassword.PasswordChar = '*';
this.txtMasterPassword.Size = new System.Drawing.Size(433, 20);
this.txtMasterPassword.TabIndex = 7;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(37, 118);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(53, 13);
this.label4.TabIndex = 6;
this.label4.Text = "Password";
//
// txtMasterUserName
//
this.txtMasterUserName.Location = new System.Drawing.Point(98, 82);
this.txtMasterUserName.Name = "txtMasterUserName";
this.txtMasterUserName.Size = new System.Drawing.Size(433, 20);
this.txtMasterUserName.TabIndex = 5;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(32, 86);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(58, 13);
this.label3.TabIndex = 4;
this.label3.Text = "User name";
//
// txtMasterServer
//
this.txtMasterServer.Location = new System.Drawing.Point(98, 18);
this.txtMasterServer.Name = "txtMasterServer";
this.txtMasterServer.Size = new System.Drawing.Size(433, 20);
this.txtMasterServer.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(52, 22);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Server";
//
// tabPage3
//
this.tabPage3.Controls.Add(this.grdFolderPaths);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(546, 329);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Folders";
this.tabPage3.UseVisualStyleBackColor = true;
//
// grdFolderPaths
//
this.grdFolderPaths.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdFolderPaths.Location = new System.Drawing.Point(125, 112);
this.grdFolderPaths.Name = "grdFolderPaths";
this.grdFolderPaths.Size = new System.Drawing.Size(240, 150);
this.grdFolderPaths.TabIndex = 0;
this.grdFolderPaths.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.grdFolderPaths_CellClick);
//
// tabPage4
//
this.tabPage4.Controls.Add(this.button1);
this.tabPage4.Controls.Add(this.txtMainPy);
this.tabPage4.Controls.Add(this.label17);
this.tabPage4.Controls.Add(this.valBenchmark);
this.tabPage4.Controls.Add(this.label16);
this.tabPage4.Controls.Add(this.valIncrement);
this.tabPage4.Controls.Add(this.label15);
this.tabPage4.Controls.Add(this.cmdBrowseGDALWarp);
this.tabPage4.Controls.Add(this.txtGDALWarp);
this.tabPage4.Controls.Add(this.label14);
this.tabPage4.Controls.Add(this.cmdBrowseCompExtents);
this.tabPage4.Controls.Add(this.txtCompExtents);
this.tabPage4.Controls.Add(this.label13);
this.tabPage4.Controls.Add(this.groupBox2);
this.tabPage4.Controls.Add(this.cboInterpolation);
this.tabPage4.Controls.Add(this.label8);
this.tabPage4.Controls.Add(this.valDefaultOutputCellSize);
this.tabPage4.Controls.Add(this.valDefaultInputCellSize);
this.tabPage4.Controls.Add(this.label7);
this.tabPage4.Controls.Add(this.label6);
this.tabPage4.Location = new System.Drawing.Point(4, 22);
this.tabPage4.Name = "tabPage4";
this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
this.tabPage4.Size = new System.Drawing.Size(546, 329);
this.tabPage4.TabIndex = 3;
this.tabPage4.Text = "Sandbar Analysis";
this.tabPage4.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Image = global::SandbarWorkbench.Properties.Resources.explorer;
this.button1.Location = new System.Drawing.Point(517, 171);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(23, 23);
this.button1.TabIndex = 18;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtMainPy
//
this.txtMainPy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtMainPy.Location = new System.Drawing.Point(176, 172);
this.txtMainPy.Name = "txtMainPy";
this.txtMainPy.ReadOnly = true;
this.txtMainPy.Size = new System.Drawing.Size(335, 20);
this.txtMainPy.TabIndex = 17;
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(39, 176);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(128, 13);
this.label17.TabIndex = 16;
this.label17.Text = "Sandbar Analysis Main.py";
//
// valBenchmark
//
this.valBenchmark.Increment = new decimal(new int[] {
1000,
0,
0,
0});
this.valBenchmark.Location = new System.Drawing.Point(420, 49);
this.valBenchmark.Maximum = new decimal(new int[] {
40000,
0,
0,
0});
this.valBenchmark.Name = "valBenchmark";
this.valBenchmark.Size = new System.Drawing.Size(120, 20);
this.valBenchmark.TabIndex = 9;
this.valBenchmark.Value = new decimal(new int[] {
8000,
0,
0,
0});
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(304, 53);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(113, 13);
this.label16.TabIndex = 8;
this.label16.Text = "Benchmark stage (cfs)";
//
// valIncrement
//
this.valIncrement.DecimalPlaces = 1;
this.valIncrement.Location = new System.Drawing.Point(420, 18);
this.valIncrement.Maximum = new decimal(new int[] {
5,
0,
0,
0});
this.valIncrement.Name = "valIncrement";
this.valIncrement.Size = new System.Drawing.Size(120, 20);
this.valIncrement.TabIndex = 7;
this.valIncrement.Value = new decimal(new int[] {
1,
0,
0,
65536});
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(300, 22);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(117, 13);
this.label15.TabIndex = 6;
this.label15.Text = "Elevation increment (m)";
//
// cmdBrowseGDALWarp
//
this.cmdBrowseGDALWarp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdBrowseGDALWarp.Image = global::SandbarWorkbench.Properties.Resources.explorer;
this.cmdBrowseGDALWarp.Location = new System.Drawing.Point(517, 142);
this.cmdBrowseGDALWarp.Name = "cmdBrowseGDALWarp";
this.cmdBrowseGDALWarp.Size = new System.Drawing.Size(23, 23);
this.cmdBrowseGDALWarp.TabIndex = 15;
this.cmdBrowseGDALWarp.UseVisualStyleBackColor = true;
this.cmdBrowseGDALWarp.Click += new System.EventHandler(this.cmdBrowseGDALWarp_Click);
//
// txtGDALWarp
//
this.txtGDALWarp.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtGDALWarp.Location = new System.Drawing.Point(176, 143);
this.txtGDALWarp.Name = "txtGDALWarp";
this.txtGDALWarp.ReadOnly = true;
this.txtGDALWarp.Size = new System.Drawing.Size(335, 20);
this.txtGDALWarp.TabIndex = 14;
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(55, 147);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(117, 13);
this.label14.TabIndex = 13;
this.label14.Text = "GDAL warp executable";
//
// cmdBrowseCompExtents
//
this.cmdBrowseCompExtents.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdBrowseCompExtents.Image = global::SandbarWorkbench.Properties.Resources.explorer;
this.cmdBrowseCompExtents.Location = new System.Drawing.Point(517, 111);
this.cmdBrowseCompExtents.Name = "cmdBrowseCompExtents";
this.cmdBrowseCompExtents.Size = new System.Drawing.Size(23, 23);
this.cmdBrowseCompExtents.TabIndex = 12;
this.cmdBrowseCompExtents.UseVisualStyleBackColor = true;
this.cmdBrowseCompExtents.Click += new System.EventHandler(this.cmdBrowseCompExtents_Click);
//
// txtCompExtents
//
this.txtCompExtents.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtCompExtents.Location = new System.Drawing.Point(176, 112);
this.txtCompExtents.Name = "txtCompExtents";
this.txtCompExtents.ReadOnly = true;
this.txtCompExtents.Size = new System.Drawing.Size(335, 20);
this.txtCompExtents.TabIndex = 11;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(16, 116);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(156, 13);
this.label13.TabIndex = 10;
this.label13.Text = "Computational extents shapefile";
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.txtSpatialReference);
this.groupBox2.Location = new System.Drawing.Point(6, 202);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(534, 121);
this.groupBox2.TabIndex = 19;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Spatial Reference";
//
// txtSpatialReference
//
this.txtSpatialReference.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtSpatialReference.Location = new System.Drawing.Point(6, 19);
this.txtSpatialReference.Multiline = true;
this.txtSpatialReference.Name = "txtSpatialReference";
this.txtSpatialReference.Size = new System.Drawing.Size(522, 96);
this.txtSpatialReference.TabIndex = 0;
//
// cboInterpolation
//
this.cboInterpolation.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboInterpolation.FormattingEnabled = true;
this.cboInterpolation.Location = new System.Drawing.Point(176, 80);
this.cboInterpolation.Name = "cboInterpolation";
this.cboInterpolation.Size = new System.Drawing.Size(121, 21);
this.cboInterpolation.TabIndex = 5;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(33, 84);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(139, 13);
this.label8.TabIndex = 4;
this.label8.Text = "Default interpolation method";
//
// valDefaultOutputCellSize
//
this.valDefaultOutputCellSize.DecimalPlaces = 2;
this.valDefaultOutputCellSize.Location = new System.Drawing.Point(176, 49);
this.valDefaultOutputCellSize.Name = "valDefaultOutputCellSize";
this.valDefaultOutputCellSize.Size = new System.Drawing.Size(120, 20);
this.valDefaultOutputCellSize.TabIndex = 3;
//
// valDefaultInputCellSize
//
this.valDefaultInputCellSize.DecimalPlaces = 2;
this.valDefaultInputCellSize.Location = new System.Drawing.Point(176, 18);
this.valDefaultInputCellSize.Name = "valDefaultInputCellSize";
this.valDefaultInputCellSize.Size = new System.Drawing.Size(120, 20);
this.valDefaultInputCellSize.TabIndex = 1;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(12, 53);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(160, 13);
this.label7.TabIndex = 2;
this.label7.Text = "Default raster output cell size (m)";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(12, 22);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(160, 13);
this.label6.TabIndex = 0;
this.label6.Text = "Default input text file cell size (m)";
//
// tabPage5
//
this.tabPage5.Controls.Add(this.cmdTestAWS);
this.tabPage5.Controls.Add(this.txtErrorLoggingKey);
this.tabPage5.Controls.Add(this.lblStreamName);
this.tabPage5.Controls.Add(this.chkAWSLoggingEnabled);
this.tabPage5.Location = new System.Drawing.Point(4, 22);
this.tabPage5.Name = "tabPage5";
this.tabPage5.Padding = new System.Windows.Forms.Padding(3);
this.tabPage5.Size = new System.Drawing.Size(546, 329);
this.tabPage5.TabIndex = 4;
this.tabPage5.Text = "Error Logging";
this.tabPage5.UseVisualStyleBackColor = true;
//
// cmdTestAWS
//
this.cmdTestAWS.Location = new System.Drawing.Point(11, 84);
this.cmdTestAWS.Name = "cmdTestAWS";
this.cmdTestAWS.Size = new System.Drawing.Size(156, 23);
this.cmdTestAWS.TabIndex = 8;
this.cmdTestAWS.Text = "Test AWS Message Log";
this.cmdTestAWS.UseVisualStyleBackColor = true;
this.cmdTestAWS.Visible = false;
//
// txtErrorLoggingKey
//
this.txtErrorLoggingKey.Location = new System.Drawing.Point(119, 36);
this.txtErrorLoggingKey.Name = "txtErrorLoggingKey";
this.txtErrorLoggingKey.ReadOnly = true;
this.txtErrorLoggingKey.Size = new System.Drawing.Size(407, 20);
this.txtErrorLoggingKey.TabIndex = 7;
//
// lblStreamName
//
this.lblStreamName.AutoSize = true;
this.lblStreamName.Location = new System.Drawing.Point(29, 40);
this.lblStreamName.Name = "lblStreamName";
this.lblStreamName.Size = new System.Drawing.Size(86, 13);
this.lblStreamName.TabIndex = 6;
this.lblStreamName.Text = "Error logging key";
//
// chkAWSLoggingEnabled
//
this.chkAWSLoggingEnabled.AutoSize = true;
this.chkAWSLoggingEnabled.Location = new System.Drawing.Point(11, 12);
this.chkAWSLoggingEnabled.Name = "chkAWSLoggingEnabled";
this.chkAWSLoggingEnabled.Size = new System.Drawing.Size(261, 17);
this.chkAWSLoggingEnabled.TabIndex = 5;
this.chkAWSLoggingEnabled.Text = "Share status and error information with developers";
this.chkAWSLoggingEnabled.UseVisualStyleBackColor = true;
//
// tabPage6
//
this.tabPage6.Controls.Add(this.cboAuditFieldDates);
this.tabPage6.Controls.Add(this.label12);
this.tabPage6.Controls.Add(this.cboSurveyDates);
this.tabPage6.Controls.Add(this.label11);
this.tabPage6.Controls.Add(this.cboTripDates);
this.tabPage6.Controls.Add(this.label10);
this.tabPage6.Location = new System.Drawing.Point(4, 22);
this.tabPage6.Name = "tabPage6";
this.tabPage6.Padding = new System.Windows.Forms.Padding(3);
this.tabPage6.Size = new System.Drawing.Size(546, 329);
this.tabPage6.TabIndex = 5;
this.tabPage6.Text = "Dates";
this.tabPage6.UseVisualStyleBackColor = true;
//
// cboAuditFieldDates
//
this.cboAuditFieldDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboAuditFieldDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboAuditFieldDates.FormattingEnabled = true;
this.cboAuditFieldDates.Location = new System.Drawing.Point(101, 71);
this.cboAuditFieldDates.Name = "cboAuditFieldDates";
this.cboAuditFieldDates.Size = new System.Drawing.Size(430, 21);
this.cboAuditFieldDates.TabIndex = 5;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(36, 75);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(58, 13);
this.label12.TabIndex = 4;
this.label12.Text = "Audit fields";
//
// cboSurveyDates
//
this.cboSurveyDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboSurveyDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboSurveyDates.FormattingEnabled = true;
this.cboSurveyDates.Location = new System.Drawing.Point(101, 44);
this.cboSurveyDates.Name = "cboSurveyDates";
this.cboSurveyDates.Size = new System.Drawing.Size(430, 21);
this.cboSurveyDates.TabIndex = 3;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(25, 48);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(69, 13);
this.label11.TabIndex = 2;
this.label11.Text = "Survey dates";
//
// cboTripDates
//
this.cboTripDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboTripDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboTripDates.FormattingEnabled = true;
this.cboTripDates.Location = new System.Drawing.Point(101, 17);
this.cboTripDates.Name = "cboTripDates";
this.cboTripDates.Size = new System.Drawing.Size(430, 21);
this.cboTripDates.TabIndex = 1;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(40, 21);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(54, 13);
this.label10.TabIndex = 0;
this.label10.Text = "Trip dates";
//
// tabPage7
//
this.tabPage7.Controls.Add(this.txtPython);
this.tabPage7.Location = new System.Drawing.Point(4, 22);
this.tabPage7.Name = "tabPage7";
this.tabPage7.Padding = new System.Windows.Forms.Padding(3);
this.tabPage7.Size = new System.Drawing.Size(546, 329);
this.tabPage7.TabIndex = 6;
this.tabPage7.Text = "Python";
this.tabPage7.UseVisualStyleBackColor = true;
//
// txtPython
//
this.txtPython.AcceptsReturn = true;
this.txtPython.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtPython.Location = new System.Drawing.Point(3, 3);
this.txtPython.Multiline = true;
this.txtPython.Name = "txtPython";
this.txtPython.Size = new System.Drawing.Size(540, 323);
this.txtPython.TabIndex = 0;
//
// cmdHelp
//
this.cmdHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cmdHelp.Location = new System.Drawing.Point(16, 373);
this.cmdHelp.Name = "cmdHelp";
this.cmdHelp.Size = new System.Drawing.Size(75, 23);
this.cmdHelp.TabIndex = 2;
this.cmdHelp.Text = "Help";
this.cmdHelp.UseVisualStyleBackColor = true;
this.cmdHelp.Click += new System.EventHandler(this.cmdHelp_Click);
//
// frmOptions
//
this.AcceptButton = this.cmdOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(578, 408);
this.Controls.Add(this.cmdHelp);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.cmdOK);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "frmOptions";
this.Text = "frmOptions";
this.Load += new System.EventHandler(this.frmOptions_Load);
this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.frmOptions_HelpRequested);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.tabPage3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grdFolderPaths)).EndInit();
this.tabPage4.ResumeLayout(false);
this.tabPage4.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.valBenchmark)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.valIncrement)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.valDefaultOutputCellSize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.valDefaultInputCellSize)).EndInit();
this.tabPage5.ResumeLayout(false);
this.tabPage5.PerformLayout();
this.tabPage6.ResumeLayout(false);
this.tabPage6.PerformLayout();
this.tabPage7.ResumeLayout(false);
this.tabPage7.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.ComboBox cboStartupView;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox chkLoadLastDatabase;
private System.Windows.Forms.TextBox txtMasterDatabase;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtMasterPassword;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtMasterUserName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtMasterServer;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.DataGridView grdFolderPaths;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rdo5Digits;
private System.Windows.Forms.RadioButton rdo4Digits;
private System.Windows.Forms.TabPage tabPage4;
private System.Windows.Forms.NumericUpDown valDefaultOutputCellSize;
private System.Windows.Forms.NumericUpDown valDefaultInputCellSize;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox cboInterpolation;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TabPage tabPage5;
private System.Windows.Forms.Button cmdTestAWS;
private System.Windows.Forms.TextBox txtErrorLoggingKey;
private System.Windows.Forms.Label lblStreamName;
private System.Windows.Forms.CheckBox chkAWSLoggingEnabled;
private System.Windows.Forms.TextBox txtInstallationGuid;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TabPage tabPage6;
private System.Windows.Forms.ComboBox cboAuditFieldDates;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.ComboBox cboSurveyDates;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ComboBox cboTripDates;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Button cmdHelp;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox txtSpatialReference;
private System.Windows.Forms.Button cmdBrowseCompExtents;
private System.Windows.Forms.TextBox txtCompExtents;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Button cmdBrowseGDALWarp;
private System.Windows.Forms.TextBox txtGDALWarp;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.NumericUpDown valBenchmark;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.NumericUpDown valIncrement;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.TabPage tabPage7;
private System.Windows.Forms.TextBox txtPython;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtMainPy;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.ToolTip tt;
}
} | NorthArrowResearch/sandbar-analysis-workbench | SandbarWorkbench/frmOptions.Designer.cs | C# | gpl-3.0 | 43,463 |
sap.ui.jsview(ui5nameSpace, {
// define the (default) controller type for this View
getControllerName: function() {
return "my.own.controller";
},
// defines the UI of this View
createContent: function(oController) {
// button text is bound to Model, "press" action is bound to Controller's event handler
return;
}
}); | Ryan-Boyd/ui5-artisan | lib/stubs/views/PlainView.js | JavaScript | gpl-3.0 | 368 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dh2744
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Vector;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dh2744
*/
public class CheckField {
//check that spike list and exp log exists, are correct and match
public static int checkSpkListExpLog(javax.swing.JTextField spikeListField,
javax.swing.JTextField expLogFileField,
javax.swing.JButton runButton,
javax.swing.JTextArea outputTextArea) {
int exitValue = 0;
runButton.setEnabled(false);
Boolean errorLog = false;
//Vector<String> logResult = new Vector<>();
// to do java 1.6 compatibility
Vector<String> logResult = new Vector<String>();
//experimental log
try {
//read in Experimental log
String csvFile = expLogFileField.getText();
String[] csvCheck1 = csvFile.split("\\.");
String csvText1 = "csv";
System.out.println("end of Exp log"+ csvCheck1[csvCheck1.length - 1] + " equals csv:" );
System.out.println(csvCheck1[csvCheck1.length - 1].equals("csv"));
//two ifs for whether string ends in "]" or not
if ( !csvCheck1[csvCheck1.length - 1].equals("csv") ){
if (!(csvCheck1[csvCheck1.length].equals("csv"))) {
logResult.add( "Exp log file chosen is not a csv file" );
ErrorHandler.errorPanel("Exp log file chosen " + '\n'
+ csvFile + '\n'
+ "Is not a csv file.");
exitValue = -1;
errorLog = true;
}
}
// This will reference one line at a time
String line = null;
Boolean expLogGood = true;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(csvFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
String[] expLogParts = line.split(",");
if (!expLogParts[0].toUpperCase().equals("PROJECT")) {
logResult.add( "Error reading in expLog File" );
logResult.add("Exp log file lacks Project column." );
ErrorHandler.errorPanel("Exp log file lacks Project column "
+ '\n'
+ "Please re-enter exp log file");
errorLog = true;
expLogGood = false;
exitValue = -1;
} else if (!expLogParts[1].toUpperCase().equals("EXPERIMENT DATE")) {
logResult.add( "Error reading in expLog File" );
logResult.add("Exp log file lacks Experiment column." );
ErrorHandler.errorPanel("Exp log file lacks Experiment column "
+ '\n'
+ "Please re-enter exp log file");
errorLog = true;
expLogGood = false;
exitValue = -1;
} else {
LineNumberReader lnr = null;
line = bufferedReader.readLine();
Integer i = 1;
line = bufferedReader.readLine();
String[] country = line.split(",");
System.out.println("Start while loop");
while (line != null) {
System.out.println(line);
System.out.println(country[0]);
System.out.println("Current line num " + i);
i++;
line = bufferedReader.readLine();
System.out.println(line);
System.out.println("line = null? " + (line == null));
//System.out.println("line.isEmpty ? " + (line.isEmpty()) );
if (line != null) {
System.out.println("line : " + line);
System.out.println("country : " + country[0]);
country = line.split(",");
}
}
System.out.println("Current line num " + i);
System.out.println("done with while loop");
// Always close files.
bufferedReader.close();
} //end of if-else
} catch (FileNotFoundException ex) {
logResult.add( "ExpLog File not found" );
System.out.println(
"Unable to open file '"
+ csvFile + "'");
errorLog = true;
exitValue = -1;
expLogGood = false;
} catch (IOException ex) {
logResult.add( "Error reading in expLog File" );
logResult.add("IOException." );
System.out.println(
"Error reading file '"
+ csvFile + "'");
errorLog = true;
expLogGood = false;
exitValue = -1;
}
System.out.println("expLogGood : " + expLogGood);
//++++++++++++++++++++++++++++++++++++read in Spk list file
String check = spikeListField.getText();
String[] temp = check.split(",");
System.out.println("spk list chooser: " + temp[0]);
String[] spkCsvFile = temp;
if (temp.length > 1) {
System.out.println("spkCsvFile.length = " + temp.length);
for (int ind = 0; ind < temp.length; ind++) {
if (0 == ind) {
spkCsvFile[ind] = temp[ind].substring(1, temp[ind].length()).trim();
System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]);
File fileCheck = new File(spkCsvFile[ind]);
System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists());
} else if (ind == (temp.length - 1)) {
spkCsvFile[ind] = temp[ind].substring(0, temp[ind].length() - 1).trim();
System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]);
File fileCheck = new File(spkCsvFile[ind]);
System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists());
} else {
spkCsvFile[ind] = temp[ind];
System.out.println("spkCsvFile[ind] " + spkCsvFile[ind].trim());
System.out.println("MMMMM" + spkCsvFile[ind].trim() + "MMMMMMM");
File fileCheck = new File(spkCsvFile[ind].trim());
System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists());
}
}
} else if (temp.length == 1) {
System.out.println("temp.length = " + temp.length);
System.out.println("temp[0].length = " + temp.length);
System.out.println("temp[0].toString().endsWith(]) = " +
temp.toString().endsWith("]") );
System.out.println("temp[0].toString().length() "+temp[0].toString().length());
System.out.println("temp[0].substring(temp[0].toString().length()-1 ) = " +
temp[0].substring(temp[0].toString().length()-1 ).toString() );
System.out.println("temp[0].substring(temp[0].toString().length()-1 ).equals(]) "+
temp[0].substring(temp[0].toString().length()-1 ).equals("]") );
if ( temp[0].substring(temp[0].toString().length()-1 ).equals("]") ){
int len = temp[0].length();
len--;
System.out.println("temp[0].toString().substring(2,3 ) = "+
temp[0].substring(2,3) );
System.out.println("temp[0].toString().substring(1,2 ) = "+
temp[0].toString().substring(1,2 ) );
System.out.println("temp[0].toString().substring(0,1 ) = "+
temp[0].substring(0,1 ) );
if (temp[0].substring(2,3 ).equals("[")){
spkCsvFile[0] = temp[0].substring(3, len).trim();
} else if (temp[0].toString().substring(1,2 ).equals("[")){
spkCsvFile[0] = temp[0].toString().substring(2, len).trim();
} else if (temp[0].toString().substring(0,1 ).equals("[")){
spkCsvFile[0] = temp[0].toString().substring(1, len).trim();
}
System.out.println("spkCsvFile[ind] " + spkCsvFile[0]);
}
File fileCheck = new File(spkCsvFile[0]);
System.out.println("exists? spkCsvFile[" + 0 + "] " + fileCheck.exists());
}
System.out.println("Done with reading in spike-list file names ");
// check that it's csv
for (int j = 0; j < spkCsvFile.length; j++) {
String[] csvCheck = spkCsvFile[j].split("\\.");
String csvText = "csv";
System.out.println(csvCheck[csvCheck.length - 1]);
System.out.println(csvCheck[csvCheck.length - 1].equals("csv"));
if (!(csvCheck[csvCheck.length - 1].equals("csv")||
csvCheck[csvCheck.length].equals("csv")) ) {
logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] );
logResult.add("Is not a csv file." );
ErrorHandler.errorPanel("Spike-list csv file chosen "
+ spkCsvFile[j] + '\n'
+ "Is not a csv file.");
errorLog = true;
exitValue = -1;
}
// spike list file
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(spkCsvFile[j].trim());
System.out.println("file reader " + spkCsvFile[j]);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
System.out.println(line);
String[] spkListHeader = line.split(",");
String third = "Time (s)";
System.out.println(spkListHeader[2]);
// check for spike list file
System.out.println(spkListHeader[2]);
if (!(spkListHeader[2].equals("Time (s)") || spkListHeader[2].equals("Time (s) ")
|| spkListHeader[2].equals("\"Time (s)\"")
|| spkListHeader[2].equals("\"Time (s) \""))) {
logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] );
logResult.add("Is not a proper spike-list file" );
logResult.add( "'Time (s)' should be third column header " );
logResult.add("Instead 3rd column is "+ spkListHeader[2].toString() );
ErrorHandler.errorPanel("Spike-list csv file chosen '" + spkCsvFile[j]+"'" + '\n'
+ "Is not a proper spike-list file" + '\n'
+ "'Time (s)' should be third column header");
exitValue = -1;
errorLog=true;
}
for (int counter2 = 1; counter2 < 5; counter2++) {
// content check
line = bufferedReader.readLine();
if (counter2 == 2) {
System.out.println(line);
String[] spkListContents = line.split(",");
//Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units
System.out.println("Time(s) " + spkListContents[2]
+ " , Electrode =" + spkListContents[3]);
}
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
logResult.add( " Unable to open file " + spkCsvFile[j] );
logResult.add(" Please select another spike list file " );
ErrorHandler.errorPanel("Unable to open file " + j + " "
+ spkCsvFile[j] + '\n'
+ "Please select another spike list file");
exitValue = -1;
errorLog = true;
} catch (IOException ex) {
logResult.add( "Error reading file " + spkCsvFile[j] );
logResult.add(" IOException " );
ErrorHandler.errorPanel(
"Error reading file '" + j + " "
+ spkCsvFile[j] + "'" + '\n' + "Please select another spike list file");
errorLog = true;
exitValue = -1;
}
} //end of loop through spike List Files
// +++++++++need to compare files
System.out.println("Starting match");
for (int j = 0; j < spkCsvFile.length; j++) {
if (expLogGood && !errorLog) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(csvFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
line = bufferedReader.readLine();
System.out.println(line);
String[] country = line.split(",");
//Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units
if (country.length>5 ){
System.out.println("Project " + country[0]
+ " , Exp Date=" + country[1]
+ " , Plate SN=" + country[2]
+ " , DIV= " + country[3]
+ " , Well=" + country[4]
+ " , trt=" + country[5]);
} else{
System.out.println("Project " + country[0]
+ " , Exp Date=" + country[1]
+ " , Plate SN=" + country[2]
+ " , DIV= " + country[3]
+ " , Well=" + country[4] );
}
// now compare to name of spk-list file
File spkListFile = new File(spkCsvFile[j]);
System.out.println("spkCsvFile "+spkCsvFile[j]);
System.out.println( "File.separator" + File.separator );
String name1 = spkListFile.getName().toString();
String[] partsName1 = name1.split("_");
System.out.println(partsName1[0]);
System.out.println(partsName1[1]);
System.out.println(partsName1[2]);
if (!(partsName1[0].equals(country[0].trim() ))) {
System.out.println("spkListFileNameParts " + partsName1[0].toString());
System.out.println("country " + country[0]);
logResult.add( "project in spk-list file name: " + partsName1[0] );
logResult.add("& experimental log file project: " + country[0]);
logResult.add("Do not match");
ErrorHandler.errorPanel(
"project in spk-list file name: " + partsName1[0] + '\n'
+ "& experimental log file project: " + country[0] + '\n'
+ "Do not match");
exitValue = -1;
errorLog = true;
} else if (!(partsName1[1].equals(country[1].trim() ))) {
logResult.add( "Experiment date does not match between" + '\n' + spkCsvFile[j] );
logResult.add("and experimental log file. ");
logResult.add("Please re-enter file");
ErrorHandler.errorPanel(
"Experiment date does not match between" + '\n' + spkCsvFile[j]
+ " name and experimental log file. '");
exitValue = -1;
errorLog = true;
} else if (!(partsName1[2].equals(country[2].trim() ))) {
logResult.add("No match between spk list" + spkCsvFile[j]);
logResult.add("and experimental log file. ");
ErrorHandler.errorPanel(
"No match between spk list" + spkCsvFile[j] + '\n'
+ "and experimental log file. '"
+ '\n' + "Project name do not match");
exitValue = -1;
errorLog = true;
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '"
+ csvFile + "'");
logResult.add(" Unable to open file ");
logResult.add("'" + csvFile + "'");
ErrorHandler.errorPanel(
"Unable to open file " + '\n'
+ "'" + csvFile + "'" + '\n'
);
exitValue = -1;
errorLog = true;
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ csvFile + "'");
ErrorHandler.errorPanel(
"Error reading file " +
"'" + csvFile + "'" + '\n'
);
logResult.add("Error reading file ");
logResult.add("'" + csvFile + "'");
errorLog = true;
exitValue = -1;
}
System.out.println("expLogGood : " + expLogGood);
System.out.println(" ");
}
System.out.println("done with match ");
System.out.println("NUMER OF TIMES THROUGH LOOP : " + j + 1);
} //end of loop through spike list files
if (!errorLog) {
runButton.setEnabled(true);
logResult.add("Files chosen are without errors");
logResult.add("They match one another");
logResult.add("proceeeding to Analysis");
}
PrintToTextArea.printToTextArea(logResult , outputTextArea);
} catch (Exception e) {
logResult.add("Try at reading the csv file failed");
logResult.add(" ");
logResult.add(" ");
e.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , outputTextArea);
}
return(exitValue);
}
public static int checkRObject(javax.swing.JTextField rasterFileChooserField,
javax.swing.JButton makeRasterButton,
javax.swing.JTextArea toolsTextArea) {
int exitValue = 0;
makeRasterButton.setEnabled(false);
Boolean errorLog = false;
//Vector<String> logResult = new Vector<>();
// to do java 1.6 compatibility
Vector<String> logResult = new Vector<String>();
//check Robject
try {
//check extension
String rObject = rasterFileChooserField.getText();
String[] rObjectCheck1 = rObject.split("\\.");
String rObjectText1 = "RData";
System.out.println(
rObject + " (-1) end in .RData? : " );
System.out.println(rObjectCheck1[rObjectCheck1.length-1 ].equals("RData"));
System.out.println(
rObject + " end in .RData? : " );
//System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData"));
//two ifs for whether string ends in "]" or not
if ( !rObjectCheck1[rObjectCheck1.length-1 ].equals("RData") ) {
System.out.println("in if statement");
ErrorHandler.errorPanel("Robject file chosen " + '\n'
+ rObject + '\n'
+ "Is not a Robject of .RData extension");
exitValue = -1;
errorLog = true;
return exitValue;
}
// This will reference one line at a time
String line = null;
Boolean expLogGood = true;
try {
// Query R for what's in the Robject
System.out.println(" right before SystemCall.systemCall(cmd0, outputTextArea) " );
Vector<String> envVars = new Vector<String>();
File fileWD = new File(System.getProperty("java.class.path"));
File dashDir = fileWD.getAbsoluteFile().getParentFile();
System.out.println("Dash dir " + dashDir.toString());
File systemPaths = new File( dashDir.toString() +File.separator+"Code" +
File.separator+"systemPaths.txt");
File javaClassPath = new File(System.getProperty("java.class.path"));
File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile();
String rootPath2Slash = rootPath1.toString();
rootPath2Slash = rootPath2Slash.replace("\\", "\\\\");
envVars=GetEnvVars.getEnvVars( systemPaths, toolsTextArea );
String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash +
File.separator +"Code"+ File.separator + "RobjectInfoScript.R "+
"RobjectPath="+rObject.toString();
System.out.println( "cmd0 " + cmd0 );
SystemCall.systemCall(cmd0, toolsTextArea );
System.out.println("After SystemCall in Raster " );
/// here we need code to populate raster parameter object
} catch (Exception i){
logResult.add("Try at running RobjectInfoScript.R");
logResult.add(" ");
logResult.add(" ");
i.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , toolsTextArea);
}
} catch (Exception e) {
logResult.add("Try at reading the Robject file failed");
logResult.add(" ");
logResult.add(" ");
e.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , toolsTextArea);
}
return(exitValue);
}
public static int checkDistFile(
javax.swing.JTextField distPlotFileField,
javax.swing.JButton plotDistrButton,
javax.swing.JTextArea distPlotTextArea) {
int exitValue = 0;
plotDistrButton.setEnabled(false);
Boolean errorLog = false;
//Vector<String> logResult = new Vector<>();
// to do java 1.6 compatibility
Vector<String> logResult = new Vector<String>();
//check Robject
try {
//check extension
String[] distPlotFile1=RemoveSqBrackets.removeSqBrackets( distPlotFileField );
String[] distPlotFileCheck1 = distPlotFile1[0].split("\\.");
String distPlotFileText1 = "csv";
System.out.println(
distPlotFile1[0] + " (-1) end in .csv? : " );
System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv"));
System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ] +
" =distPlotFileCheck1[distPlotFileCheck1.length-1 ]" );
//System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData"));
//two ifs for whether string ends in "]" or not
if ( !distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv") ) {
System.out.println("in if statement");
ErrorHandler.errorPanel("Distribution file chosen " + '\n'
+ distPlotFile1[0] + '\n'
+ "Is not a distribution file of .csv extension");
exitValue = -1;
errorLog = true;
return exitValue;
}
// This will reference one line at a time
String line = null;
Boolean expLogGood = true;
try {
// Query R for what's in the Robject
System.out.println(" right before SystemCall.systemCall(cmd0, distPlotTextArea) " );
Vector<String> envVars = new Vector<String>();
File fileWD = new File(System.getProperty("java.class.path"));
File dashDir = fileWD.getAbsoluteFile().getParentFile();
System.out.println("Dash dir " + dashDir.toString());
File systemPaths = new File( dashDir.toString() +File.separator+"Code" +
File.separator+"systemPaths.txt");
File javaClassPath = new File(System.getProperty("java.class.path"));
File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile();
String rootPath2Slash = rootPath1.toString();
rootPath2Slash = rootPath2Slash.replace("\\", "\\\\");
envVars=GetEnvVars.getEnvVars( systemPaths, distPlotTextArea );
String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash +
File.separator +"Code"+ File.separator + "distFileInfoScript.R "+
"distFilePath="+distPlotFile1[0].toString();
System.out.println( "cmd0 " + cmd0 );
SystemCall.systemCall(cmd0, distPlotTextArea );
System.out.println("After SystemCall in distPlot " );
/// here we need code to populate raster parameter object
} catch (Exception i){
logResult.add("Try at running distFileInfoScript.R");
logResult.add(" ");
logResult.add(" ");
i.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , distPlotTextArea);
}
} catch (Exception e) {
logResult.add("Try at reading the Robject file failed");
logResult.add(" ");
logResult.add(" ");
e.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult ,distPlotTextArea);
}
return(exitValue);
}
}
| igm-team/meaRtools | Java_IGMDash-master/src/CheckField.java | Java | gpl-3.0 | 29,621 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('characters', '0011_auto_20160212_1144'),
]
operations = [
migrations.CreateModel(
name='CharacterSpells',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('character', models.ForeignKey(verbose_name='Karakt\xe4r', to='characters.Character')),
],
options={
'verbose_name': 'Karakt\xe4rers magi',
'verbose_name_plural': 'Karakt\xe4rers magi',
},
),
migrations.AlterModelOptions(
name='spellextras',
options={'verbose_name': 'Magi extra', 'verbose_name_plural': 'Magi extra'},
),
migrations.AlterModelOptions(
name='spellinfo',
options={'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'},
),
migrations.AddField(
model_name='spellinfo',
name='name',
field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'),
),
migrations.AlterField(
model_name='spellinfo',
name='parent',
field=models.ForeignKey(verbose_name='Tillh\xf6righet', to='characters.SpellParent'),
),
migrations.AddField(
model_name='characterspells',
name='spells',
field=models.ManyToManyField(to='characters.SpellInfo', verbose_name='Magier och besv\xe4rjelser'),
),
]
| svamp/rp_management | characters/migrations/0012_auto_20160212_1210.py | Python | gpl-3.0 | 1,712 |