repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
henriquegemignani/randovania
|
randovania/game_description/item/ammo.py
|
2857
|
from dataclasses import dataclass
import dataclasses
from typing import Dict, Tuple, Optional
from frozendict import frozendict
from randovania.game_description.item.item_category import ItemCategory
from randovania.game_description.resources.pickup_entry import ResourceLock
from randovania.game_description.resources.resource_database import ResourceDatabase
from randovania.games.game import RandovaniaGame
@dataclass(frozen=True, order=True)
class Ammo:
game: RandovaniaGame
name: str
model_name: str
items: Tuple[str, ...]
broad_category: ItemCategory
unlocked_by: Optional[str] = None
temporary: Optional[str] = None
extra: frozendict = dataclasses.field(default_factory=frozendict)
def __post_init__(self):
if self.temporary is not None:
if self.unlocked_by is None:
raise ValueError("If temporaries is set, unlocked_by must be set.")
if len(self.items) != 1:
raise ValueError("If temporaries is set, only one item is supported. Got {0} instead".format(
len(self.items)
))
elif self.unlocked_by is not None:
raise ValueError("If temporaries is not set, unlocked_by must not be set.")
@classmethod
def from_json(cls, name: str, value: dict, game: RandovaniaGame,
item_categories: Dict[str, ItemCategory]) -> "Ammo":
return cls(
game=game,
name=name,
model_name=value["model_name"],
items=tuple(value["items"]),
broad_category=item_categories[value["broad_category"]],
unlocked_by=value.get("unlocked_by"),
temporary=value.get("temporary"),
extra=frozendict(value.get("extra", {}))
)
@property
def as_json(self) -> dict:
result = {
"model_name": self.model_name,
"items": list(self.items),
"broad_category": self.broad_category.name,
"extra": self.extra
}
if self.unlocked_by is not None:
result["temporary"] = self.temporary
result["unlocked_by"] = self.unlocked_by
return result
@property
def item_category(self) -> ItemCategory:
return AMMO_ITEM_CATEGORY
def create_resource_lock(self, resource_database: ResourceDatabase) -> Optional[ResourceLock]:
if self.unlocked_by is not None:
return ResourceLock(
locked_by=resource_database.get_item(self.unlocked_by),
item_to_lock=resource_database.get_item(self.items[0]),
temporary_item=resource_database.get_item(self.temporary),
)
return None
AMMO_ITEM_CATEGORY = ItemCategory(
name="expansion",
long_name="",
hint_details=("an ", "expansion"),
is_major=False
)
|
gpl-3.0
|
mistert14/ardu-rasp1
|
lib/SimpleDHT/SimpleDHT.cpp
|
7526
|
/*
The MIT License (MIT)
Copyright (c) 2016-2017 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "SimpleDHT.h"
int SimpleDHT::read(int pin, byte* ptemperature, byte* phumidity, byte pdata[40]) {
int ret = SimpleDHTErrSuccess;
float temperature = 0;
float humidity = 0;
if ((ret = read2(pin, &temperature, &humidity, pdata)) != SimpleDHTErrSuccess) {
return ret;
}
if (ptemperature) {
*ptemperature = (byte)(int)temperature;
}
if (phumidity) {
*phumidity = (byte)(int)humidity;
}
return ret;
}
int SimpleDHT::confirm(int pin, int us, byte level) {
int cnt = us / 10;
if ((us % 10) > 0) {
cnt++;
}
bool ok = false;
for (int i = 0; i < cnt; i++) {
delayMicroseconds(10);
if (digitalRead(pin) != level) {
ok = true;
break;
}
}
if (!ok) {
return -1;
}
return SimpleDHTErrSuccess;
}
byte SimpleDHT::bits2byte(byte data[8]) {
byte v = 0;
for (int i = 0; i < 8; i++) {
v += data[i] << (7 - i);
}
return v;
}
int SimpleDHT::parse(byte data[40], short* ptemperature, short* phumidity) {
short humidity = bits2byte(data);
short humidity2 = bits2byte(data + 8);
short temperature = bits2byte(data + 16);
short temperature2 = bits2byte(data + 24);
byte check = bits2byte(data + 32);
byte expect = (byte)humidity + (byte)humidity2 + (byte)temperature + (byte)temperature2;
if (check != expect) {
return SimpleDHTErrDataChecksum;
}
*ptemperature = temperature<<8 | temperature2;
*phumidity = humidity<<8 | humidity2;
return SimpleDHTErrSuccess;
}
int SimpleDHT11::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
int ret = SimpleDHTErrSuccess;
byte data[40] = {0};
if ((ret = sample(pin, data)) != SimpleDHTErrSuccess) {
return ret;
}
short temperature = 0;
short humidity = 0;
if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
return ret;
}
if (pdata) {
memcpy(pdata, data, 40);
}
if (ptemperature) {
*ptemperature = (int)(temperature>>8);
}
if (phumidity) {
*phumidity = (int)(humidity>>8);
}
// For example, when remove the data line, it will be success with zero data.
if (temperature == 0 && humidity == 0) {
return SimpleDHTErrZeroSamples;
}
return ret;
}
int SimpleDHT11::sample(int pin, byte data[40]) {
// empty output data.
memset(data, 0, 40);
// According to protocol: https://akizukidenshi.com/download/ds/aosong/DHT11.pdf
// notify DHT11 to start:
// 1. PULL LOW 20ms.
// 2. PULL HIGH 20-40us.
// 3. SET TO INPUT.
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(20);
digitalWrite(pin, HIGH);
pinMode(pin, INPUT);
delayMicroseconds(30);
// DHT11 starting:
// 1. PULL LOW 80us
// 2. PULL HIGH 80us
if (confirm(pin, 80, LOW)) {
return SimpleDHTErrStartLow;
}
if (confirm(pin, 80, HIGH)) {
return SimpleDHTErrStartHigh;
}
// DHT11 data transmite:
// 1. 1bit start, PULL LOW 50us
// 2. PULL HIGH 26-28us, bit(0)
// 3. PULL HIGH 70us, bit(1)
for (int j = 0; j < 40; j++) {
if (confirm(pin, 50, LOW)) {
return SimpleDHTErrDataLow;
}
// read a bit, should never call method,
// for the method call use more than 20us,
// so it maybe failed to detect the bit0.
bool ok = false;
int tick = 0;
for (int i = 0; i < 8; i++, tick++) {
if (digitalRead(pin) != HIGH) {
ok = true;
break;
}
delayMicroseconds(10);
}
if (!ok) {
return SimpleDHTErrDataRead;
}
data[j] = (tick > 3? 1:0);
}
// DHT11 EOF:
// 1. PULL LOW 50us.
if (confirm(pin, 50, LOW)) {
return SimpleDHTErrDataEOF;
}
return SimpleDHTErrSuccess;
}
int SimpleDHT22::read2(int pin, float* ptemperature, float* phumidity, byte pdata[40]) {
int ret = SimpleDHTErrSuccess;
byte data[40] = {0};
if ((ret = sample(pin, data)) != SimpleDHTErrSuccess) {
return ret;
}
short temperature = 0;
short humidity = 0;
if ((ret = parse(data, &temperature, &humidity)) != SimpleDHTErrSuccess) {
return ret;
}
if (pdata) {
memcpy(pdata, data, 40);
}
if (ptemperature) {
*ptemperature = (float)temperature / 10.0;
}
if (phumidity) {
*phumidity = (float)humidity / 10.0;
}
return ret;
}
int SimpleDHT22::sample(int pin, byte data[40]) {
// empty output data.
memset(data, 0, 40);
// According to protocol: http://akizukidenshi.com/download/ds/aosong/AM2302.pdf
// notify DHT11 to start:
// 1. T(be), PULL LOW 1ms(0.8-20ms).
// 2. T(go), PULL HIGH 30us(20-200us), use 40us.
// 3. SET TO INPUT.
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delayMicroseconds(1000);
digitalWrite(pin, HIGH);
pinMode(pin, INPUT);
delayMicroseconds(40);
// DHT11 starting:
// 1. T(rel), PULL LOW 80us(75-85us), use 90us.
// 2. T(reh), PULL HIGH 80us(75-85us), use 90us.
if (confirm(pin, 90, LOW)) {
return SimpleDHTErrStartLow;
}
if (confirm(pin, 90, HIGH)) {
return SimpleDHTErrStartHigh;
}
// DHT11 data transmite:
// 1. T(LOW), 1bit start, PULL LOW 50us(48-55us), use 60us.
// 2. T(H0), PULL HIGH 26us(22-30us), bit(0)
// 3. T(H1), PULL HIGH 70us(68-75us), bit(1)
for (int j = 0; j < 40; j++) {
if (confirm(pin, 60, LOW)) {
return SimpleDHTErrDataLow;
}
// read a bit, should never call method,
// for the method call use more than 20us,
// so it maybe failed to detect the bit0.
bool ok = false;
int tick = 0;
for (int i = 0; i < 8; i++, tick++) {
if (digitalRead(pin) != HIGH) {
ok = true;
break;
}
delayMicroseconds(10);
}
if (!ok) {
return SimpleDHTErrDataRead;
}
data[j] = (tick > 3? 1:0);
}
// DHT11 EOF:
// 1. T(en), PULL LOW 50us(45-55us), use 60us.
if (confirm(pin, 60, LOW)) {
return SimpleDHTErrDataEOF;
}
return SimpleDHTErrSuccess;
}
|
gpl-3.0
|
rudneff/Network-labs
|
lab-ip-hw/report/utils/dot2texlib/dotparsing.py
|
35748
|
# -*- coding: utf-8 -*-
"""Graphviz dot language parser.
This parser is derived from the the parser distributed with the pydot module.
Original authors are
Michael Krause <michael AT krause-software.de>
Ero Carrera <ero AT dkbza.org>
"""
__version__ = '2.8.7'
__author__ = ['Michael Krause', 'Ero Carrera', 'Kjell Magne Fauske']
__license__ = 'MIT'
import sys, glob, re, itertools,os,logging
from itertools import izip
import string
from exceptions import KeyError, AttributeError
from pyparsing import __version__ as pyparsing_version
import pyparsing
from pyparsing import (Literal, CaselessLiteral, Word, Upcase, OneOrMore, ZeroOrMore,
Forward, NotAny, delimitedList, oneOf, Group, Optional, Combine, alphas, nums,
restOfLine, cStyleComment, nums, alphanums, printables, empty, quotedString,
ParseException, ParseResults, CharsNotIn, _noncomma, dblQuotedString, QuotedString, ParserElement,
Suppress,Regex,removeQuotes)
dot_keywords = ['graph', 'subgraph', 'digraph', 'node', 'edge', 'strict']
id_re_alpha_nums = re.compile('^[_a-zA-Z][a-zA-Z0-9_]*$')
id_re_num = re.compile('^[0-9]+(.[0-9]+)?$')
id_re_with_port = re.compile('^.*:([^"]+|[^"]*\"[^"]*\"[^"]*)$')
id_re_dbl_quoted = re.compile('^\".*\"$', re.S)
id_re_html = re.compile('^<<.*>>$', re.S)
log = logging.getLogger("dot2tex")
def needs_quotes( s ):
"""Checks whether a string is a dot language ID.
It will check whether the string is solely composed
by the characters allowed in an ID or not.
If the string is one of the reserved keywords it will
need quotes too.
"""
#print >> sys.stderr, 'check:', s
if s in dot_keywords:
return True
chars = [ord(c) for c in s if ord(c)>0x7f or ord(c)==0]
if chars:
return True
res = id_re_alpha_nums.match(s)
if not res:
res = id_re_num.search(s)
#print >> sys.stderr, 'check:', s
if not res:
#res = id_re_dbl_quoted.match(s)
if not res:
res = id_re_html.match(s)
pass
else:
#print >> sys.stderr, 'num:', s
pass
## if not res:
## res = id_re_with_port.match(s)
if not res:
return True
return False
def quote_if_necessary(s):
if not isinstance( s, basestring ):
return s
tmp = s
if needs_quotes(tmp):
tmp = '"%s"' % s#.replace('"','\\"')
tmp = tmp.replace('<<','<')
tmp = tmp.replace('>>','>')
return tmp
def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem
# Code snippet from Python Cookbook, 2nd Edition by David Ascher, Alex Martelli
# and Anna Ravenscroft; O'Reilly 2005
def windows(iterable, length=2, overlap=0,padding=True):
it = iter(iterable)
results = list(itertools.islice(it, length))
while len(results) == length:
yield results
results = results[length-overlap:]
results.extend(itertools.islice(it, length-overlap))
if padding and results:
results.extend(itertools.repeat(None, length-len(results)))
yield results
def nsplit(seq, n=2):
"""Split a sequence into pieces of length n
If the lengt of the sequence isn't a multiple of n, the rest is discareded.
Note that nsplit will strings into individual characters.
Examples:
>>> nsplit('aabbcc')
[('a', 'a'), ('b', 'b'), ('c', 'c')]
>>> nsplit('aabbcc',n=3)
[('a', 'a', 'b'), ('b', 'c', 'c')]
# Note that cc is discarded
>>> nsplit('aabbcc',n=4)
[('a', 'a', 'b', 'b')]
"""
return [xy for xy in izip(*[iter(seq)]*n)]
# The following function is from the pydot project
def __find_executables(path):
"""Used by find_graphviz
path - single directory as a string
If any of the executables are found, it will return a dictionary
containing the program names as keys and their paths as values.
Otherwise returns None
"""
success = False
progs = {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': ''}
was_quoted = False
path = path.strip()
if path.startswith('"') and path.endswith('"'):
path = path[1:-1]
was_quoted = True
if os.path.isdir(path) :
for prg in progs.keys():
if progs[prg]:
continue
if os.path.exists( os.path.join(path, prg) ):
if was_quoted:
progs[prg] = '"' + os.path.join(path, prg) + '"'
else:
progs[prg] = os.path.join(path, prg)
success = True
elif os.path.exists( os.path.join(path, prg + '.exe') ):
if was_quoted:
progs[prg] = '"' + os.path.join(path, prg + '.exe') + '"'
else:
progs[prg] = os.path.join(path, prg + '.exe')
success = True
if success:
return progs
else:
return None
# The following function is from the pydot project
# The multi-platform version of this 'find_graphviz' function was
# contributed by Peter Cock
#
def find_graphviz():
"""Locate Graphviz's executables in the system.
Tries three methods:
First: Windows Registry (Windows only)
This requires Mark Hammond's pywin32 is installed.
Secondly: Search the path
It will look for 'dot', 'twopi' and 'neato' in all the directories
specified in the PATH environment variable.
Thirdly: Default install location (Windows only)
It will look for 'dot', 'twopi' and 'neato' in the default install
location under the "Program Files" directory.
It will return a dictionary containing the program names as keys
and their paths as values.
If this fails, it returns None.
"""
# Method 1 (Windows only)
#
if os.sys.platform == 'win32':
try:
import win32api, win32con
# Get the GraphViz install path from the registry
#
hkey = win32api.RegOpenKeyEx( win32con.HKEY_LOCAL_MACHINE,
"SOFTWARE\AT&T Research Labs\Graphviz", 0, win32con.KEY_QUERY_VALUE )
path = win32api.RegQueryValueEx( hkey, "InstallPath" )[0]
win32api.RegCloseKey( hkey )
# Now append the "bin" subdirectory:
#
path = os.path.join(path, "bin")
progs = __find_executables(path)
if progs is not None :
#print "Used Windows registry"
return progs
except ImportError :
# Print a messaged suggesting they install these?
#
log.debug('The win32api is not installed')
pass
except:
log.debug('Failed to access the registry key')
# Method 2 (Linux, Windows etc)
#
if os.environ.has_key('PATH'):
for path in os.environ['PATH'].split(os.pathsep):
progs = __find_executables(path)
if progs is not None :
return progs
# Method 3 (Windows only)
#
if os.sys.platform == 'win32':
# Try and work out the equivalent of "C:\Program Files" on this
# machine (might be on drive D:, or in a different language)
#
if os.environ.has_key('PROGRAMFILES'):
# Note, we could also use the win32api to get this
# information, but win32api may not be installed.
path = os.path.join(os.environ['PROGRAMFILES'], 'ATT', 'GraphViz', 'bin')
else:
#Just in case, try the default...
path = r"C:\Program Files\att\Graphviz\bin"
progs = __find_executables(path)
if progs is not None :
#print "Used default install location"
return progs
for path in (
'/usr/bin', '/usr/local/bin',
'/opt/local/bin',
'/opt/bin', '/sw/bin', '/usr/share',
'/Applications/Graphviz.app/Contents/MacOS/' ):
progs = __find_executables(path)
if progs is not None :
#print "Used path"
return progs
# Failed to find GraphViz
#
return None
ADD_NODE = 'add_node'
ADD_EDGE = 'add_edge'
ADD_GRAPH_TO_NODE_EDGE = 'add_graph_to_node_edge'
ADD_NODE_TO_GRAPH_EDGE = 'add_node_to_graph_edge'
ADD_GRAPH_TO_GRAPH_EDGE = 'add_graph_to_graph_edge'
ADD_SUBGRAPH = 'add_subgraph'
SET_DEF_NODE_ATTR = 'set_def_node_attr'
SET_DEF_EDGE_ATTR = 'set_def_edge_attr'
SET_DEF_GRAPH_ATTR = 'set_def_graph_attr'
SET_GRAPH_ATTR = 'set_graph_attr'
class DotDataParser(object):
"""Container class for parsing Graphviz dot data"""
def __init__(self):
pass
self.dotparser = self.define_dot_parser()
# parse actions
def _proc_node_id(self,toks):
if len(toks) > 1:
return (toks[0],toks[1])
else:
return toks
def _proc_attr_list(self,toks):
return dict(nsplit(toks,2))
def _proc_attr_list_combine(self,toks):
if toks:
first_dict = toks[0]
for d in toks:
first_dict.update(d)
return first_dict
return toks
def _proc_attr_assignment(self,toks):
return (SET_GRAPH_ATTR,dict(nsplit(toks,2)))
def _proc_node_stmt(self,toks):
"""Return (ADD_NODE, node_name, options)"""
if len(toks) == 2:
return tuple([ADD_NODE]+list(toks))
else:
return tuple([ADD_NODE]+list(toks)+[{}])
def _proc_edge_stmt(self,toks):
"""Return (ADD_EDGE, src, dest, options)"""
edgelist = []
opts = toks[-1]
if not isinstance(opts, dict):
opts = {}
for src,op,dest in windows(toks,length=3,overlap=1,padding=False):
# is src or dest a subgraph?
srcgraph = destgraph = False
if len(src) > 1 and src[0] == ADD_SUBGRAPH:
edgelist.append(src)
srcgraph = True
if len(dest) > 1 and dest[0] == ADD_SUBGRAPH:
edgelist.append(dest)
destgraph = True
if srcgraph or destgraph:
if srcgraph and destgraph:
edgelist.append((ADD_GRAPH_TO_GRAPH_EDGE,src[1],dest[1],opts))
elif srcgraph:
edgelist.append((ADD_GRAPH_TO_NODE_EDGE,src[1],dest,opts))
else:
edgelist.append((ADD_NODE_TO_GRAPH_EDGE,src,dest[1],opts))
else:
# ordinary edge
edgelist.append((ADD_EDGE,src,dest,opts))
return edgelist
def _proc_default_attr_stmt(self,toks):
"""Return (ADD_DEFAULT_NODE_ATTR,options"""
if len(toks)== 1:
gtype = toks;
attr = {}
else:
gtype, attr = toks
if gtype == 'node':
return (SET_DEF_NODE_ATTR,attr)
elif gtype == 'edge':
return (SET_DEF_EDGE_ATTR,attr)
elif gtype == 'graph':
return (SET_DEF_GRAPH_ATTR,attr)
else:
return ('unknown',toks)
def _proc_subgraph_stmt(self,toks):
"""Returns (ADD_SUBGRAPH, name, elements)"""
return ('add_subgraph',toks[1],toks[2].asList())
def _main_graph_stmt(self,toks):
return (toks[0], toks[1], toks[2],toks[3].asList())
# The dot grammar is based on the dot parser from the pydot project.
def define_dot_parser(self):
"""Define dot grammar
Based on the grammar http://www.graphviz.org/doc/info/lang.html
"""
# punctuation
colon = Literal(":")
lbrace = Suppress("{")
rbrace = Suppress("}")
lbrack = Suppress("[")
rbrack = Suppress("]")
lparen = Literal("(")
rparen = Literal(")")
equals = Suppress("=")
comma = Literal(",")
dot = Literal(".")
slash = Literal("/")
bslash = Literal("\\")
star = Literal("*")
semi = Suppress(";")
at = Literal("@")
minus = Literal("-")
pluss = Suppress("+")
# keywords
strict_ = CaselessLiteral("strict")
graph_ = CaselessLiteral("graph")
digraph_ = CaselessLiteral("digraph")
subgraph_ = CaselessLiteral("subgraph")
node_ = CaselessLiteral("node")
edge_ = CaselessLiteral("edge")
punctuation_ = "".join( [ c for c in string.punctuation if c not in '_' ] ) +string.whitespace
# token definitions
identifier = Word(alphanums + "_" ).setName("identifier")
#double_quoted_string = QuotedString('"', multiline=True,escChar='\\',
# unquoteResults=True) # dblQuotedString
double_quoted_string = Regex(r'\"(?:\\\"|\\\\|[^"])*\"', re.MULTILINE)
double_quoted_string.setParseAction(removeQuotes)
quoted_string = Combine(double_quoted_string+
Optional(OneOrMore(pluss+double_quoted_string)),adjacent=False)
alphastring_ = OneOrMore(CharsNotIn(punctuation_))
def parse_html(s, loc, toks):
return '<<%s>>' % ''.join(toks[0])
opener = '<'
closer = '>'
try:
html_text = pyparsing.nestedExpr( opener, closer,
(( CharsNotIn(
opener + closer ).setParseAction( lambda t:t[0] ))
)).setParseAction(parse_html)
except:
log.debug('nestedExpr not available.')
log.warning('Old version of pyparsing detected. Version 1.4.8 or '
'later is recommended. Parsing of html labels may not '
'work properly.')
html_text = Combine(Literal("<<") + OneOrMore(CharsNotIn(",]")))
ID = ( alphastring_ | html_text |
quoted_string | #.setParseAction(strip_quotes) |
identifier ).setName("ID")
float_number = Combine(Optional(minus) +
OneOrMore(Word(nums + "."))).setName("float_number")
righthand_id = (float_number | ID ).setName("righthand_id")
port_angle = (at + ID).setName("port_angle")
port_location = ((OneOrMore(Group(colon + ID)) |
Group(colon + lparen + ID + comma + ID + rparen))).setName("port_location")
port = Combine((Group(port_location + Optional(port_angle)) |
Group(port_angle + Optional(port_location)))).setName("port")
node_id = (ID + Optional(port))
a_list = OneOrMore(ID + Optional(equals + righthand_id) +
Optional(comma.suppress())).setName("a_list")
attr_list = OneOrMore(lbrack + Optional(a_list) +
rbrack).setName("attr_list").setResultsName('attrlist')
attr_stmt = ((graph_ | node_ | edge_) + attr_list).setName("attr_stmt")
edgeop = (Literal("--") | Literal("->")).setName("edgeop")
stmt_list = Forward()
graph_stmt = (lbrace + Optional(stmt_list) +
rbrace + Optional(semi) ).setName("graph_stmt")
edge_point = Forward()
edgeRHS = OneOrMore(edgeop + edge_point)
edge_stmt = edge_point + edgeRHS + Optional(attr_list)
subgraph = (Optional(subgraph_,'') + Optional(ID,'') + Group(graph_stmt)).setName("subgraph").setResultsName('ssubgraph')
edge_point << (subgraph | graph_stmt | node_id )
node_stmt = (node_id + Optional(attr_list) + Optional(semi)).setName("node_stmt")
assignment = (ID + equals + righthand_id).setName("assignment")
stmt = (assignment | edge_stmt | attr_stmt | subgraph | graph_stmt | node_stmt).setName("stmt")
stmt_list << OneOrMore(stmt + Optional(semi))
graphparser = ( (Optional(strict_,'notstrict') + ((graph_ | digraph_)) +
Optional(ID,'') + lbrace + Group(Optional(stmt_list)) +rbrace).setResultsName("graph") )
singleLineComment = Group("//" + restOfLine) | Group("#" + restOfLine)
# actions
graphparser.ignore(singleLineComment)
graphparser.ignore(cStyleComment)
node_id.setParseAction(self._proc_node_id)
assignment.setParseAction(self._proc_attr_assignment)
a_list.setParseAction(self._proc_attr_list)
edge_stmt.setParseAction(self._proc_edge_stmt)
node_stmt.setParseAction(self._proc_node_stmt)
attr_stmt.setParseAction(self._proc_default_attr_stmt)
attr_list.setParseAction(self._proc_attr_list_combine)
subgraph.setParseAction(self._proc_subgraph_stmt)
#graph_stmt.setParseAction(self._proc_graph_stmt)
graphparser.setParseAction(self._main_graph_stmt)
return graphparser
def build_graph(self,graph,tokens):
subgraph = None
for element in tokens:
cmd = element[0]
if cmd == ADD_NODE:
cmd, nodename, opts = element
node = graph.add_node(nodename,**opts)
graph.allitems.append(node)
elif cmd == ADD_EDGE:
cmd, src, dest, opts = element
srcport = destport = ""
if isinstance(src,tuple):
srcport = src[1]
src = src[0]
if isinstance(dest,tuple):
destport = dest[1]
dest = dest[0]
edge = graph.add_edge(src,dest,srcport,destport,**opts)
graph.allitems.append(edge)
elif cmd in [ADD_GRAPH_TO_NODE_EDGE, ADD_GRAPH_TO_GRAPH_EDGE,ADD_NODE_TO_GRAPH_EDGE]:
cmd, src, dest, opts = element
srcport = destport = ""
if isinstance(src,tuple):
srcport = src[1]
if isinstance(dest,tuple):
destport = dest[1]
if not (cmd == ADD_NODE_TO_GRAPH_EDGE):
if cmd == ADD_GRAPH_TO_NODE_EDGE:
src = subgraph
else:
src = prev_subgraph
dest = subgraph
else:
dest = subgraph
edges = graph.add_special_edge(src,dest,srcport,destport,**opts)
graph.allitems.extend(edges)
elif cmd == SET_GRAPH_ATTR:
graph.set_attr(**element[1])
elif cmd == SET_DEF_NODE_ATTR:
graph.add_default_node_attr(**element[1])
defattr = DotDefaultAttr('node',**element[1])
graph.allitems.append(defattr)
elif cmd == SET_DEF_EDGE_ATTR:
graph.add_default_edge_attr(**element[1])
defattr = DotDefaultAttr('edge',**element[1])
graph.allitems.append(defattr)
elif cmd == SET_DEF_GRAPH_ATTR:
graph.add_default_graph_attr(**element[1])
defattr = DotDefaultAttr('graph',**element[1])
graph.allitems.append(defattr)
elif cmd == ADD_SUBGRAPH:
cmd, name, elements = element
#print "Adding subgraph"
if subgraph:
prev_subgraph = subgraph
subgraph = graph.add_subgraph(name)
subgraph = self.build_graph(subgraph,elements)
graph.allitems.append(subgraph)
return graph
def build_top_graph(self,tokens):
"""Build a DotGraph instance from parsed data"""
# get basic graph information
strict = tokens[0] == 'strict'
graphtype = tokens[1]
directed = graphtype == 'digraph'
graphname = tokens[2]
# lets build the graph
graph = DotGraph(graphname,strict,directed)
self.graph = self.build_graph(graph,tokens[3])
def parse_dot_data(self,data):
"""Parse dot data and return a DotGraph instance"""
try:
try:
self.dotparser.parseWithTabs()
except:
log.warning('Old version of pyparsing. Parser may not work correctly')
ndata = data.replace('\\\n','')
#lines = data.splitlines()
#lines = [l.rstrip('\\') for l in lines]
tokens = self.dotparser.parseString(ndata)
self.build_top_graph(tokens[0])
return self.graph
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print err
return None
def parse_dot_data_debug(self,data):
"""Parse dot data"""
try:
try:
self.dotparser.parseWithTabs()
except:
log.warning('Old version of pyparsing. Parser may not work correctly')
tokens = self.dotparser.parseString(data)
self.build_top_graph(tokens[0])
return tokens[0]
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print err
return None
from UserDict import DictMixin
class OrderedDict(DictMixin):
def __init__(self):
self._keys = []
self._data = {}
def __setitem__(self, key, value):
if key not in self._data:
self._keys.append(key)
self._data[key] = value
def __getitem__(self, key):
return self._data[key]
def __delitem__(self, key):
del self._data[key]
self._keys.remove(key)
def __iter__(self):
for key in self._keys:
yield key
def keys(self):
return list(self._keys)
def copy(self):
copyDict = odict()
copyDict._data = self._data.copy()
copyDict._keys = self._keys[:]
return copyDict
class DotDefaultAttr(object):
def __init__(self, element_type, **kwds):
self.element_type = element_type
self.attr = kwds
def __str__(self):
attrstr = ",".join(["%s=%s" % \
(quote_if_necessary(key),quote_if_necessary(val)) \
for key,val in self.attr.items()])
if attrstr:
attrstr = "[%s]" % attrstr
return "%s%s;\n" % (self.element_type,attrstr)
else:
return ""
class DotParsingException(Exception):
"""Base class for dotparsing exceptions."""
class DotNode(object):
"""Class representing a DOT node"""
def __init__(self,name,**kwds):
"""Create a Node instance
Input:
name - name of node. Have to be a string
**kwds node attributes
"""
self.name = name
self.attr = {}
self.parent = None
self.attr.update(kwds)
def __str__(self):
attrstr = ",".join(["%s=%s" % \
(quote_if_necessary(key),quote_if_necessary(val)) \
for key,val in self.attr.items()])
if attrstr:
attrstr = "[%s]" % attrstr
return "%s%s;\n" % (quote_if_necessary(self.name),attrstr)
def __hash__(self):
return hash(self.name)
def __cmp__(self,other):
try:
if self.name == other:
return 0
except:
pass
return -1
def __getattr__(self,name):
try:
return self.attr[name]
except KeyError:
raise AttributeError
class DotGraph(object):
"""Class representing a DOT graph"""
def __init__(self,name='G',strict=True,directed=False,**kwds):
self._nodes = OrderedDict()
self._allnodes = {}#OrderedDict()
self._alledges = {} #OrderedDict()
self._allgraphs = []
self._edges = {} #OrderedDict()
self.strict = strict
self.directed = directed
self.subgraphs = []
self.name = name
self.padding = " "
self.seq = 0;
self.allitems = []
self.attr ={}
self.strict = strict
self.level = 0;
self.parent = None
self.root = self
self.adj = {}
self.default_node_attr = {}
self.default_edge_attr = {}
self.default_graph_attr = {}
self.attr.update(kwds)
self._allgraphs.append(self)
pass
def __len__(self):
return len(self._nodes)
def __getattr__(self,name):
try:
return self.attr[name]
except KeyError:
raise AttributeError
def get_name(self):
if self.name.strip():
return quote_if_necessary(self.name)
else:
return ""
def add_node(self,node,**kwds):
if not isinstance(node,DotNode):
node = DotNode(str(node),**kwds)
n = node.name
## if n not in self.adj:
## self.adj[n]={}
if n in self._allnodes:
self._allnodes[n].attr.update(kwds)
else:
node.attr.update(self.default_node_attr)
node.attr.update(kwds)
self._allnodes[n] = node
if not n in self._nodes:
self._nodes[n] = node
# Todo: Adding a node to a subgraph should insert it in parent graphs
## parent = self.parent
## if parent:
## print "Parent %s " % parent.name
## while parent:
## print "Parent %s " % parent.name
## if n not in parent._nodes:
## parent._nodes[n] = node
## parent = parent.parent
## else:
## parent = None
return node
def add_edge(self, src, dst, srcport="", dstport="",**kwds):
u = self.add_node(src)
v = self.add_node(dst)
edge = DotEdge(u,v,self.directed,srcport,dstport,**self.default_edge_attr)
edge.attr.update(kwds)
## if not self.strict:
## self.adj[u][v]=self.adj[u].get(v,[])+ [edge]
## if not self.directed:
## self.adj[v][u]=self.adj[v].get(u,[])+ [edge]
##
## else:
## self.adj[u][v]=edge
## if not self.directed:
## self.adj[v][u]=edge
edgekey = (u.name,v.name)
if edgekey in self._alledges:
edgs = self._alledges[edgekey]
if not self.strict:
#edge.parent = edge_parent
if edgekey in self._edges:
self._edges[edgekey].append(edge)
edgs.append(edge)
## else:
## edgs[0].attributes.update(edge.attributes)
## return edgs[0]
else:
## edge.parent = edge_parent
#edge.attr.update(self.default_edge_attr)
self._alledges[edgekey] = [edge]
self._edges[edgekey] = [edge]
return edge
def add_special_edge(self, src, dst, srcport="", dstport="",**kwds):
src_is_graph = isinstance(src,DotSubGraph)
dst_is_graph = isinstance(dst,DotSubGraph)
edges = []
if src_is_graph:
src_nodes = src.get_all_nodes()
else:
src_nodes = [src]
if dst_is_graph:
dst_nodes = dst.get_all_nodes()
else:
dst_nodes = [dst]
for src_node in src_nodes:
for dst_node in dst_nodes:
edge = self.add_edge(src_node,dst_node,srcport,dstport,**kwds)
edges.append(edge)
return edges
def add_default_node_attr(self,**kwds):
self.default_node_attr.update(kwds)
def add_default_edge_attr(self,**kwds):
self.default_edge_attr.update(kwds)
def add_default_graph_attr(self,**kwds):
self.attr.update(kwds)
## #nodecls = self._allnodes[name]
## #nodeparent = nodecls.parent
##
## parent = self.parent
## if parent and (not (nodeparent == self)):
## while parent:
##
## if name in parent._nodes:
##
## del parent._nodes[name]
## # changing a node parent may trigger a change in
## # edge parent
## nodecls.parent = self
## parent = None
## self._nodes[name] = nodecls
## else:
## parent = parent.parent
##
##
##
##
## else:
## nodecls.parent = self
## self._allnodes[name]=nodecls
## self._nodes[name] = nodecls
def delete_node(self, node):
if isinstance(node,DotNode):
name = node.name
else:
name = node
try:
del self._nodes[name]
del self._allnodes[name]
except:
raise DotParsingException, "Node %s does not exists" % name
def get_node(self,nodename):
"""Return node with name=nodename
Returns None if node does not exists.
"""
return self._allnodes.get(nodename,None)
## def add_edge(self, src, dst,attributes={},**kwds):
## src = self.add_node(src)
## dst = self.add_node(dst)
## edge = DotEdge(src,dst,self,attributes=attributes,**kwds)
## edgekey = (src.name,dst.name)
## # Need to set correct edge parent
## # The edge should belong to the node with the lowest level number
## if src.parent.level <= dst.parent.level:
## edge_parent = src.parent
## else:
## edge_parent = dst.parent
##
## if edgekey in self._alledges:
## edgs = self._alledges[edgekey]
## if not self.strict:
## edge.parent = edge_parent
## edgs.append(edge)
##
## else:
## edgs[0].attributes.update(edge.attributes)
## return edgs[0]
## else:
## edge.parent = edge_parent
##
## self._alledges[edgekey] = [edge]
## self._edges[edgekey] = [edge]
##
##
##
##
## return edge
def add_subgraph(self,subgraph,**kwds):
if isinstance(subgraph,DotSubGraph):
subgraphcls = subgraph
else:
subgraphcls = DotSubGraph(subgraph,self.strict,self.directed,**kwds)
subgraphcls._allnodes = self._allnodes
subgraphcls._alledges = self._alledges
subgraphcls._allgraphs = self._allgraphs
subgraphcls.parent = self
subgraphcls.root = self.root
subgraphcls.level = self.level+1;
subgraphcls.add_default_node_attr(**self.default_node_attr)
subgraphcls.add_default_edge_attr(**self.default_edge_attr)
subgraphcls.add_default_graph_attr(**self.attr)
subgraphcls.padding += self.padding
self.subgraphs.append(subgraphcls)
self._allgraphs.append(subgraphcls)
return subgraphcls
def get_subgraphs(self):
return self.subgraphs
def get_edges(self):
return self._edges
def get_all_nodes(self):
nodes = []
for subgraph in self.get_subgraphs():
nodes.extend(subgraph.get_all_nodes())
nodes.extend(self._nodes)
return nodes
def set_attr(self,**kwds):
"""Set graph attributes"""
self.attr.update(kwds)
#self.set_default_graph_attr(kwds)
nodes = property(lambda self: self._nodes.itervalues() )
allnodes = property(lambda self: self._allnodes.itervalues() )
allgraphs = property(lambda self: self._allgraphs.__iter__() )
alledges = property(lambda self: flatten(self._alledges.itervalues()) )
edges = property(get_edges)
def __str__(self):
s = ""
padding = self.padding
if len(self.allitems)>0:
grstr = "".join(["%s%s" % (padding,n) for n in map(str,flatten(self.allitems))])
attrstr = ",".join(["%s=%s" % \
(quote_if_necessary(key),quote_if_necessary(val)) \
for key,val in self.attr.items()])
if attrstr:
attrstr = "%sgraph [%s];" % (padding,attrstr)
if not isinstance(self,DotSubGraph):
s = ""
if self.strict:
s += 'strict '
if self.directed:
s += "digraph"
else:
s += "graph"
return "%s %s{\n%s\n%s\n}" % (s,self.get_name(),grstr,attrstr)
else:
return "%s %s{\n%s\n%s\n%s}" % ('subgraph',self.get_name(),grstr,attrstr,padding)
subgraphstr = "\n".join(["%s%s" % (padding,n) for n in map(str,self.subgraphs)])
nodestr = "".join(["%s%s" % (padding,n) for n in \
map(str,self._nodes.itervalues())])
edgestr = "".join(["%s%s" % (padding,n) for n in \
map(str,flatten(self.edges.itervalues()))])
attrstr = ",".join(["%s=%s" % \
(quote_if_necessary(key),quote_if_necessary(val)) \
for key,val in self.attr.items()])
if attrstr:
attrstr = "%sgraph [%s];" % (padding,attrstr)
if not isinstance(self,DotSubGraph):
s = ""
if self.strict:
s += 'strict '
if self.directed:
s += "digraph"
else:
s += "graph"
return "%s %s{\n%s\n%s\n%s\n%s\n}" % (s,self.get_name(),subgraphstr,attrstr,nodestr,edgestr)
else:
return "%s %s{\n%s\n%s\n%s\n%s\n%s}" % ('subgraph',self.get_name(),subgraphstr,attrstr,nodestr,edgestr,padding)
class DotEdge(object):
"""Class representing a DOT edge"""
def __init__(self,src,dst,directed=False,src_port="", dst_port="",**kwds):
self.src = src
self.dst = dst
self.src_port = src_port
self.dst_port = dst_port
#self.parent = parent_graph
self.attr = {}
if directed:
self.conn = "->"
else:
self.conn = "--"
self.attr.update(kwds)
def __str__(self):
attrstr = ",".join(["%s=%s" % \
(quote_if_necessary(key),quote_if_necessary(val)) \
for key,val in self.attr.items()])
if attrstr:
attrstr = "[%s]" % attrstr
return "%s%s %s %s%s %s;\n" % (quote_if_necessary(self.src.name),\
self.src_port,self.conn, \
quote_if_necessary(self.dst.name),self.dst_port,attrstr)
def get_source(self):
return self.src.name;
def get_destination(self):
return self.dst.name;
def __getattr__(self,name):
try:
return self.attr[name]
except KeyError:
raise AttributeError
class DotSubGraph(DotGraph):
"""Class representing a DOT subgraph"""
def __init__(self,name='subgG',strict=True,directed=False,**kwds):
DotGraph.__init__(self,name,strict,directed,**kwds)
def parse_dot_data(data):
"""Parse dot data and return a DotGraph instance"""
try:
try:
self.dotparser.parseWithTabs()
except:
#log.warning('Old version of pyparsing. Parser may not work correctly')
raise
ndata = data.replace('\\\n','')
tokens = self.dotparser.parseString(ndata)
self.build_top_graph(tokens[0])
return self.graph
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print err
return None
testgraph = r"""
/* Test that the various id types are parsed correctly */
digraph G {
TPR [label=TехПрог];
LFP [label=ЛиФП, pos="420,686", width="0.86"];
//"aa\\" -> b [label="12"];
}
"""
if __name__ == '__main__':
import pprint
print "Creating parser"
gp = DotDataParser()
tok = gp.parse_dot_data_debug(testgraph)
#dg = parse_dot_data(testgraph)
pprint.pprint(tok)
print gp.graph
#del(gp)
#pprint.pprint(t)
#print g
|
gpl-3.0
|
Ictp/indico
|
indico/MaKaC/plugins/Collaboration/test/unit/collaboration_test.py
|
22753
|
# -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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.
##
## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>.
# For now, disable Pylint
# pylint: disable-all
from indico.core.db import DBMgr
from MaKaC.conference import ConferenceHolder
from random import Random
from MaKaC.plugins.Collaboration.services import CollaborationRemoveCSBooking, CollaborationBookingIndexQuery, CollaborationCreateTestCSBooking
from MaKaC.plugins.Collaboration.actions import DeleteAllBookingsAction
from indico.core.index import Catalog
from MaKaC.common.indexes import IndexesHolder
from MaKaC.errors import MaKaCError
from indico.core.config import Config
from util import TestZEOServer
import math
import profile
import time
import logging
import traceback
import unittest
import shutil
import subprocess
import sys
import os, signal
################################### HOW TO USE THIS TEST ##################################
#
# There are 2 groups of configuration parameters.
#
# The 1st group (system and DB paths / configuration) deals with where some files are.
# Currently they point towards the correct locations in the CERN indicodev machine.
#
# The 2nd group deals with the extension of the test.
# This test will insert bookings randmonly in a range of conferences (going from firstConfId to lastConfId),
# trying to insert a number close to "startingBookings"
# Then it will run 4 tests:
# -add n bookings (where n = the "bookingsPerTest" variable)
# -remove n bookings (where n = the "bookingsPerTest" variable)
# -do n queries (where n = indexQueriesPerTest) to the index
# -remove n conferences (where n = removeConfsPerTest) and unindex all their bookings
#
# For this test to work, after an indico install, you need to go to
# /opt/indico/install/cds-indico-xxxxxxx/ and do:
# sudo python setup.py develop (in order to compile the .po to .mo)
# sudo vim setup.py and change INDICO_INSTALL = True to INDICO_INSTALL = False
#
# Also, this test assumes that you did a snapshot of the database in /opt/indico/db
# by copying the data.fs, data.fs.index, and data.fs.tmp into
# dbForTesting.fs, dbForTesting.fs.index, and dbForTesting.fs.tmp
#
#########################################################################################
config = Config.getInstance()
#system and DB paths / configuration
testingDbfile = '/tmp/data.fs'
collaborationDbFile = os.path.join(config.getUploadedFilesTempDir(), 'CollaborationTests-Data.fs')
zeoPort = 9685
pythonExecutable = sys.executable
#test configuration
firstConfId = 40000
lastConfId = 65000
startingBookings = 20000
bookingsPerTest = 100
indexQueriesPerTest = 50
removeConfsPerTest = 10
randomOpsPerTest = 50
startDate = '01/01/2008 00:00'
endDate = '31/12/2010 23:59'
dateFormat = '%d/%m/%Y %H:%M'
doProfile = False
makeCopy = True
doCleanUp = True
doRemove = True
def setup_module():
#this test is a performance test and takes too much time to execute
import nose
raise nose.SkipTest
class TestResponsiveness(unittest.TestCase):
def createDBServer(self, file, port):
pid = os.fork()
if pid:
return pid
else:
server = TestZEOServer(port, file)
server.start()
def setUp(self):
self.random = Random()
self._loggingSetup()
self._log("Start of test. Current pid is: " + str(os.getpid()))
self._log("Initiating setUp of test")
self._log('')
try:
if makeCopy:
self._log("Copying " + testingDbfile + " to " + collaborationDbFile + " ...")
try:
os.remove(collaborationDbFile)
os.remove(collaborationDbFile + '.index')
os.remove(collaborationDbFile + '.tmp')
except:
pass
shutil.copy(testingDbfile, collaborationDbFile)
try:
shutil.copy(testingDbfile + '.index', collaborationDbFile + '.index')
except:
self._log("problem copying " + testingDbfile + '.index')
try:
shutil.copy(testingDbfile + '.tmp', collaborationDbFile + '.tmp')
except:
self._log("problem copying " + testingDbfile + '.tmp')
self._log("copy finished.")
self._log('')
self._log("Starting the ZEO server...")
self.zeoServer = self.createDBServer(collaborationDbFile, zeoPort)
self._log("zodb server started on pid: " + str(self.zeoServer) + " .")
self._log('')
self._log("Creating a CustomDBMgr on port " + str(zeoPort))
self.cdbmgr = DBMgr.getInstance(hostname="localhost", port=zeoPort)
self._log("Starting a request ...")
self.cdbmgr.startRequest()
self._log("Request started successfully.")
self._log('')
if doCleanUp:
self._log('Cleaning the DB of bookings and recreating the indexes')
DeleteAllBookingsAction(FalseAction()).call()
self._log('Cleanup succesfull')
self._log("We start populating DB with bookings...")
#ConferenceHolder()._getIdx() is an OOBTree
size = lastConfId - firstConfId
self._log("Populating among aproximately " + str(size) + " events, from " + str(firstConfId) + " to " + str(lastConfId) + ", with aproximately " + str(startingBookings) + " bookings")
self._log("Initial size of 'all' index: " + str(IndexesHolder().getById("Collaboration").getAllBookingsIndex().getCount()))
self.validConfIds = []
self.confsWithBookings = []
populated = 0
added = 0
chance = (float(startingBookings) / float(size)) / 2.0
ch = ConferenceHolder()
for confId in xrange(firstConfId, lastConfId + 1):
confId = str(confId)
if self.random.random() < chance:
try:
conf = ch.getById(confId)
self.validConfIds.append(confId)
except MaKaCError:
continue
i = 0
bookingsForThisConf = max(int(self.random.normalvariate(3, 3)),0)
added += bookingsForThisConf
while i < bookingsForThisConf:
Catalog.getIdx("cs_bookingmanager_conference").get(conf.getId()).createTestBooking(bookingParams = {'startDate': self._randomDate(startDate, endDate)})
i += 1
populated += 1
self.confsWithBookings.append(confId)
if populated % 100 == 0:
self._log(str(populated) + ' events populated. Index size: ' + str (IndexesHolder().getById("Collaboration").getAllBookingsIndex().getCount()))
self._log("Populating finished. " + str(populated) + " events populated with " + str(added) + " bookings")
self._log("Size of 'all' index is now: " + str(IndexesHolder().getById("Collaboration").getAllBookingsIndex().getCount()))
self._log("Performing commit...")
self.cdbmgr.endRequest(True) #True = commmit
self._log("End of request")
self._log('')
except Exception, e:
tb = str(traceback.format_tb(sys.exc_info()[2]))
self.logger.error("There was an exception in setUp. Calling tearDown. Exception: " + str(e) + ", Traceback = " + tb)
self.tearDown()
self.fail("setUp failed. Cause: " + str(e) + ", Traceback = " + tb)
def tearDown(self):
self._log("Initiating tearDown of test")
self._log('')
try:
self._log("Sending kill signal to ZEO Server at pid " + str(self.zeoServer) + " ...")
os.kill(self.zeoServer, signal.SIGTERM)
self._log("Signal sent")
except Exception, e:
self._log("Problem sending kill signal: " + str(e))
try:
self._log("Waiting for ZEO Server to finish ...")
os.wait()
self._log("Zodb server finished.")
except Exception, e:
self._log("Problem waiting for ZEO Server: " + str(e))
if doRemove:
try:
self._log("Removing " + collaborationDbFile + " ...")
self._log(collaborationDbFile + " removed.")
except Exception, e:
self._log("Problem removing the test DB file: " + str(e))
self._log("End of test")
def testResponsiveness(self):
self._log("Start of tests")
self._log('')
self._log("Starting add booking test")
self._addBookingTest()
self._log("End of add booking test. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % (self.average, self.deviation, self.caverage, self.cdeviation))
self._log("Starting remove booking test")
self._removeBookingTest()
self._log("End of remove booking test. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % (self.average, self.deviation, self.caverage, self.cdeviation))
self._log("Starting index query test")
self._indexQueryTest()
self._log("End of index query test. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % (self.average, self.deviation, self.caverage, self.cdeviation))
self._log("Starting remove conference test")
self._removeConfTest()
self._log("End of remove conference test. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % (self.average, self.deviation, self.caverage, self.cdeviation))
self._log("Starting random operations test")
self._randomOpsTest()
self._log("End of random operations test. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % (self.average, self.deviation, self.caverage, self.cdeviation))
self._log("End of tests")
self._log('')
assert True
######## Add booking test ########
def _addBookingTest(self):
def executeAddBookingTest():
times = []
i = 0
while i < bookingsPerTest:
confId = self._getConfIdForAdding()
start = time.time()
cstart = time.clock()
self._addBooking(confId)
cend = time.clock()
end = time.time()
times.append((end - start, cend - cstart))
self._updateValidIdsAfterAddingBooking(confId)
i = i + 1
self.average, self.deviation, self.caverage, self.cdeviation = processResults(times)
if doProfile:
profile.runctx("executeAddBookingTest()", {}, {'executeAddBookingTest' : executeAddBookingTest}, 'addBooking.prof')
else:
exec "executeAddBookingTest()" in {}, {'executeAddBookingTest' : executeAddBookingTest}
def _getConfIdForAdding(self):
return self.random.choice(self.validConfIds)
def _updateValidIdsAfterAddingBooking(self, confId):
if confId not in self.confsWithBookings:
self.confsWithBookings.append(confId)
def _addBooking(self, confId):
self.cdbmgr.startRequest()
params = {"conference": confId,
"type": 'DummyPlugin',
"bookingParams": {"startDate": self._randomDate(startDate, endDate)},
}
service = CollaborationCreateTestCSBooking(params)
service._checkParams()
service._getAnswer()
self.cdbmgr.endRequest()
######## Remove booking test ########
def _removeBookingTest(self):
def executeRemoveBookingTest():
times = []
i = 0
while i < bookingsPerTest:
confId, bookingId = self._getIdsForRemoveBooking()
start = time.time()
cstart = time.clock()
self._removeBooking(confId, bookingId)
cend = time.clock()
end = time.time()
times.append((end - start, cend - cstart))
self._updateValidIdsAfterRemoveBooking(confId)
i = i + 1
self.average, self.deviation, self.caverage, self.cdeviation = processResults(times)
if doProfile:
profile.runctx("executeRemoveBookingTest()", {}, {'executeRemoveBookingTest' : executeRemoveBookingTest}, 'removeBooking.prof')
else:
exec "executeRemoveBookingTest()" in {}, {'executeRemoveBookingTest' : executeRemoveBookingTest}
def _getIdsForRemoveBooking(self):
n = 0
self.cdbmgr.startRequest()
while n == 0:
counter = 0
confId = self.random.choice(self.confsWithBookings)
testBookings = Catalog.getIdx("cs_bookingmanager_conference").get(confId)._bookingsByType.get("DummyPlugin", []) #list of booking ids
n = len(testBookings)
if n > 0:
bookingId = self.random.choice(testBookings)
else:
counter += 1
if counter > 100:
self.fail("Could not found a good conference for remove booking")
self.cdbmgr.endRequest()
return confId, bookingId
def _updateValidIdsAfterRemoveBooking(self, confId):
self.cdbmgr.startRequest()
if len(Catalog.getIdx("cs_bookingmanager_conference").get(confId)._bookingsByType.get("DummyPlugin", [])) == 0:
self.confsWithBookings.remove(confId)
self.cdbmgr.endRequest()
def _removeBooking(self, confId, bookingId):
self.cdbmgr.startRequest()
params = {"conference": confId,
"bookingId": bookingId
}
service = CollaborationRemoveCSBooking(params)
service._checkParams()
service._getAnswer()
self.cdbmgr.endRequest()
######## Remove conference test ########
def _removeConfTest(self):
def executeRemoveConfTest():
self.removedConfs = set([''])
times = []
i = 0
while i < removeConfsPerTest:
confId = self.random.choice(self.confsWithBookings)
start = time.time()
cstart = time.clock()
self._removeConf(confId)
cend = time.clock()
end = time.time()
times.append((end - start, cend - cstart))
i = i + 1
self.validConfIds.remove(confId)
self.confsWithBookings.remove(confId)
if len(self.confsWithBookings) == 0:
self._log("Stopped removeConf test after removing " + str(i) + " conferences")
break
self.average, self.deviation, self.caverage, self.cdeviation = processResults(times)
if doProfile:
profile.runctx("executeRemoveConfTest()", {}, {'executeRemoveConfTest' : executeRemoveConfTest}, 'removeConference.prof')
else:
exec "executeRemoveConfTest()" in {}, {'executeRemoveConfTest' : executeRemoveConfTest}
def _removeConf(self, confId):
self.cdbmgr.startRequest()
Catalog.getIdx("cs_bookingmanager_conference").get(confId).notifyDeletion()
self.cdbmgr.endRequest()
######## Index query test ########
def _indexQueryTest(self):
def executeIndexQueryTest():
times = []
i = 0
while i < indexQueriesPerTest:
start = time.time()
cstart = time.clock()
self._indexQuery()
cend = time.clock()
end = time.time()
times.append((end - start, cend - cstart))
i = i + 1
self.average, self.deviation, self.caverage, self.cdeviation = processResults(times)
if doProfile:
profile.runctx("executeIndexQueryTest()", {}, {'executeIndexQueryTest' : executeIndexQueryTest}, 'indexQuery.prof')
else:
exec "executeIndexQueryTest()" in {}, {'executeIndexQueryTest' : executeIndexQueryTest}
def _indexQuery(self):
self.cdbmgr.startRequest()
fromConfId = self.random.choice(self.validConfIds)
toConfId = self.random.choice(self.validConfIds)
if int(toConfId) < int(fromConfId):
fromConfId, toConfId = toConfId, fromConfId
fromTitle = ConferenceHolder().getById(fromConfId).getTitle()
toTitle = ConferenceHolder().getById(toConfId).getTitle()
params = {"page" : self.random.randint(0, 10),
"resultsPerPage" : 50,
"indexName": 'all',
"viewBy": 'conferenceTitle',
"orderBy": "descending",
"fromTitle": fromTitle,
"toTitle": toTitle,
"sinceDate": '',
"toDate": '',
"fromDays": '',
"toDays": '',
"onlyPending": False,
"categoryId": '',
"conferenceId": ''
}
service = CollaborationBookingIndexQuery(params)
service._checkParams()
service._getAnswer()
self.cdbmgr.endRequest()
######## Random ops test ########
def _randomOpsTest(self):
randomOps = ['removeConf'] + ['removeBooking']*2 + ['indexQuery']*3 + ['addBooking']*10
timesRemoveConf = []
timesRemoveBooking = []
timesIndexQuery = []
timesAddBooking = []
i = 0
while i < randomOpsPerTest:
i = i + 1
op = self.random.choice(randomOps)
if op == 'removeConf':
confId = self.random.choice(self.confsWithBookings)
start = time.time()
cstart = time.clock()
self._removeConf(confId)
cend = time.clock()
end = time.time()
timesRemoveConf.append((end - start, cend - cstart))
self.validConfIds.remove(confId)
self.confsWithBookings.remove(confId)
elif op == 'removeBooking':
confId, bookingId = self._getIdsForRemoveBooking()
start = time.time()
cstart = time.clock()
self._removeBooking(confId, bookingId)
cend = time.clock()
end = time.time()
timesRemoveBooking.append((end - start, cend - cstart))
self._updateValidIdsAfterRemoveBooking(confId)
elif op == 'indexQuery':
start = time.time()
cstart = time.clock()
self._indexQuery()
cend = time.clock()
end = time.time()
timesIndexQuery.append((end - start, cend - cstart))
elif op == 'addBooking':
confId = self._getConfIdForAdding()
start = time.time()
cstart = time.clock()
self._addBooking(confId)
cend = time.clock()
end = time.time()
timesAddBooking.append((end - start, cend - cstart))
if timesAddBooking:
self._log("[Random ops test] Add booking. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % processResults(timesAddBooking))
else:
self._log("[Random ops test] No add booking operations were executed")
if timesIndexQuery:
self._log("[Random ops test] Index Query. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % processResults(timesIndexQuery))
else:
self._log("[Random ops test] No index query operations were executed")
if timesRemoveBooking:
self._log("[Random ops test] Remove booking. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % processResults(timesRemoveBooking))
else:
self._log("[Random ops test] No remove booking operations were executed")
if timesRemoveConf:
self._log("[Random ops test] Remove conference. Normal time: avg= %.5fs, dev= %.5fs. CPU time: avg= %.5fs, dev= %.5fs." % processResults(timesRemoveConf))
else:
self._log("[Random ops test] No remove conference operations were executed")
self.average, self.deviation, self.caverage, self.cdeviation = processResults(timesAddBooking + timesAddBooking + timesAddBooking + timesAddBooking)
######## Logging and util stuff ########
def _loggingSetup(self):
self.logger = logging.getLogger('CollaborationTest')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
self.logger.addHandler(handler)
def _log(self, message):
self.logger.debug(str(message))
def _randomDate(self, start, end):
stime = time.mktime(time.strptime(start, dateFormat))
etime = time.mktime(time.strptime(end, dateFormat))
ptime = stime + self.random.random() * (etime - stime)
return time.strftime(dateFormat, time.localtime(ptime))
######### Helper stuff ###########3
class FalseAction:
def getOwner(self):
return None
def processResults(data):
n = len(data)
sum = 0
squareSum = 0
csum = 0
csquareSum = 0
for t in data:
sum += t[0]
csum += t[1]
squareSum += t[0] * t[0]
csquareSum += t[1] * t[1]
if n>0:
average = sum / n
caverage = csum / n
else:
average = 0
caverage = 0
if n > 1:
deviation = math.sqrt((squareSum - n * average * average) / (n - 1))
cdeviation = math.sqrt((csquareSum - n * caverage * caverage) / (n - 1))
else:
deviation = 0
cdeviation = 0
return average, deviation, caverage, cdeviation
|
gpl-3.0
|
LINUXADDICT/cakecrud
|
app/Controller/Component/RandomComponent.php
|
961
|
<?php
App::uses('Component', 'Controller');
class RandomComponent extends Component
{
/**
* Password generator function
*
* This function will randomly generate a password from a given set of characters
*
* @param int = 8, length of the password you want to generate
* @return string, the password
*/
public function generateRandomString ($length)
{
// initialize variables
$str = "";
$i = 0;
$possible = "0123456789bcdfghjkmnpqrstvwxyz";
// add random characters to $password until $length is reached
while ($i < $length) {
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
// we don't want this character if it's already in the password
if (!strstr($str, $char)) {
$str .= $char;
$i++;
}
}
return $str;
}
}
?>
|
gpl-3.0
|
xevrem/vaerydian
|
Glimpse/Controls/GTextBox.cs
|
3060
|
//
// GTextBox.cs
//
// Author:
// erika <>
//
// Copyright (c) 2016 erika
//
// 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 System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Glimpse.Input;
using Glimpse.Managers;
namespace Glimpse.Controls
{
public class GTextBox : Control
{
private int _spacing;
private Vector2 _text_lengths;
private Vector2 _text_position;
public GTextBox ()
{
}
#region implemented abstract members of Control
public override event InterfaceHandler updating;
public override void init(){
_spacing = FontManager.fonts[this.font_name].LineSpacing;
_text_lengths = FontManager.fonts [this.font_name].MeasureString (this.text);
if(autosize)
this.bounds = new Rectangle(this.bounds.Location, new Point ((int) _text_lengths.X+2*this.border, (int)_text_lengths.Y+2*border));
if (center_text) {
_text_position.Y = this.bounds.Center.ToVector2 ().Y - (_text_lengths.Y / 2f);
_text_position.X = this.bounds.Center.ToVector2 ().X - (_text_lengths.X / 2f);
} else {
_text_position = this.bounds.Location.ToVector2 ();
}
}
public override void load(ContentManager content){
this.background = content.Load<Texture2D>(this.background_name);
}
public override void update (int elapsed_time)
{
if (center_text) {
_text_lengths = FontManager.fonts [this.font_name].MeasureString (this.text);
_text_position.Y = this.bounds.Center.ToVector2 ().Y - (_text_lengths.Y / 2f);
_text_position.X = this.bounds.Center.ToVector2 ().X - (_text_lengths.X / 2f);
}
if(updating != null)
updating(this, InputManager.get_interface_args ());
}
public override void draw (SpriteBatch sprite_batch)
{
//throw new NotImplementedException ();
sprite_batch.Draw (this.background, this.bounds, this.background_color);
//TODO: fix positioning
sprite_batch.DrawString (FontManager.fonts[this.font_name], this.text, this._text_position, this.text_color);
}
public override void clean_up ()
{
this.updating = null;
}
public override void reload ()
{
throw new NotImplementedException ();
}
public override void resize ()
{
throw new NotImplementedException ();
}
public override void handle_events(InterfaceArgs args)
{
//throw new NotImplementedException();
}
#endregion
}
}
|
gpl-3.0
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/net/quic/core/quic_stream_sequencer_test.cc
|
22458
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/core/quic_stream_sequencer.h"
#include <algorithm>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "base/logging.h"
#include "base/rand_util.h"
#include "net/base/ip_endpoint.h"
#include "net/quic/core/quic_flags.h"
#include "net/quic/core/quic_stream.h"
#include "net/quic/core/quic_utils.h"
#include "net/quic/test_tools/mock_clock.h"
#include "net/quic/test_tools/quic_stream_sequencer_peer.h"
#include "net/quic/test_tools/quic_test_utils.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::StringPiece;
using std::min;
using std::string;
using testing::_;
using testing::AnyNumber;
using testing::CreateFunctor;
using testing::InSequence;
using testing::Return;
using testing::StrEq;
namespace net {
namespace test {
class MockStream : public QuicStream {
public:
MockStream(QuicSession* session, QuicStreamId id) : QuicStream(id, session) {}
MOCK_METHOD0(OnFinRead, void());
MOCK_METHOD0(OnDataAvailable, void());
MOCK_METHOD2(CloseConnectionWithDetails,
void(QuicErrorCode error, const string& details));
MOCK_METHOD1(Reset, void(QuicRstStreamErrorCode error));
MOCK_METHOD0(OnCanWrite, void());
virtual bool IsFlowControlEnabled() const { return true; }
const IPEndPoint& PeerAddressOfLatestPacket() const override {
return peer_address_;
}
protected:
IPEndPoint peer_address_ = IPEndPoint(net::test::Any4(), 65535);
};
namespace {
static const char kPayload[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
class QuicStreamSequencerTest : public ::testing::Test {
public:
void ConsumeData(size_t num_bytes) {
char buffer[1024];
ASSERT_GT(arraysize(buffer), num_bytes);
struct iovec iov;
iov.iov_base = buffer;
iov.iov_len = num_bytes;
ASSERT_EQ(static_cast<int>(num_bytes), sequencer_->Readv(&iov, 1));
}
protected:
QuicStreamSequencerTest()
: connection_(new MockQuicConnection(&helper_,
&alarm_factory_,
Perspective::IS_CLIENT)),
session_(connection_),
stream_(&session_, 1),
sequencer_(new QuicStreamSequencer(&stream_, &clock_)) {}
// Verify that the data in first region match with the expected[0].
bool VerifyReadableRegion(const std::vector<string>& expected) {
iovec iovecs[1];
if (sequencer_->GetReadableRegions(iovecs, 1)) {
return (VerifyIovecs(iovecs, 1, std::vector<string>{expected[0]}));
}
return false;
}
// Verify that the data in each of currently readable regions match with each
// item given in |expected|.
bool VerifyReadableRegions(const std::vector<string>& expected) {
iovec iovecs[5];
size_t num_iovecs =
sequencer_->GetReadableRegions(iovecs, arraysize(iovecs));
return VerifyReadableRegion(expected) &&
VerifyIovecs(iovecs, num_iovecs, expected);
}
bool VerifyIovecs(iovec* iovecs,
size_t num_iovecs,
const std::vector<string>& expected) {
int start_position = 0;
for (size_t i = 0; i < num_iovecs; ++i) {
if (!VerifyIovec(iovecs[i],
expected[0].substr(start_position, iovecs[i].iov_len))) {
return false;
}
start_position += iovecs[i].iov_len;
}
return true;
}
bool VerifyIovec(const iovec& iovec, StringPiece expected) {
if (iovec.iov_len != expected.length()) {
LOG(ERROR) << "Invalid length: " << iovec.iov_len << " vs "
<< expected.length();
return false;
}
if (memcmp(iovec.iov_base, expected.data(), expected.length()) != 0) {
LOG(ERROR) << "Invalid data: " << static_cast<char*>(iovec.iov_base)
<< " vs " << expected;
return false;
}
return true;
}
void OnFinFrame(QuicStreamOffset byte_offset, const char* data) {
QuicStreamFrame frame;
frame.stream_id = 1;
frame.offset = byte_offset;
frame.data_buffer = data;
frame.data_length = strlen(data);
frame.fin = true;
sequencer_->OnStreamFrame(frame);
}
void OnFrame(QuicStreamOffset byte_offset, const char* data) {
QuicStreamFrame frame;
frame.stream_id = 1;
frame.offset = byte_offset;
frame.data_buffer = data;
frame.data_length = strlen(data);
frame.fin = false;
sequencer_->OnStreamFrame(frame);
}
size_t NumBufferedBytes() {
return QuicStreamSequencerPeer::GetNumBufferedBytes(sequencer_.get());
}
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
MockQuicConnection* connection_;
MockClock clock_;
MockQuicSpdySession session_;
testing::StrictMock<MockStream> stream_;
std::unique_ptr<QuicStreamSequencer> sequencer_;
};
// TODO(rch): reorder these tests so they build on each other.
TEST_F(QuicStreamSequencerTest, RejectOldFrame) {
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
OnFrame(0, "abc");
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
EXPECT_EQ(3u, stream_.flow_controller()->bytes_consumed());
// Ignore this - it matches a past packet number and we should not see it
// again.
OnFrame(0, "def");
EXPECT_EQ(0u, NumBufferedBytes());
}
TEST_F(QuicStreamSequencerTest, RejectBufferedFrame) {
EXPECT_CALL(stream_, OnDataAvailable());
OnFrame(0, "abc");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
// Ignore this - it matches a buffered frame.
// Right now there's no checking that the payload is consistent.
OnFrame(0, "def");
EXPECT_EQ(3u, NumBufferedBytes());
}
TEST_F(QuicStreamSequencerTest, FullFrameConsumed) {
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
OnFrame(0, "abc");
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameConsumed) {
sequencer_->SetBlockedUntilFlush();
OnFrame(0, "abc");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
sequencer_->SetUnblocked();
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
EXPECT_FALSE(sequencer_->IsClosed());
OnFinFrame(3, "def");
EXPECT_TRUE(sequencer_->IsClosed());
}
TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameAndFinConsumed) {
sequencer_->SetBlockedUntilFlush();
OnFinFrame(0, "abc");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
EXPECT_FALSE(sequencer_->IsClosed());
sequencer_->SetUnblocked();
EXPECT_TRUE(sequencer_->IsClosed());
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, EmptyFrame) {
EXPECT_CALL(stream_,
CloseConnectionWithDetails(QUIC_EMPTY_STREAM_FRAME_NO_FIN, _));
OnFrame(0, "");
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, EmptyFinFrame) {
EXPECT_CALL(stream_, OnDataAvailable());
OnFinFrame(0, "");
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, PartialFrameConsumed) {
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 2)));
OnFrame(0, "abc");
EXPECT_EQ(1u, NumBufferedBytes());
EXPECT_EQ(2u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, NextxFrameNotConsumed) {
EXPECT_CALL(stream_, OnDataAvailable());
OnFrame(0, "abc");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, FutureFrameNotProcessed) {
OnFrame(3, "abc");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
}
TEST_F(QuicStreamSequencerTest, OutOfOrderFrameProcessed) {
// Buffer the first
OnFrame(6, "ghi");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
// Buffer the second
OnFrame(3, "def");
EXPECT_EQ(6u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_EQ(6u, sequencer_->NumBytesBuffered());
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 9)));
// Now process all of them at once.
OnFrame(0, "abc");
EXPECT_EQ(9u, sequencer_->NumBytesConsumed());
EXPECT_EQ(0u, sequencer_->NumBytesBuffered());
EXPECT_EQ(0u, NumBufferedBytes());
}
TEST_F(QuicStreamSequencerTest, BasicHalfCloseOrdered) {
InSequence s;
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
OnFinFrame(0, "abc");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
}
TEST_F(QuicStreamSequencerTest, BasicHalfCloseUnorderedWithFlush) {
OnFinFrame(6, "");
EXPECT_EQ(6u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
OnFrame(3, "def");
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 6)));
EXPECT_FALSE(sequencer_->IsClosed());
OnFrame(0, "abc");
EXPECT_TRUE(sequencer_->IsClosed());
}
TEST_F(QuicStreamSequencerTest, BasicHalfUnordered) {
OnFinFrame(3, "");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
EXPECT_CALL(stream_, OnDataAvailable())
.WillOnce(testing::Invoke(
CreateFunctor(&QuicStreamSequencerTest::ConsumeData,
base::Unretained(this), 3)));
EXPECT_FALSE(sequencer_->IsClosed());
OnFrame(0, "abc");
EXPECT_TRUE(sequencer_->IsClosed());
}
TEST_F(QuicStreamSequencerTest, TerminateWithReadv) {
char buffer[3];
OnFinFrame(3, "");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
EXPECT_FALSE(sequencer_->IsClosed());
EXPECT_CALL(stream_, OnDataAvailable());
OnFrame(0, "abc");
iovec iov = {&buffer[0], 3};
int bytes_read = sequencer_->Readv(&iov, 1);
EXPECT_EQ(3, bytes_read);
EXPECT_TRUE(sequencer_->IsClosed());
}
TEST_F(QuicStreamSequencerTest, MutipleOffsets) {
OnFinFrame(3, "");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
EXPECT_CALL(stream_, Reset(QUIC_MULTIPLE_TERMINATION_OFFSETS));
OnFinFrame(5, "");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
EXPECT_CALL(stream_, Reset(QUIC_MULTIPLE_TERMINATION_OFFSETS));
OnFinFrame(1, "");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
OnFinFrame(3, "");
EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get()));
}
class QuicSequencerRandomTest : public QuicStreamSequencerTest {
public:
typedef std::pair<int, string> Frame;
typedef std::vector<Frame> FrameList;
void CreateFrames() {
int payload_size = arraysize(kPayload) - 1;
int remaining_payload = payload_size;
while (remaining_payload != 0) {
int size = min(OneToN(6), remaining_payload);
int index = payload_size - remaining_payload;
list_.push_back(std::make_pair(index, string(kPayload + index, size)));
remaining_payload -= size;
}
}
QuicSequencerRandomTest() { CreateFrames(); }
int OneToN(int n) { return base::RandInt(1, n); }
void ReadAvailableData() {
// Read all available data
char output[arraysize(kPayload) + 1];
iovec iov;
iov.iov_base = output;
iov.iov_len = arraysize(output);
int bytes_read = sequencer_->Readv(&iov, 1);
EXPECT_NE(0, bytes_read);
output_.append(output, bytes_read);
}
string output_;
// Data which peek at using GetReadableRegion if we back up.
string peeked_;
FrameList list_;
};
// All frames are processed as soon as we have sequential data.
// Infinite buffering, so all frames are acked right away.
TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingNoBackup) {
InSequence s;
EXPECT_CALL(stream_, OnDataAvailable())
.Times(AnyNumber())
.WillRepeatedly(
Invoke(this, &QuicSequencerRandomTest::ReadAvailableData));
while (!list_.empty()) {
int index = OneToN(list_.size()) - 1;
LOG(ERROR) << "Sending index " << index << " " << list_[index].second;
OnFrame(list_[index].first, list_[index].second.data());
list_.erase(list_.begin() + index);
}
ASSERT_EQ(arraysize(kPayload) - 1, output_.size());
EXPECT_EQ(kPayload, output_);
}
TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingBackup) {
char buffer[10];
iovec iov[2];
iov[0].iov_base = &buffer[0];
iov[0].iov_len = 5;
iov[1].iov_base = &buffer[5];
iov[1].iov_len = 5;
EXPECT_CALL(stream_, OnDataAvailable()).Times(AnyNumber());
while (output_.size() != arraysize(kPayload) - 1) {
if (!list_.empty() && (base::RandUint64() % 2 == 0)) { // Send data
int index = OneToN(list_.size()) - 1;
OnFrame(list_[index].first, list_[index].second.data());
list_.erase(list_.begin() + index);
} else { // Read data
bool has_bytes = sequencer_->HasBytesToRead();
iovec peek_iov[20];
int iovs_peeked = sequencer_->GetReadableRegions(peek_iov, 20);
QuicTime timestamp = clock_.ApproximateNow();
if (has_bytes) {
ASSERT_LT(0, iovs_peeked);
ASSERT_TRUE(sequencer_->GetReadableRegion(peek_iov, ×tamp));
} else {
ASSERT_EQ(0, iovs_peeked);
ASSERT_FALSE(sequencer_->GetReadableRegion(peek_iov, ×tamp));
}
int total_bytes_to_peek = arraysize(buffer);
for (int i = 0; i < iovs_peeked; ++i) {
int bytes_to_peek = min<int>(peek_iov[i].iov_len, total_bytes_to_peek);
peeked_.append(static_cast<char*>(peek_iov[i].iov_base), bytes_to_peek);
total_bytes_to_peek -= bytes_to_peek;
if (total_bytes_to_peek == 0) {
break;
}
}
int bytes_read = sequencer_->Readv(iov, 2);
output_.append(buffer, bytes_read);
ASSERT_EQ(output_.size(), peeked_.size());
}
}
EXPECT_EQ(string(kPayload), output_);
EXPECT_EQ(string(kPayload), peeked_);
}
// Same as above, just using a different method for reading.
TEST_F(QuicStreamSequencerTest, MarkConsumed) {
InSequence s;
EXPECT_CALL(stream_, OnDataAvailable());
OnFrame(0, "abc");
OnFrame(3, "def");
OnFrame(6, "ghi");
// abcdefghi buffered.
EXPECT_EQ(9u, sequencer_->NumBytesBuffered());
// Peek into the data.
std::vector<string> expected = {"abcdefghi"};
ASSERT_TRUE(VerifyReadableRegions(expected));
// Consume 1 byte.
sequencer_->MarkConsumed(1);
EXPECT_EQ(1u, stream_.flow_controller()->bytes_consumed());
// Verify data.
std::vector<string> expected2 = {"bcdefghi"};
ASSERT_TRUE(VerifyReadableRegions(expected2));
EXPECT_EQ(8u, sequencer_->NumBytesBuffered());
// Consume 2 bytes.
sequencer_->MarkConsumed(2);
EXPECT_EQ(3u, stream_.flow_controller()->bytes_consumed());
// Verify data.
std::vector<string> expected3 = {"defghi"};
ASSERT_TRUE(VerifyReadableRegions(expected3));
EXPECT_EQ(6u, sequencer_->NumBytesBuffered());
// Consume 5 bytes.
sequencer_->MarkConsumed(5);
EXPECT_EQ(8u, stream_.flow_controller()->bytes_consumed());
// Verify data.
std::vector<string> expected4{"i"};
ASSERT_TRUE(VerifyReadableRegions(expected4));
EXPECT_EQ(1u, sequencer_->NumBytesBuffered());
}
TEST_F(QuicStreamSequencerTest, MarkConsumedError) {
EXPECT_CALL(stream_, OnDataAvailable());
OnFrame(0, "abc");
OnFrame(9, "jklmnopqrstuvwxyz");
// Peek into the data. Only the first chunk should be readable because of the
// missing data.
std::vector<string> expected{"abc"};
ASSERT_TRUE(VerifyReadableRegions(expected));
// Now, attempt to mark consumed more data than was readable and expect the
// stream to be closed.
EXPECT_CALL(stream_, Reset(QUIC_ERROR_PROCESSING_STREAM));
EXPECT_QUIC_BUG(sequencer_->MarkConsumed(4),
"Invalid argument to MarkConsumed."
" expect to consume: 4, but not enough bytes available.");
}
TEST_F(QuicStreamSequencerTest, MarkConsumedWithMissingPacket) {
InSequence s;
EXPECT_CALL(stream_, OnDataAvailable());
OnFrame(0, "abc");
OnFrame(3, "def");
// Missing packet: 6, ghi.
OnFrame(9, "jkl");
std::vector<string> expected = {"abcdef"};
ASSERT_TRUE(VerifyReadableRegions(expected));
sequencer_->MarkConsumed(6);
}
TEST_F(QuicStreamSequencerTest, DontAcceptOverlappingFrames) {
// The peer should never send us non-identical stream frames which contain
// overlapping byte ranges - if they do, we close the connection.
QuicStreamFrame frame1(kClientDataStreamId1, false, 1, StringPiece("hello"));
sequencer_->OnStreamFrame(frame1);
QuicStreamFrame frame2(kClientDataStreamId1, false, 2, StringPiece("hello"));
EXPECT_CALL(stream_,
CloseConnectionWithDetails(QUIC_OVERLAPPING_STREAM_DATA, _))
.Times(1);
sequencer_->OnStreamFrame(frame2);
}
TEST_F(QuicStreamSequencerTest, InOrderTimestamps) {
// This test verifies that timestamps returned by
// GetReadableRegion() are in the correct sequence when frames
// arrive at the sequencer in order.
EXPECT_CALL(stream_, OnDataAvailable());
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
// Buffer the first frame.
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
QuicTime t1 = clock_.ApproximateNow();
OnFrame(0, "abc");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
// Buffer the second frame.
QuicTime t2 = clock_.ApproximateNow();
OnFrame(3, "def");
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
EXPECT_EQ(6u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_EQ(6u, sequencer_->NumBytesBuffered());
iovec iovecs[1];
QuicTime timestamp(QuicTime::Zero());
EXPECT_TRUE(sequencer_->GetReadableRegion(iovecs, ×tamp));
EXPECT_EQ(timestamp, t1);
QuicStreamSequencerTest::ConsumeData(3);
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
EXPECT_TRUE(sequencer_->GetReadableRegion(iovecs, ×tamp));
EXPECT_EQ(timestamp, t2);
QuicStreamSequencerTest::ConsumeData(3);
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(6u, sequencer_->NumBytesConsumed());
EXPECT_EQ(0u, sequencer_->NumBytesBuffered());
}
TEST_F(QuicStreamSequencerTest, OutOfOrderTimestamps) {
// This test verifies that timestamps returned by
// GetReadableRegion() are in the correct sequence when frames
// arrive at the sequencer out of order.
EXPECT_CALL(stream_, OnDataAvailable());
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
// Buffer the first frame
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
QuicTime t1 = clock_.ApproximateNow();
OnFrame(3, "def");
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
// Buffer the second frame
QuicTime t2 = clock_.ApproximateNow();
OnFrame(0, "abc");
clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
EXPECT_EQ(6u, NumBufferedBytes());
EXPECT_EQ(0u, sequencer_->NumBytesConsumed());
EXPECT_EQ(6u, sequencer_->NumBytesBuffered());
iovec iovecs[1];
QuicTime timestamp(QuicTime::Zero());
EXPECT_TRUE(sequencer_->GetReadableRegion(iovecs, ×tamp));
EXPECT_EQ(timestamp, t2);
QuicStreamSequencerTest::ConsumeData(3);
EXPECT_EQ(3u, NumBufferedBytes());
EXPECT_EQ(3u, sequencer_->NumBytesConsumed());
EXPECT_EQ(3u, sequencer_->NumBytesBuffered());
EXPECT_TRUE(sequencer_->GetReadableRegion(iovecs, ×tamp));
EXPECT_EQ(timestamp, t1);
QuicStreamSequencerTest::ConsumeData(3);
EXPECT_EQ(0u, NumBufferedBytes());
EXPECT_EQ(6u, sequencer_->NumBytesConsumed());
EXPECT_EQ(0u, sequencer_->NumBytesBuffered());
}
// TODO(danzh): Figure out the way to implement this test case without the use
// of unsupported StringPiece constructor.
#if 0
TEST_F(QuicStreamSequencerTest, OnStreamFrameWithNullSource) {
// Pass in a frame with data pointing to null address, expect to close
// connection with error.
StringPiece source(nullptr, 5u);
QuicStreamFrame frame(kClientDataStreamId1, false, 1, source);
EXPECT_CALL(stream_, CloseConnectionWithDetails(
QUIC_STREAM_SEQUENCER_INVALID_STATE, _));
sequencer_->OnStreamFrame(frame);
}
#endif
TEST_F(QuicStreamSequencerTest, ReadvError) {
EXPECT_CALL(stream_, OnDataAvailable());
string source(100, 'a');
OnFrame(0u, source.data());
EXPECT_EQ(source.length(), sequencer_->NumBytesBuffered());
// Pass in a null iovec, expect to tear down connection.
EXPECT_CALL(stream_, CloseConnectionWithDetails(
QUIC_STREAM_SEQUENCER_INVALID_STATE, _));
iovec iov{nullptr, 512};
sequencer_->Readv(&iov, 1u);
}
} // namespace
} // namespace test
} // namespace net
|
gpl-3.0
|
potty-dzmeia/db4o
|
src/db4oj.tests/src/com/db4o/test/legacy/soda/engines/db4o/STDb4oClientServer.java
|
2554
|
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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.db4o.test.legacy.soda.engines.db4o;
import java.io.*;
import com.db4o.*;
import com.db4o.cs.*;
import com.db4o.foundation.*;
import com.db4o.query.*;
import com.db4o.test.legacy.soda.*;
public class STDb4oClientServer implements STEngine {
private static final int PORT = 4044;
private static final String HOST = "localhost";
private static final String FILE = "sodacs.db4o";
private static final String USER = "S.O.D.A.";
private static final String PASS = "rocks";
private static final boolean IN_PROCESS_SERVER = true;
private com.db4o.ObjectServer server;
private com.db4o.ObjectContainer con;
/**
* starts a db4o server.
* <br>To test with a remote server:<br>
* - set IN_PROCESS_SERVER to false
* - start STDb4oClientServer on the server
* - run SodaTest on the client
* - STDb4oClientServer needs to be uncommented in SodaTest#ENGINES
* The server can be stopped with CTRL + C.
*/
public static void main(String[] args) {
new File(FILE).delete();
ObjectServer server = Db4oClientServer.openServer(FILE, PORT);
server.grantAccess(USER, PASS);
server.ext().configure().messageLevel(-1);
}
public void reset() {
new File(FILE).delete();
}
public Query query() {
return con.query();
}
public void open() {
Db4o.configure().messageLevel(-1);
if (IN_PROCESS_SERVER) {
server = Db4oClientServer.openServer(FILE, PORT);
server.grantAccess(USER, PASS);
// wait for the server to be online
Runtime4.sleep(3000);
}
try {
con = Db4oClientServer.openClient(HOST, PORT, USER, PASS);
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
con.close();
if (IN_PROCESS_SERVER) {
server.close();
}
}
public void store(Object obj) {
con.store(obj);
}
public void commit(){
con.commit();
}
public void delete(Object obj){
con.delete(obj);
}
}
|
gpl-3.0
|
BruceWangNo1/jnu_database
|
public/user/services/authentication.client.service.js
|
111
|
userclient.factory('Authentication', [function(){
this.user=window.user;
return {
user: this.user
};
}]);
|
gpl-3.0
|
Fedict/eid-pki-ra
|
eid-pki-ra-integration/src/test/java/be/fedict/eid/integration/admin/CertificateAuthorityCertificateChainsSeleniumTest.java
|
4954
|
/**
* eID PKI RA Project.
* Copyright (C) 2010 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.eid.integration.admin;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import java.io.File;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import be.fedict.eid.integration.BaseSeleniumTestCase;
/**
* @author Bram Baeyens
*/
public class CertificateAuthorityCertificateChainsSeleniumTest extends BaseSeleniumTestCase {
private static final String CLIENTCA_SUBJECT = "C=BE,CN=Citizen CA,SERIALNUMBER=201007";
private static final String SERIAL_CACERT1 = "117029288888937864350596520176844645968";
private static final String SERIAL_CACERT2 = "3098404661496965511";
private static final String SERIAL_CLIENTCA = "51037179132502879506713585292514906207";
@BeforeClass
public void login() {
super.autoLogin();
}
private void goToChainsPage() {
clickAndWait("header-form:certificateauthorities");
clickAndWait("certificateAuthorityListForm:certificateAuthorityTable:0:chains");
}
@Test
public void uploadCertificate() {
goToChainsPage();
assertTextPresent("No certificates");
uploadCertificate("rootca1.crt");
assertTextNotPresent("No certificates");
assertTextPresent(SERIAL_CACERT1);
}
@Test(dependsOnMethods = "uploadCertificate")
public void uploadCertificateAgain() {
assertTextPresent(SERIAL_CACERT1);
// Upload the same certificate again
goToChainsPage();
uploadCertificate("rootca1.crt");
assertTextPresent("already present");
}
@Test(dependsOnMethods = "uploadCertificate")
public void uploadCertificateWithChild() {
goToChainsPage();
// Try without parent
uploadCertificate("childca.crt");
assertTextPresent("issuer of the certificate could not be found");
assertTextNotPresent(SERIAL_CLIENTCA);
// Try with parent account
uploadCertificate("rootca2.crt");
assertTextPresent(SERIAL_CACERT2);
uploadCertificate("childca.crt");
assertTextPresent(SERIAL_CLIENTCA);
}
@Test(dependsOnMethods = "uploadCertificateAgain")
public void deleteCertificate() {
assertTextPresent(SERIAL_CACERT1);
// Click the delete button
clickAndWait("certificateListForm:certificateTable:0:delete");
assertTextNotPresent(SERIAL_CACERT1);
}
@Test(dependsOnMethods =
{ "uploadCertificateWithChild", "deleteCertificate" })
public void assignCertificates() {
goToChainsPage();
assertTextPresent(SERIAL_CLIENTCA);
getSelenium().select("certificateChainForm:clientCertificateChainDecoration:j_id46",
"label=" + CLIENTCA_SUBJECT);
getSelenium().select("certificateChainForm:serverCertificateChainDecoration:j_id59",
"label=" + CLIENTCA_SUBJECT);
getSelenium().select("certificateChainForm:codeSigningCertificateChainDecoration:j_id72",
"label=" + CLIENTCA_SUBJECT);
clickAndWait("certificateChainForm:submitButtonBox:update");
goToChainsPage();
assertEquals("1", getValue("certificateChainForm:clientCertificateChainDecoration:j_id46"));
assertEquals("1", getValue("certificateChainForm:serverCertificateChainDecoration:j_id59"));
assertEquals("1", getValue("certificateChainForm:codeSigningCertificateChainDecoration:j_id72"));
}
@Test(dependsOnMethods="assignCertificates")
public void deleteAssignedCertificate() {
goToChainsPage();
assertTextPresent(SERIAL_CACERT2);
// Click the delete button
clickAndWait("certificateListForm:certificateTable:0:delete");
assertTextPresent("No certificates");
assertFalse ("1".equals(getValue("certificateChainForm:clientCertificateChainDecoration:j_id46")));
assertFalse ("1".equals(getValue("certificateChainForm:serverCertificateChainDecoration:j_id59")));
assertFalse ("1".equals(getValue("certificateChainForm:codeSigningCertificateChainDecoration:j_id72")));
}
private String getCertificateDirectory() {
return new File(".").getAbsolutePath() + "/src/test/resources/crt";
}
private void uploadCertificate(String certificateFile) {
type("certificateUploadForm:certificateUploadDecoration:certificateUpload", getCertificateDirectory() + "/"
+ certificateFile);
click("certificateUploadForm:certificateUploadDecoration:upload");
waitForPageToLoad();
}
}
|
gpl-3.0
|
justdoonemore/get.stuff.done
|
get.stuff.done.model/src/main/java/com/jdom/get/stuff/done/model/AddTaskModel.java
|
1015
|
/**
* Copyright (C) 2012 Just Do One More
*
* 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.jdom.get.stuff.done.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
public interface AddTaskModel extends BaseTaskModel {
void addTask(String taskName, String description, String taskList,
List<String> dependencies, Set<String> tags, Date due);
}
|
gpl-3.0
|
chengpenghui/UGame
|
src/impl/ProduceImproveCenter.cpp
|
1961
|
#include "stdafx.h"
#include "xgame.h"
#include "ProduceImproveCenter.h"
ProduceImproveCenter::ProduceImproveCenter(const CString& name , const CString& des, int index , int level)
:Building(name , des , index , level)
{
}
ProduceImproveCenter::~ProduceImproveCenter()
{
}
void ProduceImproveCenter::Load()
{
level_ = data_->GetBoatyardLevel();
self_produce_Percent_ = 0.0;
}
void ProduceImproveCenter::Save()
{
data_->SetBoatyardLevel(level_);
}
////consume
//consume resource needed
double ProduceImproveCenter::GetUpgradeMinal()
{
return get_other_factory_upgrade_resource(FACTORY_DATA[FACTORY_BUILDING_BOATYARD][FACTORY_TBL_N_METAL] , level_);
}
double ProduceImproveCenter::GetUpgradeCrystal()
{
return get_other_factory_upgrade_resource(FACTORY_DATA[FACTORY_BUILDING_BOATYARD][FACTORY_TBL_N_CRYSTAL] , level_);
}
double ProduceImproveCenter::GetUpgradeDiplogen()
{
return get_other_factory_upgrade_resource(FACTORY_DATA[FACTORY_BUILDING_BOATYARD][FACTORY_TBL_N_DIPLOGEN] , level_);
}
//total upgrade resource
double ProduceImproveCenter::GetTotalUpgradeMinal()
{
return 0L;
}
double ProduceImproveCenter::GetTotalUpgradeCrystal()
{
return 0L;
}
double ProduceImproveCenter::GetTotalUpgradeDiplogen()
{
return 0L;
}
//consume Power
unsigned long ProduceImproveCenter::GetConsumePower()
{
return 0L;
}
////produce
double ProduceImproveCenter::ProduceMinal()
{
return 0.0;
}
double ProduceImproveCenter::ProduceCrystal()
{
return 0.0;
}
double ProduceImproveCenter::ProduceDiplogen()
{
return 0.0;
}
unsigned long ProduceImproveCenter::ProducePower()
{
return 0L;
}
double ProduceImproveCenter::GetUpgradeTime()
{
upgrade_time_ = get_factory_upgrade_seconds(data_->GetRobertFactoryLevel() , data_->GetNaniteLevel() , GetUpgradeMinal() , GetUpgradeCrystal() , 1.0);
return upgrade_time_;
}
bool ProduceImproveCenter::CanLevelUp()
{
//robot factory >= 2
return data_->GetRobertFactoryLevel() >= 2;
}
|
gpl-3.0
|
sicarul/isshub
|
generic_threads.py
|
317
|
from PyQt4 import QtCore
class GenericThread(QtCore.QThread):
def __init__(self, function, *args, **kwargs):
QtCore.QThread.__init__(self)
self.function = function
self.args = args
self.kwargs = kwargs
def __del__(self):
self.wait()
def run(self):
self.function(*self.args,**self.kwargs)
return
|
gpl-3.0
|
meunierd/python-html-purifier
|
purifier/test.py
|
1134
|
# -*- coding: utf-8 -*-
"""
HTMLPurifier testing
This is not doc- or unit tests.
"""
import time
from purifier import HTMLPurifier
import bleach
test_data_files = [
'../test-data/google.ru.html',
'../test-data/megatyumen.ru.catalogue.html',
'../test-data/megatyumen.ru.html',
'../test-data/simple.html',
'../test-data/quoted_test.html',
'../test-data/custom-1.html',
]
HTMLPurifier_test_whitelist = {
'*': ['*'],
}
bleach_test_whitelist = {
'tags': ['p', 'div', 'b', 'i'],
'attrs': ['attr-2']
}
def read_file(name):
return open(name).read()
def HTMLPurifier_test(index=3, whitelist=HTMLPurifier_test_whitelist):
purifier = HTMLPurifier(whitelist)
return purifier.feed(read_file(test_data_files[index]))
def bleach_test(index=3):
return bleach.clean(
read_file(test_data_files[index]),
tags = bleach_test_whitelist['tags'],
attributes = bleach_test_whitelist['attrs'],
strip = False
)
if __name__ == '__main__':
start_time = time.clock()
index = 5
print(HTMLPurifier_test(index))
print(time.clock() - start_time, 's')
|
gpl-3.0
|
taylorsuccessor/baghli
|
catalog/controller/checkout/shipping_address.php
|
8428
|
<?php
class ControllerCheckoutShippingAddress extends Controller {
public function index() {
$this->load->language('checkout/checkout');
$data['text_address_existing'] = $this->language->get('text_address_existing');
$data['text_address_new'] = $this->language->get('text_address_new');
$data['text_select'] = $this->language->get('text_select');
$data['text_none'] = $this->language->get('text_none');
$data['text_loading'] = $this->language->get('text_loading');
$data['entry_firstname'] = $this->language->get('entry_firstname');
$data['entry_lastname'] = $this->language->get('entry_lastname');
$data['entry_company'] = $this->language->get('entry_company');
$data['entry_address_1'] = $this->language->get('entry_address_1');
$data['entry_address_2'] = $this->language->get('entry_address_2');
$data['entry_postcode'] = $this->language->get('entry_postcode');
$data['entry_city'] = $this->language->get('entry_city');
$data['entry_country'] = $this->language->get('entry_country');
$data['entry_zone'] = $this->language->get('entry_zone');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_upload'] = $this->language->get('button_upload');
if (isset($this->session->data['shipping_address']['address_id'])) {
$data['address_id'] = $this->session->data['shipping_address']['address_id'];
} else {
$data['address_id'] = $this->customer->getAddressId();
}
$this->load->model('account/address');
$data['addresses'] = $this->model_account_address->getAddresses();
if (isset($this->session->data['shipping_address']['postcode'])) {
$data['postcode'] = $this->session->data['shipping_address']['postcode'];
} else {
$data['postcode'] = '';
}
if (isset($this->session->data['shipping_address']['country_id'])) {
$data['country_id'] = $this->session->data['shipping_address']['country_id'];
} else {
$data['country_id'] = $this->config->get('config_country_id');
}
if (isset($this->session->data['shipping_address']['zone_id'])) {
$data['zone_id'] = $this->session->data['shipping_address']['zone_id'];
} else {
$data['zone_id'] = '';
}
$this->load->model('localisation/country');
$data['countries'] = $this->model_localisation_country->getCountries();
// Custom Fields
$this->load->model('account/custom_field');
$data['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));
if (isset($this->session->data['shipping_address']['custom_field'])) {
$data['shipping_address_custom_field'] = $this->session->data['shipping_address']['custom_field'];
} else {
$data['shipping_address_custom_field'] = array();
}
$this->response->setOutput($this->load->view('checkout/shipping_address', $data));
}
public function save() {
$this->load->language('checkout/checkout');
$json = array();
// Validate if customer is logged in.
if (!$this->customer->isLogged()) {
$json['redirect'] = $this->url->link('checkout/checkout', '', true);
}
// Validate if shipping is required. If not the customer should not have reached this page.
if (!$this->cart->hasShipping()) {
$json['redirect'] = $this->url->link('checkout/checkout', '', true);
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$json['redirect'] = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirements.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$json['redirect'] = $this->url->link('checkout/cart');
break;
}
}
if (!$json) {
if (isset($this->request->post['shipping_address']) && $this->request->post['shipping_address'] == 'existing') {
$this->load->model('account/address');
if (empty($this->request->post['address_id'])) {
$json['error']['warning'] = $this->language->get('error_address');
} elseif (!in_array($this->request->post['address_id'], array_keys($this->model_account_address->getAddresses()))) {
$json['error']['warning'] = $this->language->get('error_address');
}
if (!$json) {
// Default Shipping Address
$this->load->model('account/address');
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->request->post['address_id']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
}
} else {
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$json['error']['firstname'] = $this->language->get('error_firstname');
}
if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
$json['error']['lastname'] = $this->language->get('error_lastname');
}
//if ((utf8_strlen(trim($this->request->post['address_1'])) < 3) || (utf8_strlen(trim($this->request->post['address_1'])) > 128)) {
//$json['error']['address_1'] = $this->language->get('error_address_1');
// }
// if ((utf8_strlen(trim($this->request->post['city'])) < 2) || (utf8_strlen(trim($this->request->post['city'])) > 128)) {
// $json['error']['city'] = $this->language->get('error_city');
// }
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($this->request->post['postcode'])) < 2 || utf8_strlen(trim($this->request->post['postcode'])) > 10)) {
$json['error']['postcode'] = $this->language->get('error_postcode');
}
if ($this->request->post['country_id'] == '') {
$json['error']['country'] = $this->language->get('error_country');
}
//if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '' || !is_numeric($this->request->post['zone_id'])) {
//$json['error']['zone'] = $this->language->get('error_zone');
// }
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));
foreach ($custom_fields as $custom_field) {
if (($custom_field['location'] == 'address') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
} elseif (($custom_field['location'] == 'address') && ($custom_field['type'] == 'text') && !empty($custom_field['validation']) && !filter_var($this->request->post['custom_field'][$custom_field['custom_field_id']], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $custom_field['validation'])))) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if (!$json) {
// Default Shipping Address
$this->load->model('account/address');
$address_id = $this->model_account_address->addAddress($this->request->post);
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($address_id);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
if ($this->config->get('config_customer_activity')) {
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $this->customer->getId(),
'name' => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
);
$this->model_account_activity->addActivity('address_add', $activity_data);
}
}
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
|
gpl-3.0
|
zsh2938/FHC-Core
|
include/js/jquery.tablesorter.js
|
24689
|
/*
*
* TableSorter 2.0 - Client-side table sorting with ease!
* Version 2.0.3
* @requires jQuery v1.2.3
*
* Copyright (c) 2007 Christian Bach
* Examples and docs at: http://tablesorter.com
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
*
* @description Create a sortable table with multi-column sorting capabilitys
*
* @example $('table').tablesorter();
* @desc Create a simple tablesorter interface.
*
* @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
* @desc Create a tablesorter interface and sort on the first and secound column in ascending order.
*
* @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
* @desc Create a tablesorter interface and disableing the first and secound column headers.
*
* @example $('table').tablesorter({ 0: {sorter:"integer"}, 1: {sorter:"currency"} });
* @desc Create a tablesorter interface and set a column parser for the first and secound column.
*
*
* @param Object settings An object literal containing key/value pairs to provide optional settings.
*
* @option String cssHeader (optional) A string of the class name to be appended to sortable tr elements in the thead of the table.
* Default value: "header"
*
* @option String cssAsc (optional) A string of the class name to be appended to sortable tr elements in the thead on a ascending sort.
* Default value: "headerSortUp"
*
* @option String cssDesc (optional) A string of the class name to be appended to sortable tr elements in the thead on a descending sort.
* Default value: "headerSortDown"
*
* @option String sortInitialOrder (optional) A string of the inital sorting order can be asc or desc.
* Default value: "asc"
*
* @option String sortMultisortKey (optional) A string of the multi-column sort key.
* Default value: "shiftKey"
*
* @option String textExtraction (optional) A string of the text-extraction method to use.
* For complex html structures inside td cell set this option to "complex",
* on large tables the complex option can be slow.
* Default value: "simple"
*
* @option Object headers (optional) An array containing the forces sorting rules.
* This option let's you specify a default sorting rule.
* Default value: null
*
* @option Array sortList (optional) An array containing the forces sorting rules.
* This option let's you specify a default sorting rule.
* Default value: null
*
* @option Array sortForce (optional) An array containing forced sorting rules.
* This option let's you specify a default sorting rule, which is prepended to user-selected rules.
* Default value: null
*
* @option Array sortAppend (optional) An array containing forced sorting rules.
* This option let's you specify a default sorting rule, which is appended to user-selected rules.
* Default value: null
*
* @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter should apply fixed widths to the table columns.
* This is usefull when using the pager companion plugin.
* This options requires the dimension jquery plugin.
* Default value: false
*
* @option Boolean cancelSelection (optional) Boolean flag indicating if tablesorter should cancel selection of the table headers text.
* Default value: true
*
* @option Boolean debug (optional) Boolean flag indicating if tablesorter should display debuging information usefull for development.
*
* @type jQuery
*
* @name tablesorter
*
* @cat Plugins/Tablesorter
*
* @author Christian Bach/christian.bach@polyester.se
*/
(function($) {
$.extend({
tablesorter: new function() {
var parsers = [], widgets = [];
this.defaults = {
cssHeader: "header",
cssAsc: "headerSortUp",
cssDesc: "headerSortDown",
sortInitialOrder: "asc",
sortMultiSortKey: "shiftKey",
sortForce: null,
sortAppend: null,
textExtraction: "simple",
parsers: {},
widgets: [],
widgetZebra: {css: ["even","odd"]},
headers: {},
widthFixed: false,
cancelSelection: true,
sortList: [],
headerList: [],
dateFormat: "us",
decimal: '.',
debug: false
};
/* debuging utils */
function benchmark(s,d) {
log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
}
this.benchmark = benchmark;
function log(s) {
if (typeof console != "undefined" && typeof console.debug != "undefined") {
console.log(s);
} else {
alert(s);
}
}
/* parsers utils */
function buildParserCache(table,$headers) {
if(table.config.debug) { var parsersDebug = ""; }
var rows = table.tBodies[0].rows;
if(table.tBodies[0].rows[0]) {
var list = [], cells = rows[0].cells, l = cells.length;
for (var i=0;i < l; i++) {
var p = false;
if($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter) ) {
p = getParserById($($headers[i]).metadata().sorter);
} else if((table.config.headers[i] && table.config.headers[i].sorter)) {
p = getParserById(table.config.headers[i].sorter);
}
if(!p) {
p = detectParserForColumn(table,cells[i]);
}
if(table.config.debug) { parsersDebug += "column:" + i + " parser:" +p.id + "\n"; }
list.push(p);
}
}
if(table.config.debug) { log(parsersDebug); }
return list;
};
function detectParserForColumn(table,node) {
var l = parsers.length;
for(var i=1; i < l; i++) {
if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)) {
return parsers[i];
}
}
// 0 is always the generic parser (text)
return parsers[0];
}
function getParserById(name) {
var l = parsers.length;
for(var i=0; i < l; i++) {
if(parsers[i].id.toLowerCase() == name.toLowerCase()) {
return parsers[i];
}
}
return false;
}
/* utils */
function buildCache(table) {
if(table.config.debug) { var cacheTime = new Date(); }
var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
parsers = table.config.parsers,
cache = {row: [], normalized: []};
for (var i=0;i < totalRows; ++i) {
/** Add the table data to main data array */
var c = table.tBodies[0].rows[i], cols = [];
cache.row.push($(c));
for(var j=0; j < totalCells; ++j) {
cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));
}
cols.push(i); // add position for rowCache
cache.normalized.push(cols);
cols = null;
};
if(table.config.debug) { benchmark("Building cache for " + totalRows + " rows:", cacheTime); }
return cache;
};
function getElementText(config,node) {
if(!node) return "";
var t = "";
if(config.textExtraction == "simple") {
if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
t = node.childNodes[0].innerHTML;
} else {
t = node.innerHTML;
}
} else {
if(typeof(config.textExtraction) == "function") {
t = config.textExtraction(node);
} else {
t = $(node).text();
}
}
t=t.replace('ö','o');
t=t.replace('Ö','O');
t=t.replace('ü','u');
t=t.replace('Ü','U');
t=t.replace('ä','a');
t=t.replace('Ä','A');
return t;
}
function appendToTable(table,cache) {
if(table.config.debug) {var appendTime = new Date()}
var c = cache,
r = c.row,
n= c.normalized,
totalRows = n.length,
checkCell = (n[0].length-1),
tableBody = $(table.tBodies[0]),
rows = [];
for (var i=0;i < totalRows; i++) {
rows.push(r[n[i][checkCell]]);
if(!table.config.appender) {
var o = r[n[i][checkCell]];
var l = o.length;
for(var j=0; j < l; j++) {
tableBody[0].appendChild(o[j]);
}
//tableBody.append(r[n[i][checkCell]]);
}
}
if(table.config.appender) {
table.config.appender(table,rows);
}
rows = null;
if(table.config.debug) { benchmark("Rebuilt table:", appendTime); }
//apply table widgets
applyWidget(table);
// trigger sortend
setTimeout(function() {
$(table).trigger("sortEnd");
},0);
};
function buildHeaders(table) {
if(table.config.debug) { var time = new Date(); }
var meta = ($.metadata) ? true : false, tableHeadersRows = [];
for(var i = 0; i < table.tHead.rows.length; i++) { tableHeadersRows[i]=0; };
$tableHeaders = $("thead th",table);
$tableHeaders.each(function(index) {
this.count = 0;
this.column = index;
this.order = formatSortingOrder(table.config.sortInitialOrder);
if(checkHeaderMetadata(this) || checkHeaderOptions(table,index)) this.sortDisabled = true;
if(!this.sortDisabled) {
$(this).addClass(table.config.cssHeader);
}
// add cell to headerList
table.config.headerList[index]= this;
});
if(table.config.debug) { benchmark("Built headers:", time); log($tableHeaders); }
return $tableHeaders;
};
function checkCellColSpan(table, rows, row) {
var arr = [], r = table.tHead.rows, c = r[row].cells;
for(var i=0; i < c.length; i++) {
var cell = c[i];
if ( cell.colSpan > 1) {
arr = arr.concat(checkCellColSpan(table, headerArr,row++));
} else {
if(table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row+1])) {
arr.push(cell);
}
//headerArr[row] = (i+row);
}
}
return arr;
};
function checkHeaderMetadata(cell) {
if(($.metadata) && ($(cell).metadata().sorter === false)) { return true; };
return false;
}
function checkHeaderOptions(table,i) {
if((table.config.headers[i]) && (table.config.headers[i].sorter === false)) { return true; };
return false;
}
function applyWidget(table) {
var c = table.config.widgets;
var l = c.length;
for(var i=0; i < l; i++) {
getWidgetById(c[i]).format(table);
}
}
function getWidgetById(name) {
var l = widgets.length;
for(var i=0; i < l; i++) {
if(widgets[i].id.toLowerCase() == name.toLowerCase() ) {
return widgets[i];
}
}
};
function formatSortingOrder(v) {
if(typeof(v) != "Number") {
i = (v.toLowerCase() == "desc") ? 1 : 0;
} else {
i = (v == (0 || 1)) ? v : 0;
}
return i;
}
function isValueInArray(v, a) {
var l = a.length;
for(var i=0; i < l; i++) {
if(a[i][0] == v) {
return true;
}
}
return false;
}
function setHeadersCss(table,$headers, list, css) {
// remove all header information
$headers.removeClass(css[0]).removeClass(css[1]);
var h = [];
$headers.each(function(offset) {
if(!this.sortDisabled) {
h[this.column] = $(this);
}
});
var l = list.length;
for(var i=0; i < l; i++) {
h[list[i][0]].addClass(css[list[i][1]]);
}
}
function fixColumnWidth(table,$headers) {
var c = table.config;
if(c.widthFixed) {
var colgroup = $('<colgroup>');
$("tr:first td",table.tBodies[0]).each(function() {
colgroup.append($('<col>').css('width',$(this).width()));
});
$(table).prepend(colgroup);
};
}
function updateHeaderSortCount(table,sortList) {
var c = table.config, l = sortList.length;
for(var i=0; i < l; i++) {
var s = sortList[i], o = c.headerList[s[0]];
o.count = s[1];
o.count++;
}
}
/* sorting methods */
function multisort(table,sortList,cache) {
if(table.config.debug) { var sortTime = new Date(); }
var dynamicExp = "var sortWrapper = function(a,b) {", l = sortList.length;
for(var i=0; i < l; i++) {
var c = sortList[i][0];
var order = sortList[i][1];
var s = (getCachedSortType(table.config.parsers,c) == "text") ? ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ? "sortNumeric" : "sortNumericDesc");
var e = "e" + i;
dynamicExp += "var " + e + " = " + s + "(a[" + c + "],b[" + c + "]); ";
dynamicExp += "if(" + e + ") { return " + e + "; } ";
dynamicExp += "else { ";
}
// if value is the same keep orignal order
var orgOrderCol = cache.normalized[0].length - 1;
dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";
for(var i=0; i < l; i++) {
dynamicExp += "}; ";
}
dynamicExp += "return 0; ";
dynamicExp += "}; ";
eval(dynamicExp);
cache.normalized.sort(sortWrapper);
if(table.config.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order+ " time:", sortTime); }
return cache;
};
function sortText(a,b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
};
function sortTextDesc(a,b) {
return ((b < a) ? -1 : ((b > a) ? 1 : 0));
};
function sortNumeric(a,b) {
return a-b;
};
function sortNumericDesc(a,b) {
return b-a;
};
function getCachedSortType(parsers,i) {
return parsers[i].type;
};
/* public methods */
this.construct = function(settings) {
return this.each(function() {
if(!this.tHead || !this.tBodies) return;
var $this, $document,$headers, cache, config, shiftDown = 0, sortOrder;
this.config = {};
config = $.extend(this.config, $.tablesorter.defaults, settings);
// store common expression for speed
$this = $(this);
// build headers
$headers = buildHeaders(this);
// try to auto detect column type, and store in tables config
this.config.parsers = buildParserCache(this,$headers);
// build the cache for the tbody cells
cache = buildCache(this);
// get the css class names, could be done else where.
var sortCSS = [config.cssDesc,config.cssAsc];
// fixate columns if the users supplies the fixedWidth option
fixColumnWidth(this);
// apply event handling to headers
// this is to big, perhaps break it out?
$headers.click(function(e) {
$this.trigger("sortStart");
var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
if(!this.sortDisabled && totalRows > 0) {
// store exp, for speed
var $cell = $(this);
// get current column index
var i = this.column;
// get current column sort order
this.order = this.count++ % 2;
// user only whants to sort on one column
if(!e[config.sortMultiSortKey]) {
// flush the sort list
config.sortList = [];
if(config.sortForce != null) {
var a = config.sortForce;
for(var j=0; j < a.length; j++) {
if(a[j][0] != i) {
config.sortList.push(a[j]);
}
}
}
// add column to sort list
config.sortList.push([i,this.order]);
// multi column sorting
} else {
// the user has clicked on an all ready sortet column.
if(isValueInArray(i,config.sortList)) {
// revers the sorting direction for all tables.
for(var j=0; j < config.sortList.length; j++) {
var s = config.sortList[j], o = config.headerList[s[0]];
if(s[0] == i) {
o.count = s[1];
o.count++;
s[1] = o.count % 2;
}
}
} else {
// add column to sort list array
config.sortList.push([i,this.order]);
}
};
setTimeout(function() {
//set css for headers
setHeadersCss($this[0],$headers,config.sortList,sortCSS);
appendToTable($this[0],multisort($this[0],config.sortList,cache));
},1);
// stop normal event by returning false
return false;
}
// cancel selection
}).mousedown(function() {
if(config.cancelSelection) {
this.onselectstart = function() {return false};
return false;
}
});
// apply easy methods that trigger binded events
$this.bind("update",function() {
// rebuild parsers.
this.config.parsers = buildParserCache(this,$headers);
// rebuild the cache map
cache = buildCache(this);
}).bind("sorton",function(e,list) {
$(this).trigger("sortStart");
config.sortList = list;
// update and store the sortlist
var sortList = config.sortList;
// update header count index
updateHeaderSortCount(this,sortList);
//set css for headers
setHeadersCss(this,$headers,sortList,sortCSS);
// sort the table and append it to the dom
appendToTable(this,multisort(this,sortList,cache));
}).bind("appendCache",function() {
appendToTable(this,cache);
}).bind("applyWidgetId",function(e,id) {
getWidgetById(id).format(this);
}).bind("applyWidgets",function() {
// apply widgets
applyWidget(this);
});
if($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
config.sortList = $(this).metadata().sortlist;
}
// if user has supplied a sort list to constructor.
if(config.sortList.length > 0) {
$this.trigger("sorton",[config.sortList]);
}
// apply widgets
applyWidget(this);
});
};
this.addParser = function(parser) {
var l = parsers.length, a = true;
for(var i=0; i < l; i++) {
if(parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
a = false;
}
}
if(a) { parsers.push(parser); };
};
this.addWidget = function(widget) {
widgets.push(widget);
};
this.formatFloat = function(s) {
var i = parseFloat(s);
return (isNaN(i)) ? 0 : i;
};
this.formatInt = function(s) {
var i = parseInt(s);
return (isNaN(i)) ? 0 : i;
};
this.isDigit = function(s,config) {
var DECIMAL = '\\' + config.decimal;
var exp = '/(^[+]?0(' + DECIMAL +'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)' + DECIMAL +'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*' + DECIMAL +'0+$)/';
return RegExp(exp).test($.trim(s));
};
this.isInt = function(s,config) {
if(isNaN(parseInt(s)))
return false;
else
return true;
};
this.clearTableBody = function(table) {
if($.browser.msie) {
function empty() {
while ( this.firstChild ) this.removeChild( this.firstChild );
}
empty.apply(table.tBodies[0]);
} else {
table.tBodies[0].innerHTML = "";
}
};
}
});
// extend plugin scope
$.fn.extend({
tablesorter: $.tablesorter.construct
});
var ts = $.tablesorter;
// add default parsers
ts.addParser({
id: "text",
is: function(s) {
return true;
},
format: function(s) {
return $.trim(s.toLowerCase());
},
type: "text"
});
ts.addParser({
id: "digit",
is: function(s,table) {
var c = table.config;
return $.tablesorter.isDigit(s,c);
},
format: function(s) {
return $.tablesorter.formatFloat(s);
},
type: "numeric"
});
ts.addParser({
id: "digitmittausenderpunkt",
is: function(s) {
return /^[0-9.,]/.test(s);
},
format: function(s) {
return $.tablesorter.formatFloat(s.replace('.',""));
},
type: "numeric"
});
ts.addParser({
id: "DatummitUhrzeit",
is: function(s) {
return s.match(new RegExp(/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{4} (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]))$/));
},
format: function(s) {
return $.tablesorter.formatFloat(new Date(s).getTime());
},
type: "numeric"
});
ts.addParser({
id: "integer",
is: function(s,table) {
var c = table.config;
return $.tablesorter.isInt(s,c);
},
format: function(s) {
return $.tablesorter.formatInt(s);
},
type: "numeric"
});
ts.addParser({
id: "currency",
is: function(s) {
return /^[£$€?.]/.test(s);
},
format: function(s) {
return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));
},
type: "numeric"
});
ts.addParser({
id: "ipAddress",
is: function(s) {
return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
},
format: function(s) {
var a = s.split("."), r = "", l = a.length;
for(var i = 0; i < l; i++) {
var item = a[i];
if(item.length == 2) {
r += "0" + item;
} else {
r += item;
}
}
return $.tablesorter.formatFloat(r);
},
type: "numeric"
});
ts.addParser({
id: "url",
is: function(s) {
return /^(https?|ftp|file):\/\/$/.test(s);
},
format: function(s) {
return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));
},
type: "text"
});
ts.addParser({
id: "isoDate",
is: function(s) {
return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
},
format: function(s) {
return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(new RegExp(/-/g),"/")).getTime() : "0");
},
type: "numeric"
});
ts.addParser({
id: "percent",
is: function(s) {
return /\%$/.test($.trim(s));
},
format: function(s) {
return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));
},
type: "numeric"
});
ts.addParser({
id: "usLongDate",
is: function(s) {
return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));
},
format: function(s) {
return $.tablesorter.formatFloat(new Date(s).getTime());
},
type: "numeric"
});
ts.addParser({
id: "shortDate",
is: function(s) {
return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
},
format: function(s,table) {
var c = table.config;
s = s.replace(/\-/g,"/");
if(c.dateFormat == "us") {
// reformat the string in ISO format
s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
} else if(c.dateFormat == "uk") {
//reformat the string in ISO format
s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
} else if(c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
}
return $.tablesorter.formatFloat(new Date(s).getTime());
},
type: "numeric"
});
ts.addParser({
id: "dedate",
is: function(s) {
return /\d{1,2}.\d{1,2}.\d{2,4}/.test(s);
},
format: function(s) {
s = s.replace(/(\d{1,2}).(\d{1,2}).(\d{2,4})/, "$2/$1/$3");
return $.tablesorter.formatFloat(new Date(s).getTime());
},
type: "numeric"
});
ts.addParser({
id: "time",
is: function(s) {
return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
},
format: function(s) {
return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
},
type: "numeric"
});
ts.addParser({
id: "metadata",
is: function(s) {
return false;
},
format: function(s,table,cell) {
var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
return $(cell).metadata()[p];
},
type: "numeric"
});
// add default widgets
ts.addWidget({
id: "zebra",
format: function(table) {
if(table.config.debug) { var time = new Date(); }
$("tr:visible",table.tBodies[0])
.filter(':even')
.removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0])
.end().filter(':odd')
.removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);
if(table.config.debug) { $.tablesorter.benchmark("Applying Zebra widget", time); }
}
});
})(jQuery);
|
gpl-3.0
|
Brok9n/mercury
|
src/util/time.cpp
|
1572
|
#include "time.hpp"
#include <ctime>
#include <sstream>
#include "environment.hpp"
#ifdef NIL_WINDOWS
#include <nil/windows.hpp>
#else
#include <sys/time.h>
#include <sys/times.h>
#endif
#include <iostream>
namespace nil
{
ulong time()
{
return static_cast<ulong>(std::time(0));
}
ullong milliseconds()
{
#ifdef NIL_WINDOWS
::SYSTEMTIME system_time;
::GetLocalTime(&system_time);
ullong output = time() * 1000ull + system_time.wMilliseconds;
#else
ullong output = time() * 1000ull;
::timeval time_value;
::gettimeofday(&time_value, 0);
//::tm * time_data = ::localtime(&time_value.tv_sec);
output += static_cast<ullong>(time_value.tv_usec / 1000);
#endif
return output;
}
std::string timestamp()
{
std::time_t current_time;
std::time(¤t_time);
std::tm * pointer = std::localtime(¤t_time);
std::stringstream output;
output.fill('0');
output << (pointer->tm_year + 1900) << ".";
output.width(2);
output << (pointer->tm_mon + 1) << ".";
output.width(2);
output << pointer->tm_mday << " ";
output.width(2);
output << pointer->tm_hour << ":";
output.width(2);
output << pointer->tm_min << ":";
output.width(2);
output << pointer->tm_sec;
return output.str();
}
ullong boot_time()
{
#ifdef NIL_WINDOWS
#if (_WIN32_WINNT >= 0x0600)
return static_cast<ullong>(::GetTickCount64());
#else
return static_cast<ullong>(::GetTickCount());
#endif
#else
tms tm;
return static_cast<ullong>(::times(&tm));
#endif
}
}
|
gpl-3.0
|
nt001-01/AFD
|
server.js
|
584
|
/*eslint no-console:0 */
'use strict';
require('core-js/fn/object/assign');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');
const open = require('open');
//Server
//End Server
new WebpackDevServer(webpack(config), config.devServer)
.listen(config.port, 'localhost', (err) => {
if (err) {
console.log(err);
}
console.log('Listening at localhost:' + config.port);
console.log('Opening your system browser...');
open('http://localhost:' + config.port + '/webpack-dev-server/');
});
|
gpl-3.0
|
hebra/meterbeat
|
src/main/java/io/github/hebra/elasticsearch/beat/meterbeat/MeasurementResult.java
|
1127
|
/**
* (C) 2016-2017 Hendrik Brandt <https://github.com/hebra/> This file is part of MeterBeat. MeterBeat 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. MeterBeat 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 MeterBeat. If not, see <http://www.gnu.org/licenses/>.
***/
package io.github.hebra.elasticsearch.beat.meterbeat;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(staticName = "of")
public class MeasurementResult
{
@Getter
private String timestamp;
@Getter @NonNull
private final String deviceName;
@Getter @NonNull
private final Double power;
@Getter @NonNull
private final Double temperature;
}
|
gpl-3.0
|
WaddellEngineering/HarMANi
|
app/js/contactController.js
|
16425
|
/**
* Created by Brett Eckert on 3/28/2016.
*/
/*global $, confirm, initParams, angular */
angular.module('waddellEng').controller(
'ContactController', ['commonService', 'objectStoreService', 'authenticationService',
function (commonService, objectStoreService, authenticationService) {
"use strict";
var cont = this, firstNewCont = true, firstNewComp = true, firstNewMun = true;
cont.newContact = function () {
try {
var newContact;
if (firstNewCont) {
newContact = {
'contactID': null,
'title': null,
'name': "New Contact",
'companyID': null,
'email': null,
'phone1': null,
'phone2': null,
'address': null,
'poAddress': null,
'cityID': null,
'provinceID': null,
'postal': null,
'fax': null,
'notes': null,
'active': "1"
};
cont.contactList.push(newContact);
cont.activeContactButton(null);
} else {
commonService.setResponseMsg(1, 'Already Added a contact!',
'You need to save your changes on the first contact you have ' +
'created before creating a new one.');
}
} catch (e) {
commonService.setResponseMsg(1, 'Contact Creation Failed!',
'Please try again.');
} finally {
firstNewCont = false;
window.scrollTo(0, document.body.scrollHeight);
}
};
cont.activeContactButton = function (contctID) {
var contactLookup = cont.contactList.map(function (contact) {
return contact.contactID;
}).indexOf(contctID);
cont.currContactActive = cont.contactList[contactLookup];
};
cont.saveContact = function () {
try {
var property, sc, isInsert = false, tempRegReplace;
sc = cont.currContactActive;
if (sc.contactID === null) {
sc.mode = 'insert';
isInsert = true;
} else {
sc.mode = 'update';
}
for (property in sc) {
if (sc.hasOwnProperty(property)) {
if (sc[property] === '' || sc[property] === undefined) {
sc[property] = null;
}
}
}
if (sc.phone1 !== null) {
tempRegReplace = sc.phone1;
tempRegReplace = tempRegReplace.replace(/\D/g, '');
sc.phone1 = tempRegReplace;
}
if (sc.phone2 !== null) {
tempRegReplace = sc.phone2;
tempRegReplace = tempRegReplace.replace(/\D/g, '');
sc.phone2 = tempRegReplace;
}
if (sc.fax !== null) {
tempRegReplace = sc.fax;
tempRegReplace = tempRegReplace.replace(/\D/g, '');
sc.fax = tempRegReplace;
}
if (sc.postal !== null) {
tempRegReplace = sc.postal;
tempRegReplace = tempRegReplace.replace(/\W/g, '');
sc.postal = tempRegReplace;
}
if (sc.companyID !== undefined) {
if (sc.companyID === "null") {
sc.companyID = null;
}
}
if (sc.title === "null") {
sc.title = null;
}
objectStoreService.setContact(sc).then(function (response) {
if (response.data === "Success!") {
objectStoreService.getContactsCompanies(false).then(function () {
var jsonData = angular.fromJson(
localStorage.getItem("objectContactsCompanies"));
cont.contactList = jsonData[0];
commonService.setResponseMsg(0, "Contact Saved!",
"Contact Save Successful");
if (isInsert) {
cont.currContactActive = null;
}
firstNewCont = true;
});
} else if (response.data === "Duplicate!") {
commonService.setResponseMsg(1, "Contact already exists!", "Pick a unique name.");
} else {
commonService.setResponseMsg(1, "Contact Not Saved!",
"Please try again");
}
}, function (response) {
commonService.setResponseMsg(1, "Contact Not Saved!",
"Please try again");
});
} catch (e) {
commonService.setResponseMsg(1, "Contact Not Saved!", "Please try again");
}
};
cont.newCompany = function () {
try {
var newCompany;
if (firstNewComp) {
newCompany = {
'company_id': null,
'company_name': 'New Company',
'company_address': null,
'company_po_address': null,
'company_city': null,
'company_province': null,
'company_postal_code': null,
'company_phone': null,
'company_fax': null,
'company_email': null,
'company_contractor': 0,
'company_sub_contractor': 0,
'company_truss': 0,
'company_active': '1',
'company_notes': null,
'company_invoice_to': null,
'company_po_required': null
};
cont.companyList.push(newCompany);
cont.activeCompanyButton(null);
} else {
commonService.setResponseMsg(1, 'Already Added a company!',
'You need to save your changes on the first company you have ' +
'created before creating a new one.');
}
} catch (e) {
commonService.setResponseMsg(1, 'Company Creation Failed!',
'Please try again.');
} finally {
firstNewComp = false;
window.scrollTo(0, document.body.scrollHeight);
}
};
cont.activeCompanyButton = function (compnyID) {
var companyLookup = cont.companyList.map(function (company) {
return company.company_id;
}).indexOf(compnyID);
cont.currCompanyActive = cont.companyList[companyLookup];
};
cont.saveCompany = function () {
try {
var property, sc = cont.currCompanyActive, isInsert = false, tempRegReplace;
if (sc.company_id === null) {
sc.mode = 'insert';
isInsert = true;
} else {
sc.mode = 'update';
}
if (sc.company_phone !== null) {
tempRegReplace = sc.company_phone;
tempRegReplace = tempRegReplace.replace(/\D/g, '');
sc.company_phone = tempRegReplace;
}
if (sc.company_fax !== null) {
tempRegReplace = sc.company_fax;
tempRegReplace = tempRegReplace.replace(/\D/g, '');
sc.company_fax = tempRegReplace;
}
if (sc.company_postal_code !== null) {
tempRegReplace = sc.company_postal_code;
tempRegReplace = tempRegReplace.replace(/\W/g, '');
sc.company_postal_code = tempRegReplace;
}
for (property in sc) {
if (sc.hasOwnProperty(property)) {
if (sc[property] === '' || sc[property] === undefined) {
sc[property] = null;
}
}
}
objectStoreService.setCompany(sc).then(function (response) {
if (response.data === "Success!") {
objectStoreService.getContactsCompanies(false).then(function () {
var jsonData = angular.fromJson(
localStorage.getItem("objectContactsCompanies"));
cont.companyList = jsonData[1];
commonService.setResponseMsg(0, "Company Saved!",
"Company Save Successful");
if (isInsert) {
cont.currCompanyActive = null;
}
firstNewComp = true;
});
} else if (response.data === "Duplicate!") {
commonService.setResponseMsg(1, "Company already exists!", "Pick a unique name.");
} else {
commonService.setResponseMsg(1, "Company Not Saved!",
"Please try again");
}
}, function (response) {
commonService.setResponseMsg(1, "Company Not Saved!",
"Please try again");
});
} catch (e) {
commonService.setResponseMsg(1, "Company Not Saved!", "Please try again");
}
};
cont.newMun = function () {
try {
var newMun;
if (firstNewMun) {
newMun = {
'municipalityID': null,
'municipalityName': 'New Municipality',
'municipalityContactID': null,
'municipalityStatus': null,
'municipalityGeo': null
};
cont.munList.push(newMun);
cont.activeMunButton(null);
} else {
commonService.setResponseMsg(1, 'Already Added a municipality!',
'You need to save your changes on the first municipality you have ' +
'created before creating a new one.');
}
} catch (e) {
commonService.setResponseMsg(1, 'Municipality Creation Failed!',
'Please try again.');
} finally {
firstNewMun = false;
window.scrollTo(0, document.body.scrollHeight);
}
};
cont.activeMunButton = function (munID) {
var munLookup = cont.munList.map(function (mun) {
return mun.municipalityID;
}).indexOf(munID);
cont.currMunActive = cont.munList[munLookup];
};
cont.saveMun = function () {
try {
var property, sm = cont.currMunActive, isInsert = false;
if (sm.municipalityID === null) {
sm.mode = 'insert';
isInsert = true;
} else {
sm.mode = 'update';
}
for (property in sm) {
if (sm.hasOwnProperty(property)) {
if (sm[property] === '' || sm[property] === undefined) {
sm[property] = null;
}
}
}
objectStoreService.setMunicipality(sm).then(function (response) {
if (response.data === "Success!") {
objectStoreService.getObjectStore(false).then(function () {
var jsonData = angular.fromJson(
localStorage.getItem("objectStore"));
cont.munList = jsonData[8];
commonService.setResponseMsg(0, "Municipality Saved!",
"Municipality Save Successful");
if (isInsert) {
cont.currMunActive = null;
}
firstNewMun = true;
});
} else if (response.data === "Duplicate!") {
commonService.setResponseMsg(1, "Municipality already exists!", "Pick a unique name.");
} else {
commonService.setResponseMsg(1, "Municipality Not Saved!",
"Please try again");
}
}, function (response) {
commonService.setResponseMsg(1, "Municipality Not Saved!",
"Please try again");
});
} catch (e) {
commonService.setResponseMsg(1, "Municipality Not Saved!", "Please try again");
}
};
//Stop user from accessing if not logged in
cont.run = function () {
if (commonService.getCurrEmp() !== null && commonService.getCurrEmp() !== undefined
&& commonService.getCurrEmp() !== '') {
cont.contactList = angular.fromJson(localStorage.getItem("objectContactsCompanies"));
cont.companyList = cont.contactList[1];
cont.contactList = cont.contactList[0];
cont.munList = angular.fromJson(localStorage.getItem("objectStore"));
cont.munStatuses = cont.munList[11];
cont.munList = cont.munList[8];
cont.currContactActive = null;
cont.currCompanyActive = null;
cont.currMunActive = null;
cont.searchTypes = [
{name: 'Contacts', url: 'pages/contacts/contact/contactSearch.html'},
{name: 'Companies', url: 'pages/contacts/company/companiesSearch.html'},
{
name: 'Municipalities',
url: 'pages/contacts/municipality/municipalitiesSearch.html'
}
];
cont.searchType = cont.searchTypes[0];
} else {
authenticationService.setLogout();
}
};
}]);
|
gpl-3.0
|
moddevices/mda-lv2
|
src/mdaTestTone.cpp
|
16960
|
/*
Copyright 2008-2011 David Robillard <http://drobilla.net>
Copyright 1999-2000 Paul Kellett (Maxim Digital Audio)
This 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mdaTestTone.h"
#include <math.h>
#include <stdlib.h>
AudioEffect *createEffectInstance(audioMasterCallback audioMaster)
{
return new mdaTestTone(audioMaster);
}
mdaTestTone::mdaTestTone(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, 1, 8)
{
fParam0 = 0.0f; //mode
fParam1 = 0.71f; //level dB
fParam2 = 0.50f; //pan dB
fParam3 = 0.57f; //freq1 B
fParam4 = 0.50f; //freq2 Hz
fParam5 = 0.00f; //thru dB
fParam6 = 0.30f; //sweep ms
fParam7 = 1.00f; //cal dBFS
setNumInputs(2);
setNumOutputs(2);
setUniqueID("mdaTestTone");
DECLARE_LVZ_DEPRECATED(canMono) ();
canProcessReplacing();
strcpy(programName, "Signal Generator");
updateTx = updateRx = 0;
sw = swx = 0.0f;
suspend();
setParameter(6, 0.f);
}
bool mdaTestTone::getProductString(char* text) { strcpy(text, "MDA TestTone"); return true; }
bool mdaTestTone::getVendorString(char* text) { strcpy(text, "mda"); return true; }
bool mdaTestTone::getEffectName(char* name) { strcpy(name, "TestTone"); return true; }
mdaTestTone::~mdaTestTone()
{
}
void mdaTestTone::suspend()
{
zz0 = zz1 = zz2 = zz3 = zz4 = zz5 = phi = 0.0f;
}
void mdaTestTone::setProgramName(char *name)
{
strcpy(programName, name);
}
void mdaTestTone::getProgramName(char *name)
{
strcpy(name, programName);
}
bool mdaTestTone::getProgramNameIndexed (int32_t category, int32_t index, char* name)
{
if (index == 0)
{
strcpy(name, programName);
return true;
}
return false;
}
#include <stdio.h>
static void int2strng(int32_t value, char *string) { sprintf(string, "%d", value); }
static void float2strng(float value, char *string) { sprintf(string, "%.2f", value); }
void mdaTestTone::setParameter(int32_t index, float value)
{
switch(index)
{
case 0: fParam0 = value; break;
case 1: fParam1 = value; break;
case 2: fParam2 = value; break;
case 3: fParam3 = value; break;
case 4: fParam4 = value; break;
case 6: fParam5 = value; break;
case 5: fParam6 = value; break;
case 7: fParam7 = value; break;
}
//just update display text...
mode = int(8.9 * fParam0);
float f, df=0.0f;
if(fParam4>0.6) df = 1.25f*fParam4 - 0.75f;
if(fParam4<0.4) df = 1.25f*fParam4 - 0.50f;
switch(mode)
{
case 0: //MIDI note
f = (float)floor(128.f*fParam3);
//int2strng((int32_t)f, disp1); //Semi
midi2string(f, disp1); //Semitones
int2strng((int32_t)(100.f*df), disp2); //Cents
break;
case 1: //no frequency display
case 2:
case 3:
case 4: strcpy(disp1, "--");
strcpy(disp2, "--"); break;
case 5: //sine
f = 13.f + (float)floor(30.f*fParam3);
iso2string(f, disp1); //iso band freq
f=(float)pow(10.0f, 0.1f*(f+df));
float2strng(f, disp2); //Hz
break;
case 6: //log sweep & step
case 7: sw = 13.f + (float)floor(30.f*fParam3);
swx = 13.f + (float)floor(30.f*fParam4);
iso2string(sw, disp1); //start freq
iso2string(swx, disp2); //end freq
break;
case 8: //lin sweep
sw = 200.f * (float)floor(100.f*fParam3);
swx = 200.f * (float)floor(100.f*fParam4);
int2strng((int32_t)sw, disp1); //start freq
int2strng((int32_t)swx, disp2); //end freq
break;
}
updateTx++;
}
void mdaTestTone::update()
{
updateRx = updateTx;
float f, df, twopi=6.2831853f;
//calcs here!
mode = int(8.9 * fParam0);
left = 0.05f * (float)int(60.f*fParam1);
left = (float)pow(10.0f, left - 3.f);
if(mode==2) left*=0.0000610f; //scale white for RAND_MAX = 32767
if(mode==3) left*=0.0000243f; //scale pink for RAND_MAX = 32767
if(fParam2<0.3f) right=0.f; else right=left;
if(fParam2>0.6f) left=0.f;
len = 1.f + 0.5f*(float)int(62*fParam6);
swt=(int32_t)(len*getSampleRate());
if(fParam7>0.8) //output level trim
{
if(fParam7>0.96) cal = 0.f;
else if(fParam7>0.92) cal = -0.01000001f;
else if(fParam7>0.88) cal = -0.02000001f;
else if(fParam7>0.84) cal = -0.1f;
else cal = -0.2f;
calx = (float)pow(10.0f, 0.05f*cal);
left*=calx; right*=calx;
calx = 0.f;
}
else //output level calibrate
{
cal = (float)int(25.f*fParam7 - 21.1f);
calx = cal;
}
df=0.f;
if(fParam4>0.6) df = 1.25f*fParam4 - 0.75f;
if(fParam4<0.4) df = 1.25f*fParam4 - 0.50f;
switch(mode)
{
case 0: //MIDI note
f = (float)floor(128.f*fParam3);
//int2strng((int32_t)f, disp1); //Semi
midi2string(f, disp1); //Semitones
int2strng((int32_t)(100.f*df), disp2); //Cents
dphi = 51.37006f*(float)pow(1.0594631f,f+df)/getSampleRate();
break;
case 1: //no frequency display
case 2:
case 3:
case 4: strcpy(disp1, "--");
strcpy(disp2, "--"); break;
case 5: //sine
f = 13.f + (float)floor(30.f*fParam3);
iso2string(f, disp1); //iso band freq
f=(float)pow(10.0f, 0.1f*(f+df));
float2strng(f, disp2); //Hz
dphi=twopi*f/getSampleRate();
break;
case 6: //log sweep & step
case 7: sw = 13.f + (float)floor(30.f*fParam3);
swx = 13.f + (float)floor(30.f*fParam4);
iso2string(sw, disp1); //start freq
iso2string(swx, disp2); //end freq
if(sw>swx) { swd=swx; swx=sw; sw=swd; } //only sweep up
if(mode==7) swx += 1.f;
swd = (swx-sw) / (len*getSampleRate());
swt= 2 * (int32_t)getSampleRate();
break;
case 8: //lin sweep
sw = 200.f * (float)floor(100.f*fParam3);
swx = 200.f * (float)floor(100.f*fParam4);
int2strng((int32_t)sw, disp1); //start freq
int2strng((int32_t)swx, disp2); //end freq
if(sw>swx) { swd=swx; swx=sw; sw=swd; } //only sweep up
sw = twopi*sw/getSampleRate();
swx = twopi*swx/getSampleRate();
swd = (swx-sw) / (len*getSampleRate());
swt= 2 * (int32_t)getSampleRate();
break;
}
thru = (float)pow(10.0f, (0.05f * (float)int(40.f*fParam5)) - 2.f);
if(fParam5==0.0f) thru=0.0f;
fscale = twopi/getSampleRate();
}
void mdaTestTone::midi2string(float n, char *text)
{
char t[8];
int nn, o, s, p=0;
nn = int(n);
if(nn>99) t[p++] = 48 + (int(0.01*n)%10);
if(nn>9) t[p++] = 48 + (int(0.10*n)%10);
t[p++] = 48 + (int(n)%10);
t[p++] = ' ';
o = int(nn/12.f); s = nn-(12*o); o -= 2;
switch(s)
{
case 0: t[p++]='C'; break;
case 1: t[p++]='C'; t[p++]='#'; break;
case 2: t[p++]='D'; break;
case 3: t[p++]='D'; t[p++]='#'; break;
case 4: t[p++]='E'; break;
case 5: t[p++]='F'; break;
case 6: t[p++]='F'; t[p++]='#'; break;
case 7: t[p++]='G'; break;
case 8: t[p++]='G'; t[p++]='#'; break;
case 9: t[p++]='A'; break;
case 10: t[p++]='A'; t[p++]='#'; break;
default: t[p++]='B';
}
if(o<0) { t[p++]='-'; o = -o; }
t[p++]= 48 + (o%10);
t[p]=0;
strcpy(text, t);
}
void mdaTestTone::iso2string(float b, char *text)
{
switch(int(b))
{
case 13: strcpy(text, "20 Hz"); break;
case 14: strcpy(text, "25 Hz"); break;
case 15: strcpy(text, "31 Hz"); break;
case 16: strcpy(text, "40 Hz"); break;
case 17: strcpy(text, "50 Hz"); break;
case 18: strcpy(text, "63 Hz"); break;
case 19: strcpy(text, "80 Hz"); break;
case 20: strcpy(text, "100 Hz"); break;
case 21: strcpy(text, "125 Hz"); break;
case 22: strcpy(text, "160 Hz"); break;
case 23: strcpy(text, "200 Hz"); break;
case 24: strcpy(text, "250 Hz"); break;
case 25: strcpy(text, "310 Hz"); break;
case 26: strcpy(text, "400 Hz"); break;
case 27: strcpy(text, "500 Hz"); break;
case 28: strcpy(text, "630 Hz"); break;
case 29: strcpy(text, "800 Hz"); break;
case 30: strcpy(text, "1 kHz"); break;
case 31: strcpy(text, "1.25 kHz"); break;
case 32: strcpy(text, "1.6 kHz"); break;
case 33: strcpy(text, "2.0 kHz"); break;
case 34: strcpy(text, "2.5 kHz"); break;
case 35: strcpy(text, "3.1 kHz"); break;
case 36: strcpy(text, "4 kHz"); break;
case 37: strcpy(text, "5 kHz"); break;
case 38: strcpy(text, "6.3 kHz"); break;
case 39: strcpy(text, "8 kHz"); break;
case 40: strcpy(text, "10 kHz"); break;
case 41: strcpy(text, "12.5 kHz"); break;
case 42: strcpy(text, "16 kHz"); break;
case 43: strcpy(text, "20 kHz"); break;
default: strcpy(text, "--"); break;
}
}
float mdaTestTone::getParameter(int32_t index)
{
float v=0;
switch(index)
{
case 0: v = fParam0; break;
case 1: v = fParam1; break;
case 2: v = fParam2; break;
case 3: v = fParam3; break;
case 4: v = fParam4; break;
case 6: v = fParam5; break;
case 5: v = fParam6; break;
case 7: v = fParam7; break;
}
return v;
}
void mdaTestTone::getParameterName(int32_t index, char *label)
{
switch(index)
{
case 0: strcpy(label, "Mode"); break;
case 1: strcpy(label, "Level"); break;
case 2: strcpy(label, "Channel"); break;
case 3: strcpy(label, "F1"); break;
case 4: strcpy(label, "F2"); break;
case 6: strcpy(label, "Thru"); break;
case 5: strcpy(label, "Sweep"); break;
case 7: strcpy(label, "Zero dB"); break;
}
}
void mdaTestTone::getParameterDisplay(int32_t index, char *text)
{
switch(index)
{
case 0:
switch(mode)
{
case 0: strcpy(text, "MIDI #"); break;
case 1: strcpy(text, "IMPULSE"); break;
case 2: strcpy(text, "WHITE"); break;
case 3: strcpy(text, "PINK"); break;
case 4: strcpy(text, "---"); break;
case 5: strcpy(text, "SINE"); break;
case 6: strcpy(text, "LOG SWP."); break;
case 7: strcpy(text, "LOG STEP"); break;
case 8: strcpy(text, "LIN SWP."); break;
} break;
case 1: int2strng((int32_t)(int(60.f * fParam1) - 60.0 - calx), text); break;
case 2: if(fParam2>0.3f)
{ if(fParam2>0.7f) strcpy(text, "RIGHT");
else strcpy(text, "CENTRE"); }
else strcpy(text, "LEFT"); break;
case 3: strcpy(text, disp1); break;
case 4: strcpy(text, disp2); break;
case 6: if(fParam5==0) strcpy(text, "OFF");
else int2strng((int32_t)(40 * fParam5 - 40), text); break;
case 5: int2strng(1000 + 500*int(62*fParam6), text); break;
case 7: float2strng(cal, text); break;
}
}
void mdaTestTone::getParameterLabel(int32_t index, char *label)
{
switch(index)
{
case 0: strcpy(label, ""); break;
case 1: strcpy(label, "dB"); break;
case 2: strcpy(label, "L <> R"); break;
case 3: strcpy(label, ""); break;
case 4: strcpy(label, ""); break;
case 6: strcpy(label, "dB"); break;
case 5: strcpy(label, "ms"); break;
case 7: strcpy(label, "dBFS"); break;
}
}
//--------------------------------------------------------------------------------
// process
void mdaTestTone::process(float **inputs, float **outputs, int32_t sampleFrames)
{
if(updateRx != updateTx) update();
float *in1 = inputs[0];
float *in2 = inputs[1];
float *out1 = outputs[0];
float *out2 = outputs[1];
float a, b, c, d, x=0.0f, twopi=6.2831853f;
float z0=zz0, z1=zz1, z2=zz2, z3=zz3, z4=zz4, z5=zz5;
float ph=phi, dph=dphi, l=left, r=right, t=thru;
float s=sw, sx=swx, ds=swd, fsc=fscale;
int32_t st=swt;
int m=mode;
--in1;
--in2;
--out1;
--out2;
while(--sampleFrames >= 0)
{
a = *++in1;
b = *++in2;
c = out1[1];
d = out2[1];
switch(m)
{
case 1: if(st>0) { st--; x=0.f; } else //impulse
{
x=1.f;
st=(int32_t)(len*getSampleRate());
}
break;
case 2: //noise
#ifdef _WIN32
case 3: x = (float)(rand() - 16384); //for RAND_MAX = 32767
#else //mac/gcc
case 3: x = (float)((rand() & 0x7FFF) - 16384);
#endif
if(m==3)
{
z0 = 0.997f * z0 + 0.029591f * x; //pink filter
z1 = 0.985f * z1 + 0.032534f * x;
z2 = 0.950f * z2 + 0.048056f * x;
z3 = 0.850f * z3 + 0.090579f * x;
z4 = 0.620f * z4 + 0.108990f * x;
z5 = 0.250f * z5 + 0.255784f * x;
x = z0 + z1 + z2 + z3 + z4 + z5;
}
break;
case 4: x=0.f; break; //mute
case 0: //tones
case 5:
case 9: ph = (float)fmod(ph+dph,twopi);
x = (float)sin(ph);
break;
case 6: //log sweep & step
case 7: if(st>0) { st--; ph=0.f; } else
{
s += ds;
if(m==7) dph = fsc * (float)pow(10.0f, 0.1f * (float)int(s));
else dph = fsc * (float)pow(10.0f, 0.1f * s);
x = (float)sin(ph);
ph = (float)fmod(ph+dph,twopi);
if(s>sx) { l=0.f; r=0.f; }
}
break;
case 8: //lin sweep
if(st>0) { st--; ph=0.f; } else
{
s += ds;
x = (float)sin(ph);
ph = (float)fmod(ph+s,twopi);
if(s>sx) { l=0.f; r=0.f; }
}
break;
}
*++out1 = c + t*a + l*x;
*++out2 = d + t*b + r*x;
}
zz0=z0; zz1=z1; zz2=z2; zz3=z3, zz4=z4; zz5=z5;
phi=ph; sw=s; swt=st;
if(s>sx) setParameter(0, fParam0); //retrigger sweep
}
void mdaTestTone::processReplacing(float **inputs, float **outputs, int32_t sampleFrames)
{
if(updateRx != updateTx) update();
float *in1 = inputs[0];
float *in2 = inputs[1];
float *out1 = outputs[0];
float *out2 = outputs[1];
float a, b, x=0.0f, twopi=6.2831853f;
float z0=zz0, z1=zz1, z2=zz2, z3=zz3, z4=zz4, z5=zz5;
float ph=phi, dph=dphi, l=left, r=right, t=thru;
float s=sw, sx=swx, ds=swd, fsc=fscale;
int32_t st=swt;
int m=mode;
--in1;
--in2;
--out1;
--out2;
while(--sampleFrames >= 0)
{
a = *++in1;
b = *++in2;
switch(m)
{
case 1: if(st>0) { st--; x=0.f; } else //impulse
{
x=1.f;
st=(int32_t)(len*getSampleRate());
}
break;
case 2: //noise
#ifdef _WIN32
case 3: x = (float)(rand() - 16384); //for RAND_MAX = 32767
#else //mac/gcc
case 3: x = (float)((rand() & 0x7FFF) - 16384);
#endif
if(m==3)
{
z0 = 0.997f * z0 + 0.029591f * x; //pink filter
z1 = 0.985f * z1 + 0.032534f * x;
z2 = 0.950f * z2 + 0.048056f * x;
z3 = 0.850f * z3 + 0.090579f * x;
z4 = 0.620f * z4 + 0.108990f * x;
z5 = 0.250f * z5 + 0.255784f * x;
x = z0 + z1 + z2 + z3 + z4 + z5;
}
break;
case 4: x=0.f; break; //mute
case 0: //tones
case 5:
case 9: ph = (float)fmod(ph+dph,twopi);
x = (float)sin(ph);
break;
case 6: //log sweep & step
case 7: if(st>0) { st--; ph=0.f; } else
{
s += ds;
if(m==7) dph = fsc * (float)pow(10.0f, 0.1f * (float)int(s));
else dph = fsc * (float)pow(10.0f, 0.1f * s);
x = (float)sin(ph);
ph = (float)fmod(ph+dph,twopi);
if(s>sx) { l=0.f; r=0.f; }
}
break;
case 8: //lin sweep
if(st>0) { st--; ph=0.f; } else
{
s += ds;
x = (float)sin(ph);
ph = (float)fmod(ph+s,twopi);
if(s>sx) { l=0.f; r=0.f; }
}
break;
}
*++out1 = t*a + l*x;
*++out2 = t*b + r*x;
}
zz0=z0; zz1=z1; zz2=z2; zz3=z3, zz4=z4; zz5=z5;
phi=ph; sw=s; swt=st;
if(s>sx) setParameter(0, fParam0); //retrigger sweep
}
|
gpl-3.0
|
UCLL-ELO/WEB_ASP
|
ASP_LOGIN/ASP_LOGIN/Account/Lockout.aspx.designer.cs
|
440
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ASP_LOGIN.Account
{
public partial class Lockout
{
}
}
|
gpl-3.0
|
amigosz/Annom-1
|
Annom_Common/com/Thecheatgamer1/Annom/Core/Proxy/CommonProxy.java
|
945
|
package com.Thecheatgamer1.Annom.Core.Proxy;
import net.minecraftforge.common.ForgeDirection;
public class CommonProxy {
public void registerKeyBindingHandler() {
}
public void registerRenderTickHandler() {
}
public void registerDrawBlockHighlightHandler() {
}
public void setKeyBinding(String name, int value) {
}
public void registerSoundHandler() {
}
public void initRenderingAndTextures() {
}
public void sendRequestEventPacket(byte eventType, int originX, int originY, int originZ, byte sideHit, byte rangeX, byte rangeY, byte rangeZ, String data) {
}
public void handleTileEntityPacket(int x, int y, int z, ForgeDirection orientation, byte state, String customName) {
}
public void handleTileWithItemPacket(int x, int y, int z, ForgeDirection orientation, byte state, String customName, int itemID, int metaData, int stackSize, int color) {
}
}
|
gpl-3.0
|
linuxdeepin/deepin-ui
|
dtk/ui/window_base.py
|
8685
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Wang Yong
#
# Author: Wang Yong <lazycat.manatee@gmail.com>
# Maintainer: Wang Yong <lazycat.manatee@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
# 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 cairo
import gobject
from constant import EDGE_DICT
from skin_config import skin_config
import gtk
from utils import (resize_window, is_double_click, move_window)
class WindowBase(gtk.Window):
'''
WindowBase class.
@undocumented: draw_background
@undocumented: draw_skin
@undocumented: get_cursor_type_with_coordinate
'''
__gsignals__ = {
"window-resize" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self,
window_type=gtk.WINDOW_TOPLEVEL,
):
'''
Initialize WindowBase class.
@param window_type: The window type, default is gtk.WINDOW_TOPLEVEL
'''
gtk.Window.__init__(self, window_type)
self.move_window_x = 0
self.move_window_y = 0
self.move_start_x = 0
self.move_start_y = 0
self.move_end_x = 0
self.move_end_y = 0
def show_window(self):
'''
Show the window.
'''
self.show_all()
def toggle_max_window(self):
'''
Toggle the window size between maximized size and normal size.
'''
window_state = self.window.get_state()
if window_state & gtk.gdk.WINDOW_STATE_MAXIMIZED == gtk.gdk.WINDOW_STATE_MAXIMIZED:
self.unmaximize()
else:
self.maximize()
def toggle_fullscreen_window(self):
'''
Toggle the window between fullscreen mode and normal size.
'''
window_state = self.window.get_state()
if window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN == gtk.gdk.WINDOW_STATE_FULLSCREEN:
self.unfullscreen()
else:
self.fullscreen()
def close_window(self):
'''
Close the window. Send the destroy signal to the program.
@return: Always return False.
'''
# Hide window immediately when user click close button,
# user will feeling this software very quick, ;p
self.hide_all()
self.emit("destroy")
return False
def min_window(self):
'''
Minimize the window. Make it iconified.
'''
self.iconify()
def resize_window(self, widget, event):
'''
Resize the window.
@param widget: The window of type gtk.Widget.
@param event: A signal of type gtk.gdk.Event.
'''
if self.enable_resize:
edge = self.get_edge()
if edge != None:
resize_window(self, event, self, edge)
self.emit("window-resize")
def is_disable_window_maximized(self):
'''
An interface which indicates whether the window could be maximized, you should implement this function you own.
@return: Always return False.
'''
return False
def monitor_window_state(self, widget, event):
'''
Internal function to monitor window state,
add shadow when window at maximized or fullscreen status. Otherwise hide shadow.
@param widget: The window of type gtk.Widget.
@param event: The event of gtk.gdk.Event.
'''
window_state = self.window.get_state()
if (window_state & gtk.gdk.WINDOW_STATE_MAXIMIZED == gtk.gdk.WINDOW_STATE_MAXIMIZED or
window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN == gtk.gdk.WINDOW_STATE_FULLSCREEN):
self.hide_shadow()
if self.is_disable_window_maximized():
self.unmaximize()
else:
self.show_shadow()
def add_motion_move_event(self, widget):
'''
Add move event callback.
@param widget: A widget of type gtk.Widget.
'''
def handle_button_press(widget, event):
(self.move_window_x, self.move_window_y) = widget.get_toplevel().window.get_origin()
(self.move_start_x, self.move_start_y) = event.x_root, event.y_root
def handle_motion_event(widget, event):
(self.move_end_x, self.move_end_y) = event.x_root, event.y_root
widget.get_toplevel().move(
int(self.move_window_x + self.move_end_x - self.move_start_x),
int(self.move_window_y + self.move_end_y - self.move_start_y),
)
widget.connect("button-press-event", handle_button_press)
widget.connect("motion-notify-event", handle_motion_event)
def add_move_event(self, widget):
'''
Add move event callback.
@param widget: A widget of type gtk.Widget.
'''
widget.connect("button-press-event", lambda w, e: move_window(w, e, self))
def add_toggle_event(self, widget):
'''
Add toggle event callback.
@param widget: A widget of type gtk.Widget.
'''
widget.connect("button-press-event", self.double_click_window)
def double_click_window(self, widget, event):
'''
Double click event handler of the window. It will maximize the window.
@param widget: A widget of type gtk.Widget.
@param event: A event of type gtk.gdk.Event.
@return: Always return False.
'''
if is_double_click(event):
self.toggle_max_window()
return False
def get_edge(self):
'''
Get the edge which the cursor is on, according to the cursor type.
@return: If there is a corresponding cursor type, an instance of gtk.gdk.WindowEdge is returned, else None is returned.
'''
if EDGE_DICT.has_key(self.cursor_type):
return EDGE_DICT[self.cursor_type]
else:
return None
def draw_background(self, cr, x, y, w, h):
cr.set_source_rgba(*self.background_color)
cr.set_operator(cairo.OPERATOR_SOURCE)
cr.paint()
def draw_skin(self, cr, x, y, w, h):
skin_config.render_background(cr, self, x, y)
def draw_mask(self, cr, x, y, w, h):
'''
Draw mask interface, you should implement this function own.
@param cr: Cairo context.
@param x: X coordinate of draw area.
@param y: Y coordinate of draw area.
@param w: Width of draw area.
@param h: Height of draw area.
'''
pass
def get_cursor_type_with_coordinate(self, ex, ey, wx, wy, ww, wh):
'''
Get cursor type with given coordinate.
'''
if self.get_resizable():
if wx <= ex <= wx + self.shadow_padding:
if wy <= ey <= wy + self.shadow_padding * 2:
return gtk.gdk.TOP_LEFT_CORNER
elif wy + wh - (self.shadow_padding * 2) <= ey <= wy + wh:
return gtk.gdk.BOTTOM_LEFT_CORNER
elif wy + self.shadow_padding < ey < wy + wh - self.shadow_padding:
return gtk.gdk.LEFT_SIDE
else:
return None
elif wx + ww - self.shadow_padding <= ex <= wx + ww:
if wy <= ey <= wy + self.shadow_padding * 2:
return gtk.gdk.TOP_RIGHT_CORNER
elif wy + wh - (self.shadow_padding * 2) <= ey <= wy + wh:
return gtk.gdk.BOTTOM_RIGHT_CORNER
elif wy + self.shadow_padding < ey < wy + wh - self.shadow_padding:
return gtk.gdk.RIGHT_SIDE
else:
return None
elif wx + self.shadow_padding < ex < wx + ww - self.shadow_padding:
if wy <= ey <= wy + self.shadow_padding:
return gtk.gdk.TOP_SIDE
elif wy + wh - self.shadow_padding <= ey <= wy + wh:
return gtk.gdk.BOTTOM_SIDE
else:
return None
else:
return None
else:
return None
|
gpl-3.0
|
gvera85/sikronk
|
application/libraries/funciones.php
|
355
|
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Funciones {
public function generateRedirectURL()
{
$CI = &get_instance();
$preURL = parse_url($_SERVER['REQUEST_URI']);
$redirectUrl = array('redirectUrl' => 'http://' . $_SERVER['SERVER_NAME'] . $preURL['path']);
$CI->session->set_userdata($redirectUrl);
}
}
|
gpl-3.0
|
Invertika/data
|
scripts/maps/ow-p0010-n0018-o0000.lua
|
1404
|
----------------------------------------------------------------------------------
-- Map File --
-- --
-- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und --
-- anderer Dinge. --
-- --
----------------------------------------------------------------------------------
-- Copyright 2010 The Invertika Development Team --
-- --
-- This file is part of Invertika. --
-- --
-- Invertika 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 any later version. --
----------------------------------------------------------------------------------
require "scripts/lua/npclib"
require "scripts/libs/warp"
atinit(function()
create_inter_map_warp_trigger(1802, 1854, 1804, 1752) --- Intermap warp
end)
|
gpl-3.0
|
reid-vollett/Software_Quality_Project
|
MissileLauncher.py
|
1830
|
from ezmath import *
import GlobalVariables
from Missile import missile
from Poly import poly
from Weapon import weapon
# a high-damage power weapon that locks onto nearby enemies
class missileLauncher(weapon):
def __init__(this):
'''initializes the missileLauncher'''
weapon.__init__(this)
this.fireDelay = 15
this.ammo = 45
def draw(this):
# draws the reticle of the missileLauncher
col = (255, 100, 0)
verts1 = [(0, 0), (0, 1), (2, 0)]
verts2 = [(0, 0), (0, -1), (2, 0)]
ret1 = poly()
tpos = transform((20, 10), (0, 0), GlobalVariables.p1.angle)
ret1.pos = addPoints(tpos, GlobalVariables.p1.pos)
ret1.angle = GlobalVariables.p1.angle
ret1.verts = verts1
ret1.scale = 7 * (this.ammo / 45)
ret1.thickness = 3
ret1.color = col
ret2 = poly()
tpos = transform((20, -10), (0, 0), GlobalVariables.p1.angle)
ret2.pos = addPoints(tpos, GlobalVariables.p1.pos)
ret2.angle = GlobalVariables.p1.angle
ret2.verts = verts2
ret2.scale = 7 * (this.ammo / 45)
ret2.thickness = 3
ret2.color = col
GlobalVariables.maincam.toDraw(ret2)
GlobalVariables.maincam.toDraw(ret1)
def fire(this, pos, aim, vel):
'''releases a missile projectile'''
this.ammo -= 1
proj = missile(pos, aim, 10)
proj.vel = addPoints(proj.vel, vel)
proj.damage = 3
GlobalVariables.projectiles.append(proj)
def trigger(this, pos, aim, vel):
if (this.ammo <= 0):
return False
if (this.firewait <= 0):
GlobalVariables.sounds[6].play()
this.fire(pos, aim, vel)
this.firewait = this.fireDelay
return True
return False
|
gpl-3.0
|
nzaillian/evergreen-app
|
app/helpers/render_helper.rb
|
205
|
module RenderHelper
def render_content(*args, &block)
augmented_args = _normalize_args(*args, &block)
augmented_args[:formats] = [:html]
render_to_string(augmented_args).html_safe
end
end
|
gpl-3.0
|
kakone/GoogleCast
|
GoogleCast/Messages/Receiver/SetVolumeMessage.cs
|
416
|
using System.Runtime.Serialization;
using GoogleCast.Models;
namespace GoogleCast.Messages.Receiver
{
/// <summary>
/// Volume Message
/// </summary>
[DataContract]
class SetVolumeMessage : MessageWithId
{
/// <summary>
/// Gets or sets the volume
/// </summary>
[DataMember(Name = "volume")]
public Volume Volume { get; set; } = default!;
}
}
|
gpl-3.0
|
hmenke/espresso
|
src/core/unit_tests/common/gaussian.hpp
|
1663
|
/*
Copyright (C) 2010-2018 The ESPResSo project
This file is part of ESPResSo.
ESPResSo 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.
ESPResSo 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/>.
*/
#ifndef CORE_UNIT_TESTS_COMMON_GAUSSIAN_HPP
#define CORE_UNIT_TESTS_COMMON_GAUSSIAN_HPP
#include "Vector.hpp"
#include <boost/multi_array.hpp>
#include <cmath>
inline double gaussian(Vector3d x, Vector3d x0, double sigma) {
return std::exp(-((x - x0).norm2() / (2. * sigma * sigma)));
}
inline Vector3d del_gaussian(Vector3d x, Vector3d x0, double sigma) {
return -(x - x0) * gaussian(x, x0, sigma) / (sigma * sigma);
}
inline boost::multi_array<double, 3> gaussian_field(int size, Vector3d h,
Vector3d origin,
Vector3d x0, double sigma) {
boost::multi_array<double, 3> data(Vector<3, int>{10, 10, 10});
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
for (int k = 0; k < 10; k++) {
auto const x = origin + Vector3d{i * h[0], j * h[1], k * h[2]};
data[i][j][k] = gaussian(x, x0, sigma);
}
return data;
}
#endif
|
gpl-3.0
|
GTsianakas/space3D
|
DemoThree.java
|
1486
|
import java.util.ArrayList;
public class DemoThree{
ArrayList<PhysicalObject> list = new ArrayList<>();
public DemoThree(){
for (int i = 0; i < 500; i++){
list.add(new PhysicalSphere(1, //size
Math.random()*600.2-300.1+500, //xpos
Math.random()*600.2-300.1, //ypos
Math.random()*600.2-300.1, //zpos
0, //xspeed
0, //yspeed
0)); //zspeed
}
for (int i = 0; i < 500; i++){
list.add(new PhysicalSphere(1, //size
Math.random()*600.2-300.1-500, //xpos
Math.random()*600.2-300.1, //ypos
Math.random()*600.2-300.1, //zpos
0, //xspeed
0, //yspeed
0)); //zspeed
}
/* list.add(new PhysicalSphere(2000,10, //mass //size
200, //xpos
-800, //ypos
1, //zpos
0,//Math.random()*2-1, //xspeed
0,//Math.random()*2-1, //yspeed
0));//Math.random()*2-1)); //zspeed */
}
public ArrayList<PhysicalObject> getList(){
return this.list;
}
}
|
gpl-3.0
|
Interfacelab/ilab-media-tools
|
lib/mcloud-aws/aws-sdk-php/src/RAM/RAMClient.php
|
4682
|
<?php
namespace MediaCloud\Vendor\Aws\RAM;
use MediaCloud\Vendor\Aws\AwsClient;
/**
* This client is used to interact with the **AWS Resource Access Manager** service.
* @method \MediaCloud\Vendor\Aws\Result acceptResourceShareInvitation(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise acceptResourceShareInvitationAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result associateResourceShare(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise associateResourceShareAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result associateResourceSharePermission(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise associateResourceSharePermissionAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result createResourceShare(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise createResourceShareAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result deleteResourceShare(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise deleteResourceShareAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result disassociateResourceShare(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise disassociateResourceShareAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result disassociateResourceSharePermission(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise disassociateResourceSharePermissionAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result enableSharingWithAwsOrganization(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise enableSharingWithAwsOrganizationAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result getPermission(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getPermissionAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result getResourcePolicies(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getResourcePoliciesAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result getResourceShareAssociations(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getResourceShareAssociationsAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result getResourceShareInvitations(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getResourceShareInvitationsAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result getResourceShares(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise getResourceSharesAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result listPendingInvitationResources(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listPendingInvitationResourcesAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result listPermissions(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listPermissionsAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result listPrincipals(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listPrincipalsAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result listResourceSharePermissions(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listResourceSharePermissionsAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result listResourceTypes(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listResourceTypesAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result listResources(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise listResourcesAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result promoteResourceShareCreatedFromPolicy(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise promoteResourceShareCreatedFromPolicyAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result rejectResourceShareInvitation(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise rejectResourceShareInvitationAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result tagResource(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise tagResourceAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result untagResource(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise untagResourceAsync(array $args = [])
* @method \MediaCloud\Vendor\Aws\Result updateResourceShare(array $args = [])
* @method \MediaCloud\Vendor\GuzzleHttp\Promise\Promise updateResourceShareAsync(array $args = [])
*/
class RAMClient extends AwsClient {}
|
gpl-3.0
|
damicon/zfswatcher
|
golibs/src/code.google.com/p/gcfg/bool.go
|
411
|
package gcfg
import (
"fmt"
)
type gbool bool
var gboolValues = map[string]interface{}{
"true": true, "yes": true, "on": true, "1": true,
"false": false, "no": false, "off": false, "0": false}
func (b *gbool) Scan(state fmt.ScanState, verb rune) error {
v, err := scanEnum(state, gboolValues, true)
if err != nil {
return err
}
bb, _ := v.(bool) // cannot be non-bool
*b = gbool(bb)
return nil
}
|
gpl-3.0
|
cemfi/meico
|
src/meico/mpm/elements/styles/MetricalAccentuationStyle.java
|
3279
|
package meico.mpm.elements.styles;
import meico.mei.Helper;
import meico.mpm.elements.styles.defs.AccentuationPatternDef;
import nu.xom.Element;
import java.util.HashMap;
import java.util.LinkedList;
/**
* This class interfaces metrical accentuation style definitions.
* Basically, these define a string and
* and assotiate it with an instance of AccentuationPatternDef.
* @author Axel Berndt
*/
public class MetricalAccentuationStyle extends GenericStyle<AccentuationPatternDef> {
/**
* this constructor generates an empty styleDef for AccentuationPatternDefs to be added subsequently
* @param name
* @throws Exception
*/
private MetricalAccentuationStyle(String name) throws Exception {
super(name);
}
/**
* this constructor generates the object from xml input
* @param xml
* @throws Exception
*/
private MetricalAccentuationStyle(Element xml) throws Exception {
super(xml);
}
/**
* MetricalAccentuationStyle factory
* @param name
* @return
*/
public static MetricalAccentuationStyle createMetricalAccentuationStyle(String name) {
MetricalAccentuationStyle metricalAccentuationStyle;
try {
metricalAccentuationStyle = new MetricalAccentuationStyle(name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return metricalAccentuationStyle;
}
/**
* MetricalAccentuationStyle factory
* @param name
* @param id
* @return
*/
public static MetricalAccentuationStyle createMetricalAccentuationStyle(String name, String id) {
MetricalAccentuationStyle metricalAccentuationStyle;
try {
metricalAccentuationStyle = new MetricalAccentuationStyle(name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
metricalAccentuationStyle.setId(id);
return metricalAccentuationStyle;
}
/**
* MetricalAccentuationStyle factory
* @param xml
* @return
*/
public static MetricalAccentuationStyle createMetricalAccentuationStyle(Element xml) {
MetricalAccentuationStyle metricalAccentuationStyle;
try {
metricalAccentuationStyle = new MetricalAccentuationStyle(xml);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return metricalAccentuationStyle;
}
/**
* set the data of this object, this parses the xml element and generates the according data structure
* @param xml
*/
protected void parseData(Element xml) throws Exception {
super.parseData(xml);
// parse the MetricalAccentuationStyle elements (the children of this styleDef)
LinkedList<Element> maDefs = Helper.getAllChildElements("accentuationPatternDef", this.getXml());
for (Element maDef : maDefs) { // for each AccentuationPattern
AccentuationPatternDef apd = AccentuationPatternDef.createAccentuationPatternDef(maDef);
if (apd == null)
continue;
this.defs.put(apd.getName(), apd); // add the (name, AccentuationPatternDef) pair to the lookup table
}
}
}
|
gpl-3.0
|
zhehaowang/ndn-cxx
|
tests/unit-tests/test-version.cpp
|
1789
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2013-2014 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx 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.
*
* ndn-cxx 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 copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#include "version.hpp"
#include "boost-test.hpp"
#include <stdio.h>
namespace ndn {
namespace tests {
BOOST_AUTO_TEST_SUITE(TestVersion)
BOOST_AUTO_TEST_CASE(Version)
{
BOOST_CHECK_EQUAL(NDN_CXX_VERSION, NDN_CXX_VERSION_MAJOR * 1000000 +
NDN_CXX_VERSION_MINOR * 1000 +
NDN_CXX_VERSION_PATCH);
}
BOOST_AUTO_TEST_CASE(VersionString)
{
BOOST_STATIC_ASSERT(NDN_CXX_VERSION_MAJOR < 1000);
char buf[20];
snprintf(buf, sizeof(buf), "%d.%d.%d",
NDN_CXX_VERSION_MAJOR, NDN_CXX_VERSION_MINOR, NDN_CXX_VERSION_PATCH);
BOOST_CHECK_EQUAL(std::string(NDN_CXX_VERSION_STRING), std::string(buf));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace tests
} // namespace ndn
|
gpl-3.0
|
Schumix/Schumix2
|
Applications/Schumix.Installer/Compiler/Build.cs
|
2432
|
/*
* This file is part of Schumix.
*
* Copyright (C) 2010-2013 Megax <http://megax.yeahunter.hu/>
* Copyright (C) 2013-2015 Schumix Team <http://schumix.eu/>
*
* Schumix 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.
*
* Schumix 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 Schumix. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Microsoft.Build.Utilities;
using Schumix.Installer;
using Schumix.Installer.Logger;
using Schumix.Installer.Platforms;
namespace Schumix.Installer.Compiler
{
sealed class Build
{
private readonly Platform sPlatform = Singleton<Platform>.Instance;
public bool HasError { get; private set; }
public Build(string dir)
{
Compile(dir);
}
private void Compile(string dir)
{
var build = new Process();
build.StartInfo.UseShellExecute = false;
build.StartInfo.RedirectStandardOutput = true;
build.StartInfo.RedirectStandardError = true;
if(sPlatform.IsLinux)
{
build.StartInfo.FileName = "xbuild";
build.StartInfo.Arguments = string.Format("/p:Configuration=\"Release\" {0}/Schumix.sln", dir);
}
else if(sPlatform.IsWindows)
{
File.Copy(ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version40) + "\\MSBuild.exe", dir + "\\MSBuild.exe");
build.StartInfo.FileName = dir + "\\MSBuild.exe";
build.StartInfo.Arguments = string.Format("/p:Configuration=\"Release\" {0}/Schumix.sln /flp:LogFile=msbuild.log;Verbosity=Detailed", dir);
}
build.Start();
build.PriorityClass = ProcessPriorityClass.Normal;
var error = build.StandardError;
var output = build.StandardOutput;
HasError = false;
while(!output.EndOfStream)
Log.Debug("Build", output.ReadLine());
while(!error.EndOfStream)
{
if(!HasError)
HasError = true;
Log.Debug("Build", error.ReadLine());
}
build.WaitForExit();
build.Dispose();
}
}
}
|
gpl-3.0
|
thiagorcdl/AdventOfCode
|
2020/src/day_01/__init__.py
|
1150
|
#!/usr/bin/env python
from src.utils import BaseResolution
class Resolution(BaseResolution):
"""Logics for resolving day 1."""
day = 1
def part_1(self, input_lines: list):
"""Run n**2 solution for part 1."""
total = 2020
for i, line in enumerate(input_lines):
line = int(line)
rest = total - line
for candidate in input_lines[i+1:]:
candidate = int(candidate)
if rest == candidate:
print(line * candidate)
return
def part_2(self, input_lines: list):
"""Run n**3 solution for part 2."""
total = 2020
for i, line in enumerate(input_lines):
line = int(line)
rest = total - line
for candidate1 in input_lines[i+1:]:
candidate1 = int(candidate1)
rest2 = rest - candidate1
for candidate2 in input_lines[i+2:]:
candidate2 = int(candidate2)
if rest2 == candidate2:
print(line * candidate1 * candidate2)
return
|
gpl-3.0
|
ISRAPIL/FastCorePE
|
src/pocketmine/level/particle/MobSpawnParticle.php
|
727
|
<?php
namespace pocketmine\level\particle;
use pocketmine\network\protocol\LevelEventPacket;
use pocketmine\math\Vector3;
class MobSpawnParticle extends Particle {
protected $width;
protected $height;
public function __construct(Vector3 $pos, $width = 0, $height = 0) {
parent::__construct($pos->x, $pos->y, $pos->z);
$this->width = $width;
$this->height = $height;
}
public function encode() {
$pk = new LevelEventPacket;
$pk->evid = LevelEventPacket::EVENT_PARTICLE_SPAWN;
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->data = ($this->width & 0xff) + (($this->height & 0xff) << 8);
return $pk;
}
}
|
gpl-3.0
|
HopeFOAM/HopeFOAM
|
ThirdParty-0.1/ParaView-5.0.1/Utilities/VisItBridge/databases/RAW/RAWEnginePluginInfo.C
|
3110
|
/*****************************************************************************
*
* Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY 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 <RAWPluginInfo.h>
#include <avtRAWWriter.h>
// ****************************************************************************
// Function: GetEngineInfo
//
// Purpose:
// Return a new EnginePluginInfo for the RAW database.
//
// Programmer: generated by xml2info
// Creation: omitted
//
// ****************************************************************************
extern "C" DBP_EXPORT EngineDatabasePluginInfo* RAW_GetEngineInfo()
{
return new RAWEnginePluginInfo;
}
// ****************************************************************************
// Method: RAWEnginePluginInfo::GetWriter
//
// Purpose:
// Sets up a RAW writer.
//
// Returns: A RAW writer.
//
// Programmer: generated by xml2info
// Creation: omitted
//
// ****************************************************************************
avtDatabaseWriter *
RAWEnginePluginInfo::GetWriter(void)
{
return new avtRAWWriter;
}
|
gpl-3.0
|
ctxis/canape
|
CANAPE.Scripting/BasePipelineNodeWithPersist.cs
|
2797
|
// CANAPE Network Testing Tool
// Copyright (C) 2014 Context Information Security
//
// 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 CANAPE.Nodes;
using CANAPE.Utils;
namespace CANAPE.Scripting
{
/// <summary>
/// Base class for a pipeline node with persistance
/// </summary>
/// <typeparam name="T">The configuration types</typeparam>
public abstract class BasePipelineNodeWithPersist<T>
: BasePipelineNode, IPersistNode where T : class, new()
{
/// <summary>
/// Protected constructor
/// </summary>
protected BasePipelineNodeWithPersist()
{
_config = new T();
}
/// <summary>
/// The current config
/// </summary>
private T _config;
/// <summary>
/// The current config
/// </summary>
public T Config
{
get { return _config; }
}
/// <summary>
/// Overridable method to validate config, should throw an ArgumentException if invalid
/// </summary>
/// <param name="config">The config</param>
protected virtual void ValidateConfig(T config)
{
// Do nothing
}
#region IPersistDynamicNode Members
/// <summary>
/// Get the current state
/// </summary>
/// <param name="logger"></param>
/// <returns>The state object</returns>
public object GetState(Logger logger)
{
return _config;
}
/// <summary>
/// Set the current state
/// </summary>
/// <param name="state">The state object</param>
/// <param name="logger"></param>
public void SetState(object state, Logger logger)
{
T config = state as T;
if (config == null)
{
logger.LogError(CANAPE.Scripting.Properties.Resources.BasePipelineNodeWithPersist_InvalidConfig, GetType().Name);
}
else
{
ValidateConfig(config);
_config = config;
}
}
#endregion
}
}
|
gpl-3.0
|
RumAngelov/ConvPlugin
|
JuceLibraryCode/modules/juce_audio_plugin_client/VST3/juce_VST3_Wrapper.cpp
|
98625
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include "../../juce_core/system/juce_TargetPlatform.h"
//==============================================================================
#if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
#if JUCE_PLUGINHOST_VST3 && (JUCE_MAC || JUCE_WINDOWS)
#undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
#define JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY 1
#endif
#include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
#undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
#include "../utility/juce_CheckSettingMacros.h"
#include "../utility/juce_IncludeModuleHeaders.h"
#include "../utility/juce_WindowsHooks.h"
#include "../utility/juce_FakeMouseMoveGenerator.h"
#include "../../juce_audio_processors/format_types/juce_VST3Common.h"
#ifndef JUCE_VST3_CAN_REPLACE_VST2
#define JUCE_VST3_CAN_REPLACE_VST2 1
#endif
#if JUCE_VST3_CAN_REPLACE_VST2
#include "../../juce_audio_processors/format_types/juce_VSTInterface.h"
#endif
#ifndef JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
#define JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS 1
#endif
#if JUCE_VST3_CAN_REPLACE_VST2
#if JUCE_MSVC
#pragma warning (push)
#pragma warning (disable: 4514 4996)
#endif
#if JUCE_MSVC
#pragma warning (pop)
#endif
#endif
namespace juce
{
using namespace Steinberg;
//==============================================================================
#if JUCE_MAC
extern void initialiseMacVST();
#if ! JUCE_64BIT
extern void updateEditorCompBoundsVST (Component*);
#endif
extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
extern JUCE_API void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
#endif
//==============================================================================
class JuceAudioProcessor : public FUnknown
{
public:
JuceAudioProcessor (AudioProcessor* source) noexcept : audioProcessor (source) {}
virtual ~JuceAudioProcessor() {}
AudioProcessor* get() const noexcept { return audioProcessor; }
JUCE_DECLARE_VST3_COM_QUERY_METHODS
JUCE_DECLARE_VST3_COM_REF_METHODS
static const FUID iid;
bool isBypassed = false;
private:
Atomic<int> refCount;
ScopedPointer<AudioProcessor> audioProcessor;
ScopedJuceInitialiser_GUI libraryInitialiser;
JuceAudioProcessor() JUCE_DELETED_FUNCTION;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
};
class JuceVST3Component;
//==============================================================================
class JuceVST3EditController : public Vst::EditController,
public Vst::IMidiMapping,
public AudioProcessorListener
{
public:
JuceVST3EditController (Vst::IHostApplication* host)
{
if (host != nullptr)
host->queryInterface (FUnknown::iid, (void**) &hostContext);
}
//==============================================================================
static const FUID iid;
//==============================================================================
#if JUCE_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winconsistent-missing-override"
#endif
REFCOUNT_METHODS (ComponentBase)
#if JUCE_CLANG
#pragma clang diagnostic pop
#endif
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
{
audioProcessor->addRef();
*obj = audioProcessor;
return kResultOk;
}
*obj = nullptr;
return kNoInterface;
}
//==============================================================================
tresult PLUGIN_API initialize (FUnknown* context) override
{
if (hostContext != context)
{
if (hostContext != nullptr)
hostContext->release();
hostContext = context;
if (hostContext != nullptr)
hostContext->addRef();
}
return kResultTrue;
}
tresult PLUGIN_API terminate() override
{
if (auto* pluginInstance = getPluginInstance())
pluginInstance->removeListener (this);
audioProcessor = nullptr;
return EditController::terminate();
}
//==============================================================================
enum InternalParameters
{
paramPreset = 0x70727374, // 'prst'
paramBypass = 0x62797073, // 'byps'
paramMidiControllerOffset = 0x6d636d00 // 'mdm*'
};
struct Param : public Vst::Parameter
{
Param (AudioProcessor& p, int index, Vst::ParamID paramID) : owner (p), paramIndex (index)
{
info.id = paramID;
toString128 (info.title, p.getParameterName (index));
toString128 (info.shortTitle, p.getParameterName (index, 8));
toString128 (info.units, p.getParameterLabel (index));
const int numSteps = p.getParameterNumSteps (index);
info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
info.defaultNormalizedValue = p.getParameterDefaultValue (index);
jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
info.unitId = Vst::kRootUnitId;
// is this a meter?
if (((p.getParameterCategory (index) & 0xffff0000) >> 16) == 2)
info.flags = Vst::ParameterInfo::kIsReadOnly;
else
info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
valueNormalized = info.defaultNormalizedValue;
}
virtual ~Param() {}
bool setNormalized (Vst::ParamValue v) override
{
v = jlimit (0.0, 1.0, v);
if (v != valueNormalized)
{
valueNormalized = v;
owner.setParameter (paramIndex, static_cast<float> (v));
changed();
return true;
}
return false;
}
void toString (Vst::ParamValue value, Vst::String128 result) const override
{
if (auto* p = owner.getParameters()[paramIndex])
toString128 (result, p->getText ((float) value, 128));
else
// remain backward-compatible with old JUCE code
toString128 (result, owner.getParameterText (paramIndex, 128));
}
bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
{
if (auto* p = owner.getParameters()[paramIndex])
{
outValueNormalized = p->getValueForText (getStringFromVstTChars (text));
return true;
}
return false;
}
static String getStringFromVstTChars (const Vst::TChar* text)
{
return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
}
Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
private:
AudioProcessor& owner;
int paramIndex;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
};
//==============================================================================
struct BypassParam : public Vst::Parameter
{
BypassParam (Vst::ParamID vstParamID)
{
info.id = vstParamID;
toString128 (info.title, "Bypass");
toString128 (info.shortTitle, "Bypass");
toString128 (info.units, "");
info.stepCount = 1;
info.defaultNormalizedValue = 0.0f;
info.unitId = Vst::kRootUnitId;
info.flags = Vst::ParameterInfo::kIsBypass | Vst::ParameterInfo::kCanAutomate;
}
virtual ~BypassParam() {}
bool setNormalized (Vst::ParamValue v) override
{
bool bypass = (v != 0.0f);
v = (bypass ? 1.0f : 0.0f);
if (valueNormalized != v)
{
valueNormalized = v;
changed();
return true;
}
return false;
}
void toString (Vst::ParamValue value, Vst::String128 result) const override
{
bool bypass = (value != 0.0f);
toString128 (result, bypass ? "On" : "Off");
}
bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
{
auto paramValueString = getStringFromVstTChars (text);
if (paramValueString.equalsIgnoreCase ("on")
|| paramValueString.equalsIgnoreCase ("yes")
|| paramValueString.equalsIgnoreCase ("true"))
{
outValueNormalized = 1.0f;
return true;
}
if (paramValueString.equalsIgnoreCase ("off")
|| paramValueString.equalsIgnoreCase ("no")
|| paramValueString.equalsIgnoreCase ("false"))
{
outValueNormalized = 0.0f;
return true;
}
var varValue = JSON::fromString (paramValueString);
if (varValue.isDouble() || varValue.isInt()
|| varValue.isInt64() || varValue.isBool())
{
double value = varValue;
outValueNormalized = (value != 0.0) ? 1.0f : 0.0f;
return true;
}
return false;
}
static String getStringFromVstTChars (const Vst::TChar* text)
{
return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
}
Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BypassParam)
};
//==============================================================================
struct ProgramChangeParameter : public Vst::Parameter
{
ProgramChangeParameter (AudioProcessor& p) : owner (p)
{
jassert (owner.getNumPrograms() > 1);
info.id = paramPreset;
toString128 (info.title, "Program");
toString128 (info.shortTitle, "Program");
toString128 (info.units, "");
info.stepCount = owner.getNumPrograms() - 1;
info.defaultNormalizedValue = static_cast<Vst::ParamValue> (owner.getCurrentProgram())
/ static_cast<Vst::ParamValue> (info.stepCount);
info.unitId = Vst::kRootUnitId;
info.flags = Vst::ParameterInfo::kIsProgramChange | Vst::ParameterInfo::kCanAutomate;
}
virtual ~ProgramChangeParameter() {}
bool setNormalized (Vst::ParamValue v) override
{
Vst::ParamValue program = v * info.stepCount;
if (! isPositiveAndBelow ((int) program, owner.getNumPrograms()))
return false;
if (valueNormalized != v)
{
valueNormalized = v;
changed();
return true;
}
return false;
}
void toString (Vst::ParamValue value, Vst::String128 result) const override
{
toString128 (result, owner.getProgramName (static_cast<int> (value * info.stepCount)));
}
bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
{
auto paramValueString = getStringFromVstTChars (text);
auto n = owner.getNumPrograms();
for (int i = 0; i < n; ++i)
{
if (paramValueString == owner.getProgramName (i))
{
outValueNormalized = static_cast<Vst::ParamValue> (i) / info.stepCount;
return true;
}
}
return false;
}
static String getStringFromVstTChars (const Vst::TChar* text)
{
return String (CharPointer_UTF16 (reinterpret_cast<const CharPointer_UTF16::CharType*> (text)));
}
Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v * info.stepCount; }
Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v / info.stepCount; }
private:
AudioProcessor& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgramChangeParameter)
};
//==============================================================================
tresult PLUGIN_API setComponentState (IBStream* stream) override
{
// Cubase and Nuendo need to inform the host of the current parameter values
if (auto* pluginInstance = getPluginInstance())
{
auto numParameters = pluginInstance->getNumParameters();
for (int i = 0; i < numParameters; ++i)
setParamNormalized (getVSTParamIDForIndex (i), (double) pluginInstance->getParameter (i));
setParamNormalized (bypassParamID, audioProcessor->isBypassed ? 1.0f : 0.0f);
auto numPrograms = pluginInstance->getNumPrograms();
if (numPrograms > 1)
setParamNormalized (paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
/ static_cast<Vst::ParamValue> (numPrograms - 1));
}
if (auto* handler = getComponentHandler())
handler->restartComponent (Vst::kParamValuesChanged);
return Vst::EditController::setComponentState (stream);
}
void setAudioProcessor (JuceAudioProcessor* audioProc)
{
if (audioProcessor != audioProc)
{
audioProcessor = audioProc;
setupParameters();
}
}
tresult PLUGIN_API connect (IConnectionPoint* other) override
{
if (other != nullptr && audioProcessor == nullptr)
{
auto result = ComponentBase::connect (other);
if (! audioProcessor.loadFrom (other))
sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
else
setupParameters();
return result;
}
jassertfalse;
return kResultFalse;
}
//==============================================================================
tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
{
resultID = midiControllerToParameter[channel][midiControllerNumber];
return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
}
// Converts an incoming parameter index to a MIDI controller:
bool getMidiControllerForParameter (Vst::ParamID index, int& channel, int& ctrlNumber)
{
auto mappedIndex = static_cast<int> (index - parameterToMidiControllerOffset);
if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
{
auto& mc = parameterToMidiController[mappedIndex];
if (mc.channel != -1 && mc.ctrlNumber != -1)
{
channel = jlimit (1, 16, mc.channel + 1);
ctrlNumber = mc.ctrlNumber;
return true;
}
}
return false;
}
inline bool isMidiControllerParamID (Vst::ParamID paramID) const noexcept
{
return (paramID >= parameterToMidiControllerOffset
&& isPositiveAndBelow (paramID - parameterToMidiControllerOffset,
static_cast<Vst::ParamID> (numElementsInArray (parameterToMidiController))));
}
//==============================================================================
IPlugView* PLUGIN_API createView (const char* name) override
{
if (auto* pluginInstance = getPluginInstance())
{
if (pluginInstance->hasEditor() && name != nullptr
&& strcmp (name, Vst::ViewType::kEditor) == 0)
{
return new JuceVST3Editor (*this, *pluginInstance);
}
}
return nullptr;
}
//==============================================================================
void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit (getVSTParamIDForIndex (index)); }
void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit (getVSTParamIDForIndex (index)); }
void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
{
// NB: Cubase has problems if performEdit is called without setParamNormalized
EditController::setParamNormalized (getVSTParamIDForIndex (index), (double) newValue);
performEdit (getVSTParamIDForIndex (index), (double) newValue);
}
void audioProcessorChanged (AudioProcessor*) override
{
if (auto* pluginInstance = getPluginInstance())
{
if (pluginInstance->getNumPrograms() > 1)
EditController::setParamNormalized (paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
/ static_cast<Vst::ParamValue> (pluginInstance->getNumPrograms() - 1));
}
if (componentHandler != nullptr)
componentHandler->restartComponent (Vst::kLatencyChanged | Vst::kParamValuesChanged);
}
//==============================================================================
AudioProcessor* getPluginInstance() const noexcept
{
if (audioProcessor != nullptr)
return audioProcessor->get();
return nullptr;
}
private:
friend class JuceVST3Component;
//==============================================================================
ComSmartPtr<JuceAudioProcessor> audioProcessor;
ScopedJuceInitialiser_GUI libraryInitialiser;
struct MidiController
{
int channel = -1, ctrlNumber = -1;
};
enum { numMIDIChannels = 16 };
Vst::ParamID parameterToMidiControllerOffset;
MidiController parameterToMidiController[numMIDIChannels * Vst::kCountCtrlNumber];
Vst::ParamID midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
//==============================================================================
#if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
bool usingManagedParameter = false;
Array<Vst::ParamID> vstParamIDs;
#endif
Vst::ParamID bypassParamID;
//==============================================================================
void setupParameters()
{
if (auto* pluginInstance = getPluginInstance())
{
pluginInstance->addListener (this);
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
const bool usingManagedParameter = false;
#endif
if (parameters.getParameterCount() <= 0)
{
auto numParameters = pluginInstance->getNumParameters();
#if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
usingManagedParameter = (pluginInstance->getParameters().size() == numParameters);
#endif
for (int i = 0; i < numParameters; ++i)
{
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
const Vst::ParamID vstParamID = static_cast<Vst::ParamID> (i);
#else
const Vst::ParamID vstParamID = generateVSTParamIDForIndex (pluginInstance, i);
vstParamIDs.add (vstParamID);
#endif
parameters.addParameter (new Param (*pluginInstance, i, vstParamID));
}
bypassParamID = static_cast<Vst::ParamID> (usingManagedParameter ? paramBypass : numParameters);
parameters.addParameter (new BypassParam (bypassParamID));
if (pluginInstance->getNumPrograms() > 1)
parameters.addParameter (new ProgramChangeParameter (*pluginInstance));
}
#if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
parameterToMidiControllerOffset = static_cast<Vst::ParamID> (usingManagedParameter ? paramMidiControllerOffset
: parameters.getParameterCount());
initialiseMidiControllerMappings();
#endif
audioProcessorChanged (pluginInstance);
}
}
void initialiseMidiControllerMappings()
{
for (int c = 0, p = 0; c < numMIDIChannels; ++c)
{
for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
{
midiControllerToParameter[c][i] = static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset;
parameterToMidiController[p].channel = c;
parameterToMidiController[p].ctrlNumber = i;
parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset, 0, 0, 0,
Vst::ParameterInfo::kCanAutomate, Vst::kRootUnitId));
}
}
}
void sendIntMessage (const char* idTag, const Steinberg::int64 value)
{
jassert (hostContext != nullptr);
if (auto* message = allocateMessage())
{
const FReleaser releaser (message);
message->setMessageID (idTag);
message->getAttributes()->setInt (idTag, value);
sendMessage (message);
}
}
//==============================================================================
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept { return static_cast<Vst::ParamID> (paramIndex); }
#else
static Vst::ParamID generateVSTParamIDForIndex (AudioProcessor* const pluginFilter, int paramIndex)
{
jassert (pluginFilter != nullptr);
const int n = pluginFilter->getNumParameters();
const bool managedParameter = (pluginFilter->getParameters().size() == n);
if (isPositiveAndBelow (paramIndex, n))
{
auto juceParamID = pluginFilter->getParameterID (paramIndex);
auto paramHash = static_cast<Vst::ParamID> (juceParamID.hashCode());
#if JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS
// studio one doesn't like negative parameters
paramHash &= ~(1 << (sizeof (Vst::ParamID) * 8 - 1));
#endif
return managedParameter ? paramHash
: static_cast<Vst::ParamID> (juceParamID.getIntValue());
}
return static_cast<Vst::ParamID> (-1);
}
inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
{
return usingManagedParameter ? vstParamIDs.getReference (paramIndex)
: static_cast<Vst::ParamID> (paramIndex);
}
#endif
//==============================================================================
class JuceVST3Editor : public Vst::EditorView,
public Steinberg::IPlugViewContentScaleSupport,
private Timer
{
public:
JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
: Vst::EditorView (&ec, nullptr),
owner (&ec), pluginInstance (p)
{
component = new ContentWrapperComponent (*this, p);
}
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Steinberg::IPlugViewContentScaleSupport)
return Vst::EditorView::queryInterface (targetIID, obj);
}
REFCOUNT_METHODS (Vst::EditorView)
//==============================================================================
tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
{
if (type != nullptr && pluginInstance.hasEditor())
{
#if JUCE_WINDOWS
if (strcmp (type, kPlatformTypeHWND) == 0)
#else
if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
#endif
return kResultTrue;
}
return kResultFalse;
}
tresult PLUGIN_API attached (void* parent, FIDString type) override
{
if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
return kResultFalse;
if (component == nullptr)
component = new ContentWrapperComponent (*this, pluginInstance);
#if JUCE_WINDOWS
component->addToDesktop (0, parent);
component->setOpaque (true);
component->setVisible (true);
#else
isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
macHostWindow = juce::attachComponentToWindowRefVST (component, parent, isNSView);
#endif
component->resizeHostWindow();
systemWindow = parent;
attachedToParent();
// Life's too short to faff around with wave lab
if (getHostType().isWavelab())
startTimer (200);
return kResultTrue;
}
tresult PLUGIN_API removed() override
{
if (component != nullptr)
{
#if JUCE_WINDOWS
component->removeFromDesktop();
#else
if (macHostWindow != nullptr)
{
juce::detachComponentFromWindowRefVST (component, macHostWindow, isNSView);
macHostWindow = nullptr;
}
#endif
component = nullptr;
}
return CPluginView::removed();
}
tresult PLUGIN_API onSize (ViewRect* newSize) override
{
if (newSize != nullptr)
{
rect = *newSize;
if (component != nullptr)
{
component->setSize (rect.getWidth(), rect.getHeight());
if (auto* peer = component->getPeer())
peer->updateBounds();
}
return kResultTrue;
}
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API getSize (ViewRect* size) override
{
if (size != nullptr && component != nullptr)
{
*size = ViewRect (0, 0, component->getWidth(), component->getHeight());
return kResultTrue;
}
return kResultFalse;
}
tresult PLUGIN_API canResize() override
{
if (component != nullptr)
if (auto* editor = component->pluginEditor.get())
return editor->isResizable() ? kResultTrue : kResultFalse;
return kResultFalse;
}
tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
{
if (rectToCheck != nullptr && component != nullptr)
{
// checkSizeConstraint
auto juceRect = Rectangle<int>::leftTopRightBottom (rectToCheck->left, rectToCheck->top,
rectToCheck->right, rectToCheck->bottom);
if (auto* editor = component->pluginEditor.get())
{
if (auto* constrainer = editor->getConstrainer())
{
auto scaledMin = component->getLocalArea (editor, Rectangle<int> (constrainer->getMinimumWidth(),
constrainer->getMinimumHeight()));
auto scaledMax = component->getLocalArea (editor, Rectangle<int> (constrainer->getMaximumWidth(),
constrainer->getMaximumHeight()));
juceRect.setSize (jlimit (scaledMin.getWidth(), scaledMax.getWidth(), juceRect.getWidth()),
jlimit (scaledMin.getHeight(), scaledMax.getHeight(), juceRect.getHeight()));
}
}
rectToCheck->right = rectToCheck->left + juceRect.getWidth();
rectToCheck->bottom = rectToCheck->top + juceRect.getHeight();
return kResultTrue;
}
jassertfalse;
return kResultFalse;
}
tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
{
#if (JUCE_MAC || JUCE_IOS)
ignoreUnused (factor);
#else
if (auto* editor = component->pluginEditor.get())
{
editor->setScaleFactor (factor);
return kResultTrue;
}
#endif
return kResultFalse;
}
private:
void timerCallback() override
{
stopTimer();
ViewRect viewRect;
getSize (&viewRect);
onSize (&viewRect);
}
//==============================================================================
struct ContentWrapperComponent : public Component
{
ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
: pluginEditor (plugin.createEditorIfNeeded()),
owner (editor)
{
setOpaque (true);
setBroughtToFrontOnMouseClick (true);
// if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
jassert (pluginEditor != nullptr);
if (pluginEditor != nullptr)
{
addAndMakeVisible (pluginEditor);
pluginEditor->setTopLeftPosition (0, 0);
lastBounds = getSizeToContainChild();
isResizingParentToFitChild = true;
setBounds (lastBounds);
isResizingParentToFitChild = false;
resizeHostWindow();
}
ignoreUnused (fakeMouseGenerator);
}
~ContentWrapperComponent()
{
if (pluginEditor != nullptr)
{
PopupMenu::dismissAllActiveMenus();
pluginEditor->processor.editorBeingDeleted (pluginEditor);
}
}
void paint (Graphics& g) override
{
g.fillAll (Colours::black);
}
juce::Rectangle<int> getSizeToContainChild()
{
if (pluginEditor != nullptr)
return getLocalArea (pluginEditor, pluginEditor->getLocalBounds());
return {};
}
void childBoundsChanged (Component*) override
{
if (isResizingChildToFitParent)
return;
auto b = getSizeToContainChild();
if (lastBounds != b)
{
lastBounds = b;
isResizingParentToFitChild = true;
resizeHostWindow();
isResizingParentToFitChild = false;
}
}
void resized() override
{
if (pluginEditor != nullptr)
{
if (! isResizingParentToFitChild)
{
lastBounds = getLocalBounds();
isResizingChildToFitParent = true;
pluginEditor->setTopLeftPosition (0, 0);
pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
isResizingChildToFitParent = false;
}
}
}
void resizeHostWindow()
{
if (pluginEditor != nullptr)
{
auto b = getSizeToContainChild();
auto w = b.getWidth();
auto h = b.getHeight();
auto host = getHostType();
#if JUCE_WINDOWS
setSize (w, h);
#else
if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper()))
juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
#endif
if (owner.plugFrame != nullptr)
{
ViewRect newSize (0, 0, w, h);
isResizingParentToFitChild = true;
owner.plugFrame->resizeView (&owner, &newSize);
isResizingParentToFitChild = false;
#if JUCE_MAC
if (host.isWavelab() || host.isReaper())
#else
if (host.isWavelab())
#endif
setBounds (0, 0, w, h);
}
}
}
ScopedPointer<AudioProcessorEditor> pluginEditor;
private:
JuceVST3Editor& owner;
FakeMouseMoveGenerator fakeMouseGenerator;
Rectangle<int> lastBounds;
bool isResizingChildToFitParent = false;
bool isResizingParentToFitChild = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
};
//==============================================================================
ComSmartPtr<JuceVST3EditController> owner;
AudioProcessor& pluginInstance;
ScopedPointer<ContentWrapperComponent> component;
friend struct ContentWrapperComponent;
#if JUCE_MAC
void* macHostWindow = nullptr;
bool isNSView = false;
#endif
#if JUCE_WINDOWS
WindowsHooks hooks;
#endif
ScopedJuceInitialiser_GUI libraryInitialiser;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
};
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
};
namespace
{
template <typename FloatType> struct AudioBusPointerHelper {};
template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
template <typename FloatType> struct ChooseBufferHelper {};
template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
}
//==============================================================================
class JuceVST3Component : public Vst::IComponent,
public Vst::IAudioProcessor,
public Vst::IUnitInfo,
public Vst::IConnectionPoint,
public AudioPlayHead
{
public:
JuceVST3Component (Vst::IHostApplication* h)
: pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
host (h)
{
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
const int numConfigs = sizeof (configs) / sizeof (short[2]);
jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
#endif
// VST-3 requires your default layout to be non-discrete!
// For example, your default layout must be mono, stereo, quadrophonic
// and not AudioChannelSet::discreteChannels (2) etc.
jassert (checkBusFormatsAreNotDiscrete());
comPluginInstance = new JuceAudioProcessor (pluginInstance);
zerostruct (processContext);
processSetup.maxSamplesPerBlock = 1024;
processSetup.processMode = Vst::kRealtime;
processSetup.sampleRate = 44100.0;
processSetup.symbolicSampleSize = Vst::kSample32;
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
vstBypassParameterId = static_cast<Vst::ParamID> (pluginInstance->getNumParameters());
#else
cacheParameterIDs();
#endif
pluginInstance->setPlayHead (this);
}
~JuceVST3Component()
{
if (pluginInstance != nullptr)
if (pluginInstance->getPlayHead() == this)
pluginInstance->setPlayHead (nullptr);
}
//==============================================================================
AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
//==============================================================================
static const FUID iid;
JUCE_DECLARE_VST3_COM_REF_METHODS
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
{
comPluginInstance->addRef();
*obj = comPluginInstance;
return kResultOk;
}
*obj = nullptr;
return kNoInterface;
}
//==============================================================================
tresult PLUGIN_API initialize (FUnknown* hostContext) override
{
if (host != hostContext)
host.loadFrom (hostContext);
processContext.sampleRate = processSetup.sampleRate;
preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
return kResultTrue;
}
tresult PLUGIN_API terminate() override
{
getPluginInstance().releaseResources();
return kResultTrue;
}
//==============================================================================
tresult PLUGIN_API connect (IConnectionPoint* other) override
{
if (other != nullptr && juceVST3EditController == nullptr)
juceVST3EditController.loadFrom (other);
return kResultTrue;
}
tresult PLUGIN_API disconnect (IConnectionPoint*) override
{
juceVST3EditController = nullptr;
return kResultTrue;
}
tresult PLUGIN_API notify (Vst::IMessage* message) override
{
if (message != nullptr && juceVST3EditController == nullptr)
{
Steinberg::int64 value = 0;
if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
{
juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
if (juceVST3EditController != nullptr)
juceVST3EditController->setAudioProcessor (comPluginInstance);
else
jassertfalse;
}
}
return kResultTrue;
}
tresult PLUGIN_API getControllerClassId (TUID classID) override
{
memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
return kResultTrue;
}
//==============================================================================
tresult PLUGIN_API setActive (TBool state) override
{
if (! state)
{
getPluginInstance().releaseResources();
deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
}
else
{
auto sampleRate = getPluginInstance().getSampleRate();
auto bufferSize = getPluginInstance().getBlockSize();
sampleRate = processSetup.sampleRate > 0.0
? processSetup.sampleRate
: sampleRate;
bufferSize = processSetup.maxSamplesPerBlock > 0
? (int) processSetup.maxSamplesPerBlock
: bufferSize;
allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
preparePlugin (sampleRate, bufferSize);
}
return kResultOk;
}
tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
bool isBypassed() { return comPluginInstance->isBypassed; }
void setBypassed (bool bypassed) { comPluginInstance->isBypassed = bypassed; }
//==============================================================================
void writeJucePrivateStateInformation (MemoryOutputStream& out)
{
ValueTree privateData (kJucePrivateDataIdentifier);
// for now we only store the bypass value
privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
privateData.writeToStream (out);
}
void setJucePrivateStateInformation (const void* data, int sizeInBytes)
{
auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
}
void getStateInformation (MemoryBlock& destData)
{
pluginInstance->getStateInformation (destData);
// With bypass support, JUCE now needs to store private state data.
// Put this at the end of the plug-in state and add a few null characters
// so that plug-ins built with older versions of JUCE will hopefully ignore
// this data. Additionally, we need to add some sort of magic identifier
// at the very end of the private data so that JUCE has some sort of
// way to figure out if the data was stored with a newer JUCE version.
MemoryOutputStream extraData;
extraData.writeInt64 (0);
writeJucePrivateStateInformation (extraData);
auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
extraData.writeInt64 (privateDataSize);
extraData << kJucePrivateDataIdentifier;
// write magic string
destData.append (extraData.getData(), extraData.getDataSize());
}
void setStateInformation (const void* data, int sizeAsInt)
{
int64 size = sizeAsInt;
// Check if this data was written with a newer JUCE version
// and if it has the JUCE private data magic code at the end
auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
{
auto buffer = static_cast<const char*> (data);
String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
CharPointer_UTF8 (buffer + size));
if (magic == kJucePrivateDataIdentifier)
{
// found a JUCE private data section
uint64 privateDataSize;
std::memcpy (&privateDataSize,
buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
sizeof (uint64));
privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
if (privateDataSize > 0)
setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
size -= sizeof (uint64);
}
}
if (size >= 0)
pluginInstance->setStateInformation (data, static_cast<int> (size));
}
//==============================================================================
#if JUCE_VST3_CAN_REPLACE_VST2
void loadVST2VstWBlock (const char* data, int size)
{
auto headerLen = static_cast<int> (htonl (*(juce::int32*) (data + 4)));
auto bank = (const vst2FxBank*) (data + (8 + headerLen));
auto version = static_cast<int> (htonl (bank->version1)); ignoreUnused (version);
jassert ('VstW' == htonl (*(juce::int32*) data));
jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
jassert ('CcnK' == htonl (bank->magic1));
jassert ('FBCh' == htonl (bank->magic2));
jassert (version == 1 || version == 2);
jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
setStateInformation (bank->chunk,
jmin ((int) (size - (bank->chunk - data)),
(int) htonl (bank->chunkSize)));
}
bool loadVST3PresetFile (const char* data, int size)
{
if (size < 48)
return false;
// At offset 4 there's a little-endian version number which seems to typically be 1
// At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
jassert (entryCount > 0);
for (int i = 0; i < entryCount; ++i)
{
auto entryOffset = chunkListOffset + 8 + 20 * i;
if (entryOffset + 20 > size)
return false;
if (memcmp (data + entryOffset, "Comp", 4) == 0)
{
// "Comp" entries seem to contain the data.
auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
{
jassertfalse;
return false;
}
loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
}
}
return true;
}
bool loadVST2CompatibleState (const char* data, int size)
{
if (size < 4)
return false;
if (htonl (*(juce::int32*) data) == 'VstW')
{
loadVST2VstWBlock (data, size);
return true;
}
if (memcmp (data, "VST3", 4) == 0)
{
// In Cubase 5, when loading VST3 .vstpreset files,
// we get the whole content of the files to load.
// In Cubase 7 we get just the contents within and
// we go directly to the loadVST2VstW codepath instead.
return loadVST3PresetFile (data, size);
}
return false;
}
#endif
bool loadStateData (const void* data, int size)
{
#if JUCE_VST3_CAN_REPLACE_VST2
return loadVST2CompatibleState ((const char*) data, size);
#else
setStateInformation (data, size);
return true;
#endif
}
bool readFromMemoryStream (IBStream* state)
{
FUnknownPtr<ISizeableStream> s (state);
Steinberg::int64 size = 0;
if (s != nullptr
&& s->getStreamSize (size) == kResultOk
&& size > 0
&& size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
{
MemoryBlock block (static_cast<size_t> (size));
// turns out that Cubase 9 might give you the incorrect stream size :-(
Steinberg::int32 bytesRead = 1;
int len;
for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
break;
if (len == 0)
return false;
block.setSize (static_cast<size_t> (len));
// Adobe Audition CS6 hack to avoid trying to use corrupted streams:
if (getHostType().isAdobeAudition())
if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
return false;
return loadStateData (block.getData(), (int) block.getSize());
}
return false;
}
bool readFromUnknownStream (IBStream* state)
{
MemoryOutputStream allData;
{
const size_t bytesPerBlock = 4096;
HeapBlock<char> buffer (bytesPerBlock);
for (;;)
{
Steinberg::int32 bytesRead = 0;
auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
break;
allData.write (buffer, static_cast<size_t> (bytesRead));
}
}
const size_t dataSize = allData.getDataSize();
return dataSize > 0 && dataSize < 0x7fffffff
&& loadStateData (allData.getData(), (int) dataSize);
}
tresult PLUGIN_API setState (IBStream* state) override
{
if (state == nullptr)
return kInvalidArgument;
FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
{
if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
return kResultTrue;
if (readFromUnknownStream (state))
return kResultTrue;
}
return kResultFalse;
}
#if JUCE_VST3_CAN_REPLACE_VST2
static tresult writeVST2Int (IBStream* state, int n)
{
juce::int32 t = (juce::int32) htonl (n);
return state->write (&t, 4);
}
static tresult writeVST2Header (IBStream* state, bool bypassed)
{
tresult status = writeVST2Int (state, 'VstW');
if (status == kResultOk) status = writeVST2Int (state, 8); // header size
if (status == kResultOk) status = writeVST2Int (state, 1); // version
if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
return status;
}
#endif
tresult PLUGIN_API getState (IBStream* state) override
{
if (state == nullptr)
return kInvalidArgument;
juce::MemoryBlock mem;
getStateInformation (mem);
#if JUCE_VST3_CAN_REPLACE_VST2
tresult status = writeVST2Header (state, isBypassed());
if (status != kResultOk)
return status;
const int bankBlockSize = 160;
vst2FxBank bank;
zerostruct (bank);
bank.magic1 = (int32) htonl ('CcnK');
bank.size = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
bank.magic2 = (int32) htonl ('FBCh');
bank.version1 = (int32) htonl (2);
bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
bank.version2 = (int32) htonl (JucePlugin_VersionCode);
bank.chunkSize = (int32) htonl ((unsigned int) mem.getSize());
status = state->write (&bank, bankBlockSize);
if (status != kResultOk)
return status;
#endif
return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
}
//==============================================================================
Steinberg::int32 PLUGIN_API getUnitCount() override
{
return 1;
}
tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
{
if (unitIndex == 0)
{
info.id = Vst::kRootUnitId;
info.parentUnitId = Vst::kNoParentUnitId;
info.programListId = Vst::kNoProgramListId;
toString128 (info.name, TRANS("Root Unit"));
return kResultTrue;
}
zerostruct (info);
return kResultFalse;
}
Steinberg::int32 PLUGIN_API getProgramListCount() override
{
if (getPluginInstance().getNumPrograms() > 0)
return 1;
return 0;
}
tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
{
if (listIndex == 0)
{
info.id = JuceVST3EditController::paramPreset;
info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
toString128 (info.name, TRANS("Factory Presets"));
return kResultTrue;
}
jassertfalse;
zerostruct (info);
return kResultFalse;
}
tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
{
if (listId == JuceVST3EditController::paramPreset
&& isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
{
toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
return kResultTrue;
}
jassertfalse;
toString128 (name, juce::String());
return kResultFalse;
}
tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
{
zerostruct (unitId);
return kNotImplemented;
}
//==============================================================================
bool getCurrentPosition (CurrentPositionInfo& info) override
{
info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
info.timeInSeconds = processContext.systemTime / 1000000000.0;
info.bpm = jmax (1.0, processContext.tempo);
info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
info.ppqPosition = processContext.projectTimeMusic;
info.ppqLoopStart = processContext.cycleStartMusic;
info.ppqLoopEnd = processContext.cycleEndMusic;
info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
info.editOriginTime = 0.0;
info.frameRate = AudioPlayHead::fpsUnknown;
if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
{
switch (processContext.frameRate.framesPerSecond)
{
case 24: info.frameRate = AudioPlayHead::fps24; break;
case 25: info.frameRate = AudioPlayHead::fps25; break;
case 29: info.frameRate = AudioPlayHead::fps30drop; break;
case 30:
{
if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
info.frameRate = AudioPlayHead::fps30drop;
else
info.frameRate = AudioPlayHead::fps30;
}
break;
default: break;
}
}
return true;
}
//==============================================================================
int getNumAudioBuses (bool isInput) const
{
int busCount = pluginInstance->getBusCount (isInput);
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
const int numConfigs = sizeof (configs) / sizeof (short[2]);
bool hasOnlyZeroChannels = true;
for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
if (configs[i][isInput ? 0 : 1] != 0)
hasOnlyZeroChannels = false;
busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
#endif
return busCount;
}
//==============================================================================
Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
{
if (type == Vst::kAudio)
return getNumAudioBuses (dir == Vst::kInput);
if (type == Vst::kEvent)
{
if (dir == Vst::kInput)
return isMidiInputBusEnabled ? 1 : 0;
if (dir == Vst::kOutput)
return isMidiOutputBusEnabled ? 1 : 0;
}
return 0;
}
tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
Steinberg::int32 index, Vst::BusInfo& info) override
{
if (type == Vst::kAudio)
{
if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
return kResultFalse;
if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
{
info.mediaType = Vst::kAudio;
info.direction = dir;
info.channelCount = bus->getLastEnabledLayout().size();
toString128 (info.name, bus->getName());
#if JucePlugin_IsSynth
info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
#else
info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
#endif
info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
return kResultTrue;
}
}
if (type == Vst::kEvent)
{
info.flags = Vst::BusInfo::kDefaultActive;
#if JucePlugin_WantsMidiInput
if (dir == Vst::kInput && index == 0)
{
info.mediaType = Vst::kEvent;
info.direction = dir;
info.channelCount = 16;
toString128 (info.name, TRANS("MIDI Input"));
info.busType = Vst::kMain;
return kResultTrue;
}
#endif
#if JucePlugin_ProducesMidiOutput
if (dir == Vst::kOutput && index == 0)
{
info.mediaType = Vst::kEvent;
info.direction = dir;
info.channelCount = 16;
toString128 (info.name, TRANS("MIDI Output"));
info.busType = Vst::kMain;
return kResultTrue;
}
#endif
}
zerostruct (info);
return kResultFalse;
}
tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
{
if (type == Vst::kEvent)
{
if (index != 0)
return kResultFalse;
if (dir == Vst::kInput)
isMidiInputBusEnabled = (state != 0);
else
isMidiOutputBusEnabled = (state != 0);
return kResultTrue;
}
if (type == Vst::kAudio)
{
if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
return kResultFalse;
if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
{
#ifdef JucePlugin_PreferredChannelConfigurations
auto newLayout = pluginInstance->getBusesLayout();
auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
(dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
return kResultFalse;
#endif
return bus->enable (state != 0) ? kResultTrue : kResultFalse;
}
}
return kResultFalse;
}
bool checkBusFormatsAreNotDiscrete()
{
auto numInputBuses = pluginInstance->getBusCount (true);
auto numOutputBuses = pluginInstance->getBusCount (false);
for (int i = 0; i < numInputBuses; ++i)
if (pluginInstance->getChannelLayoutOfBus (true, i).isDiscreteLayout())
return false;
for (int i = 0; i < numOutputBuses; ++i)
if (pluginInstance->getChannelLayoutOfBus (false, i).isDiscreteLayout())
return false;
return true;
}
tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
{
auto numInputBuses = pluginInstance->getBusCount (true);
auto numOutputBuses = pluginInstance->getBusCount (false);
if (numIns > numInputBuses || numOuts > numOutputBuses)
return false;
auto requested = pluginInstance->getBusesLayout();
for (int i = 0; i < numIns; ++i)
requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
for (int i = 0; i < numOuts; ++i)
requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
if (! AudioProcessor::containsLayout (requested, configs))
return kResultFalse;
#endif
return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
}
tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
{
if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
{
arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
return kResultTrue;
}
return kResultFalse;
}
//==============================================================================
tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
{
return (symbolicSampleSize == Vst::kSample32
|| (getPluginInstance().supportsDoublePrecisionProcessing()
&& symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
}
Steinberg::uint32 PLUGIN_API getLatencySamples() override
{
return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
}
tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
{
if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
return kResultFalse;
processSetup = newSetup;
processContext.sampleRate = processSetup.sampleRate;
getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
? AudioProcessor::doublePrecision
: AudioProcessor::singlePrecision);
preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
return kResultTrue;
}
tresult PLUGIN_API setProcessing (TBool state) override
{
if (! state)
getPluginInstance().reset();
return kResultTrue;
}
Steinberg::uint32 PLUGIN_API getTailSamples() override
{
auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
return Vst::kNoTail;
return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
}
//==============================================================================
void processParameterChanges (Vst::IParameterChanges& paramChanges)
{
jassert (pluginInstance != nullptr);
auto numParamsChanged = paramChanges.getParameterCount();
for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
{
if (auto* paramQueue = paramChanges.getParameterData (i))
{
auto numPoints = paramQueue->getPointCount();
Steinberg::int32 offsetSamples = 0;
double value = 0.0;
if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
{
auto vstParamID = paramQueue->getParameterId();
if (vstParamID == vstBypassParameterId)
setBypassed (static_cast<float> (value) != 0.0f);
#if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
#endif
else if (vstParamID == JuceVST3EditController::paramPreset)
{
auto numPrograms = pluginInstance->getNumPrograms();
auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
&& programValue != pluginInstance->getCurrentProgram())
pluginInstance->setCurrentProgram (programValue);
}
else
{
auto index = getJuceIndexForVSTParamID (vstParamID);
if (isPositiveAndBelow (index, pluginInstance->getNumParameters()))
pluginInstance->setParameter (index, static_cast<float> (value));
}
}
}
}
}
void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
{
// If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
int channel, ctrlNumber;
if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
{
if (ctrlNumber == Vst::kAfterTouch)
midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
else if (ctrlNumber == Vst::kPitchBend)
midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
else
midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
jlimit (0, 127, ctrlNumber),
jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
}
}
tresult PLUGIN_API process (Vst::ProcessData& data) override
{
if (pluginInstance == nullptr)
return kResultFalse;
if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
return kResultFalse;
if (data.processContext != nullptr)
processContext = *data.processContext;
else
zerostruct (processContext);
midiBuffer.clear();
#if JucePlugin_WantsMidiInput
if (data.inputEvents != nullptr)
MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
#endif
if (getHostType().isWavelab())
{
const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
&& (numInputChans + numOutputChans) == 0)
return kResultFalse;
}
if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
else jassertfalse;
#if JucePlugin_ProducesMidiOutput
if (data.outputEvents != nullptr)
MidiEventList::toEventList (*data.outputEvents, midiBuffer);
#endif
return kResultTrue;
}
private:
//==============================================================================
Atomic<int> refCount { 1 };
AudioProcessor* pluginInstance;
ComSmartPtr<Vst::IHostApplication> host;
ComSmartPtr<JuceAudioProcessor> comPluginInstance;
ComSmartPtr<JuceVST3EditController> juceVST3EditController;
/**
Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
this object needs to be copied on every call to process() to be up-to-date...
*/
Vst::ProcessContext processContext;
Vst::ProcessSetup processSetup;
MidiBuffer midiBuffer;
Array<float*> channelListFloat;
Array<double*> channelListDouble;
AudioBuffer<float> emptyBufferFloat;
AudioBuffer<double> emptyBufferDouble;
#if JucePlugin_WantsMidiInput
bool isMidiInputBusEnabled = true;
#else
bool isMidiInputBusEnabled = false;
#endif
#if JucePlugin_ProducesMidiOutput
bool isMidiOutputBusEnabled = true;
#else
bool isMidiOutputBusEnabled = false;
#endif
ScopedJuceInitialiser_GUI libraryInitialiser;
#if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
bool usingManagedParameter;
Array<Vst::ParamID> vstParamIDs;
HashMap<int32, int> paramMap;
#endif
Vst::ParamID vstBypassParameterId;
static const char* kJucePrivateDataIdentifier;
//==============================================================================
template <typename FloatType>
void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
{
int totalInputChans = 0, totalOutputChans = 0;
bool tmpBufferNeedsClearing = false;
auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
// Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
int vstInputs;
for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
&& data.inputs[vstInputs].numChannels > 0)
break;
int vstOutputs;
for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
&& data.outputs[vstOutputs].numChannels > 0)
break;
{
auto n = jmax (vstOutputs, getNumAudioBuses (false));
for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
{
if (bus < vstOutputs)
{
if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
{
auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
for (int i = 0; i < numChans; ++i)
{
if (auto dst = busChannels[i])
{
if (totalOutputChans >= plugInInputChannels)
FloatVectorOperations::clear (dst, (int) data.numSamples);
channelList.set (totalOutputChans++, busChannels[i]);
}
}
}
}
else
{
const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
for (int i = 0; i < numChans; ++i)
{
if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
{
tmpBufferNeedsClearing = true;
channelList.set (totalOutputChans++, tmpBuffer);
}
else
return;
}
}
}
}
{
auto n = jmax (vstInputs, getNumAudioBuses (true));
for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
{
if (bus < vstInputs)
{
if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
{
const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
for (int i = 0; i < numChans; ++i)
{
if (busChannels[i] != nullptr)
{
if (totalInputChans >= totalOutputChans)
channelList.set (totalInputChans, busChannels[i]);
else
{
auto* dst = channelList.getReference (totalInputChans);
auto* src = busChannels[i];
if (dst != src)
FloatVectorOperations::copy (dst, src, (int) data.numSamples);
}
}
++totalInputChans;
}
}
}
else
{
auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
for (int i = 0; i < numChans; ++i)
{
if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
{
tmpBufferNeedsClearing = true;
channelList.set (totalInputChans++, tmpBuffer);
}
else
return;
}
}
}
}
if (tmpBufferNeedsClearing)
ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
AudioBuffer<FloatType> buffer;
if (int totalChans = jmax (totalOutputChans, totalInputChans))
buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
{
const ScopedLock sl (pluginInstance->getCallbackLock());
pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
if (data.inputParameterChanges != nullptr)
processParameterChanges (*data.inputParameterChanges);
#if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
const int numMidiEventsComingIn = midiBuffer.getNumEvents();
#endif
if (pluginInstance->isSuspended())
{
buffer.clear();
}
else
{
if (totalInputChans == pluginInstance->getTotalNumInputChannels()
&& totalOutputChans == pluginInstance->getTotalNumOutputChannels())
{
if (isBypassed())
pluginInstance->processBlockBypassed (buffer, midiBuffer);
else
pluginInstance->processBlock (buffer, midiBuffer);
}
}
#if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
/* This assertion is caused when you've added some events to the
midiMessages array in your processBlock() method, which usually means
that you're trying to send them somewhere. But in this case they're
getting thrown away.
If your plugin does want to send MIDI messages, you'll need to set
the JucePlugin_ProducesMidiOutput macro to 1 in your
JucePluginCharacteristics.h file.
If you don't want to produce any MIDI output, then you should clear the
midiMessages array at the end of your processBlock() method, to
indicate that you don't want any of the events to be passed through
to the output.
*/
jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
#endif
}
}
//==============================================================================
template <typename FloatType>
void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
{
channelList.clearQuick();
channelList.insertMultiple (0, nullptr, 128);
auto& p = getPluginInstance();
buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
buffer.clear();
}
template <typename FloatType>
void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
{
channelList.clearQuick();
channelList.resize (0);
buffer.setSize (0, 0);
}
template <typename FloatType>
static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
{
return AudioBusPointerHelper<FloatType>::impl (data);
}
template <typename FloatType>
FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
{
auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
// we can't do anything if the host requests to render many more samples than the
// block size, we need to bail out
if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
return nullptr;
return buffer.getWritePointer (channel);
}
void preparePlugin (double sampleRate, int bufferSize)
{
auto& p = getPluginInstance();
p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
p.prepareToPlay (sampleRate, bufferSize);
}
//==============================================================================
#if JUCE_FORCE_USE_LEGACY_PARAM_IDS
inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept { return static_cast<Vst::ParamID> (paramIndex); }
inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept { return static_cast<int> (paramID); }
#else
void cacheParameterIDs()
{
const int numParameters = pluginInstance->getNumParameters();
usingManagedParameter = (pluginInstance->getParameters().size() == numParameters);
vstBypassParameterId = static_cast<Vst::ParamID> (usingManagedParameter ? JuceVST3EditController::paramBypass : numParameters);
for (int i = 0; i < numParameters; ++i)
{
auto paramID = JuceVST3EditController::generateVSTParamIDForIndex (pluginInstance, i);
// Consider yourself very unlucky if you hit this assertion. The hash code of your
// parameter ids are not unique.
jassert (! vstParamIDs.contains (paramID));
vstParamIDs.add (paramID);
paramMap.set (static_cast<int32> (paramID), i);
}
}
inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
{
return usingManagedParameter ? vstParamIDs.getReference (paramIndex)
: static_cast<Vst::ParamID> (paramIndex);
}
inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept
{
return usingManagedParameter ? paramMap[static_cast<int32> (paramID)]
: static_cast<int> (paramID);
}
#endif
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
};
const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
//==============================================================================
#if JUCE_MSVC
#pragma warning (push, 0)
#pragma warning (disable: 4310)
#elif JUCE_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wall"
#endif
DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
DEF_CLASS_IID (JuceAudioProcessor)
#if JUCE_VST3_CAN_REPLACE_VST2
FUID getFUIDForVST2ID (bool forControllerUID)
{
TUID uuid;
extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
return FUID (uuid);
}
const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
#else
DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
DEF_CLASS_IID (JuceVST3EditController)
DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
DEF_CLASS_IID (JuceVST3Component)
#endif
#if JUCE_MSVC
#pragma warning (pop)
#elif JUCE_CLANG
#pragma clang diagnostic pop
#endif
//==============================================================================
bool initModule()
{
#if JUCE_MAC
initialiseMacVST();
#endif
return true;
}
bool shutdownModule()
{
return true;
}
#undef JUCE_EXPORTED_FUNCTION
#if JUCE_WINDOWS
extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
#define JUCE_EXPORTED_FUNCTION
#else
#define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
CFBundleRef globalBundleInstance = nullptr;
juce::uint32 numBundleRefs = 0;
juce::Array<CFBundleRef> bundleRefs;
enum { MaxPathLength = 2048 };
char modulePath[MaxPathLength] = { 0 };
void* moduleHandle = nullptr;
JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
{
if (ref != nullptr)
{
++numBundleRefs;
CFRetain (ref);
bundleRefs.add (ref);
if (moduleHandle == nullptr)
{
globalBundleInstance = ref;
moduleHandle = ref;
CFURLRef tempURL = CFBundleCopyBundleURL (ref);
CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
CFRelease (tempURL);
}
}
return initModule();
}
JUCE_EXPORTED_FUNCTION bool bundleExit()
{
if (shutdownModule())
{
if (--numBundleRefs == 0)
{
for (int i = 0; i < bundleRefs.size(); ++i)
CFRelease (bundleRefs.getUnchecked (i));
bundleRefs.clear();
}
return true;
}
return false;
}
#endif
//==============================================================================
/** This typedef represents VST3's createInstance() function signature */
typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
static FUnknown* createComponentInstance (Vst::IHostApplication* host)
{
return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
}
static FUnknown* createControllerInstance (Vst::IHostApplication* host)
{
return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
}
//==============================================================================
struct JucePluginFactory;
static JucePluginFactory* globalFactory = nullptr;
//==============================================================================
struct JucePluginFactory : public IPluginFactory3
{
JucePluginFactory()
: factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
{
}
virtual ~JucePluginFactory()
{
if (globalFactory == this)
globalFactory = nullptr;
}
//==============================================================================
bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
{
if (createFunction == nullptr)
{
jassertfalse;
return false;
}
auto* entry = classes.add (new ClassEntry (info, createFunction));
entry->infoW.fromAscii (info);
return true;
}
bool isClassRegistered (const FUID& cid) const
{
for (int i = 0; i < classes.size(); ++i)
if (classes.getUnchecked (i)->infoW.cid == cid)
return true;
return false;
}
//==============================================================================
JUCE_DECLARE_VST3_COM_REF_METHODS
tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
{
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
jassertfalse; // Something new?
*obj = nullptr;
return kNotImplemented;
}
//==============================================================================
Steinberg::int32 PLUGIN_API countClasses() override
{
return (Steinberg::int32) classes.size();
}
tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
{
if (info == nullptr)
return kInvalidArgument;
memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
return kResultOk;
}
tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
{
return getPClassInfo<PClassInfo> (index, info);
}
tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
{
return getPClassInfo<PClassInfo2> (index, info);
}
tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
{
if (info != nullptr)
{
if (auto* entry = classes[(int) index])
{
memcpy (info, &entry->infoW, sizeof (PClassInfoW));
return kResultOk;
}
}
return kInvalidArgument;
}
tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
{
*obj = nullptr;
FUID sourceFuid = sourceIid;
if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
{
jassertfalse; // The host you're running in has severe implementation issues!
return kInvalidArgument;
}
TUID iidToQuery;
sourceFuid.toTUID (iidToQuery);
for (auto* entry : classes)
{
if (doUIDsMatch (entry->infoW.cid, cid))
{
if (auto* instance = entry->createFunction (host))
{
const FReleaser releaser (instance);
if (instance->queryInterface (iidToQuery, obj) == kResultOk)
return kResultOk;
}
break;
}
}
return kNoInterface;
}
tresult PLUGIN_API setHostContext (FUnknown* context) override
{
host.loadFrom (context);
if (host != nullptr)
{
Vst::String128 name;
host->getName (name);
return kResultTrue;
}
return kNotImplemented;
}
private:
//==============================================================================
ScopedJuceInitialiser_GUI libraryInitialiser;
Atomic<int> refCount { 1 };
const PFactoryInfo factoryInfo;
ComSmartPtr<Vst::IHostApplication> host;
//==============================================================================
struct ClassEntry
{
ClassEntry() noexcept {}
ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
: info2 (info), createFunction (fn) {}
PClassInfo2 info2;
PClassInfoW infoW;
CreateFunction createFunction = {};
bool isUnicode = false;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
};
OwnedArray<ClassEntry> classes;
//==============================================================================
template<class PClassInfoType>
tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
{
if (info != nullptr)
{
zerostruct (*info);
if (auto* entry = classes[(int) index])
{
if (entry->isUnicode)
return kResultFalse;
memcpy (info, &entry->info2, sizeof (PClassInfoType));
return kResultOk;
}
}
jassertfalse;
return kInvalidArgument;
}
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
};
} // juce namespace
//==============================================================================
#ifndef JucePlugin_Vst3ComponentFlags
#if JucePlugin_IsSynth
#define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
#else
#define JucePlugin_Vst3ComponentFlags 0
#endif
#endif
#ifndef JucePlugin_Vst3Category
#if JucePlugin_IsSynth
#define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
#else
#define JucePlugin_Vst3Category Vst::PlugType::kFx
#endif
#endif
//==============================================================================
// The VST3 plugin entry point.
JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
{
PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
#if JUCE_WINDOWS
// Cunning trick to force this function to be exported. Life's too short to
// faff around creating .def files for this kind of thing.
#pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
#endif
if (globalFactory == nullptr)
{
globalFactory = new JucePluginFactory();
static const PClassInfo2 componentClass (JuceVST3Component::iid,
PClassInfo::kManyInstances,
kVstAudioEffectClass,
JucePlugin_Name,
JucePlugin_Vst3ComponentFlags,
JucePlugin_Vst3Category,
JucePlugin_Manufacturer,
JucePlugin_VersionString,
kVstVersionString);
globalFactory->registerClass (componentClass, createComponentInstance);
static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
PClassInfo::kManyInstances,
kVstComponentControllerClass,
JucePlugin_Name,
JucePlugin_Vst3ComponentFlags,
JucePlugin_Vst3Category,
JucePlugin_Manufacturer,
JucePlugin_VersionString,
kVstVersionString);
globalFactory->registerClass (controllerClass, createControllerInstance);
}
else
{
globalFactory->addRef();
}
return dynamic_cast<IPluginFactory*> (globalFactory);
}
//==============================================================================
#if _MSC_VER || JUCE_MINGW
extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
#endif
#endif //JucePlugin_Build_VST3
|
gpl-3.0
|
RumAngelov/ConvPlugin
|
JuceLibraryCode/modules/juce_core/maths/juce_Random.cpp
|
4583
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
Random::Random (const int64 seedValue) noexcept : seed (seedValue)
{
}
Random::Random() : seed (1)
{
setSeedRandomly();
}
Random::~Random() noexcept
{
}
void Random::setSeed (const int64 newSeed) noexcept
{
seed = newSeed;
}
void Random::combineSeed (const int64 seedValue) noexcept
{
seed ^= nextInt64() ^ seedValue;
}
void Random::setSeedRandomly()
{
static int64 globalSeed = 0;
combineSeed (globalSeed ^ (int64) (pointer_sized_int) this);
combineSeed (Time::getMillisecondCounter());
combineSeed (Time::getHighResolutionTicks());
combineSeed (Time::getHighResolutionTicksPerSecond());
combineSeed (Time::currentTimeMillis());
globalSeed ^= seed;
}
Random& Random::getSystemRandom() noexcept
{
static Random sysRand;
return sysRand;
}
//==============================================================================
int Random::nextInt() noexcept
{
seed = (seed * 0x5deece66dLL + 11) & 0xffffffffffffLL;
return (int) (seed >> 16);
}
int Random::nextInt (const int maxValue) noexcept
{
jassert (maxValue > 0);
return (int) ((((unsigned int) nextInt()) * (uint64) maxValue) >> 32);
}
int Random::nextInt (Range<int> range) noexcept
{
return range.getStart() + nextInt (range.getLength());
}
int64 Random::nextInt64() noexcept
{
return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
}
bool Random::nextBool() noexcept
{
return (nextInt() & 0x40000000) != 0;
}
float Random::nextFloat() noexcept
{
return static_cast<uint32> (nextInt()) / (std::numeric_limits<uint32>::max() + 1.0f);
}
double Random::nextDouble() noexcept
{
return static_cast<uint32> (nextInt()) / (std::numeric_limits<uint32>::max() + 1.0);
}
BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
{
BigInteger n;
do
{
fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
}
while (n >= maximumValue);
return n;
}
void Random::fillBitsRandomly (void* const buffer, size_t bytes)
{
int* d = static_cast<int*> (buffer);
for (; bytes >= sizeof (int); bytes -= sizeof (int))
*d++ = nextInt();
if (bytes > 0)
{
const int lastBytes = nextInt();
memcpy (d, &lastBytes, bytes);
}
}
void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
{
arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
while ((startBit & 31) != 0 && numBits > 0)
{
arrayToChange.setBit (startBit++, nextBool());
--numBits;
}
while (numBits >= 32)
{
arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
startBit += 32;
numBits -= 32;
}
while (--numBits >= 0)
arrayToChange.setBit (startBit + numBits, nextBool());
}
//==============================================================================
#if JUCE_UNIT_TESTS
class RandomTests : public UnitTest
{
public:
RandomTests() : UnitTest ("Random", "Maths") {}
void runTest() override
{
beginTest ("Random");
Random r = getRandom();
for (int i = 2000; --i >= 0;)
{
expect (r.nextDouble() >= 0.0 && r.nextDouble() < 1.0);
expect (r.nextFloat() >= 0.0f && r.nextFloat() < 1.0f);
expect (r.nextInt (5) >= 0 && r.nextInt (5) < 5);
expect (r.nextInt (1) == 0);
int n = r.nextInt (50) + 1;
expect (r.nextInt (n) >= 0 && r.nextInt (n) < n);
n = r.nextInt (0x7ffffffe) + 1;
expect (r.nextInt (n) >= 0 && r.nextInt (n) < n);
}
}
};
static RandomTests randomTests;
#endif
|
gpl-3.0
|
Themaister/RSound
|
binds/cs/RSound.cs
|
2800
|
using System;
using System.Runtime.InteropServices;
namespace RSound
{
public unsafe class AudioStream : IDisposable
{
public enum Format : int
{
RSD_S16_LE = 0x0001,
RSD_S16_BE = 0x0002,
RSD_U16_LE = 0x0004,
RSD_U16_BE = 0x0008,
RSD_U8 = 0x0010,
RSD_S8 = 0x0020,
RSD_S16_NE = 0x0040,
RSD_U16_NE = 0x0080,
RSD_ALAW = 0x0100,
RSD_MULAW = 0x0200,
RSD_S32_LE = 0x0400,
RSD_S32_BE = 0x0800,
RSD_S32_NE = 0x1000,
RSD_U32_LE = 0x2000,
RSD_U32_BE = 0x4000,
RSD_U32_NE = 0x8000,
}
private void* rd;
#if win32
private const string library = "rsound.dll";
#else
private const string library = "librsound.so";
#endif
[DllImport(library)]
private static extern int rsd_simple_start(void** rd, string host, string port,
string ident, int rate, int channels, int format);
[DllImport(library)]
private static extern IntPtr rsd_write(void* rd, void* buffer, IntPtr size);
[DllImport(library)]
private static extern int rsd_free(void* rd);
[DllImport(library)]
private static extern int rsd_stop(void* rd);
[DllImport(library)]
private static extern IntPtr rsd_get_avail(void* rd);
[DllImport(library)]
private static extern IntPtr rsd_delay_ms(void* rd);
public AudioStream(int rate, int channels, Format fmt, string host = null, string port = null, string ident = null)
{
this.rd = null;
int rc;
fixed (void **ptr = &this.rd)
{
rc = rsd_simple_start(ptr, host, port, ident, rate, channels, (int)fmt);
}
if (rc < 0)
{
throw new Exception("Couldn't connect to server.");
}
}
public void Write(byte[] buffer)
{
IntPtr rc;
fixed (byte *ptr = buffer)
{
rc = rsd_write(this.rd, ptr, (IntPtr)buffer.Length);
}
if (rc == (IntPtr)0)
{
throw new Exception("Connection closed.");
}
}
public float Delay()
{
IntPtr ms = rsd_delay_ms(this.rd);
return (float)ms / (float)1000.0;
}
public void Dispose()
{
if (this.rd != null)
{
rsd_stop(this.rd);
rsd_free(this.rd);
this.rd = null;
}
}
public int WriteAvail()
{
IntPtr avail = rsd_get_avail(this.rd);
return (int)avail;
}
~AudioStream()
{
if (this.rd != null)
{
rsd_stop(this.rd);
rsd_free(this.rd);
}
}
}
}
|
gpl-3.0
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
|
src/lduSolvers/lduSolver/bicgStabSolver/bicgStabSolver.H
|
3296
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
bicgStabSolver
Description
Preconditioned Bi-Conjugate Gradient stabilised solver with run-time
selectable preconditioning.
Author
Hrvoje Jasak, Wikki Ltd. All rights reserved.
SourceFiles
bicgStabSolver.C
\*---------------------------------------------------------------------------*/
#ifndef bicgStabSolver_H
#define bicgStabSolver_H
#include "lduMatrix.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class bicgStabSolver Declaration
\*---------------------------------------------------------------------------*/
class bicgStabSolver
:
public lduSolver
{
// Private data
//- Preconditioner
autoPtr<lduPreconditioner> preconPtr_;
// Private Member Functions
//- Disallow default bitwise copy construct
bicgStabSolver(const bicgStabSolver&);
//- Disallow default bitwise assignment
void operator=(const bicgStabSolver&);
public:
//- Runtime type information
TypeName("BiCGStab");
// Constructors
//- Construct from matrix components and solver data stream
bicgStabSolver
(
const word& fieldName,
const lduMatrix& matrix,
const FieldField<Field, scalar>& coupleBouCoeffs,
const FieldField<Field, scalar>& coupleIntCoeffs,
const lduInterfaceFieldPtrsList& interfaces,
const dictionary& dict
);
// Destructor
virtual ~bicgStabSolver()
{}
// Member Functions
//- Solve the matrix with this solver
virtual lduSolverPerformance solve
(
scalarField& x,
const scalarField& b,
const direction cmpt = 0
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
gpl-3.0
|
socialplanning/opencore
|
opencore/project/browser/projpage.js
|
8161
|
/*
On page load, the SortableManager:
- Finds the table by its id (sortable_table).
- Parses its thead for columns with a "mochi:format" attribute.
- Parses the data out of the tbody based upon information given in the
"mochi:format" attribute, and clones the tr elements for later re-use.
- Clones the column header th elements for use as a template when drawing
sort arrow columns.
- Stores away a reference to the tbody, as it will be replaced on each sort.
- Performs the first sort.
On sort request:
- Sorts the data based on the given key and direction
- Creates a new tbody from the rows in the new ordering
- Replaces the column header th elements with clickable versions, adding an
indicator (↑ or ↓) to the most recently sorted column.
*/
function trimString (str) {
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
String.prototype.trim = trimString;
SortableManager = function () {
this.thead = null;
this.tbody = null;
this.columns = [];
this.rows = [];
this.sortState = {};
this.sortkey = 0;
};
mouseOverFunc = function () {
addElementClass(this, "over");
};
mouseOutFunc = function () {
removeElementClass(this, "over");
};
ignoreEvent = function (ev) {
if (ev && ev.preventDefault) {
ev.preventDefault();
ev.stopPropagation();
} else if (typeof(event) != 'undefined') {
event.cancelBubble = false;
event.returnValue = false;
}
};
var showThisMany=10
update(
SortableManager.prototype, {
"showAllHandler": function(link) {
link.onmousedown = ignoreEvent;
link.onclick=this.onLetterClick('all');
},
"loadLetterHandlers": function(letterlist) {
/***
setup handlers for alphabet
***/
//get links
var lis = letterlist.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
var li = lis[i];
link=li.getElementsByTagName('a')[0];
link.onmousedown = ignoreEvent;
letter=link.getAttribute("name");
link.onclick = this.onLetterClick(letter.trim());
}
},
"initWithTable": function (table) {
/***
Initialize the SortableManager with a table object
***/
// Find the thead
this.thead = table.getElementsByTagName('thead')[0];
// get the mochi:format key and contents for each column header
var cols = this.thead.getElementsByTagName('th');
for (var i = 0; i < cols.length; i++) {
var node = cols[i];
var attr = null;
try {
attr = node.getAttribute("mochi:format");
} catch (err) {
// pass
}
var o = node.childNodes;
this.columns.push({
"format": attr,
"element": node,
"proto": node.cloneNode(true)
});
}
// scrape the tbody for data
this.tbody = table.getElementsByTagName('tbody')[0];
// every row
var rows = this.tbody.getElementsByTagName('tr');
log("rows " + rows.length)
for (var i = 0; i < rows.length; i++) {
// every cell
var row = rows[i];
var cols = row.getElementsByTagName('td');
var rowData = [];
for (var j = 0; j < cols.length; j++) {
// scrape the text and build the appropriate object out of it
var cell = cols[j];
var obj = scrapeText(cell);
switch (this.columns[j].format) {
case 'isodate':
obj = isoDate(obj);
break;
case 'str':
break;
case 'istr':
obj = obj.toLowerCase();
break;
// cases for numbers, etc. could be here
default:
break;
}
rowData.push(obj);
}
// stow away a reference to the TR and save it
rowData.row = row.cloneNode(true);
this.rows.push(rowData);
}
// do initial sort on first column
this.drawSortedRows(this.sortkey, true, false, false);
},
"onSortClick": function (name) {
/***
Return a sort function for click events
***/
return bind(function () {
log('onSortClick', name);
var order = this.sortState[name];
if (order == null) {
order = true;
} else if (name == this.sortkey) {
order = !order;
}
this.drawSortedRows(name, order, true, false);
}, this);
},
"onLetterClick": function (letter) {
/***
Return a sort function for click events
on little alphabet
***/
return bind(function () {
this.drawSortedRows(0, true, true, letter);
}, this);
},
"setVisibility": function(rows, regex) {
/*** makes rows uncollapse and collapse by regex ***/
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
row.style.display = "";
if(regex){
cell = row.getElementsByTagName('td')[0];
var txt = ''
if (cell.textContent) {
txt = cell.textContent;
}
else if (cell.innerText) {
txt = cell.innerText;
}
if(!txt.trim().match(regex)){
row.style.display = "none"; /* visibility='collapsed'; */
}
}
}
},
"drawSortedRows":
function (key, forward, clicked, letter) {
/***
Draw the new sorted table body, and modify the column headers
if appropriate
***/
log('drawSortedRows', key, forward);
this.sortkey = key;
// sort based on the state given (forward or reverse)
var cmp = (forward ? keyComparator : reverseKeyComparator);
this.rows.sort(cmp(key));
if(!letter){
// save it so we can flip next time
this.sortState[key] = forward;
}
// get every "row" element from this.rows and make a new tbody
var newBody = TBODY(null, map(itemgetter("row"), this.rows));
// swap in the new tbody
this.tbody = swapDOM(this.tbody, newBody);
//do letter check
if (letter){
var rows = this.tbody.getElementsByTagName('tr');
if(letter != 'all'){
var regex = "^["+letter+letter.toUpperCase()+"]+";
log("re:" + regex);
regex = new RegExp(regex);
this.setVisibility(rows, regex);
} else {
this.setVisibility(rows, false);
}
}
for (var i = 0; i < this.columns.length; i++) {
var col = this.columns[i];
var node = col.proto.cloneNode(true);
// remove the existing events to minimize IE leaks
col.element.onclick = null;
col.element.onmousedown = null;
col.element.onmouseover = null;
col.element.onmouseout = null;
// set new events for the new node
node.onclick = this.onSortClick(i);
node.onmousedown = ignoreEvent;
node.onmouseover = mouseOverFunc;
node.onmouseout = mouseOutFunc;
// if this is the sorted column
if (key == i) {
// \u2193 is down arrow, \u2191 is up arrow
// forward sorts mean the rows get bigger going down
var arrow = (forward ? "\u2193" : "\u2191");
// add the character to the column header
node.appendChild(SPAN(null, arrow));
if (clicked) {
node.onmouseover();
}
}
// swap in the new th
col.element = swapDOM(col.element, node);
}
}
});
sortableManager = new SortableManager();
/* add our load events */
addLoadEvent(function () {
sortableManager.initWithTable($('projects-table'));
});
addLoadEvent(function (){
sortableManager.showAllHandler($('abc-show-all'))
})
addLoadEvent(function () {
sortableManager.loadLetterHandlers($('abc-click'));
});
|
gpl-3.0
|
echmet/CEval
|
src/crashhandling/crashhandlerlinux.cpp
|
7270
|
#ifdef CRASHHANDLING_LINUX
#include "crashhandlerlinux.h"
#include "crashhandlingprovider.h"
#include "crashhandlerlinux_stacktrace.h"
#include "rawmemblock.h"
#include <algorithm>
#include <cstring>
#include <errno.h>
#include <syscall.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sched.h>
#define sys_prctl(param1, param2, param3, param4, param5) syscall(__NR_prctl, param1, param2, param3, param4, param5)
#define sys_sigaltstack(newStack, originalStack) syscall(__NR_sigaltstack, newStack, originalStack)
const std::array<int, 6> CrashHandlerLinux::m_handledSignals = {{ SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, SIGTRAP }};
CrashHandlerLinux::CrashHandlerLinux(const std::string &miniDumpPath) :
CrashHandlerBase(miniDumpPath),
m_installed(false),
m_mainThreadId(syscall(__NR_gettid))
{
m_pipeDes[0] = 1;
m_pipeDes[1] = -1;
m_crashInfo.reserve(LinuxStackTracer::MAX_FRAMES * LinuxStackTracer::MAX_LINE_LENGTH + 1);
}
CrashHandlerLinux::~CrashHandlerLinux()
{
uninstall();
}
constexpr size_t CrashHandlerLinux::alternateStackSize()
{
return (16384 > SIGSTKSZ) ? 16384 : SIGSTKSZ;
}
void CrashHandlerLinux::crashHandlerFunc(int signum, siginfo_t *siginfo, void *vuctx)
{
CrashHandlerLinux *me = CrashHandlingProvider<CrashHandlerLinux>::handler();
pthread_mutex_lock(&me->m_handlerMutex);
const bool haveDump = me->handleSignal(siginfo, vuctx);
me->restoreHandler(signum);
if (haveDump)
me->finalize();
pthread_mutex_unlock(&me->m_handlerMutex);
/* Send the signal to the main thread if necessary */
if (!me->mainThreadCrashed()) {
if (syscall(__NR_tgkill, me->m_mainThreadId, getpid(), signum))
_exit(EXIT_FAILURE);
return;
}
/* Retrigger the signal by hand if it came from a userspace kill() */
if (siginfo->si_code == SI_USER || signum == SIGABRT) {
if (retrigger(signum))
_exit(EXIT_FAILURE);
}
}
const std::string & CrashHandlerLinux::crashInfo() const
{
return m_crashInfo;
}
/* This may run in a compromised context */
bool CrashHandlerLinux::generateMiniDump(const int signum)
{
size_t backtraceLines = 0;
RawMemBlock<char> backtrace;
if (!LinuxStackTracer::getBacktrace(backtrace, backtraceLines, signum))
return false;
for (size_t idx = 0; idx < backtraceLines; idx++) {
const char *line = backtrace.mem() + (idx * LinuxStackTracer::MAX_LINE_LENGTH);
m_crashInfo += std::string(line);
}
return true;
}
/* This may run in a compromised context */
bool CrashHandlerLinux::handleSignal(siginfo_t *siginfo, void *vuctx)
{
ucontext_t *uctx = static_cast<ucontext_t *>(vuctx);
const bool signalTrusted = siginfo->si_code > 0;
const bool signalPidTrusted = siginfo->si_code == SI_USER || siginfo->si_code == SI_TKILL;
if (signalTrusted || (signalPidTrusted && siginfo->si_pid == getpid()))
sys_prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
if (uctx->uc_mcontext.fpregs)
memcpy(&m_crashCtx.fpuState, uctx->uc_mcontext.fpregs, sizeof(struct _libc_fpstate));
m_crashCtx.exceptionThreadId = syscall(__NR_gettid);
return generateMiniDump(siginfo->si_signo);
}
bool CrashHandlerLinux::install()
{
struct sigaction crashAction;
if (sem_init(&m_waitForKillSemaphore, 0, 0) == -1)
return false;
if (pthread_mutex_init(&m_handlerMutex, nullptr) != 0)
return false;
memset(&m_crashCtx, 0, sizeof(CrashContext));
memset(&m_crashCtx.siginfo, 0, sizeof(siginfo_t));
memset(&m_crashCtx.uctx, 0, sizeof(ucontext_t));
memset(&m_crashCtx.fpuState, 0, sizeof(_libc_fpstate));
memset(&m_originalStack, 0, sizeof(stack_t));
memset(&m_alternateStack, 0, sizeof(stack_t));
m_alternateStack.ss_sp = malloc(alternateStackSize()); /* Consider using mmap() instead */
m_alternateStack.ss_size = alternateStackSize();
if (sys_sigaltstack(&m_alternateStack, &m_originalStack) < 0)
goto errout_1;
/* Store the original crash handlers */
for (size_t idx = 0; idx < m_handledSignals.size(); idx++) {
const int signum = m_handledSignals.at(idx);
if (sigaction(signum, nullptr, &m_originalHandlers[idx]) < 0)
goto errout_1;
}
memset(&crashAction, 0, sizeof(struct sigaction));
sigemptyset(&crashAction.sa_mask);
for (const int signum : m_handledSignals)
sigaddset(&crashAction.sa_mask, signum);
crashAction.sa_flags = SA_SIGINFO | SA_SIGINFO;
crashAction.sa_sigaction = crashHandlerFunc;
for (size_t idx = 0; idx < m_crashHandlers.size(); idx++) {
const int signum = m_handledSignals.at(idx);
if (sigaction(signum, &crashAction, nullptr) < 0) {
/* Something went wrong while wiring up the crash handler.
* Unwind and error out */
for (size_t jdx = 0; jdx <= idx; jdx++) {
const int _signum = m_handledSignals.at(jdx);
if (sigaction(_signum, &m_originalHandlers[jdx], nullptr) < 0)
signal(_signum, SIG_DFL); /* Install the default handler if we have failed to restore the original one */
}
goto errout_2;
}
}
m_installed = true;
return true;
errout_2:
if (restoreOriginalStack() == false)
_exit(1); /* TODO: Report the failure to restore the original stack to the user */
errout_1:
free(m_alternateStack.ss_sp);
return false;
}
bool CrashHandlerLinux::mainThreadCrashed() const
{
return m_mainThreadId == m_crashCtx.exceptionThreadId;
}
void CrashHandlerLinux::proceedToKill() const
{
sem_post(const_cast<sem_t *>(&m_waitForKillSemaphore));
}
bool CrashHandlerLinux::retrigger(const int signum)
{
const pid_t threadId = syscall(__NR_gettid);
const pid_t processId = getpid();
return syscall(__NR_tgkill, threadId, processId, signum) == 0;
}
void CrashHandlerLinux::restoreHandler(const int signum)
{
size_t idx;
for (idx = 0; idx < m_handledSignals.size(); idx++) {
if (m_handledSignals.at(idx) == signum)
break;
}
if (idx == m_handledSignals.size())
return;
if (sigaction(signum, &m_originalHandlers[idx], nullptr) < 0)
signal(signum, SIG_DFL);
}
bool CrashHandlerLinux::restoreOriginalStack()
{
stack_t currentStack;
bool altStackDisabled;
if (sys_sigaltstack(nullptr, ¤tStack) == -1) /* Get info about the currently used stack */
return false;
if (m_alternateStack.ss_sp == currentStack.ss_sp) { /* Are we on the alternate stack? */
if (m_originalStack.ss_sp != nullptr) /* Do we have the original stack? */
altStackDisabled = sys_sigaltstack(&m_originalStack, nullptr) == 0;
else {
/* No pointer to the original stack so just disable the current one */
stack_t stackDisabler;
stackDisabler.ss_flags = SS_DISABLE;
altStackDisabled = sys_sigaltstack(&stackDisabler, nullptr) == 0;
}
} else
altStackDisabled = true;
return altStackDisabled;
}
void CrashHandlerLinux::uninstall()
{
if (!m_installed)
return;
for (const int signum : m_handledSignals)
restoreHandler(signum);
if (restoreOriginalStack()) {
free(m_alternateStack.ss_sp);
memset(&m_alternateStack, 0, sizeof(stack_t));
}
m_installed = false;
}
void CrashHandlerLinux::waitForKill()
{
sem_wait(&m_waitForKillSemaphore);
}
#endif // CRASHHANDLING_LINUX
|
gpl-3.0
|
mapleez/eztip
|
go/working-with-go/http/template.go
|
1339
|
package main
import (
"fmt"
"html/template"
"os"
"strings"
)
type Friend struct {
Fname string
}
type Person struct {
UserName string
Emails []string
Friends []*Friend
}
func EmailDealWith (args ...interface {}) string {
var s string
ok := false
if len (args) == 1 {
s, ok = args [0].(string)
}
if !ok {
s= fmt.Sprint (args ...)
}
substrs := strings.Split (s, "@")
if len (substrs) != 2 {
return s
}
return substrs [0] + " at " + substrs [1]
}
func _test_html_template () {
t, err := template.New ("foo").Parse (`{{define "T"}} Hello, {{.}}{{end}}`)
err = t.ExecuteTemplate (os.Stdout, "T", "this is TTTT")
if err != nil {
println (err.Error ())
}
}
func main () {
_test_html_template ()
println ("---------------------")
f1 := Friend {Fname: "minux.ma"}
f2 := Friend {Fname: "xushiwei"}
t := template.New ("fieldname example")
t = t.Funcs (template.FuncMap {"emailDeal": EmailDealWith})
t, _ = t.Parse (`
hello {{.UserName}}!
{{range .Emails}}
an emails {{.|emailDeal}}
{{end}}
{{with .Friends}}
{{range .}}
my friend name is {{.Fname}}
{{end}}
{{end}}
`)
p := Person {UserName: "Astaxie",
Emails: []string {"astaxie@beego.me", "astaxie@gmail.com"},
Friends: []*Friend {&f1, &f2}}
t.Execute (os.Stdout, p)
}
|
gpl-3.0
|
mozartframework/cms
|
build/demosite/WebContent/WEB-INF/mozart/wp/htdocs/scripts/image-01.js
|
3538
|
// image
//-----------------------------------
// src - ñîóðñ êàðòèíêè
// ôóíêöèÿ ñîçäàåò îáúåêò ñ ñîóðñîì ðàâíûì çíà÷åíèþ src
function image_obj(src){
this.img=new Image()
this.img.src=src
}
// var i = new image_obj_onoff('on.gif','off.gif')
// image_set_onoff (document.images[..],i,'on')
//-----------------------------------
// src_on - ñîóðñ êàðòèíêè
// src_off - ñîóðñ êàðòèíêè
// ôóíêöèÿ äîáàâëÿåò â image_obj äâà ñâîéñòâà on è off ñ ñîóðñàìè src_on è src_off ñîîòâåòñòâåííî
function image_obj_onoff(src_on, src_off){
this.img=new Array()
this.img['on']=new image_obj(src_on)
this.img['off']=new image_obj(src_off)
}
//-----------------------------------
// obj - óêàçàòåëü íà HTML îáúåêò
// obj_set - óêàçàòåëü íà îáúåêò image
// ôóíêöèÿ âûñòàâëÿåò ñîóðñ obj ðàâíûé ñîóðñó îáúåêòà obj_set
function image_set(obj, obj_set){
if(obj && obj_set) obj.src=obj_set.img.src
}
//-----------------------------------
// obj - óêàçàòåëü íà îáúåêò img
// obj_off - óêàçàòåëü íà îáúåêò èç êîòîðîãî áåðóòñÿ çíà÷åíèÿ on è off
// onoff - çíà÷åíèå on èëè off
// ôóíêöèÿ âûñòàâëÿåò obj çíà÷åíèÿ ñîóðñ on èëè off èç îáúåêòà obj_off
function image_set_onoff(obj, obj_off, onoff){
if(obj_off) { image_set(obj, obj_off.img[onoff]) }
}
//-----------------------------------
// ôóíêöèÿ âûñòàâëÿåò ìåòîäó FilterChange çíà÷åíèå ðàâíîå 0
function filterChange(){
this.filterChange=0
}
//-----------------------------------
// img - óêàçàòåëü íà ñóùåñòâóþùèé îáúåêò img
// src - ñîóðñ êàðòèíêè
// filter - ôèëüòð
// new_img - ?
// ôóíêöèÿ âîçðàùàåò true â ñëó÷àå óñïåõà ïîäìåíû src img, åñëè ôèëüòðû ó òåêóùåãî img íå çàäàíû, òî ñîçäàåò íîâûé îáúåêò img
function changeImg(img,src,filter,new_img){
filter = (filter) ? filter : -1
if ( ! img.filters || filter == -1 ) {
new_img = new image_obj(src)
image_set(img,new_img)
return true
}
if( img.filterChange ) return false
if( IE4 && filter >= 0 ){
img.onfilterchange=filterChange
img.filterChange=1
img.filters.item(0).Transition=filter
img.filters.item(0).Apply()
}
img.src=src
if(IE4 && filter>=0) img.filters.item(0).Play()
return true
}
//-----------------------------------
// obj - óêàçàòåëü íà òåêóùóþ êàðòèíêó
// iarray - ìàññèâ êàðòèíîê
// timeout - âðåìÿ çàäåðæêè ïîêàçûâàíèÿ obj â ìèëëèñåêóíäàõ
// next - èíäåêñ, ñ êîòîðîãî íà÷àòü ïîêàçûâàòü ñëàéäû
// filter - ôèëüòð íà ñëàéä
// loop - ïàðàìåòð, îïðåäåëÿþùèé öèêëè÷íîñòü ïîêàçûâàíèÿ ñëàéäîâ
// i - óêàçàòåëü íà êàðòèíêó êîòîðóþ ïîêàçàòü ñëåäóþùåé
// ôóíêöèÿ ñîçäàåò ìàññèâ îáúåêòîâ obj, êîòîðûå ïîêàçûâàþòñÿ êàê ñëàéäû
function slideShow (obj,iarray,timeout,next,filter,loop,i) {
next = (next) ? next : 0
if (next < 0) return -100;
filter = (filter) ? filter : -1
i = new image_obj(iarray[next])
eval ("setTimeout('changeImg(document.images[\""+obj.name+"\"],\""+i.img.src+"\","+filter+")',"+timeout+")")
if (next < iarray.length-1)
next++
else if (loop)
next=0;
else
next =-1
return next;
}
//-----------------------------------
// iarray - ìàññèâ îáúåêòîâ êàðòèíîê
// img - óêàçàòåëü íà êàðòèíêó
// ôóíêöèÿ äîáàâëÿåò â iarray êàðòèíêó img
function load_img_array (iarray, img) {
if (!iarray.length)
return
for ( i=0; i<iarray.length; i++ ){
eval ("img"+i+" = new image_obj('"+iarray[i]+"')");
}
}
|
gpl-3.0
|
ChangDeWM/WMS
|
WMS.Common.Utility/ValidateCode/AnimatedGifEncoder.cs
|
9849
|
using System;
using System.Drawing;
using System.IO;
namespace WMS.Common.Utility
{
public class AnimatedGifEncoder
{
protected int colorDepth;
protected byte[] colorTab;
protected int delay;
protected int dispose = -1;
protected bool firstFrame = true;
protected int height;
protected Image image;
protected byte[] indexedPixels;
protected MemoryStream Memory;
protected int palSize = 7;
protected byte[] pixels;
protected int repeat = -1;
protected int sample = 10;
protected bool sizeSet;
protected bool started;
protected int transIndex;
protected Color transparent = Color.Empty;
protected bool[] usedEntry = new bool[0x100];
protected int width;
public bool AddFrame(Image im)
{
if ((im == null) || !this.started)
{
return false;
}
bool flag = true;
try
{
if (!this.sizeSet)
{
this.SetSize(im.Width, im.Height);
}
this.image = im;
this.GetImagePixels();
this.AnalyzePixels();
if (this.firstFrame)
{
this.WriteLSD();
this.WritePalette();
if (this.repeat >= 0)
{
this.WriteNetscapeExt();
}
}
this.WriteGraphicCtrlExt();
this.WriteImageDesc();
if (!this.firstFrame)
{
this.WritePalette();
}
this.WritePixels();
this.firstFrame = false;
}
catch (IOException)
{
flag = false;
}
return flag;
}
protected void AnalyzePixels()
{
int length = this.pixels.Length;
int num2 = length / 3;
this.indexedPixels = new byte[num2];
NeuQuant quant = new NeuQuant(this.pixels, length, this.sample);
this.colorTab = quant.Process();
int num3 = 0;
for (int i = 0; i < num2; i++)
{
int index = quant.Map(this.pixels[num3++] & 0xff, this.pixels[num3++] & 0xff, this.pixels[num3++] & 0xff);
this.usedEntry[index] = true;
this.indexedPixels[i] = (byte) index;
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
if (this.transparent != Color.Empty)
{
this.transIndex = this.FindClosest(this.transparent);
}
}
protected int FindClosest(Color c)
{
if (this.colorTab == null)
{
return -1;
}
int r = c.R;
int g = c.G;
int b = c.B;
int num4 = 0;
int num5 = 0x1000000;
int length = this.colorTab.Length;
for (int i = 0; i < length; i++)
{
int num8 = r - (this.colorTab[i++] & 0xff);
int num9 = g - (this.colorTab[i++] & 0xff);
int num10 = b - (this.colorTab[i] & 0xff);
int num11 = ((num8 * num8) + (num9 * num9)) + (num10 * num10);
int index = i / 3;
if (this.usedEntry[index] && (num11 < num5))
{
num5 = num11;
num4 = index;
}
}
return num4;
}
protected void GetImagePixels()
{
int width = this.image.Width;
int height = this.image.Height;
if ((width != this.width) || (height != this.height))
{
Image image = new Bitmap(this.width, this.height);
Graphics graphics = Graphics.FromImage(image);
graphics.DrawImage(this.image, 0, 0);
this.image = image;
graphics.Dispose();
}
this.pixels = new byte[(3 * this.image.Width) * this.image.Height];
int index = 0;
Bitmap bitmap = new Bitmap(this.image);
for (int i = 0; i < this.image.Height; i++)
{
for (int j = 0; j < this.image.Width; j++)
{
Color pixel = bitmap.GetPixel(j, i);
this.pixels[index] = pixel.R;
index++;
this.pixels[index] = pixel.G;
index++;
this.pixels[index] = pixel.B;
index++;
}
}
}
public void OutPut(ref MemoryStream MemoryResult)
{
this.started = false;
this.Memory.WriteByte(0x3b);
this.Memory.Flush();
MemoryResult = this.Memory;
this.Memory.Close();
this.Memory.Dispose();
this.transIndex = 0;
this.Memory = null;
this.image = null;
this.pixels = null;
this.indexedPixels = null;
this.colorTab = null;
this.firstFrame = true;
}
public void SetDelay(int ms)
{
this.delay = (int) Math.Round((double) (((float) ms) / 10f));
}
public void SetDispose(int code)
{
if (code >= 0)
{
this.dispose = code;
}
}
public void SetFrameRate(float fps)
{
if (fps != 0f)
{
this.delay = (int) Math.Round((double) (100f / fps));
}
}
public void SetQuality(int quality)
{
if (quality < 1)
{
quality = 1;
}
this.sample = quality;
}
public void SetRepeat(int iter)
{
if (iter >= 0)
{
this.repeat = iter;
}
}
public void SetSize(int w, int h)
{
if (!this.started || this.firstFrame)
{
this.width = w;
this.height = h;
if (this.width < 1)
{
this.width = 320;
}
if (this.height < 1)
{
this.height = 240;
}
this.sizeSet = true;
}
}
public void SetTransparent(Color c)
{
this.transparent = c;
}
public void Start()
{
this.Memory = new MemoryStream();
this.WriteString("GIF89a");
this.started = true;
}
protected void WriteGraphicCtrlExt()
{
int num;
int num2;
this.Memory.WriteByte(0x21);
this.Memory.WriteByte(0xf9);
this.Memory.WriteByte(4);
if (this.transparent == Color.Empty)
{
num = 0;
num2 = 0;
}
else
{
num = 1;
num2 = 2;
}
if (this.dispose >= 0)
{
num2 = this.dispose & 7;
}
num2 = num2 << 2;
this.Memory.WriteByte(Convert.ToByte((int) (num2 | num)));
this.WriteShort(this.delay);
this.Memory.WriteByte(Convert.ToByte(this.transIndex));
this.Memory.WriteByte(0);
}
protected void WriteImageDesc()
{
this.Memory.WriteByte(0x2c);
this.WriteShort(0);
this.WriteShort(0);
this.WriteShort(this.width);
this.WriteShort(this.height);
if (this.firstFrame)
{
this.Memory.WriteByte(0);
}
else
{
this.Memory.WriteByte(Convert.ToByte((int) (0x80 | this.palSize)));
}
}
protected void WriteLSD()
{
this.WriteShort(this.width);
this.WriteShort(this.height);
this.Memory.WriteByte(Convert.ToByte((int) (240 | this.palSize)));
this.Memory.WriteByte(0);
this.Memory.WriteByte(0);
}
protected void WriteNetscapeExt()
{
this.Memory.WriteByte(0x21);
this.Memory.WriteByte(0xff);
this.Memory.WriteByte(11);
this.WriteString("NETSCAPE2.0");
this.Memory.WriteByte(3);
this.Memory.WriteByte(1);
this.WriteShort(this.repeat);
this.Memory.WriteByte(0);
}
protected void WritePalette()
{
this.Memory.Write(this.colorTab, 0, this.colorTab.Length);
int num = 0x300 - this.colorTab.Length;
for (int i = 0; i < num; i++)
{
this.Memory.WriteByte(0);
}
}
protected void WritePixels()
{
new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth).Encode(this.Memory);
}
protected void WriteShort(int value)
{
this.Memory.WriteByte(Convert.ToByte((int) (value & 0xff)));
this.Memory.WriteByte(Convert.ToByte((int) ((value >> 8) & 0xff)));
}
protected void WriteString(string s)
{
char[] chArray = s.ToCharArray();
for (int i = 0; i < chArray.Length; i++)
{
this.Memory.WriteByte((byte) chArray[i]);
}
}
}
}
|
gpl-3.0
|
khan0407/FinalArcade
|
theme/binarius/layout/general.php
|
5668
|
<?php
$hasheading = ($PAGE->heading);
$hasnavbar = (empty($PAGE->layout_options['nonavbar']) && $PAGE->has_navbar());
$hasfooter = (empty($PAGE->layout_options['nofooter']));
$hassidepost = $PAGE->blocks->region_has_content('side-post', $OUTPUT);
$showsidepost = ($hassidepost && !$PAGE->blocks->region_completely_docked('side-post', $OUTPUT));
$custommenu = $OUTPUT->custom_menu();
$hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custommenu));
$bodyclasses = array();
if ($showsidepost) {
$bodyclasses[] = 'side-post-only';
} else if (!$showsidepost) {
$bodyclasses[] = 'content-only';
}
if ($hascustommenu) {
$bodyclasses[] = 'has-custom-menu';
}
<<<<<<< HEAD
=======
$courseheader = $coursecontentheader = $coursecontentfooter = $coursefooter = '';
if (empty($PAGE->layout_options['nocourseheaderfooter'])) {
$courseheader = $OUTPUT->course_header();
$coursecontentheader = $OUTPUT->course_content_header();
if (empty($PAGE->layout_options['nocoursefooter'])) {
$coursecontentfooter = $OUTPUT->course_content_footer();
$coursefooter = $OUTPUT->course_footer();
}
}
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
echo $OUTPUT->doctype() ?>
<html <?php echo $OUTPUT->htmlattributes() ?>>
<head>
<title><?php echo $PAGE->title ?></title>
<link rel="shortcut icon" href="<?php echo $OUTPUT->pix_url('favicon', 'theme')?>" />
<?php echo $OUTPUT->standard_head_html() ?>
</head>
<body id="<?php p($PAGE->bodyid) ?>" class="<?php p($PAGE->bodyclasses.' '.join(' ', $bodyclasses)) ?>">
<?php echo $OUTPUT->standard_top_of_body_html() ?>
<div id="page">
<<<<<<< HEAD
<?php if ($hasheading || $hasnavbar) { ?>
=======
<?php if ($hasheading || $hasnavbar || !empty($courseheader) || !empty($coursefooter)) { ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
<div id="wrapper" class="clearfix">
<!-- START OF HEADER -->
<div id="page-header" class="inside">
<div id="page-header-wrapper" class="wrapper clearfix">
<?php if ($hasheading) { ?>
<h1 class="headermain"><?php echo $PAGE->heading ?></h1>
<div class="headermenu"><?php
echo $OUTPUT->login_info();
if (!empty($PAGE->layout_options['langmenu'])) {
echo $OUTPUT->lang_menu();
}
echo $PAGE->headingmenu ?>
</div>
<?php } ?>
<?php if ($hascustommenu) { ?>
<div id="custommenu"><?php echo $custommenu; ?></div>
<?php } ?>
</div>
</div>
<<<<<<< HEAD
=======
<?php if (!empty($courseheader)) { ?>
<div id="course-header"><?php echo $courseheader; ?></div>
<?php } ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
<?php if ($hasnavbar) { ?>
<div class="navbar">
<div class="wrapper clearfix">
<div class="breadcrumb"><?php echo $OUTPUT->navbar(); ?></div>
<div class="navbutton"> <?php echo $PAGE->button; ?></div>
</div>
</div>
<?php } ?>
<!-- END OF HEADER -->
<?php } ?>
<!-- START OF CONTENT -->
<div id="page-content-wrapper" class="wrapper clearfix">
<div id="page-content">
<div id="region-main-box">
<div id="region-post-box">
<div id="region-main-wrap">
<div id="region-main">
<div class="region-content">
<<<<<<< HEAD
<?php echo $OUTPUT->main_content() ?>
=======
<?php echo $coursecontentheader; ?>
<?php echo $OUTPUT->main_content() ?>
<?php echo $coursecontentfooter; ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
</div>
</div>
</div>
<?php if ($hassidepost) { ?>
<div id="region-post" class="block-region">
<div class="region-content">
<?php echo $OUTPUT->blocks_for_region('side-post') ?>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<!-- END OF CONTENT -->
<<<<<<< HEAD
<?php if ($hasheading || $hasnavbar) { ?>
=======
<?php if (!empty($coursefooter)) { ?>
<div id="course-footer"><?php echo $coursefooter; ?></div>
<?php } ?>
<?php if ($hasheading || $hasnavbar || !empty($courseheader) || !empty($coursefooter)) { ?>
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
<div class="myclear"></div>
</div>
<?php } ?>
<!-- START OF FOOTER -->
<?php if ($hasfooter) { ?>
<div id="page-footer" class="wrapper">
<p class="helplink"><?php echo page_doc_link(get_string('moodledocslink')) ?></p>
<?php
echo $OUTPUT->login_info();
echo $OUTPUT->home_link();
echo $OUTPUT->standard_footer_html();
?>
</div>
<?php } ?>
</div>
<?php echo $OUTPUT->standard_end_of_body_html() ?>
</body>
</html>
|
gpl-3.0
|
marook/brainfs
|
test/test_subject_directory.py
|
2472
|
#
# Copyright 2010 Markus Pielmeier
#
# This file is part of brainfs.
#
# brainfs 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.
#
# brainfs 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 brainfs. If not, see <http://www.gnu.org/licenses/>.
#
from brainfs import dom
import unittest
import test_view
from brainfs import subject_directory
class SubjectDirectoryViewTest(test_view.AbstractNodeViewTest):
def validatePushNode(self, subjects, view):
attr = view.getattr('/.push')
host = 'localhost'
path = ''
url = 'http://' + host + path + '\n'
# TODO maybe we should set the second param somehow specific?
view.open('/.push', '32768')
p = 0
while p < len(url):
l = view.write('/.push', url[p:len(url)], p + attr.st_size)
self.assertTrue(l > 0)
p = p + l
self.assertEquals(len(url), p)
found = False
for s in [s for s in subjects if isinstance(s, dom.HttpSubject)]:
if not s.host == host:
continue
if not s.path == path:
continue
if not s.port == None:
continue
if not s.method == 'GET':
continue
found = True
if not found:
self.fail(msg = 'Can\'t find pushed subject')
self.validateNodeView(view, '/' + host)
def testInterface(self):
"""Validate View interface for SubjectDirectoryView
"""
subjects = [
dom.FileSubject('etc/demo_resources/00_IMG008.jpg')
]
view = subject_directory.SubjectDirectoryView(subjects)
self.validateNodeView(view, '/')
self.validateNodeView(view, '/00_IMG008.jpg')
r = view.symlink('../the file', '/the link')
# TODO assert r's content
self.validateNodeView(view, '/the link')
self.validatePushNode(subjects, view)
if __name__ == "__main__":
import brainfs
unittest.main()
|
gpl-3.0
|
atomist-blogs/spring5-kotlin
|
src/commands/kotlinUtils.ts
|
2456
|
/*
* Copyright © 2017 Atomist, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { KotlinFileParser } from "@atomist/antlr/tree/ast/antlr/kotlin/KotlinFileParser";
import { logger } from "@atomist/automation-client/internal/util/logger";
import {
SpringBootProjectStructure,
} from "@atomist/automation-client/operations/generate/java/SpringBootProjectStructure";
import { ProjectAsync } from "@atomist/automation-client/project/Project";
import { findFileMatches } from "@atomist/automation-client/tree/ast/astUtils";
import { evaluateScalarValue } from "@atomist/tree-path/path/expressionEngine";
export const AllKotlinFiles = "src/**/kotlin/**/*.kt";
export const KotlinSourceFiles = "src/main/kotlin/**/*.kt";
/**
* Infer the Spring Boot structure of a Kotlin project, looking for a Kotlin
* class annotated with @SpringBootApplication
* @param {ProjectAsync} p
* @return {Promise<SpringBootProjectStructure>}
*/
export function inferFromKotlinSource(p: ProjectAsync): Promise<SpringBootProjectStructure> {
// Run a path expression against the Kotlin ANTLR grammar
return findFileMatches(p, KotlinFileParser, KotlinSourceFiles,
"//classDeclaration[//annotation[@value='@SpringBootApplication']]/simpleIdentifier")
.then(files => {
if (files.length !== 1) {
return undefined;
} else {
const f = files[0];
const appClass = f.matches[0].$value;
// Use the AST from the matching file to extract the package
const packageName = evaluateScalarValue(f.fileNode, "//packageHeader/identifier");
logger.info(`Spring Boot inference: packageName=${packageName}, appClass=${appClass}`);
return (packageName && appClass) ?
new SpringBootProjectStructure(packageName, appClass, f.file) :
undefined;
}
});
}
|
gpl-3.0
|
ovidiusimionica/isolation-levels-demo
|
src/test/java/com/example/IsolationLevelsDemoApplicationTests.java
|
435
|
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = IsolationLevelsDemoApplication.class)
public class IsolationLevelsDemoApplicationTests {
@Test
public void contextLoads() {
}
}
|
gpl-3.0
|
astrophysicist87/iEBE-Plumberg
|
EBE-Node/photonEmission/ph_rates/sum_up_all_QGP_channels.py
|
569
|
#!/usr/bin/env python
from numpy import *
channel_list = ['QGP_2to2_hard', 'QGP_2to2_soft' ]
rate_type_list = ['eqrate', 'viscous', 'bulkvis']
sum_data = 0.0*loadtxt('rate_%s_%s.dat' % (channel_list[0], rate_type_list[0]))
for itype in range(len(rate_type_list)):
for ich in range(len(channel_list)):
filename = 'rate_%s_%s.dat' % (channel_list[ich], rate_type_list[itype])
data = loadtxt(filename)
sum_data += data
savetxt('rate_QGP_2to2_total_%s.dat' % rate_type_list[itype],
sum_data, fmt='%.10e', delimiter = ' ')
|
gpl-3.0
|
neilh23/eudyptula
|
stk/src/TubeBell.cpp
|
2105
|
/***************************************************/
/*! \class TubeBell
\brief STK tubular bell (orchestral chime) FM
synthesis instrument.
This class implements two simple FM Pairs
summed together, also referred to as algorithm
5 of the TX81Z.
\code
Algorithm 5 is : 4->3--\
+ --> Out
2->1--/
\endcode
Control Change Numbers:
- Modulator Index One = 2
- Crossfade of Outputs = 4
- LFO Speed = 11
- LFO Depth = 1
- ADSR 2 & 4 Target = 128
The basic Chowning/Stanford FM patent expired
in 1995, but there exist follow-on patents,
mostly assigned to Yamaha. If you are of the
type who should worry about this (making
money) worry away.
by Perry R. Cook and Gary P. Scavone, 1995-2011.
*/
/***************************************************/
#include "TubeBell.h"
namespace stk {
TubeBell :: TubeBell( void )
: FM()
{
// Concatenate the STK rawwave path to the rawwave files
for ( unsigned int i=0; i<3; i++ )
waves_[i] = new FileLoop( (Stk::rawwavePath() + "sinewave.raw").c_str(), true );
waves_[3] = new FileLoop( (Stk::rawwavePath() + "fwavblnk.raw").c_str(), true );
this->setRatio(0, 1.0 * 0.995);
this->setRatio(1, 1.414 * 0.995);
this->setRatio(2, 1.0 * 1.005);
this->setRatio(3, 1.414 * 1.000);
gains_[0] = fmGains_[94];
gains_[1] = fmGains_[76];
gains_[2] = fmGains_[99];
gains_[3] = fmGains_[71];
adsr_[0]->setAllTimes( 0.005, 4.0, 0.0, 0.04);
adsr_[1]->setAllTimes( 0.005, 4.0, 0.0, 0.04);
adsr_[2]->setAllTimes( 0.001, 2.0, 0.0, 0.04);
adsr_[3]->setAllTimes( 0.004, 4.0, 0.0, 0.04);
twozero_.setGain( 0.5 );
vibrato_.setFrequency( 2.0 );
}
TubeBell :: ~TubeBell( void )
{
}
void TubeBell :: noteOn( StkFloat frequency, StkFloat amplitude )
{
gains_[0] = amplitude * fmGains_[94];
gains_[1] = amplitude * fmGains_[76];
gains_[2] = amplitude * fmGains_[99];
gains_[3] = amplitude * fmGains_[71];
this->setFrequency( frequency );
this->keyOn();
}
} // stk namespace
|
gpl-3.0
|
OsirisSPS/osiris-sps
|
client/src/plugins/python/wrappers/extensionsmodulecontrol.pypp.cpp
|
22180
|
// This file has been generated by Py++.
#include "stdafx.h"
#include "pypluspluscommon.h"
#include "boost/python.hpp"
#include "__call_policies.pypp.hpp"
#include "extensionsmodulecontrol.h"
#include "xmldocument.h"
#include "ideskin.h"
#include "idesession.h"
#include "ideportalcontrol.h"
#include "datatree.h"
#include "htmlattributes.h"
#include "htmlevent.h"
#include "eventssource.h"
#include "htmlvirtualpage.h"
#include "htmlwriter.h"
#include "httprequest.h"
#include "httpresponse.h"
#include "httpsession.h"
#include "extensionsmoduleviewer.h"
#include "extensionsinvalidmodule.h"
#include "extensionsmoduleviewerhidden.h"
#include "extensionsmoduleeditor.h"
#include "extensionsmodulecontrol.pypp.hpp"
namespace bp = boost::python;
struct ExtensionsModuleControl_wrapper : ::osiris::ExtensionsModuleControl, ::osiris::PythonWrapper< ::osiris::ExtensionsModuleControl > {
ExtensionsModuleControl_wrapper( )
: ::osiris::ExtensionsModuleControl( )
, ::osiris::PythonWrapper< ::osiris::ExtensionsModuleControl >(){
// null constructor
}
static boost::python::object getModule( ::osiris::ExtensionsModuleControl const & inst ){
::osiris::PythonThreadSaver __pythreadSaver;
::boost::shared_ptr<osiris::IExtensionsModule> const result = inst.getModule();
__pythreadSaver.restore();
return boost::python::object( result );
}
static boost::python::object getTitle( ::osiris::ExtensionsModuleControl const & inst ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::String const & result = inst.getTitle();
__pythreadSaver.restore();
typedef bp::return_value_policy< bp::copy_const_reference > call_policies_t;
return boost::python::object( pyplusplus::call_policies::make_object< call_policies_t, ::osiris::String const & >( result ) );
}
static boost::python::object getInstance( ::osiris::ExtensionsModuleControl const & inst ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::UniqueID const & result = inst.getInstance();
__pythreadSaver.restore();
typedef bp::return_value_policy< bp::copy_const_reference > call_policies_t;
return boost::python::object( pyplusplus::call_policies::make_object< call_policies_t, ::osiris::UniqueID const & >( result ) );
}
static boost::python::object getModuleDocument( ::osiris::ExtensionsModuleControl const & inst ){
::osiris::PythonThreadSaver __pythreadSaver;
::boost::shared_ptr<osiris::XMLDocument> result = inst.getModuleDocument();
__pythreadSaver.restore();
return boost::python::object( result );
}
virtual bool init( ::boost::shared_ptr< osiris::IExtensionsModule > module, ::osiris::String const & title, ::osiris::UniqueID const & instance, ::osiris::String const & xml ) {
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_init = this->get_override( "init" ) )
return func_init( module, boost::ref(title), boost::ref(instance), boost::ref(xml) );
else{
__pystate.leave();
return this->::osiris::ExtensionsModuleControl::init( module, boost::ref(title), boost::ref(instance), boost::ref(xml) );
}
}
bool default_init( ::boost::shared_ptr< osiris::IExtensionsModule > module, ::osiris::String const & title, ::osiris::UniqueID const & instance, ::osiris::String const & xml ) {
::osiris::PythonThreadSaver __pythreadSaver;
return ::osiris::ExtensionsModuleControl::init( module, boost::ref(title), boost::ref(instance), boost::ref(xml) );
}
bool decodeEvent( ::osiris::String const & command, ::osiris::String & eventName, ::osiris::HtmlEvent & e ) const {
return ::osiris::IHtmlControl::decodeEvent( boost::ref(command), boost::ref(eventName), boost::ref(e) );
}
::osiris::String encodeEvent( ::osiris::String const & eventName, ::osiris::HtmlEvent const * e=(nullptr) ) const {
return ::osiris::IHtmlControl::encodeEvent( boost::ref(eventName), boost::python::ptr(e) );
}
virtual ::boost::shared_ptr< osiris::HttpSession > getSession( ) const {
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_getSession = this->get_override( "getSession" ) )
return func_getSession( );
else{
__pystate.leave();
return this->::osiris::IHtmlControl::getSession( );
}
}
::boost::shared_ptr< osiris::HttpSession > default_getSession( ) const {
::osiris::PythonThreadSaver __pythreadSaver;
return ::osiris::IHtmlControl::getSession( );
}
virtual void onEvent( ::osiris::String const & name, ::osiris::IEvent * e=(nullptr) ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onEvent = this->get_override( "onEvent" ) )
func_onEvent( boost::ref(name), boost::python::ptr(e) );
else{
__pystate.leave();
this->::osiris::IHtmlControl::onEvent( boost::ref(name), boost::python::ptr(e) );
}
}
virtual void default_onEvent( ::osiris::String const & name, ::osiris::IEvent * e=(nullptr) ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::onEvent( boost::ref(name), boost::python::ptr(e) );
}
virtual void onInit( ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onInit = this->get_override( "onInit" ) )
func_onInit( );
else{
__pystate.leave();
this->::osiris::IHtmlControl::onInit( );
}
}
virtual void default_onInit( ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::onInit( );
}
virtual void onLoad( ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onLoad = this->get_override( "onLoad" ) )
func_onLoad( );
else{
__pystate.leave();
this->::osiris::IHtmlControl::onLoad( );
}
}
virtual void default_onLoad( ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::onLoad( );
}
virtual void onLoadViewState( ::osiris::DataTree const & state ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onLoadViewState = this->get_override( "onLoadViewState" ) )
func_onLoadViewState( boost::ref(state) );
else{
__pystate.leave();
this->::osiris::IHtmlControl::onLoadViewState( boost::ref(state) );
}
}
virtual void default_onLoadViewState( ::osiris::DataTree const & state ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::onLoadViewState( boost::ref(state) );
}
virtual void onPreRender( ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onPreRender = this->get_override( "onPreRender" ) )
func_onPreRender( );
else{
__pystate.leave();
this->::osiris::IHtmlControl::onPreRender( );
}
}
virtual void default_onPreRender( ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::onPreRender( );
}
virtual void onRender( ::osiris::HtmlWriter & writer ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onRender = this->get_override( "onRender" ) )
func_onRender( boost::ref(writer) );
else{
__pystate.leave();
this->::osiris::HtmlDiv::onRender( boost::ref(writer) );
}
}
virtual void default_onRender( ::osiris::HtmlWriter & writer ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::HtmlDiv::onRender( boost::ref(writer) );
}
virtual void onSaveViewState( ::osiris::DataTree & state ){
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_onSaveViewState = this->get_override( "onSaveViewState" ) )
func_onSaveViewState( boost::ref(state) );
else{
__pystate.leave();
this->::osiris::IHtmlControl::onSaveViewState( boost::ref(state) );
}
}
virtual void default_onSaveViewState( ::osiris::DataTree & state ){
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::onSaveViewState( boost::ref(state) );
}
virtual void renderAttributes( ::osiris::HtmlWriter & writer ) {
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_renderAttributes = this->get_override( "renderAttributes" ) )
func_renderAttributes( boost::ref(writer) );
else{
__pystate.leave();
this->::osiris::IHtmlControl::renderAttributes( boost::ref(writer) );
}
}
void default_renderAttributes( ::osiris::HtmlWriter & writer ) {
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::renderAttributes( boost::ref(writer) );
}
virtual void renderChilds( ::osiris::HtmlWriter & writer ) {
::osiris::PythonState __pystate(getPythonThreadState());
if( ::osiris::PythonOverride func_renderChilds = this->get_override( "renderChilds" ) )
func_renderChilds( boost::ref(writer) );
else{
__pystate.leave();
this->::osiris::IHtmlControl::renderChilds( boost::ref(writer) );
}
}
void default_renderChilds( ::osiris::HtmlWriter & writer ) {
::osiris::PythonThreadSaver __pythreadSaver;
::osiris::IHtmlControl::renderChilds( boost::ref(writer) );
}
void saveViewState( ::osiris::DataTree & states ){
::osiris::IHtmlControl::saveViewState( boost::ref(states) );
}
};
void register_ExtensionsModuleControl_class(){
{ //::osiris::ExtensionsModuleControl
typedef ::boost::python::class_< ExtensionsModuleControl_wrapper, ::boost::python::bases< ::osiris::IPortalPageControl< osiris::HtmlDiv > >, ::boost::noncopyable > ExtensionsModuleControl_exposer_t;
ExtensionsModuleControl_exposer_t ExtensionsModuleControl_exposer = ExtensionsModuleControl_exposer_t( "ExtensionsModuleControl", ::boost::python::no_init );
::boost::python::scope ExtensionsModuleControl_scope( ExtensionsModuleControl_exposer );
ExtensionsModuleControl_exposer.def( ::boost::python::init< >() );
{ //::osiris::ExtensionsModuleControl::getModule
typedef boost::python::object ( *getModule_function_type )( ::osiris::ExtensionsModuleControl const & );
ExtensionsModuleControl_exposer.def(
"getModule"
, getModule_function_type( &ExtensionsModuleControl_wrapper::getModule ) );
}
{ //::osiris::ExtensionsModuleControl::getTitle
typedef boost::python::object ( *getTitle_function_type )( ::osiris::ExtensionsModuleControl const & );
ExtensionsModuleControl_exposer.def(
"getTitle"
, getTitle_function_type( &ExtensionsModuleControl_wrapper::getTitle ) );
}
{ //::osiris::ExtensionsModuleControl::getInstance
typedef boost::python::object ( *getInstance_function_type )( ::osiris::ExtensionsModuleControl const & );
ExtensionsModuleControl_exposer.def(
"getInstance"
, getInstance_function_type( &ExtensionsModuleControl_wrapper::getInstance ) );
}
{ //::osiris::ExtensionsModuleControl::getModuleDocument
typedef boost::python::object ( *getModuleDocument_function_type )( ::osiris::ExtensionsModuleControl const & );
ExtensionsModuleControl_exposer.def(
"getModuleDocument"
, getModuleDocument_function_type( &ExtensionsModuleControl_wrapper::getModuleDocument ) );
}
{ //::osiris::ExtensionsModuleControl::init
typedef bool ( ::osiris::ExtensionsModuleControl::*init_function_type )( ::boost::shared_ptr< osiris::IExtensionsModule >,::osiris::String const &,::osiris::UniqueID const &,::osiris::String const & ) ;
typedef bool ( ExtensionsModuleControl_wrapper::*default_init_function_type )( ::boost::shared_ptr< osiris::IExtensionsModule >,::osiris::String const &,::osiris::UniqueID const &,::osiris::String const & ) ;
ExtensionsModuleControl_exposer.def(
"init"
, init_function_type(&::osiris::ExtensionsModuleControl::init)
, default_init_function_type(&ExtensionsModuleControl_wrapper::default_init)
, ( ::boost::python::arg("module"), ::boost::python::arg("title"), ::boost::python::arg("instance"), ::boost::python::arg("xml") ) );
}
{ //::osiris::IHtmlControl::decodeEvent
typedef bool ( ExtensionsModuleControl_wrapper::*decodeEvent_function_type )( ::osiris::String const &,::osiris::String &,::osiris::HtmlEvent & ) const;
ExtensionsModuleControl_exposer.def(
"decodeEvent"
, decodeEvent_function_type( &ExtensionsModuleControl_wrapper::decodeEvent )
, ( ::boost::python::arg("command"), ::boost::python::arg("eventName"), ::boost::python::arg("e") ) );
}
{ //::osiris::IHtmlControl::encodeEvent
typedef ::osiris::String ( ExtensionsModuleControl_wrapper::*encodeEvent_function_type )( ::osiris::String const &,::osiris::HtmlEvent const * ) const;
ExtensionsModuleControl_exposer.def(
"encodeEvent"
, encodeEvent_function_type( &ExtensionsModuleControl_wrapper::encodeEvent )
, ( ::boost::python::arg("eventName"), ::boost::python::arg("e")=(nullptr) ) );
}
{ //::osiris::IHtmlControl::getSession
typedef ::boost::shared_ptr< osiris::HttpSession > ( ::osiris::IHtmlControl::*getSession_function_type )( ) const;
typedef ::boost::shared_ptr< osiris::HttpSession > ( ExtensionsModuleControl_wrapper::*default_getSession_function_type )( ) const;
ExtensionsModuleControl_exposer.def(
"getSession"
, getSession_function_type(&::osiris::IHtmlControl::getSession)
, default_getSession_function_type(&ExtensionsModuleControl_wrapper::default_getSession) );
}
{ //::osiris::IHtmlControl::onEvent
typedef void ( ExtensionsModuleControl_wrapper::*onEvent_function_type )( ::osiris::String const &,::osiris::IEvent * ) ;
ExtensionsModuleControl_exposer.def(
"onEvent"
, onEvent_function_type( &ExtensionsModuleControl_wrapper::default_onEvent )
, ( ::boost::python::arg("name"), ::boost::python::arg("e")=(nullptr) ) );
}
{ //::osiris::IHtmlControl::onInit
typedef void ( ExtensionsModuleControl_wrapper::*onInit_function_type )( ) ;
ExtensionsModuleControl_exposer.def(
"onInit"
, onInit_function_type( &ExtensionsModuleControl_wrapper::default_onInit ) );
}
{ //::osiris::IHtmlControl::onLoad
typedef void ( ExtensionsModuleControl_wrapper::*onLoad_function_type )( ) ;
ExtensionsModuleControl_exposer.def(
"onLoad"
, onLoad_function_type( &ExtensionsModuleControl_wrapper::default_onLoad ) );
}
{ //::osiris::IHtmlControl::onLoadViewState
typedef void ( ExtensionsModuleControl_wrapper::*onLoadViewState_function_type )( ::osiris::DataTree const & ) ;
ExtensionsModuleControl_exposer.def(
"onLoadViewState"
, onLoadViewState_function_type( &ExtensionsModuleControl_wrapper::default_onLoadViewState )
, ( ::boost::python::arg("state") ) );
}
{ //::osiris::IHtmlControl::onPreRender
typedef void ( ExtensionsModuleControl_wrapper::*onPreRender_function_type )( ) ;
ExtensionsModuleControl_exposer.def(
"onPreRender"
, onPreRender_function_type( &ExtensionsModuleControl_wrapper::default_onPreRender ) );
}
{ //::osiris::HtmlDiv::onRender
typedef void ( ExtensionsModuleControl_wrapper::*onRender_function_type )( ::osiris::HtmlWriter & ) ;
ExtensionsModuleControl_exposer.def(
"onRender"
, onRender_function_type( &ExtensionsModuleControl_wrapper::default_onRender )
, ( ::boost::python::arg("writer") ) );
}
{ //::osiris::IHtmlControl::onSaveViewState
typedef void ( ExtensionsModuleControl_wrapper::*onSaveViewState_function_type )( ::osiris::DataTree & ) ;
ExtensionsModuleControl_exposer.def(
"onSaveViewState"
, onSaveViewState_function_type( &ExtensionsModuleControl_wrapper::default_onSaveViewState )
, ( ::boost::python::arg("state") ) );
}
{ //::osiris::IHtmlControl::renderAttributes
typedef void ( ::osiris::IHtmlControl::*renderAttributes_function_type )( ::osiris::HtmlWriter & ) ;
typedef void ( ExtensionsModuleControl_wrapper::*default_renderAttributes_function_type )( ::osiris::HtmlWriter & ) ;
ExtensionsModuleControl_exposer.def(
"renderAttributes"
, renderAttributes_function_type(&::osiris::IHtmlControl::renderAttributes)
, default_renderAttributes_function_type(&ExtensionsModuleControl_wrapper::default_renderAttributes)
, ( ::boost::python::arg("writer") ) );
}
{ //::osiris::IHtmlControl::renderChilds
typedef void ( ::osiris::IHtmlControl::*renderChilds_function_type )( ::osiris::HtmlWriter & ) ;
typedef void ( ExtensionsModuleControl_wrapper::*default_renderChilds_function_type )( ::osiris::HtmlWriter & ) ;
ExtensionsModuleControl_exposer.def(
"renderChilds"
, renderChilds_function_type(&::osiris::IHtmlControl::renderChilds)
, default_renderChilds_function_type(&ExtensionsModuleControl_wrapper::default_renderChilds)
, ( ::boost::python::arg("writer") ) );
}
{ //::osiris::IHtmlControl::saveViewState
typedef void ( ExtensionsModuleControl_wrapper::*saveViewState_function_type )( ::osiris::DataTree & ) ;
ExtensionsModuleControl_exposer.def(
"saveViewState"
, saveViewState_function_type( &ExtensionsModuleControl_wrapper::saveViewState )
, ( ::boost::python::arg("states") ) );
}
{ //property "module"[fget=::osiris::ExtensionsModuleControl::getModule]
typedef ::boost::shared_ptr<osiris::IExtensionsModule> const ( ::osiris::ExtensionsModuleControl::*fget )( ) const;
ExtensionsModuleControl_exposer.add_property(
"module"
, fget( &::osiris::ExtensionsModuleControl::getModule )
, "get property, built on top of \"boost::shared_ptr<osiris::IExtensionsModule> const osiris::ExtensionsModuleControl::getModule() const [member function]\"" );
}
{ //property "title"[fget=::osiris::ExtensionsModuleControl::getTitle]
typedef ::osiris::String const & ( ::osiris::ExtensionsModuleControl::*fget )( ) const;
ExtensionsModuleControl_exposer.add_property(
"title"
, ::boost::python::make_function(
fget( &::osiris::ExtensionsModuleControl::getTitle )
, bp::return_value_policy< bp::copy_const_reference >() )
, "get property, built on top of \"osiris::String const & osiris::ExtensionsModuleControl::getTitle() const [member function]\"" );
}
{ //property "instance"[fget=::osiris::ExtensionsModuleControl::getInstance]
typedef ::osiris::UniqueID const & ( ::osiris::ExtensionsModuleControl::*fget )( ) const;
ExtensionsModuleControl_exposer.add_property(
"instance"
, ::boost::python::make_function(
fget( &::osiris::ExtensionsModuleControl::getInstance )
, bp::return_value_policy< bp::copy_const_reference >() )
, "get property, built on top of \"osiris::UniqueID const & osiris::ExtensionsModuleControl::getInstance() const [member function]\"" );
}
{ //property "moduleDocument"[fget=::osiris::ExtensionsModuleControl::getModuleDocument]
typedef ::boost::shared_ptr<osiris::XMLDocument> ( ::osiris::ExtensionsModuleControl::*fget )( ) const;
ExtensionsModuleControl_exposer.add_property(
"moduleDocument"
, fget( &::osiris::ExtensionsModuleControl::getModuleDocument )
, "get property, built on top of \"boost::shared_ptr<osiris::XMLDocument> osiris::ExtensionsModuleControl::getModuleDocument() const [member function]\"" );
}
}
}
|
gpl-3.0
|
vpsfreecz/vpsadmin-webui
|
webui/ajax.php
|
2438
|
<?php
/*
./ajax.php
vpsAdmin
Web-admin interface for OpenVZ (see http://openvz.org)
Copyright (C) 2008-2009 Pavel Snajdr, snajpa@snajpa.net
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License 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 '/etc/vpsadmin/config.php';
session_start();
define ('CRON_MODE', false);
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 11 Jan 1991 06:30:00 GMT"); // Date in the past
// Include libraries
include WWW_ROOT.'vendor/autoload.php';
include WWW_ROOT.'lib/version.lib.php';
include WWW_ROOT.'lib/xtemplate.lib.php';
include WWW_ROOT.'lib/functions.lib.php';
include WWW_ROOT.'lib/transact.lib.php';
include WWW_ROOT.'lib/vps.lib.php';
include WWW_ROOT.'lib/members.lib.php';
include WWW_ROOT.'lib/cluster.lib.php';
include WWW_ROOT.'lib/gettext_stream.lib.php';
include WWW_ROOT.'lib/gettext_inc.lib.php';
include WWW_ROOT.'lib/gettext_lang.lib.php';
$api = new \HaveAPI\Client(INT_API_URL, API_VERSION, client_identity());
$api->registerDescriptionChangeFunc('api_description_changed');
if($_SESSION["api_description"]) {
$api->setDescription($_SESSION["api_description"]);
}
// Create a template class
include WWW_ROOT.'config_cfg.php';
if ($_SESSION["logged_in"]) {
try {
$api->authenticate('token', array('token' => $_SESSION['session_token']), false);
if ($_SESSION["transactbox_expiration"] < time()) {
unset($_SESSION);
session_destroy();
$_GET["page"] = "";
}
switch ($_GET["page"]) {
case 'vps':
include WWW_ROOT.'pages/ajax_vps.php';
break;
default:
header("HTTP/1.0 404 Not Found");
}
} catch (\HaveAPI\Client\Exception\Base $e) {
echo "Connection to the API lost.";
} catch (\Httpful\Exception\ConnectionErrorException $e) {
echo "The API is not responding.";
}
} else {
header("HTTP/1.0 404 Not Found");
}
?>
|
gpl-3.0
|
wazari972/WebAlbums
|
WebAlbums-iService/src/net/wazari/service/exchange/ViewSessionPhoto.java
|
2492
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.wazari.service.exchange;
import net.wazari.service.exchange.ViewSession.VSession;
/**
*
* @author kevin
*/
public interface ViewSessionPhoto extends VSession {
enum Photo_Action {
MASSEDIT, EDIT, SUBMIT
}
enum Photo_Special {
VISIONNEUSE, FASTEDIT, ABOUT, RANDOM
}
interface ViewSessionPhotoFastEdit extends VSession {
Integer getId();
String getDesc();
Integer[] getTagSet();
enum TagAction {SET, ADD, RM}
TagAction getTagAction();
Integer getStars();
Integer getNewStarLevel();
void setStarLevel(Integer starLevel);
boolean getSuppr();
}
interface ViewSessionPhotoSimple extends VSession {
Integer getId();
String getPath();
}
interface ViewSessionPhotoSubmit extends VSession {
boolean getSuppr();
String getDesc();
boolean getRepresent();
String getDroit() ;
Integer[] getNewTag();
Integer[] getTags();
boolean getThemeBackground();
boolean getThemePicture();
Integer getId();
Integer getTagPhoto();
}
interface ViewSessionPhotoEdit extends VSession {
Integer getId();
Integer getAlbum();
Integer getAlbmPage();
Integer getPage();
}
interface ViewSessionAnAlbum extends VSession {
Integer getAlbum();
}
interface ViewSessionPhotoDisplayMassEdit {
enum Turn {
RIGHT, LEFT, TAG, UNTAG, MVTAG, NOTHING, AUTHOR
}
Turn getTurn();
boolean getChk(Integer id);
Integer[] getAddTags();
Integer getRmTag();
}
interface ViewSessionPhotoDisplay extends VSession {
boolean getWantMassedit();
ViewSessionPhotoDisplayMassEdit getMassEdit();
Integer getPage();
Integer getAlbum();
Integer getAlbmPage();
}
Photo_Action getPhotoAction();
Photo_Special getPhotoSpecial();
ViewSessionPhotoEdit getSessionPhotoEdit();
ViewSessionPhotoDisplay getSessionPhotoDisplay();
ViewSessionPhotoSubmit getSessionPhotoSubmit();
ViewSessionPhotoFastEdit getSessionPhotoFastEdit();
ViewSessionPhotoSimple getSessionPhotoSimple();
}
|
gpl-3.0
|
Saereth/AstralSorcery
|
src/main/java/hellfirepvp/astralsorcery/common/util/SoundHelper.java
|
4259
|
/*******************************************************************************
* HellFirePvP / Astral Sorcery 2017
*
* This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.common.util;
import hellfirepvp.astralsorcery.client.util.PositionedLoopSound;
import hellfirepvp.astralsorcery.common.util.data.Vector3;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: SoundHelper
* Created by HellFirePvP
* Date: 06.12.2016 / 12:45
*/
public class SoundHelper {
public static void playSoundAround(SoundEvent sound, World world, Vec3i position, float volume, float pitch) {
playSoundAround(sound, SoundCategory.MASTER, world, position.getX(), position.getY(), position.getZ(), volume, pitch);
}
public static void playSoundAround(SoundEvent sound, SoundCategory category, World world, Vec3i position, float volume, float pitch) {
playSoundAround(sound, category, world, position.getX(), position.getY(), position.getZ(), volume, pitch);
}
public static void playSoundAround(SoundEvent sound, World world, Vector3 position, float volume, float pitch) {
playSoundAround(sound, SoundCategory.MASTER, world, position.getX(), position.getY(), position.getZ(), volume, pitch);
}
public static void playSoundAround(SoundEvent sound, SoundCategory category, World world, Vector3 position, float volume, float pitch) {
playSoundAround(sound, category, world, position.getX(), position.getY(), position.getZ(), volume, pitch);
}
public static void playSoundAround(SoundEvent sound, SoundCategory category, World world, double posX, double posY, double posZ, float volume, float pitch) {
if(sound instanceof SoundUtils.CategorizedSoundEvent) {
category = ((SoundUtils.CategorizedSoundEvent) sound).getCategory();
}
world.playSound(null, posX, posY, posZ, sound, category, volume, pitch);
}
@SideOnly(Side.CLIENT)
public static PositionedLoopSound playSoundLoopClient(SoundEvent sound, Vector3 pos, float volume, float pitch, PositionedLoopSound.ActivityFunction func) {
SoundCategory cat = SoundCategory.MASTER;
if(sound instanceof SoundUtils.CategorizedSoundEvent) {
cat = ((SoundUtils.CategorizedSoundEvent) sound).getCategory();
}
PositionedLoopSound posSound = new PositionedLoopSound(sound, cat, volume, pitch, pos);
posSound.setRefreshFunction(func);
Minecraft.getMinecraft().getSoundHandler().playSound(posSound);
return posSound;
}
@SideOnly(Side.CLIENT)
public float getSoundVolume(SoundCategory cat) {
return Minecraft.getMinecraft().gameSettings.getSoundLevel(cat);
}
@SideOnly(Side.CLIENT)
public static void playSoundClient(SoundEvent sound, float volume, float pitch) {
EntityPlayerSP player = Minecraft.getMinecraft().player;
player.playSound(sound, volume, pitch);
}
@SideOnly(Side.CLIENT)
public static void playSoundClientWorld(SoundUtils.CategorizedSoundEvent sound, BlockPos pos, float volume, float pitch) {
playSoundClientWorld(sound, sound.getCategory(), pos, volume, pitch);
}
@SideOnly(Side.CLIENT)
public static void playSoundClientWorld(SoundEvent sound, SoundCategory cat, BlockPos pos, float volume, float pitch) {
if(Minecraft.getMinecraft().world != null) {
Minecraft.getMinecraft().world.playSound(Minecraft.getMinecraft().player, pos.getX(), pos.getY(), pos.getZ(), sound, cat, volume, pitch);
}
}
}
|
gpl-3.0
|
Traderain/Wolven-kit
|
WolvenKit.CR2W/Types/W3/RTTIConvert/W3PostFXOnGroundComponent.cs
|
1766
|
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class W3PostFXOnGroundComponent : CSelfUpdatingComponent
{
[Ordinal(1)] [RED("fadeInTime")] public CFloat FadeInTime { get; set;}
[Ordinal(2)] [RED("activeTime")] public CFloat ActiveTime { get; set;}
[Ordinal(3)] [RED("fadeOutTime")] public CFloat FadeOutTime { get; set;}
[Ordinal(4)] [RED("range")] public CFloat Range { get; set;}
[Ordinal(5)] [RED("type")] public CInt32 Type { get; set;}
[Ordinal(6)] [RED("updateDelay")] public CFloat UpdateDelay { get; set;}
[Ordinal(7)] [RED("stopAtDeath")] public CBool StopAtDeath { get; set;}
[Ordinal(8)] [RED("m_Actor")] public CHandle<CActor> M_Actor { get; set;}
[Ordinal(9)] [RED("m_DelaySinceLastUpdate")] public CFloat M_DelaySinceLastUpdate { get; set;}
[Ordinal(10)] [RED("m_DefaultFadeInTime")] public CFloat M_DefaultFadeInTime { get; set;}
[Ordinal(11)] [RED("m_DefaultActiveTime")] public CFloat M_DefaultActiveTime { get; set;}
[Ordinal(12)] [RED("m_DefaultFadeOutTime")] public CFloat M_DefaultFadeOutTime { get; set;}
[Ordinal(13)] [RED("m_DefaultRange")] public CFloat M_DefaultRange { get; set;}
public W3PostFXOnGroundComponent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3PostFXOnGroundComponent(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
}
|
gpl-3.0
|
Zanaj/AuraMaster-production
|
src/Shared/Network/Op.cs
|
20189
|
// Copyright (c) Aura development team - Licensed under GNU GPL
// For more information, see license file in the main folder
namespace Aura.Shared.Network
{
/// <summary>
/// All Op codes
/// </summary>
public static class Op
{
// Login Server
// ------------------------------------------------------------------
public const int ClientIdent = 0x0FD1020A;
public const int ClientIdentR = 0x1F;
public const int Login = 0x0FD12002;
public const int LoginR = 0x23;
public const int ChannelStatus = 0x26;
public const int CharacterInfoRequest = 0x29;
public const int CharacterInfoRequestR = 0x2A;
public const int CreateCharacter = 0x2B;
public const int CreateCharacterR = 0x2C;
public const int DeleteCharacterRequest = 0x2D;
public const int DeleteCharacterRequestR = 0x2E;
public const int ChannelInfoRequest = 0x2F;
public const int ChannelInfoRequestR = 0x30;
public const int DeleteCharacter = 0x35;
public const int DeleteCharacterR = 0x36;
public const int RecoverCharacter = 0x37;
public const int RecoverCharacterR = 0x38;
public const int NameCheck = 0x39;
public const int NameCheckR = 0x3A;
public const int PetInfoRequest = 0x3B;
public const int PetInfoRequestR = 0x3C;
public const int CreatePet = 0x3D;
public const int CreatePetR = 0x3E;
public const int DeletePetRequest = 0x3F;
public const int DeletePetRequestR = 0x40;
public const int DeletePet = 0x41;
public const int DeletePetR = 0x42;
public const int RecoverPet = 0x43;
public const int RecoverPetR = 0x44;
public const int CreatePartner = 0x45;
public const int CreatePartnerR = 0x46;
public const int AccountInfoRequest = 0x47;
public const int AccountInfoRequestR = 0x48;
public const int AcceptGift = 0x49;
public const int AcceptGiftR = 0x4A;
public const int RefuseGift = 0x4B;
public const int RefuseGiftR = 0x4C;
public const int DisconnectInform = 0x4D;
public const int PetCreationOptionsRequest = 0x50;
public const int PetCreationOptionsRequestR = 0x51;
public const int PartnerCreationOptionsRequest = 0x55;
public const int PartnerCreationOptionsRequestR = 0x56;
public const int LoginUnk = 0x5A; // Sent on login
public const int LoginUnkR = 0x5B; // ^ Response, only known parameter: 0 byte.
public const int TradeCard = 0x5C;
public const int TradeCardR = 0x5D;
// Channel Server
// ------------------------------------------------------------------
public const int ChannelLogin = 0x4E22;
public const int ChannelLoginR = 0x4E23;
public const int DisconnectRequest = 0x4E24;
public const int DisconnectRequestR = 0x4E25;
public const int RequestClientDisconnect = 0x4E26;
public const int Disappear = 0x4E2A;
public const int SwitchChannel = 0x4E32;
public const int SwitchChannelR = 0x4E33;
public const int GetChannelList = 0x4E34;
public const int GetChannelListR = 0x4E35;
public const int WarpUnk1 = 0x4E39;
public const int RequestRebirth = 0x4E84;
public const int RequestRebirthR = 0x4E85;
public const int PonsUpdate = 0x4E8F; // b:2, i:amount, sent on login
public const int ChannelCharacterInfoRequest = 0x5208;
public const int ChannelCharacterInfoRequestR = 0x5209;
public const int EntityAppears = 0x520C;
public const int EntityDisappears = 0x520D;
public const int CreatureBodyUpdate = 0x520E;
public const int ItemAppears = 0x5211;
public const int ItemDisappears = 0x5212;
public const int AssignSittingProp = 0x5215;
public const int Chat = 0x526C;
public const int Notice = 0x526D;
public const int WarpUnk2 = 0x526E;
public const int MsgBox = 0x526F;
public const int AcquireInfo = 0x5271;
public const int WhisperChat = 0x5273;
public const int BeginnerChat = 0x5275;
public const int AcquireInfo2 = 0x5278; // ?
public const int VisualChat = 0x527A;
public const int PropAppears = 0x52D0;
public const int PropDisappears = 0x52D1;
public const int PropUpdate = 0x52D2; // Doors, MGs?
public const int EntitiesAppear = 0x5334;
public const int EntitiesDisappear = 0x5335;
public const int RemoveDeathScreen = 0x53FD;
public const int IsNowDead = 0x53FC;
public const int Revive = 0x53FE;
public const int Revived = 0x53FF;
public const int DeadMenu = 0x5401;
public const int DeadMenuR = 0x5402;
public const int DeadFeather = 0x5403;
public const int UseGesture = 0x540E;
public const int UseGestureR = 0x540F;
public const int NpcTalkStart = 0x55F0;
public const int NpcTalkStartR = 0x55F1;
public const int NpcTalkEnd = 0x55F2;
public const int NpcTalkEndR = 0x55F3;
public const int NpcTalkPartner = 0x55F8;
public const int NpcTalkPartnerR = 0x55F9;
public const int ItemMove = 0x59D8;
public const int ItemMoveR = 0x59D9;
public const int ItemPickUp = 0x59DA;
public const int ItemPickUpR = 0x59DB;
public const int ItemDrop = 0x59DC;
public const int ItemDropR = 0x59DD;
public const int ItemMoveInfo = 0x59DE;
public const int ItemSwitchInfo = 0x59DF;
public const int ItemNew = 0x59E0;
public const int ItemRemove = 0x59E1;
public const int ItemDestroy = 0x59E2;
public const int ItemDestroyR = 0x59E4;
public const int EquipmentChanged = 0x59E6;
public const int EquipmentMoved = 0x59E7;
public const int ItemSplit = 0x59E8;
public const int ItemSplitR = 0x59E9;
public const int ItemAmount = 0x59EA;
public const int UseItem = 0x59EB;
public const int UseItemR = 0x59EC;
public const int UnequipBag = 0x59F4;
public const int UnequipBagR = 0x59F5;
// [180300, NA166 (18.09.2013)] 2 new ops
//public const int ? = 0x59F8; // Request for that --v ?
//public const int ? = 0x59F9; // "Unable to receive [something]."
// Does this actually have to do something with Npcs? Sent by the
// server when selecting "@end", before the actual NpcTalkEnd
public const int NpcTalkSelectEnd = 0x59FB;
public const int SwitchSet = 0x5BCD;
public const int SwitchSetR = 0x5BCE;
public const int UpdateWeaponSet = 0x5BCF;
public const int ItemStateChange = 0x5BD0;
public const int ItemStateChangeR = 0x5BD1;
public const int ItemUpdate = 0x5BD4;
public const int ItemDurabilityUpdate = 0x5BD5;
public const int ItemStateChanged = 0x5BD9;
public const int ItemExpUpdate = 0x5BDA;
public const int ViewEquipment = 0x5BDF;
public const int ViewEquipmentR = 0x5BE0;
public const int OptionSet = 0x5BE7;
public const int OptionSetR = 0x5BE8;
public const int AddKeyword = 0x5DC1;
public const int RemoveKeyword = 0x5DC3;
public const int NpcTalkKeyword = 0x5DC4;
public const int NpcTalkKeywordR = 0x5DC5;
public const int AddObserverRequest = 0x61A8;
public const int SetLocation = 0x6594;
public const int TurnTo = 0x6596;
public const int EnterRegion = 0x6597;
public const int EnterRegionRequest = 0x6598;
public const int WarpRegion = 0x6599; // on warp
public const int ForceRunTo = 0x659A;
public const int ForceWalkTo = 0x659B;
public const int EnterRegionRequestR = 0x659C; // on login
public const int UrlUpdateChronicle = 0x65A2;
public const int UrlUpdateAdvertise = 0x65A3;
public const int UrlUpdateGuestbook = 0x65A4;
public const int UrlUpdatePvp = 0x65A5;
public const int UrlUpdateDungeonBoard = 0x65A6;
public const int TakeOff = 0x65A8;
public const int TakingOff = 0x65A9;
public const int TakeOffR = 0x65AA;
public const int FlyTo = 0x65AE;
public const int FlyingTo = 0x65AF;
public const int Land = 0x65AB;
public const int Landing = 0x65AC;
public const int CanLand = 0x65AD;
public const int SkillInfo = 0x6979;
public const int SkillTrainingUp = 0x697C;
public const int SkillAdvance = 0x697E;
public const int SkillRankUp = 0x697F; // Response to Advance
public const int SkillPrepare = 0x6982;
public const int SkillReady = 0x6983;
public const int SkillUse = 0x6986;
public const int SkillComplete = 0x6987;
public const int SkillCancel = 0x6989;
public const int SkillStart = 0x698A;
public const int SkillStop = 0x698B;
public const int SkillPrepareSilentCancel = 0x698C;
public const int SkillUseSilentCancel = 0x698D;
//public const int ? = 0x698E; // no parameters, found after a Complete/Cancel with one of the special horses
public const int SkillStartSilentCancel = 0x698F;
public const int SkillStopSilentCancel = 0x6990;
public const int SkillStackSet = 0x6991;
public const int SkillStackUpdate = 0x6992;
public const int UseMotion = 0x6D62;
public const int PlayAnimation = 0x6D63; // s:data/.../anim/..., 1:0, 2:0, 1:0
public const int CancelMotion = 0x6D65;
public const int MotionCancel2 = 0x6D66; // Delayed?
public const int LevelUp = 0x6D69;
public const int RankUp = 0x6D6A;
public const int SitDown = 0x6D6C;
public const int StandUp = 0x6D6D;
public const int ArenaHideOn = 0x6D6F;
public const int ArenaHideOff = 0x6D70;
public const int ChangeStanceRequest = 0x6E28;
public const int ChangeStanceRequestR = 0x6E29;
public const int ChangeStance = 0x6E2A;
public const int RiseFromTheDead = 0x701D;
public const int CharacterLock = 0x701E;
public const int CharacterUnlock = 0x701F;
public const int PlayDead = 0x7021;
public const int OpenUmbrella = 0x7025;
public const int CloseUmbrella = 0x7026;
public const int SpreadWingsOn = 0x702E;
public const int SpreadWingsOff = 0x702F;
public const int NpcShopBuyItem = 0x7150;
public const int NpcShopBuyItemR = 0x7151;
public const int NpcShopSellItem = 0x7152;
public const int NpcShopSellItemR = 0x7153;
public const int ClearNpcShop = 0x7158; // Empties tabs
public const int AddToNpcShop = 0x7159; // Adds items while shop is open, works like open
public const int OpenNpcShop = 0x715E;
public const int OpenMail = 0x7242;
public const int CloseMail = 0x7243;
public const int ConfirmMailRecipent = 0x7244;
public const int ConfirmMailRecipentR = 0x7245;
public const int SendMail = 0x7246;
public const int SendMailR = 0x7247;
public const int GetMails = 0x7248;
public const int GetMailsR = 0x7249;
public const int MarkMailRead = 0x724A;
public const int MarkMailReadR = 0x724B;
public const int RecieveMailItem = 0x724C;
public const int ReceiveMailItemR = 0x724D;
public const int ReturnMail = 0x724E;
public const int ReturnMailR = 0x724F;
public const int DeleteMail = 0x7250;
public const int DeleteMailR = 0x7251;
public const int RecallMail = 0x7252;
public const int RecallMailR = 0x7253;
public const int UnreadMailCount = 0x7255;
public const int StatUpdatePrivate = 0x7530;
public const int StatUpdatePublic = 0x7532;
public const int CombatTargetUpdate = 0x791A; // ?
public const int CombatSetAim = 0x791D;
public const int CombatSetAimR = 0x791E;
public const int SetCombatTarget = 0x7920;
public const int SetFinisher = 0x7921;
public const int SetFinisher2 = 0x7922;
public const int CombatAction = 0x7924;
public const int CombatActionEnd = 0x7925;
public const int CombatActionPack = 0x7926;
public const int CombatUsedSkill = 0x7927;
public const int CombatAttackR = 0x7D01;
public const int EventInform = 0x88B8;
public const int NewQuest = 0x8CA0;
public const int QuestClear = 0x8CA1;
public const int QuestUpdate = 0x8CA2;
public const int CompleteQuest = 0x8CA3;
public const int CompleteQuestR = 0x8CA4;
public const int GiveUpQuest = 0x8CA5;
public const int GiveUpQuestR = 0x8CA6;
public const int QuestStartPTJ = 0x8D68; // ?
public const int QuestEndPTJ = 0x8D69; // ?
public const int QuestUpdatePTJ = 0x8D6A;
public const int PartyCreate = 0x8E94;
public const int PartyCreateR = 0x8E95;
public const int PartyCreateUpdate = 0x8E96;
public const int PartyJoin = 0x8E97;
public const int PartyJoinR = 0x8E98;
public const int PartyJoinUpdate = 0x8E99;
public const int PartyLeave = 0x8E9A;
public const int PartyLeaveR = 0x8E9B;
public const int PartyLeaveUpdate = 0x8E9C;
public const int PartyRemove = 0x8E9D;
public const int PartyRemoveR = 0x8E9E;
public const int PartyRemoved = 0x8E9F;
public const int PartyChangeSetting = 0x8EA0;
public const int PartyChangeSettingR = 0x8EA1;
public const int PartySettingUpdate = 0x8EA2;
public const int PartyChangePassword = 0x8EA3;
public const int PartyChangePasswordR = 0x8EA4;
public const int PartyChangeLeader = 0x8EA5;
public const int PartyChangeLeaderR = 0x8EA6;
public const int PartyChangeLeaderUpdate = 0x8EA7;
public const int PartyWantedShow = 0x8EA9;
public const int PartyWantedShowR = 0x8EAA;
public const int PartyWantedOpened = 0x8EAB;
public const int PartyWantedHide = 0x8EAC;
public const int PartyWantedHideR = 0x8EAD;
public const int PartyWantedClosed = 0x8EAE;
public const int PartyChangeFinish = 0x8EB5;
public const int PartyChangeFinishR = 0x8EB6;
public const int PartyFinishUpdate = 0x8EB7;
public const int PartyChangeExp = 0x8EB8;
public const int PartyChangeExpR = 0x8EB9;
public const int PartyExpUpdate = 0x8EBA;
public const int GuildInfoNoGuild = 0x8EFB;
public const int OpenGuildPanel = 0x8EFC;
public const int GuildInfo = 0x8EFD;
public const int GuildApply = 0x8EFF;
public const int GuildApplyR = 0x8F00;
public const int GuildMembershipChanged = 0x8F01;
public const int GuildstoneLocation = 0x8F02;
public const int ConvertGp = 0x8F03;
public const int ConvertGpR = 0x8F04;
public const int ConvertGpConfirm = 0x8F05;
public const int ConvertGpConfirmR = 0x8F06;
public const int GuildDonate = 0x8F07;
public const int GuildDonateR = 0x8F08;
public const int GuildMessage = 0x8F0F;
public const int AddTitleKnowledge = 0x8FC0;
public const int AddTitle = 0x8FC1;
public const int ChangeTitle = 0x8FC4;
public const int TitleUpdate = 0x8FC5;
public const int ChangeTitleR = 0x8FC6;
public const int PetRegister = 0x9024;
public const int PetUnregister = 0x9025;
public const int SummonPet = 0x902C;
public const int SummonPetR = 0x902D;
public const int UnsummonPet = 0x9031;
public const int UnsummonPetR = 0x9032;
public const int TelePet = 0x9033;
public const int TelePetR = 0x9034;
public const int PutItemIntoPetInv = 0x9035;
public const int PutItemIntoPetInvR = 0x9036;
public const int TakeItemFromPetInv = 0x9037;
public const int TakeItemFromPetInvR = 0x9038;
public const int HitProp = 0x9088;
public const int HitPropR = 0x9089;
public const int HittingProp = 0x908A;
public const int TouchProp = 0x908B;
public const int TouchPropR = 0x908C;
public const int PropInteraction = 0x908D; // Doors?
public const int PlaySound = 0x908F;
public const int Effect = 0x9090;
public const int EffectDelayed = 0x9091;
public const int QuestOwlComplete = 0x9093;
public const int QuestOwlNew = 0x9094;
public const int PartyWantedUpdate = 0x9095;
public const int PvPInformation = 0x9096;
public const int NaoRevivalExit = 0x9098;
public const int NaoRevivalEntrance = 0x909C;
public const int DungeonInfo = 0x9470;
public const int ArenaRoundInfo = 0x9667;
public const int ArenaRoundInfoCancel = 0x9668;
public const int AgeUpEffect = 0x9858;
public const int ConditionUpdate = 0xA028;
public const int DyePaletteReq = 0xA418;
public const int DyePaletteReqR = 0xA419;
public const int DyePickColor = 0xA41A;
public const int DyePickColorR = 0xA41B;
public const int Transformation = 0xA41C;
public const int PetAction = 0xA41D;
public const int SharpMind = 0xA41E;
public const int MoonGateInfoRequest = 0xA428;
public const int MoonGateInfoRequestR = 0xA429;
public const int MoonGateMap = 0xA42D;
public const int MoonGateUse = 0xA42E;
public const int MoonGateUseR = 0xA42F;
public const int ItemShopInfo = 0xA436;
public const int PartyWindowUpdate = 0xA43C;
public const int ContinentWarpCoolDown = 0xA43D;
public const int ContinentWarpCoolDownR = 0xA43E;
public const int PartyTypeUpdate = 0xA44B;
public const int OpenItemShop = 0xA44D;
// [150000~180000] Something was removed here
public const int MailsRequest = 0xA897;
public const int MailsRequestR = 0xA898;
public const int SetPetAi = 0xA8A1;
public const int GetPetAi = 0xA8A2;
public const int GetPetAiR = 0xA8A3;
public const int WarpUnk3 = 0xA8AF;
public const int UmbrellaJump = 0xA8E0;
public const int UmbrellaJumpR = 0xA8E1;
public const int UmbrellaLand = 0xA8E2;
public const int SetBgm = 0xA910;
public const int UnsetBgm = 0xA911;
public const int EnableRoyalAlchemist = 0xA9A3;
public const int SosButtonRequest = 0xA9A9;
public const int SosButtonRequestR = 0xA9AA;
public const int SkillTeleport = 0xA9F0;
// [150000~180000] Something was added? Next two ops changed.
// [180800, NA196] Something was added? Ops 0xAAXX - 0xABXX increased by 4.
public const int SubsribeStunMeter = 0xAA21;
public const int StunMeterTotal = 0xAA22;
public const int StunMeterUpdate = 0xAA23;
public const int HomesteadInfoRequest = 0xAA58;
public const int HomesteadInfoRequestR = 0xAA59;
// [180300, NA166 (18.09.2013)] 2 new ops somewhere here, possibly the two below
public const int ChannelLoginUnk = 0xAA87;
public const int ChannelLoginUnkR = 0xAA88;
public const int CollectionRequest = 0xAA8B;
public const int CollectionRequestR = 0xAA8C;
public const int UnkEsc = 0xAAF3;
public const int GoBeautyShop = 0xAAF8;
public const int GoBeautyShopR = 0xAAF9;
public const int LeaveBeautyShop = 0xAAFA;
public const int LeaveBeautyShopR = 0xAAFB;
public const int OpenBeautyShop = 0xAAFC;
//public const int ? = 0xAAFD; // Buy looks?
//public const int ? = 0xAAFE; // Buy looks R?
public const int CancelBeautyShop = 0xAAFF;
public const int CancelBeautyShopR = 0xAB00;
public const int TalentInfoUpdate = 0xAB17;
public const int TalentTitleChange = 0xAB18;
public const int TalentTitleUpdate = 0xAB19;
public const int ShamalaTransformationUpdate = 0xAB1B;
public const int ShamalaTransformationUse = 0xAB1C;
public const int ShamalaTransformation = 0xAB1D;
public const int ShamalaTransformationEnd = 0xAB1E;
public const int ShamalaTransformationEndR = 0xAB1F;
public const int NpcTalk = 0x13882;
public const int NpcTalkSelect = 0x13883;
public const int SpecialLogin = 0x15F90; // ?
public const int EnterSoulStream = 0x15F91;
//public const int ? = 0x15F92;
public const int LeaveSoulStream = 0x15F93;
public const int LeaveSoulStreamR = 0x15F94;
public const int FinishedCutscene = 0x186A0;
public const int PlayCutscene = 0x186A6;
public const int CutsceneEnd = 0x186A7;
public const int CutsceneUnk = 0x186A8;
public const int Weather = 0x1ADB0;
public const int GmcpOpen = 0x1D589;
public const int GmcpClose = 0x1D58A;
public const int GmcpSummon = 0x1D58B;
public const int GmcpMoveToChar = 0x1D58C;
public const int GmcpWarp = 0x1D58D;
public const int GmcpRevive = 0x1D58E;
public const int GmcpInvisibility = 0x1D58F;
public const int GmcpInvisibilityR = 0x1D590;
public const int GmcpSearch = 0x1D595;
public const int GmcpExpel = 0x1D596;
public const int GmcpBan = 0x1D597;
public const int GmcpNpcList = 0x1D59F;
public const int GmcpNpcListR = 0x1D5A0;
public const int PetMount = 0x1FBD0;
public const int PetMountR = 0x1FBD1;
public const int PetUnmount = 0x1FBD2;
public const int PetUnmountR = 0x1FBD3;
public const int VehicleInfo = 0x1FBD4;
public const int Run = 0x0F213303;
public const int Running = 0x0F44BBA3;
public const int CombatAttack = 0x0FCC3231;
public const int Walking = 0x0FD13021;
public const int Walk = 0x0FF23431;
//shit I added
public const int HandicraftUse = 0x699e;
// Internal communication
// ------------------------------------------------------------------
public static class Internal
{
public const int ServerIdentify = 0x42420001;
public const int ServerIdentifyR = 0x42420002;
public const int ChannelStatus = 0x42420101;
public const int BroadcastNotice = 0x42420201;
}
}
// public const int MailsRequest = 0xA898;
// public const int MailsRequestR = 0xA899;
}
|
gpl-3.0
|
alickyao/studyCSharp
|
NewCyclone/NewCyclone/Areas/HelpPage/HelpPageAreaRegistration.cs
|
693
|
using System.Web.Http;
using System.Web.Mvc;
namespace NewCyclone.Areas.HelpPage
{
public class HelpPageAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "HelpPage";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HelpPage_Default",
"Help/{action}/{apiId}",
new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });
HelpPageConfig.Register(GlobalConfiguration.Configuration);
}
}
}
|
gpl-3.0
|
Muzietto/jcip-jciop
|
src/main/java/net/faustinelli/javafx/ensemble/samples/charts/area/AdvancedAreaChartSample.java
|
17291
|
/*
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* 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 Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.faustinelli.javafx.ensemble.samples.charts.area;
import net.faustinelli.javafx.ensemble.Sample;
import net.faustinelli.javafx.ensemble.controls.PropertySheet;
import net.faustinelli.javafx.ensemble.util.ChartActions;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.util.Duration;
/**
*
* An advanced area chart with a variety of actions and settable properties
* for experimenting with the charts features.
*
* @see javafx.scene.chart.AreaChart
* @see javafx.scene.chart.Chart
* @see javafx.scene.chart.LineChart
* @see javafx.scene.chart.NumberAxis
* @see javafx.scene.chart.XYChart
*/
public class AdvancedAreaChartSample extends Sample {
public AdvancedAreaChartSample() {
getChildren().add(createChart());
}
protected AreaChart<Number, Number> createChart() {
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
AreaChart<Number,Number> ac = new AreaChart<Number,Number>(xAxis,yAxis);
// setup chart
ac.setTitle("Area Chart Example");
xAxis.setLabel("X Axis");
yAxis.setLabel("Y Axis");
// add starting data
for (int s=0;s<3;s++) {
XYChart.Series<Number,Number> series = new XYChart.Series<Number,Number>();
series.setName("Data Series "+s);
double x = 0;
while (x<95) {
series.getData().add(new XYChart.Data<Number,Number>(x, Math.random()*99));
x += 5 + (15*Math.random());
}
series.getData().add(new XYChart.Data<Number,Number>(99d, Math.random()*99));
ac.getData().add(series);
}
return ac;
}
// REMOVE ME
@Override public Node getSideBarExtraContent() {
return createPropertySheet();
}
@Override public String getSideBarExtraContentTitle() {
return "Chart Properties";
}
protected PropertySheet createPropertySheet() {
final AreaChart<Number,Number> ac = (AreaChart<Number,Number>)getChildren().get(0);
final NumberAxis xAxis = (NumberAxis)ac.getXAxis();
final NumberAxis yAxis = (NumberAxis)ac.getYAxis();
// create actions
EventHandler<ActionEvent> addDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (ac.getData() != null && !ac.getData().isEmpty()) {
XYChart.Series<Number, Number> s = ac.getData().get((int)(Math.random()*ac.getData().size()));
if(s!=null) {
double x = Math.random()*50;
double y = Math.random()*50;
s.getData().add(0, new AreaChart.Data<Number,Number>(x,y));
}
}
}
};
EventHandler<ActionEvent> insertDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ObservableList<XYChart.Series<Number, Number>> data = ac.getData();
if (data != null && !data.isEmpty()) {
XYChart.Series<Number, Number> s = data.get((int) (Math.random() * data.size()));
if(s!=null) s.getData().add((int)(s.getData().size()*Math.random()) ,
new LineChart.Data<Number,Number>(Math.random()*1000, Math.random()*1000));
}
}
};
EventHandler<ActionEvent> addDataItemNegative = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ObservableList<XYChart.Series<Number, Number>> data = ac.getData();
if (data != null && !data.isEmpty()) {
XYChart.Series<Number, Number> s = data.get((int) (Math.random() * data.size()));
if(s!=null) s.getData().add(new AreaChart.Data<Number,Number>(Math.random()*-200, Math.random()*-200));
}
}
};
EventHandler<ActionEvent> deleteDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ChartActions.deleteDataItem(ac);
}
};
EventHandler<ActionEvent> changeDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ObservableList<XYChart.Series<Number, Number>> data = ac.getData();
if (data != null && !data.isEmpty()) {
XYChart.Series<Number, Number> s = data.get((int) (Math.random() * (data.size())));
if(s!=null && !s.getData().isEmpty()) {
XYChart.Data<Number,Number> d = s.getData().get((int)(Math.random()*(s.getData().size())));
if (d!=null) {
d.setXValue(d.getXValue().doubleValue() + (Math.random() * 50) -25);
d.setYValue(Math.random() * 1000);
}
}
}
}
};
EventHandler<ActionEvent> addSeries = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (ac.getData() == null) {
ac.setData(FXCollections.<Series<Number, Number>>observableArrayList());
}
AreaChart.Series<Number,Number> series = new AreaChart.Series<Number,Number>();
series.setName("Data Series 1");
double x = 0;
for (int i=0; i<10; i++) {
x += Math.random()*100;
series.getData().add(new AreaChart.Data<Number, Number>(x, Math.random()*800));
}
ac.getData().add(series);
}
};
EventHandler<ActionEvent> deleteSeries = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (ac.getData() != null && !ac.getData().isEmpty()) {
ac.getData().remove((int)(Math.random() * ac.getData().size()));
}
}
};
EventHandler<ActionEvent> animateData = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (ac.getData() == null) {
return;
}
Timeline tl = new Timeline();
tl.getKeyFrames().add(
new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
for (XYChart.Series<Number, Number> series: ac.getData()) {
for (XYChart.Data<Number, Number> data: series.getData()) {
data.setXValue(Math.random()*1000);
data.setYValue(Math.random()*1000);
}
}
}
})
);
tl.setCycleCount(30);
tl.play();
}
};
EventHandler<ActionEvent> animateDataFast = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (ac.getData() == null) {
return;
}
ac.setAnimated(false);
Timeline tl = new Timeline();
tl.getKeyFrames().add(
new KeyFrame(Duration.millis(50), new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
for (XYChart.Series<Number, Number> series: ac.getData()) {
for (XYChart.Data<Number, Number> data: series.getData()) {
data.setXValue(-500 + Math.random()*1000);
data.setYValue(-500 + Math.random()*1000);
}
}
}
})
);
tl.setOnFinished(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ac.setAnimated(true);
}
});
tl.setCycleCount(100);
tl.play();
}
};
EventHandler<ActionEvent> removeAllData = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ac.setData(null);
}
};
EventHandler<ActionEvent> setNewData = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ObservableList<XYChart.Series<Number,Number>> data = FXCollections.observableArrayList();
for (int j=0; j<5;j++) {
AreaChart.Series<Number,Number> series = new AreaChart.Series<Number,Number>();
series.setName("Data Series "+j);
double x = 0;
for (int i=0; i<10; i++) {
x += Math.random()*100;
series.getData().add(new AreaChart.Data<Number,Number>(x, Math.random()*800));
}
data.add(series);
}
ac.setData(data);
}
};
//Create X/Y side overriding values to filter out unhelpful values
List<Enum> xValidSides = new ArrayList();
xValidSides.add(Side.BOTTOM);
xValidSides.add(Side.TOP);
List<Enum> yValidSides = new ArrayList();
yValidSides.add(Side.LEFT);
yValidSides.add(Side.RIGHT);
// create property sheet
return new PropertySheet(
new PropertySheet.PropertyGroup("Actions",
PropertySheet.createProperty("Add Data Item",addDataItem),
PropertySheet.createProperty("Insert Data Item",insertDataItem),
PropertySheet.createProperty("Add Data Item Negative",addDataItemNegative),
PropertySheet.createProperty("Delete Data Item",deleteDataItem),
PropertySheet.createProperty("Change Data Item",changeDataItem),
PropertySheet.createProperty("Add Series",addSeries),
PropertySheet.createProperty("Delete Series",deleteSeries),
PropertySheet.createProperty("Remove All Data",removeAllData),
PropertySheet.createProperty("Set New Data",setNewData)
),
new PropertySheet.PropertyGroup("Chart Properties",
PropertySheet.createProperty("Title",ac.titleProperty()),
PropertySheet.createProperty("Title Side",ac.titleSideProperty()),
PropertySheet.createProperty("Legend Side",ac.legendSideProperty())
),
new PropertySheet.PropertyGroup("XY Chart Properties",
PropertySheet.createProperty("Vertical Grid Line Visible",ac.verticalGridLinesVisibleProperty()),
PropertySheet.createProperty("Horizontal Grid Line Visible",ac.horizontalGridLinesVisibleProperty()),
PropertySheet.createProperty("Alternative Column Fill Visible",ac.alternativeColumnFillVisibleProperty()),
PropertySheet.createProperty("Alternative Row Fill Visible",ac.alternativeRowFillVisibleProperty()),
PropertySheet.createProperty("Vertical Zero Line Visible",ac.verticalZeroLineVisibleProperty()),
PropertySheet.createProperty("Horizontal Zero Line Visible",ac.horizontalZeroLineVisibleProperty()),
PropertySheet.createProperty("Animated",ac.animatedProperty())
),
new PropertySheet.PropertyGroup("X Axis Properties",
PropertySheet.createProperty("Side",xAxis.sideProperty(), xValidSides),
PropertySheet.createProperty("Label",xAxis.labelProperty()),
PropertySheet.createProperty("Tick Mark Length",xAxis.tickLengthProperty()),
PropertySheet.createProperty("Auto Ranging",xAxis.autoRangingProperty()),
PropertySheet.createProperty("Tick Label Font",xAxis.tickLabelFontProperty()),
PropertySheet.createProperty("Tick Label Fill",xAxis.tickLabelFillProperty()),
PropertySheet.createProperty("Tick Label Gap",xAxis.tickLabelGapProperty()),
// Value Axis Props
//PropertySheet.createProperty("Scale",xAxis.scaleProperty(), true),
PropertySheet.createProperty("Lower Bound",xAxis.lowerBoundProperty(), true),
PropertySheet.createProperty("Upper Bound",xAxis.upperBoundProperty(), true),
PropertySheet.createProperty("Tick Label Formatter",xAxis.tickLabelFormatterProperty()),
PropertySheet.createProperty("Minor Tick Length",xAxis.minorTickLengthProperty()),
PropertySheet.createProperty("Minor Tick Count",xAxis.minorTickCountProperty()),
// Number Axis Properties
PropertySheet.createProperty("Force Zero In Range",xAxis.forceZeroInRangeProperty()),
PropertySheet.createProperty("Tick Unit",xAxis.tickUnitProperty())
),
new PropertySheet.PropertyGroup("Y Axis Properties",
PropertySheet.createProperty("Side",yAxis.sideProperty(), yValidSides),
PropertySheet.createProperty("Label",yAxis.labelProperty()),
PropertySheet.createProperty("Tick Mark Length",yAxis.tickLengthProperty()),
PropertySheet.createProperty("Auto Ranging",yAxis.autoRangingProperty()),
PropertySheet.createProperty("Tick Label Font",yAxis.tickLabelFontProperty()),
PropertySheet.createProperty("Tick Label Fill",yAxis.tickLabelFillProperty()),
PropertySheet.createProperty("Tick Label Gap",yAxis.tickLabelGapProperty()),
// Value Axis Props
//PropertySheet.createProperty("Scale",yAxis.scaleProperty(), true),
PropertySheet.createProperty("Lower Bound",yAxis.lowerBoundProperty(), true),
PropertySheet.createProperty("Upper Bound",yAxis.upperBoundProperty(), true),
PropertySheet.createProperty("Tick Label Formatter",yAxis.tickLabelFormatterProperty()),
PropertySheet.createProperty("Minor Tick Length",yAxis.minorTickLengthProperty()),
PropertySheet.createProperty("Minor Tick Count",yAxis.minorTickCountProperty()),
// Number Axis Properties
PropertySheet.createProperty("Force Zero In Range",yAxis.forceZeroInRangeProperty()),
PropertySheet.createProperty("Tick Unit",yAxis.tickUnitProperty())
)
);
}
// END REMOVE ME
}
|
gpl-3.0
|
bnetcc/darkstar
|
scripts/zones/Lower_Jeuno/npcs/Rakuru_Rakoru.lua
|
848
|
--------------------------------------------------------------
--Rakuru-Rakoru
--Lower Jeuno
-- Adds all BLU spells
--------------------------------------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
|
gpl-3.0
|
isalnikov/ACMP
|
src/test/java/ru/isalnikov/acmp/acmp327/MainTest.java
|
756
|
/*
* 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.
*/
package ru.isalnikov.acmp.acmp327;
import java.io.ByteArrayInputStream;
import org.junit.Test;
import static org.junit.Assert.*;
import ru.isalnikov.acmp.base.BaseTest;
public class MainTest extends BaseTest {
@Test
public void test1() {
String data = "3\n"
+ "715068\n"
+ "445219\n"
+ "012200";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Main.main(null);
assertEquals("Yes\n"
+ "No\n"
+ "Yes\n", outContent.toString());
}
}
|
gpl-3.0
|
DBCDK/hejmdal
|
src/utils/attribute.mapper.util.js
|
4266
|
/**
* @file
*
* Maps data from CULR (and IDprovider) as specified by the Smaug-setting for the given serviceClient
*
*/
import {log} from './logging.util';
import {mapFromCpr} from './cpr.util';
import {getInstitutionsForUser} from '../components/UniLogin/unilogin.component';
import {getAgencyRights} from '../components/Forsrights/forsrights.client.js';
import {getDbcidpAgencyRights} from '../components/DBCIDP/dbcidp.client';
/**
* Attribute mapper
*
* @param req
* @param res
* @param next
* @returns {*}
*/
export default async function mapAttributesToTicket(req, res, next) {
const state = req.getState();
const user = req.getUser();
if (state && state.serviceClient && state.culr) {
const serviceAttributes = state.serviceClient.attributes;
const culr = state.culr;
const ticketAttributes = await mapCulrResponse(
culr,
serviceAttributes,
user,
state.serviceClient.id
);
req.setState({ticket: {attributes: ticketAttributes}});
}
await next();
}
/**
* Maps the response from CULR according to the given array of fields
*
* @param {object} culr The CULR reponse object
* @param {object} attributes The attributes object defined in Smaug
* @param {object} user data returned by the idp
* @param clientId
* @param accessToken
* @see ATTRIBUTES
* @returns {Promise<{}>}
*/
export async function mapCulrResponse(
culr,
attributes,
user,
clientId,
accessToken
) {
let mapped = {};
let cpr = user.cpr || null;
let agencies = [];
let fromCpr = {};
if (culr.accounts && Array.isArray(culr.accounts)) {
culr.accounts.forEach(account => {
if (account.userIdType === 'CPR' && !cpr) {
cpr = account.userIdValue;
}
agencies.push({
agencyId: account.provider,
userId: account.userIdValue,
userIdType: account.userIdType
});
});
} else if (cpr && user.agency) {
agencies.push({
agencyId: user.agency,
userId: cpr,
userIdType: 'CPR'
});
}
if (cpr) {
fromCpr = mapFromCpr(cpr);
}
const fields = Object.keys(attributes);
await Promise.all(
fields.map(async field => { // eslint-disable-line complexity
// eslint-disable-line complexity
try {
switch (field) {
case 'birthDate':
case 'birthYear':
case 'gender':
mapped[field] = fromCpr[field] || null;
break;
case 'cpr':
mapped.cpr = cpr;
break;
case 'agencies':
case 'libraries':
mapped.agencies = agencies;
break;
case 'municipality':
mapped.municipality = culr.municipalityNumber || null;
break;
case 'municipalityAgencyId':
mapped.municipalityAgencyId = culr.municipalityAgencyId || null;
break;
case 'uniloginId':
mapped.uniloginId = user.uniloginId || null;
break;
case 'userId':
mapped.userId = user.userId;
break;
case 'pincode':
mapped.pincode = user.pincode;
break;
case 'wayfId':
mapped.wayfId = user.wayfId ? user.wayfId : null;
break;
case 'uniqueId':
mapped.uniqueId = culr.culrId;
break;
case 'uniLoginInstitutions': {
mapped.uniLoginInstitutions =
(user.uniloginId &&
(await getInstitutionsForUser(user.uniloginId))) ||
[];
break;
}
case 'netpunktAgency':
mapped.netpunktAgency = user.agency || null;
break;
case 'forsrights':
mapped.forsrights = await getAgencyRights(accessToken, [
user.agency
]);
break;
case 'dbcidp':
mapped.dbcidp = await getDbcidpAgencyRights(accessToken, user);
break;
default:
log.warn('Cannot map attribute: ' + field);
break;
}
} catch (error) {
log.error('Failed to map attribute: ' + field, {
error: error.message,
stack: error.stack
});
}
})
);
return mapped;
}
|
gpl-3.0
|
PhilippC/keepass2android
|
src/keepass2android/settings/RoundsPreference.cs
|
4861
|
/*
This file is part of Keepass2Android, Copyright 2013 Philipp Crocoll. This file is based on Keepassdroid, Copyright Brian Pellin.
Keepass2Android 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.
Keepass2Android 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 Keepass2Android. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Globalization;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using Android.Preferences;
using KeePassLib;
using Android.Util;
using KeePassLib.Cryptography.KeyDerivation;
namespace keepass2android.settings
{
public abstract class KdfNumberParamPreference: DialogPreference {
internal TextView edittext;
protected override View OnCreateDialogView() {
View view = base.OnCreateDialogView();
edittext = (TextView) view.FindViewById(Resource.Id.rounds);
ulong numRounds = ParamValue;
edittext.Text = numRounds.ToString(CultureInfo.InvariantCulture);
view.FindViewById<TextView>(Resource.Id.rounds_explaination).Text = ExplanationString;
return view;
}
public virtual string ExplanationString
{
get { return ""; }
}
public abstract ulong ParamValue { get; set; }
public KdfNumberParamPreference(Context context, IAttributeSet attrs):base(context, attrs) {
}
public KdfNumberParamPreference(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
}
protected override void OnDialogClosed(bool positiveResult) {
base.OnDialogClosed(positiveResult);
if ( positiveResult ) {
ulong paramValue;
String strRounds = edittext.Text;
if (!(ulong.TryParse(strRounds,out paramValue)))
{
Toast.MakeText(Context, Resource.String.error_param_not_number, ToastLength.Long).Show();
return;
}
if ( paramValue < 1 ) {
paramValue = 1;
}
Database db = App.Kp2a.CurrentDb;
ulong oldValue = ParamValue;
if (oldValue == paramValue)
{
return;
}
ParamValue = paramValue;
Handler handler = new Handler();
SaveDb save = new SaveDb((Activity)Context, App.Kp2a, App.Kp2a.CurrentDb, new KdfNumberParamPreference.AfterSave((Activity)Context, handler, oldValue, this));
ProgressTask pt = new ProgressTask(App.Kp2a, (Activity)Context, save);
pt.Run();
}
}
private class AfterSave : OnFinish {
private readonly ulong _oldRounds;
private readonly Context _ctx;
private readonly KdfNumberParamPreference _pref;
public AfterSave(Activity ctx, Handler handler, ulong oldRounds, KdfNumberParamPreference pref):base(ctx, handler) {
_pref = pref;
_ctx = ctx;
_oldRounds = oldRounds;
}
public override void Run() {
if ( Success ) {
if ( _pref.OnPreferenceChangeListener != null ) {
_pref.OnPreferenceChangeListener.OnPreferenceChange(_pref, null);
}
} else {
DisplayMessage(_ctx);
App.Kp2a.CurrentDb.KpDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds, _oldRounds);
}
base.Run();
}
}
}
/// <summary>
/// Represents the setting for the number of key transformation rounds. Changing this requires to save the database.
/// </summary>
public class RoundsPreference : KdfNumberParamPreference {
private readonly Context _context;
public ulong KeyEncryptionRounds
{
get
{
AesKdf kdf = new AesKdf();
if (!kdf.Uuid.Equals(App.Kp2a.CurrentDb.KpDatabase.KdfParameters.KdfUuid))
return (uint) PwDefs.DefaultKeyEncryptionRounds;
else
{
ulong uRounds = App.Kp2a.CurrentDb.KpDatabase.KdfParameters.GetUInt64(
AesKdf.ParamRounds, PwDefs.DefaultKeyEncryptionRounds);
uRounds = Math.Min(uRounds, 0xFFFFFFFEUL);
return (uint) uRounds;
}
}
set { App.Kp2a.CurrentDb.KpDatabase.KdfParameters.SetUInt64(AesKdf.ParamRounds, value); }
}
public RoundsPreference(Context context, IAttributeSet attrs):base(context, attrs)
{
_context = context;
}
public RoundsPreference(Context context, IAttributeSet attrs, int defStyle): base(context, attrs, defStyle)
{
_context = context;
}
public override string ExplanationString
{
get { return _context.GetString(Resource.String.rounds_explaination); }
}
public override ulong ParamValue
{
get { return KeyEncryptionRounds; }
set { KeyEncryptionRounds = value; }
}
}
}
|
gpl-3.0
|
komatsuyuji/jhako
|
frontends/public/app/controller/history/Flowchart.js
|
7342
|
/////////////////////////////////////////////////////////////////////////////////
//
// jHako WebGUI
// Copyright (C) 2014-2015 Komatsu Yuji(Zheng Chuyu)
//
// 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/>.
//
/////////////////////////////////////////////////////////////////////////////////
Ext.define('Jhako.controller.history.Flowchart', {
extend: 'Ext.app.Controller',
refs: [{
ref: 'historyFlowchart',
selector: 'historyFlowchart'
}, {
ref: 'historyJobunitTab',
selector: 'historyJobunitTab'
}],
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
init: function() {
this.control({
'historyFlowchart': {
afterrender: this.onAfterRender,
mousedown: this.onMousedown,
dblclick: this.onDblclick,
}
});
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onReset: function() {
var me = this;
var flowchart = me.getHistoryFlowchart();
var surface = flowchart.surface;
if (!surface)
return;
surface.removeAll();
surface.selectedjob = null;
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onAfterRender: function(flowchart) {
var surface = flowchart.surface;
surface.selectedjob = null;
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onMousedown: function(e) {
var me = this;
var flowchart = me.getHistoryFlowchart();
var surface = flowchart.surface;
surface.getGroup('flowchart_choice').hide(true);
surface.selectedjob = null;
var tab = me.getHistoryJobunitTab();
tab.setActiveTab('comm_jobnet');
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onDblclick: function(e) {
var me = this;
var flowchart = me.getHistoryFlowchart();
var surface = flowchart.surface;
if (!surface.selectedjob)
return;
var record = surface.selectedjob;
if (!(record.data.kind > JOBUNIT_KIND_ROOTJOBNET && record.data.kind < JOBUNIT_KIND_STARTJOB))
return;
me.onReset();
var ctrl = Jhako.app.getController('history.List');
ctrl.onLoadJobnet(record.data.id);
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onDrawFlowchart: function(record) {
if (!record) return;
var me = this;
var flowchart = me.getHistoryFlowchart();
var surface = flowchart.surface;
if (surface) surface.removeAll();
else return;
surface.add(new Jhako.draw.Choice()).hide(true);
if ('jhako.model.histjobunitsStore' in record) {
var store = record['jhako.model.histjobunitsStore'];
store.getRange().forEach(function(job) {
me.onDrawJob(job);
});
record['jhako.model.connectorsStore'].each(function(conn) {
prev_job = store.getById(conn.data.prev_jobid)
next_job = store.getById(conn.data.next_jobid);
if (!prev_job || !next_job)
return;
me.onDrawConnector(conn, prev_job, next_job);
});
};
var ctrl = Jhako.app.getController('history.JobunitTab');
ctrl.onLoadJobunit(record);
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onDrawConnector: function(record, prev_job, next_job) {
var me = this;
var flowchart = me.getHistoryFlowchart();
var surface = flowchart.surface;
var connector = new Jhako.draw.ConnectorView(record, prev_job, next_job);
surface.add(connector);
var group = surface.getGroup('spriteconn_' + record.data.id);
group.show(true);
return group;
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onDrawJob: function(record) {
var me = this;
var flowchart = me.getHistoryFlowchart();
var surface = flowchart.surface;
surface.add(new Jhako.draw.JobView(record));
var group = surface.getGroup('spritegroup_' + record.data.id);
group.on({
'mousedown': me.onMousedownJob,
});
group.show(true);
return group;
},
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
onMousedownJob: function(job, t) {
var surface = job.surface;
var record = job.record;
var group = surface.getGroup('spritegroup_' + record.data.id);
if (!group)
return;
var bbox = group.getBBox();
var choice = surface.getGroup('flowchart_choice');
choice.setAttributes({
width: bbox.width + 2,
height: bbox.height + 2,
x: bbox.x - 1,
y: bbox.y - 1
});
choice.show(true);
surface.selectedjob = record;
// load job record
var ctrl = Jhako.app.getController('history.JobunitTab');
ctrl.onLoadJobunit(record);
},
});
|
gpl-3.0
|
iterate-ch/cyberduck
|
core/src/main/java/ch/cyberduck/core/DefaultProviderHelpService.java
|
1324
|
package ch.cyberduck.core;
/*
* Copyright (c) 2002-2013 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* feedback@cyberduck.ch
*/
import org.apache.commons.lang3.StringUtils;
public class DefaultProviderHelpService extends RootProviderHelpService {
public DefaultProviderHelpService() {
super();
}
public DefaultProviderHelpService(final String base) {
super(base);
}
@Override
public String help(final Protocol provider) {
if(StringUtils.isNotBlank(provider.getHelp())) {
return provider.getHelp();
}
return this.help(provider.getIdentifier());
}
@Override
public String help(final Scheme scheme) {
return this.help(scheme.name());
}
}
|
gpl-3.0
|
spidi123q/love_life_calculator
|
library/dashed-circular-progress-master/app/src/main/java/com/github/glomadrian/sample/fragment/Pager.java
|
3686
|
package com.github.glomadrian.sample.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.glomadrian.dashedcircularprogress.DashedCircularProgress;
import com.github.glomadrian.sample.R;
/**
* @author Adrián García Lomas
*/
public class Pager extends Fragment {
private DashedCircularProgress dashedCircularProgress;
private ViewPager viewPager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dashedCircularProgress = (DashedCircularProgress) view.findViewById(R.id.simple);
viewPager = (ViewPager) view.findViewById(R.id.circular_view_pager);
viewPager.setAdapter(new PagerAdapter(getChildFragmentManager()));
onSpeed();
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
//Empty
}
@Override
public void onPageSelected(int position) {
if (position == 0) {
onSpeed();
} else if (position == 1) {
onStrong();
}
}
@Override
public void onPageScrollStateChanged(int state) {
//Empty
}
});
}
private void onSpeed() {
dashedCircularProgress.setIcon(R.drawable.speed);
dashedCircularProgress.setValue(46);
}
private void onStrong() {
dashedCircularProgress.setIcon(R.drawable.strong);
dashedCircularProgress.setValue(68);
}
public static Pager getInstance() {
return new Pager();
}
private class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new SpeedFragment();
case 1:
return new StrongFragment();
}
return new SpeedFragment();
}
@Override
public int getCount() {
return 2;
}
}
public static class SpeedFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.speed, container, false);
}
}
public static class StrongFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.strong, container, false);
}
}
}
|
gpl-3.0
|
ckaestne/LEADT
|
workspace/argouml_diagrams/argouml-app/src/org/argouml/cognitive/ui/WizDescription.java
|
6123
|
// $Id: WizDescription.java 12777 2007-06-08 07:46:22Z tfmorris $
// Copyright (c) 1996-2006 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.cognitive.ui;
import java.awt.BorderLayout;
import java.text.MessageFormat;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.apache.log4j.Logger;
import org.argouml.cognitive.Critic;
import org.argouml.cognitive.Decision;
import org.argouml.cognitive.Goal;
import org.argouml.cognitive.ToDoItem;
import org.argouml.cognitive.Translator;
import org.argouml.model.Model;
/**
* This class represents the first step of the wizard.
* It contains the description of the
* wizard in case the selected target is a todo item.
* An appropriate message is shown in case nothing is selected, or
* in case the user selected one of the branches (folders) in the
* tree in the todo panel.
*/
public class WizDescription extends WizStep {
/**
* Logger.
*/
private static final Logger LOG = Logger.getLogger(WizDescription.class);
////////////////////////////////////////////////////////////////
// instance variables
private JTextArea description = new JTextArea();
/**
* The constructor.
*
*/
public WizDescription() {
super();
LOG.info("making WizDescription");
description.setLineWrap(true);
description.setWrapStyleWord(true);
getMainPanel().setLayout(new BorderLayout());
getMainPanel().add(new JScrollPane(description), BorderLayout.CENTER);
}
/*
* @see org.argouml.cognitive.ui.WizStep#setTarget(java.lang.Object)
*/
public void setTarget(Object item) {
String message = "";
super.setTarget(item);
Object target = item;
if (target == null) {
description.setEditable(false);
description.setText(
Translator.localize("message.item.no-item-selected"));
} else if (target instanceof ToDoItem) {
ToDoItem tdi = (ToDoItem) target;
description.setEditable(false);
description.setEnabled(true);
description.setText(tdi.getDescription());
description.setCaretPosition(0);
} else if (target instanceof PriorityNode) {
message =
MessageFormat.format(
Translator.localize("message.item.branch-priority"),
new Object [] {
target.toString(),
});
description.setEditable(false);
description.setText(message);
return;
} else if (target instanceof Critic) {
message =
MessageFormat.format(
Translator.localize("message.item.branch-critic"),
new Object [] {
target.toString(),
});
description.setEditable(false);
description.setText(message);
return;
} else if (Model.getFacade().isAUMLElement(target)) {
message =
MessageFormat.format(
Translator.localize("message.item.branch-model"),
new Object [] {
Model.getFacade().toString(target),
});
description.setEditable(false);
description.setText(message);
return;
} else if (target instanceof Decision) {
message =
MessageFormat.format(
Translator.localize("message.item.branch-decision"),
new Object [] {
Model.getFacade().toString(target),
});
description.setText(message);
return;
} else if (target instanceof Goal) {
message =
MessageFormat.format(
Translator.localize("message.item.branch-goal"),
new Object [] {
Model.getFacade().toString(target),
});
description.setText(message);
return;
} else if (target instanceof KnowledgeTypeNode) {
message =
MessageFormat.format(
Translator.localize("message.item.branch-knowledge"),
new Object [] {
Model.getFacade().toString(target),
});
description.setText(message);
return;
} else {
description.setText("");
return;
}
}
/**
* The UID.
*/
private static final long serialVersionUID = 2545592446694112088L;
} /* end class WizDescription */
|
gpl-3.0
|
dejan-brkic/search
|
crafter-search-batch-indexer/src/main/java/org/craftercms/search/batch/impl/XmlFileBatchIndexer.java
|
3452
|
package org.craftercms.search.batch.impl;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.craftercms.core.exception.CrafterException;
import org.craftercms.core.exception.XmlException;
import org.craftercms.core.processors.ItemProcessor;
import org.craftercms.core.processors.impl.ItemProcessorPipeline;
import org.craftercms.core.service.ContentStoreService;
import org.craftercms.core.service.Context;
import org.craftercms.core.service.Item;
import org.craftercms.search.batch.IndexingStatus;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Required;
/**
* {@link org.craftercms.search.batch.BatchIndexer} that updates/deletes XML files from a search index.
*
* @author avasquez
*/
public class XmlFileBatchIndexer extends AbstractBatchIndexer {
private static final Log logger = LogFactory.getLog(XmlFileBatchIndexer.class);
public static final List<String> DEFAULT_INCLUDE_FILENAME_PATTERNS = Collections.singletonList("^.*\\.xml$");
protected ItemProcessor itemProcessor;
public XmlFileBatchIndexer() {
includeFileNamePatterns = DEFAULT_INCLUDE_FILENAME_PATTERNS;
}
public void setItemProcessor(ItemProcessor itemProcessor) {
this.itemProcessor = itemProcessor;
}
public void setItemProcessors(List<ItemProcessor> itemProcessors) {
this.itemProcessor = new ItemProcessorPipeline(itemProcessors);
}
@Override
protected void doSingleFileUpdate(String indexId, String siteName, ContentStoreService contentStoreService, Context context,
String path, boolean delete, IndexingStatus status) throws Exception {
if (delete) {
doDelete(indexId, siteName, path, status);
} else {
doUpdate(indexId, siteName, path, processXml(siteName, contentStoreService, context, path), status);
}
}
protected String processXml(String siteName, ContentStoreService contentStoreService, Context context,
String path) throws CrafterException {
if (logger.isDebugEnabled()) {
logger.debug("Processing XML @ " + getSiteBasedPath(siteName, path) + " before indexing");
}
Item item = contentStoreService.getItem(context, null, path, itemProcessor);
Document doc = item.getDescriptorDom();
if (doc != null) {
String xml = documentToString(item.getDescriptorDom());
if (logger.isDebugEnabled()) {
logger.debug("XML @ " + getSiteBasedPath(siteName, path) + " processed successfully:\n" + xml);
}
return xml;
} else {
throw new XmlException("Item @ " + getSiteBasedPath(siteName, path) + " doesn't seem to be an XML file");
}
}
protected String documentToString(Document document) {
StringWriter stringWriter = new StringWriter();
OutputFormat format = OutputFormat.createCompactFormat();
XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
try {
xmlWriter.write(document);
} catch (IOException e) {
// Ignore, shouldn't happen.
}
return stringWriter.toString();
}
}
|
gpl-3.0
|
Acquati/aulas-tesseract
|
tutorial-crud/laravel-forum/database/migrations/2017_05_19_141013_create_thread_subscriptions_table.php
|
930
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateThreadSubscriptionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('thread_subscriptions', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('thread_id');
$table->timestamps();
$table->unique(['user_id', 'thread_id']);
$table->foreign('thread_id')
->references('id')
->on('threads')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('thread_subscriptions');
}
}
|
gpl-3.0
|
domainmod/domainmod
|
_includes/breadcrumbs/segments-add.inc.php
|
1101
|
<?php
/**
* /_includes/breadcrumbs/segments-add.inc.php
*
* This file is part of DomainMOD, an open source domain and internet asset manager.
* Copyright (c) 2010-2021 Greg Chetcuti <greg@chetcuti.com>
*
* Project: http://domainmod.org Author: http://chetcuti.com
*
* DomainMOD 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.
*
* DomainMOD 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 DomainMOD. If not, see
* http://www.gnu.org/licenses/.
*
*/
?>
<li class="breadcrumb-item"><a href="<?php echo $web_root; ?>/segments/"><?php echo _('Segments'); ?></a></li>
<li class="breadcrumb-item active"><?php echo $breadcrumb; ?></li>
</ol>
|
gpl-3.0
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
|
src/foam/primitives/ints/ulong/ulongIO.C
|
2604
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
Description
Reads a ulong from an input stream.
\*---------------------------------------------------------------------------*/
#include "error.H"
#include "ulong.H"
#include "IOstreams.H"
#include <sstream>
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Foam::word Foam::name(const unsigned long val)
{
std::ostringstream buf;
buf << val;
return buf.str();
}
// * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * //
Foam::Istream& Foam::operator>>(Istream& is, unsigned long& val)
{
token t(is);
if (!t.good())
{
is.setBad();
return is;
}
if (t.isLabel())
{
val = static_cast<unsigned long>(t.labelToken());
}
else
{
is.setBad();
FatalIOErrorIn("operator>>(Istream&, unsigned long&)", is)
<< "wrong token type - expected unsigned long found " << t.info()
<< exit(FatalIOError);
return is;
}
// Check state of Istream
is.check("Istream& operator>>(Istream&, unsigned long&)");
return is;
}
unsigned long Foam::readUlong(Istream& is)
{
unsigned long val;
is >> val;
return val;
}
Foam::Ostream& Foam::operator<<(Ostream& os, const unsigned long val)
{
os.write(label(val));
os.check("Ostream& operator<<(Ostream&, const unsigned long)");
return os;
}
// ************************************************************************* //
|
gpl-3.0
|
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
|
src/turbulenceModels/incompressible/RAS/kOmegaSST/kOmegaSST.H
|
8619
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::incompressible::RASModels::kOmegaSST
Description
Implementation of the k-omega-SST turbulence model for incompressible
flows.
Turbulence model described in:
@verbatim
Menter, F., Esch, T.
"Elements of Industrial Heat Transfer Prediction"
16th Brazilian Congress of Mechanical Engineering (COBEM),
Nov. 2001.
@endverbatim
with updated coefficients from
@verbatim
Menter, F. R., Kuntz, M., and Langtry, R.,
"Ten Years of Industrial Experience with the SST Turbulence Model",
Turbulence, Heat and Mass Transfer 4, 2003,
pp. 625 - 632.
@endverbatim
but with the consistent production terms from the 2001 paper as form in the
2003 paper is a typo, see
@verbatim
http://turbmodels.larc.nasa.gov/sst.html
@endverbatim
and the addition of the optional F3 term for rough walls from
\verbatim
Hellsten, A.
"Some Improvements in Menter’s k-omega-SST turbulence model"
29th AIAA Fluid Dynamics Conference,
AIAA-98-2554,
June 1998.
\endverbatim
Note that this implementation is written in terms of alpha diffusion
coefficients rather than the more traditional sigma (alpha = 1/sigma) so
that the blending can be applied to all coefficuients in a consistent
manner. The paper suggests that sigma is blended but this would not be
consistent with the blending of the k-epsilon and k-omega models.
Also note that the error in the last term of equation (2) relating to
sigma has been corrected.
The default model coefficients correspond to the following:
@verbatim
kOmegaSSTCoeffs
{
alphaK1 0.85;
alphaK2 1.0;
alphaOmega1 0.5;
alphaOmega2 0.856;
beta1 0.075;
beta2 0.0828;
betaStar 0.09;
gamma1 5/9;
gamma2 0.44;
a1 0.31;
b1 1.0;
c1 10.0;
F3 no;
}
@endverbatim
SourceFiles
kOmegaSST.C
\*---------------------------------------------------------------------------*/
#ifndef kOmegaSST_H
#define kOmegaSST_H
#include "RASModel.H"
#include "wallDist.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace incompressible
{
namespace RASModels
{
/*---------------------------------------------------------------------------*\
Class kOmega Declaration
\*---------------------------------------------------------------------------*/
class kOmegaSST
:
public RASModel
{
// Private data
// Model coefficients
dimensionedScalar alphaK1_;
dimensionedScalar alphaK2_;
dimensionedScalar alphaOmega1_;
dimensionedScalar alphaOmega2_;
dimensionedScalar gamma1_;
dimensionedScalar gamma2_;
dimensionedScalar beta1_;
dimensionedScalar beta2_;
dimensionedScalar betaStar_;
dimensionedScalar a1_;
dimensionedScalar b1_;
dimensionedScalar c1_;
Switch F3_;
//- Wall distance field
// Note: different to wall distance in parent RASModel
wallDist y_;
// Fields
volScalarField k_;
volScalarField omega_;
volScalarField nut_;
// Private member functions
tmp<volScalarField> F1(const volScalarField& CDkOmega) const;
tmp<volScalarField> F2() const;
tmp<volScalarField> F3() const;
tmp<volScalarField> F23() const;
tmp<volScalarField> blend
(
const volScalarField& F1,
const dimensionedScalar& psi1,
const dimensionedScalar& psi2
) const
{
return F1*(psi1 - psi2) + psi2;
}
tmp<volScalarField> alphaK
(
const volScalarField& F1
) const
{
return blend(F1, alphaK1_, alphaK2_);
}
tmp<volScalarField> alphaOmega
(
const volScalarField& F1
) const
{
return blend(F1, alphaOmega1_, alphaOmega2_);
}
tmp<volScalarField> beta
(
const volScalarField& F1
) const
{
return blend(F1, beta1_, beta2_);
}
tmp<volScalarField> gamma
(
const volScalarField& F1
) const
{
return blend(F1, gamma1_, gamma2_);
}
public:
//- Runtime type information
TypeName("kOmegaSST");
// Constructors
//- Construct from components
kOmegaSST
(
const volVectorField& U,
const surfaceScalarField& phi,
transportModel& transport
);
//- Destructor
virtual ~kOmegaSST()
{}
// Member Functions
//- Return the turbulence viscosity
virtual tmp<volScalarField> nut() const
{
return nut_;
}
//- Return the effective diffusivity for k
tmp<volScalarField> DkEff(const volScalarField& F1) const
{
return tmp<volScalarField>
(
new volScalarField("DkEff", alphaK(F1)*nut_ + nu())
);
}
//- Return the effective diffusivity for omega
tmp<volScalarField> DomegaEff(const volScalarField& F1) const
{
return tmp<volScalarField>
(
new volScalarField("DomegaEff", alphaOmega(F1)*nut_ + nu())
);
}
//- Return the turbulence kinetic energy
virtual tmp<volScalarField> k() const
{
return k_;
}
//- Return the turbulence specific dissipation rate
virtual tmp<volScalarField> omega() const
{
return omega_;
}
//- Return the turbulence kinetic energy dissipation rate
virtual tmp<volScalarField> epsilon() const
{
return tmp<volScalarField>
(
new volScalarField
(
IOobject
(
"epsilon",
mesh_.time().timeName(),
mesh_
),
betaStar_*k_*omega_,
omega_.boundaryField().types()
)
);
}
//- Return the Reynolds stress tensor
virtual tmp<volSymmTensorField> R() const;
//- Return the effective stress tensor including the laminar stress
virtual tmp<volSymmTensorField> devReff() const;
//- Return the source term for the momentum equation
virtual tmp<fvVectorMatrix> divDevReff(volVectorField& U) const;
//- Solve the turbulence equations and correct the turbulence viscosity
virtual void correct();
//- Read RASProperties dictionary
virtual bool read();
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace RASModels
} // namespace incompressible
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
gpl-3.0
|
Areax/TerrasNaxium
|
Assets/Scripts/HarryPotterUnity/Cards/BasicBehavior/ItemLessonBook.cs
|
572
|
using System.Collections.Generic;
namespace HarryPotterUnity.Cards.BasicBehavior
{
public class ItemLessonBook : ItemLessonProvider
{
public override bool CanPerformInPlayAction()
{
return Player.CanUseActions() && Player.IsLocalPlayer;
}
public override void OnInPlayAction(List<BaseCard> targets = null)
{
Player.Discard.Add(this);
Player.Deck.DrawCard();
Player.Deck.DrawCard();
Player.Deck.DrawCard();
Player.UseActions();
}
}
}
|
gpl-3.0
|
easy-as-pie-labs/tweap
|
tweap/todo/migrations/0001_initial.py
|
1103
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('project_management', '0003_tag'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Todo',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('description', models.CharField(null=True, blank=True, max_length=1000)),
('due_date', models.DateField(null=True, blank=True)),
('assignees', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),
('project', models.ForeignKey(to='project_management.Project')),
('tags', models.ManyToManyField(to='project_management.Tag')),
],
options={
},
bases=(models.Model,),
),
]
|
gpl-3.0
|
qunying/gps
|
share/plug-ins/dispatching.py
|
4239
|
"""Highlighting all dispatching calls in the current editor
This package will highlight with a special background color all
dispatching calls found in the current editor. In particular, at such
locations, the cross-references might not lead accurate result (for
instance "go to body"), since the exact subprogram that is called is
not known until run time.
"""
#############################################################################
# No user customization below this line
#############################################################################
import GPS
from gps_utils.highlighter import Location_Highlighter, OverlayStyle
GPS.Preference("Plugins/dispatching/color").create(
"Highlight color", "color",
"""Background color to use for dispatching calls""",
"#FFF3C2")
GPS.Preference("Plugins/dispatching/context").create(
"Search context", "integer",
"""When the cross-reference information is not up-to-date, \
GPS will search a few lines around the original location for \
matching entities. This preference indicates how many lines \
it will search -- the bigger the slower of course, and potentially \
less precise too""", 5, 0, 50)
class Dispatching_Highlighter(Location_Highlighter):
def __init__(self):
Location_Highlighter.__init__(self, style=None)
self.background_color = None
self.context = None
self.__on_preferences_changed(hook=None)
GPS.Hook("preferences_changed").add(self.__on_preferences_changed)
GPS.Hook("file_edited").add(self.__on_file_edited)
GPS.Hook("file_changed_on_disk").add(self.__on_file_edited)
if GPS.Logger("ENTITIES.SQLITE").active:
GPS.Hook("xref_updated").add(self.__on_compilation_finished)
else:
GPS.Hook("compilation_finished").add(
self.__on_compilation_finished)
def __del__(self):
Location_Highlighter.__del__(self)
GPS.Hook("preferences_changed").remove(self.__on_preferences_changed)
GPS.Hook("file_edited").remove(self.__on_file_edited)
GPS.Hook("file_changed_on_disk").remove(self.__on_file_edited)
if GPS.Logger("ENTITIES.SQLITE").active:
GPS.Hook("xref_updated").remove(self.__on_compilation_finished)
else:
GPS.Hook("compilation_finished").remove(
self.__on_compilation_finished)
def __on_preferences_changed(self, hook):
changed = False
v = GPS.Preference("Plugins/dispatching/context").get()
if v != self.context:
self.context = v
changed = True
v = GPS.Preference("Plugins/dispatching/color").get()
if v != self.background_color:
self.background_color = v
self.set_style(OverlayStyle(name="dispatchcalls", background=v))
changed = True
if changed:
self.stop_highlight()
self.__on_compilation_finished()
def __on_file_edited(self, hook, file):
# File might have been opened in a QGen browser
buffer = GPS.EditorBuffer.get(file, open=False)
if buffer:
self.start_highlight(buffer)
def __on_compilation_finished(
self, hook=None, category="", target_name="",
mode_name="", status=""):
"""Re-highlight all editors"""
for b in GPS.EditorBuffer.list():
self.start_highlight(b) # automatically removes old highlights
def recompute_refs(self, buffer):
try:
# Minor optimization to query the names of each entities only once.
names = dict()
result = []
for e, r in buffer.file().references(kind="dispatching call"):
n = names.get(e)
if n is None:
n = names[e] = e.name()
result.append((n, r))
return result
except Exception as e:
GPS.Logger("DISPATCHING").log("recompute_refs exception %s" % e)
# xref engine might not be up-to-date, or available yet
return []
highlighter = None
def on_gps_started(h):
global highlighter
highlighter = Dispatching_Highlighter()
GPS.Hook("gps_started").add(on_gps_started)
|
gpl-3.0
|
PapenfussLab/PathOS
|
Tools/Hl7Tools/src/main/java/org/petermac/hl7/model/v251/group/RPL_I02_PROVIDER.java
|
5370
|
/*
* This class is an auto-generated source file for a HAPI
* HL7 v2.x standard structure class.
*
* For more information, visit: http://hl7api.sourceforge.net/
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
* specific language governing rights and limitations under the License.
*
* The Original Code is "[file_name]". Description:
* "[one_line_description]"
*
* The Initial Developer of the Original Code is University Health Network. Copyright (C)
* 2012. All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms of the
* GNU General Public License (the "GPL"), in which case the provisions of the GPL are
* applicable instead of those above. If you wish to allow use of your version of this
* file only under the terms of the GPL and not to allow others to use your version
* of this file under the MPL, indicate your decision by deleting the provisions above
* and replace them with the notice and other provisions required by the GPL License.
* If you do not delete the provisions above, a recipient may use your version of
* this file under either the MPL or the GPL.
*
*/
package org.petermac.hl7.model.v251.group;
import org.petermac.hl7.model.v251.segment.*;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.parser.ModelClassFactory;
import ca.uhn.hl7v2.model.*;
/**
* <p>Represents a RPL_I02_PROVIDER group structure (a Group object).
* A Group is an ordered collection of message segments that can repeat together or be optionally in/excluded together.
* This Group contains the following elements:
* </p>
* <ul>
* <li>1: PRD (Provider Data) <b> </b></li>
* <li>2: CTD (Contact Data) <b>optional repeating </b></li>
* </ul>
*/
//@SuppressWarnings("unused")
public class RPL_I02_PROVIDER extends AbstractGroup {
/**
* Creates a new RPL_I02_PROVIDER group
*/
public RPL_I02_PROVIDER(Group parent, ModelClassFactory factory) {
super(parent, factory);
init(factory);
}
private void init(ModelClassFactory factory) {
try {
this.add(PRD.class, true, false, false);
this.add(CTD.class, false, true, false);
} catch(HL7Exception e) {
log.error("Unexpected error creating RPL_I02_PROVIDER - this is probably a bug in the source code generator.", e);
}
}
/**
* Returns "2.5.1"
*/
public String getVersion() {
return "2.5.1";
}
/**
* Returns
* PRD (Provider Data) - creates it if necessary
*/
public PRD getPRD() {
PRD retVal = getTyped("PRD", PRD.class);
return retVal;
}
/**
* Returns
* the first repetition of
* CTD (Contact Data) - creates it if necessary
*/
public CTD getCTD() {
CTD retVal = getTyped("CTD", CTD.class);
return retVal;
}
/**
* Returns a specific repetition of
* CTD (Contact Data) - creates it if necessary
*
* @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0)
* @throws HL7Exception if the repetition requested is more than one
* greater than the number of existing repetitions.
*/
public CTD getCTD(int rep) {
CTD retVal = getTyped("CTD", rep, CTD.class);
return retVal;
}
/**
* Returns the number of existing repetitions of CTD
*/
public int getCTDReps() {
return getReps("CTD");
}
/**
* <p>
* Returns a non-modifiable List containing all current existing repetitions of CTD.
* <p>
* <p>
* Note that unlike {@link #getCTD()}, this method will not create any reps
* if none are already present, so an empty list may be returned.
* </p>
*/
public java.util.List<CTD> getCTDAll() throws HL7Exception {
return getAllAsList("CTD", CTD.class);
}
/**
* Inserts a specific repetition of CTD (Contact Data)
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public void insertCTD(CTD structure, int rep) throws HL7Exception {
super.insertRepetition("CTD", structure, rep);
}
/**
* Inserts a specific repetition of CTD (Contact Data)
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public CTD insertCTD(int rep) throws HL7Exception {
return (CTD)super.insertRepetition("CTD", rep);
}
/**
* Removes a specific repetition of CTD (Contact Data)
* @see AbstractGroup#removeRepetition(String, int)
*/
public CTD removeCTD(int rep) throws HL7Exception {
return (CTD)super.removeRepetition("CTD", rep);
}
}
|
gpl-3.0
|
ISRAPIL/FastCorePE
|
src/pocketmine/entity/Item.php
|
6325
|
<?php
namespace pocketmine\entity;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\ItemDespawnEvent;
use pocketmine\event\entity\ItemSpawnEvent;
use pocketmine\item\Item as ItemItem;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\ShortTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\network\protocol\AddItemEntityPacket;
use pocketmine\Player;
class Item extends Entity {
const NETWORK_ID = 64;
protected $owner = null;
protected $thrower = null;
protected $pickupDelay = 0;
/** @var ItemItem */
protected $item;
public $width = 0.25;
public $length = 0.25;
public $height = 0.25;
protected $gravity = 0.04;
protected $drag = 0.02;
public $canCollide = false;
protected function initEntity() {
parent::initEntity();
$this->setMaxHealth(5);
$this->setHealth($this->namedtag["Health"]);
if (isset($this->namedtag->Age)) {
$this->age = $this->namedtag["Age"];
}
if (isset($this->namedtag->PickupDelay)) {
$this->pickupDelay = $this->namedtag["PickupDelay"];
}
if (isset($this->namedtag->Owner)) {
$this->owner = $this->namedtag["Owner"];
}
if (isset($this->namedtag->Thrower)) {
$this->thrower = $this->namedtag["Thrower"];
}
if (!isset($this->namedtag->Item)) {
$this->close();
return;
}
assert($this->namedtag->Item instanceof CompoundTag);
$this->item = ItemItem::nbtDeserialize($this->namedtag->Item);
$this->server->getPluginManager()->callEvent(new ItemSpawnEvent($this));
}
public function attack($damage, EntityDamageEvent $source) {
if (
$source->getCause() === EntityDamageEvent::CAUSE_VOID or
$source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK or
$source->getCause() === EntityDamageEvent::CAUSE_ENTITY_EXPLOSION or
$source->getCause() === EntityDamageEvent::CAUSE_BLOCK_EXPLOSION
) {
parent::attack($damage, $source);
}
}
public function onUpdate($currentTick) {
if ($this->closed) {
return false;
}
$this->age++;
$tickDiff = $currentTick - $this->lastUpdate;
if ($tickDiff <= 0 and ! $this->justCreated) {
return true;
}
$this->lastUpdate = $currentTick;
$this->timings->startTiming();
$hasUpdate = $this->entityBaseTick($tickDiff);
if ($this->isAlive()) {
if ($this->pickupDelay > 0 and $this->pickupDelay < 32767) { //Infinite delay
$this->pickupDelay -= $tickDiff;
if ($this->pickupDelay < 0) {
$this->pickupDelay = 0;
}
}
$this->motionY -= $this->gravity;
if ($this->checkObstruction($this->x, $this->y, $this->z)) {
$hasUpdate = true;
}
$this->move($this->motionX, $this->motionY, $this->motionZ);
$friction = 1 - $this->drag;
if ($this->onGround and ( abs($this->motionX) > 0.00001 or abs($this->motionZ) > 0.00001)) {
$friction = $this->getLevel()->getBlock($this->temporalVector->setComponents((int) floor($this->x), (int) floor($this->y - 1), (int) floor($this->z) - 1))->getFrictionFactor() * $friction;
}
$this->motionX *= $friction;
$this->motionY *= 1 - $this->drag;
$this->motionZ *= $friction;
if ($this->onGround) {
$this->motionY *= -0.5;
}
if ($currentTick % 5 == 0)
$this->updateMovement();
if ($this->age > 2000) {
$this->server->getPluginManager()->callEvent($ev = new ItemDespawnEvent($this));
if ($ev->isCancelled()) {
$this->age = 0;
} else {
$this->kill();
$hasUpdate = true;
}
}
}
$this->timings->stopTiming();
return $hasUpdate or ! $this->onGround or abs($this->motionX) > 0.00001 or abs($this->motionY) > 0.00001 or abs($this->motionZ) > 0.00001;
}
public function saveNBT() {
parent::saveNBT();
$this->namedtag->Item = $this->item->nbtSerialize(-1, "Item");
$this->namedtag->Health = new ShortTag("Health", $this->getHealth());
$this->namedtag->Age = new ShortTag("Age", $this->age);
$this->namedtag->PickupDelay = new ShortTag("PickupDelay", $this->pickupDelay);
if ($this->owner !== null) {
$this->namedtag->Owner = new StringTag("Owner", $this->owner);
}
if ($this->thrower !== null) {
$this->namedtag->Thrower = new StringTag("Thrower", $this->thrower);
}
}
/**
* @return ItemItem
*/
public function getItem() {
return $this->item;
}
public function canCollideWith(Entity $entity) {
return false;
}
/**
* @return int
*/
public function getPickupDelay() {
return $this->pickupDelay;
}
/**
* @param int $delay
*/
public function setPickupDelay($delay) {
$this->pickupDelay = $delay;
}
/**
* @return string
*/
public function getOwner() {
return $this->owner;
}
/**
* @param string $owner
*/
public function setOwner($owner) {
$this->owner = $owner;
}
/**
* @return string
*/
public function getThrower() {
return $this->thrower;
}
/**
* @param string $thrower
*/
public function setThrower($thrower) {
$this->thrower = $thrower;
}
public function spawnTo(Player $player) {
$pk = new AddItemEntityPacket();
$pk->eid = $this->getId();
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->speedX = $this->motionX;
$pk->speedY = $this->motionY;
$pk->speedZ = $this->motionZ;
$pk->item = $this->getItem();
$player->dataPacket($pk);
$this->sendData($player);
parent::spawnTo($player);
}
}
|
gpl-3.0
|
kendo-labs/kendo-bootstrapper
|
lib/platform.js
|
11659
|
var CP = require("child_process");
var PATH = require("path");
var FS = require("fs");
var UTILS = require("./utils.js");
var PROJECT = require("./project.js");
var CONFIG = require("./config.js");
var PLIST = require("./plist.js");
function run_program(cmd, args, opts, callback) {
var p = CP.spawn(cmd, args, opts);
if (callback) {
var out = "", err = "";
p.stdout.on("data", function(data){ out += data });
p.stderr.on("data", function(data){ err += data });
p.stdout.on("end", function(){
if (!/\S/.test(err)) err = null;
callback(err, out);
});
}
return p;
}
function dispatch(unix, win, mac) {
switch (process.platform) {
case "linux":
case "freebsd":
return unix();
break;
case "win32":
case "win64":
return win();
break;
case "sunos":
throw new Error("What? SunOS??");
case "darwin":
if (mac) return mac();
break;
default:
throw new Error("To be implemented");
}
}
function locate_application(names, callback) {
if (!(names instanceof Array)) names = [ names ];
function log_search(name) {
PROJECT.client_log({
message: "Searching application: " + name
});
}
function linux(){
var paths = process.env.PATH.split(/:+/);
do_search(paths);
function do_search(p) {
if (p.length == 0) {
callback(new Error("Cannot find executable: " + names));
return;
}
var found = {};
FS.stat(p[0], function(err, stat){
if (err || !stat.isDirectory()) {
return do_search(p.slice(1));
}
UTILS.fs_find(p[0], {
filter: function(f) {
return !f.stat.isDirectory() && names.indexOf(f.name) >= 0;
},
callback: function(err, f) {
if (!err)
found[f.full] = f;
},
recurse: function(){ return false },
finish: function() {
var files = Object.keys(found);
if (files.length > 0) {
files.sort(function(a, b){
a = found[a];
b = found[b];
return names.indexOf(a.name) - names.indexOf(b.name);
});
callback(null, files[0]);
} else {
do_search(p.slice(1));
}
}
});
});
}
};
dispatch(
linux,
function win() {
var paths = [
process.env.LOCALAPPDATA,
process.env['PROGRAMFILES(X86)'],
process.env.PROGRAMFILES,
process.env.COMMONPROGRAMFILES,
process.env.APPDATA,
process.env.HOME,
process.env.WINDIR,
].filter(function(x){ return x != null });
log_search(names[0]);
do_search(names, paths);
function do_search(x, p) {
if (p.length == 0) {
if (x.length == 0) {
callback(new Error("Cannot find executable: " + names));
} else {
log_search(x[1]);
do_search(x.slice(1), paths);
}
return;
}
var cp = CP.spawn(process.env.ComSpec, [
"/c",
"DIR /b /s " + x[0]
], {
cwd: p[0]
});
var data = "";
cp.stdout.setEncoding("utf8");
cp.stdout.on("data", function(str){ data += str });
cp.stdout.on("end", function(){
data = data.replace(/^\s+|\s+$/g, "").split(/\r?\n/);
if (/\S/.test(data[0])) {
return callback(null, data[0]);
}
do_search(x, p.slice(1));
});
}
},
linux // we can use the same semantics on OSX
);
};
function darwin_edit_file_unknown_editor(root, filename, line, col, callback) {
PROJECT.client_log({
cprefix: "Info",
message: "No editor defined, trying `open -t`"
});
run_program("open", [ "-t", filename ], { cwd: root });
callback(null, "open");
};
function darwin_run_applescript(script) {
if (script instanceof Array)
script = script.join("\n");
var p = CP.spawn("osascript");
p.stdin.write(script, "utf8");
p.stdin.end();
};
function darwin_edit_file_with_application(editor, filename) {
darwin_run_applescript([
'tell application ' + JSON.stringify(editor),
' activate',
' open POSIX file ' + JSON.stringify(filename),
'end tell',
]);
};
function darwin_get_editor_apps() {
var appdir = "/Applications";
var applications = FS.readdirSync(appdir);
var editors = [];
applications.forEach(function(app){
if (!(/\.app$/).test(app)) return;
try {
var stat = FS.statSync(PATH.join(appdir, app));
if (!stat.isDirectory()) return;
} catch(ex) {}
var contents = PATH.join(appdir, app, "Contents");
var info;
try {
try {
info = FS.readFileSync(PATH.join(contents, "Info.plist"), "utf8");
info = PLIST.parse_xml(info);
} catch(ex) {}
if (!info) return;
if (!info.CFBundleDocumentTypes) return;
info.CFBundleDocumentTypes.forEach(function(dt){
if (!(/^editor$/i.test(dt.CFBundleTypeRole))) return;
if (!dt.CFBundleTypeExtensions) return;
if (dt.CFBundleTypeExtensions.contains(null, function(el){
return (/^(js|css|coffee|html?|php|asp)$/i.test(el));
})) {
throw info;
}
});
} catch(ex) {
if (ex === info) editors.push({
name : info.CFBundleName,
executable : info.CFBundleExecutable,
info : info.CFBundleGetInfoString,
icon : PATH.join(contents, "Resources", info.CFBundleIconFile),
});
else {
console.log(ex.stack);
throw ex;
}
}
});
return editors;
};
exports.darwin_get_editor_apps = darwin_get_editor_apps;
function edit_file(root, filename, line, col, callback) {
var editor = CONFIG.get("editor");
if (process.platform == "darwin") {
if (!editor) {
darwin_edit_file_unknown_editor(root, filename, line, col, callback);
} else {
darwin_edit_file_with_application(editor.name, PATH.join(root, filename));
}
return;
}
if (!editor) {
PROJECT.client_log({
cprefix: "Error",
message: "No editor configured"
});
callback(new Error("No editor configured"));
return;
}
var args =
col != null ? (editor.args.cmd3 || editor.args.cmd2 || editor.args.cmd1)
: line != null ? (editor.args.cmd2 || editor.args.cmd1)
: (editor.args.cmd1 || [ "{file}" ]);
args = args.map(function(tmpl){
return UTILS.template(tmpl, {
file : filename,
line : line,
col : col
});
});
var cmd = editor.path;
function linux() {
run_program(cmd, args, { cwd: root });
callback(null, cmd);
};
dispatch(
linux,
function win() {
var script = PATH.join(TOPLEVEL_DIR, "tools", "win", "run-in-foreground.js");
var p = run_program("cscript", [
script,
cmd,
].concat(args), { cwd: root });
callback(null, cmd);
},
linux
);
};
exports.edit_file = edit_file;
exports.locate_code_editor = function(callback) {
dispatch(
function linux() {
locate_application([ "sublime_text", "gedit", "gvim", "emacs" ], callback);
},
function win() {
locate_application([ "sublime_text.exe", "notepad++.exe", "gvim.exe", "notepad.exe" ], callback);
},
function mac() {
locate_application([ "sublime_text", "subl", "gvim", "mvim" ], callback);
}
);
};
exports.locate_application = locate_application;
function get_tool(name) {
return dispatch(
function linux() {
return name;
},
function win() {
return PATH.join(TOPLEVEL_DIR, "tools", "win", name + ".exe");
},
function mac() {
return PATH.join(TOPLEVEL_DIR, "tools", "osx", name);
}
);
};
exports.get_tool = get_tool;
function optimize_image(filename, callback) {
if (/\.jpe?g$/i.test(filename)) return optimize_image_jpeg(filename, callback);
if (/\.png$/i.test(filename)) return optimize_image_png(filename, callback);
return callback(new Error("Can't optimize " + filename));
};
function write_a_pile_of_chunks_into_a_file(filename, chunks, callback) {
FS.open(filename, "w", parseInt(644, 8), function(err, fd){
// wow, file descriptors! I'm so back to '89.
(function next(err) {
if (err) return callback(err);
if (chunks.length == 0) {
FS.close(fd, callback);
} else {
var buf = chunks.shift();
FS.write(fd, buf, 0, buf.length, null, next);
}
})(err);
});
};
function optimize_image_jpeg(filename, callback) {
var jpegtran = get_tool("jpegtran");
var chunks = [];
var p = CP.spawn(jpegtran, [ filename ]);
p.stderr.on("data", function(data){ console.log(data) });
p.stdout.on("data", function(buffer){ chunks.push(buffer) });
p.stdout.on("end", function(){
write_a_pile_of_chunks_into_a_file(filename, chunks, callback);
});
};
function optimize_image_png(filename, callback) {
var optipng = get_tool("optipng");
var p = CP.spawn(optipng, [ filename ]);
p.stdout.on("end", function(){
callback();
});
};
exports.optimize_image = optimize_image;
exports.HOME = function() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
};
exports.tray_notification = function(msg) {
return dispatch(
function linux() {
CP.spawn("notify-send", [ "-a", "Kendo Bootstrapper", msg.title, msg.body ]);
},
function win() {
CP.spawn(get_tool("notifu"),
[ "/p", msg.title,
"/m", msg.body,
"/d", 10, // disappear after 10 seconds
"/i", PATH.join(TOPLEVEL_DIR, "docroot", "favicon.ico")
]);
},
function mac() {
CP.spawn(get_tool("usernotification"), [
"-title", "Kendo Bootstrapper",
"-subtitle", msg.title,
"-informativeText", msg.body
]);
}
);
};
function win32_get_drives(callback) {
run_program("cscript", [ PATH.join(TOPLEVEL_DIR, "tools", "win", "list-drives.js") ],
{},
function(err, output){
if (err) return callback(err);
output = output.replace(/^[^]*---CUT-HERE---\s*/, "");
var lines = output.replace(/^\s+|\s+$/g, "").split(/\r?\n/);
callback(null, lines.map(function(line){
var a = line.split(/\s*\|\s*/);
return {
disk: a[0],
type: a[1],
name: a[2],
};
}));
});
};
exports.win32_get_drives = win32_get_drives;
exports.windows = /^win(32|64)$/i.test(process.platform);
|
gpl-3.0
|
IOT-DSA/dslink-java-knx
|
src/main/java/org/dsa/iot/knx/DeviceFolder.java
|
6225
|
package org.dsa.iot.knx;
import java.util.Map;
import java.util.Queue;
import org.dsa.iot.dslink.node.Node;
import org.dsa.iot.dslink.node.actions.ActionResult;
import org.dsa.iot.dslink.node.value.Value;
import org.dsa.iot.dslink.node.value.ValueType;
import org.dsa.iot.knx.masterdata.MasterDataParser;
import org.dsa.iot.knx.project.EtsXmlParser;
import org.dsa.iot.knx.project.KnxProjectParser;
import org.dsa.iot.knx.project.OpcFileParser;
import org.dsa.iot.knx.datapoint.DatapointType;
import org.dsa.iot.knx.groupaddress.GroupAddressParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tuwien.auto.calimero.GroupAddress;
import tuwien.auto.calimero.exception.KNXFormatException;
public class DeviceFolder extends EditableFolder {
private static final Logger LOGGER;
static {
LOGGER = LoggerFactory.getLogger(DeviceFolder.class);
}
public DeviceFolder(KnxConnection conn, Node node) {
super(conn, node);
}
public DeviceFolder(KnxConnection conn, EditableFolder root, Node node) {
super(conn, node);
this.root = root;
}
@Override
protected void edit(ActionResult event) {
}
@Override
protected void addFolder(String name) {
Node child = node.createChild(name, true).build();
new DeviceFolder(conn, root, child);
}
@Override
protected void addPoint(ActionResult event) {
String pointName = event.getParameter(ATTR_POINT_NAME, ValueType.STRING).getString();
String groupAddressStr = event.getParameter(ATTR_GROUP_ADDRESS).getString();
DatapointType type;
try {
type = DatapointType
.valueOf(event.getParameter(ATTR_POINT_TYPE, ValueType.STRING).getString().toUpperCase());
} catch (Exception e) {
LOGGER.error("invalid type");
LOGGER.debug("error: ", e);
return;
}
GroupAddress groupAddress = null;
try {
groupAddress = new GroupAddress(groupAddressStr);
} catch (KNXFormatException e1) {
LOGGER.debug("", e1);
return;
}
String group = Utils.getGroupName(groupAddress);
ValueType valType = DatapointType.getValueType(type);
Node pointNode = node.createChild(pointName, true).setValueType(valType).build();
pointNode.setAttribute(ATTR_POINT_TYPE, new Value(type.toString()));
pointNode.setAttribute(ATTR_GROUP_ADDRESS, new Value(groupAddress.toString()));
DevicePoint point = new DevicePoint(conn, this, pointNode);
setupPoint(point, groupAddress.toString(), group);
}
@Override
protected void importMasterData(ActionResult event) {
String masterDataContent = event.getParameter(ATTR_MASTER_DATA_CONTENT, ValueType.STRING).getString();
MasterDataParser masterDataParser = new MasterDataParser();
if (masterDataContent != null && !masterDataContent.isEmpty()) {
masterDataParser.parse(masterDataContent);
}
}
@Override
protected void importProjectByXml(ActionResult event) {
String contentProject = event.getParameter(ATTR_PROJECT_CONTENT_XML, ValueType.STRING).getString();
EtsXmlParser projectParser = new EtsXmlParser(this);
if (contentProject != null && !contentProject.isEmpty()) {
projectParser.parse(contentProject);
}
}
@Override
protected void importProjectByEsf(ActionResult event) {
String content = event.getParameter(ATTR_PROJECT_CONTENT_ESF, ValueType.STRING).getString();
KnxProjectParser parser = new OpcFileParser(this);
parser.parse(content);
}
@Override
protected void importProjectByGroupAddress(ActionResult event) {
String content = event.getParameter(ATTR_PROJECT_CONTENT_GROUP_ADDRESS, ValueType.STRING).getString();
boolean withNamingConvention = event.getParameter(ATTR_PROJECT_NAMING_CONVENTION, ValueType.BOOL).getBool();
GroupAddressParser parser = new GroupAddressParser(this);
parser.parse(content, withNamingConvention);
}
public Node buildFolderTree(Node parent, Queue<String> path) {
if (path.size() > 0) {
String name = path.poll();
Node child = parent.createChild(name, true).build();
new DeviceFolder(getConnection(), child);
Node node = buildFolderTree(child, path);
return node;
} else {
return parent;
}
}
@Override
public void buildDataPoint(Node parent, GroupAddressBean addressBean) {
GroupAddress groupAddress = null;
try {
groupAddress = new GroupAddress(addressBean.getGroupAddress());
} catch (KNXFormatException e) {
LOGGER.debug("", e);
} finally {
if (null == groupAddress)
return;
}
DatapointType type = DatapointType.valueOf(addressBean.getDataPointType());
ValueType valueType = DatapointType.getValueType(type);
String dataPointName = addressBean.getDataPointName();
Node pointNode = parent.createChild(dataPointName, true).setValueType(valueType).build();
pointNode.setAttribute(ATTR_POINT_TYPE, new Value(type.name()));
pointNode.setAttribute(ATTR_GROUP_ADDRESS, new Value(groupAddress.toString()));
DevicePoint point = new DevicePoint(conn, this, pointNode);
setupPoint(point, groupAddress.toString(), addressBean.getMiddleGroup());
}
void setupPoint(DevicePoint point, String groupAddressStr, String group) {
getConnection().setupPointListener(point);
getConnection().updateGroupToPoints(group, point, true);
getConnection().updateAddressToPoint(groupAddressStr, point, true);
}
@Override
void restoreLastSession() {
Map<String, Node> children = node.getChildren();
if (null == children)
return;
for (Node child : children.values()) {
Value restype = child.getAttribute(ATTR_RESTORE_TYPE);
if (null != restype && ATTR_EDITABLE_FOLDER.equals(restype.getString())) {
DeviceFolder folder = new DeviceFolder(this.getConnection(), root, child);
folder.restoreLastSession();
} else if (null != restype && ATTR_EDITABLE_POINT.equals(restype.getString())) {
DevicePoint point = new DevicePoint(this.getConnection(), this, child);
try {
String groupAddressStr = child.getAttribute(ATTR_GROUP_ADDRESS).getString();
GroupAddress groupAddress = new GroupAddress(groupAddressStr);
String group = Utils.getGroupName(groupAddress);
setupPoint(point, groupAddressStr, group);
} catch (Exception e) {
LOGGER.debug("", e);
}
} else if (null == child.getAction() && !NODE_STATUS.equals(child.getName())) {
node.removeChild(child);
}
}
}
}
|
gpl-3.0
|
goyoo-php/mobcent
|
app/models/AppbymeSendsms.php
|
3343
|
<?php
/**
* 微信绑定model类
*
* @author HanPengyu
* @copyright 2012-2015 Appbyme
*/
if (!defined('IN_DISCUZ') || !defined('IN_APPBYME')) {
exit('Access Denied');
}
class AppbymeSendsms extends DiscuzAR {
public static function model($className = __CLASS__) {
return parent::model($className);
}
public function tableName() {
return '{{appbyme_sendsms}}';
}
public function rules() {
return array();
}
public static function getTableName() {
if (WebUtils::getDzPluginAppbymeAppConfig('mobcent_sms_table')) {
$table = 'common_member_profile';
} else {
$table = 'appbyme_sendsms';
}
return $table;
}
// 根据手机号获取uid
public static function getMobileUid($mobile) {
return DbUtils::createDbUtils(true)->queryRow('
SELECT *
FROM %t
WHERE mobile=%s
AND uid > 0
',
array(self::getTableName(), $mobile)
);
}
public static function checkMobile($mobile) {
return (int)DbUtils::createDbUtils(true)->queryRow('
SELECT *
FROM %t
WHERE mobile=%s
AND uid > 0
',
array(self::getTableName(), $mobile)
);
}
// 插入手机号和验证码时候进行验证
public static function getMobileUidInfo($mobile) {
return DbUtils::createDbUtils(true)->queryRow('
SELECT *
FROM %t
WHERE mobile=%s
AND uid=0
',
array('appbyme_sendsms', $mobile)
);
}
public static function getBindByMobileCode($mobile, $code) {
return DbUtils::createDbUtils(true)->queryRow('
SELECT *
FROM %t
WHERE mobile=%s
AND code=%s
',
array('appbyme_sendsms', $mobile, $code)
);
}
public static function getBindInfoByUid($uid) {
return DbUtils::createDbUtils(true)->queryRow('
SELECT *
FROM %t
WHERE uid=%d
',
array(self::getTableName(), $uid)
);
}
public static function checkUserBindMobile($uid)
{
$mobile = DbUtils::createDbUtils(true)->queryFirst('
SELECT `mobile`
FROM %t
WHERE uid=%d
',
array(self::getTableName(), $uid)
);
if(empty($mobile)){
return false;
}else{
return true;
}
}
public static function getPhoneByUid($uid) {
return DbUtils::createDbUtils(true)->queryRow('
SELECT mobile
FROM %t
WHERE uid=%d
',
array(self::getTableName(), $uid)
);
}
public static function insertMobile($data) {
return DbUtils::createDbUtils(true)->insert('appbyme_sendsms', $data);
}
public static function updateMobile($mobile, $data) {
$result = DbUtils::createDbUtils(true)->update('appbyme_sendsms', $data, array('mobile' => $mobile));
if ($data['uid']) {
$result = DbUtils::createDbUtils(true)->update('common_member_profile', array('mobile' => $mobile), $data);
}
return $result;
}
}
?>
|
gpl-3.0
|
kkurapaty/SourceCodeCounter
|
SourceCodeCounter/Common/EnumExtensions.cs
|
1358
|
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace SourceCodeCounter.Common
{
/// <summary>
/// This class contains extension functions for enum type
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// Returns description of enum value if attached with enum member through DiscriptionAttribute
/// </summary>
/// <returns>Description of enum value</returns>
/// <see cref="DescriptionAttribute"/>
public static string ToDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
var descriptions = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (descriptions.Length > 0) ? descriptions[0].Description : fi.Name;
}
/// <summary>
/// Returns true if enum matches any of the given values
/// </summary>
/// <param name="value">Value to match</param>
/// <param name="values">Values to match against</param>
/// <returns>Return true if matched</returns>
public static bool In(this Enum value, params Enum[] values)
{
return values.Any(x => Equals(x, value));
}
}
}
|
gpl-3.0
|
mbj36/open-event-orga-server
|
open_event/forms/admin/language_form.py
|
302
|
"""Copyright 2015 Rafal Kowalski"""
from flask_wtf import Form
from wtforms import StringField, validators
class LanguageForm(Form):
"""Language Form class"""
name = StringField('Name', [validators.DataRequired()])
label_en = StringField('Label En')
label_de = StringField('Label DE')
|
gpl-3.0
|
flintforge/pyorgmode
|
pyorgmode/__init__.py
|
278
|
from .PyOrgMode import (OrgNode, OrgElement, OrgDataStructure, OrgDate)
__title__ = 'pyorgmode'
__version__ = '0.2.0'
__authors__ = 'the pyorgmode team'
__license__ = 'GPLv3'
__copyright__ = 'Jonathan BISSON'
__all__ = ['OrgNode','OrgElement', 'OrgDataStructure', 'OrgDate']
|
gpl-3.0
|
jazztickets/irrlamb
|
src/irrlicht/CXMLReader.cpp
|
1544
|
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CXMLReaderImpl.h"
#include "CXMLReader.h"
#include "IReadFile.h"
namespace irr
{
namespace io
{
//! Irrlicht implementation of the file read callback for the xml parser
class CIrrXMLFileReadCallBack : public IFileReadCallBack
{
public:
//! construct from FILE pointer
CIrrXMLFileReadCallBack(IReadFile* file)
: ReadFile(file)
{
ReadFile->grab();
}
//! destructor
virtual ~CIrrXMLFileReadCallBack()
{
ReadFile->drop();
}
//! Reads an amount of bytes from the file.
virtual int read(void* buffer, int sizeToRead)
{
return ReadFile->read(buffer, sizeToRead);
}
//! Returns size of file in bytes
virtual long getSize() const
{
return ReadFile->getSize();
}
private:
IReadFile* ReadFile;
}; // end class CMyXMLFileReadCallBack
// now create an implementation for IXMLReader using irrXML.
//! Creates an instance of a wide character xml parser.
IXMLReader* createIXMLReader(IReadFile* file)
{
if (!file)
return 0;
return new CXMLReaderImpl<wchar_t, IReferenceCounted>(new CIrrXMLFileReadCallBack(file));
}
//! Creates an instance of an UFT-8 or ASCII character xml parser.
IXMLReaderUTF8* createIXMLReaderUTF8(IReadFile* file)
{
if (!file)
return 0;
return new CXMLReaderImpl<char, IReferenceCounted>(new CIrrXMLFileReadCallBack(file));
}
} // end namespace
} // end namespace
|
gpl-3.0
|
Syliddar/ProBonoTracker
|
src/MemigrationProBonoTracker/Models/PersonViewModel/AssociatedPersonViewModel.cs
|
306
|
namespace MemigrationProBonoTracker.Models.PersonViewModel
{
public class AssociatedPersonViewModel
{
public int RelationId { get; set; }
public int AssociatedPersonId { get; set; }
public string FullName { get; set; }
public string Relation { get; set; }
}
}
|
gpl-3.0
|
mxhdev/SQLChecker
|
src/sqlchecker/io/impl/SimpleFileReader.java
|
689
|
package sqlchecker.io.impl;
import sqlchecker.io.AbstractFileReader;
public class SimpleFileReader extends AbstractFileReader {
private String fContent = "";
public SimpleFileReader(String path) {
super(path);
}
@Override
protected void onReadLine(String line) {
fContent += line + "\n";
}
@Override
protected void beforeReading(String pathToFile) {
fContent = "";
}
@Override
protected void afterReading(String pathToFile) {}
/**
* Only call this function after reading a file
* @return The content of the file as a String, lines are
* separated by \n
*/
public String getFileContent() {
return fContent;
}
}
|
gpl-3.0
|
cstrouse/chromebrew
|
packages/font_util.rb
|
1327
|
require 'package'
class Font_util < Package
description 'Tools for truncating and subseting of ISO10646-1 BDF fonts'
homepage 'https://xorg.freedesktop.org'
version '1.3.2'
compatibility 'all'
source_url 'https://www.x.org/releases/individual/font/font-util-1.3.2.tar.bz2'
source_sha256 '3ad880444123ac06a7238546fa38a2a6ad7f7e0cc3614de7e103863616522282'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/font_util-1.3.2-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/font_util-1.3.2-chromeos-armv7l.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/font_util-1.3.2-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/font_util-1.3.2-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: 'cdb0bcfb44dd1513f0db12b85f6b46b63ef1b937c0a7a17a4d7d4655667632bb',
armv7l: 'cdb0bcfb44dd1513f0db12b85f6b46b63ef1b937c0a7a17a4d7d4655667632bb',
i686: 'e53928dc50fe10c1a45adf1529bb829d96add95920b5697dbd237bc705ff5f06',
x86_64: '56739db34fb689edc5b5aea0c360c3ffdb12aec9e9bccfbd557d7c2c27542d47',
})
depends_on 'util_macros'
def self.build
system "./configure #{CREW_OPTIONS}"
system 'make'
end
def self.install
system "make install DESTDIR=#{CREW_DEST_DIR}"
end
end
|
gpl-3.0
|
Karplyak/avtomag.url.ph
|
wp-content/themes/net2ftp_installer.php
|
236521
|
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | License GNU/GPL - David Gartner - July 2006 |
// -------------------------------------------------------------------------------
// | PhpConcept Library - Tar Module 1.3 |
// | License GNU/GPL - Vincent Blavet - August 2001 |
// -------------------------------------------------------------------------------
// | PhpConcept Library - Zip Module 2.5 |
// | License GNU/LGPL - Vincent Blavet - March 2006 |
// -------------------------------------------------------------------------------
// | 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 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 |
// -------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Set PHP parameters
// --------------------------------------------------------------------------------
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set("max_execution_time", "300");
ini_set("memory_limit", "64M");
// --------------------------------------------------------------------------------
// Check the security code
// --------------------------------------------------------------------------------
if ($_GET["security_code"] == "") {
echo "You didn't enter the security code at the end of the URL. For security reasons the net2ftp install script only executes when this code is entered.";
exit();
}
elseif ($_GET["security_code"] != "pysieupfpk31ch1fhygf" || $_GET["security_code"] == ("NET2FTP_" . "SECURITY_CODE")) {
echo "Incorrect security code. For security reasons the net2ftp install script only executes when the correct code is entered.";
exit();
}
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function validateDirectory($directory) {
// --------------
// Remove * ? < > |
// --------------
$directory = preg_replace("/[\\*\\?\\<\\>\\|]/", "", $directory);
return $directory;
} // end validateDirectory
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function validateGenericInput($input) {
// --------------
// Remove the following characters <>
// --------------
$input = preg_replace("/\\<\\>]/", "", $input);
return $input;
} // end validateGenericInput
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function get_filename_extension($filename) {
// --------------
// This function returns the extension of a filename:
// name.ext1.ext2.ext3 --> ext3
// name --> name
// .name --> name
// .name.ext --> ext
// It also converts the result to lower case:
// name.ext1.EXT2 --> ext2
// --------------
$lastdotposition = strrpos($filename,".");
if ($lastdotposition === 0) { $extension = substr($filename, 1); }
elseif ($lastdotposition == "") { $extension = $filename; }
else { $extension = substr($filename, $lastdotposition + 1); }
return strtolower($extension);
} // End get_filename_extension
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function delete_dirorfile($dirorfile, $mode) {
// --------------
// This function deletes a local directory recursively
// Credit goes to itportal at gmail dot com, 17-Jul-2006 05:29
// --------------
if ($mode != "execute") { $mode = "simulate"; }
if (is_dir($dirorfile)) {
$directory = $dirorfile;
if(substr($dir, -1, 1) == "/"){
$directory = substr($directory, 0, strlen($directory) - 1);
}
if ($handle = opendir("$directory")) {
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..") {
if (is_dir("$directory/$item")) {
if ($mode == "execute") { echo "Processing directory $directory/$item<br />\n"; }
delete_dirorfile("$directory/$item", $mode);
} else {
if ($mode == "execute") {
unlink("$directory/$item");
echo "Removed file $directory/$item<br />\n";
}
elseif ($mode == "simulate") {
echo "File $directory/$item<br />\n";
}
}
}
}
closedir($handle);
if ($mode == "execute") {
rmdir($directory);
echo "Removed directory $directory<br />\n";
}
elseif ($mode == "simulate") {
echo "Directory $directory<br />\n";
}
}
}
elseif (is_file($dirorfile)) {
$file = $dirorfile;
if ($mode == "execute") {
unlink($file);
echo "Removed file $file<br />\n";
}
elseif ($mode == "simulate") {
echo "File $file<br />\n";
}
}
else {
if ($mode == "execute") {
echo "Could not remove $dirorfile<br />\n.";
}
elseif ($mode == "simulate") {
echo "Entry $dirorfile can't be removed.<br />\n";
}
}
} // End delete_dirorfile
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function ftpAsciiBinary($filename) {
// --------------
// Checks the first character of a file and its extension to see if it should be
// transferred in ASCII or Binary mode
// --------------
$firstcharacter = substr($filename, 0, 1);
if ($firstcharacter == ".") {
$ftpmode = FTP_ASCII;
return $ftpmode;
}
$last = get_filename_extension($filename);
if (
$last == "1st" ||
$last == "asp" ||
$last == "bas" ||
$last == "bat" ||
$last == "c" ||
$last == "cfg" ||
$last == "cfm" ||
$last == "cgi" ||
$last == "conf" ||
$last == "cpp" ||
$last == "css" ||
$last == "csv" ||
$last == "dhtml" ||
$last == "diz" ||
$last == "default" ||
$last == "file" ||
$last == "h" ||
$last == "hpp" ||
$last == "htaccess" ||
$last == "htpasswd" ||
$last == "htm" ||
$last == "html" ||
$last == "inc" ||
$last == "ini" ||
$last == "js" ||
$last == "jsp" ||
$last == "log" ||
$last == "m3u" ||
$last == "mak" ||
$last == "msg" ||
$last == "nfo" ||
$last == "old" ||
$last == "pas" ||
$last == "patch" ||
$last == "perl" ||
$last == "php" ||
$last == "php3" ||
$last == "phps" ||
$last == "phtml" ||
$last == "pinerc" ||
$last == "pl" ||
$last == "pm" ||
$last == "qmail" ||
$last == "readme" ||
$last == "setup" ||
$last == "seq" ||
$last == "sh" ||
$last == "sql" ||
$last == "style" ||
$last == "tcl" ||
$last == "tex" ||
$last == "threads" ||
$last == "tmpl" ||
$last == "tpl" ||
$last == "txt" ||
$last == "ubb" ||
$last == "vbs" ||
$last == "xml" ||
strstr($last, "htm")
) { $ftpmode = FTP_ASCII; }
else { $ftpmode = FTP_BINARY; }
return $ftpmode;
} // end ftpAsciiBinary
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// --------------------------------------------------------------------------------
// PhpConcept Library - Zip Module 2.5
// --------------------------------------------------------------------------------
// License GNU/LGPL - Vincent Blavet - March 2006
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
// PclZip is a PHP library that manage ZIP archives.
// So far tests show that archives generated by PclZip are readable by
// WinZip application and other tools.
//
// Description :
// See readme.txt and http://www.phpconcept.net
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// $Id: pclzip.lib.php,v 1.44 2006/03/08 21:23:59 vblavet Exp $
// --------------------------------------------------------------------------------
// ----- Constants
define( 'PCLZIP_READ_BLOCK_SIZE', 2048 );
// ----- File list separator
// In version 1.x of PclZip, the separator for file list is a space
// (which is not a very smart choice, specifically for windows paths !).
// A better separator should be a comma (,). This constant gives you the
// abilty to change that.
// However notice that changing this value, may have impact on existing
// scripts, using space separated filenames.
// Recommanded values for compatibility with older versions :
//define( 'PCLZIP_SEPARATOR', ' ' );
// Recommanded values for smart separation of filenames.
define( 'PCLZIP_SEPARATOR', ',' );
// ----- Error configuration
// 0 : PclZip Class integrated error handling
// 1 : PclError external library error handling. By enabling this
// you must ensure that you have included PclError library.
// [2,...] : reserved for futur use
define( 'PCLZIP_ERROR_EXTERNAL', 0 );
// ----- Optional static temporary directory
// By default temporary files are generated in the script current
// path.
// If defined :
// - MUST BE terminated by a '/'.
// - MUST be a valid, already created directory
// Samples :
// define( 'PCLZIP_TEMPORARY_DIR', '/temp/' );
// define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' );
define( 'PCLZIP_TEMPORARY_DIR', '' );
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------
// ----- Global variables
$g_pclzip_version = "2.5";
// ----- Error codes
// -1 : Unable to open file in binary write mode
// -2 : Unable to open file in binary read mode
// -3 : Invalid parameters
// -4 : File does not exist
// -5 : Filename is too long (max. 255)
// -6 : Not a valid zip file
// -7 : Invalid extracted file size
// -8 : Unable to create directory
// -9 : Invalid archive extension
// -10 : Invalid archive format
// -11 : Unable to delete file (unlink)
// -12 : Unable to rename file (rename)
// -13 : Invalid header checksum
// -14 : Invalid archive size
define( 'PCLZIP_ERR_USER_ABORTED', 2 );
define( 'PCLZIP_ERR_NO_ERROR', 0 );
define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 );
define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 );
define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 );
define( 'PCLZIP_ERR_MISSING_FILE', -4 );
define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 );
define( 'PCLZIP_ERR_INVALID_ZIP', -6 );
define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 );
define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 );
define( 'PCLZIP_ERR_BAD_EXTENSION', -9 );
define( 'PCLZIP_ERR_BAD_FORMAT', -10 );
define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 );
define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 );
define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 );
define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 );
define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 );
define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 );
define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 );
define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 );
define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 );
define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 );
define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 );
// ----- Options values
define( 'PCLZIP_OPT_PATH', 77001 );
define( 'PCLZIP_OPT_ADD_PATH', 77002 );
define( 'PCLZIP_OPT_REMOVE_PATH', 77003 );
define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 );
define( 'PCLZIP_OPT_SET_CHMOD', 77005 );
define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 );
define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 );
define( 'PCLZIP_OPT_BY_NAME', 77008 );
define( 'PCLZIP_OPT_BY_INDEX', 77009 );
define( 'PCLZIP_OPT_BY_EREG', 77010 );
define( 'PCLZIP_OPT_BY_PREG', 77011 );
define( 'PCLZIP_OPT_COMMENT', 77012 );
define( 'PCLZIP_OPT_ADD_COMMENT', 77013 );
define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 );
define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 );
define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 );
define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 );
// Having big trouble with crypt. Need to multiply 2 long int
// which is not correctly supported by PHP ...
//define( 'PCLZIP_OPT_CRYPT', 77018 );
define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 );
// ----- File description attributes
define( 'PCLZIP_ATT_FILE_NAME', 79001 );
define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 );
define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 );
// ----- Call backs values
define( 'PCLZIP_CB_PRE_EXTRACT', 78001 );
define( 'PCLZIP_CB_POST_EXTRACT', 78002 );
define( 'PCLZIP_CB_PRE_ADD', 78003 );
define( 'PCLZIP_CB_POST_ADD', 78004 );
/* For futur use
define( 'PCLZIP_CB_PRE_LIST', 78005 );
define( 'PCLZIP_CB_POST_LIST', 78006 );
define( 'PCLZIP_CB_PRE_DELETE', 78007 );
define( 'PCLZIP_CB_POST_DELETE', 78008 );
*/
// --------------------------------------------------------------------------------
// Class : PclZip
// Description :
// PclZip is the class that represent a Zip archive.
// The public methods allow the manipulation of the archive.
// Attributes :
// Attributes must not be accessed directly.
// Methods :
// PclZip() : Object creator
// create() : Creates the Zip archive
// listContent() : List the content of the Zip archive
// extract() : Extract the content of the archive
// properties() : List the properties of the archive
// --------------------------------------------------------------------------------
class PclZip
{
// ----- Filename of the zip file
var $zipname = '';
// ----- File descriptor of the zip file
var $zip_fd = 0;
// ----- Internal error handling
var $error_code = 1;
var $error_string = '';
// ----- Current status of the magic_quotes_runtime
// This value store the php configuration for magic_quotes
// The class can then disable the magic_quotes and reset it after
var $magic_quotes_status;
// --------------------------------------------------------------------------------
// Function : PclZip()
// Description :
// Creates a PclZip object and set the name of the associated Zip archive
// filename.
// Note that no real action is taken, if the archive does not exist it is not
// created. Use create() for that.
// --------------------------------------------------------------------------------
function PclZip($p_zipname)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::PclZip', "zipname=$p_zipname");
// ----- Tests the zlib
if (!function_exists('gzopen'))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 1, "zlib extension seems to be missing");
die('Abort '.basename(__FILE__).' : Missing zlib extensions');
}
// ----- Set the attributes
$this->zipname = $p_zipname;
$this->zip_fd = 0;
$this->magic_quotes_status = -1;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 1);
return;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : listContent()
// Description :
// This public method, gives the list of the files and directories, with their
// properties.
// The properties of each entries in the list are (used also in other functions) :
// filename : Name of the file. For a create or add action it is the filename
// given by the user. For an extract function it is the filename
// of the extracted file.
// stored_filename : Name of the file / directory stored in the archive.
// size : Size of the stored file.
// compressed_size : Size of the file's data compressed in the archive
// (without the headers overhead)
// mtime : Last known modification date of the file (UNIX timestamp)
// comment : Comment associated with the file
// folder : true | false
// index : index of the file in the archive
// status : status of the action (depending of the action) :
// Values are :
// ok : OK !
// filtered : the file / dir is not extracted (filtered by user)
// already_a_directory : the file can not be extracted because a
// directory with the same name already exists
// write_protected : the file can not be extracted because a file
// with the same name already exists and is
// write protected
// newer_exist : the file was not extracted because a newer file exists
// path_creation_fail : the file is not extracted because the folder
// does not exists and can not be created
// write_error : the file was not extracted because there was a
// error while writing the file
// read_error : the file was not extracted because there was a error
// while reading the file
// invalid_header : the file was not extracted because of an archive
// format error (bad file header)
// Note that each time a method can continue operating when there
// is an action error on a file, the error is only logged in the file status.
// Return Values :
// 0 on an unrecoverable failure,
// The list of the files in the archive.
// --------------------------------------------------------------------------------
function listContent()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::listContent', "");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = $this->privList($p_list)) != 1)
{
unset($p_list);
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extract($p_path="./", $p_remove_path="")
// extract([$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method extract all the files / directories from the archive to the
// folder indicated in $p_path.
// If you want to ignore the 'root' part of path of the memorized files
// you can indicate this in the optional $p_remove_path parameter.
// By default, if a newer file with the same name already exists, the
// file is not extracted.
//
// If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
// are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
// at the end of the path value of PCLZIP_OPT_PATH.
// Parameters :
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// PCLZIP_OPT_PATH :
// PCLZIP_OPT_ADD_PATH :
// PCLZIP_OPT_REMOVE_PATH :
// PCLZIP_OPT_REMOVE_ALL_PATH :
// PCLZIP_CB_PRE_EXTRACT :
// PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 or a negative value on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function extract()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extract", "");
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method");
// ----- Default values for option
$v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options");
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (PCLZIP_OPT_PATH => 'optional',
PCLZIP_OPT_REMOVE_PATH => 'optional',
PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
PCLZIP_OPT_ADD_PATH => 'optional',
PCLZIP_CB_PRE_EXTRACT => 'optional',
PCLZIP_CB_POST_EXTRACT => 'optional',
PCLZIP_OPT_SET_CHMOD => 'optional',
PCLZIP_OPT_BY_NAME => 'optional',
PCLZIP_OPT_BY_EREG => 'optional',
PCLZIP_OPT_BY_PREG => 'optional',
PCLZIP_OPT_BY_INDEX => 'optional',
PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
PCLZIP_OPT_REPLACE_NEWER => 'optional'
,PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional'
));
if ($v_result != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Set the arguments
if (isset($v_options[PCLZIP_OPT_PATH])) {
$v_path = $v_options[PCLZIP_OPT_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[PCLZIP_OPT_ADD_PATH];
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis");
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return 0;
}
}
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'");
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
$v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo());
return(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : properties()
// Description :
// This method gives the properties of the archive.
// The properties are :
// nb : Number of files in the archive
// comment : Comment associated with the archive file
// status : not_exist, ok
// Parameters :
// None
// Return Values :
// 0 on failure,
// An array with the archive properties.
// --------------------------------------------------------------------------------
function properties()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::properties", "");
// ----- Reset the error handler
$this->privErrorReset();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check archive
if (!$this->privCheckFormat()) {
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return(0);
}
// ----- Default properties
$v_prop = array();
$v_prop['comment'] = '';
$v_prop['nb'] = 0;
$v_prop['status'] = 'not_exist';
// ----- Look if file exists
if (@is_file($this->zipname))
{
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), 0);
return 0;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0);
return 0;
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Set the user attributes
$v_prop['comment'] = $v_central_dir['comment'];
$v_prop['nb'] = $v_central_dir['entries'];
$v_prop['status'] = 'ok';
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_prop);
return $v_prop;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFormat()
// Description :
// This method check that the archive exists and is a valid zip archive.
// Several level of check exists. (futur)
// Parameters :
// $p_level : Level of check. Default 0.
// 0 : Check the first bytes (magic codes) (default value))
// 1 : 0 + Check the central directory (futur)
// 2 : 1 + Check each file header (futur)
// Return Values :
// true on success,
// false on error, the error code is set.
// --------------------------------------------------------------------------------
function privCheckFormat($p_level=0)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFormat", "");
$v_result = true;
// ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the file exits
if (!is_file($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo());
return(false);
}
// ----- Check that the file is readeable
if (!is_readable($this->zipname)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo());
return(false);
}
// ----- Check the magic code
// TBC
// ----- Check the central header
// TBC
// ----- Check each file header
// TBC
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privParseOptions()
// Description :
// This internal methods reads the variable list of arguments ($p_options_list,
// $p_size) and generate an array with the options and values ($v_result_list).
// $v_requested_options contains the options that can be present and those that
// must be present.
// $v_requested_options is an array, with the option value as key, and 'optional',
// or 'mandatory' as value.
// Parameters :
// See above.
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privParseOptions", "");
$v_result=1;
// ----- Read the options
$i=0;
while ($i<$p_size) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Looking for table index $i, option = '".PclZipUtilOptionText($p_options_list[$i])."(".$p_options_list[$i].")'");
// ----- Check if the option is supported
if (!isset($v_requested_options[$p_options_list[$i]])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Look for next option
switch ($p_options_list[$i]) {
// ----- Look for options that request a path value
case PCLZIP_OPT_PATH :
case PCLZIP_OPT_REMOVE_PATH :
case PCLZIP_OPT_ADD_PATH :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if ( is_string($p_options_list[$i+1])
&& ($p_options_list[$i+1] != '')) {
$v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." set with an empty value is ignored.");
}
break;
// ----- Look for options that request an array of string for value
case PCLZIP_OPT_BY_NAME :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that request an EREG or PREG expression
case PCLZIP_OPT_BY_EREG :
case PCLZIP_OPT_BY_PREG :
//case PCLZIP_OPT_CRYPT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that takes a string
case PCLZIP_OPT_COMMENT :
case PCLZIP_OPT_ADD_COMMENT :
case PCLZIP_OPT_PREPEND_COMMENT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE,
"Missing parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE,
"Wrong parameter value for option '"
.PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that request an array of index
case PCLZIP_OPT_BY_INDEX :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_work_list = array();
if (is_string($p_options_list[$i+1])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is a string '".$p_options_list[$i+1]."'");
// ----- Remove spaces
$p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
// ----- Parse items
$v_work_list = explode(",", $p_options_list[$i+1]);
}
else if (is_integer($p_options_list[$i+1])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an integer '".$p_options_list[$i+1]."'");
$v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an array");
$v_work_list = $p_options_list[$i+1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Reduce the index list
// each index item in the list must be a couple with a start and
// an end value : [0,3], [5-5], [8-10], ...
// ----- Check the format of each item
$v_sort_flag=false;
$v_sort_value=0;
for ($j=0; $j<sizeof($v_work_list); $j++) {
// ----- Explode the item
$v_item_list = explode("-", $v_work_list[$j]);
$v_size_item_list = sizeof($v_item_list);
// ----- TBC : Here we might check that each item is a
// real integer ...
// ----- Look for single value
if ($v_size_item_list == 1) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
}
elseif ($v_size_item_list == 2) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
}
else {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extracted index item = [".$v_result_list[$p_options_list[$i]][$j]['start'].",".$v_result_list[$p_options_list[$i]][$j]['end']."]");
// ----- Look for list sort
if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The list should be sorted ...");
$v_sort_flag=true;
// ----- TBC : An automatic sort should be writen ...
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
$v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
}
// ----- Sort the items
if ($v_sort_flag) {
// TBC : To Be Completed
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "List sorting is not yet write ...");
}
// ----- Next option
$i++;
break;
// ----- Look for options that request no value
case PCLZIP_OPT_REMOVE_ALL_PATH :
case PCLZIP_OPT_EXTRACT_AS_STRING :
case PCLZIP_OPT_NO_COMPRESSION :
case PCLZIP_OPT_EXTRACT_IN_OUTPUT :
case PCLZIP_OPT_REPLACE_NEWER :
case PCLZIP_OPT_STOP_ON_ERROR :
$v_result_list[$p_options_list[$i]] = true;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
break;
// ----- Look for options that request an octal value
case PCLZIP_OPT_SET_CHMOD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'");
$i++;
break;
// ----- Look for options that request a call-back
case PCLZIP_CB_PRE_EXTRACT :
case PCLZIP_CB_POST_EXTRACT :
case PCLZIP_CB_PRE_ADD :
case PCLZIP_CB_POST_ADD :
/* for futur use
case PCLZIP_CB_PRE_DELETE :
case PCLZIP_CB_POST_DELETE :
case PCLZIP_CB_PRE_LIST :
case PCLZIP_CB_POST_LIST :
*/
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Get the value
$v_function_name = $p_options_list[$i+1];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "call-back ".PclZipUtilOptionText($p_options_list[$i])." = '".$v_function_name."'");
// ----- Check that the value is a valid existing function
if (!function_exists($v_function_name)) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Set the attribute
$v_result_list[$p_options_list[$i]] = $v_function_name;
$i++;
break;
default :
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '"
.$p_options_list[$i]."'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Next options
$i++;
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Look if present
if (!isset($v_result_list[$key])) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOpenFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privOpenFd($p_mode)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privOpenFd", 'mode='.$p_mode);
$v_result=1;
// ----- Look if already open
if ($this->zip_fd != 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Open file in '.$p_mode.' mode');
if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCloseFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privCloseFd()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCloseFd", "");
$v_result=1;
if ($this->zip_fd != 0)
@fclose($this->zip_fd);
$this->zip_fd = 0;
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privList()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privList(&$p_list)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privList", "list");
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Go to beginning of Central Dir
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Offset : ".$v_central_dir['offset']."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_central_dir['offset']))
{
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'");
// ----- Read each entry
for ($i=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$v_header['index'] = $i;
// ----- Get the only interesting attributes
$this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
unset($v_header);
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privConvertHeader2FileInfo()
// Description :
// This function takes the file informations from the central directory
// entries and extract the interesting parameters that will be given back.
// The resulting file infos are set in the array $p_info
// $p_info['filename'] : Filename with full path. Given by user (add),
// extracted in the filesystem (extract).
// $p_info['stored_filename'] : Stored filename in the archive.
// $p_info['size'] = Size of the file.
// $p_info['compressed_size'] = Compressed size of the file.
// $p_info['mtime'] = Last modification date of the file.
// $p_info['comment'] = Comment associated with the file.
// $p_info['folder'] = true/false : indicates if the entry is a folder or not.
// $p_info['status'] = status of the action on the file.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privConvertHeader2FileInfo($p_header, &$p_info)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privConvertHeader2FileInfo", "Filename='".$p_header['filename']."'");
$v_result=1;
// ----- Get the interesting attributes
$p_info['filename'] = $p_header['filename'];
$p_info['stored_filename'] = $p_header['stored_filename'];
$p_info['size'] = $p_header['size'];
$p_info['compressed_size'] = $p_header['compressed_size'];
$p_info['mtime'] = $p_header['mtime'];
$p_info['comment'] = $p_header['comment'];
$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
$p_info['index'] = $p_header['index'];
$p_info['status'] = $p_header['status'];
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractByRule()
// Description :
// Extract a file or directory depending of rules (by index, by name, ...)
// Parameters :
// $p_file_list : An array where will be placed the properties of each
// extracted file
// $p_path : Path to add while writing the extracted files
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// 1 on success,0 or less on error (see error code list)
// --------------------------------------------------------------------------------
function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privExtractByRule", "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'");
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check the path
if ( ($p_path == "")
|| ( (substr($p_path, 0, 1) != "/")
&& (substr($p_path, 0, 3) != "../")
&& (substr($p_path,1,2)!=":/")))
// net2ftp
// $p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'");
$p_path = substr($p_path, 0, strlen($p_path)-1);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]");
}
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the zip file
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_result = $this->privOpenFd('rb')) != 1)
{
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
// ----- Read each entry
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry : '$i'");
// ----- Read next Central dir entry
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position before rewind : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position after rewind : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position after fseek : ".ftell($this->zip_fd)."'");
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the index
$v_header['index'] = $i;
// ----- Store the file position
$v_pos_entry = ftell($this->zip_fd);
// ----- Look for the specific extract rules
$v_extract = false;
// ----- Look for extract by name rule
if ( (isset($p_options[PCLZIP_OPT_BY_NAME]))
&& ($p_options[PCLZIP_OPT_BY_NAME] != 0)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'");
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Compare with file '".$p_options[PCLZIP_OPT_BY_NAME][$j]."'");
// ----- Look for a directory
if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The searched item is a directory");
// ----- Look if the directory is in the filename path
if ( (strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path");
$v_extract = true;
}
}
// ----- Look for a filename
elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one.");
$v_extract = true;
}
}
}
// ----- Look for extract by ereg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_EREG]))
&& ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'");
if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression");
$v_extract = true;
}
}
// ----- Look for extract by preg rule
else if ( (isset($p_options[PCLZIP_OPT_BY_PREG]))
&& ($p_options[PCLZIP_OPT_BY_PREG] != "")) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'");
if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression");
$v_extract = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX]))
&& ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'");
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look if index '$i' is in [".$p_options[PCLZIP_OPT_BY_INDEX][$j]['start'].",".$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']."]");
if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range");
$v_extract = true;
}
if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop");
$j_start = $j+1;
}
if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop");
break;
}
}
}
// ----- Look for no rule, which means extract all the archive
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with no rule (extract all)");
$v_extract = true;
}
// ----- Check compression method
if ( ($v_extract)
&& ( ($v_header['compression'] != 8)
&& ($v_header['compression'] != 0))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported compression method (".$v_header['compression'].")");
$v_header['status'] = 'unsupported_compression';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
"Filename '".$v_header['stored_filename']."' is "
."compressed by an unsupported compression "
."method (".$v_header['compression'].") ");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Check encrypted files
if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported file encryption");
$v_header['status'] = 'unsupported_encryption';
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
$this->privSwapBackMagicQuotes();
PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
"Unsupported encryption for "
." filename '".$v_header['stored_filename']
."'");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "No need for extract");
$v_result = $this->privConvertHeader2FileInfo($v_header,
$p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$v_extract = false;
}
// ----- Look for real extraction
if ($v_extract)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file '".$v_header['filename']."', index '$i'");
// ----- Go to the file position
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'");
@rewind($this->zip_fd);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'");
if (@fseek($this->zip_fd, $v_header['offset']))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'");
// ----- Look for extraction as string
if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) {
// ----- Extracting the file
$v_result1 = $this->privExtractFileAsString($v_header, $v_string);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1);
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Set the file content
$p_file_list[$v_nb_extracted]['content'] = $v_string;
// ----- Next extracted file
$v_nb_extracted++;
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
&& ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1);
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
$p_path, $p_remove_path,
$p_remove_all_path,
$p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1);
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
}
}
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFile()
// Description :
// Parameters :
// Return Values :
//
// 1 : ... ?
// PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
// --------------------------------------------------------------------------------
function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFile', "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'");
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'");
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for all path to remove
if ($p_remove_all_path == true) {
// ----- Look for folder entry that not need to be extracted
if (($p_entry['external']&0x00000010)==0x00000010) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The entry is a folder : need to be filtered");
$p_entry['status'] = "filtered";
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "All path is removed");
// ----- Get the basename of the path
$p_entry['filename'] = basename($p_entry['filename']);
}
// ----- Look for path to remove
else if ($p_remove_path != "")
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look for some path to remove");
if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The folder is the same as the removed path '".$p_entry['filename']."'");
// ----- Change the file status
$p_entry['status'] = "filtered";
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
$p_remove_path_size = strlen($p_remove_path);
if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '".$p_entry['filename']."'");
// ----- Remove the path
$p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Resulting file is '".$p_entry['filename']."'");
}
}
// ----- Add the path
if ($p_path != '') {
$p_entry['filename'] = $p_path."/".$p_entry['filename'];
}
// ----- Check a base_dir_restriction
if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Check the extract directory restriction");
$v_inclusion
= PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION],
$p_entry['filename']);
if ($v_inclusion == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_EXTRACT_DIR_RESTRICTION is selected, file is outside restriction");
PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION,
"Filename '".$p_entry['filename']."' is "
."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'");
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'");
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Look for specific actions while the file exist
if (file_exists($p_entry['filename']))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$p_entry['filename']."' already exists");
// ----- Look if file is a directory
if (is_dir($p_entry['filename']))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is a directory");
// ----- Change the file status
$p_entry['status'] = "already_a_directory";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY,
"Filename '".$p_entry['filename']."' is "
."already used by an existing directory");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is write protected");
// ----- Change the file status
$p_entry['status'] = "write_protected";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Filename '".$p_entry['filename']."' exists "
."and is write protected");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Look if the extracted file is older
else if (filemtime($p_entry['filename']) > $p_entry['mtime'])
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is newer (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")");
// ----- Change the file status
if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER]))
&& ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_REPLACE_NEWER is selected, file will be replaced");
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be replaced");
$p_entry['status'] = "newer_exist";
// ----- Look for PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped");
PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL,
"Newer version of '".$p_entry['filename']."' exists "
."and option PCLZIP_OPT_REPLACE_NEWER is not selected");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is older than the extrated one - will be replaced by the extracted one (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")");
}
}
// ----- Check the directory availability and create it if necessary
else {
if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/'))
$v_dir_to_check = $p_entry['filename'];
else if (!strstr($p_entry['filename'], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($p_entry['filename']);
if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '".$p_entry['filename']."'");
// ----- Change the file status
$p_entry['status'] = "path_creation_fail";
// ----- Return
////--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
//return $v_result;
$v_result = 1;
}
}
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file");
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode");
// ----- Change the file status
$p_entry['status'] = "write_error";
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read '".$p_entry['size']."' bytes");
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read $v_read_size bytes");
$v_buffer = @fread($this->zip_fd, $v_read_size);
/* Try to speed up the code
$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_binary_data, $v_read_size);
*/
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Closing the destination file
fclose($v_dest_file);
// ----- Change the file mtime
touch($p_entry['filename'], $p_entry['mtime']);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (Compression method ".$p_entry['compression'].")");
// ----- TBC
// Need to be finished
if (($p_entry['flag'] & 1) == 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File is encrypted");
/*
// ----- Read the encryption header
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read 12 encryption header bytes");
$v_encryption_header = @fread($this->zip_fd, 12);
// ----- Read the encrypted & compressed file in a buffer
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".($p_entry['compressed_size']-12)."' compressed & encrypted bytes");
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']-12);
// ----- Decrypt the buffer
$this->privDecrypt($v_encryption_header, $v_buffer,
$p_entry['compressed_size']-12, $p_entry['crc']);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Buffer is '".$v_buffer."'");
*/
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".$p_entry['compressed_size']."' compressed bytes");
// ----- Read the compressed file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
// ----- Decompress the file
$v_file_content = @gzinflate($v_buffer);
unset($v_buffer);
if ($v_file_content === FALSE) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to inflate compressed file");
// ----- Change the file status
// TBC
$p_entry['status'] = "error";
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode");
// ----- Change the file status
$p_entry['status'] = "write_error";
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Write the uncompressed data
@fwrite($v_dest_file, $v_file_content, $p_entry['size']);
unset($v_file_content);
// ----- Closing the destination file
@fclose($v_dest_file);
// ----- Change the file mtime
@touch($p_entry['filename'], $p_entry['mtime']);
}
// ----- Look for chmod option
if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "chmod option activated '".$p_options[PCLZIP_OPT_SET_CHMOD]."'");
// ----- Change the mode of the file
@chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileInOutput()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileInOutput(&$p_entry, &$p_options)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileInOutput', "");
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'");
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'");
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'");
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
if ($p_entry['compressed_size'] == $p_entry['size']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes");
// ----- Read the file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Send the file to the output
echo $v_buffer;
unset($v_buffer);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Reading '".$p_entry['size']."' bytes");
// ----- Read the compressed file in a buffer (one shot)
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
$v_file_content = gzinflate($v_buffer);
unset($v_buffer);
// ----- Send the file to the output
echo $v_file_content;
unset($v_file_content);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction");
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);');
// ----- Look for abort result
if ($v_result == 2) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction");
$v_result = PCLZIP_ERR_USER_ABORTED;
}
}
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileAsString()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileAsString(&$p_entry, &$p_string)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileAsString', "p_entry['filename']='".$p_entry['filename']."'");
$v_result=1;
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'");
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file in string (with path) '".$p_entry['filename']."', size '$v_header[size]'");
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
// if ($p_entry['compressed_size'] == $p_entry['size'])
if ($p_entry['compression'] == 0) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes");
// ----- Reading the file
$p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (compression method '".$p_entry['compression']."')");
// ----- Reading the file
$v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
// ----- Decompress the file
if (($p_string = @gzinflate($v_data)) === FALSE) {
// TBC
}
}
// ----- Trace
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
else {
// TBC : error : can not extract a folder in a string
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadFileHeader(&$p_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadFileHeader", "");
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'");
$v_data = unpack('Vid', $v_binary_data);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'");
// ----- Check signature
if ($v_data['id'] != 0x04034b50)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid File header");
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 26);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 26)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data));
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Extract the values
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header : '".$v_binary_data."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header (Hex) : '".bin2hex($v_binary_data)."'");
$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
// ----- Get filename
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "File name length : ".$v_data['filename_len']);
$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename : \''.$p_header['filename'].'\'');
// ----- Get extra_fields
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extra field length : ".$v_data['extra_len']);
if ($v_data['extra_len'] != 0) {
$p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
}
else {
$p_header['extra'] = '';
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Extra field : \''.bin2hex($p_header['extra']).'\'');
// ----- Extract properties
$p_header['version_extracted'] = $v_data['version'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : ('.$p_header['version_extracted'].') \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\'');
$p_header['compression'] = $v_data['compression'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compression method : \''.$p_header['compression'].'\'');
$p_header['size'] = $v_data['size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_header['size'].'\'');
$p_header['compressed_size'] = $v_data['compressed_size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_header['compressed_size'].'\'');
$p_header['crc'] = $v_data['crc'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\'');
$p_header['flag'] = $v_data['flag'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Flag : \''.$p_header['flag'].'\'');
$p_header['filename_len'] = $v_data['filename_len'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename_len : \''.$p_header['filename_len'].'\'');
// ----- Recuperate date in UNIX format
$p_header['mdate'] = $v_data['mdate'];
$p_header['mtime'] = $v_data['mtime'];
if ($p_header['mdate'] && $p_header['mtime'])
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
else
{
$p_header['mtime'] = time();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
// TBC
//for(reset($v_data); $key = key($v_data); next($v_data)) {
// //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Attribut[$key] = ".$v_data[$key]);
//}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set the status field
$p_header['status'] = "ok";
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadCentralFileHeader(&$p_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadCentralFileHeader", "");
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'");
$v_data = unpack('Vid', $v_binary_data);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'");
// ----- Check signature
if ($v_data['id'] != 0x02014b50)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid Central Dir File signature");
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 42);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 42)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data));
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Extract the values
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header : '".$v_binary_data."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header (Hex) : '".bin2hex($v_binary_data)."'");
$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
// ----- Get filename
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File name length : ".$p_header['filename_len']);
if ($p_header['filename_len'] != 0)
$p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
else
$p_header['filename'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Filename : \''.$p_header['filename'].'\'');
// ----- Get extra
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Extra length : ".$p_header['extra_len']);
if ($p_header['extra_len'] != 0)
$p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
else
$p_header['extra'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Extra : \''.$p_header['extra'].'\'');
// ----- Get comment
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Comment length : ".$p_header['comment_len']);
if ($p_header['comment_len'] != 0)
$p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
else
$p_header['comment'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Comment : \''.$p_header['comment'].'\'');
// ----- Extract properties
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version : \''.($p_header['version']/10).'.'.($p_header['version']%10).'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Size : \''.$p_header['size'].'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Compressed Size : \''.$p_header['compressed_size'].'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Flag : \''.$p_header['flag'].'\'');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Offset : \''.$p_header['offset'].'\'');
// ----- Recuperate date in UNIX format
if ($p_header['mdate'] && $p_header['mtime'])
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
else
{
$p_header['mtime'] = time();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\'');
}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set default status to ok
$p_header['status'] = 'ok';
// ----- Look if it is a directory
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Internal (Hex) : '".sprintf("Ox%04X", $p_header['internal'])."'");
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "External (Hex) : '".sprintf("Ox%04X", $p_header['external'])."' (".(($p_header['external']&0x00000010)==0x00000010?'is a folder':'is a file').')');
if (substr($p_header['filename'], -1) == '/') {
//$p_header['external'] = 0x41FF0010;
$p_header['external'] = 0x00000010;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Force folder external : \''.sprintf("Ox%04X", $p_header['external']).'\'');
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Header of filename : \''.$p_header['filename'].'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFileHeaders()
// Description :
// Parameters :
// Return Values :
// 1 on success,
// 0 on error;
// --------------------------------------------------------------------------------
function privCheckFileHeaders(&$p_local_header, &$p_central_header)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFileHeaders", "");
$v_result=1;
// ----- Check the static values
// TBC
if ($p_local_header['filename'] != $p_central_header['filename']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename" : TBC To Be Completed');
}
if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "version_extracted" : TBC To Be Completed');
}
if ($p_local_header['flag'] != $p_central_header['flag']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "flag" : TBC To Be Completed');
}
if ($p_local_header['compression'] != $p_central_header['compression']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "compression" : TBC To Be Completed');
}
if ($p_local_header['mtime'] != $p_central_header['mtime']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "mtime" : TBC To Be Completed');
}
if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename_len" : TBC To Be Completed');
}
// ----- Look for flag bit 3
if (($p_local_header['flag'] & 8) == 8) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Purpose bit flag bit 3 set !');
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'File size, compression size and crc found in central header');
$p_local_header['size'] = $p_central_header['size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_local_header['size'].'\'');
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_local_header['compressed_size'].'\'');
$p_local_header['crc'] = $p_central_header['crc'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_local_header['crc']).'\'');
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadEndCentralDir()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadEndCentralDir(&$p_central_dir)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadEndCentralDir", "");
$v_result=1;
// ----- Go to the end of the zip file
$v_size = filesize($this->zipname);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size of the file :$v_size");
@fseek($this->zip_fd, $v_size);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position at end of zip file : \''.ftell($this->zip_fd).'\'');
if (@ftell($this->zip_fd) != $v_size)
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- First try : look if this is an archive with no commentaries (most of the time)
// in this case the end of central dir is at 22 bytes of the file end
$v_found = 0;
if ($v_size > 26) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Look for central dir with no comment');
@fseek($this->zip_fd, $v_size-22);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after min central position : \''.ftell($this->zip_fd).'\'');
if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Read for bytes
$v_binary_data = @fread($this->zip_fd, 4);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Binary data is : '".sprintf("%08x", $v_binary_data)."'");
$v_data = @unpack('Vid', $v_binary_data);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'");
// ----- Check signature
if ($v_data['id'] == 0x06054b50) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found central dir at the default position.");
$v_found = 1;
}
$v_pos = ftell($this->zip_fd);
}
// ----- Go back to the maximum possible size of the Central Dir End Record
if (!$v_found) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Start extended search of end central dir');
$v_maximum_size = 65557; // 0xFFFF + 22;
if ($v_maximum_size > $v_size)
$v_maximum_size = $v_size;
@fseek($this->zip_fd, $v_size-$v_maximum_size);
if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after max central position : \''.ftell($this->zip_fd).'\'');
// ----- Read byte per byte in order to find the signature
$v_pos = ftell($this->zip_fd);
$v_bytes = 0x00000000;
while ($v_pos < $v_size)
{
// ----- Read a byte
$v_byte = @fread($this->zip_fd, 1);
// ----- Add the byte
$v_bytes = ($v_bytes << 8) | Ord($v_byte);
// ----- Compare the bytes
if ($v_bytes == 0x504b0506)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Found End Central Dir signature at position : \''.ftell($this->zip_fd).'\'');
$v_pos++;
break;
}
$v_pos++;
}
// ----- Look if not found end of central dir
if ($v_pos == $v_size)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to find End of Central Dir Record signature");
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Read the first 18 bytes of the header
$v_binary_data = fread($this->zip_fd, 18);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 18)
{
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Extract the values
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record : '".$v_binary_data."'");
////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record (Hex) : '".bin2hex($v_binary_data)."'");
$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
// ----- Check the global size
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Comment length : ".$v_data['comment_size']);
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The central dir is not at the end of the archive. Some trailing bytes exists after the archive.");
// ----- Removed in release 2.2 see readme file
// The check of the file size is a little too strict.
// Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
// While decrypted, zip has training 0 bytes
if (0) {
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT,
'The central dir is not at the end of the archive.'
.' Some trailing bytes exists after the archive.');
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
}
// ----- Get comment
if ($v_data['comment_size'] != 0)
$p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
else
$p_central_dir['comment'] = '';
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment : \''.$p_central_dir['comment'].'\'');
$p_central_dir['entries'] = $v_data['entries'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries : \''.$p_central_dir['entries'].'\'');
$p_central_dir['disk_entries'] = $v_data['disk_entries'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries for this disk : \''.$p_central_dir['disk_entries'].'\'');
$p_central_dir['offset'] = $v_data['offset'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Offset of Central Dir : \''.$p_central_dir['offset'].'\'');
$p_central_dir['size'] = $v_data['size'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size of Central Dir : \''.$p_central_dir['size'].'\'');
$p_central_dir['disk'] = $v_data['disk'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Disk number : \''.$p_central_dir['disk'].'\'');
$p_central_dir['disk_start'] = $v_data['disk_start'];
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Start disk number : \''.$p_central_dir['disk_start'].'\'');
// TBC
//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
// //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "central_dir[$key] = ".$p_central_dir[$key]);
//}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check.
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function privDirCheck($p_dir, $p_is_dir=false)
{
$v_result = 1;
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDirCheck", "entry='$p_dir', is_dir='".($p_is_dir?"true":"false")."'");
// ----- Remove the final '/'
if (($p_is_dir) && (substr($p_dir, -1)=='/'))
{
$p_dir = substr($p_dir, 0, strlen($p_dir)-1);
}
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Looking for entry '$p_dir'");
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == ""))
{
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, "'$p_dir' is a directory");
return 1;
}
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Parent directory is '$p_parent_dir'");
// ----- Just a check
if ($p_parent_dir != $p_dir)
{
// ----- Look for parent directory
if ($p_parent_dir != "")
{
if (($v_result = $this->privDirCheck($p_parent_dir)) != 1)
{
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
}
// ----- Create the directory
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Create directory '$p_dir'");
if (!@mkdir($p_dir, 0777))
{
// ----- Error log
PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo());
return PclZip::errorCode();
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result, "Directory '$p_dir' created");
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorLog($p_error_code=0, $p_error_string='')
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclError($p_error_code, $p_error_string);
}
else {
$this->error_code = $p_error_code;
$this->error_string = $p_error_string;
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorReset()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclErrorReset();
}
else {
$this->error_code = 0;
$this->error_string = '';
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDecrypt()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDecrypt($p_encryption_header, &$p_buffer, $p_size, $p_crc)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDecrypt', "size=".$p_size."");
$v_result=1;
// ----- To Be Modified ;-)
$v_pwd = "test";
$p_buffer = PclZipUtilZipDecrypt($p_buffer, $p_size, $p_encryption_header,
$p_crc, $v_pwd);
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDisableMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDisableMagicQuotes()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDisableMagicQuotes', "");
$v_result=1;
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote already disabled");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Get and memorize the magic_quote value
$this->magic_quotes_status = @get_magic_quotes_runtime();
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Current magic_quotes_runtime status is '".($this->magic_quotes_status==0?'disable':'enable')."'");
// ----- Disable magic_quotes
if ($this->magic_quotes_status == 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Disable magic_quotes");
@set_magic_quotes_runtime(0);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privSwapBackMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privSwapBackMagicQuotes()
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privSwapBackMagicQuotes', "");
$v_result=1;
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote not modified");
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Swap back magic_quotes
if ($this->magic_quotes_status == 1) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Enable back magic_quotes");
@set_magic_quotes_runtime($this->magic_quotes_status);
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
}
// End of class
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilPathInclusion()
// Description :
// This function indicates if the path $p_path is under the $p_dir tree. Or,
// said in an other way, if the file or sub-dir $p_path is inside the dir
// $p_dir.
// The function indicates also if the path is exactly the same as the dir.
// This function supports path with duplicated '/' like '//', but does not
// support '.' or '..' statements.
// Parameters :
// Return Values :
// 0 if $p_path is not inside directory $p_dir
// 1 if $p_path is inside directory $p_dir
// 2 if $p_path is exactly the same as $p_dir
// --------------------------------------------------------------------------------
function PclZipUtilPathInclusion($p_dir, $p_path)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathInclusion", "dir='$p_dir', path='$p_path'");
$v_result = 1;
// ----- Look for path beginning by ./
if ( ($p_dir == '.')
|| ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
$p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_dir '".$p_dir."'");
}
if ( ($p_path == '.')
|| ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
$p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1);
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_path '".$p_path."'");
}
// ----- Explode dir and path by directory separator
$v_list_dir = explode("/", $p_dir);
$v_list_dir_size = sizeof($v_list_dir);
$v_list_path = explode("/", $p_path);
$v_list_path_size = sizeof($v_list_path);
// ----- Study directories paths
$i = 0;
$j = 0;
while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Working on dir($i)='".$v_list_dir[$i]."' and path($j)='".$v_list_path[$j]."'");
// ----- Look for empty dir (path reduction)
if ($v_list_dir[$i] == '') {
$i++;
continue;
}
if ($v_list_path[$j] == '') {
$j++;
continue;
}
// ----- Compare the items
if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Items ($i,$j) are different");
$v_result = 0;
}
// ----- Next items
$i++;
$j++;
}
// ----- Look if everything seems to be the same
if ($v_result) {
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Look for tie break");
// ----- Skip all the empty items
while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++;
while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++;
//--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Looking on dir($i)='".($i < $v_list_dir_size?$v_list_dir[$i]:'')."' and path($j)='".($j < $v_list_path_size?$v_list_path[$j]:'')."'");
if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
// ----- There are exactly the same
$v_result = 2;
}
else if ($i < $v_list_dir_size) {
// ----- The path is shorter than the dir
$v_result = 0;
}
}
// ----- Return
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilOptionText()
// Description :
// Translate option value in text. Mainly for debug purpose.
// Parameters :
// $p_option : the option value.
// Return Values :
// The option text value.
// --------------------------------------------------------------------------------
function PclZipUtilOptionText($p_option)
{
//--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilOptionText", "option='".$p_option."'");
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
$v_prefix = substr($v_key, 0, 10);
if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
&& ($v_list[$v_key] == $p_option)) {
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_key);
return $v_key;
}
}
$v_result = 'Unknown';
//--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclZipUtilTranslateWinPath()
// Description :
// Translate windows path by replacing '\' by '/' and optionally removing
// drive letter.
// Parameters :
// $p_path : path to translate.
// $p_remove_disk_letter : true | false
// Return Values :
// The path translated.
// --------------------------------------------------------------------------------
function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
{
if (stristr(php_uname(), 'windows')) {
// ----- Look for potential disk letter
if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
return $p_path;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// PhpConcept Library - Tar Module 1.3
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - August 2001
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
// PclTar is a library that allow you to create a GNU TAR + GNU ZIP archive,
// to add files or directories, to extract all the archive or a part of it.
// So far tests show that the files generated by PclTar are readable by
// gzip tools and WinZip application.
//
// Description :
// See readme.txt (English & Français) and http://www.phpconcept.net
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// ----- Look for double include
if (!defined("PCL_TAR"))
{
define( "PCL_TAR", 1 );
// ----- Configuration variable
// Theses values may be changed by the user of PclTar library
if (!isset($g_pcltar_lib_dir))
$g_pcltar_lib_dir = "lib";
// ----- Error codes
// -1 : Unable to open file in binary write mode
// -2 : Unable to open file in binary read mode
// -3 : Invalid parameters
// -4 : File does not exist
// -5 : Filename is too long (max. 99)
// -6 : Not a valid tar file
// -7 : Invalid extracted file size
// -8 : Unable to create directory
// -9 : Invalid archive extension
// -10 : Invalid archive format
// -11 : Unable to delete file (unlink)
// -12 : Unable to rename file (rename)
// -13 : Invalid header checksum
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------
// ----- Global variables
$g_pcltar_version = "1.3";
// ----- Extract extension type (.php3/.php/...)
$g_pcltar_extension = substr(strrchr(basename($PATH_TRANSLATED), '.'), 1);
// ----- Include other libraries
// This library should be called by each script before the include of PhpZip
// Library in order to limit the potential 'lib' directory path problem.
// NET2FTP
// Do not include the 2 other libraries again, they are already included below
// if (!defined("PCLERROR_LIB"))
// {
// include($g_pcltar_lib_dir."/pclerror.lib.".$g_pcltar_extension);
// }
// if (!defined("PCLTRACE_LIB"))
// {
// include($g_pcltar_lib_dir."/pcltrace.lib.".$g_pcltar_extension);
// }
// --------------------------------------------------------------------------------
// Function : PclTarList()
// Description :
// Gives the list of all the files present in the tar archive $p_tarname.
// The list is the function result, it will be 0 on error.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// 0 on error (Use PclErrorCode() and PclErrorString() for more info)
// or
// An array containing file properties. Each file properties is an array of
// properties.
// The properties (array field names) are :
// filename, size, mode, uid, gid, mtime, typeflag, status
// Exemple : $v_list = PclTarList("my.tar");
// for ($i=0; $i<sizeof($v_list); $i++)
// echo "Filename :'".$v_list[$i][filename]."'<br>";
// --------------------------------------------------------------------------------
function PclTarList($p_tarname, $p_mode="")
{
TrFctStart(__FILE__, __LINE__, "PclTarList", "tar=$p_tarname, mode='$p_mode'");
$v_result=1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode!="tar") && ($p_mode!="tgz")))
{
if (($p_mode = PclTarHandleExtension($p_tarname)) == "")
{
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = PclTarHandleExtract($p_tarname, 0, $p_list, "list", "", $p_mode, "")) != 1)
{
unset($p_list);
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return(0);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarExtract()
// Description :
// Extract all the files present in the archive $p_tarname, in the directory
// $p_path. The relative path of the archived files are keep and become
// relative to $p_path.
// If a file with the same name already exists it will be replaced.
// If the path to the file does not exist, it will be created.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file.
// $p_path : Path where the files will be extracted. The files will use
// their memorized path from $p_path.
// If $p_path is "", files will be extracted in "./".
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_path and $p_remove_path are commulative.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// Same as PclTarList()
// --------------------------------------------------------------------------------
function PclTarExtract($p_tarname, $p_path="./", $p_remove_path="", $p_mode="")
{
TrFctStart(__FILE__, __LINE__, "PclTarExtract", "tar='$p_tarname', path='$p_path', remove_path='$p_remove_path', mode='$p_mode'");
$v_result=1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode!="tar") && ($p_mode!="tgz")))
{
if (($p_mode = PclTarHandleExtension($p_tarname)) == "")
{
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtract($p_tarname, 0, $p_list, "complete", $p_path, $v_tar_mode, $p_remove_path)) != 1)
{
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return(0);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarExtractList()
// Description :
// Extract the files present in the archive $p_tarname and specified in
// $p_filelist, in the directory
// $p_path. The relative path of the archived files are keep and become
// relative to $p_path.
// If a directory is spécified in the list, all the files from this directory
// will be extracted.
// If a file with the same name already exists it will be replaced.
// If the path to the file does not exist, it will be created.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_path : Path where the files will be extracted. The files will use
// their memorized path from $p_path.
// If $p_path is "", files will be extracted in "./".
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_path and $p_remove_path are commulative.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// Same as PclTarList()
// --------------------------------------------------------------------------------
function PclTarExtractList($p_tarname, $p_filelist, $p_path="./", $p_remove_path="", $p_mode="")
{
TrFctStart(__FILE__, __LINE__, "PclTarExtractList", "tar=$p_tarname, list, path=$p_path, remove_path='$p_remove_path', mode='$p_mode'");
$v_result=1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode!="tar") && ($p_mode!="tgz")))
{
if (($p_mode = PclTarHandleExtension($p_tarname)) == "")
{
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist))
{
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtract($p_tarname, $p_filelist, $p_list, "partial", $p_path, $v_tar_mode, $p_remove_path)) != 1)
{
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return(0);
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist))
{
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtract($p_tarname, $v_list, $p_list, "partial", $p_path, $v_tar_mode, $p_remove_path)) != 1)
{
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return(0);
}
}
// ----- Invalid variable
else
{
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarExtractIndex()
// Description :
// Extract the files present in the archive $p_tarname and specified at
// the indexes in $p_index, in the directory
// $p_path. The relative path of the archived files are keep and become
// relative to $p_path.
// If a directory is specified in the list, the directory only is created. All
// the file stored in this archive for this directory
// are not extracted.
// If a file with the same name already exists it will be replaced.
// If the path to the file does not exist, it will be created.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_index : A single index (integer) or a string of indexes of files to
// extract. The form of the string is "0,4-6,8-12" with only numbers
// and '-' for range or ',' to separate ranges. No spaces or ';'
// are allowed.
// $p_path : Path where the files will be extracted. The files will use
// their memorized path from $p_path.
// If $p_path is "", files will be extracted in "./".
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_path and $p_remove_path are commulative.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// Same as PclTarList()
// --------------------------------------------------------------------------------
function PclTarExtractIndex($p_tarname, $p_index, $p_path="./", $p_remove_path="", $p_mode="")
{
TrFctStart(__FILE__, __LINE__, "PclTarExtractIndex", "tar=$p_tarname, index='$p_index', path=$p_path, remove_path='$p_remove_path', mode='$p_mode'");
$v_result=1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode!="tar") && ($p_mode!="tgz")))
{
if (($p_mode = PclTarHandleExtension($p_tarname)) == "")
{
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Look if the $p_index is really an integer
if (is_integer($p_index))
{
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtractByIndexList($p_tarname, "$p_index", $p_list, $p_path, $p_remove_path, $v_tar_mode)) != 1)
{
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return(0);
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_index))
{
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtractByIndexList($p_tarname, $p_index, $p_list, $p_path, $p_remove_path, $v_tar_mode)) != 1)
{
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return(0);
}
}
// ----- Invalid variable
else
{
// ----- Error log
PclErrorLog(-3, "Invalid variable type $p_index");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtract()
// Description :
// Parameters :
// $p_tarname : Filename of the tar (or tgz) archive
// $p_file_list : An array which contains the list of files to extract, this
// array may be empty when $p_mode is 'complete'
// $p_list_detail : An array where will be placed the properties of each extracted/listed file
// $p_mode : 'complete' will extract all files from the archive,
// 'partial' will look for files in $p_file_list
// 'list' will only list the files from the archive without any extract
// $p_path : Path to add while writing the extracted files
// $p_tar_mode : 'tar' for GNU TAR archive, 'tgz' for compressed archive
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtract($p_tarname, $p_file_list, &$p_list_detail, $p_mode, $p_path, $p_tar_mode, $p_remove_path)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtract", "archive='$p_tarname', list, mode=$p_mode, path=$p_path, tar_mode=$p_tar_mode, remove_path='$p_remove_path'");
$v_result=1;
$v_nb = 0;
$v_extract_all = TRUE;
$v_listing = FALSE;
// ----- Check the path
if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../")))
$p_path = "./".$p_path;
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Study the mode
switch ($p_mode) {
case "complete" :
// ----- Flag extract of all files
$v_extract_all = TRUE;
$v_listing = FALSE;
break;
case "partial" :
// ----- Flag extract of specific files
$v_extract_all = FALSE;
$v_listing = FALSE;
break;
case "list" :
// ----- Flag list of all files
$v_extract_all = FALSE;
$v_listing = TRUE;
break;
default :
// ----- Error log
PclErrorLog(-3, "Invalid extract mode ($p_mode)");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open the tar file
if ($p_tar_mode == "tar")
{
TrFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
$v_tar = fopen($p_tarname, "rb");
}
else
{
TrFctMessage(__FILE__, __LINE__, 3, "Open file in gzip binary read mode");
$v_tar = @gzopen($p_tarname, "rb");
}
// ----- Check that the archive is open
if ($v_tar == 0)
{
// ----- Error log
PclErrorLog(-2, "Unable to open archive '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Read the blocks
While (!($v_end_of_file = ($p_tar_mode == "tar"?feof($v_tar):gzeof($v_tar))))
{
TrFctMessage(__FILE__, __LINE__, 3, "Looking for next header ...");
// ----- Clear cache of file infos
clearstatcache();
// ----- Reset extract tag
$v_extract_file = FALSE;
$v_extraction_stopped = 0;
// ----- Read the 512 bytes header
if ($p_tar_mode == "tar")
$v_binary_data = fread($v_tar, 512);
else
$v_binary_data = gzread($v_tar, 512);
// ----- Read the header properties
if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1)
{
// ----- Close the archive file
if ($p_tar_mode == "tar")
fclose($v_tar);
else
gzclose($v_tar);
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for empty blocks to skip
if ($v_header[filename] == "")
{
TrFctMessage(__FILE__, __LINE__, 2, "Empty block found. End of archive ?");
continue;
}
TrFctMessage(__FILE__, __LINE__, 2, "Found file '$v_header[filename]', size '$v_header[size]'");
// ----- Look for partial extract
if ((!$v_extract_all) && (is_array($p_file_list)))
{
TrFctMessage(__FILE__, __LINE__, 2, "Look if the file '$v_header[filename]' need to be extracted");
// ----- By default no unzip if the file is not found
$v_extract_file = FALSE;
// ----- Look into the file list
for ($i=0; $i<sizeof($p_file_list); $i++)
{
TrFctMessage(__FILE__, __LINE__, 2, "Compare archived file '$v_header[filename]' from asked list file '".$p_file_list[$i]."'");
// ----- Look if it is a directory
if (substr($p_file_list[$i], -1) == "/")
{
TrFctMessage(__FILE__, __LINE__, 3, "Compare file '$v_header[filename]' with directory '$p_file_list[$i]'");
// ----- Look if the directory is in the filename path
if ((strlen($v_header[filename]) > strlen($p_file_list[$i])) && (substr($v_header[filename], 0, strlen($p_file_list[$i])) == $p_file_list[$i]))
{
// ----- The file is in the directory, so extract it
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' is in directory '$p_file_list[$i]' : extract it");
$v_extract_file = TRUE;
// ----- End of loop
break;
}
}
// ----- It is a file, so compare the file names
else if ($p_file_list[$i] == $v_header[filename])
{
// ----- File found
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' should be extracted");
$v_extract_file = TRUE;
// ----- End of loop
break;
}
}
// ----- Trace
if (!$v_extract_file)
{
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' should not be extracted");
}
}
else
{
// ----- All files need to be extracted
$v_extract_file = TRUE;
}
// ----- Look if this file need to be extracted
if (($v_extract_file) && (!$v_listing))
{
// ----- Look for path to remove
if (($p_remove_path != "")
&& (substr($v_header[filename], 0, $p_remove_path_size) == $p_remove_path))
{
TrFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '$v_header[filename]'");
// ----- Remove the path
$v_header[filename] = substr($v_header[filename], $p_remove_path_size);
TrFctMessage(__FILE__, __LINE__, 3, "Reslting file is '$v_header[filename]'");
}
// ----- Add the path to the file
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
TrFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'");
$p_path = substr($p_path, 0, strlen($p_path)-1);
TrFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]");
}
// ----- Add the path
if (substr($v_header[filename], 0, 1) == "/")
$v_header[filename] = $p_path.$v_header[filename];
else
$v_header[filename] = $p_path."/".$v_header[filename];
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '$v_header[filename]', size '$v_header[size]'");
// ----- Check that the file does not exists
if (file_exists($v_header[filename]))
{
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' already exists");
// ----- Look if file is a directory
if (is_dir($v_header[filename]))
{
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is a directory");
// ----- Change the file status
$v_header[status] = "already_a_directory";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
// ----- Look if file is write protected
else if (!is_writeable($v_header[filename]))
{
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is write protected");
// ----- Change the file status
$v_header[status] = "write_protected";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
// ----- Look if the extracted file is older
else if (filemtime($v_header[filename]) > $v_header[mtime])
{
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is newer (".date("l dS of F Y h:i:s A", filemtime($v_header[filename])).") than the extracted file (".date("l dS of F Y h:i:s A", $v_header[mtime]).")");
// ----- Change the file status
$v_header[status] = "newer_exist";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
// ----- Check the directory availability and create it if necessary
else
{
if ($v_header[typeflag]=="5")
$v_dir_to_check = $v_header[filename];
else if (!strstr($v_header[filename], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($v_header[filename]);
if (($v_result = PclTarHandlerDirCheck($v_dir_to_check)) != 1)
{
TrFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '$v_header[filename]'");
// ----- Change the file status
$v_header[status] = "path_creation_fail";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
// ----- Do the extraction
if (($v_extract_file) && ($v_header[typeflag]!="5"))
{
// ----- Open the destination file in write mode
if (($v_dest_file = @fopen($v_header[filename], "wb")) == 0)
{
TrFctMessage(__FILE__, __LINE__, 2, "Error while opening '$v_header[filename]' in write binary mode");
// ----- Change the file status
$v_header[status] = "write_error";
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar")
fseek($v_tar, ftell($v_tar)+(ceil(($v_header[size]/512))*512));
else
gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
}
else
{
TrFctMessage(__FILE__, __LINE__, 2, "Start extraction of '$v_header[filename]'");
// ----- Read data
$n = floor($v_header[size]/512);
for ($i=0; $i<$n; $i++)
{
TrFctMessage(__FILE__, __LINE__, 3, "Read complete 512 bytes block number ".($i+1));
if ($p_tar_mode == "tar")
$v_content = fread($v_tar, 512);
else
$v_content = gzread($v_tar, 512);
fwrite($v_dest_file, $v_content, 512);
}
if (($v_header[size] % 512) != 0)
{
TrFctMessage(__FILE__, __LINE__, 3, "Read last ".($v_header[size] % 512)." bytes in a 512 block");
if ($p_tar_mode == "tar")
$v_content = fread($v_tar, 512);
else
$v_content = gzread($v_tar, 512);
fwrite($v_dest_file, $v_content, ($v_header[size] % 512));
}
// ----- Close the destination file
fclose($v_dest_file);
// ----- Change the file mode, mtime
touch($v_header[filename], $v_header[mtime]);
//chmod($v_header[filename], DecOct($v_header[mode]));
}
// ----- Check the file size
clearstatcache();
if (filesize($v_header[filename]) != $v_header[size])
{
// ----- Close the archive file
if ($p_tar_mode == "tar")
fclose($v_tar);
else
gzclose($v_tar);
// ----- Error log
PclErrorLog(-7, "Extracted file '$v_header[filename]' does not have the correct file size '".filesize($v_filename)."' ('$v_header[size]' expected). Archive may be corrupted.");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
else
{
TrFctMessage(__FILE__, __LINE__, 2, "Extraction of file '$v_header[filename]' skipped.");
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar")
fseek($v_tar, ftell($v_tar)+(ceil(($v_header[size]/512))*512));
else
gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
}
}
// ----- Look for file that is not to be unzipped
else
{
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Jump file '$v_header[filename]'");
TrFctMessage(__FILE__, __LINE__, 4, "Position avant jump [".($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))."]");
// ----- Jump to next file
if ($p_tar_mode == "tar")
fseek($v_tar, ($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))+(ceil(($v_header[size]/512))*512));
else
gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
TrFctMessage(__FILE__, __LINE__, 4, "Position après jump [".($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))."]");
}
if ($p_tar_mode == "tar")
$v_end_of_file = feof($v_tar);
else
$v_end_of_file = gzeof($v_tar);
// ----- File name and properties are logged if listing mode or file is extracted
if ($v_listing || $v_extract_file || $v_extraction_stopped)
{
TrFctMessage(__FILE__, __LINE__, 2, "Memorize info about file '$v_header[filename]'");
// ----- Log extracted files
if (($v_file_dir = dirname($v_header[filename])) == $v_header[filename])
$v_file_dir = "";
if ((substr($v_header[filename], 0, 1) == "/") && ($v_file_dir == ""))
$v_file_dir = "/";
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
// ----- Increment
$v_nb++;
}
}
// ----- Close the tarfile
if ($p_tar_mode == "tar")
fclose($v_tar);
else
gzclose($v_tar);
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtractByIndexList()
// Description :
// Extract the files which are at the indexes specified. If the 'file' at the
// index is a directory, the directory only is created, not all the files stored
// for that directory.
// Parameters :
// $p_index_string : String of indexes of files to extract. The form of the
// string is "0,4-6,8-12" with only numbers and '-' for
// for range, and ',' to separate ranges. No spaces or ';'
// are allowed.
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtractByIndexList($p_tarname, $p_index_string, &$p_list_detail, $p_path, $p_remove_path, $p_tar_mode)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtractByIndexList", "archive='$p_tarname', index_string='$p_index_string', list, path=$p_path, remove_path='$p_remove_path', tar_mode=$p_tar_mode");
$v_result=1;
$v_nb = 0;
// ----- TBC : I should check the string by a regexp
// ----- Check the path
if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 0, 2) != "./")))
$p_path = "./".$p_path;
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the tar file
if ($p_tar_mode == "tar")
{
TrFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
$v_tar = @fopen($p_tarname, "rb");
}
else
{
TrFctMessage(__FILE__, __LINE__, 3, "Open file in gzip binary read mode");
$v_tar = @gzopen($p_tarname, "rb");
}
// ----- Check that the archive is open
if ($v_tar == 0)
{
// ----- Error log
PclErrorLog(-2, "Unable to open archive '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Manipulate the index list
$v_list = explode(",", $p_index_string);
sort($v_list);
// ----- Loop on the index list
$v_index=0;
for ($i=0; ($i<sizeof($v_list)) && ($v_result); $i++)
{
TrFctMessage(__FILE__, __LINE__, 3, "Looking for index part '$v_list[$i]'");
// ----- Extract range
$v_index_list = explode("-", $v_list[$i]);
$v_size_index_list = sizeof($v_index_list);
if ($v_size_index_list == 1)
{
TrFctMessage(__FILE__, __LINE__, 3, "Only one index '$v_index_list[0]'");
// ----- Do the extraction
$v_result = PclTarHandleExtractByIndex($v_tar, $v_index, $v_index_list[0], $v_index_list[0], $p_list_detail, $p_path, $p_remove_path, $p_tar_mode);
}
else if ($v_size_index_list == 2)
{
TrFctMessage(__FILE__, __LINE__, 3, "Two indexes '$v_index_list[0]' and '$v_index_list[1]'");
// ----- Do the extraction
$v_result = PclTarHandleExtractByIndex($v_tar, $v_index, $v_index_list[0], $v_index_list[1], $p_list_detail, $p_path, $p_remove_path, $p_tar_mode);
}
}
// ----- Close the tarfile
if ($p_tar_mode == "tar")
fclose($v_tar);
else
gzclose($v_tar);
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtractByIndex()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtractByIndex($p_tar, &$p_index_current, $p_index_start, $p_index_stop, &$p_list_detail, $p_path, $p_remove_path, $p_tar_mode)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtractByIndex", "archive_descr='$p_tar', index_current=$p_index_current, index_start='$p_index_start', index_stop='$p_index_stop', list, path=$p_path, remove_path='$p_remove_path', tar_mode=$p_tar_mode");
$v_result=1;
$v_nb = 0;
// TBC : I should replace all $v_tar by $p_tar in this function ....
$v_tar = $p_tar;
// ----- Look the number of elements already in $p_list_detail
$v_nb = sizeof($p_list_detail);
// ----- Read the blocks
While (!($v_end_of_file = ($p_tar_mode == "tar"?feof($v_tar):gzeof($v_tar))))
{
TrFctMessage(__FILE__, __LINE__, 3, "Looking for next file ...");
TrFctMessage(__FILE__, __LINE__, 3, "Index current=$p_index_current, range=[$p_index_start, $p_index_stop])");
if ($p_index_current > $p_index_stop)
{
TrFctMessage(__FILE__, __LINE__, 2, "Stop extraction, past stop index");
break;
}
// ----- Clear cache of file infos
clearstatcache();
// ----- Reset extract tag
$v_extract_file = FALSE;
$v_extraction_stopped = 0;
// ----- Read the 512 bytes header
if ($p_tar_mode == "tar")
$v_binary_data = fread($v_tar, 512);
else
$v_binary_data = gzread($v_tar, 512);
// ----- Read the header properties
if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1)
{
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for empty blocks to skip
if ($v_header[filename] == "")
{
TrFctMessage(__FILE__, __LINE__, 2, "Empty block found. End of archive ?");
continue;
}
TrFctMessage(__FILE__, __LINE__, 2, "Found file '$v_header[filename]', size '$v_header[size]'");
// ----- Look if file is in the range to be extracted
if (($p_index_current >= $p_index_start) && ($p_index_current <= $p_index_stop))
{
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' is in the range to be extracted");
$v_extract_file = TRUE;
}
else
{
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' is out of the range");
$v_extract_file = FALSE;
}
// ----- Look if this file need to be extracted
if ($v_extract_file)
{
if (($v_result = PclTarHandleExtractFile($v_tar, $v_header, $p_path, $p_remove_path, $p_tar_mode)) != 1)
{
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
// ----- Look for file that is not to be extracted
else
{
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Jump file '$v_header[filename]'");
TrFctMessage(__FILE__, __LINE__, 4, "Position avant jump [".($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))."]");
// ----- Jump to next file
if ($p_tar_mode == "tar")
fseek($v_tar, ($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))+(ceil(($v_header[size]/512))*512));
else
gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
TrFctMessage(__FILE__, __LINE__, 4, "Position après jump [".($p_tar_mode=="tar"?ftell($v_tar):gztell($v_tar))."]");
}
if ($p_tar_mode == "tar")
$v_end_of_file = feof($v_tar);
else
$v_end_of_file = gzeof($v_tar);
// ----- File name and properties are logged if listing mode or file is extracted
if ($v_extract_file)
{
TrFctMessage(__FILE__, __LINE__, 2, "Memorize info about file '$v_header[filename]'");
// ----- Log extracted files
if (($v_file_dir = dirname($v_header[filename])) == $v_header[filename])
$v_file_dir = "";
if ((substr($v_header[filename], 0, 1) == "/") && ($v_file_dir == ""))
$v_file_dir = "/";
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
// ----- Increment
$v_nb++;
}
// ----- Increment the current file index
$p_index_current++;
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtractFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtractFile($p_tar, &$v_header, $p_path, $p_remove_path, $p_tar_mode)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtractFile", "archive_descr='$p_tar', path=$p_path, remove_path='$p_remove_path', tar_mode=$p_tar_mode");
$v_result=1;
// TBC : I should replace all $v_tar by $p_tar in this function ....
$v_tar = $p_tar;
$v_extract_file = 1;
$p_remove_path_size = strlen($p_remove_path);
// ----- Look for path to remove
if (($p_remove_path != "")
&& (substr($v_header[filename], 0, $p_remove_path_size) == $p_remove_path))
{
TrFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '$v_header[filename]'");
// ----- Remove the path
$v_header[filename] = substr($v_header[filename], $p_remove_path_size);
TrFctMessage(__FILE__, __LINE__, 3, "Resulting file is '$v_header[filename]'");
}
// ----- Add the path to the file
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
TrFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'");
$p_path = substr($p_path, 0, strlen($p_path)-1);
TrFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]");
}
// ----- Add the path
if (substr($v_header[filename], 0, 1) == "/")
$v_header[filename] = $p_path.$v_header[filename];
else
$v_header[filename] = $p_path."/".$v_header[filename];
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '$v_header[filename]', size '$v_header[size]'");
// ----- Check that the file does not exists
if (file_exists($v_header[filename]))
{
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' already exists");
// ----- Look if file is a directory
if (is_dir($v_header[filename]))
{
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is a directory");
// ----- Change the file status
$v_header[status] = "already_a_directory";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
// ----- Look if file is write protected
else if (!is_writeable($v_header[filename]))
if (!is_writeable($v_header[filename]))
{
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is write protected");
// ----- Change the file status
$v_header[status] = "write_protected";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
// ----- Look if the extracted file is older
else if (filemtime($v_header[filename]) > $v_header[mtime])
{
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is newer (".date("l dS of F Y h:i:s A", filemtime($v_header[filename])).") than the extracted file (".date("l dS of F Y h:i:s A", $v_header[mtime]).")");
// ----- Change the file status
$v_header[status] = "newer_exist";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
// ----- Check the directory availability and create it if necessary
else
{
if ($v_header[typeflag]=="5")
$v_dir_to_check = $v_header[filename];
else if (!strstr($v_header[filename], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($v_header[filename]);
if (($v_result = PclTarHandlerDirCheck($v_dir_to_check)) != 1)
{
TrFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '$v_header[filename]'");
// ----- Change the file status
$v_header[status] = "path_creation_fail";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
// ----- Do the real bytes extraction (if not a directory)
if (($v_extract_file) && ($v_header[typeflag]!="5"))
{
// ----- Open the destination file in write mode
if (($v_dest_file = @fopen($v_header[filename], "wb")) == 0)
{
TrFctMessage(__FILE__, __LINE__, 2, "Error while opening '$v_header[filename]' in write binary mode");
// ----- Change the file status
$v_header[status] = "write_error";
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar")
fseek($v_tar, ftell($v_tar)+(ceil(($v_header[size]/512))*512));
else
gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
}
else
{
TrFctMessage(__FILE__, __LINE__, 2, "Start extraction of '$v_header[filename]'");
// ----- Read data
$n = floor($v_header[size]/512);
for ($i=0; $i<$n; $i++)
{
TrFctMessage(__FILE__, __LINE__, 3, "Read complete 512 bytes block number ".($i+1));
if ($p_tar_mode == "tar")
$v_content = fread($v_tar, 512);
else
$v_content = gzread($v_tar, 512);
fwrite($v_dest_file, $v_content, 512);
}
if (($v_header[size] % 512) != 0)
{
TrFctMessage(__FILE__, __LINE__, 3, "Read last ".($v_header[size] % 512)." bytes in a 512 block");
if ($p_tar_mode == "tar")
$v_content = fread($v_tar, 512);
else
$v_content = gzread($v_tar, 512);
fwrite($v_dest_file, $v_content, ($v_header[size] % 512));
}
// ----- Close the destination file
fclose($v_dest_file);
// ----- Change the file mode, mtime
touch($v_header[filename], $v_header[mtime]);
//chmod($v_header[filename], DecOct($v_header[mode]));
}
// ----- Check the file size
clearstatcache();
if (filesize($v_header[filename]) != $v_header[size])
{
// ----- Error log
PclErrorLog(-7, "Extracted file '$v_header[filename]' does not have the correct file size '".filesize($v_filename)."' ('$v_header[size]' expected). Archive may be corrupted.");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extraction done");
}
else
{
TrFctMessage(__FILE__, __LINE__, 2, "Extraction of file '$v_header[filename]' skipped.");
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar")
fseek($v_tar, ftell($v_tar)+(ceil(($v_header[size]/512))*512));
else
gzseek($v_tar, gztell($v_tar)+(ceil(($v_header[size]/512))*512));
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleReadHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleReadHeader($v_binary_data, &$v_header)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandleReadHeader", "");
$v_result=1;
// ----- Read the 512 bytes header
/*
if ($p_tar_mode == "tar")
$v_binary_data = fread($p_tar, 512);
else
$v_binary_data = gzread($p_tar, 512);
*/
// ----- Look for no more block
if (strlen($v_binary_data)==0)
{
$v_header[filename] = "";
$v_header[status] = "empty";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result, "End of archive found");
return $v_result;
}
// ----- Look for invalid block size
if (strlen($v_binary_data) != 512)
{
$v_header[filename] = "";
$v_header[status] = "invalid_header";
TrFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data));
// ----- Error log
PclErrorLog(-10, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i=0; $i<148; $i++)
{
$v_checksum+=ord(substr($v_binary_data,$i,1));
}
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i=148; $i<156; $i++)
{
$v_checksum += ord(' ');
}
// ..... Last part of the header
for ($i=156; $i<512; $i++)
{
$v_checksum+=ord(substr($v_binary_data,$i,1));
}
TrFctMessage(__FILE__, __LINE__, 3, "Calculated checksum : $v_checksum");
// ----- Extract the values
TrFctMessage(__FILE__, __LINE__, 2, "Header : '$v_binary_data'");
$v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor", $v_binary_data);
// ----- Extract the checksum for check
$v_header[checksum] = OctDec(trim($v_data[checksum]));
TrFctMessage(__FILE__, __LINE__, 3, "File checksum : $v_header[checksum]");
if ($v_header[checksum] != $v_checksum)
{
TrFctMessage(__FILE__, __LINE__, 2, "File checksum is invalid : $v_checksum calculated, $v_header[checksum] expected");
$v_header[filename] = "";
$v_header[status] = "invalid_header";
// ----- Look for last block (empty block)
if (($v_checksum == 256) && ($v_header[checksum] == 0))
{
$v_header[status] = "empty";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result, "End of archive found");
return $v_result;
}
// ----- Error log
PclErrorLog(-13, "Invalid checksum : $v_checksum calculated, $v_header[checksum] expected");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
TrFctMessage(__FILE__, __LINE__, 2, "File checksum is valid ($v_checksum)");
// ----- Extract the properties
$v_header[filename] = trim($v_data[filename]);
TrFctMessage(__FILE__, __LINE__, 2, "Name : '$v_header[filename]'");
$v_header[mode] = OctDec(trim($v_data[mode]));
TrFctMessage(__FILE__, __LINE__, 2, "Mode : '".DecOct($v_header[mode])."'");
$v_header[uid] = OctDec(trim($v_data[uid]));
TrFctMessage(__FILE__, __LINE__, 2, "Uid : '$v_header[uid]'");
$v_header[gid] = OctDec(trim($v_data[gid]));
TrFctMessage(__FILE__, __LINE__, 2, "Gid : '$v_header[gid]'");
$v_header[size] = OctDec(trim($v_data[size]));
TrFctMessage(__FILE__, __LINE__, 2, "Size : '$v_header[size]'");
$v_header[mtime] = OctDec(trim($v_data[mtime]));
TrFctMessage(__FILE__, __LINE__, 2, "Date : ".date("l dS of F Y h:i:s A", $v_header[mtime]));
if (($v_header[typeflag] = $v_data[typeflag]) == "5")
{
$v_header[size] = 0;
TrFctMessage(__FILE__, __LINE__, 2, "Size (folder) : '$v_header[size]'");
}
TrFctMessage(__FILE__, __LINE__, 2, "File typeflag : $v_header[typeflag]");
/* ----- All these fields are removed form the header because they do not carry interesting info
$v_header[link] = trim($v_data[link]);
TrFctMessage(__FILE__, __LINE__, 2, "Linkname : $v_header[linkname]");
$v_header[magic] = trim($v_data[magic]);
TrFctMessage(__FILE__, __LINE__, 2, "Magic : $v_header[magic]");
$v_header[version] = trim($v_data[version]);
TrFctMessage(__FILE__, __LINE__, 2, "Version : $v_header[version]");
$v_header[uname] = trim($v_data[uname]);
TrFctMessage(__FILE__, __LINE__, 2, "Uname : $v_header[uname]");
$v_header[gname] = trim($v_data[gname]);
TrFctMessage(__FILE__, __LINE__, 2, "Gname : $v_header[gname]");
$v_header[devmajor] = trim($v_data[devmajor]);
TrFctMessage(__FILE__, __LINE__, 2, "Devmajor : $v_header[devmajor]");
$v_header[devminor] = trim($v_data[devminor]);
TrFctMessage(__FILE__, __LINE__, 2, "Devminor : $v_header[devminor]");
*/
// ----- Set the status field
$v_header[status] = "ok";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandlerDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check (without / at the end).
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function PclTarHandlerDirCheck($p_dir)
{
$v_result = 1;
TrFctStart(__FILE__, __LINE__, "PclTarHandlerDirCheck", "$p_dir");
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == ""))
{
TrFctEnd(__FILE__, __LINE__, "'$p_dir' is a directory");
return 1;
}
// ----- Look for file alone
/*
if (!strstr("$p_dir", "/"))
{
TrFctEnd(__FILE__, __LINE__, "'$p_dir' is a file with no directory");
return 1;
}
*/
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
TrFctMessage(__FILE__, __LINE__, 3, "Parent directory is '$p_parent_dir'");
// ----- Just a check
if ($p_parent_dir != $p_dir)
{
// ----- Look for parent directory
if ($p_parent_dir != "")
{
if (($v_result = PclTarHandlerDirCheck($p_parent_dir)) != 1)
{
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
}
// ----- Create the directory
TrFctMessage(__FILE__, __LINE__, 3, "Create directory '$p_dir'");
if (!@mkdir($p_dir, 0777))
{
// ----- Error log
PclErrorLog(-8, "Unable to create directory '$p_dir'");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result, "Directory '$p_dir' created");
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtension()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtension($p_tarname)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtension", "tar=$p_tarname");
// ----- Look for file extension
if ((substr($p_tarname, -7) == ".tar.gz") || (substr($p_tarname, -4) == ".tgz"))
{
TrFctMessage(__FILE__, __LINE__, 2, "Archive is a gzip tar");
$v_tar_mode = "tgz";
}
else if (substr($p_tarname, -4) == ".tar")
{
TrFctMessage(__FILE__, __LINE__, 2, "Archive is a tar");
$v_tar_mode = "tar";
}
else
{
// ----- Error log
PclErrorLog(-9, "Invalid archive extension");
TrFctMessage(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
$v_tar_mode = "";
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_tar_mode);
return $v_tar_mode;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandlePathReduction()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandlePathReduction($p_dir)
{
TrFctStart(__FILE__, __LINE__, "PclTarHandlePathReduction", "dir='$p_dir'");
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "")
{
// ----- Explode path by directory names
$v_list = explode("/", $p_dir);
// ----- Study directories from last to first
for ($i=sizeof($v_list)-1; $i>=0; $i--)
{
// ----- Look for current path
if ($v_list[$i] == ".")
{
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..")
{
// ----- Ignore it and ignore the $i-1
$i--;
}
else if (($v_list[$i] == "") && ($i!=(sizeof($v_list)-1)) && ($i!=0))
{
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
}
else
{
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
}
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// ----- End of double include look
}
// --------------------------------------------------------------------------------
// PhpConcept Library (PCL) Error 1.0
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - Mars 2001
// http://www.phpconcept.net & http://phpconcept.free.fr
// --------------------------------------------------------------------------------
// Français :
// La description de l'usage de la librairie PCL Error 1.0 n'est pas encore
// disponible. Celle-ci n'est pour le moment distribuée qu'avec les
// développements applicatifs de PhpConcept.
// Une version indépendante sera bientot disponible sur http://www.phpconcept.net
//
// English :
// The PCL Error 1.0 library description is not available yet. This library is
// released only with PhpConcept application and libraries.
// An independant release will be soon available on http://www.phpconcept.net
//
// --------------------------------------------------------------------------------
//
// * Avertissement :
//
// Cette librairie a été créée de façon non professionnelle.
// Son usage est au risque et péril de celui qui l'utilise, en aucun cas l'auteur
// de ce code ne pourra être tenu pour responsable des éventuels dégats qu'il pourrait
// engendrer.
// Il est entendu cependant que l'auteur a réalisé ce code par plaisir et n'y a
// caché aucun virus, ni malveillance.
// Cette libairie est distribuée sous la license GNU/GPL (http://www.gnu.org)
//
// * Auteur :
//
// Ce code a été écrit par Vincent Blavet (vincent@blavet.net) sur son temps
// de loisir.
//
// --------------------------------------------------------------------------------
// ----- Look for double include
if (!defined("PCLERROR_LIB"))
{
define( "PCLERROR_LIB", 1 );
// ----- Version
$g_pcl_error_version = "1.0";
// ----- Internal variables
// These values must only be change by PclError library functions
$g_pcl_error_string = "";
$g_pcl_error_code = 1;
// --------------------------------------------------------------------------------
// Function : PclErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorLog($p_error_code=0, $p_error_string="")
{
global $g_pcl_error_string;
global $g_pcl_error_code;
$g_pcl_error_code = $p_error_code;
$g_pcl_error_string = $p_error_string;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorFatal()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorFatal($p_file, $p_line, $p_error_string="")
{
global $g_pcl_error_string;
global $g_pcl_error_code;
$v_message = "<html><body>";
$v_message .= "<p align=center><font color=red bgcolor=white><b>PclError Library has detected a fatal error on file '$p_file', line $p_line</b></font></p>";
$v_message .= "<p align=center><font color=red bgcolor=white><b>$p_error_string</b></font></p>";
$v_message .= "</body></html>";
die($v_message);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorReset()
{
global $g_pcl_error_string;
global $g_pcl_error_code;
$g_pcl_error_code = 1;
$g_pcl_error_string = "";
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorCode()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorCode()
{
global $g_pcl_error_string;
global $g_pcl_error_code;
return($g_pcl_error_code);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorString()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorString()
{
global $g_pcl_error_string;
global $g_pcl_error_code;
return($g_pcl_error_string." [code $g_pcl_error_code]");
}
// --------------------------------------------------------------------------------
// ----- End of double include look
}
// --------------------------------------------------------------------------------
// PhpConcept Library (PCL) Trace 2.0-beta1
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - August 2003
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// The PCL Trace library description is not available yet.
// This library was first released only with PclZip library.
// An independant release will be soon available on http://www.phpconcept.net
//
// --------------------------------------------------------------------------------
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// ----- Version
$g_pcltrace_version = "2.0-beta1";
// ----- Internal variables
// These values must be change by PclTrace library functions
$g_pcl_trace_mode = "memory";
$g_pcl_trace_filename = "trace.txt";
$g_pcl_trace_name = array();
$g_pcl_trace_index = 0;
$g_pcl_trace_level = 0;
$g_pcl_trace_suspend = false;
//$g_pcl_trace_entries = array();
// ----- For compatibility reason
define ('PCLTRACE_LIB', 1);
// --------------------------------------------------------------------------------
// Function : TrOn($p_level, $p_mode, $p_filename)
// Description :
// Parameters :
// $p_level : Trace level
// $p_mode : Mode of trace displaying :
// 'normal' : messages are displayed at function call
// 'memory' : messages are memorized in a table and can be display by
// TrDisplay() function. (default)
// 'log' : messages are writed in the file $p_filename
// --------------------------------------------------------------------------------
function PclTraceOn($p_level=1, $p_mode="memory", $p_filename="trace.txt")
{
TrOn($p_level, $p_mode, $p_filename);
}
function TrOn($p_level=1, $p_mode="memory", $p_filename="trace.txt")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Enable trace mode
$g_pcl_trace_level = $p_level;
// ----- Memorize mode and filename
switch ($p_mode) {
case "normal" :
case "memory" :
case "log" :
$g_pcl_trace_mode = $p_mode;
break;
default :
$g_pcl_trace_mode = "logged";
}
// ----- Memorize filename
$g_pcl_trace_filename = $p_filename;
$g_pcl_trace_suspend = false;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : IsTrOn()
// Description :
// Return value :
// The trace level (0 for disable).
// --------------------------------------------------------------------------------
function PclTraceIsOn()
{
return IsTrOn();
}
function IsTrOn()
{
global $g_pcl_trace_level;
return($g_pcl_trace_level);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrOff()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceOff()
{
TrOff();
}
function TrOff()
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
// ----- Clean
$g_pcl_trace_mode = "memory";
unset($g_pcl_trace_entries);
unset($g_pcl_trace_name);
unset($g_pcl_trace_index);
// ----- Switch off trace
$g_pcl_trace_level = 0;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTraceSuspend()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceSuspend()
{
global $g_pcl_trace_suspend;
$g_pcl_trace_suspend = true;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTraceResume()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceResume()
{
global $g_pcl_trace_suspend;
$g_pcl_trace_suspend = false;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrFctStart()
// Description :
// Just a trace function for debbugging purpose before I use a better tool !!!!
// Start and stop of this function is by $g_pcl_trace_level global variable.
// Parameters :
// $p_level : Level of trace required.
// --------------------------------------------------------------------------------
function PclTraceFctStart($p_file, $p_line, $p_name, $p_param="", $p_message="")
{
TrFctStart($p_file, $p_line, $p_name, $p_param, $p_message);
}
function TrFctStart($p_file, $p_line, $p_name, $p_param="", $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < 1) || ($g_pcl_trace_suspend))
return;
// ----- Add the function name in the list
if (!isset($g_pcl_trace_name))
$g_pcl_trace_name = $p_name;
else
$g_pcl_trace_name .= ",".$p_name;
// ----- Update the function entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = $p_name;
$g_pcl_trace_entries[$i]['param'] = $p_param;
$g_pcl_trace_entries[$i]['message'] = "";
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "1"; // means start of function
// ----- Update the message entry
if ($p_message != "")
{
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "3"; // means message
}
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
// ----- Increment the index
$g_pcl_trace_index++;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrFctEnd()
// Description :
// Just a trace function for debbugging purpose before I use a better tool !!!!
// Start and stop of this function is by $g_pcl_trace_level global variable.
// Parameters :
// $p_level : Level of trace required.
// --------------------------------------------------------------------------------
function PclTraceFctEnd($p_file, $p_line, $p_return=1, $p_message="")
{
TrFctEnd($p_file, $p_line, $p_return, $p_message);
}
function TrFctEnd($p_file, $p_line, $p_return=1, $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < 1) || ($g_pcl_trace_suspend))
return;
// ----- Extract the function name in the list
// ----- Remove the function name in the list
if (!($v_name = strrchr($g_pcl_trace_name, ",")))
{
$v_name = $g_pcl_trace_name;
$g_pcl_trace_name = "";
}
else
{
$g_pcl_trace_name = substr($g_pcl_trace_name, 0, strlen($g_pcl_trace_name)-strlen($v_name));
$v_name = substr($v_name, -strlen($v_name)+1);
}
// ----- Decrement the index
$g_pcl_trace_index--;
// ----- Update the message entry
if ($p_message != "")
{
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "3"; // means message
}
// ----- Update the function entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = $v_name;
$g_pcl_trace_entries[$i]['param'] = $p_return;
$g_pcl_trace_entries[$i]['message'] = "";
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "2"; // means end of function
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrFctMessage()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceFctMessage($p_file, $p_line, $p_level, $p_message="")
{
TrFctMessage($p_file, $p_line, $p_level, $p_message);
}
function TrFctMessage($p_file, $p_line, $p_level, $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < $p_level) || ($g_pcl_trace_suspend))
return;
// ----- Update the entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "3"; // means message of function
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrMessage()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceMessage($p_file, $p_line, $p_level, $p_message="")
{
TrMessage($p_file, $p_line, $p_level, $p_message);
}
function TrMessage($p_file, $p_line, $p_level, $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < $p_level) || ($g_pcl_trace_suspend))
return;
// ----- Update the entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "4"; // means simple message
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTraceAction()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceAction($p_entry)
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
if ($g_pcl_trace_mode == "normal")
{
for ($i=0; $i<$p_entry['index']; $i++)
echo "---";
if ($p_entry['type'] == 1)
echo "<b>".$p_entry['name']."</b>(".$p_entry['param'].") : ".$p_entry['message']." [".$p_entry[file].", ".$p_entry[line]."]<br>";
else if ($p_entry['type'] == 2)
echo "<b>".$p_entry['name']."</b>()=".$p_entry['param']." : ".$p_entry['message']." [".$p_entry[file].", ".$p_entry[line]."]<br>";
else
echo $p_entry['message']." [".$p_entry['file'].", ".$p_entry['line']."]<br>";
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Register global variables and validate user input
// --------------------------------------------------------------------------------
if (isset($_POST["package_url"]) == true) { $package_url = validateGenericInput($_POST["package_url"]); }
if (isset($_POST["ftpserver"]) == true) { $ftpserver = validateGenericInput($_POST["ftpserver"]); }
if (isset($_POST["ftpserverport"]) == true) { $ftpserverport = validateGenericInput($_POST["ftpserverport"]); }
if (isset($_POST["username"]) == true) { $username = validateGenericInput($_POST["username"]); }
if (isset($_POST["password"]) == true) { $password = validateGenericInput($_POST["password"]); }
if (isset($_POST["passivemode"]) == true) { $passivemode = validateGenericInput($_POST["passivemode"]); }
if (isset($_POST["targetdirectory"]) == true) { $targetdirectory = validateDirectory($_POST["targetdirectory"]); }
if (isset($_POST["screen"]) == true) { $screen = validateGenericInput($_POST["screen"]); }
if (isset($_SERVER["SCRIPT_NAME"]) == true) { $php_self = $_SERVER["SCRIPT_NAME"]; }
elseif (isset($_SERVER["PHP_SELF"]) == true) { $php_self = $_SERVER["PHP_SELF"]; }
$tempdir = dirname(__FILE__) . "/net2ftp_temp_33d1o";
// --------------------------------------------------------------------------------
// HTML start
// --------------------------------------------------------------------------------
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en" dir="LTR">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1">
<meta name="keywords" content="net2ftp, web, ftp, based, web-based, xftp, client, PHP, SSL, password, server, free, gnu, gpl, gnu/gpl, net, net to ftp, netftp, connect, user, gui, interface, web2ftp, edit, editor, online, code, php, upload, download, copy, move, delete, zip, tar, unzip, untar, recursive, rename, chmod, syntax, highlighting, host, hosting, ISP, webserver, plan, bandwidth">
<meta name="description" content="net2ftp is a web based FTP client. It is mainly aimed at managing websites using a browser. Edit code, upload/download files, copy/move/delete directories recursively, rename files and directories -- without installing any software.">
<link rel="shortcut icon" href="favicon.ico">
<title>net2ftp - a web based FTP client</title>
<style type="text/css">
.header21 {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 20px;
font-style: normal;
color: #1D64AD;
font-weight: bold;
text-decoration: none;
}
</style>
</head>
<body>
<div class="header21">net2ftp installation script</div><br />
<?php
// --------------------------------------------------------------------------------
// Screen 1
// Select which package to install, and where to install it
// Select which directories to remove
// --------------------------------------------------------------------------------
if ($screen == "" || $screen == "1") {
?>
<form name="ActionForm" action="net2ftp_installer.php?security_code=pysieupfpk31ch1fhygf" method="post">
<input type="hidden" name="screen" value="2">
Package <br />
<select name="package" onchange="document.forms['ActionForm'].package_url.value=document.forms['ActionForm'].package.options[document.forms['ActionForm'].package.selectedIndex].value;">
<option value="" selected="selected"> </option>
<option value="" style="font-weight: bold; text-decoration: underline;">Blogs</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/evocms/b2evolution-1.8.0-2006-07-09.zip">b2evolution 1.8.0</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/nucleuscms/nucleus3.23.zip">Nucleus 3.23 English</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/nucleuscmsde/nucleus3.23_de.zip">Nucleus 3.23 German</option>
<option value="http://wordpress.org/latest.tar.gz">WordPress (latest version)</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Content management</option>
<option value="http://ftp.osuosl.org/pub/drupal/files/projects/drupal-4.6.8.tar.gz">Drupal 4.6.8</option>
<option value="http://ftp.osuosl.org/pub/drupal/files/projects/drupal-4.7.2.tar.gz">Drupal 4.7.2</option>
<option value="http://ez.no/content/download/137355/877522/file/ezpublish-3.8.3-gpl.tar.gz">eZ Publish 3.8.3</option>
<option value="http://www.geeklog.net/filemgmt/visit.php?lid=747">Geeklog</option>
<option value="http://developer.joomla.org/sf/frs/do/downloadFile/projects.joomla/frs.joomla_1_0.1_0_10/frs5790?dl=1">Joomla 1.0.10</option>
<option value="http://mamboxchange.com/frs/download.php/7368/mambov4.5.3h.tar.gz">Mambo 4.5.3h</option>
<option value="http://mamboxchange.com/frs/download.php/7877/MamboV4.5.4.tar.gz">Mambo 4.5.4</option>
<option value="http://mamboxchange.com/frs/download.php/8046/MamboV4.6RC2.tar.gz">Mambo 4.6 RC2</option>
<option value="http://download.moodle.org/stable16/moodle-latest-16.tgz">Moodle 1.6.1 stable</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpwcms/phpwcms_1.2.5-DEV.tgz">phpWCMS 1.2.5</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpwebsite/phpwebsite-0.10.2-full.tar.gz">phpWebSite 0.10.2 full</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpwebsite/phpwebsite-0.10.2-full.tar.gz">phpWebSite 0.10.2 full</option>
<option value="http://noc.postnuke.com/frs/download.php/987/PostNuke-0.762.tar.gz">Post-Nuke 0.762</option>
<option value="http://siteframe.org/files/2/34/siteframe-5.0.2-768.tar.gz">Siteframe 5.0.2</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/typo3/dummy-4.0.tar.gz">TYPO3 4.0 dummy</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/typo3/typo3_src-4.0.tar.gz">TYPO3 4.0 source</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/xoops/xoops-2.0.14.tar.gz">Xoops 2.0.14</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Customer relationship</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/cslive/craftysyntax2.12.9.tar.gz">Crafty Syntax Live Help 2.12.9</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/helpcenterlive/hcl_2-1-2.zip">Help Center Live 2.1.2</option>
<option value="http://www.phpsupporttickets.com/pages/php_support_tickets/dist/free/PHP_S_Tickets_v2.2.tar.gz">PHP Support Tickets</option>
<option value="http://www.support-logic.com/download/index.php?cmd=download&id=22">Support Logic Helpdesk 1.3</option>
<option value="http://www.sheddnet.net/forums/attachment.php?attachmentid=77&d=1146954912">Support Services Manager 1.0.2</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Development</option>
<option value="http://www.net2ftp.com/download/net2ftp_v0.93.zip">net2ftp 0.93 full version</option>
<option value="http://www.net2ftp.com/download/net2ftp_v0.93_light.zip">net2ftp 0.93 light version</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpmyadmin/phpMyAdmin-2.8.2.tar.gz">phpMyAdmin 2.8.2</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Discussion boards</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpbb/phpBB-2.0.21.tar.gz">phpBB 2.0.21</option>
<option value="http://www.punbb.org/download/punbb-1.2.12.tar.gz">punBB 1.2.12</option>
<option value="http://www.simplemachines.org/download/index.php/smf_1-0-7_install.tar.gz">Simple Machines Forum 1.0.7</option>
<option value="" style="font-weight: bold; text-decoration: underline;">E-Commerce</option>
<option value="https://www.cubecart.com/site/helpdesk/index.php?_m=downloads&_a=viewdownload&downloaditemid=44&nav=0,5">CubeCart</option>
<option value="http://www.oscommerce.com/redirect.php/go,28">OS Commerce 2.2 Milestone 2 Update 051113</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/zencart/zen-cart-v1.1.4d.zip">Zen Cart 1.1.4d</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/zencart/zen-cart-1-2-7-d_full-release.zip">Zen Cart 1.2.7d full release</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/zencart/zen-cart-v1.3.0.2-full-fileset.zip">Zen Cart 1.3.0.2 full fileset</option>
<option value="" style="font-weight: bold; text-decoration: underline;">FAQ</option>
<option value="http://www.lethalpenguin.net/design/faqmasterflex.php?download=true">FAQMasterFlex</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Guestbooks</option>
<option value="http://www.danskcinders.com/download/ViPER_Guestbook_X1.1.zip">ViPER Guestbook 1.1</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Hosting billing</option>
<option value="http://www.phpcoin.com/coin_addons/dload.php?id=108">phpCOIN 1.2.3</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Image galleries</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/coppermine/cpg1.4.8.zip">Coppermine Photo Gallery 1.4.8</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/gallery/gallery-2.1.1a-typical.tar.gz">Gallery 2.1.1a (typical)</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/gallery/gallery-2.1.1a-full.tar.gz">Gallery 2.1.1a (full)</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/gallery/gallery-2.1.1a-minimal.tar.gz">Gallery 2.1.1a (mininal)</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/gallery/gallery-2.1.1a-developer.tar.gz">Gallery 2.1.1a (developer)</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Mailing lists</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phplist/phplist-2.10.2.tgz">PHPlist 2.10.2</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Polls and surveys</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpesp/phpESP-1.8.2.tar.gz">phpESP 1.8.2</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpsurveyor/phpsurveyor-1_00.zip">PHPSurveyor 1.0</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Project management</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/dotproject/dotproject-2.0.4.tar.gz">dotProject 2.0.4</option>
<option value="http://www.phprojekt.com/modules.php?op=modload&name=Downloads&file=index&req=getit&lid=3">PHProjekt 5.1</option>
<option value="http://www.tutos.org/download/TUTOS-php-1.2.20050904.tar.gz">Tutos 1.2.20050904</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Webmail</option>
<option value="ftp://ftp.horde.org/pub/horde/horde-3.1.2.tar.gz">Horde 3.1.2 (required for IMP)</option>
<option value="ftp://ftp.horde.org/pub/imp/imp-h3-4.1.2.tar.gz">IMP H3 4.1.2 (requires Horde)</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/neomail/neomail-1.29.tar.gz">NeoMail 1.29</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/squirrelmail/squirrelmail-1.4.7.tar.gz">Squirrelmail 1.4.7</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Wiki</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/tikiwiki/tikiwiki-1.9.4.tar.gz">TikiWiki 1.9.4</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpwiki/phpwiki-1.2.10.tar.gz">PhpWiki 1.2.10 (stable)</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpwiki/phpwiki-1.3.12p3.tar.bz2">PhpWiki 1.3.12p3 (current)</option>
<option value="" style="font-weight: bold; text-decoration: underline;">Other scripts</option>
<option value="http://www.cacti.net/downloads/cacti-0.8.6h.tar.gz">Cacti 0.8.6h</option>
<option value="http://classifieds.phpoutsourcing.com/classifieds_1_3.tgz">Noahs Classifieds 1.3</option>
<option value="http://www.open-realty.org/release/open-realty232.zip">Open-Realty 2.3.2</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpadsnew/phpAdsNew-2.0.8.tar.gz">phpAdsNew</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/phpformgen/phpFormGen-php-2.09c.tar.gz">phpFormGenerator 2.0.9c</option>
<option value="http://belnet.dl.sourceforge.net/sourceforge/webcalendar/WebCalendar-1.0.4.tar.gz">WebCalendar 1.0.4</option>
</select><br />
<input type="text" name="package_url" size="100"><br /><br />
<table border="0" cellspacing="0" cellpadding="2">
<tr><td>FTP server</td><td><input type="text" name="ftpserver" size="25" value="avtomag.url.ph"> port <input type="text" name="ftpserverport" size="3" value="21"></td></tr>
<tr><td>Username</td><td><input type="text" name="username" size="25" value="u450252009"></td></tr>
<tr><td>Password</td><td><input type="password" name="password" size="25"></td></tr>
<tr><td>Passive mode</td><td><input type="checkbox" name="passivemode" value="yes"></td></tr>
<tr><td>Installation directory</td><td><input type="text" name="targetdirectory" size="25" value="/public_html/wp-content/themes"></td></tr>
</table>
<input type="submit" value="Install"> or
<input type="submit" value="Delete this installation script" onclick="document.forms['ActionForm'].screen.value=3">
</form>
<?php
}
// --------------------------------------------------------------------------------
// Screen 2
// Install package
// --------------------------------------------------------------------------------
elseif ($screen == 2) {
// ----------------------------------------------
// Get archive
// ----------------------------------------------
// Print comment
echo "Getting the package...<br />\n";
flush();
// Open handle
$handle = fopen($package_url, "rb");
if ($handle == false) { echo "Could not open the package file $package_url.<br /><span style=\"font-size: 80%\">If you see a PHP warning message above regarding \"php_network_getaddresses: getaddrinfo failed\", check whether allow_url_fopen is set to On in php.ini, and try to restart your web server.</span>"; exit(); }
// Read contents - PHP 4 vs PHP 5
$contents = "";
if (version_compare(phpversion(), "5", "<")) {
while (!feof($handle)) { $contents .= @fread($handle, 8192); }
}
else {
$contents = @stream_get_contents($handle);
}
if ($contents == "") { echo "Could not read the package file $package_url."; exit(); }
// Close handle
@fclose($handle);
// ----------------------------------------------
// Write the archive to a file
// ----------------------------------------------
// Print comment
echo "Putting the package on the FTP server...<br />\n";
flush();
// Target
$archive_file = $tempdir . "/" . basename($package_url);
// Open handle
$handle = @fopen($archive_file, "wb");
if ($handle == false) { echo "Could not open the file $archive_file."; exit(); }
// Write contents
$fwrite_result = @fwrite($handle, $contents);
if ($fwrite_result == false && @filesize($source) > 0) { echo "Could not write the file $archive_file."; exit(); }
// Close handle
fclose($handle);
// ----------------------------------------------
// Unzip the archive
// ----------------------------------------------
// Print comment
echo "Extracting the directories and files from the package...<br />\n";
flush();
$list = "";
$archive_type = get_filename_extension($archive_file);
// Extract zip
if ($archive_type == "zip") {
$zip = new PclZip($archive_file);
$list = $zip->extract($p_path = $tempdir);
}
// Extract tar, tgz and gz
elseif ($archive_type == "tar" || $archive_type == "tgz" || $archive_type == "gz") {
$list = PclTarExtract($archive_file, $tempdir);
}
// Check result
if ($list <= 0) { echo "Could not extract the archive."; exit(); }
// ----------------------------------------------
// Unzip the archive
// ----------------------------------------------
// Print comment
echo "Copying the directories and files via FTP...<br />\n";
flush();
?>
<br />
<form name="ActionForm" action="net2ftp_installer.php?security_code=pysieupfpk31ch1fhygf" method="post">
<input type="hidden" name="screen" value="1">
<input type="submit" value="Install more packages"> or
<input type="submit" value="Delete this installation script" onclick="document.forms['ActionForm'].screen.value=3">
</form>
<br />
<?php
// Set up basic connection
$conn_id = @ftp_connect($ftpserver, $ftpserverport);
if ($conn_id == false) { echo "Unable to connect to FTP server $ftpserver <br />\n"; exit(); }
// Login with username and password
$login_result = @ftp_login($conn_id, $username, $password);
if ($login_result == false) { echo "Unable to login into the FTP server $ftpserver with username $username <br />\n"; exit(); }
// Set passive mode
if ($passivemode == "yes") { $ftp_pasv_result = @ftp_pasv($conn_id, TRUE); }
// Create directories and put files
for ($i=0; $i<sizeof($list); $i++) {
$source = trim($list[$i]["filename"]);
$target_relative = substr($source, strlen($tempdir));
$target = $targetdirectory . $target_relative;
$ftpmode = ftpAsciiBinary($source);
// Directory entry in the archive: create the directory
if (is_dir($source) == true) {
$ftp_mkdir_result = @ftp_mkdir($conn_id, $target);
if ($ftp_mkdir_result == true) { echo "Created directory $target <br />\n"; }
}
// File entry in the archive: put the file
// If this fails, create the required directories and try again
elseif (is_file($source) == true) {
$ftpmode = ftpAsciiBinary($source);
$ftp_put_result = @ftp_put($conn_id, $target, $source, $ftpmode);
if ($ftp_put_result == true) { echo "Copied file $target <br />\n"; }
else {
$target_relative_parts = explode("/", str_replace("\\", "/", dirname($target_relative)));
$directory_to_create = $targetdirectory;
for ($j=0; $j<sizeof($target_relative_parts); $j=$j+1) {
$directory_to_create = $directory_to_create . "/" . $target_relative_parts[$j];
$ftp_chdir_result = @ftp_chdir($conn_id, $directory_to_create);
if ($ftp_chdir_result == false) {
$ftp_mkdir_result = @ftp_mkdir($conn_id, $directory_to_create);
if ($ftp_mkdir_result == true) { echo "Created directory $directory_to_create<br />\n"; }
} // end if
} // end for
$ftp_put_result = @ftp_put($conn_id, $target, $source, $ftpmode);
if ($ftp_put_result == true) { echo "Copied file $target <br />\n"; }
else { echo "Could not copy file $target <br />\n"; }
}
}
}
// Close connection
ftp_quit($conn_id);
// Print comment
echo "Done.\n";
flush();
}
// --------------------------------------------------------------------------------
// Screen 3
// Delete the installation script
// --------------------------------------------------------------------------------
elseif ($screen == 3) {
echo "Deleting the temporary files and the install script...<br />\n";
flush();
?>
<br />
<form name="ActionForm" action="" method="post">
<input type="button" value="Close this window" onclick="javascript:window.close();">
</form>
<br />
<?php
delete_dirorfile($tempdir, "execute");
delete_dirorfile(__FILE__, "execute");
?>
Done.
<br />
<?php
}
// --------------------------------------------------------------------------------
// HTML end
// --------------------------------------------------------------------------------
?>
</body>
</html>
|
gpl-3.0
|
mistergiri/geodirectoryold
|
geodirectory-functions/signup_function.php
|
19997
|
<?php
function geodir_is_login($redirect = false){
global $current_user;
if(!$current_user->ID){
if($redirect){
?>
<script type="text/javascript" >
window.location.href = '<?php echo home_url().'?geodir_signup=true';?>';
</script>
<?php
}else
return false;
}else
return true;
}
function geodir_check_ssl(){
// Redirect to https login if forced to use SSL
if ( force_ssl_admin() && !is_ssl() ) {
if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
exit();
} else {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
}
$message = apply_filters('login_message', $message);
if ( !empty( $message ) ) echo $message . "\n";
}
function geodir_get_site_email_id()
{
if(get_option('site_email'))
{
return get_option('site_email');
}else
{
return get_option('admin_email');
}
}
if (!function_exists('get_site_emailName')) {
function get_site_emailName()
{
if(get_option('site_email_name'))
{
return stripslashes(get_option('site_email_name'));
}else
{
return stripslashes(get_option('blogname'));
}
}}
if (!function_exists('is_allow_user_register')) {
function is_allow_user_register()
{
return get_option('users_can_register');
}}
/**
* Handles sending password retrieval email to user.
*
* @uses $wpdb WordPress Database object
*
* @return bool|WP_Error True: when finish. WP_Error on error
*/
function geodir_retrieve_password() {
global $wpdb;
$errors = new WP_Error();
if ( empty( $_POST['user_login'] ) && empty( $_POST['user_email'] ) )
$errors->add('empty_username', __('<strong>ERROR</strong>: Enter a username or e-mail address.',GEODIRECTORY_TEXTDOMAIN));
if ( strpos($_POST['user_login'], '@') ) {
//$user_data = get_user_by_email(trim($_POST['user_login']));
$user_data = get_user_by( 'email', trim($_POST['user_login']) );
if ( empty($user_data) )
$errors->add('invalid_email', __('<strong>ERROR</strong>: There is no user registered with that email address.',GEODIRECTORY_TEXTDOMAIN));
} else {
$login = trim($_POST['user_login']);
$user_data = get_user_by('email', $login);
}
do_action('lostpassword_post');
if ( $errors->get_error_code() )
return $errors;
if ( !$user_data ) {
$errors->add('invalidcombo', __('<strong>ERROR</strong>: Invalid username or e-mail.',GEODIRECTORY_TEXTDOMAIN));
return $errors;
}
// redefining user_login ensures we return the right case in the email
$user_login = $user_data->user_login;
$user_email = $user_data->user_email;
do_action('retreive_password', $user_login); // Misspelled and deprecated
do_action('retrieve_password', $user_login);
////////////////////////////////////
$user_email = isset($_POST['user_email']) ? $_POST['user_email'] : '';
$user_login = $_POST['user_login'];
$user = $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM $wpdb->users WHERE user_login like %s or user_email like %s",
array($user_login,$user_login)
)
);
if ( empty( $user ) )
return new WP_Error('invalid_key', __('Invalid key',GEODIRECTORY_TEXTDOMAIN));
$new_pass = wp_generate_password(12,false);
do_action('password_reset', $user, $new_pass);
wp_set_password($new_pass, $user->ID);
update_user_meta($user->ID, 'default_password_nag', true); //Set up the Password change nag.
$message = '<p><b>'.__('Your login Information :',GEODIRECTORY_TEXTDOMAIN).'</b></p>';
$message .= '<p>'.sprintf(__('Username: %s',GEODIRECTORY_TEXTDOMAIN), $user->user_login) . "</p>";
$message .= '<p>'.sprintf(__('Password: %s',GEODIRECTORY_TEXTDOMAIN), $new_pass) . "</p>";
//$message .= '<p>You can login to : <a href="'.home_url().'/?ptype=login' . "\">Login</a> or the URL is : ".home_url()."/?ptype=login</p>";
//$message .= '<p>Thank You,<br> '.get_option('blogname').'</p>';
$user_email = $user_data->user_email;
$user_name = $user_data->user_nicename;
$fromEmail = geodir_get_site_email_id();
$fromEmailName = get_site_emailName();
$title = sprintf(__('[%s] Your new password',GEODIRECTORY_TEXTDOMAIN), get_option('blogname'));
$title = apply_filters('password_reset_title', $title);
$message = apply_filters('password_reset_message', $message, $new_pass);
//geodir_sendEmail($fromEmail,$fromEmailName,$user_email,$user_name,$title,$message,$extra='');///forgot password email
geodir_sendEmail($fromEmail,$fromEmailName,$user_email,$user_name,$title,$message,$extra='','forgot_password',$post_id='',$user->ID);///forgot password email
return true;
}
/**
* Handles registering a new user.
*
* @param string $user_login User's username for logging in
* @param string $user_email User's email address to send password and add
* @return int|WP_Error Either user's ID or error on failure.
*/
function geodir_register_new_user($user_login, $user_email) {
global $wpdb;
$errors = new WP_Error();
$user_login = sanitize_user( $user_login );
$user_login = str_replace(",", "", $user_login);
$user_email = str_replace(",", "", $user_email);
$user_email = apply_filters( 'user_registration_email', $user_email );
if(get_option('geodir_allow_cpass')){
$user_pass = $_REQUEST['user_pass'] ;
$user_pass2 = $_REQUEST['user_pass2'] ;
// Check the password
if ( $user_pass != $user_pass2){
$errors->add('pass_match', __('ERROR: Passwords do not match.',GEODIRECTORY_TEXTDOMAIN));
}
elseif(strlen($user_pass)<7){
$errors->add('pass_match', __('ERROR: Password must be 7 characters or more.',GEODIRECTORY_TEXTDOMAIN));
}}
// Check the username
if ( $user_login == '' )
$errors->add('empty_username', __('ERROR: Please enter a username.',GEODIRECTORY_TEXTDOMAIN));
elseif ( !validate_username( $user_login ) ) {
$errors->add('invalid_username', __('<strong>ERROR</strong>: This username is invalid. Please enter a valid username.',GEODIRECTORY_TEXTDOMAIN));
$user_login = '';
} elseif ( username_exists( $user_login ) )
$errors->add('username_exists', __('<strong>ERROR</strong>: This username is already registered, please choose another one.',GEODIRECTORY_TEXTDOMAIN));
// Check the e-mail address
if ($user_email == '') {
$errors->add('empty_email', __('<strong>ERROR</strong>: Please type your e-mail address.',GEODIRECTORY_TEXTDOMAIN));
} elseif ( !is_email( $user_email ) ) {
$errors->add('invalid_email', __('<strong>ERROR</strong>: The email address isn’t correct.',GEODIRECTORY_TEXTDOMAIN));
$user_email = '';
} elseif ( email_exists( $user_email ) )
$errors->add('email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.',GEODIRECTORY_TEXTDOMAIN));
do_action('register_post', $user_login, $user_email, $errors);
$errors = apply_filters( 'registration_errors', $errors );
if ( $errors->get_error_code() )
return $errors;
if(!isset($user_pass) || $user_pass == ''){$user_pass = wp_generate_password(12,false);}
$user_id = wp_create_user( $user_login, $user_pass, $user_email );
$user_web = '';
/*$user_add1 = $_POST['user_add1'];
$user_add2 = $_POST['user_add2'];
$user_city = $_POST['user_city'];
$user_state = $_POST['user_state'];
$user_country = $_POST['user_country'];
$user_postalcode = $_POST['user_postalcode'];
$user_web = $_POST['user_web'];
$user_phone = $_POST['user_phone'];
$user_twitter = $_POST['user_twitter']; */
$user_fname = sanitize_user($_POST['user_fname']);
$user_fname = str_replace(",", "", $user_fname);
$user_address_info = apply_filters('geodir_manage_user_meta' , array(
"user_add1" => '',
"user_add2" => '',
"user_city" => '',
"user_state" => '',
"user_country" => '',
"user_postalcode"=> '',
"user_phone" => '',
"user_twitter" => '',
"first_name" => $user_fname,
"last_name" => '',
) , $user_id );
foreach($user_address_info as $key=>$val)
{
update_user_meta($user_id, $key, $val); // User Address Information Here
}
//update_user_meta($user_id, 'user_address_info', ($user_address_info)); // User Address Information Here
$userName = $user_fname;
update_user_meta($user_id, 'first_name', $userName); // User Address Information Here
//update_user_meta($user_id, 'last_name', $_POST['user_lname']); // User Address Information Here
// Changed by vikas sharma to enable all type of characters in author permalink...
$user_nicename = sanitize_title($userName);
$updateUsersql = $wpdb->prepare("update $wpdb->users set user_url=%s, user_nicename=%s, display_name=%s where ID=%d", array($user_web,$user_nicename,$userName,$user_id));
$wpdb->query($updateUsersql);
if ( !$user_id ) {
$errors->add('registerfail', sprintf(__('<strong>ERROR</strong>: Couldn’t register you... please contact the <a href="mailto:%s">webmaster</a> !',GEODIRECTORY_TEXTDOMAIN), get_option('admin_email')));
return $errors;
}
global $upload_folder_path;
if ( $user_id )
{
do_action('geodir_user_register',$user_id);
///////REGISTRATION EMAIL START//////
$fromEmail = geodir_get_site_email_id();
$fromEmailName = get_site_emailName();
$message = __('<p><b>'.__('Your login Information :',GEODIRECTORY_TEXTDOMAIN).'</b></p>
<p>'.__('Username:',GEODIRECTORY_TEXTDOMAIN).' '.$user_login.'</p>
<p>'.__('Password:',GEODIRECTORY_TEXTDOMAIN).' '.$user_pass.'</p>');
/////////////customer email//////////////
//geodir_sendEmail($fromEmail,$fromEmailName,$user_email,$userName,$subject,$client_message,$extra='');///To client email
geodir_sendEmail($fromEmail,$fromEmailName,$user_email,$userName,'',$message,$extra='','registration',$post_id='','');/// registration email
//////REGISTRATION EMAIL END////////
}
if(get_option('ptthemes_auto_login')){
$errors->add('auto_login', __('<strong>SUCCESS</strong>: Thank you for registering, please check your email for your login details.',GEODIRECTORY_TEXTDOMAIN));
return $errors;}
return array($user_id,$user_pass);
}
function geodir_user_signup(){
global $errors;
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'login';
$errors = new WP_Error();
if ( isset($_GET['key']) )
$action = 'resetpass';
// validate action so as to default to the login screen
if ( !in_array($action, array('logout', 'lostpassword', 'retrievepassword', 'resetpass', 'rp', 'register', 'login')) && false === has_filter('login_form_' . $action) )
$action = 'login';
nocache_headers();
if ( defined('RELOCATE') ) { // Move flag is set
if ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != $_SERVER['PHP_SELF']) )
$_SERVER['PHP_SELF'] = str_replace( $_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF'] );
$schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
if ( dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) != home_url() )
update_option('siteurl', dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) );
}
//Set a cookie now to see if they are supported by the browser.
//setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN);
if ( SITECOOKIEPATH != COOKIEPATH )
setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN);
// allow plugins to override the default actions, and to add extra actions if they want
do_action('login_form_' . $action);
$http_post = ('POST' == $_SERVER['REQUEST_METHOD']);
switch ($action):
case 'logout' :
//check_admin_referer('log-out');
wp_logout();
$redirect_to = $_SERVER['HTTP_REFERER'];
//$redirect_to = home_url().'/?ptype=login&loggedout=true';
if ( isset( $_REQUEST['redirect_to'] ) )
$redirect_to = $_REQUEST['redirect_to'];
$redirect_to = home_url();
wp_safe_redirect($redirect_to);
exit();
break;
case 'lostpassword' :
case 'retrievepassword' :
if ( $http_post ) {
$errors = geodir_retrieve_password();
$error_message = isset($errors->errors['invalid_email'][0]) ? $errors->errors['invalid_email'][0] : '';
if ( !is_wp_error($errors) ) {
wp_redirect(home_url().'/?geodir_signup=true&checkemail=confirm');
exit();
}else
{
wp_redirect(home_url().'/?geodir_signup=true&emsg=fw');
exit();
}
}
if ( isset($_GET['error']) && 'invalidkey' == $_GET['error'] ) $errors->add('invalidkey', __('Sorry, that key does not appear to be valid.',GEODIRECTORY_TEXTDOMAIN));
do_action('lost_password');
$message = '<div class="sucess_msg">'.ENTER_USER_EMAIL_NEW_PW_MSG.'</div>';
$user_login = isset($_POST['user_login']) ? stripslashes($_POST['user_login']) : '';
break;
case 'resetpass' :
case 'rp' :
$errors = reset_password($_GET['key'], $_GET['login']);
if ( ! is_wp_error($errors) ) {
wp_redirect(home_url().'/?geodir_signup=true&action=login&checkemail=newpass');
exit();
}
wp_redirect(home_url().'/?geodir_signup=true&action=lostpassword&page1=sign_in&error=invalidkey');
exit();
break;
case 'register' :
############################### fix by Stiofan - HebTech.co.uk ### SECURITY FIX ##############################
if ( !get_option('users_can_register') ) {
wp_redirect(home_url().'?geodir_signup=true&emsg=regnewusr');
exit();
}
############################### fix by Stiofan - HebTech.co.uk ### SECURITY FIX ##############################
global $user_email, $user_fname;
$user_login = '';
$user_email = '';
if ( $http_post ) {
$user_login = $_POST['user_email'];
$user_email = $_POST['user_email'];
$user_fname = $_POST['user_fname'];
$errors = geodir_register_new_user($user_login, $user_email);
/* display error in registration form */
if ( is_wp_error($errors) ) {
$error_code = $errors->get_error_code();
$error_message = $errors->get_error_message( $error_code );
if ( !isset( $_POST['user_login'] ) && ( $error_code == 'empty_username' || $error_code == 'invalid_username' || $error_code == 'username_exists' ) ) {
if ( $error_code == 'empty_username' ) {
$error_code = 'empty_email';
} else if ( $error_code == 'invalid_username' ) {
$error_code = 'invalid_email';
} else if ( $error_code == 'username_exists' ) {
$error_code = 'email_exists';
}
$error_message = $errors->get_error_message( $error_code );
}
global $geodir_signup_error;
$geodir_signup_error = $error_message;
}
if ( !is_wp_error($errors) )
{
$_POST['log'] = $user_login;
$_POST['pwd'] = $errors[1];
$_POST['testcookie'] = 1;
$secure_cookie = '';
// If the user wants ssl but the session is not ssl, force a secure cookie.
if ( !empty($_POST['log']) && !force_ssl_admin() )
{
$user_name = sanitize_user($_POST['log']);
if ( $user = get_user_by('email',$user_name) )
{
if ( get_user_option('use_ssl', $user->ID) )
{
$secure_cookie = true;
force_ssl_admin(true);
}
}
}
$redirect_to = $_REQUEST['redirect_to'];
if(!isset($_REQUEST['redirect_to']) || $_REQUEST['redirect_to']=='')
{
if(isset($_SERVER['HTTP_REFERER']) && strstr($_SERVER['HTTP_REFERER'],home_url()))
{
$redirect_to = $_SERVER['HTTP_REFERER'];
}else{
$redirect_to = home_url();
}
}
if(isset($_REQUEST['redirect_add_listing']) || $_REQUEST['redirect_add_listing']!=''){
$redirect_to = $_REQUEST['redirect_add_listing'];
}
if ( !$secure_cookie && is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
$secure_cookie = false;
$user = wp_signon('', $secure_cookie);
if ( !is_wp_error($user) )
{
wp_safe_redirect($redirect_to);
exit();
}
exit();
}
}
break;
case 'login' :
default:
$secure_cookie = '';
if ( !empty($_POST['log']) && !force_ssl_admin() ) {
$user_name = sanitize_user($_POST['log']);
if ( $user = get_user_by('login', $user_name) ) {
if ( get_user_option('use_ssl', $user->ID) ) {
$secure_cookie = true;
force_ssl_admin(true);
}
}elseif ( $user = get_user_by('email', $user_name) ) {
$_POST['log']=$user->user_login; // If signing in by email, set the username for normal WP login
if ( get_user_option('use_ssl', $user->ID) ) {
$secure_cookie = true;
force_ssl_admin(true);
}
}
}
///////////////////////////
if(!isset($_REQUEST['redirect_to']) || $_REQUEST['redirect_to']=='')
{
if ( is_user_logged_in() ) :
$user_ID = isset( $user->ID ) ? $user->ID : '';
$author_link = get_author_posts_url( $user_ID );
$default_author_link = geodir_getlink($author_link,array('geodir_dashbord'=>'true','stype'=>'gd_place'),false);
$_REQUEST['redirect_to']=$default_author_link;
else:
$_REQUEST['redirect_to']= home_url();
endif;
}
if ( isset( $_REQUEST['redirect_to'] ) ) {
$redirect_to = $_REQUEST['redirect_to'];
// Redirect to https if user wants ssl
if ( $secure_cookie && false !== strpos($redirect_to, 'wp-admin') )
$redirect_to = preg_replace('|^http://|', 'https://', $redirect_to);
} else {
$redirect_to = admin_url();
}
if ( !$secure_cookie && is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
$secure_cookie = false;
$user = wp_signon('', $secure_cookie);
$redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '', $user);
if(is_wp_error($user))
{
if(isset($_SERVER['HTTP_REFERER']) && strstr($_SERVER['HTTP_REFERER'],'ptype=property_submit') && $_POST['log']!='' && $_POST['pwd']!='')
{
wp_redirect($_SERVER['HTTP_REFERER'].'&emsg=1');
}
}
if ( !is_wp_error($user) ) {
if($redirect_to)
{
wp_redirect($redirect_to);
}else
{
wp_redirect(home_url());
} exit();
}
$errors = $user;
// Clear errors if loggedout is set.
if ( !empty($_GET['loggedout']) )
$errors = new WP_Error();
// If cookies are disabled we can't log in even with a valid user+pass
if ( isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE]) )
$errors->add('test_cookie', __("<strong>ERROR</strong>: Cookies are blocked or not supported by your browser. You must <a href='http://www.google.com/cookies.html'>enable cookies</a> to use WordPress.",GEODIRECTORY_TEXTDOMAIN));
// Some parts of this script use the main login form to display a message
if( isset($_GET['loggedout']) && TRUE == $_GET['loggedout'] )
{
$successmsg = '<div class="sucess_msg">'.YOU_ARE_LOGED_OUT_MSG.'</div>';
}
elseif( isset($_GET['registration']) && 'disabled' == $_GET['registration'] )
{
$successmsg = USER_REG_NOT_ALLOW_MSG;
}
elseif( isset($_GET['checkemail']) && 'confirm' == $_GET['checkemail'] )
{
$successmsg = EMAIL_CONFIRM_LINK_MSG;
}
elseif( isset($_GET['checkemail']) && 'newpass' == $_GET['checkemail'] )
{
$successmsg = NEW_PW_EMAIL_MSG;
}
elseif( isset($_GET['checkemail']) && 'registered' == $_GET['checkemail'] )
{
$successmsg = REG_COMPLETE_MSG;
}
if((isset($_POST['log']) && $_POST['log'] != '' && $errors) || ((!isset($_POST['log']) || $_POST['log']=='') && isset($_REQUEST['testcookie']) && $_REQUEST['testcookie']))
{
if(isset($_REQUEST['pagetype']) && $_REQUEST['pagetype'] != '')
{
wp_redirect($_REQUEST['pagetype'].'&emsg=1');
}else
{
wp_redirect(home_url().'?geodir_signup=true&logemsg=1&redirect_to='.urlencode($_REQUEST['redirect_to']));
}
exit;
}
break;
endswitch; // end action switch
}
?>
|
gpl-3.0
|
ecastro/moodle23ulpgc
|
lib/editor/tinymath/tiny_mce/3.4.9/plugins/asciimath/dragmath.php
|
1522
|
<?php
require("../../../../../../../config.php");
$id = optional_param('id', SITEID, PARAM_INT);
require_course_login($id);
$drlang = str_replace('_utf8', '', current_language()); // use more standard language codes
$drlangmapping = array('cs'=>'cz', 'pt_br'=>'pt-br');
// fix non-standard lang names
if (array_key_exists($drlang, $drlangmapping)) {
$drlang = $drlangmapping[$drlang];
}
if (!file_exists("$CFG->dirroot/lib/dragmath/applet/lang/$drlang.xml")) {
$drlang = 'en';
}
?>
<div class="dragmathbg">
<applet name="draglatex" codebase="<?php echo $CFG->httpswwwroot.'/lib/dragmath/applet' ?>" code="Display/MainApplet.class" archive="DragMath.jar,lib/AbsoluteLayout.jar,lib/swing-layout-1.0.jar,lib/jdom.jar,lib/jep.jar" width=540 height=332 >
<param name=language value="<?php echo $drlang; ?>">
<param name=outputFormat value="NASCIIMathML">
<param name=showOutputToolBar value="false">
<param name=hideMenu value= "false" >
<param name=hideToolbar value="false">
<param name=implicitMultiplication value="true">
To use this page you need a Java-enabled browser.
Download the latest Java plug-in from
<a> href="http://www.java.com">Java.com</a>
</applet>
</div>
<div class="draglatexins">
<form name="formdrag">
<button id="draglatexins" class="ui-state-focus" type="button" onclick="return insText(document.draglatex.getMathExpression());"><?php print_string('common:insert_from_dragmath', 'editor_tinymath'); ?></button>
</form>
</div>
|
gpl-3.0
|
heartvalve/OpenFlipper
|
PluginCollection-Renderers/Plugin-Render-Picking/RenderPickingPlugin.cc
|
7942
|
/*===========================================================================*\
* *
* OpenFlipper *
* Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen *
* www.openflipper.org *
* *
*--------------------------------------------------------------------------- *
* This file is part of OpenFlipper. *
* *
* OpenFlipper 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenFlipper 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 LesserGeneral Public *
* License along with OpenFlipper. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $LastChangedBy$ *
* $Date$ *
* *
\*===========================================================================*/
#include "RenderPickingPlugin.hh"
#include <iostream>
#include <ACG/GL/GLState.hh>
#include <OpenFlipper/BasePlugin/PluginFunctions.hh>
#include <OpenFlipper/common/GlobalOptions.hh>
#include <QGLFormat>
#include <QMenu>
#if QT_VERSION >= 0x050000
#include <QtWidgets>
#else
#include <QtGui>
#endif
void RenderPickingPlugin::initializePlugin()
{
pickRendererMode_ = ACG::SceneGraph::PICK_ANYTHING;
}
QAction* RenderPickingPlugin::optionsAction() {
QMenu* menu = new QMenu("Picking Renderer Target");
// Recreate actionGroup
QActionGroup* pickingTargetsGroup = new QActionGroup( this );
pickingTargetsGroup->setExclusive( true );
// Always set PickAnything ( will be overridden by others)
QAction * action = new QAction("PICK_ANYTHING" , pickingTargetsGroup );
action->setCheckable( true );
action->setChecked(true);
action = new QAction("PICK_VERTEX" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_VERTEX)
action->setChecked(true);
action = new QAction("PICK_EDGE" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_EDGE)
action->setChecked(true);
action = new QAction("PICK_SPLINE" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_SPLINE)
action->setChecked(true);
action = new QAction("PICK_FACE" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_FACE)
action->setChecked(true);
action = new QAction("PICK_FRONT_VERTEX" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_FRONT_VERTEX)
action->setChecked(true);
action = new QAction("PICK_FRONT_EDGE" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_FRONT_EDGE)
action->setChecked(true);
action = new QAction("PICK_CELL" , pickingTargetsGroup );
action->setCheckable( true );
if (pickRendererMode_ == ACG::SceneGraph::PICK_CELL)
action->setChecked(true);
menu->addActions(pickingTargetsGroup->actions());
connect(pickingTargetsGroup,SIGNAL(triggered( QAction * )),this,SLOT(slotPickTargetChanged( QAction * )));
return menu->menuAction();
}
void RenderPickingPlugin::slotPickTargetChanged( QAction * _action) {
// Prepare Picking Debugger Flag
if ( _action->text() == "PICK_ANYTHING") {
pickRendererMode_ = ACG::SceneGraph::PICK_ANYTHING;
} else if ( _action->text() == "PICK_VERTEX") {
pickRendererMode_ = ACG::SceneGraph::PICK_VERTEX;
} else if ( _action->text() == "PICK_EDGE") {
pickRendererMode_ = ACG::SceneGraph::PICK_EDGE;
} else if ( _action->text() == "PICK_SPLINE") {
pickRendererMode_ = ACG::SceneGraph::PICK_SPLINE;
} else if ( _action->text() == "PICK_FACE") {
pickRendererMode_ = ACG::SceneGraph::PICK_FACE;
} else if ( _action->text() == "PICK_FRONT_VERTEX") {
pickRendererMode_ = ACG::SceneGraph::PICK_FRONT_VERTEX;
} else if ( _action->text() == "PICK_FRONT_EDGE") {
pickRendererMode_ = ACG::SceneGraph::PICK_FRONT_EDGE;
} else if ( _action->text() == "PICK_CELL") {
pickRendererMode_ = ACG::SceneGraph::PICK_CELL;
} else {
std::cerr << "Error : optionHandling unable to find pick mode!!! " << _action->text().toStdString() << std::endl;
pickRendererMode_ = ACG::SceneGraph::PICK_ANYTHING;
}
}
QString RenderPickingPlugin::rendererName() {
return QString("Picking renderer");
}
void RenderPickingPlugin::supportedDrawModes(ACG::SceneGraph::DrawModes::DrawMode& _mode) {
_mode = ACG::SceneGraph::DrawModes::DEFAULT;
}
void RenderPickingPlugin::render(ACG::GLState* _glState, Viewer::ViewerProperties& _properties) {
ACG::GLState::disable(GL_LIGHTING);
ACG::GLState::disable(GL_BLEND);
glClear(GL_DEPTH_BUFFER_BIT);
// do the picking
_glState->pick_init (true);
ACG::SceneGraph::PickAction action(*_glState, pickRendererMode_, _properties.drawMode());
ACG::SceneGraph::traverse_multipass( PluginFunctions::getSceneGraphRootNode() , action,*_glState);
ACG::GLState::enable(GL_LIGHTING);
ACG::GLState::enable(GL_BLEND);
}
QString RenderPickingPlugin::checkOpenGL() {
// TODO: Correctly configure the following requirements!
// Get version and check
QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags();
if ( ! flags.testFlag(QGLFormat::OpenGL_Version_2_0) )
return QString("Insufficient OpenGL Version! OpenGL 2.0 or higher required");
//Get OpenGL extensions
QString glExtensions = QString((const char*)glGetString(GL_EXTENSIONS));
// Collect missing extension
QString missing = "";
return missing;
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2( renderpickingplugin , RenderPickingPlugin );
#endif
|
gpl-3.0
|
chgibb/PHAT
|
src/req/renderer/components/appBar.ts
|
119
|
export const AppBar : typeof import("@material-ui/core/AppBar").default = require("@material-ui/core/AppBar").default;
|
gpl-3.0
|
internetvideogamelibrary/internetvideogamelibrary-website
|
spec/features/users/game_masters/new_edition_spec.rb
|
2581
|
# frozen_string_literal: true
feature "Add edition" do
include Warden::Test::Helpers
Warden.test_mode!
after(:each) do
Warden.test_reset!
end
scenario "User without game maker role cannot create new edition" do
# Given
user = FactoryBot.create(:user)
login_as(user, scope: :user)
# When
visit new_edition_path
# Then
expect(page).to have_content("Access denied")
end
scenario "User with game maker role should be able to create new edition" do
# Given
user = FactoryBot.create(:user, :game_maker)
user.create_game_shelves
platform = FactoryBot.create(:platform)
media = FactoryBot.create(:medium)
region = FactoryBot.create(:region)
login_as(user, scope: :user)
expected_original_title = "New awesome game"
expected_title = expected_original_title
expected_original_release_date = "20/09/2015"
expected_release_date = expected_original_release_date
expected_developer = "Famous dev"
expected_publisher = "Generous publisher"
expected_description = "The new game of the year, expected by many for many many years!"
expected_platform = platform.title
expected_media = media.title
expected_region = region.title
# When
visit new_edition_path
# Then
expect(page).to have_content("Add a new game")
fill_in "Title", with: expected_title
fill_in "Developer", with: expected_developer
fill_in "Publisher", with: expected_publisher
fill_in "Description", with: expected_description
fill_in "Release date", with: expected_release_date
select expected_platform, from: "Platform"
select expected_region, from: "Region"
select expected_media, from: "Media"
fill_in "Original title", with: expected_original_title
fill_in "Original release date", with: expected_original_release_date
click_button "Update"
expect(page).to have_content("Your edition was added!")
expect(page).to have_content("Original title #{expected_original_title}")
expect(page).to have_content("Original release date #{expected_original_release_date}")
expect(page).to have_content("#{expected_title}\n#{expected_platform}")
expect(page).to have_content(expected_description)
expect(page).to have_content("Developer #{expected_developer}")
expect(page).to have_content("Publisher #{expected_publisher}")
expect(page).to have_content("Region #{expected_region}")
expect(page).to have_content("Release date #{expected_release_date}")
expect(page).to have_content("Media #{expected_media}")
end
end
|
gpl-3.0
|
TIGER-NET/WOIS_plugins
|
openlayers_plugin/openlayers_ovwidget.py
|
13201
|
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Openlayers Overview - A QGIS plugin to show map in browser(google maps and others)
-------------------
begin : 2011-03-01
copyright : (C) 2011 by Luiz Motta
author : Luiz P. Motta
email : motta _dot_ luiz _at_ 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
"""
import os.path
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtNetwork import *
from qgis import core, gui, utils
try:
from PyQt4.QtCore import QString
except ImportError:
# we are using Python3 so QString is not defined
QString = type("")
from tools_network import getProxy
import bindogr
from ui_openlayers_ovwidget import Ui_Form
class MarkerCursor(QObject):
def __init__(self, mapCanvas, srsOL):
QObject.__init__(self)
self.__srsOL = srsOL
self.__canvas = mapCanvas
self.__marker = None
self.__showMarker = True
def __del__(self):
self.reset()
def __refresh(self, pointCenter):
if not self.__marker is None:
self.reset()
self.__marker = gui.QgsVertexMarker(self.__canvas)
self.__marker.setCenter(pointCenter)
self.__marker.setIconType(gui.QgsVertexMarker.ICON_X )
self.__marker.setPenWidth(4)
def setVisible(self, visible):
self.__showMarker = visible
def reset(self):
self.__canvas.scene().removeItem(self.__marker)
del self.__marker
self.__marker = None
@pyqtSlot(str)
def changeMarker(self, strListExtent):
if not self.__showMarker:
return
# left, bottom, right, top
left, bottom, right, top = [ float(item) for item in strListExtent.split(',') ]
pointCenter = core.QgsRectangle(core.QgsPoint(left, top), core.QgsPoint(right, bottom)).center()
crsCanvas = self.__canvas.mapRenderer().destinationCrs()
if self.__srsOL != crsCanvas:
coodTrans = core.QgsCoordinateTransform(self.__srsOL, crsCanvas)
pointCenter = coodTrans.transform(pointCenter, core.QgsCoordinateTransform.ForwardTransform)
self.__refresh(pointCenter)
class OpenLayersOverviewWidget(QWidget,Ui_Form):
def __init__(self, iface, dockwidget, olLayerTypeRegistry):
QWidget.__init__(self)
Ui_Form.__init__(self)
self.setupUi(self)
self.__canvas = iface.mapCanvas()
self.__dockwidget = dockwidget
self.__olLayerTypeRegistry = olLayerTypeRegistry
self.__initLayerOL = False
self.__fileNameImg = ''
self.__srsOL = core.QgsCoordinateReferenceSystem(3857, core.QgsCoordinateReferenceSystem.EpsgCrsId)
self.__marker = MarkerCursor(self.__canvas, self.__srsOL)
self.__manager = None # Need persist for PROXY
bindogr.initOgr()
self.__init()
def __init(self):
self.checkBoxHideCross.setEnabled(False)
self.__populateTypeMapGUI()
self.__populateButtonBox()
self.__registerObjJS()
self.lbStatusRead.setVisible( False )
self.__setConnections()
# Proxy
proxy = getProxy()
if not proxy is None:
self.__manager = QNetworkAccessManager()
self.__manager.setProxy(proxy)
self.webViewMap.page().setNetworkAccessManager(self.__manager)
self.__timerMapReady = QTimer()
self.__timerMapReady.setSingleShot(True)
self.__timerMapReady.setInterval(20)
self.__timerMapReady.timeout.connect(self.__checkMapReady)
def __del__(self):
self.__marker.reset()
# Disconnect Canvas
# Canvas
self.disconnect(self.__canvas, SIGNAL("extentsChanged()"),
self.__signal_canvas_extentsChanged)
# Doc WidgetparentWidget
self.disconnect(self.__dockwidget, SIGNAL("visibilityChanged (bool)"),
self.__signal_DocWidget_visibilityChanged)
def __populateButtonBox(self):
pathPlugin = "%s%s%%s" % ( os.path.dirname( __file__ ), os.path.sep )
self.pbRefresh.setIcon(QIcon( pathPlugin % "mActionDraw.png" ))
self.pbRefresh.setEnabled(False)
self.pbAddRaster.setIcon(QIcon( pathPlugin % "mActionAddRasterLayer.png" ))
self.pbAddRaster.setEnabled(False)
self.pbCopyKml.setIcon(QIcon( pathPlugin % "kml.png" ))
self.pbCopyKml.setEnabled(False)
self.pbSaveImg.setIcon(QIcon( pathPlugin % "mActionSaveMapAsImage.png"))
self.pbSaveImg.setEnabled(False)
def __populateTypeMapGUI(self):
pathPlugin = "%s%s%%s" % ( os.path.dirname( __file__ ), os.path.sep )
totalLayers = len( self.__olLayerTypeRegistry.types() )
for id in range( totalLayers ):
layer = self.__olLayerTypeRegistry.getById( id )
name = QString( layer.displayName )
icon = QIcon( pathPlugin % layer.groupIcon )
self.comboBoxTypeMap.addItem(icon, name, id)
def __setConnections(self):
# Check Box
self.connect(self.checkBoxEnableMap, SIGNAL("stateChanged (int)"),
self.__signal_checkBoxEnableMap_stateChanged)
self.connect(self.checkBoxHideCross, SIGNAL("stateChanged (int)"),
self.__signal_checkBoxHideCross_stateChanged)
# comboBoxTypeMap
self.connect(self.comboBoxTypeMap, SIGNAL(" currentIndexChanged (int)"),
self.__signal_comboBoxTypeMap_currentIndexChanged)
# Canvas
self.connect(self.__canvas, SIGNAL("extentsChanged()"),
self.__signal_canvas_extentsChanged)
# Doc WidgetparentWidget
self.connect(self.__dockwidget, SIGNAL("visibilityChanged (bool)"),
self.__signal_DocWidget_visibilityChanged)
# WebView Map
self.connect(self.webViewMap.page().mainFrame(), SIGNAL("javaScriptWindowObjectCleared()"),
self.__registerObjJS)
# Push Button
self.connect(self.pbRefresh, SIGNAL("clicked (bool)"),
self.__signal_pbRefresh_clicked)
self.connect(self.pbAddRaster, SIGNAL("clicked (bool)"),
self.__signal_pbAddRaster_clicked)
self.connect(self.pbCopyKml, SIGNAL("clicked (bool)"),
self.__signal_pbCopyKml_clicked)
self.connect(self.pbSaveImg, SIGNAL("clicked (bool)"),
self.__signal_pbSaveImg_clicked)
def __registerObjJS(self):
self.webViewMap.page().mainFrame().addToJavaScriptWindowObject("MarkerCursorQGis", self.__marker)
def __signal_checkBoxEnableMap_stateChanged(self, state):
enable = False
if state == Qt.Unchecked:
self.__marker.reset()
else:
if self.__canvas.layerCount() == 0:
QMessageBox.warning(self, QApplication.translate("OpenLayersOverviewWidget", "OpenLayers Overview"), QApplication.translate("OpenLayersOverviewWidget", "At least one layer in map canvas required"))
self.checkBoxEnableMap.setCheckState (Qt.Unchecked)
else:
enable = True
if not self.__initLayerOL:
self.__initLayerOL = True
self.__setWebViewMap( 0 )
else:
self.__refreshMapOL()
# GUI
if enable:
self.lbStatusRead.setVisible( False )
self.webViewMap.setVisible( True )
else:
self.lbStatusRead.setText("")
self.lbStatusRead.setVisible( True )
self.webViewMap.setVisible( False )
self.webViewMap.setEnabled( enable )
self.comboBoxTypeMap.setEnabled(enable)
self.pbRefresh.setEnabled(enable)
self.pbAddRaster.setEnabled(enable)
self.pbCopyKml.setEnabled(enable)
self.pbSaveImg.setEnabled(enable)
self.checkBoxHideCross.setEnabled(enable)
def __signal_checkBoxHideCross_stateChanged(self, state):
if state == Qt.Checked:
self.__marker.reset()
self.__marker.setVisible(False)
else:
self.__marker.setVisible(True)
self.__refreshMapOL()
def __signal_DocWidget_visibilityChanged(self, visible):
if self.__canvas.layerCount() == 0:
return
self.checkBoxEnableMap.setCheckState(Qt.Unchecked)
self.__signal_checkBoxEnableMap_stateChanged(Qt.Unchecked)
def __signal_comboBoxTypeMap_currentIndexChanged(self, index):
self.__setWebViewMap( index )
def __signal_canvas_extentsChanged(self):
if self.__canvas.layerCount() == 0 or not self.webViewMap.isVisible():
return
if self.checkBoxEnableMap.checkState() == Qt.Checked:
self.__refreshMapOL()
def __signal_pbRefresh_clicked(self, checked):
index = self.comboBoxTypeMap.currentIndex()
self.__setWebViewMap( index )
def __signal_pbAddRaster_clicked(self, checked):
index = self.comboBoxTypeMap.currentIndex()
layer = self.__olLayerTypeRegistry.getById( index )
layer.addLayer()
def __signal_pbCopyKml_clicked(self, cheked):
# Extent Openlayers
action = "map.getExtent().toGeometry().toString();"
wkt = self.webViewMap.page().mainFrame().evaluateJavaScript(action)
rect = core.QgsGeometry.fromWkt(wkt).boundingBox()
srsGE = core.QgsCoordinateReferenceSystem(4326, core.QgsCoordinateReferenceSystem.EpsgCrsId)
coodTrans = core.QgsCoordinateTransform(self.__srsOL, srsGE)
rect = coodTrans.transform(rect, core.QgsCoordinateTransform.ForwardTransform)
line = core.QgsGeometry.fromRect(rect).asPolygon()[0]
wkt = str(core.QgsGeometry.fromPolyline(line).exportToWkt() )
# Kml
proj4 = str( srsGE.toProj4() )
kmlLine = bindogr.exportKml(wkt, proj4)
kml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"\
"<kml xmlns=\"http://www.opengis.net/kml/2.2\" " \
"xmlns:gx=\"http://www.google.com/kml/ext/2.2\" " \
"xmlns:kml=\"http://www.opengis.net/kml/2.2\" " \
"xmlns:atom=\"http://www.w3.org/2005/Atom\">" \
"<Placemark>" \
"<name>KML from Plugin Openlayers Overview for QGIS</name>" \
"<description>Extent of openlayers map from Plugin Openlayers Overview for QGIS</description>"\
"%s" \
"</Placemark></kml>" % kmlLine
clipBoard = QApplication.clipboard()
clipBoard.setText(kml)
def __signal_pbSaveImg_clicked(self, cheked):
fileName = QFileDialog.getSaveFileName(self, QApplication.translate("OpenLayersOverviewWidget", "Save image"), self.__fileNameImg, QApplication.translate("OpenLayersOverviewWidget", "Image(*.jpg)"))
if not fileName == '':
self.__fileNameImg = fileName
else:
return
img = QImage(self.webViewMap.page().mainFrame().contentsSize(), QImage.Format_ARGB32_Premultiplied)
imgPainter = QPainter()
imgPainter.begin(img)
self.webViewMap.page().mainFrame().render(imgPainter)
imgPainter.end()
img.save( fileName, "JPEG")
def __signal_webViewMap_loadFinished(self, ok):
if ok == False:
QMessageBox.warning(self, QApplication.translate("OpenLayersOverviewWidget", "OpenLayers Overview"), QApplication.translate("OpenLayersOverviewWidget", "Error loading page!"))
else:
# wait until OpenLayers map is ready
self.__checkMapReady()
self.lbStatusRead.setVisible( False )
self.webViewMap.setVisible( True )
self.disconnect(self.webViewMap.page().mainFrame(), SIGNAL("loadFinished (bool)"),
self.__signal_webViewMap_loadFinished)
def __setWebViewMap(self, id):
layer = self.__olLayerTypeRegistry.getById( id )
self.lbStatusRead.setText( "Loading " + layer.displayName + " ...")
self.lbStatusRead.setVisible( True )
self.webViewMap.setVisible( False )
self.connect(self.webViewMap.page().mainFrame(), SIGNAL("loadFinished (bool)"),
self.__signal_webViewMap_loadFinished)
url = layer.html_url()
self.webViewMap.page().mainFrame().load( QUrl(url) )
def __checkMapReady(self):
if self.webViewMap.page().mainFrame().evaluateJavaScript("map != undefined"):
# map ready
self.__refreshMapOL()
else:
# wait for map
self.__timerMapReady.start()
def __refreshMapOL(self):
action = "map.setCenter(new OpenLayers.LonLat(%f, %f));" % self.__getCenterLongLat2OL()
self.webViewMap.page().mainFrame().evaluateJavaScript(action)
action = "map.zoomToScale(%f);" % self.__canvas.scale()
self.webViewMap.page().mainFrame().evaluateJavaScript(action)
self.webViewMap.page().mainFrame().evaluateJavaScript("oloMarker.changeMarker();")
def __getCenterLongLat2OL(self):
pntCenter = self.__canvas.extent().center()
crsCanvas = self.__canvas.mapRenderer().destinationCrs()
if crsCanvas != self.__srsOL:
coodTrans = core.QgsCoordinateTransform(crsCanvas, self.__srsOL)
pntCenter = coodTrans.transform(pntCenter, core.QgsCoordinateTransform.ForwardTransform)
return tuple( [ pntCenter.x(),pntCenter.y() ] )
|
gpl-3.0
|
lobzik84/upravdom_web
|
public_html/assets/js/components/common/anchorTitle.js
|
776
|
class AnchorTitle {
constructor($element) {
this.$anchorTitle = $('<div class="anchorTitle"></div>');
this.$element = $element;
$('body').append(this.$anchorTitle);
this.$element.data('description', $element.attr('data-description'))
.removeAttr('title')
.on('mouseenter', () => {
this.show();
})
.on('mouseleave', () => {
this.hide();
});
}
show() {
const offset = this.$element.offset();
this.$anchorTitle.css({
top: `${(offset.top + this.$element.outerHeight() + 4)}px`,
left: `${offset.left}px`,
})
.html(this.$element.attr('data-description'))
.addClass('anchorTitle_show');
}
hide() {
this.$anchorTitle.removeClass('anchorTitle_show');
}
}
export default AnchorTitle;
|
gpl-3.0
|
dmitry-vlasov/mdl
|
src/mm/ast/source/mm_ast_source_Assertion.hpp
|
4426
|
/*****************************************************************************/
/* Project name: mm - decompiler from metamath to mdl */
/* File Name: mm_ast_source_Assertion.hpp */
/* Description: metamath assertion */
/* Copyright: (c) 2006-2009 Dmitri Vlasov */
/* Author: Dmitri Yurievich Vlasov, Novosibirsk, Russia */
/* Email: vlasov at academ.org */
/* URL: http://mathdevlanguage.sourceforge.net */
/* Modified by: */
/* License: GNU General Public License Version 3 */
/*****************************************************************************/
#pragma once
#include "interface/mm_interface.hpp"
#include "ast/mm_ast.dpp"
namespace mm {
namespace ast {
namespace source {
class Assertion : public mm :: source :: Assertion {
public :
Assertion
(
const Location&,
const value :: Label,
const vector :: Literal&,
mm :: source :: Block* const,
const mm :: source :: Comments*
);
virtual ~ Assertion();
// source :: Assertion interface
virtual void applyCheck (Stack* const) const;
virtual const mm :: target :: Step* applyTranslate (Stack* const) const;
virtual bool areDisjoined (const value :: Literal, const value :: Literal) const;
virtual void checkDisjoined (const mm :: source :: Assertion* const) const;
virtual bool newVariable (const value :: Literal) const;
virtual bool isAxiomatic() const = 0;
virtual bool isProvable() const = 0;
virtual bool isVerified() const = 0;
// object :: Expressive interface
virtual bool isEqual (const Expression* const) const;
virtual void assignTo (const Expression* const);
// object :: Labeled interface
virtual value :: Label getLabel() const;
// object :: Verifiable interface
virtual void check() const = 0;
// object :: Translatable interface
virtual const object :: Targetive* translate() const = 0;
virtual bool isBlock() const;
virtual bool isDisjoined() const;
virtual bool isFloating() const;
virtual bool isEssential() const;
// object :: Writable interface
virtual void write (String&) const = 0;
// object :: Object interface
virtual void commitSuicide() = 0;
virtual Size_t getVolume() const;
virtual Size_t getSizeOf() const;
protected :
// translator part
bool isStatement () const;
bool isDefinition () const;
bool isSuperType () const;
const mm :: target :: Variables* translateVariables() const;
const mm :: target :: Disjoineds* translateDisjoineds (const bool) const;
void translateDefinition (mm :: target :: Statement* const) const;
void translateHypothesis (mm :: target :: Statement* const) const;
void translateProposition (mm :: target :: Statement* const) const;
void translateTerm (mm :: target :: Syntactic* const) const;
const Location location_;
const value :: Label label_;
mutable const mm :: source :: Disjoined* disjoined_;
const mm :: source :: Hypothesis* const hypothesis_;
const mm :: source :: Comments* const comments_;
const mm :: Expression* proposition_;
private :
void initStatic() const;
// checker part
void computeVariables();
void computeDisjoineds() const;
void unify (Stack* const, const mm :: source :: Hypothesis* const) const;
void checkHypothesis (const mm :: source :: Hypothesis* const, const bool) const;
stack :: Line* pushPropositionCheck (Stack* const) const;
const mm :: target :: Step* pushPropositionTranslate (Stack* const) const;
vector :: Literal variables_;
static bool staticVolumeCounted_;
static mm :: Substitution* substitution_;
static mm :: Stack* localStack_;
enum {
INITIAL_LOCAL_STACK_CAPACITY = 32,
INITIAL_ARGUMENTS_CAPACITY = 32
};
// translator part
mm :: target :: Variables* translateVariables (const mm :: source :: Hypothesis* const) const;
mm :: target :: Disjoineds* translateDisjoineds
(
const mm :: source :: Disjoined* const,
const bool
) const;
void translateHypothesis (mm :: target :: Statement* const, const mm :: source :: Hypothesis* const) const;
static vector :: target :: Step* arguments_;
mutable const mm :: target :: Statement* statement_;
friend class auxiliary :: Volume;
};
}
}
}
#include "ast/source/mm_ast_source_Assertion.ipp"
|
gpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.