code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package com.lichkin.framework.springboot.controllers.impl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.lichkin.framework.bases.LKDatas;
import com.lichkin.framework.bases.annotations.WithOutLogin;
import com.lichkin.framework.springboot.controllers.LKController;
/**
* 页面跳转逻辑
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
@Controller
@RequestMapping(value = "/demo")
public class LKDemoController extends LKController {
/**
* 页面跳转
* @param requestDatas 请求参数,由框架自动解析请求的参数并注入。
* @param subUrl 子路径
* @return 页面路径,附带了请求参数及请求路径的相关信息。
*/
@WithOutLogin
@RequestMapping(value = "/{subUrl}.html", method = RequestMethod.GET)
public ModelAndView toGo(final LKDatas requestDatas, @PathVariable(value = "subUrl") final String subUrl) {
return getModelAndView(requestDatas);
}
}
| china-zhuangxuxin/LKFramework | lichkin-springboot-demos/lichkin-springboot-demo-web/src/main/java/com/lichkin/framework/springboot/controllers/impl/LKDemoController.java | Java | mit | 1,209 |
module.exports = {
"extends": "airbnb",
"parser": "babel-eslint",
"plugins": [
"react"
],
"rules": {
"react/prop-types": 0,
"react/jsx-boolean-value": 0,
"consistent-return": 0,
"guard-for-in": 0,
"no-use-before-define": 0,
"space-before-function-paren": [2, { "anonymous": "never", "named": "always" }]
}
};
| danieloliveira079/healthy-life-app-v1 | .eslintrc.js | JavaScript | mit | 351 |
package au.com.codeka.planetrender;
import java.util.Random;
import au.com.codeka.common.PerlinNoise;
import au.com.codeka.common.Vector2;
import au.com.codeka.common.Vector3;
/**
* This class takes a ray that's going in a certain direction and warps it based on a noise pattern. This is used
* to generate misshapen asteroid images, for example.
*/
public class RayWarper {
private NoiseGenerator mNoiseGenerator;
private double mWarpFactor;
public RayWarper(Template.WarpTemplate tmpl, Random rand) {
if (tmpl.getNoiseGenerator() == Template.WarpTemplate.NoiseGenerator.Perlin) {
mNoiseGenerator = new PerlinGenerator(tmpl, rand);
} else if (tmpl.getNoiseGenerator() == Template.WarpTemplate.NoiseGenerator.Spiral) {
mNoiseGenerator = new SpiralGenerator(tmpl, rand);
}
mWarpFactor = tmpl.getWarpFactor();
}
public void warp(Vector3 vec, double u, double v) {
mNoiseGenerator.warp(vec, u, v, mWarpFactor);
}
static abstract class NoiseGenerator {
protected double getNoise(double u, double v) {
return 0.0;
}
protected Vector3 getValue(double u, double v) {
double x = getNoise(u * 0.25, v * 0.25);
double y = getNoise(0.25 + u * 0.25, v * 0.25);
double z = getNoise(u * 0.25, 0.25 + v * 0.25);
return Vector3.pool.borrow().reset(x, y, z);
}
protected void warp(Vector3 vec, double u, double v, double factor) {
Vector3 warpVector = getValue(u, v);
warpVector.reset(warpVector.x * factor + (1.0 - factor),
warpVector.y * factor + (1.0 - factor),
warpVector.z * factor + (1.0 - factor));
vec.reset(vec.x * warpVector.x,
vec.y * warpVector.y,
vec.z * warpVector.z);
Vector3.pool.release(warpVector);
}
}
static class PerlinGenerator extends NoiseGenerator {
private PerlinNoise mNoise;
public PerlinGenerator(Template.WarpTemplate tmpl, Random rand) {
mNoise = new TemplatedPerlinNoise(tmpl.getParameter(Template.PerlinNoiseTemplate.class), rand);
}
@Override
public double getNoise(double u, double v) {
return mNoise.getNoise(u, v);
}
}
static class SpiralGenerator extends NoiseGenerator {
public SpiralGenerator(Template.WarpTemplate tmpl, Random rand) {
}
@Override
protected void warp(Vector3 vec, double u, double v, double factor) {
Vector2 uv = Vector2.pool.borrow().reset(u, v);
uv.rotate(factor * uv.length() * 2.0 * Math.PI * 2.0 / 360.0);
vec.reset(uv.x, -uv.y, 1.0);
Vector2.pool.release(uv);
}
}
}
| jife94/wwmmo | planet-render/src/au/com/codeka/planetrender/RayWarper.java | Java | mit | 2,860 |
<?php defined('SYSPATH') or die('No direct script access.');
class Jelly_Meta extends Jelly_Core_Meta {}
| loonies/kohana-jelly | classes/jelly/meta.php | PHP | mit | 106 |
//>>built
define("clipart/SpinInput",["dojo/_base/declare","clipart/_clipart"],function(_1,_2){
return _1("clipart.SpinInput",[_2],{});
});
| Bonome/pauline-desgrandchamp.com | lib/clipart/SpinInput.js | JavaScript | mit | 140 |
## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
import sys
from pubnub import PubnubTornado as Pubnub
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo'
secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo'
cipher_key = len(sys.argv) > 4 and sys.argv[4] or ''
ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False
## -----------------------------------------------------------------------
## Initiate Pubnub State
## -----------------------------------------------------------------------
pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key,
secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on)
channel = 'hello_world'
# Asynchronous usage
def callback(message):
print(message)
pubnub.here_now(channel, callback=callback, error=callback)
pubnub.start()
| teddywing/pubnub-python | python-tornado/examples/here-now.py | Python | mit | 1,031 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Common.Core;
using Microsoft.Common.Core.Logging;
using Microsoft.R.Common.Core.Output;
using static System.FormattableString;
namespace Microsoft.R.Host.Client.BrokerServices {
public class WebServer {
private static ConcurrentDictionary<int, WebServer> Servers { get; } = new ConcurrentDictionary<int, WebServer>();
private static object _serverLock = new object();
private readonly IRemoteUriWebService _remoteUriService;
private readonly string _baseAddress;
private readonly IActionLog _log;
private readonly IConsole _console;
private readonly string _name;
private HttpListener _listener;
public string LocalHost { get; }
public int LocalPort { get; private set; }
public string RemoteHost { get; }
public int RemotePort { get; }
private WebServer(string remoteHostIp, int remotePort, string baseAddress, string name, IActionLog log, IConsole console) {
_name = name.ToUpperInvariant();
_baseAddress = baseAddress;
_log = log;
_console = console;
LocalHost = IPAddress.Loopback.ToString();
RemoteHost = remoteHostIp;
RemotePort = remotePort;
_remoteUriService = new RemoteUriWebService(baseAddress, log, console);
}
public void Initialize(CancellationToken ct) {
Random r = new Random();
// if remote port is between 10000 and 32000, select a port in the same range.
// R Help uses ports in that range.
int localPortMin = (RemotePort >= 10000 && RemotePort <= 32000) ? 10000 : 49152;
int localPortMax = (RemotePort >= 10000 && RemotePort <= 32000) ? 32000 : 65535;
_console.WriteErrorLine(Resources.Info_RemoteWebServerStarting.FormatInvariant(_name));
while (true) {
ct.ThrowIfCancellationRequested();
_listener = new HttpListener();
LocalPort = r.Next(localPortMin, localPortMax);
_listener.Prefixes.Add(Invariant($"http://{LocalHost}:{LocalPort}/"));
try {
_listener.Start();
} catch (HttpListenerException) {
_listener.Close();
continue;
} catch (ObjectDisposedException) {
// Socket got closed
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name));
_console.WriteErrorLine(Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name));
throw new OperationCanceledException();
}
break;
}
try {
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort));
_console.WriteErrorLine(Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort));
_console.WriteErrorLine(Resources.Info_RemoteWebServerDetails.FormatInvariant(Environment.MachineName, LocalHost, LocalPort, _name, _baseAddress));
} catch {
}
}
private void Stop() {
try {
if (_listener.IsListening) {
_listener.Stop();
}
_listener.Close();
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_RemoteWebServerStopped.FormatInvariant(_name));
_console.WriteErrorLine(Resources.Info_RemoteWebServerStopped.FormatInvariant(_name));
} catch (Exception ex) when (!ex.IsCriticalException()) {
}
}
public static void Stop(int port) {
if (Servers.TryRemove(port, out WebServer server)) {
server.Stop();
}
}
public static void StopAll() {
var ports = Servers.Keys.AsArray();
foreach (var port in ports) {
Stop(port);
}
}
private async Task DoWorkAsync(CancellationToken ct = default(CancellationToken)) {
try {
while (_listener.IsListening) {
if (ct.IsCancellationRequested) {
_listener.Stop();
break;
}
HttpListenerContext context = await _listener.GetContextAsync();
string localUrl = $"{LocalHost}:{LocalPort}";
string remoteUrl = $"{RemoteHost}:{RemotePort}";
_remoteUriService.GetResponseAsync(context, localUrl, remoteUrl, ct).DoNotWait();
}
} catch(Exception ex) {
if (Servers.ContainsKey(RemotePort)) {
// Log only if we expect this web server to be running and it fails.
_log.WriteLine(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_RemoteWebServerFailed.FormatInvariant(_name, ex.Message));
_console.WriteErrorLine(Resources.Error_RemoteWebServerFailed.FormatInvariant(_name, ex.Message));
}
} finally {
Stop(RemotePort);
}
}
public static Task<string> CreateWebServerAndHandleUrlAsync(string remoteUrl, string baseAddress, string name, IActionLog log, IConsole console, CancellationToken ct = default(CancellationToken)) {
var remoteUri = new Uri(remoteUrl);
var localUri = new UriBuilder(remoteUri);
WebServer server;
lock (_serverLock) {
if (!Servers.TryGetValue(remoteUri.Port, out server)) {
server = new WebServer(remoteUri.Host, remoteUri.Port, baseAddress, name, log, console);
server.Initialize(ct);
Servers.TryAdd(remoteUri.Port, server);
}
}
server.DoWorkAsync(ct).DoNotWait();
localUri.Host = server.LocalHost;
localUri.Port = server.LocalPort;
return Task.FromResult(localUri.Uri.ToString());
}
}
}
| AlexanderSher/RTVS | src/Windows/Host/Client/Impl/BrokerServices/WebServer.cs | C# | mit | 6,593 |
<?php
/*
* Copyright 2014 Google 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.
*/
require_once realpath(dirname(__FILE__) . '/../../../autoload.php');
/**
* A blank storage class, for cases where caching is not
* required.
*/
class Google_Cache_Null extends Google_Cache_Abstract
{
public function __construct(Google_Client $client)
{
}
/**
* @inheritDoc
*/
public function get($key, $expiration = false)
{
return false;
}
/**
* @inheritDoc
*/
public function set($key, $value)
{
// Nop.
}
/**
* @inheritDoc
* @param String $key
*/
public function delete($key)
{
// Nop.
}
}
| prashantevolvus/crux | google/src/Google/Cache/Null.php | PHP | mit | 1,222 |
/**
* Created by jiangli on 15/1/6.
*/
"use strict";
var request = require('request');
var iconv = require('iconv-lite');
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;
/**
* [_parseYouku 解析优酷网]
* @param [type] $url [description]
* @return [type] [description]
*/
module.exports = function($url,callback){
var $matches = $url.match(/id\_([\w=]+)/);
if ($matches&&$matches.length>1){
return _getYouku($matches[1].trim(),callback);
}else{
return null;
}
}
function _getYouku($vid,callback){
var $base = "http://v.youku.com/player/getPlaylist/VideoIDS/";
var $blink = $base+$vid;
var $link = $blink+"/Pf/4/ctype/12/ev/1";
request($link, function(er, response,body) {
if (er)
return callback(er);
var $retval = body;
if($retval){
var $rs = JSON.parse($retval);
request($blink, function(er, response,body) {
if (er)
return callback(er);
var $data = {
'1080Phd3':[],
'超清hd2':[],
'高清mp4':[],
'高清flvhd':[],
'标清flv':[],
'高清3gphd':[],
'3gp':[]
};
var $bretval = body;
var $brs = JSON.parse($bretval);
var $rs_data = $rs.data[0];
var $brs_data = $brs.data[0];
if($rs_data.error){
return callback(null, $data['error'] = $rs_data.error);
}
var $streamtypes = $rs_data.streamtypes; //可以输出的视频清晰度
var $streamfileids = $rs_data.streamfileids;
var $seed = $rs_data.seed;
var $segs = $rs_data.segs;
var $ip = $rs_data.ip;
var $bsegs = $brs_data.segs;
var yk_e_result = yk_e('becaf9be', yk_na($rs_data.ep)).split('_');
var $sid = yk_e_result[0], $token = yk_e_result[1];
for(var $key in $segs){
if(in_array($key,$streamtypes)){
var $segs_key_val = $segs[$key];
for(var kk=0;kk<$segs_key_val.length;kk++){
var $v = $segs_key_val[kk];
var $no = $v.no.toString(16).toUpperCase(); //转换为16进制 大写
if($no.length == 1){
$no ="0"+$no; //no 为每段视频序号
}
//构建视频地址K值
var $_k = $v.k;
if ((!$_k || $_k == '') || $_k == '-1') {
$_k = $bsegs[$key][kk].k;
}
var $fileId = getFileid($streamfileids[$key],$seed);
$fileId = $fileId.substr(0,8)+$no+$fileId.substr(10);
var m0 = yk_e('bf7e5f01', $sid + '_' + $fileId + '_' + $token);
var m1 = yk_d(m0);
var iconv_result = iconv.decode(new Buffer(m1), 'UTF-8');
if(iconv_result!=""){
var $ep = urlencode(iconv_result);
var $typeArray = [];
$typeArray['flv']= 'flv';
$typeArray['mp4']= 'mp4';
$typeArray['hd2']= 'flv';
$typeArray['3gphd']= 'mp4';
$typeArray['3gp']= 'flv';
$typeArray['hd3']= 'flv';
//判断视频清晰度
var $sharpness = []; //清晰度 数组
$sharpness['flv']= '标清flv';
$sharpness['flvhd']= '高清flvhd';
$sharpness['mp4']= '高清mp4';
$sharpness['hd2']= '超清hd2';
$sharpness['3gphd']= '高清3gphd';
$sharpness['3gp']= '3gp';
$sharpness['hd3']= '1080Phd3';
var $fileType = $typeArray[$key];
$data[$sharpness[$key]][kk] = "http://k.youku.com/player/getFlvPath/sid/"+$sid+"_00/st/"+$fileType+"/fileid/"+$fileId+"?K="+$_k+"&hd=1&myp=0&ts="+((((($v['seconds']+'&ypp=0&ctype=12&ev=1&token=')+$token)+'&oip=')+$ip)+'&ep=')+$ep;
}
}
}
}
//返回 图片 标题 链接 时长 视频地址
$data['coverImg'] = $rs['data'][0]['logo'];
$data['title'] = $rs['data'][0]['title'];
$data['seconds'] = $rs['data'][0]['seconds'];
return callback(null,$data);
});
}else{
return callback(null,null);
}
})
}
function urlencode(str) {
str = (str + '').toString();
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/%20/g, '+');
};
function in_array(needle, haystack, argStrict) {
var key = '',
strict = !! argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
};
//start 获得优酷视频需要用到的方法
function getSid(){
var $sid = new Date().getTime()+(Math.random() * 9001+10000);
return $sid;
}
function getKey($key1,$key2){
var $a = parseInt($key1,16);
var $b = $a ^0xA55AA5A5;
var $b = $b.toString(16);
return $key2+$b;
}
function getFileid($fileId,$seed){
var $mixed = getMixString($seed);
var $ids = $fileId.replace(/(\**$)/g, "").split('*'); //去掉末尾的*号分割为数组
var $realId = "";
for (var $i=0;$i<$ids.length;$i++){
var $idx = $ids[$i];
$realId += $mixed.substr($idx,1);
}
return $realId;
}
function getMixString($seed){
var $mixed = "";
var $source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890";
var $len = $source.length;
for(var $i=0;$i<$len;$i++){
$seed = ($seed * 211 + 30031)%65536;
var $index = ($seed / 65536 * $source.length);
var $c = $source.substr($index,1);
$mixed += $c;
$source = $source.replace($c,"");
}
return $mixed;
}
function yk_d($a){
if (!$a) {
return '';
}
var $f = $a.length;
var $b = 0;
var $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var $c = ''; $b < $f;) {
var $e = charCodeAt($a, $b++) & 255;
if ($b == $f) {
$c += charAt($str, $e >> 2);
$c += charAt($str, ($e & 3) << 4);
$c += '==';
break;
}
var $g = charCodeAt($a, $b++);
if ($b == $f) {
$c += charAt($str, $e >> 2);
$c += charAt($str, ($e & 3) << 4 | ($g & 240) >> 4);
$c += charAt($str, ($g & 15) << 2);
$c += '=';
break;
}
var $h = charCodeAt($a, $b++);
$c += charAt($str, $e >> 2);
$c += charAt($str, ($e & 3) << 4 | ($g & 240) >> 4);
$c += charAt($str, ($g & 15) << 2 | ($h & 192) >> 6);
$c += charAt($str, $h & 63);
}
return $c;
}
function yk_na($a){
if (!$a) {
return '';
}
var $sz = '-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1';
var $h = $sz.split(',');
var $i = $a.length;
var $f = 0;
for (var $e = ''; $f < $i;) {
var $c;
do {
$c = $h[charCodeAt($a, $f++) & 255];
} while ($f < $i && -1 == $c);
if (-1 == $c) {
break;
}
var $b;
do {
$b = $h[charCodeAt($a, $f++) & 255];
} while ($f < $i && -1 == $b);
if (-1 == $b) {
break;
}
$e += String.fromCharCode($c << 2 | ($b & 48) >> 4);
do {
$c = charCodeAt($a, $f++) & 255;
if (61 == $c) {
return $e;
}
$c = $h[$c];
} while ($f < $i && -1 == $c);
if (-1 == $c) {
break;
}
$e += String.fromCharCode(($b & 15) << 4 | ($c & 60) >> 2);
do {
$b = charCodeAt($a, $f++) & 255;
if (61 == $b) {
return $e;
}
$b = $h[$b];
} while ($f < $i && -1 == $b);
if (-1 == $b) {
break;
}
$e += String.fromCharCode(($c & 3) << 6 | $b);
}
return $e;
}
function yk_e($a, $c){
var $b = [];
for (var $f = 0, $i, $e = '', $h = 0; 256 > $h; $h++) {
$b[$h] = $h;
}
for ($h = 0; 256 > $h; $h++) {
$f = (($f + $b[$h]) + charCodeAt($a, $h % $a.length)) % 256;
$i = $b[$h];
$b[$h] = $b[$f];
$b[$f] = $i;
}
for (var $q = ($f = ($h = 0)); $q < $c.length; $q++) {
$h = ($h + 1) % 256;
$f = ($f + $b[$h]) % 256;
$i = $b[$h];
$b[$h] = $b[$f];
$b[$f] = $i;
$e += String.fromCharCode(charCodeAt($c, $q) ^ $b[($b[$h] + $b[$f]) % 256]);
}
return $e;
}
function md5(str){
var shasum = crypto.createHash('md5');
shasum.update(str);
return shasum.digest('hex');
}
function charCodeAt($str, $index){
var $charCode = [];
var $key = md5($str);
$index = $index + 1;
if ($charCode[$key]) {
return $charCode[$key][$index];
}
$charCode[$key] = unpack('C*', $str);
return $charCode[$key][$index];
}
function charAt($str, $index){
return $str.substr($index, 1);
}
function unpack(format, data) {
var formatPointer = 0, dataPointer = 0, result = {}, instruction = '',
quantifier = '', label = '', currentData = '', i = 0, j = 0,
word = '', fbits = 0, ebits = 0, dataByteLength = 0;
var fromIEEE754 = function(bytes, ebits, fbits) {
// Bytes to bits
var bits = [];
for (var i = bytes.length; i; i -= 1) {
var m_byte = bytes[i - 1];
for (var j = 8; j; j -= 1) {
bits.push(m_byte % 2 ? 1 : 0); m_byte = m_byte >> 1;
}
}
bits.reverse();
var str = bits.join('');
// Unpack sign, exponent, fraction
var bias = (1 << (ebits - 1)) - 1;
var s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
var e = parseInt(str.substring(1, 1 + ebits), 2);
var f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
}
else if (e > 0) {
return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
}
else if (f !== 0) {
return s * Math.pow(2, -(bias-1)) * (f / Math.pow(2, fbits));
}
else {
return s * 0;
}
}
while (formatPointer < format.length) {
instruction = format.charAt(formatPointer);
// Start reading 'quantifier'
quantifier = '';
formatPointer++;
while ((formatPointer < format.length) &&
(format.charAt(formatPointer).match(/[\d\*]/) !== null)) {
quantifier += format.charAt(formatPointer);
formatPointer++;
}
if (quantifier === '') {
quantifier = '1';
}
// Start reading label
label = '';
while ((formatPointer < format.length) &&
(format.charAt(formatPointer) !== '/')) {
label += format.charAt(formatPointer);
formatPointer++;
}
if (format.charAt(formatPointer) === '/') {
formatPointer++;
}
// Process given instruction
switch (instruction) {
case 'a': // NUL-padded string
case 'A': // SPACE-padded string
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier);
dataPointer += quantifier;
var currentResult;
if (instruction === 'a') {
currentResult = currentData.replace(/\0+$/, '');
} else {
currentResult = currentData.replace(/ +$/, '');
}
result[label] = currentResult;
break;
case 'h': // Hex string, low nibble first
case 'H': // Hex string, high nibble first
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier);
dataPointer += quantifier;
if (quantifier > currentData.length) {
throw new Error('Warning: unpack(): Type ' + instruction +
': not enough input, need ' + quantifier);
}
currentResult = '';
for (i = 0; i < currentData.length; i++) {
word = currentData.charCodeAt(i).toString(16);
if (instruction === 'h') {
word = word[1] + word[0];
}
currentResult += word;
}
result[label] = currentResult;
break;
case 'c': // signed char
case 'C': // unsigned c
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier);
dataPointer += quantifier;
for (i = 0; i < currentData.length; i++) {
currentResult = currentData.charCodeAt(i);
if ((instruction === 'c') && (currentResult >= 128)) {
currentResult -= 256;
}
result[label + (quantifier > 1 ?
(i + 1) :
'')] = currentResult;
}
break;
case 'S': // unsigned short (always 16 bit, machine byte order)
case 's': // signed short (always 16 bit, machine byte order)
case 'v': // unsigned short (always 16 bit, little endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 2;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 2);
dataPointer += quantifier * 2;
for (i = 0; i < currentData.length; i += 2) {
// sum per word;
currentResult = ((currentData.charCodeAt(i + 1) & 0xFF) << 8) +
(currentData.charCodeAt(i) & 0xFF);
if ((instruction === 's') && (currentResult >= 32768)) {
currentResult -= 65536;
}
result[label + (quantifier > 1 ?
((i / 2) + 1) :
'')] = currentResult;
}
break;
case 'n': // unsigned short (always 16 bit, big endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 2;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 2);
dataPointer += quantifier * 2;
for (i = 0; i < currentData.length; i += 2) {
// sum per word;
currentResult = ((currentData.charCodeAt(i) & 0xFF) << 8) +
(currentData.charCodeAt(i + 1) & 0xFF);
result[label + (quantifier > 1 ?
((i / 2) + 1) :
'')] = currentResult;
}
break;
case 'i': // signed integer (machine dependent size and byte order)
case 'I': // unsigned integer (machine dependent size & byte order)
case 'l': // signed long (always 32 bit, machine byte order)
case 'L': // unsigned long (always 32 bit, machine byte order)
case 'V': // unsigned long (always 32 bit, little endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 4;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 4);
dataPointer += quantifier * 4;
for (i = 0; i < currentData.length; i += 4) {
currentResult =
((currentData.charCodeAt(i + 3) & 0xFF) << 24) +
((currentData.charCodeAt(i + 2) & 0xFF) << 16) +
((currentData.charCodeAt(i + 1) & 0xFF) << 8) +
((currentData.charCodeAt(i) & 0xFF));
result[label + (quantifier > 1 ?
((i / 4) + 1) :
'')] = currentResult;
}
break;
case 'N': // unsigned long (always 32 bit, little endian byte order)
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / 4;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * 4);
dataPointer += quantifier * 4;
for (i = 0; i < currentData.length; i += 4) {
currentResult =
((currentData.charCodeAt(i) & 0xFF) << 24) +
((currentData.charCodeAt(i + 1) & 0xFF) << 16) +
((currentData.charCodeAt(i + 2) & 0xFF) << 8) +
((currentData.charCodeAt(i + 3) & 0xFF));
result[label + (quantifier > 1 ?
((i / 4) + 1) :
'')] = currentResult;
}
break;
case 'f': //float
case 'd': //double
ebits = 8;
fbits = (instruction === 'f') ? 23 : 52;
dataByteLength = 4;
if (instruction === 'd') {
ebits = 11;
dataByteLength = 8;
}
if (quantifier === '*') {
quantifier = (data.length - dataPointer) / dataByteLength;
} else {
quantifier = parseInt(quantifier, 10);
}
currentData = data.substr(dataPointer, quantifier * dataByteLength);
dataPointer += quantifier * dataByteLength;
for (i = 0; i < currentData.length; i += dataByteLength) {
data = currentData.substr(i, dataByteLength);
var bytes = [];
for (j = data.length - 1; j >= 0; --j) {
bytes.push(data.charCodeAt(j));
}
result[label + (quantifier > 1 ?
((i / 4) + 1) :
'')] = fromIEEE754(bytes, ebits, fbits);
}
break;
case 'x': // NUL byte
case 'X': // Back up one byte
case '@': // NUL byte
if (quantifier === '*') {
quantifier = data.length - dataPointer;
} else {
quantifier = parseInt(quantifier, 10);
}
if (quantifier > 0) {
if (instruction === 'X') {
dataPointer -= quantifier;
} else {
if (instruction === 'x') {
dataPointer += quantifier;
} else {
dataPointer = quantifier;
}
}
}
break;
default:
throw new Error('Warning: unpack() Type ' + instruction +
': unknown format code');
}
}
return result;
} | jiangli373/nodeParseVideo | lib/youku.js | JavaScript | mit | 21,702 |
/*
* Copyright (c) 2011 Stephen A. Pratt
*
* 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.
*/
namespace org.critterai.interop
{
/// <summary>
/// Indicates how an object's unmanaged resources have been allocated and are managed.
/// </summary>
public enum AllocType : byte
{
/// <summary>
/// Unmanaged resources were allocated locally and must be freed locally.
/// </summary>
Local = 0,
/// <summary>
/// Unmanaged resources were allocated by an external library and a call must be made
/// to the library to free them.
/// </summary>
External = 1,
/// <summary>
/// Unmanaged resources were allocated and are managed by an external library. There is
/// no local responsiblity to directly free the resources.
/// </summary>
/// <remarks>
/// <para>
/// Objects of this type are usually allocated and owned by another unmanaged object. So
/// its resources are freed by its owner when its owner is freed.
/// </para>
/// </remarks>
ExternallyManaged = 2
}
}
| stevefsp/critterai | src/main/Assets/CAI/util/interop/AllocType.cs | C# | mit | 2,238 |
class Post < ActiveRecord::Base
validates :title, presence: true
validates :slug, presence: true, uniqueness: true
acts_as_url :title, :url_attribute => :slug
default_scope order('created_at desc')
def to_param
slug
end
def external?
!url.blank?
end
end
| chanman82/ChandlerCollins.com | app/models/post.rb | Ruby | mit | 280 |
# -*- coding: utf-8 -*-
import numbers
import numpy as np
from ..constants import BOLTZMANN_IN_MEV_K
from ..energy import Energy
class Analysis(object):
r"""Class containing methods for the Data class
Attributes
----------
detailed_balance_factor
Methods
-------
integrate
position
width
scattering_function
dynamic_susceptibility
estimate_background
get_keys
get_bounds
"""
@property
def detailed_balance_factor(self):
r"""Returns the detailed balance factor (sometimes called the Bose
factor)
Parameters
----------
None
Returns
-------
dbf : ndarray
The detailed balance factor (temperature correction)
"""
return 1. - np.exp(-self.Q[:, 3] / BOLTZMANN_IN_MEV_K / self.temp)
def integrate(self, bounds=None, background=None, hkle=True):
r"""Returns the integrated intensity within given bounds
Parameters
----------
bounds : bool, optional
A boolean expression representing the bounds inside which the
calculation will be performed
background : float or dict, optional
Default: None
hkle : bool, optional
If True, integrates only over h, k, l, e dimensions, otherwise
integrates over all dimensions in :py:attr:`.Data.data`
Returns
-------
result : float
The integrated intensity either over all data, or within
specified boundaries
"""
result = 0
for key in self.get_keys(hkle):
result += np.trapz(self.intensity[self.get_bounds(bounds)] - self.estimate_background(background),
np.squeeze(self.data[key][self.get_bounds(bounds)]))
return result
def position(self, bounds=None, background=None, hkle=True):
r"""Returns the position of a peak within the given bounds
Parameters
----------
bounds : bool, optional
A boolean expression representing the bounds inside which the
calculation will be performed
background : float or dict, optional
Default: None
hkle : bool, optional
If True, integrates only over h, k, l, e dimensions, otherwise
integrates over all dimensions in :py:attr:`.Data.data`
Returns
-------
result : tup
The result is a tuple with position in each dimension of Q,
(h, k, l, e)
"""
result = ()
for key in self.get_keys(hkle):
_result = 0
for key_integrate in self.get_keys(hkle):
_result += np.trapz(self.data[key][self.get_bounds(bounds)] *
(self.intensity[self.get_bounds(bounds)] - self.estimate_background(background)),
self.data[key_integrate][self.get_bounds(bounds)]) / self.integrate(bounds, background)
result += (np.squeeze(_result),)
if hkle:
return result
else:
return dict((key, value) for key, value in zip(self.get_keys(hkle), result))
def width(self, bounds=None, background=None, fwhm=False, hkle=True):
r"""Returns the mean-squared width of a peak within the given bounds
Parameters
----------
bounds : bool, optional
A boolean expression representing the bounds inside which the
calculation will be performed
background : float or dict, optional
Default: None
fwhm : bool, optional
If True, returns width in fwhm, otherwise in mean-squared width.
Default: False
hkle : bool, optional
If True, integrates only over h, k, l, e dimensions, otherwise
integrates over all dimensions in :py:attr:`.Data.data`
Returns
-------
result : tup
The result is a tuple with the width in each dimension of Q,
(h, k, l, e)
"""
result = ()
for key in self.get_keys(hkle):
_result = 0
for key_integrate in self.get_keys(hkle):
_result += np.trapz((self.data[key][self.get_bounds(bounds)] -
self.position(bounds, background, hkle=False)[key]) ** 2 *
(self.intensity[self.get_bounds(bounds)] - self.estimate_background(background)),
self.data[key_integrate][self.get_bounds(bounds)]) / self.integrate(bounds, background)
if fwhm:
result += (np.sqrt(np.squeeze(_result)) * 2. * np.sqrt(2. * np.log(2.)),)
else:
result += (np.squeeze(_result),)
if hkle:
return result
else:
return dict((key, value) for key, value in zip(self.get_keys(hkle), result))
def scattering_function(self, material, ei):
r"""Returns the neutron scattering function, i.e. the detector counts
scaled by :math:`4 \pi / \sigma_{\mathrm{tot}} * k_i/k_f`.
Parameters
----------
material : object
Definition of the material given by the :py:class:`.Material`
class
ei : float
Incident energy in meV
Returns
-------
counts : ndarray
The detector counts scaled by the total scattering cross section
and ki/kf
"""
ki = Energy(energy=ei).wavevector
kf = Energy(energy=ei - self.e).wavevector
return 4 * np.pi / material.total_scattering_cross_section * ki / kf * self.detector
def dynamic_susceptibility(self, material, ei):
r"""Returns the dynamic susceptibility
:math:`\chi^{\prime\prime}(\mathbf{Q},\hbar\omega)`
Parameters
----------
material : object
Definition of the material given by the :py:class:`.Material`
class
ei : float
Incident energy in meV
Returns
-------
counts : ndarray
The detector counts turned into the scattering function multiplied
by the detailed balance factor
"""
return self.scattering_function(material, ei) * self.detailed_balance_factor
def estimate_background(self, bg_params):
r"""Estimate the background according to ``type`` specified.
Parameters
----------
bg_params : dict
Input dictionary has keys 'type' and 'value'. Types are
* 'constant' : background is the constant given by 'value'
* 'percent' : background is estimated by the bottom x%, where x
is value
* 'minimum' : background is estimated as the detector counts
Returns
-------
background : float or ndarray
Value determined to be the background. Will return ndarray only if
`'type'` is `'constant'` and `'value'` is an ndarray
"""
if isinstance(bg_params, type(None)):
return 0
elif isinstance(bg_params, numbers.Number):
return bg_params
elif bg_params['type'] == 'constant':
return bg_params['value']
elif bg_params['type'] == 'percent':
inten = self.intensity[self.intensity >= 0.]
Npts = int(inten.size * (bg_params['value'] / 100.))
min_vals = inten[np.argsort(inten)[:Npts]]
background = np.average(min_vals)
return background
elif bg_params['type'] == 'minimum':
return min(self.intensity)
else:
return 0
def get_bounds(self, bounds):
r"""Generates a to_fit tuple if bounds is present in kwargs
Parameters
----------
bounds : dict
Returns
-------
to_fit : tuple
Tuple of indices
"""
if bounds is not None:
return np.where(bounds)
else:
return np.where(self.Q[:, 0])
def get_keys(self, hkle):
r"""Returns all of the Dictionary key names
Parameters
----------
hkle : bool
If True only returns keys for h,k,l,e, otherwise returns all keys
Returns
-------
keys : list
:py:attr:`.Data.data` dictionary keys
"""
if hkle:
return [key for key in self.data if key in self.Q_keys.values()]
else:
return [key for key in self.data if key not in self.data_keys.values()]
| neutronpy/neutronpy | neutronpy/data/analysis.py | Python | mit | 8,726 |
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.CSharp.Data.Handling
{
public class AddingDataToCells
{
public static void Run()
{
// ExStart:1
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Adding a string value to the cell
worksheet.Cells["A1"].PutValue("Hello World");
// Adding a double value to the cell
worksheet.Cells["A2"].PutValue(20.5);
// Adding an integer value to the cell
worksheet.Cells["A3"].PutValue(15);
// Adding a boolean value to the cell
worksheet.Cells["A4"].PutValue(true);
// Adding a date/time value to the cell
worksheet.Cells["A5"].PutValue(DateTime.Now);
// Setting the display format of the date
Style style = worksheet.Cells["A5"].GetStyle();
style.Number = 15;
worksheet.Cells["A5"].SetStyle(style);
// Saving the Excel file
workbook.Save(dataDir + "output.out.xls");
// ExEnd:1
}
}
}
| aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Data/Handling/AddingDataToCells.cs | C# | mit | 1,673 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* LICENSE:
* 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/>.
*
*
* @categories Games/Entertainment, Systems Administration
* @package Bright Game Panel
* @author warhawk3407 <warhawk3407@gmail.com> @NOSPAM
* @copyleft 2013
* @license GNU General Public License version 3.0 (GPLv3)
* @version (Release 0) DEVELOPER BETA 8
* @link http://www.bgpanel.net/
*/
$page = 'boxgamefile';
$tab = 3;
$isSummary = TRUE;
###
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$boxid = $_GET['id'];
}
else
{
exit('Error: BoxID error.');
}
###
$return = 'boxgamefile.php?id='.urlencode($boxid);
require("../configuration.php");
require("./include.php");
require_once("../includes/func.ssh2.inc.php");
require_once("../libs/phpseclib/Crypt/AES.php");
require_once("../libs/gameinstaller/gameinstaller.php");
$title = T_('Box Game File Repositories');
if (query_numrows( "SELECT `name` FROM `".DBPREFIX."box` WHERE `boxid` = '".$boxid."'" ) == 0)
{
exit('Error: BoxID is invalid.');
}
$rows = query_fetch_assoc( "SELECT * FROM `".DBPREFIX."box` WHERE `boxid` = '".$boxid."' LIMIT 1" );
$games = mysql_query( "SELECT * FROM `".DBPREFIX."game` ORDER BY `game`" );
$aes = new Crypt_AES();
$aes->setKeyLength(256);
$aes->setKey(CRYPT_KEY);
// Get SSH2 Object OR ERROR String
$ssh = newNetSSH2($rows['ip'], $rows['sshport'], $rows['login'], $aes->decrypt($rows['password']));
if (!is_object($ssh))
{
$_SESSION['msg1'] = T_('Connection Error!');
$_SESSION['msg2'] = $ssh;
$_SESSION['msg-type'] = 'error';
}
$gameInstaller = new GameInstaller( $ssh );
include("./bootstrap/header.php");
/**
* Notifications
*/
include("./bootstrap/notifications.php");
?>
<ul class="nav nav-tabs">
<li><a href="boxsummary.php?id=<?php echo $boxid; ?>"><?php echo T_('Summary'); ?></a></li>
<li><a href="boxprofile.php?id=<?php echo $boxid; ?>"><?php echo T_('Profile'); ?></a></li>
<li><a href="boxip.php?id=<?php echo $boxid; ?>"><?php echo T_('IP Addresses'); ?></a></li>
<li><a href="boxserver.php?id=<?php echo $boxid; ?>"><?php echo T_('Servers'); ?></a></li>
<li><a href="boxchart.php?id=<?php echo $boxid; ?>"><?php echo T_('Charts'); ?></a></li>
<li class="active"><a href="boxgamefile.php?id=<?php echo $boxid; ?>"><?php echo T_('Game File Repositories'); ?></a></li>
<li><a href="boxlog.php?id=<?php echo $boxid; ?>"><?php echo T_('Activity Logs'); ?></a></li>
</ul>
<div class="well">
<table id="gamefiles" class="zebra-striped">
<thead>
<tr>
<th><?php echo T_('Game'); ?></th>
<th><?php echo T_('Cache Directory'); ?></th>
<th><?php echo T_('Disk Usage'); ?></th>
<th><?php echo T_('Last Modification'); ?></th>
<th><?php echo T_('Status'); ?></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while ($rowsGames = mysql_fetch_assoc($games))
{
$repoCacheInfo = $gameInstaller->getCacheInfo( $rowsGames['cachedir'] );
$gameExists = $gameInstaller->gameExists( $rowsGames['game'] );
?>
<tr>
<td><?php echo htmlspecialchars($rowsGames['game'], ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($rowsGames['cachedir'], ENT_QUOTES); ?></td>
<td><?php if ($repoCacheInfo != FALSE) { echo htmlspecialchars($repoCacheInfo['size'], ENT_QUOTES); } else { echo T_('None'); } ?></td>
<td><?php if ($repoCacheInfo != FALSE) { echo @date('l | F j, Y | H:i', $repoCacheInfo['mtime']); } else { echo T_('Never'); } ?></td>
<td><?php
if ($gameExists == FALSE) {
echo "<span class=\"label\">".T_('Game Not Supported')."</span>";
}
else if ($repoCacheInfo == FALSE) {
echo "<span class=\"label label-warning\">".T_('No Cache')."</span>";
}
else if ($repoCacheInfo['status'] == 'Ready') {
echo "<span class=\"label label-success\">Ready</span>";
}
else if ($repoCacheInfo['status'] == 'Aborted') {
echo "<span class=\"label label-important\">Aborted</span>";
}
else {
echo "<span class=\"label label-info\">".htmlspecialchars($repoCacheInfo['status'], ENT_QUOTES)."</span>";
}
?></td>
<td>
<!-- Actions -->
<div style="text-align: center;">
<?php
if ($gameExists)
{
if ( ($repoCacheInfo == FALSE) || ($repoCacheInfo['status'] == 'Aborted') ) {
// No repo OR repo not ready
?>
<a class="btn btn-small" href="#" onclick="doRepoAction('<?php echo $boxid; ?>', '<?php echo $rowsGames['gameid']; ?>', 'makeRepo', '<?php echo T_('create a new cache repository for'); ?>', '<?php echo htmlspecialchars($rowsGames['game'], ENT_QUOTES); ?>')">
<i class="icon-download-alt <?php echo formatIcon(); ?>"></i>
</a>
<?php
}
if ( ($repoCacheInfo != FALSE) && ($repoCacheInfo['status'] != 'Aborted') && ($repoCacheInfo['status'] != 'Ready') ) {
// Operation in progress
?>
<a class="btn btn-small" href="#" onclick="doRepoAction('<?php echo $boxid; ?>', '<?php echo $rowsGames['gameid']; ?>', 'abortOperation', '<?php echo T_('abort current operation for repository'); ?>', '<?php echo htmlspecialchars($rowsGames['game'], ENT_QUOTES); ?>')">
<i class="icon-stop <?php echo formatIcon(); ?>"></i>
</a>
<?php
}
if ( $repoCacheInfo['status'] == 'Ready') {
// Cache Ready
?>
<a class="btn btn-small" href="#" onclick="doRepoAction('<?php echo $boxid; ?>', '<?php echo $rowsGames['gameid']; ?>', 'makeRepo', '<?php echo T_('refresh repository contents for'); ?>', '<?php echo htmlspecialchars($rowsGames['game'], ENT_QUOTES); ?>')">
<i class="icon-repeat <?php echo formatIcon(); ?>"></i>
</a>
<?php
}
}
?>
</div>
</td>
<td>
<!-- Drop Action -->
<div style="text-align: center;">
<?php
if ($gameExists)
{
if ( ($repoCacheInfo != FALSE) && ( ($repoCacheInfo['status'] == 'Aborted') || ($repoCacheInfo['status'] == 'Ready') ) ) {
// Repo exists AND no operation in progress
?>
<a class="btn btn-small" href="#" onclick="doRepoAction('<?php echo $boxid; ?>', '<?php echo $rowsGames['gameid']; ?>', 'deleteRepo', '<?php echo T_('remove cache repository for'); ?>', '<?php echo htmlspecialchars($rowsGames['game'], ENT_QUOTES); ?>')">
<i class="icon-trash <?php echo formatIcon(); ?>"></i>
</a>
<?php
}
}
?>
</div>
</td>
</tr>
<?php
}
?> </tbody>
</table>
<?php
if (mysql_num_rows($games) != 0)
{
?>
<script type="text/javascript">
$(document).ready(function() {
$("#gamefiles").tablesorter({
headers: {
5: {
sorter: false
},
6: {
sorter: false
}
},
sortList: [[0,0]]
});
});
<!-- -->
function doRepoAction(boxid, gameid, task, action, game)
{
if (confirm('<?php echo T_('Are you sure you want to'); ?> '+action+' '+game+' ?'))
{
window.location='boxprocess.php?boxid='+boxid+'&gameid='+gameid+'&task='+task;
}
}
</script>
<?php
}
unset($games);
?>
</div>
<?php
include("./bootstrap/footer.php");
?> | kinnngg/knightofsorrow.tk | bgp/admin/boxgamefile.php | PHP | mit | 7,705 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
// The function calculates center of gravity and the central second order moments
static void icvCompleteMomentState( CvMoments* moments )
{
double cx = 0, cy = 0;
double mu20, mu11, mu02;
assert( moments != 0 );
moments->inv_sqrt_m00 = 0;
if( fabs(moments->m00) > DBL_EPSILON )
{
double inv_m00 = 1. / moments->m00;
cx = moments->m10 * inv_m00;
cy = moments->m01 * inv_m00;
moments->inv_sqrt_m00 = std::sqrt( fabs(inv_m00) );
}
// mu20 = m20 - m10*cx
mu20 = moments->m20 - moments->m10 * cx;
// mu11 = m11 - m10*cy
mu11 = moments->m11 - moments->m10 * cy;
// mu02 = m02 - m01*cy
mu02 = moments->m02 - moments->m01 * cy;
moments->mu20 = mu20;
moments->mu11 = mu11;
moments->mu02 = mu02;
// mu30 = m30 - cx*(3*mu20 + cx*m10)
moments->mu30 = moments->m30 - cx * (3 * mu20 + cx * moments->m10);
mu11 += mu11;
// mu21 = m21 - cx*(2*mu11 + cx*m01) - cy*mu20
moments->mu21 = moments->m21 - cx * (mu11 + cx * moments->m01) - cy * mu20;
// mu12 = m12 - cy*(2*mu11 + cy*m10) - cx*mu02
moments->mu12 = moments->m12 - cy * (mu11 + cy * moments->m10) - cx * mu02;
// mu03 = m03 - cy*(3*mu02 + cy*m01)
moments->mu03 = moments->m03 - cy * (3 * mu02 + cy * moments->m01);
}
static void icvContourMoments( CvSeq* contour, CvMoments* moments )
{
int is_float = CV_SEQ_ELTYPE(contour) == CV_32FC2;
if( contour->total )
{
CvSeqReader reader;
double a00, a10, a01, a20, a11, a02, a30, a21, a12, a03;
double xi, yi, xi2, yi2, xi_1, yi_1, xi_12, yi_12, dxy, xii_1, yii_1;
int lpt = contour->total;
a00 = a10 = a01 = a20 = a11 = a02 = a30 = a21 = a12 = a03 = 0;
cvStartReadSeq( contour, &reader, 0 );
if( !is_float )
{
xi_1 = ((CvPoint*)(reader.ptr))->x;
yi_1 = ((CvPoint*)(reader.ptr))->y;
}
else
{
xi_1 = ((CvPoint2D32f*)(reader.ptr))->x;
yi_1 = ((CvPoint2D32f*)(reader.ptr))->y;
}
CV_NEXT_SEQ_ELEM( contour->elem_size, reader );
xi_12 = xi_1 * xi_1;
yi_12 = yi_1 * yi_1;
while( lpt-- > 0 )
{
if( !is_float )
{
xi = ((CvPoint*)(reader.ptr))->x;
yi = ((CvPoint*)(reader.ptr))->y;
}
else
{
xi = ((CvPoint2D32f*)(reader.ptr))->x;
yi = ((CvPoint2D32f*)(reader.ptr))->y;
}
CV_NEXT_SEQ_ELEM( contour->elem_size, reader );
xi2 = xi * xi;
yi2 = yi * yi;
dxy = xi_1 * yi - xi * yi_1;
xii_1 = xi_1 + xi;
yii_1 = yi_1 + yi;
a00 += dxy;
a10 += dxy * xii_1;
a01 += dxy * yii_1;
a20 += dxy * (xi_1 * xii_1 + xi2);
a11 += dxy * (xi_1 * (yii_1 + yi_1) + xi * (yii_1 + yi));
a02 += dxy * (yi_1 * yii_1 + yi2);
a30 += dxy * xii_1 * (xi_12 + xi2);
a03 += dxy * yii_1 * (yi_12 + yi2);
a21 +=
dxy * (xi_12 * (3 * yi_1 + yi) + 2 * xi * xi_1 * yii_1 +
xi2 * (yi_1 + 3 * yi));
a12 +=
dxy * (yi_12 * (3 * xi_1 + xi) + 2 * yi * yi_1 * xii_1 +
yi2 * (xi_1 + 3 * xi));
xi_1 = xi;
yi_1 = yi;
xi_12 = xi2;
yi_12 = yi2;
}
double db1_2, db1_6, db1_12, db1_24, db1_20, db1_60;
if( fabs(a00) > FLT_EPSILON )
{
if( a00 > 0 )
{
db1_2 = 0.5;
db1_6 = 0.16666666666666666666666666666667;
db1_12 = 0.083333333333333333333333333333333;
db1_24 = 0.041666666666666666666666666666667;
db1_20 = 0.05;
db1_60 = 0.016666666666666666666666666666667;
}
else
{
db1_2 = -0.5;
db1_6 = -0.16666666666666666666666666666667;
db1_12 = -0.083333333333333333333333333333333;
db1_24 = -0.041666666666666666666666666666667;
db1_20 = -0.05;
db1_60 = -0.016666666666666666666666666666667;
}
// spatial moments
moments->m00 = a00 * db1_2;
moments->m10 = a10 * db1_6;
moments->m01 = a01 * db1_6;
moments->m20 = a20 * db1_12;
moments->m11 = a11 * db1_24;
moments->m02 = a02 * db1_12;
moments->m30 = a30 * db1_20;
moments->m21 = a21 * db1_60;
moments->m12 = a12 * db1_60;
moments->m03 = a03 * db1_20;
icvCompleteMomentState( moments );
}
}
}
/****************************************************************************************\
* Spatial Raster Moments *
\****************************************************************************************/
template<typename T, typename WT, typename MT>
static void momentsInTile( const cv::Mat& img, double* moments )
{
cv::Size size = img.size();
int x, y;
MT mom[10] = {0,0,0,0,0,0,0,0,0,0};
for( y = 0; y < size.height; y++ )
{
const T* ptr = (const T*)(img.data + y*img.step);
WT x0 = 0, x1 = 0, x2 = 0;
MT x3 = 0;
for( x = 0; x < size.width; x++ )
{
WT p = ptr[x];
WT xp = x * p, xxp;
x0 += p;
x1 += xp;
xxp = xp * x;
x2 += xxp;
x3 += xxp * x;
}
WT py = y * x0, sy = y*y;
mom[9] += ((MT)py) * sy; // m03
mom[8] += ((MT)x1) * sy; // m12
mom[7] += ((MT)x2) * y; // m21
mom[6] += x3; // m30
mom[5] += x0 * sy; // m02
mom[4] += x1 * y; // m11
mom[3] += x2; // m20
mom[2] += py; // m01
mom[1] += x1; // m10
mom[0] += x0; // m00
}
for( x = 0; x < 10; x++ )
moments[x] = (double)mom[x];
}
#if CV_SSE2
template<> void momentsInTile<uchar, int, int>( const cv::Mat& img, double* moments )
{
typedef uchar T;
typedef int WT;
typedef int MT;
cv::Size size = img.size();
int x, y;
MT mom[10] = {0,0,0,0,0,0,0,0,0,0};
bool useSIMD = cv::checkHardwareSupport(CV_CPU_SSE2);
for( y = 0; y < size.height; y++ )
{
const T* ptr = img.ptr<T>(y);
int x0 = 0, x1 = 0, x2 = 0, x3 = 0, x = 0;
if( useSIMD )
{
__m128i qx_init = _mm_setr_epi16(0, 1, 2, 3, 4, 5, 6, 7);
__m128i dx = _mm_set1_epi16(8);
__m128i z = _mm_setzero_si128(), qx0 = z, qx1 = z, qx2 = z, qx3 = z, qx = qx_init;
for( ; x <= size.width - 8; x += 8 )
{
__m128i p = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*)(ptr + x)), z);
qx0 = _mm_add_epi32(qx0, _mm_sad_epu8(p, z));
__m128i px = _mm_mullo_epi16(p, qx);
__m128i sx = _mm_mullo_epi16(qx, qx);
qx1 = _mm_add_epi32(qx1, _mm_madd_epi16(p, qx));
qx2 = _mm_add_epi32(qx2, _mm_madd_epi16(p, sx));
qx3 = _mm_add_epi32(qx3, _mm_madd_epi16(px, sx));
qx = _mm_add_epi16(qx, dx);
}
int CV_DECL_ALIGNED(16) buf[4];
_mm_store_si128((__m128i*)buf, qx0);
x0 = buf[0] + buf[1] + buf[2] + buf[3];
_mm_store_si128((__m128i*)buf, qx1);
x1 = buf[0] + buf[1] + buf[2] + buf[3];
_mm_store_si128((__m128i*)buf, qx2);
x2 = buf[0] + buf[1] + buf[2] + buf[3];
_mm_store_si128((__m128i*)buf, qx3);
x3 = buf[0] + buf[1] + buf[2] + buf[3];
}
for( ; x < size.width; x++ )
{
WT p = ptr[x];
WT xp = x * p, xxp;
x0 += p;
x1 += xp;
xxp = xp * x;
x2 += xxp;
x3 += xxp * x;
}
WT py = y * x0, sy = y*y;
mom[9] += ((MT)py) * sy; // m03
mom[8] += ((MT)x1) * sy; // m12
mom[7] += ((MT)x2) * y; // m21
mom[6] += x3; // m30
mom[5] += x0 * sy; // m02
mom[4] += x1 * y; // m11
mom[3] += x2; // m20
mom[2] += py; // m01
mom[1] += x1; // m10
mom[0] += x0; // m00
}
for( x = 0; x < 10; x++ )
moments[x] = (double)mom[x];
}
#endif
typedef void (*CvMomentsInTileFunc)(const cv::Mat& img, double* moments);
CV_IMPL void cvMoments( const void* array, CvMoments* moments, int binary )
{
const int TILE_SIZE = 32;
int type, depth, cn, coi = 0;
CvMat stub, *mat = (CvMat*)array;
CvMomentsInTileFunc func = 0;
CvContour contourHeader;
CvSeq* contour = 0;
CvSeqBlock block;
double buf[TILE_SIZE*TILE_SIZE];
uchar nzbuf[TILE_SIZE*TILE_SIZE];
if( CV_IS_SEQ( array ))
{
contour = (CvSeq*)array;
if( !CV_IS_SEQ_POINT_SET( contour ))
CV_Error( CV_StsBadArg, "The passed sequence is not a valid contour" );
}
if( !moments )
CV_Error( CV_StsNullPtr, "" );
memset( moments, 0, sizeof(*moments));
if( !contour )
{
mat = cvGetMat( mat, &stub, &coi );
type = CV_MAT_TYPE( mat->type );
if( type == CV_32SC2 || type == CV_32FC2 )
{
contour = cvPointSeqFromMat(
CV_SEQ_KIND_CURVE | CV_SEQ_FLAG_CLOSED,
mat, &contourHeader, &block );
}
}
if( contour )
{
icvContourMoments( contour, moments );
return;
}
type = CV_MAT_TYPE( mat->type );
depth = CV_MAT_DEPTH( type );
cn = CV_MAT_CN( type );
cv::Size size = cvGetMatSize( mat );
if( cn > 1 && coi == 0 )
CV_Error( CV_StsBadArg, "Invalid image type" );
if( size.width <= 0 || size.height <= 0 )
return;
if( binary || depth == CV_8U )
func = momentsInTile<uchar, int, int>;
else if( depth == CV_16U )
func = momentsInTile<ushort, int, int64>;
else if( depth == CV_16S )
func = momentsInTile<short, int, int64>;
else if( depth == CV_32F )
func = momentsInTile<float, double, double>;
else if( depth == CV_64F )
func = momentsInTile<double, double, double>;
else
CV_Error( CV_StsUnsupportedFormat, "" );
cv::Mat src0(mat);
for( int y = 0; y < size.height; y += TILE_SIZE )
{
cv::Size tileSize;
tileSize.height = std::min(TILE_SIZE, size.height - y);
for( int x = 0; x < size.width; x += TILE_SIZE )
{
tileSize.width = std::min(TILE_SIZE, size.width - x);
cv::Mat src(src0, cv::Rect(x, y, tileSize.width, tileSize.height));
if( coi > 0 )
{
cv::Mat tmp(tileSize, depth, buf);
int pairs[] = {coi-1, 0};
cv::mixChannels(&src, 1, &tmp, 1, pairs, 1);
src = tmp;
}
if( binary )
{
cv::Mat tmp(tileSize, CV_8U, nzbuf);
cv::compare( src, 0, tmp, CV_CMP_NE );
src = tmp;
}
double mom[10];
func( src, mom );
if(binary)
{
double s = 1./255;
for( int k = 0; k < 10; k++ )
mom[k] *= s;
}
double xm = x * mom[0], ym = y * mom[0];
// accumulate moments computed in each tile
// + m00 ( = m00' )
moments->m00 += mom[0];
// + m10 ( = m10' + x*m00' )
moments->m10 += mom[1] + xm;
// + m01 ( = m01' + y*m00' )
moments->m01 += mom[2] + ym;
// + m20 ( = m20' + 2*x*m10' + x*x*m00' )
moments->m20 += mom[3] + x * (mom[1] * 2 + xm);
// + m11 ( = m11' + x*m01' + y*m10' + x*y*m00' )
moments->m11 += mom[4] + x * (mom[2] + ym) + y * mom[1];
// + m02 ( = m02' + 2*y*m01' + y*y*m00' )
moments->m02 += mom[5] + y * (mom[2] * 2 + ym);
// + m30 ( = m30' + 3*x*m20' + 3*x*x*m10' + x*x*x*m00' )
moments->m30 += mom[6] + x * (3. * mom[3] + x * (3. * mom[1] + xm));
// + m21 ( = m21' + x*(2*m11' + 2*y*m10' + x*m01' + x*y*m00') + y*m20')
moments->m21 += mom[7] + x * (2 * (mom[4] + y * mom[1]) + x * (mom[2] + ym)) + y * mom[3];
// + m12 ( = m12' + y*(2*m11' + 2*x*m01' + y*m10' + x*y*m00') + x*m02')
moments->m12 += mom[8] + y * (2 * (mom[4] + x * mom[2]) + y * (mom[1] + xm)) + x * mom[5];
// + m03 ( = m03' + 3*y*m02' + 3*y*y*m01' + y*y*y*m00' )
moments->m03 += mom[9] + y * (3. * mom[5] + y * (3. * mom[2] + ym));
}
}
icvCompleteMomentState( moments );
}
CV_IMPL void cvGetHuMoments( CvMoments * mState, CvHuMoments * HuState )
{
if( !mState || !HuState )
CV_Error( CV_StsNullPtr, "" );
double m00s = mState->inv_sqrt_m00, m00 = m00s * m00s, s2 = m00 * m00, s3 = s2 * m00s;
double nu20 = mState->mu20 * s2,
nu11 = mState->mu11 * s2,
nu02 = mState->mu02 * s2,
nu30 = mState->mu30 * s3,
nu21 = mState->mu21 * s3, nu12 = mState->mu12 * s3, nu03 = mState->mu03 * s3;
double t0 = nu30 + nu12;
double t1 = nu21 + nu03;
double q0 = t0 * t0, q1 = t1 * t1;
double n4 = 4 * nu11;
double s = nu20 + nu02;
double d = nu20 - nu02;
HuState->hu1 = s;
HuState->hu2 = d * d + n4 * nu11;
HuState->hu4 = q0 + q1;
HuState->hu6 = d * (q0 - q1) + n4 * t0 * t1;
t0 *= q0 - 3 * q1;
t1 *= 3 * q0 - q1;
q0 = nu30 - 3 * nu12;
q1 = 3 * nu21 - nu03;
HuState->hu3 = q0 * q0 + q1 * q1;
HuState->hu5 = q0 * t0 + q1 * t1;
HuState->hu7 = q1 * t0 - q0 * t1;
}
CV_IMPL double cvGetSpatialMoment( CvMoments * moments, int x_order, int y_order )
{
int order = x_order + y_order;
if( !moments )
CV_Error( CV_StsNullPtr, "" );
if( (x_order | y_order) < 0 || order > 3 )
CV_Error( CV_StsOutOfRange, "" );
return (&(moments->m00))[order + (order >> 1) + (order > 2) * 2 + y_order];
}
CV_IMPL double cvGetCentralMoment( CvMoments * moments, int x_order, int y_order )
{
int order = x_order + y_order;
if( !moments )
CV_Error( CV_StsNullPtr, "" );
if( (x_order | y_order) < 0 || order > 3 )
CV_Error( CV_StsOutOfRange, "" );
return order >= 2 ? (&(moments->m00))[4 + order * 3 + y_order] :
order == 0 ? moments->m00 : 0;
}
CV_IMPL double cvGetNormalizedCentralMoment( CvMoments * moments, int x_order, int y_order )
{
int order = x_order + y_order;
double mu = cvGetCentralMoment( moments, x_order, y_order );
double m00s = moments->inv_sqrt_m00;
while( --order >= 0 )
mu *= m00s;
return mu * m00s * m00s;
}
namespace cv
{
Moments::Moments()
{
m00 = m10 = m01 = m20 = m11 = m02 = m30 = m21 = m12 = m03 =
mu20 = mu11 = mu02 = mu30 = mu21 = mu12 = mu03 =
nu20 = nu11 = nu02 = nu30 = nu21 = nu12 = nu03 = 0.;
}
Moments::Moments( double _m00, double _m10, double _m01, double _m20, double _m11,
double _m02, double _m30, double _m21, double _m12, double _m03 )
{
m00 = _m00; m10 = _m10; m01 = _m01;
m20 = _m20; m11 = _m11; m02 = _m02;
m30 = _m30; m21 = _m21; m12 = _m12; m03 = _m03;
double cx = 0, cy = 0, inv_m00 = 0;
if( std::abs(m00) > DBL_EPSILON )
{
inv_m00 = 1./m00;
cx = m10*inv_m00; cy = m01*inv_m00;
}
mu20 = m20 - m10*cx;
mu11 = m11 - m10*cy;
mu02 = m02 - m01*cy;
mu30 = m30 - cx*(3*mu20 + cx*m10);
mu21 = m21 - cx*(2*mu11 + cx*m01) - cy*mu20;
mu12 = m12 - cy*(2*mu11 + cy*m10) - cx*mu02;
mu03 = m03 - cy*(3*mu02 + cy*m01);
double inv_sqrt_m00 = std::sqrt(std::abs(inv_m00));
double s2 = inv_m00*inv_m00, s3 = s2*inv_sqrt_m00;
nu20 = mu20*s2; nu11 = mu11*s2; nu02 = mu02*s2;
nu30 = mu30*s3; nu21 = mu21*s3; nu12 = mu12*s3; nu03 = mu03*s3;
}
Moments::Moments( const CvMoments& m )
{
*this = Moments(m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03);
}
Moments::operator CvMoments() const
{
CvMoments m;
m.m00 = m00; m.m10 = m10; m.m01 = m01;
m.m20 = m20; m.m11 = m11; m.m02 = m02;
m.m30 = m30; m.m21 = m21; m.m12 = m12; m.m03 = m03;
m.mu20 = mu20; m.mu11 = mu11; m.mu02 = mu02;
m.mu30 = mu30; m.mu21 = mu21; m.mu12 = mu12; m.mu03 = mu03;
double am00 = std::abs(m00);
m.inv_sqrt_m00 = am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0;
return m;
}
}
cv::Moments cv::moments( const Mat& array, bool binaryImage )
{
CvMoments om;
CvMat _array = array;
cvMoments(&_array, &om, binaryImage);
return om;
}
void cv::HuMoments( const Moments& m, double hu[7] )
{
double t0 = m.nu30 + m.nu12;
double t1 = m.nu21 + m.nu03;
double q0 = t0 * t0, q1 = t1 * t1;
double n4 = 4 * m.nu11;
double s = m.nu20 + m.nu02;
double d = m.nu20 - m.nu02;
hu[0] = s;
hu[1] = d * d + n4 * m.nu11;
hu[3] = q0 + q1;
hu[5] = d * (q0 - q1) + n4 * t0 * t1;
t0 *= q0 - 3 * q1;
t1 *= 3 * q0 - q1;
q0 = m.nu30 - 3 * m.nu12;
q1 = 3 * m.nu21 - m.nu03;
hu[2] = q0 * q0 + q1 * q1;
hu[4] = q0 * t0 + q1 * t1;
hu[6] = q1 * t0 - q0 * t1;
}
/* End of file. */
| eirTony/INDI1 | to/lang/OpenCV-2.2.0/modules/imgproc/src/moments.cpp | C++ | mit | 19,603 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive
{
[ExportInteractive(typeof(IExecuteInInteractiveCommandHandler), ContentTypeNames.CSharpContentType)]
internal sealed class CSharpInteractiveCommandHandler : InteractiveCommandHandler, IExecuteInInteractiveCommandHandler
{
private readonly CSharpVsInteractiveWindowProvider _interactiveWindowProvider;
private readonly ISendToInteractiveSubmissionProvider _sendToInteractiveSubmissionProvider;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpInteractiveCommandHandler(
CSharpVsInteractiveWindowProvider interactiveWindowProvider,
ISendToInteractiveSubmissionProvider sendToInteractiveSubmissionProvider,
IContentTypeRegistryService contentTypeRegistryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEditorOperationsFactoryService editorOperationsFactoryService)
: base(contentTypeRegistryService, editorOptionsFactoryService, editorOperationsFactoryService)
{
_interactiveWindowProvider = interactiveWindowProvider;
_sendToInteractiveSubmissionProvider = sendToInteractiveSubmissionProvider;
}
protected override ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider => _sendToInteractiveSubmissionProvider;
protected override IInteractiveWindow OpenInteractiveWindow(bool focus)
=> _interactiveWindowProvider.Open(instanceId: 0, focus: focus).InteractiveWindow;
}
}
| dotnet/roslyn | src/VisualStudio/CSharp/Impl/Interactive/CSharpInteractiveCommandHandler.cs | C# | mit | 2,251 |
class AddIndexes < ActiveRecord::Migration
def self.up
add_index :authentications, :user_id
add_index :games, :black_player_id
add_index :games, :white_player_id
add_index :games, :current_player_id
add_index :games, [:id, :current_player_id, :finished_at]
end
def self.down
remove_index :authentications, :user_id
remove_index :games, :black_player_id
remove_index :games, :white_player_id
remove_index :games, :current_player_id
remove_index :games, :column => [:id, :current_player_id, :finished_at]
end
end
| brownman/alone.in.the.galaxy | db/migrate/20101017234019_add_indexes.rb | Ruby | mit | 560 |
module.exports = {
getMeta: function(meta) {
var d = meta.metaDescription || meta.description || meta.Description;
if (d && d instanceof Array) {
d = d[0];
}
return {
description: d
}
}
}; | loklak/loklak_webclient | iframely/plugins/meta/description.js | JavaScript | mit | 264 |
/*
* Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $
*
*/
;(function($) {
// TODO rewrite as a widget, removing all the extra plugins
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
// TODO use event delegation
this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
// don't handle click events on children, eg. checkboxes
if ( this == event.target )
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea if not present
var hitarea = this.find("div." + CLASSES.hitarea);
if (!hitarea.length)
hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
})
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
this.data("toggler", toggler);
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() {
return this.href.toLowerCase() == location.href.toLowerCase();
});
if ( current.length ) {
// TODO update the open/closed classes
var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
if (settings.prerendered) {
// if prerendered is on, replicate the basic class swapping
items.filter("li")
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
}
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this;
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
$.treeview = {};
var CLASSES = ($.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
});
})(jQuery);
| rgeraads/phpDocumentor2 | data/templates/responsive-twig/js/jquery.treeview.js | JavaScript | mit | 8,204 |
!((document, $) => {
var clip = new Clipboard('.copy-button');
clip.on('success', function(e) {
$('.copied').show();
$('.copied').fadeOut(2000);
});
})(document, jQuery);
| cehfisher/a11y-style-guide | src/global/js/copy-button.js | JavaScript | mit | 186 |
var binary = require('node-pre-gyp');
var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);
var Stream = require('stream').Stream,
inherits = require('util').inherits;
function Snapshot() {}
Snapshot.prototype.getHeader = function() {
return {
typeId: this.typeId,
uid: this.uid,
title: this.title
}
}
/**
* @param {Snapshot} other
* @returns {Object}
*/
Snapshot.prototype.compare = function(other) {
var selfHist = nodesHist(this),
otherHist = nodesHist(other),
keys = Object.keys(selfHist).concat(Object.keys(otherHist)),
diff = {};
keys.forEach(function(key) {
if (key in diff) return;
var selfCount = selfHist[key] || 0,
otherCount = otherHist[key] || 0;
diff[key] = otherCount - selfCount;
});
return diff;
};
function ExportStream() {
Stream.Transform.call(this);
this._transform = function noTransform(chunk, encoding, done) {
done(null, chunk);
}
}
inherits(ExportStream, Stream.Transform);
/**
* @param {Stream.Writable|function} dataReceiver
* @returns {Stream|undefined}
*/
Snapshot.prototype.export = function(dataReceiver) {
dataReceiver = dataReceiver || new ExportStream();
var toStream = dataReceiver instanceof Stream,
chunks = toStream ? null : [];
function onChunk(chunk, len) {
if (toStream) dataReceiver.write(chunk);
else chunks.push(chunk);
}
function onDone() {
if (toStream) dataReceiver.end();
else dataReceiver(null, chunks.join(''));
}
this.serialize(onChunk, onDone);
return toStream ? dataReceiver : undefined;
};
function nodes(snapshot) {
var n = snapshot.nodesCount, i, nodes = [];
for (i = 0; i < n; i++) {
nodes[i] = snapshot.getNode(i);
}
return nodes;
};
function nodesHist(snapshot) {
var objects = {};
nodes(snapshot).forEach(function(node){
var key = node.type === "Object" ? node.name : node.type;
objects[key] = objects[node.name] || 0;
objects[key]++;
});
return objects;
};
function CpuProfile() {}
CpuProfile.prototype.getHeader = function() {
return {
typeId: this.typeId,
uid: this.uid,
title: this.title
}
}
CpuProfile.prototype.export = function(dataReceiver) {
dataReceiver = dataReceiver || new ExportStream();
var toStream = dataReceiver instanceof Stream;
var error, result;
try {
result = JSON.stringify(this);
} catch (err) {
error = err;
}
process.nextTick(function() {
if (toStream) {
if (error) {
dataReceiver.emit('error', error);
}
dataReceiver.end(result);
} else {
dataReceiver(error, result);
}
});
return toStream ? dataReceiver : undefined;
};
var startTime, endTime;
var activeProfiles = [];
var profiler = {
/*HEAP PROFILER API*/
get snapshots() { return binding.heap.snapshots; },
takeSnapshot: function(name, control) {
var snapshot = binding.heap.takeSnapshot.apply(null, arguments);
snapshot.__proto__ = Snapshot.prototype;
snapshot.title = name;
return snapshot;
},
getSnapshot: function(index) {
var snapshot = binding.heap.snapshots[index];
if (!snapshot) return;
snapshot.__proto__ = Snapshot.prototype;
return snapshot;
},
findSnapshot: function(uid) {
var snapshot = binding.heap.snapshots.filter(function(snapshot) {
return snapshot.uid == uid;
})[0];
if (!snapshot) return;
snapshot.__proto__ = Snapshot.prototype;
return snapshot;
},
deleteAllSnapshots: function () {
binding.heap.snapshots.forEach(function(snapshot) {
snapshot.delete();
});
},
startTrackingHeapObjects: binding.heap.startTrackingHeapObjects,
stopTrackingHeapObjects: binding.heap.stopTrackingHeapObjects,
getHeapStats: binding.heap.getHeapStats,
getObjectByHeapObjectId: binding.heap.getObjectByHeapObjectId,
/*CPU PROFILER API*/
get profiles() { return binding.cpu.profiles; },
startProfiling: function(name, recsamples) {
if (activeProfiles.length == 0 && typeof process._startProfilerIdleNotifier == "function")
process._startProfilerIdleNotifier();
name = name || "";
if (activeProfiles.indexOf(name) < 0)
activeProfiles.push(name)
startTime = Date.now();
binding.cpu.startProfiling(name, recsamples);
},
stopProfiling: function(name) {
var index = activeProfiles.indexOf(name);
if (name && index < 0)
return;
var profile = binding.cpu.stopProfiling(name);
endTime = Date.now();
profile.__proto__ = CpuProfile.prototype;
if (!profile.startTime) profile.startTime = startTime;
if (!profile.endTime) profile.endTime = endTime;
if (name)
activeProfiles.splice(index, 1);
else
activeProfiles.length = activeProfiles.length - 1;
if (activeProfiles.length == 0 && typeof process._stopProfilerIdleNotifier == "function")
process._stopProfilerIdleNotifier();
return profile;
},
getProfile: function(index) {
return binding.cpu.profiles[index];
},
findProfile: function(uid) {
var profile = binding.cpu.profiles.filter(function(profile) {
return profile.uid == uid;
})[0];
return profile;
},
deleteAllProfiles: function() {
binding.cpu.profiles.forEach(function(profile) {
profile.delete();
});
}
};
module.exports = profiler;
process.profiler = profiler;
| timmyg/pedalwagon-api | node_modules/node-inspector/node_modules/v8-profiler/v8-profiler.js | JavaScript | mit | 5,446 |
from itertools import imap, chain
def set_name(name, f):
try:
f.__pipetools__name__ = name
except (AttributeError, UnicodeEncodeError):
pass
return f
def get_name(f):
from pipetools.main import Pipe
pipetools_name = getattr(f, '__pipetools__name__', None)
if pipetools_name:
return pipetools_name() if callable(pipetools_name) else pipetools_name
if isinstance(f, Pipe):
return repr(f)
return f.__name__ if hasattr(f, '__name__') else repr(f)
def repr_args(*args, **kwargs):
return ', '.join(chain(
imap('{0!r}'.format, args),
imap('{0[0]}={0[1]!r}'.format, kwargs.iteritems())))
| katakumpo/pipetools | pipetools/debug.py | Python | mit | 672 |
using System;
using NPoco;
using Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;
namespace Umbraco.Cms.Infrastructure.Persistence.Dtos
{
[TableName(TableName)]
[ExplicitColumns]
[PrimaryKey("Id")]
internal class TwoFactorLoginDto
{
public const string TableName = Cms.Core.Constants.DatabaseSchema.Tables.TwoFactorLogin;
[Column("id")]
[PrimaryKeyColumn]
public int Id { get; set; }
[Column("userOrMemberKey")]
[Index(IndexTypes.NonClustered)]
public Guid UserOrMemberKey { get; set; }
[Column("providerName")]
[Length(400)]
[NullSetting(NullSetting = NullSettings.NotNull)]
[Index(IndexTypes.UniqueNonClustered, ForColumns = "providerName,userOrMemberKey", Name = "IX_" + TableName + "_ProviderName")]
public string ProviderName { get; set; }
[Column("secret")]
[Length(400)]
[NullSetting(NullSetting = NullSettings.NotNull)]
public string Secret { get; set; }
}
}
| marcemarc/Umbraco-CMS | src/Umbraco.Infrastructure/Persistence/Dtos/TwoFactorLoginDto.cs | C# | mit | 1,035 |
/**
* webdriverio
* https://github.com/Camme/webdriverio
*
* A WebDriver module for nodejs. Either use the super easy help commands or use the base
* Webdriver wire protocol commands. Its totally inspired by jellyfishs webdriver, but the
* goal is to make all the webdriver protocol items available, as near the original as possible.
*
* Copyright (c) 2013 Camilo Tapia <camilo.tapia@gmail.com>
* Licensed under the MIT license.
*
* Contributors:
* Dan Jenkins <dan.jenkins@holidayextras.com>
* Christian Bromann <mail@christian-bromann.com>
* Vincent Voyer <vincent@zeroload.net>
*/
import WebdriverIO from './lib/webdriverio'
import Multibrowser from './lib/multibrowser'
import ErrorHandler from './lib/utils/ErrorHandler'
import getImplementedCommands from './lib/helpers/getImplementedCommands'
import pkg from './package.json'
const IMPLEMENTED_COMMANDS = getImplementedCommands()
const VERSION = pkg.version
let remote = function (options = {}, modifier) {
/**
* initialise monad
*/
let wdio = WebdriverIO(options, modifier)
/**
* build prototype: commands
*/
for (let commandName of Object.keys(IMPLEMENTED_COMMANDS)) {
wdio.lift(commandName, IMPLEMENTED_COMMANDS[commandName])
}
let prototype = wdio()
prototype.defer.resolve()
return prototype
}
let multiremote = function (options) {
let multibrowser = new Multibrowser()
for (let browserName of Object.keys(options)) {
multibrowser.addInstance(
browserName,
remote(options[browserName], multibrowser.getInstanceModifier())
)
}
return remote(options, multibrowser.getModifier())
}
export { remote, multiremote, VERSION, ErrorHandler }
| testingbot/webdriverjs | index.js | JavaScript | mit | 1,748 |
<?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2015 Elcodi.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Component\Currency\Adapter\CurrencyExchangeRatesProvider;
use GuzzleHttp\Client;
use Elcodi\Component\Currency\Adapter\CurrencyExchangeRatesProvider\Interfaces\CurrencyExchangeRatesProviderAdapterInterface;
/**
* Class YahooFinanceProviderAdapter
*/
class YahooFinanceProviderAdapter implements CurrencyExchangeRatesProviderAdapterInterface
{
/**
* @var Client
*
* Client
*/
private $client;
/**
* Service constructor
*
* @param Client $client Guzzle client for requests
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* Get the latest exchange rates.
*
* This method will take in account always that the base currency is USD,
* and the result must complain this format.
*
* [
* "EUR" => "1,78342784",
* "YEN" => "0,67438268",
* ...
* ]
*
* @return array exchange rates
*/
public function getExchangeRates()
{
$exchangeRates = [];
$response = $this
->client
->get(
'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote',
[
'query' => [
'format' => 'json',
],
]
)
->json();
foreach ($response['list']['resources'] as $resource) {
$fields = $resource['resource']['fields'];
$symbol = str_replace('=X', '', $fields['symbol']);
$exchangeRates[$symbol] = (float) $fields['price'];
}
return $exchangeRates;
}
}
| shopery/elcodi | src/Elcodi/Component/Currency/Adapter/CurrencyExchangeRatesProvider/YahooFinanceProviderAdapter.php | PHP | mit | 2,097 |
package org.telegram.android.views.dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.AbsListView;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import org.telegram.android.R;
import org.telegram.android.TelegramApplication;
import org.telegram.android.log.Logger;
import org.telegram.android.ui.FontController;
import org.telegram.android.ui.TextUtil;
/**
* Created by ex3ndr on 15.11.13.
*/
public class ConversationListView extends ListView {
private static final String TAG = "ConversationListView";
private static final int DELTA = 26;
private static final long ANIMATION_DURATION = 200;
private static final int ACTIVATE_DELTA = 50;
private static final long UI_TIMEOUT = 900;
private TelegramApplication application;
private String visibleDate = null;
private int formattedVisibleDate = -1;
private int timeDivMeasure;
private String visibleDateNext = null;
private int formattedVisibleDateNext = -1;
private int timeDivMeasureNext;
private TextPaint timeDivPaint;
private Drawable serviceDrawable;
private Rect servicePadding;
private int offset;
private int oldHeight;
private long animationTime = 0;
private boolean isTimeVisible = false;
private Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
Logger.d(TAG, "notify");
if (msg.what == 0) {
if (isTimeVisible) {
isTimeVisible = false;
scrollDistance = 0;
animationTime = SystemClock.uptimeMillis();
}
invalidate();
} else if (msg.what == 1) {
isTimeVisible = true;
invalidate();
}
}
};
private int scrollDistance;
public ConversationListView(Context context) {
super(context);
init();
}
public ConversationListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ConversationListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public VisibleViewItem[] dump() {
int childCount = getChildCount();
int idCount = 0;
int headerCount = 0;
for (int i = 0; i < childCount; i++) {
int index = getFirstVisiblePosition() + i;
long id = getItemIdAtPosition(index);
if (id > 0) {
idCount++;
} else {
headerCount++;
}
}
VisibleViewItem[] res = new VisibleViewItem[idCount];
int resIndex = 0;
for (int i = 0; i < childCount; i++) {
View v = getChildAt(i);
int index = getFirstVisiblePosition() + i;
long id = getItemIdAtPosition(index);
if (id > 0) {
int top = ((v == null) ? 0 : v.getTop()) - getPaddingTop();
res[resIndex++] = new VisibleViewItem(index + headerCount, top, id);
}
}
return res;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
VisibleViewItem[] items = null;
if (changed) {
items = dump();
}
super.onLayout(changed, l, t, r, b);
if (changed) {
final int changeDelta = (b - t) - oldHeight;
if (changeDelta < 0 && items.length > 0) {
final VisibleViewItem item = items[items.length - 1];
setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta);
post(new Runnable() {
@Override
public void run() {
setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta);
}
});
}
}
oldHeight = b - t;
}
private void init() {
application = (TelegramApplication) getContext().getApplicationContext();
setOnScrollListener(new ScrollListener());
serviceDrawable = getResources().getDrawable(R.drawable.st_bubble_service);
servicePadding = new Rect();
serviceDrawable.getPadding(servicePadding);
timeDivPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
timeDivPaint.setTextSize(getSp(15));
timeDivPaint.setColor(0xffFFFFFF);
timeDivPaint.setTypeface(FontController.loadTypeface(getContext(), "regular"));
}
private void drawTime(Canvas canvas, int drawOffset, float alpha, boolean first) {
int w = first ? timeDivMeasure : timeDivMeasureNext;
serviceDrawable.setAlpha((int) (alpha * 255));
timeDivPaint.setAlpha((int) (alpha * 255));
serviceDrawable.setBounds(
getWidth() / 2 - w / 2 - servicePadding.left,
getPx(44 - 8) - serviceDrawable.getIntrinsicHeight() + drawOffset,
getWidth() / 2 + w / 2 + servicePadding.right,
getPx(44 - 8) + drawOffset);
serviceDrawable.draw(canvas);
canvas.drawText(first ? visibleDate : visibleDateNext, getWidth() / 2 - w / 2, getPx(44 - 17) + drawOffset, timeDivPaint);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
boolean isAnimated = false;
boolean isShown;
if (isTimeVisible) {
isShown = isTimeVisible;
} else {
isShown = SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION;
}
if (isShown) {
float animationRatio = 1.0f;
if (SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION) {
isAnimated = true;
animationRatio = (SystemClock.uptimeMillis() - animationTime) / ((float) ANIMATION_DURATION);
if (animationRatio > 1.0f) {
animationRatio = 1.0f;
}
if (!isTimeVisible) {
animationRatio = 1.0f - animationRatio;
}
}
int drawOffset = offset;
if (offset == 0) {
if (visibleDate != null) {
drawTime(canvas, drawOffset, 1.0f * animationRatio, true);
}
} else {
float ratio = Math.min(1.0f, Math.abs(offset / (float) getPx(DELTA)));
if (visibleDateNext != null) {
drawTime(canvas, drawOffset + getPx(DELTA), ratio * animationRatio, false);
}
if (visibleDate != null) {
drawTime(canvas, drawOffset, (1.0f - ratio) * animationRatio, true);
}
}
}
if (isAnimated) {
invalidate();
}
}
protected int getPx(float dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
protected int getSp(float sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
}
private class ScrollListener implements OnScrollListener {
private int state = SCROLL_STATE_IDLE;
private int lastVisibleItem = -1;
private int lastTop = 0;
private int lastScrollY = -1;
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_FLING || i == SCROLL_STATE_TOUCH_SCROLL) {
handler.removeMessages(0);
}
if (i == SCROLL_STATE_IDLE) {
handler.removeMessages(0);
handler.sendEmptyMessageDelayed(0, UI_TIMEOUT);
}
state = i;
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// if (lastScrollY == -1) {
// lastScrollY = getScrollY();
// } else if (lastScrollY != getScrollY()) {
// lastScrollY = getScrollY();
// application.getImageController().doPause();
// }
if (lastVisibleItem == -1 || lastVisibleItem != firstVisibleItem || state == SCROLL_STATE_IDLE) {
lastVisibleItem = firstVisibleItem;
lastTop = 0;
View view = getChildAt(0 + getHeaderViewsCount());
if (view != null) {
lastTop = view.getTop();
}
} else {
View view = getChildAt(0 + getHeaderViewsCount());
if (view != null) {
int topDelta = Math.abs(view.getTop() - lastTop);
lastTop = view.getTop();
scrollDistance += topDelta;
if (scrollDistance > getPx(ACTIVATE_DELTA) && !isTimeVisible) {
isTimeVisible = true;
animationTime = SystemClock.uptimeMillis();
handler.removeMessages(0);
}
}
}
// handler.removeMessages(0);
ListAdapter adapter = getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
adapter = ((HeaderViewListAdapter) adapter).getWrappedAdapter();
}
if (adapter instanceof ConversationAdapter) {
if (firstVisibleItem == 0) {
visibleDate = null;
visibleDateNext = null;
formattedVisibleDate = -1;
formattedVisibleDateNext = -1;
View view = getChildAt(1);
if (view != null) {
offset = Math.min(view.getTop() - getPx(DELTA), 0);
if (adapter.getCount() > 0) {
int date = ((ConversationAdapter) adapter).getItemDate(0);
visibleDateNext = TextUtil.formatDateLong(date);
timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext);
}
}
return;
}
int realFirstVisibleItem = firstVisibleItem - getHeaderViewsCount();
if (realFirstVisibleItem >= 0 && realFirstVisibleItem < adapter.getCount()) {
int date = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem);
int prevDate = date;
boolean isSameDays = true;
if (realFirstVisibleItem > 0 && realFirstVisibleItem + 2 < adapter.getCount()) {
prevDate = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem + 1);
isSameDays = TextUtil.areSameDays(prevDate, date);
}
if (isSameDays) {
offset = 0;
} else {
View view = getChildAt(firstVisibleItem - realFirstVisibleItem);
if (view != null) {
offset = Math.min(view.getTop() - getPx(DELTA), 0);
}
if (!TextUtil.areSameDays(prevDate, System.currentTimeMillis() / 1000)) {
if (!TextUtil.areSameDays(prevDate, formattedVisibleDateNext)) {
formattedVisibleDateNext = prevDate;
visibleDateNext = TextUtil.formatDateLong(prevDate);
timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext);
}
} else {
visibleDateNext = null;
formattedVisibleDateNext = -1;
}
}
if (!TextUtil.areSameDays(date, System.currentTimeMillis() / 1000)) {
if (!TextUtil.areSameDays(date, formattedVisibleDate)) {
formattedVisibleDate = date;
visibleDate = TextUtil.formatDateLong(date);
timeDivMeasure = (int) timeDivPaint.measureText(visibleDate);
}
} else {
visibleDate = null;
formattedVisibleDate = -1;
}
}
}
}
}
}
| ex3ndr/telegram | app/src/main/java/org/telegram/android/views/dialog/ConversationListView.java | Java | mit | 13,050 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreOverlay.h"
#include "OgreRoot.h"
#include "OgreSceneManager.h"
#include "OgreOverlayContainer.h"
#include "OgreCamera.h"
#include "OgreOverlayManager.h"
#include "OgreQuaternion.h"
#include "OgreVector3.h"
namespace Ogre {
//---------------------------------------------------------------------
Overlay::Overlay(const String& name) :
mName(name),
mRotate(0.0f),
mScrollX(0.0f), mScrollY(0.0f),
mScaleX(1.0f), mScaleY(1.0f),
mTransformOutOfDate(true), mTransformUpdated(true),
mZOrder(100), mVisible(false), mInitialised(false)
{
mRootNode = OGRE_NEW SceneNode(NULL);
}
//---------------------------------------------------------------------
Overlay::~Overlay()
{
// remove children
OGRE_DELETE mRootNode;
for (OverlayContainerList::iterator i = m2DElements.begin();
i != m2DElements.end(); ++i)
{
(*i)->_notifyParent(0, 0);
}
}
//---------------------------------------------------------------------
const String& Overlay::getName(void) const
{
return mName;
}
//---------------------------------------------------------------------
void Overlay::assignZOrders()
{
ushort zorder = static_cast<ushort>(mZOrder * 100.0f);
// Notify attached 2D elements
OverlayContainerList::iterator i, iend;
iend = m2DElements.end();
for (i = m2DElements.begin(); i != iend; ++i)
{
zorder = (*i)->_notifyZOrder(zorder);
}
}
//---------------------------------------------------------------------
void Overlay::setZOrder(ushort zorder)
{
// Limit to 650 since this is multiplied by 100 to pad out for containers
assert (zorder <= 650 && "Overlay Z-order cannot be greater than 650!");
mZOrder = zorder;
assignZOrders();
}
//---------------------------------------------------------------------
ushort Overlay::getZOrder(void) const
{
return (ushort)mZOrder;
}
//---------------------------------------------------------------------
bool Overlay::isVisible(void) const
{
return mVisible;
}
//---------------------------------------------------------------------
void Overlay::show(void)
{
mVisible = true;
if (!mInitialised)
{
initialise();
}
}
//---------------------------------------------------------------------
void Overlay::hide(void)
{
mVisible = false;
}
//---------------------------------------------------------------------
void Overlay::initialise(void)
{
OverlayContainerList::iterator i, iend;
iend = m2DElements.end();
for (i = m2DElements.begin(); i != m2DElements.end(); ++i)
{
(*i)->initialise();
}
mInitialised = true;
}
//---------------------------------------------------------------------
void Overlay::add2D(OverlayContainer* cont)
{
m2DElements.push_back(cont);
// Notify parent
cont->_notifyParent(0, this);
assignZOrders();
Matrix4 xform;
_getWorldTransforms(&xform);
cont->_notifyWorldTransforms(xform);
cont->_notifyViewport();
}
//---------------------------------------------------------------------
void Overlay::remove2D(OverlayContainer* cont)
{
m2DElements.remove(cont);
cont->_notifyParent(0, 0);
assignZOrders();
}
//---------------------------------------------------------------------
void Overlay::add3D(SceneNode* node)
{
mRootNode->addChild(node);
}
//---------------------------------------------------------------------
void Overlay::remove3D(SceneNode* node)
{
mRootNode->removeChild(node->getName());
}
//---------------------------------------------------------------------
void Overlay::clear(void)
{
mRootNode->removeAllChildren();
m2DElements.clear();
// Note no deallocation, memory handled by OverlayManager & SceneManager
}
//---------------------------------------------------------------------
void Overlay::setScroll(Real x, Real y)
{
mScrollX = x;
mScrollY = y;
mTransformOutOfDate = true;
mTransformUpdated = true;
}
//---------------------------------------------------------------------
Real Overlay::getScrollX(void) const
{
return mScrollX;
}
//---------------------------------------------------------------------
Real Overlay::getScrollY(void) const
{
return mScrollY;
}
//---------------------------------------------------------------------
OverlayContainer* Overlay::getChild(const String& name)
{
OverlayContainerList::iterator i, iend;
iend = m2DElements.end();
for (i = m2DElements.begin(); i != iend; ++i)
{
if ((*i)->getName() == name)
{
return *i;
}
}
return NULL;
}
//---------------------------------------------------------------------
void Overlay::scroll(Real xoff, Real yoff)
{
mScrollX += xoff;
mScrollY += yoff;
mTransformOutOfDate = true;
mTransformUpdated = true;
}
//---------------------------------------------------------------------
void Overlay::setRotate(const Radian& angle)
{
mRotate = angle;
mTransformOutOfDate = true;
mTransformUpdated = true;
}
//---------------------------------------------------------------------
void Overlay::rotate(const Radian& angle)
{
setRotate(mRotate + angle);
}
//---------------------------------------------------------------------
void Overlay::setScale(Real x, Real y)
{
mScaleX = x;
mScaleY = y;
mTransformOutOfDate = true;
mTransformUpdated = true;
}
//---------------------------------------------------------------------
Real Overlay::getScaleX(void) const
{
return mScaleX;
}
//---------------------------------------------------------------------
Real Overlay::getScaleY(void) const
{
return mScaleY;
}
//---------------------------------------------------------------------
void Overlay::_getWorldTransforms(Matrix4* xform) const
{
if (mTransformOutOfDate)
{
updateTransform();
}
*xform = mTransform;
}
//---------------------------------------------------------------------
void Overlay::_findVisibleObjects(Camera* cam, RenderQueue* queue)
{
OverlayContainerList::iterator i, iend;
if (OverlayManager::getSingleton().hasViewportChanged())
{
iend = m2DElements.end();
for (i = m2DElements.begin(); i != iend; ++i)
{
(*i)->_notifyViewport();
}
}
// update elements
if (mTransformUpdated)
{
Matrix4 xform;
_getWorldTransforms(&xform);
iend = m2DElements.end();
for (i = m2DElements.begin(); i != iend; ++i)
{
(*i)->_notifyWorldTransforms(xform);
}
mTransformUpdated = false;
}
if (mVisible)
{
// Add 3D elements
mRootNode->setPosition(cam->getDerivedPosition());
mRootNode->setOrientation(cam->getDerivedOrientation());
mRootNode->_update(true, false);
// Set up the default queue group for the objects about to be added
uint8 oldgrp = queue->getDefaultQueueGroup();
ushort oldPriority = queue-> getDefaultRenderablePriority();
queue->setDefaultQueueGroup(RENDER_QUEUE_OVERLAY);
queue->setDefaultRenderablePriority(static_cast<ushort>((mZOrder*100)-1));
mRootNode->_findVisibleObjects(cam, queue, NULL, true, false);
// Reset the group
queue->setDefaultQueueGroup(oldgrp);
queue->setDefaultRenderablePriority(oldPriority);
// Add 2D elements
iend = m2DElements.end();
for (i = m2DElements.begin(); i != iend; ++i)
{
(*i)->_update();
(*i)->_updateRenderQueue(queue);
}
}
}
//---------------------------------------------------------------------
void Overlay::updateTransform(void) const
{
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
Radian orientationRotation = Radian(0);
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
orientationRotation = Radian(OverlayManager::getSingleton().getViewportOrientationMode() * Math::HALF_PI);
#endif
Matrix3 rot3x3, scale3x3;
rot3x3.FromEulerAnglesXYZ(Radian(0), Radian(0), mRotate + orientationRotation);
scale3x3 = Matrix3::ZERO;
scale3x3[0][0] = mScaleX;
scale3x3[1][1] = mScaleY;
scale3x3[2][2] = 1.0f;
mTransform = Matrix4::IDENTITY;
mTransform = rot3x3 * scale3x3;
mTransform.setTrans(Vector3(mScrollX, mScrollY, 0));
mTransformOutOfDate = false;
}
//---------------------------------------------------------------------
OverlayElement* Overlay::findElementAt(Real x, Real y)
{
OverlayElement* ret = NULL;
int currZ = -1;
OverlayContainerList::iterator i, iend;
iend = m2DElements.end();
for (i = m2DElements.begin(); i != iend; ++i)
{
int z = (*i)->getZOrder();
if (z > currZ)
{
OverlayElement* elementFound = (*i)->findElementAt(x,y);
if(elementFound)
{
currZ = elementFound->getZOrder();
ret = elementFound;
}
}
}
return ret;
}
}
| xsilium-frameworks/xsilium-engine | Library/Ogre/Components/Overlay/src/OgreOverlay.cpp | C++ | mit | 11,191 |
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import * as React from 'react';
import PropTypes from 'prop-types';
import { Transition } from 'react-transition-group';
import useTheme from '../styles/useTheme';
import { reflow, getTransitionProps } from '../transitions/utils';
import useForkRef from '../utils/useForkRef';
function getScale(value) {
return `scale(${value}, ${value ** 2})`;
}
const styles = {
entering: {
opacity: 1,
transform: getScale(1)
},
entered: {
opacity: 1,
transform: 'none'
}
};
/**
* The Grow transition is used by the [Tooltip](/components/tooltips/) and
* [Popover](/components/popover/) components.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
const Grow = React.forwardRef(function Grow(props, ref) {
const {
children,
in: inProp,
onEnter,
onExit,
style,
timeout = 'auto'
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]);
const timer = React.useRef();
const autoTimeout = React.useRef();
const handleRef = useForkRef(children.ref, ref);
const theme = useTheme();
const handleEnter = (node, isAppearing) => {
reflow(node); // So the animation always start from the start.
const {
duration: transitionDuration,
delay
} = getTransitionProps({
style,
timeout
}, {
mode: 'enter'
});
let duration;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
autoTimeout.current = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [theme.transitions.create('opacity', {
duration,
delay
}), theme.transitions.create('transform', {
duration: duration * 0.666,
delay
})].join(',');
if (onEnter) {
onEnter(node, isAppearing);
}
};
const handleExit = node => {
const {
duration: transitionDuration,
delay
} = getTransitionProps({
style,
timeout
}, {
mode: 'exit'
});
let duration;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
autoTimeout.current = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [theme.transitions.create('opacity', {
duration,
delay
}), theme.transitions.create('transform', {
duration: duration * 0.666,
delay: delay || duration * 0.333
})].join(',');
node.style.opacity = '0';
node.style.transform = getScale(0.75);
if (onExit) {
onExit(node);
}
};
const addEndListener = (_, next) => {
if (timeout === 'auto') {
timer.current = setTimeout(next, autoTimeout.current || 0);
}
};
React.useEffect(() => {
return () => {
clearTimeout(timer.current);
};
}, []);
return /*#__PURE__*/React.createElement(Transition, _extends({
appear: true,
in: inProp,
onEnter: handleEnter,
onExit: handleExit,
addEndListener: addEndListener,
timeout: timeout === 'auto' ? null : timeout
}, other), (state, childProps) => {
return React.cloneElement(children, _extends({
style: _extends({
opacity: 0,
transform: getScale(0.75),
visibility: state === 'exited' && !inProp ? 'hidden' : undefined
}, styles[state], {}, style, {}, children.props.style),
ref: handleRef
}, childProps));
});
});
process.env.NODE_ENV !== "production" ? Grow.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A single child content element.
*/
children: PropTypes.element,
/**
* If `true`, show the component; triggers the enter or exit animation.
*/
in: PropTypes.bool,
/**
* @ignore
*/
onEnter: PropTypes.func,
/**
* @ignore
*/
onExit: PropTypes.func,
/**
* @ignore
*/
style: PropTypes.object,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
*
* Set to 'auto' to automatically calculate transition time based on height.
*/
timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({
appear: PropTypes.number,
enter: PropTypes.number,
exit: PropTypes.number
})])
} : void 0;
Grow.muiSupportAuto = true;
export default Grow; | cdnjs/cdnjs | ajax/libs/material-ui/4.9.9/es/Grow/Grow.js | JavaScript | mit | 4,874 |
import * as React from 'react';
declare class JqxGrid extends React.PureComponent<IGridProps, IState> {
protected static getDerivedStateFromProps(props: IGridProps, state: IState): null | IState;
private _jqx;
private _id;
private _componentSelector;
constructor(props: IGridProps);
componentDidMount(): void;
componentDidUpdate(): void;
render(): React.ReactNode;
setOptions(options: IGridProps): void;
getOptions(option: string): any;
autoresizecolumns(type?: string): void;
autoresizecolumn(dataField: string, type?: string): void;
beginupdate(): void;
clear(): void;
createChart(type: string, dataSource?: any): void;
destroy(): void;
endupdate(): void;
ensurerowvisible(rowBoundIndex: number): void;
focus(): void;
getcolumnindex(dataField: string): number;
getcolumn(dataField: string): IGridGetColumn;
getcolumnproperty(dataField: string, propertyName: string): any;
getrowid(rowBoundIndex: number): string;
getrowdata(rowBoundIndex: number): any;
getrowdatabyid(rowID: string): any;
getrowboundindexbyid(rowID: string): number;
getrowboundindex(rowDisplayIndex: number): number;
getrows(): any[];
getboundrows(): any[];
getdisplayrows(): any[];
getdatainformation(): IGridGetDataInformation;
getsortinformation(): IGridGetSortInformation;
getpaginginformation(): IGridGetPagingInformation;
hidecolumn(dataField: string): void;
hideloadelement(): void;
hiderowdetails(rowBoundIndex: number): void;
iscolumnvisible(dataField: string): boolean;
iscolumnpinned(dataField: string): boolean;
localizestrings(localizationobject: IGridLocalizationobject): void;
pincolumn(dataField: string): void;
refreshdata(): void;
refresh(): void;
renderWidget(): void;
scrolloffset(top: number, left: number): void;
scrollposition(): IGridScrollPosition;
showloadelement(): void;
showrowdetails(rowBoundIndex: number): void;
setcolumnindex(dataField: string, index: number): void;
setcolumnproperty(dataField: string, propertyName: any, propertyValue: any): void;
showcolumn(dataField: string): void;
unpincolumn(dataField: string): void;
updatebounddata(type?: any): void;
updating(): boolean;
getsortcolumn(): string;
removesort(): void;
sortby(dataField: string, sortOrder: string): void;
addgroup(dataField: string): void;
cleargroups(): void;
collapsegroup(group: number | string): void;
collapseallgroups(): void;
expandallgroups(): void;
expandgroup(group: number | string): void;
getrootgroupscount(): number;
getgroup(groupIndex: number): IGridGetGroup;
insertgroup(groupIndex: number, dataField: string): void;
iscolumngroupable(): boolean;
removegroupat(groupIndex: number): void;
removegroup(dataField: string): void;
addfilter(dataField: string, filterGroup: any, refreshGrid?: boolean): void;
applyfilters(): void;
clearfilters(): void;
getfilterinformation(): any;
getcolumnat(index: number): any;
removefilter(dataField: string, refreshGrid: boolean): void;
refreshfilterrow(): void;
gotopage(pagenumber: number): void;
gotoprevpage(): void;
gotonextpage(): void;
addrow(rowIds: any, data: any, rowPosition?: any): void;
begincelledit(rowBoundIndex: number, dataField: string): void;
beginrowedit(rowBoundIndex: number): void;
closemenu(): void;
deleterow(rowIds: string | number | Array<number | string>): void;
endcelledit(rowBoundIndex: number, dataField: string, confirmChanges: boolean): void;
endrowedit(rowBoundIndex: number, confirmChanges: boolean): void;
getcell(rowBoundIndex: number, datafield: string): IGridGetCell;
getcellatposition(left: number, top: number): IGridGetCell;
getcelltext(rowBoundIndex: number, dataField: string): string;
getcelltextbyid(rowID: string, dataField: string): string;
getcellvaluebyid(rowID: string, dataField: string): any;
getcellvalue(rowBoundIndex: number, dataField: string): any;
isBindingCompleted(): boolean;
openmenu(dataField: string): void;
setcellvalue(rowBoundIndex: number, dataField: string, value: any): void;
setcellvaluebyid(rowID: string, dataField: string, value: any): void;
showvalidationpopup(rowBoundIndex: number, dataField: string, validationMessage: string): void;
updaterow(rowIds: string | number | Array<number | string>, data: any): void;
clearselection(): void;
getselectedrowindex(): number;
getselectedrowindexes(): number[];
getselectedcell(): IGridGetSelectedCell;
getselectedcells(): IGridGetSelectedCell[];
selectcell(rowBoundIndex: number, dataField: string): void;
selectallrows(): void;
selectrow(rowBoundIndex: number): void;
unselectrow(rowBoundIndex: number): void;
unselectcell(rowBoundIndex: number, dataField: string): void;
getcolumnaggregateddata(dataField: string, aggregates: any[]): string;
refreshaggregates(): void;
renderaggregates(): void;
exportdata(dataType: string, fileName?: string, exportHeader?: boolean, rows?: number[], exportHiddenColumns?: boolean, serverURL?: string, charSet?: string): any;
exportview(dataType: string, fileName?: string): any;
openColumnChooser(columns?: any, header?: string): void;
getstate(): IGridGetState;
loadstate(stateobject: any): void;
savestate(): IGridGetState;
private _manageProps;
private _wireEvents;
}
export default JqxGrid;
export declare const jqx: any;
export declare const JQXLite: any;
interface IState {
lastProps: object;
}
export interface IGridCharting {
appendTo?: string;
colorScheme?: string;
dialog?: (width: number, height: number, header: string, position: any, enabled: boolean) => void;
formatSettings?: any;
ready?: any;
}
export interface IGridColumn {
text?: string;
datafield?: string;
displayfield?: string;
threestatecheckbox?: boolean;
sortable?: boolean;
filterable?: boolean;
filter?: (cellValue?: any, rowData?: any, dataField?: string, filterGroup?: any, defaultFilterResult?: any) => any;
buttonclick?: (row: number) => void;
hideable?: boolean;
hidden?: boolean;
groupable?: boolean;
menu?: boolean;
exportable?: boolean;
columngroup?: string;
enabletooltips?: boolean;
columntype?: 'number' | 'checkbox' | 'button' | 'numberinput' | 'dropdownlist' | 'combobox' | 'datetimeinput' | 'textbox' | 'rating' | 'progressbar' | 'template' | 'custom';
renderer?: (defaultText?: string, alignment?: string, height?: number) => string;
rendered?: (columnHeaderElement?: any) => void;
cellsrenderer?: (row?: number, columnfield?: string, value?: any, defaulthtml?: string, columnproperties?: any, rowdata?: any) => string;
aggregatesrenderer?: (aggregates?: any, column?: any, element?: any, summaryData?: any) => string;
validation?: (cell?: any, value?: number) => any;
createwidget?: (row: any, column: any, value: string, cellElement: any) => void;
initwidget?: (row: number, column: string, value: string, cellElement: any) => void;
createfilterwidget?: (column: any, htmlElement: HTMLElement, editor: any) => void;
createfilterpanel?: (datafield: string, filterPanel: any) => void;
initeditor?: (row: number, cellvalue: any, editor: any, celltext: any, pressedChar: string, callback: any) => void;
createeditor?: (row: number, cellvalue: any, editor: any, celltext: any, cellwidth: any, cellheight: any) => void;
destroyeditor?: (row: number, callback: any) => void;
geteditorvalue?: (row: number, cellvalue: any, editor: any) => any;
cellbeginedit?: (row: number, datafield: string, columntype: string, value: any) => boolean;
cellendedit?: (row: number, datafield: string, columntype: string, oldvalue: any, newvalue: any) => boolean;
cellvaluechanging?: (row: number, datafield: string, columntype: string, oldvalue: any, newvalue: any) => string | void;
createeverpresentrowwidget?: (datafield: string, htmlElement: HTMLElement, popup: any, addRowCallback: any) => any;
initeverpresentrowwidget?: (datafield: string, htmlElement: HTMLElement, popup: any) => void;
reseteverpresentrowwidgetvalue?: (datafield: string, htmlElement: HTMLElement) => void;
geteverpresentrowwidgetvalue?: (datafield: string, htmlElement: HTMLElement) => any;
destroyeverpresentrowwidget?: (htmlElement: HTMLElement) => void;
validateeverpresentrowwidgetvalue?: (datafield: string, value: any, rowValues: any) => boolean | object;
cellsformat?: string;
cellclassname?: any;
aggregates?: any;
align?: 'left' | 'center' | 'right';
cellsalign?: 'left' | 'center' | 'right';
width?: number | string;
minwidth?: any;
maxwidth?: any;
resizable?: boolean;
draggable?: boolean;
editable?: boolean;
classname?: string;
pinned?: boolean;
nullable?: boolean;
filteritems?: any;
filterdelay?: number;
filtertype?: 'textbox' | 'input' | 'checkedlist' | 'list' | 'number' | 'bool' | 'date' | 'range' | 'custom';
filtercondition?: 'EMPTY' | 'NOT_EMPTY' | 'CONTAINS' | 'CONTAINS_CASE_SENSITIVE' | 'DOES_NOT_CONTAIN' | 'DOES_NOT_CONTAIN_CASE_SENSITIVE' | 'STARTS_WITH' | 'STARTS_WITH_CASE_SENSITIVE' | 'ENDS_WITH' | 'ENDS_WITH_CASE_SENSITIVE' | 'EQUAL' | 'EQUAL_CASE_SENSITIVE' | 'NULL' | 'NOT_NULL' | 'EQUAL' | 'NOT_EQUAL' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'NULL' | 'NOT_NULL';
}
export interface IGridSourceDataFields {
name?: string;
type?: 'string' | 'date' | 'int' | 'float' | 'number' | 'bool';
format?: string;
map?: string;
id?: string;
text?: string;
source?: any[];
}
export interface IGridSource {
url?: string;
data?: any;
localdata?: any;
datatype?: 'xml' | 'json' | 'jsonp' | 'tsv' | 'csv' | 'local' | 'array' | 'observablearray';
type?: 'GET' | 'POST';
id?: string;
root?: string;
record?: string;
datafields?: IGridSourceDataFields[];
pagenum?: number;
pagesize?: number;
pager?: (pagenum?: number, pagesize?: number, oldpagenum?: number) => any;
sortcolumn?: string;
sortdirection?: 'asc' | 'desc';
sort?: (column?: any, direction?: any) => void;
filter?: (filters?: any, recordsArray?: any) => void;
addrow?: (rowid?: any, rowdata?: any, position?: any, commit?: boolean) => void;
deleterow?: (rowid?: any, commit?: boolean) => void;
updaterow?: (rowid?: any, newdata?: any, commit?: any) => void;
processdata?: (data: any) => void;
formatdata?: (data: any) => any;
async?: boolean;
totalrecords?: number;
unboundmode?: boolean;
}
export interface IGridGetColumn {
datafield?: string;
displayfield?: string;
text?: string;
sortable?: boolean;
filterable?: boolean;
exportable?: boolean;
editable?: boolean;
groupable?: boolean;
resizable?: boolean;
draggable?: boolean;
classname?: string;
cellclassname?: any;
width?: number | string;
menu?: boolean;
}
export interface IGridGetDataInformation {
rowscount?: string;
sortinformation?: any;
sortcolumn?: any;
sortdirection?: any;
paginginformation?: any;
pagenum?: any;
pagesize?: any;
pagescount?: any;
}
export interface IGridGetSortInformation {
sortcolumn?: string;
sortdirection?: any;
}
export interface IGridGetPagingInformation {
pagenum?: string;
pagesize?: any;
pagescount?: any;
}
export interface IGridDateNaming {
names?: string[];
namesAbbr?: string[];
namesShort?: string[];
}
export interface IGridLocalizationobject {
filterstringcomparisonoperators?: any;
filternumericcomparisonoperators?: any;
filterdatecomparisonoperators?: any;
filterbooleancomparisonoperators?: any;
pagergotopagestring?: string;
pagershowrowsstring?: string;
pagerrangestring?: string;
pagernextbuttonstring?: string;
pagerpreviousbuttonstring?: string;
sortascendingstring?: string;
sortdescendingstring?: string;
sortremovestring?: string;
firstDay?: number;
percentsymbol?: string;
currencysymbol?: string;
currencysymbolposition?: string;
decimalseparator?: string;
thousandsseparator?: string;
days?: IGridDateNaming;
months?: IGridDateNaming;
addrowstring?: string;
updaterowstring?: string;
deleterowstring?: string;
resetrowstring?: string;
everpresentrowplaceholder?: string;
emptydatastring?: string;
}
export interface IGridScrollPosition {
top?: number;
left?: number;
}
export interface IGridGetGroup {
group?: number;
level?: number;
expanded?: number;
subgroups?: number;
subrows?: number;
}
export interface IGridGetCell {
value?: number;
row?: number;
column?: number;
}
export interface IGridGetSelectedCell {
rowindex?: number;
datafield?: string;
}
export interface IGridGetStateColumns {
width?: number | string;
hidden?: boolean;
index?: number;
pinned?: boolean;
groupable?: boolean;
resizable?: boolean;
draggable?: boolean;
text?: string;
align?: string;
cellsalign?: string;
}
export interface IGridGetState {
width?: number | string;
height?: number | string;
pagenum?: number;
pagesize?: number;
pagesizeoptions?: string[];
sortcolumn?: any;
sortdirection?: any;
filters?: any;
groups?: any;
columns?: IGridGetStateColumns;
}
export interface IGridColumnmenuopening {
menu?: any;
datafield?: any;
height?: any;
}
export interface IGridColumnmenuclosing {
menu?: any;
datafield?: any;
height?: any;
}
export interface IGridCellhover {
cellhtmlElement?: any;
x?: any;
y?: any;
}
export interface IGridGroupsrenderer {
text?: string;
group?: number;
expanded?: boolean;
data?: object;
}
export interface IGridGroupcolumnrenderer {
text?: any;
}
export interface IGridHandlekeyboardnavigation {
event?: any;
}
export interface IGridScrollfeedback {
row?: object;
}
export interface IGridFilter {
cellValue?: any;
rowData?: any;
dataField?: string;
filterGroup?: any;
defaultFilterResult?: boolean;
}
export interface IGridRendertoolbar {
toolbar?: any;
}
export interface IGridRenderstatusbar {
statusbar?: any;
}
interface IGridOptions {
altrows?: boolean;
altstart?: number;
altstep?: number;
autoshowloadelement?: boolean;
autoshowfiltericon?: boolean;
autoshowcolumnsmenubutton?: boolean;
showcolumnlines?: boolean;
showrowlines?: boolean;
showcolumnheaderlines?: boolean;
adaptive?: boolean;
adaptivewidth?: number;
clipboard?: boolean;
closeablegroups?: boolean;
columnsmenuwidth?: number;
columnmenuopening?: (menu?: IGridColumnmenuopening['menu'], datafield?: IGridColumnmenuopening['datafield'], height?: IGridColumnmenuopening['height']) => boolean | void;
columnmenuclosing?: (menu?: IGridColumnmenuclosing['menu'], datafield?: IGridColumnmenuclosing['datafield'], height?: IGridColumnmenuclosing['height']) => boolean;
cellhover?: (cellhtmlElement?: IGridCellhover['cellhtmlElement'], x?: IGridCellhover['x'], y?: IGridCellhover['y']) => void;
enablekeyboarddelete?: boolean;
enableellipsis?: boolean;
enablemousewheel?: boolean;
enableanimations?: boolean;
enabletooltips?: boolean;
enablehover?: boolean;
enablebrowserselection?: boolean;
everpresentrowposition?: 'top' | 'bottom' | 'topAboveFilterRow';
everpresentrowheight?: number;
everpresentrowactions?: string;
everpresentrowactionsmode?: 'popup' | 'columns';
filterrowheight?: number;
filtermode?: 'default' | 'excel';
groupsrenderer?: (text?: IGridGroupsrenderer['text'], group?: IGridGroupsrenderer['group'], expanded?: IGridGroupsrenderer['expanded'], data?: IGridGroupsrenderer['data']) => string;
groupcolumnrenderer?: (text?: IGridGroupcolumnrenderer['text']) => string;
groupsexpandedbydefault?: boolean;
handlekeyboardnavigation?: (event: IGridHandlekeyboardnavigation['event']) => boolean;
pagerrenderer?: () => any[];
rtl?: boolean;
showdefaultloadelement?: boolean;
showfiltercolumnbackground?: boolean;
showfiltermenuitems?: boolean;
showpinnedcolumnbackground?: boolean;
showsortcolumnbackground?: boolean;
showsortmenuitems?: boolean;
showgroupmenuitems?: boolean;
showrowdetailscolumn?: boolean;
showheader?: boolean;
showgroupsheader?: boolean;
showaggregates?: boolean;
showgroupaggregates?: boolean;
showeverpresentrow?: boolean;
showfilterrow?: boolean;
showemptyrow?: boolean;
showstatusbar?: boolean;
statusbarheight?: number;
showtoolbar?: boolean;
showfilterbar?: boolean;
filterbarmode?: string;
selectionmode?: 'none' | 'singlerow' | 'multiplerows' | 'multiplerowsextended' | 'singlecell' | 'multiplecells' | 'multiplecellsextended' | 'multiplecellsadvanced' | 'checkbox';
updatefilterconditions?: (type?: string, defaultconditions?: any) => any;
updatefilterpanel?: (filtertypedropdown1?: any, filtertypedropdown2?: any, filteroperatordropdown?: any, filterinputfield1?: any, filterinputfield2?: any, filterbutton?: any, clearbutton?: any, columnfilter?: any, filtertype?: any, filterconditions?: any) => any;
theme?: string;
toolbarheight?: number;
autoheight?: boolean;
autorowheight?: boolean;
columnsheight?: number;
deferreddatafields?: string[];
groupsheaderheight?: number;
groupindentwidth?: number;
height?: number | string;
pagerheight?: number | string;
rowsheight?: number;
scrollbarsize?: number | string;
scrollmode?: 'default' | 'logical' | 'deferred';
scrollfeedback?: (row: IGridScrollfeedback['row']) => string;
width?: string | number;
autosavestate?: boolean;
autoloadstate?: boolean;
columns?: IGridColumn[];
enableSanitize?: boolean;
cardview?: boolean;
cardviewcolumns?: any;
cardheight?: number;
cardsize?: number;
columngroups?: any[];
columnsmenu?: boolean;
columnsresize?: boolean;
columnsautoresize?: boolean;
columnsreorder?: boolean;
charting?: IGridCharting;
disabled?: boolean;
editable?: boolean;
editmode?: 'click' | 'selectedcell' | 'selectedrow' | 'dblclick' | 'programmatic';
filter?: (cellValue?: IGridFilter['cellValue'], rowData?: IGridFilter['rowData'], dataField?: IGridFilter['dataField'], filterGroup?: IGridFilter['filterGroup'], defaultFilterResult?: IGridFilter['defaultFilterResult']) => any;
filterable?: boolean;
groupable?: boolean;
groups?: string[];
horizontalscrollbarstep?: number;
horizontalscrollbarlargestep?: number;
initrowdetails?: (index?: number, parentElement?: any, gridElement?: any, datarecord?: any) => void;
keyboardnavigation?: boolean;
localization?: IGridLocalizationobject;
pagesize?: number;
pagesizeoptions?: Array<number | string>;
pagermode?: 'simple' | 'default' | 'material';
pagerbuttonscount?: number;
pageable?: boolean;
autofill?: boolean;
rowdetails?: boolean;
rowdetailstemplate?: any;
ready?: () => void;
rendered?: (type: any) => void;
renderstatusbar?: (statusbar?: IGridRenderstatusbar['statusbar']) => void;
rendertoolbar?: (toolbar?: IGridRendertoolbar['toolbar']) => void;
rendergridrows?: (params?: any) => any;
sortable?: boolean;
sortmode?: string;
selectedrowindex?: number;
selectedrowindexes?: number[];
source?: IGridSource;
sorttogglestates?: '0' | '1' | '2';
updatedelay?: number;
virtualmode?: boolean;
verticalscrollbarstep?: number;
verticalscrollbarlargestep?: number;
}
export interface IGridProps extends IGridOptions {
className?: string;
style?: React.CSSProperties;
onBindingcomplete?: (e?: Event) => void;
onColumnresized?: (e?: Event) => void;
onColumnreordered?: (e?: Event) => void;
onColumnclick?: (e?: Event) => void;
onCellclick?: (e?: Event) => void;
onCelldoubleclick?: (e?: Event) => void;
onCellselect?: (e?: Event) => void;
onCellunselect?: (e?: Event) => void;
onCellvaluechanged?: (e?: Event) => void;
onCellbeginedit?: (e?: Event) => void;
onCellendedit?: (e?: Event) => void;
onFilter?: (e?: Event) => void;
onGroupschanged?: (e?: Event) => void;
onGroupexpand?: (e?: Event) => void;
onGroupcollapse?: (e?: Event) => void;
onPagechanged?: (e?: Event) => void;
onPagesizechanged?: (e?: Event) => void;
onRowclick?: (e?: Event) => void;
onRowdoubleclick?: (e?: Event) => void;
onRowselect?: (e?: Event) => void;
onRowunselect?: (e?: Event) => void;
onRowexpand?: (e?: Event) => void;
onRowcollapse?: (e?: Event) => void;
onSort?: (e?: Event) => void;
}
| cdnjs/cdnjs | ajax/libs/jqwidgets/12.1.2/jqwidgets-react-tsx/jqxgrid/react_jqxgrid.d.ts | TypeScript | mit | 21,567 |
"use strict";
exports.__esModule = true;
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createElement = _interopRequireDefault(require("../createElement"));
var _css = _interopRequireDefault(require("../StyleSheet/css"));
var _pick = _interopRequireDefault(require("../../modules/pick"));
var _useElementLayout = _interopRequireDefault(require("../../hooks/useElementLayout"));
var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs"));
var _usePlatformMethods = _interopRequireDefault(require("../../hooks/usePlatformMethods"));
var _useResponderEvents = _interopRequireDefault(require("../../hooks/useResponderEvents"));
var _StyleSheet = _interopRequireDefault(require("../StyleSheet"));
var _TextAncestorContext = _interopRequireDefault(require("../Text/TextAncestorContext"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
var forwardPropsList = {
accessibilityLabel: true,
accessibilityLiveRegion: true,
accessibilityRole: true,
accessibilityState: true,
accessibilityValue: true,
accessible: true,
children: true,
classList: true,
disabled: true,
importantForAccessibility: true,
nativeID: true,
onBlur: true,
onClick: true,
onClickCapture: true,
onContextMenu: true,
onFocus: true,
onKeyDown: true,
onKeyUp: true,
onTouchCancel: true,
onTouchCancelCapture: true,
onTouchEnd: true,
onTouchEndCapture: true,
onTouchMove: true,
onTouchMoveCapture: true,
onTouchStart: true,
onTouchStartCapture: true,
pointerEvents: true,
ref: true,
style: true,
testID: true,
// unstable
dataSet: true,
onMouseDown: true,
onMouseEnter: true,
onMouseLeave: true,
onMouseMove: true,
onMouseOver: true,
onMouseOut: true,
onMouseUp: true,
onScroll: true,
onWheel: true,
href: true,
rel: true,
target: true
};
var pickProps = function pickProps(props) {
return (0, _pick.default)(props, forwardPropsList);
};
var View = (0, React.forwardRef)(function (props, forwardedRef) {
var onLayout = props.onLayout,
onMoveShouldSetResponder = props.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture,
onResponderEnd = props.onResponderEnd,
onResponderGrant = props.onResponderGrant,
onResponderMove = props.onResponderMove,
onResponderReject = props.onResponderReject,
onResponderRelease = props.onResponderRelease,
onResponderStart = props.onResponderStart,
onResponderTerminate = props.onResponderTerminate,
onResponderTerminationRequest = props.onResponderTerminationRequest,
onScrollShouldSetResponder = props.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = props.onStartShouldSetResponder,
onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture;
if (process.env.NODE_ENV !== 'production') {
React.Children.toArray(props.children).forEach(function (item) {
if (typeof item === 'string') {
console.error("Unexpected text node: " + item + ". A text node cannot be a child of a <View>.");
}
});
}
var hasTextAncestor = (0, React.useContext)(_TextAncestorContext.default);
var hostRef = (0, React.useRef)(null);
var classList = [classes.view];
var style = _StyleSheet.default.compose(hasTextAncestor && styles.inline, props.style);
(0, _useElementLayout.default)(hostRef, onLayout);
(0, _useResponderEvents.default)(hostRef, {
onMoveShouldSetResponder: onMoveShouldSetResponder,
onMoveShouldSetResponderCapture: onMoveShouldSetResponderCapture,
onResponderEnd: onResponderEnd,
onResponderGrant: onResponderGrant,
onResponderMove: onResponderMove,
onResponderReject: onResponderReject,
onResponderRelease: onResponderRelease,
onResponderStart: onResponderStart,
onResponderTerminate: onResponderTerminate,
onResponderTerminationRequest: onResponderTerminationRequest,
onScrollShouldSetResponder: onScrollShouldSetResponder,
onScrollShouldSetResponderCapture: onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder: onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture: onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder: onStartShouldSetResponder,
onStartShouldSetResponderCapture: onStartShouldSetResponderCapture
});
var supportedProps = pickProps(props);
supportedProps.classList = classList;
supportedProps.style = style;
var platformMethodsRef = (0, _usePlatformMethods.default)(hostRef, supportedProps);
var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef);
supportedProps.ref = setRef;
return (0, _createElement.default)('div', supportedProps);
});
View.displayName = 'View';
var classes = _css.default.create({
view: {
alignItems: 'stretch',
border: '0 solid black',
boxSizing: 'border-box',
display: 'flex',
flexBasis: 'auto',
flexDirection: 'column',
flexShrink: 0,
margin: 0,
minHeight: 0,
minWidth: 0,
padding: 0,
position: 'relative',
zIndex: 0
}
});
var styles = _StyleSheet.default.create({
inline: {
display: 'inline-flex'
}
});
var _default = View;
exports.default = _default;
module.exports = exports.default; | cdnjs/cdnjs | ajax/libs/react-native-web/0.0.0-e437e3f47/cjs/exports/View/index.js | JavaScript | mit | 6,819 |
/*******************************************************************************
* Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
******************************************************************************/
package org.eclipse.kura.net;
import java.util.Map;
import org.osgi.annotation.versioning.ProviderType;
import org.osgi.service.event.Event;
/**
* An event raised when a network interface has been removed from the system.
*
* @noextend This class is not intended to be subclassed by clients.
*/
@ProviderType
public class NetInterfaceRemovedEvent extends Event {
/** Topic of the NetworkInterfaceRemovedEvent */
public static final String NETWORK_EVENT_INTERFACE_REMOVED_TOPIC = "org/eclipse/kura/net/NetworkEvent/interface/REMOVED";
/** Name of the property to access the network interface name */
public static final String NETWORK_EVENT_INTERFACE_PROPERTY = "network.interface";
public NetInterfaceRemovedEvent(Map<String, ?> properties) {
super(NETWORK_EVENT_INTERFACE_REMOVED_TOPIC, properties);
}
/**
* Returns the name of the removed interface.
*
* @return
*/
public String getInterfaceName() {
return (String) getProperty(NETWORK_EVENT_INTERFACE_PROPERTY);
}
}
| ctron/kura | kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/net/NetInterfaceRemovedEvent.java | Java | epl-1.0 | 1,545 |
/* ********************************************************************** **
** Copyright notice **
** **
** (c) 2005-2009 RSSOwl Development Team **
** http://www.rssowl.org/ **
** **
** All rights reserved **
** **
** This program and the accompanying materials are made available under **
** the terms of the Eclipse Public License v1.0 which accompanies this **
** distribution, and is available at: **
** http://www.rssowl.org/legal/epl-v10.html **
** **
** A copy is found in the file epl-v10.html and important notices to the **
** license from the team is found in the textfile LICENSE.txt distributed **
** in this package. **
** **
** This copyright notice MUST APPEAR in all copies of the file! **
** **
** Contributors: **
** RSSOwl Development Team - initial API and implementation **
** **
** ********************************************************************** */
package org.rssowl.core.internal.persist.service;
import org.rssowl.core.persist.IEntity;
import org.rssowl.core.persist.event.ModelEvent;
import org.rssowl.core.persist.event.runnable.EventRunnable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
/**
* A {@link Map} of {@link ModelEvent} pointing to {@link EventRunnable}.
*/
public class EventsMap {
private static final EventsMap INSTANCE = new EventsMap();
private static class InternalMap extends HashMap<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> {
InternalMap() {
super();
}
}
private final ThreadLocal<InternalMap> fEvents = new ThreadLocal<InternalMap>();
private final ThreadLocal<Map<IEntity, ModelEvent>> fEventTemplatesMap = new ThreadLocal<Map<IEntity, ModelEvent>>();
private EventsMap() {
// Enforce singleton pattern
}
public final static EventsMap getInstance() {
return INSTANCE;
}
public final void putPersistEvent(ModelEvent event) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event);
eventRunnable.addCheckedPersistEvent(event);
}
public final void putUpdateEvent(ModelEvent event) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event);
eventRunnable.addCheckedUpdateEvent(event);
}
public final void putRemoveEvent(ModelEvent event) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event);
eventRunnable.addCheckedRemoveEvent(event);
}
public final boolean containsPersistEvent(Class<? extends ModelEvent> eventClass, IEntity entity) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
return eventRunnable.getPersistEvents().contains(entity);
}
public final boolean containsUpdateEvent(Class<? extends ModelEvent> eventClass, IEntity entity) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
return eventRunnable.getUpdateEvents().contains(entity);
}
public final boolean containsRemoveEvent(Class<? extends ModelEvent> eventClass, IEntity entity) {
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
return eventRunnable.getRemoveEvents().contains(entity);
}
private EventRunnable<? extends ModelEvent> getEventRunnable(Class<? extends ModelEvent> eventClass) {
InternalMap map = fEvents.get();
if (map == null) {
map = new InternalMap();
fEvents.set(map);
}
EventRunnable<? extends ModelEvent> eventRunnable = map.get(eventClass);
return eventRunnable;
}
private EventRunnable<? extends ModelEvent> getEventRunnable(ModelEvent event) {
Class<? extends ModelEvent> eventClass = event.getClass();
EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass);
if (eventRunnable == null) {
eventRunnable = event.createEventRunnable();
fEvents.get().put(eventClass, eventRunnable);
}
return eventRunnable;
}
public EventRunnable<? extends ModelEvent> removeEventRunnable(Class<? extends ModelEvent> klass) {
InternalMap map = fEvents.get();
if (map == null)
return null;
EventRunnable<? extends ModelEvent> runnable = map.remove(klass);
return runnable;
}
public List<EventRunnable<?>> getEventRunnables() {
InternalMap map = fEvents.get();
if (map == null)
return new ArrayList<EventRunnable<?>>(0);
List<EventRunnable<?>> eventRunnables = new ArrayList<EventRunnable<?>>(map.size());
for (Map.Entry<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> entry : map.entrySet()) {
eventRunnables.add(entry.getValue());
}
return eventRunnables;
}
public List<EventRunnable<?>> removeEventRunnables() {
InternalMap map = fEvents.get();
if (map == null)
return new ArrayList<EventRunnable<?>>(0);
List<EventRunnable<?>> eventRunnables = getEventRunnables();
map.clear();
return eventRunnables;
}
public void putEventTemplate(ModelEvent event) {
Map<IEntity, ModelEvent> map = fEventTemplatesMap.get();
if (map == null) {
map = new IdentityHashMap<IEntity, ModelEvent>();
fEventTemplatesMap.set(map);
}
map.put(event.getEntity(), event);
}
public final Map<IEntity, ModelEvent> getEventTemplatesMap() {
Map<IEntity, ModelEvent> map = fEventTemplatesMap.get();
if (map == null)
return Collections.emptyMap();
return Collections.unmodifiableMap(fEventTemplatesMap.get());
}
public Map<IEntity, ModelEvent> removeEventTemplatesMap() {
Map<IEntity, ModelEvent> map = fEventTemplatesMap.get();
fEventTemplatesMap.remove();
return map;
}
} | rssowl/RSSOwl | org.rssowl.core/src/org/rssowl/core/internal/persist/service/EventsMap.java | Java | epl-1.0 | 6,658 |
/*******************************************************************************
* Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura.web.shared.model;
import java.io.Serializable;
import java.util.Date;
import org.eclipse.kura.web.shared.DateUtils;
public class GwtDeviceConfig extends GwtBaseModel implements Serializable {
private static final long serialVersionUID = 1708831984640005284L;
public GwtDeviceConfig() {
}
@Override
@SuppressWarnings({ "unchecked" })
public <X> X get(String property) {
if ("lastEventOnFormatted".equals(property)) {
return (X) DateUtils.formatDateTime((Date) get("lastEventOn"));
} else if ("uptimeFormatted".equals(property)) {
if (getUptime() == -1) {
return (X) "Unknown";
} else {
return (X) String.valueOf(getUptime());
}
} else {
return super.get(property);
}
}
public String getAccountName() {
return get("accountName");
}
public void setAccountName(String accountName) {
set("accountName", accountName);
}
public String getClientId() {
return (String) get("clientId");
}
public void setClientId(String clientId) {
set("clientId", clientId);
}
public Long getUptime() {
return (Long) get("uptime");
}
public String getUptimeFormatted() {
return (String) get("uptimeFormatted");
}
public void setUptime(Long uptime) {
set("uptime", uptime);
}
public String getGwtDeviceStatus() {
return (String) get("gwtDeviceStatus");
}
public void setGwtDeviceStatus(String gwtDeviceStatus) {
set("gwtDeviceStatus", gwtDeviceStatus);
}
public String getDisplayName() {
return (String) get("displayName");
}
public void setDisplayName(String displayName) {
set("displayName", displayName);
}
public String getModelName() {
return (String) get("modelName");
}
public void setModelName(String modelName) {
set("modelName", modelName);
}
public String getModelId() {
return (String) get("modelId");
}
public void setModelId(String modelId) {
set("modelId", modelId);
}
public String getPartNumber() {
return (String) get("partNumber");
}
public void setPartNumber(String partNumber) {
set("partNumber", partNumber);
}
public String getSerialNumber() {
return (String) get("serialNumber");
}
public void setSerialNumber(String serialNumber) {
set("serialNumber", serialNumber);
}
public String getAvailableProcessors() {
return (String) get("availableProcessors");
}
public void setAvailableProcessors(String availableProcessors) {
set("availableProcessors", availableProcessors);
}
public String getTotalMemory() {
return (String) get("totalMemory");
}
public void setTotalMemory(String totalMemory) {
set("totalMemory", totalMemory);
}
public String getFirmwareVersion() {
return (String) get("firmwareVersion");
}
public void setFirmwareVersion(String firmwareVersion) {
set("firmwareVersion", firmwareVersion);
}
public String getBiosVersion() {
return (String) get("biosVersion");
}
public void setBiosVersion(String biosVersion) {
set("biosVersion", biosVersion);
}
public String getOs() {
return (String) get("os");
}
public void setOs(String os) {
set("os", os);
}
public String getOsVersion() {
return (String) get("osVersion");
}
public void setOsVersion(String osVersion) {
set("osVersion", osVersion);
}
public String getOsArch() {
return (String) get("osArch");
}
public void setOsArch(String osArch) {
set("osArch", osArch);
}
public String getJvmName() {
return (String) get("jvmName");
}
public void setJvmName(String jvmName) {
set("jvmName", jvmName);
}
public String getJvmVersion() {
return (String) get("jvmVersion");
}
public void setJvmVersion(String jvmVersion) {
set("jvmVersion", jvmVersion);
}
public String getJvmProfile() {
return (String) get("jvmProfile");
}
public void setJvmProfile(String jvmProfile) {
set("jvmProfile", jvmProfile);
}
public String getOsgiFramework() {
return (String) get("osgiFramework");
}
public void setOsgiFramework(String osgiFramework) {
set("osgiFramework", osgiFramework);
}
public String getOsgiFrameworkVersion() {
return (String) get("osgiFrameworkVersion");
}
public void setOsgiFrameworkVersion(String osgiFrameworkVersion) {
set("osgiFrameworkVersion", osgiFrameworkVersion);
}
public String getConnectionInterface() {
return (String) get("connectionInterface");
}
public void setConnectionInterface(String connectionInterface) {
set("connectionInterface", connectionInterface);
}
public String getConnectionIp() {
return (String) get("connectionIp");
}
public void setConnectionIp(String connectionIp) {
set("connectionIp", connectionIp);
}
public String getAcceptEncoding() {
return (String) get("acceptEncoding");
}
public void setAcceptEncoding(String acceptEncoding) {
set("acceptEncoding", acceptEncoding);
}
public String getApplicationIdentifiers() {
return (String) get("applicationIdentifiers");
}
public void setApplicationIdentifiers(String applicationIdentifiers) {
set("applicationIdentifiers", applicationIdentifiers);
}
public Double getGpsLatitude() {
return (Double) get("gpsLatitude");
}
public void setGpsLatitude(Double gpsLatitude) {
set("gpsLatitude", gpsLatitude);
}
public Double getGpsLongitude() {
return (Double) get("gpsLongitude");
}
public void setGpsLongitude(Double gpsLongitude) {
set("gpsLongitude", gpsLongitude);
}
public Double getGpsAltitude() {
return (Double) get("gpsAltitude");
}
public void setGpsAltitude(Double gpsAltitude) {
set("gpsAltitude", gpsAltitude);
}
public String getGpsAddress() {
return (String) get("gpsAddress");
}
public void setGpsAddress(String gpsAddress) {
set("gpsAddress", gpsAddress);
}
public Date getLastEventOn() {
return (Date) get("lastEventOn");
}
public String getLastEventOnFormatted() {
return (String) get("lastEventOnFormatted");
}
public void setLastEventOn(Date lastEventDate) {
set("lastEventOn", lastEventDate);
}
public String getLastEventType() {
return (String) get("lastEventType");
}
public void setLastEventType(String lastEventType) {
set("lastEventType", lastEventType);
}
public boolean isOnline() {
return getGwtDeviceStatus().compareTo("CONNECTED") == 0;
}
}
| ctron/kura | kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/model/GwtDeviceConfig.java | Java | epl-1.0 | 7,591 |
/*******************************************************************************
* Copyright (c) 2010 - 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Lars Vogel <lars.Vogel@gmail.com> - Bug 419770
*******************************************************************************/
package com.vogella.e4.appmodel.app.handlers;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
public class QuitHandler {
@Execute
public void execute(IWorkbench workbench, Shell shell){
if (MessageDialog.openConfirm(shell, "Confirmation",
"Do you want to exit?")) {
workbench.close();
}
}
}
| scela/EclipseCon2014 | com.vogella.e4.appmodel.app/src/com/vogella/e4/appmodel/app/handlers/QuitHandler.java | Java | epl-1.0 | 1,040 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.ext.git.client.compare;
import org.eclipse.che.ide.api.resources.Project;
import org.eclipse.che.ide.ext.git.client.compare.FileStatus.Status;
/**
* Describes changed in any way project files. Supports adding and removing items dynamically.
*
* @author Mykola Morhun
*/
public class MutableAlteredFiles extends AlteredFiles {
/**
* Parses raw git diff string and creates advanced representation.
*
* @param project the project under diff operation
* @param diff plain result of git diff operation
*/
public MutableAlteredFiles(Project project, String diff) {
super(project, diff);
}
/**
* Creates mutable altered files list based on changes from another project.
*
* @param project the project under diff operation
* @param alteredFiles changes from another project
*/
public MutableAlteredFiles(Project project, AlteredFiles alteredFiles) {
super(project, "");
this.alteredFilesStatuses.putAll(alteredFiles.alteredFilesStatuses);
this.alteredFilesList.addAll(alteredFiles.alteredFilesList);
}
/**
* Creates an empty list of altered files.
*
* @param project the project under diff operation
*/
public MutableAlteredFiles(Project project) {
super(project, "");
}
/**
* Adds or updates a file in altered file list. If given file is already exists does nothing.
*
* @param file full path to file and its name relatively to project root
* @param status git status of the file
* @return true if file was added or updated and false if the file is already exists in this list
*/
public boolean addFile(String file, Status status) {
if (status.equals(alteredFilesStatuses.get(file))) {
return false;
}
if (alteredFilesStatuses.put(file, status) == null) {
// it's not a status change, new file was added
alteredFilesList.add(file);
}
return true;
}
/**
* Removes given file from the altered files list. If given file isn't present does nothing.
*
* @param file full path to file and its name relatively to project root
* @return true if the file was deleted and false otherwise
*/
public boolean removeFile(String file) {
alteredFilesStatuses.remove(file);
return alteredFilesList.remove(file);
}
}
| akervern/che | plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/compare/MutableAlteredFiles.java | Java | epl-1.0 | 2,645 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport.multicast;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import org.apache.activemq.command.Command;
import org.apache.activemq.command.Endpoint;
import org.apache.activemq.transport.udp.DatagramEndpoint;
import org.apache.activemq.transport.udp.DatagramHeaderMarshaller;
/**
*
*
*/
public class MulticastDatagramHeaderMarshaller extends DatagramHeaderMarshaller {
private final byte[] localUriAsBytes;
public MulticastDatagramHeaderMarshaller(String localUri) {
this.localUriAsBytes = localUri.getBytes();
}
public Endpoint createEndpoint(ByteBuffer readBuffer, SocketAddress address) {
int size = readBuffer.getInt();
byte[] data = new byte[size];
readBuffer.get(data);
return new DatagramEndpoint(new String(data), address);
}
public void writeHeader(Command command, ByteBuffer writeBuffer) {
writeBuffer.putInt(localUriAsBytes.length);
writeBuffer.put(localUriAsBytes);
super.writeHeader(command, writeBuffer);
}
}
| Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/transport/multicast/MulticastDatagramHeaderMarshaller.java | Java | epl-1.0 | 1,880 |
/*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.trends.databrowser2.propsheet;
import org.csstudio.swt.rtplot.undo.UndoableActionManager;
import org.csstudio.trends.databrowser2.Activator;
import org.csstudio.trends.databrowser2.Messages;
import org.csstudio.trends.databrowser2.model.PVItem;
import org.csstudio.trends.databrowser2.preferences.Preferences;
import org.eclipse.jface.action.Action;
/** Action that configures PVs to use default archive data sources.
* @author Kay Kasemir
*/
public class UseDefaultArchivesAction extends Action
{
final private UndoableActionManager operations_manager;
final private PVItem pvs[];
/** Initialize
* @param shell Parent shell for dialog
* @param pvs PVs that should use default archives
*/
public UseDefaultArchivesAction(final UndoableActionManager operations_manager,
final PVItem pvs[])
{
super(Messages.UseDefaultArchives,
Activator.getDefault().getImageDescriptor("icons/archive.gif")); //$NON-NLS-1$
this.operations_manager = operations_manager;
this.pvs = pvs;
}
@Override
public void run()
{
new AddArchiveCommand(operations_manager, pvs, Preferences.getArchives(), true);
}
}
| ControlSystemStudio/cs-studio | applications/databrowser/databrowser-plugins/org.csstudio.trends.databrowser2/src/org/csstudio/trends/databrowser2/propsheet/UseDefaultArchivesAction.java | Java | epl-1.0 | 1,688 |
/*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This 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.
*/
package MWC.GUI.Properties.Swing;
// Copyright MWC 1999, Debrief 3 Project
// $RCSfile: SwingDatePropertyEditor.java,v $
// @author $Author: Ian.Mayo $
// @version $Revision: 1.3 $
// $Log: SwingDatePropertyEditor.java,v $
// Revision 1.3 2004/11/26 11:32:48 Ian.Mayo
// Moving closer, supporting checking for time resolution
//
// Revision 1.2 2004/05/25 15:29:37 Ian.Mayo
// Commit updates from home
//
// Revision 1.1.1.1 2004/03/04 20:31:20 ian
// no message
//
// Revision 1.1.1.1 2003/07/17 10:07:26 Ian.Mayo
// Initial import
//
// Revision 1.2 2002-05-28 09:25:47+01 ian_mayo
// after switch to new system
//
// Revision 1.1 2002-05-28 09:14:33+01 ian_mayo
// Initial revision
//
// Revision 1.1 2002-04-11 14:01:26+01 ian_mayo
// Initial revision
//
// Revision 1.1 2001-08-31 10:36:55+01 administrator
// Tidied up layout, so all data is displayed when editor panel is first opened
//
// Revision 1.0 2001-07-17 08:43:31+01 administrator
// Initial revision
//
// Revision 1.4 2001-07-12 12:06:59+01 novatech
// use tooltips to show the date format
//
// Revision 1.3 2001-01-21 21:38:23+00 novatech
// handle focusGained = select all text
//
// Revision 1.2 2001-01-17 09:41:37+00 novatech
// factor generic processing to parent class, and provide support for NULL values
//
// Revision 1.1 2001-01-03 13:42:39+00 novatech
// Initial revision
//
// Revision 1.1.1.1 2000/12/12 21:45:37 ianmayo
// initial version
//
// Revision 1.5 2000-10-09 13:35:47+01 ian_mayo
// Switched stack traces to go to log file
//
// Revision 1.4 2000-04-03 10:48:57+01 ian_mayo
// squeeze up the controls
//
// Revision 1.3 2000-02-02 14:25:07+00 ian_mayo
// correct package naming
//
// Revision 1.2 1999-11-23 11:05:03+00 ian_mayo
// further introduction of SWING components
//
// Revision 1.1 1999-11-16 16:07:19+00 ian_mayo
// Initial revision
//
// Revision 1.1 1999-11-16 16:02:29+00 ian_mayo
// Initial revision
//
// Revision 1.2 1999-11-11 18:16:09+00 ian_mayo
// new class, now working
//
// Revision 1.1 1999-10-12 15:36:48+01 ian_mayo
// Initial revision
//
// Revision 1.1 1999-08-26 10:05:48+01 administrator
// Initial revision
//
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import MWC.GUI.Dialogs.DialogFactory;
import MWC.GenericData.HiResDate;
import MWC.Utilities.TextFormatting.DebriefFormatDateTime;
public class SwingDatePropertyEditor extends
MWC.GUI.Properties.DatePropertyEditor implements java.awt.event.FocusListener
{
/////////////////////////////////////////////////////////////
// member variables
////////////////////////////////////////////////////////////
/**
* field to edit the date
*/
JTextField _theDate;
/**
* field to edit the time
*/
JTextField _theTime;
/**
* label to show the microsecodns
*/
JLabel _theMicrosTxt;
/**
* panel to hold everything
*/
JPanel _theHolder;
/////////////////////////////////////////////////////////////
// constructor
////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// member functions
////////////////////////////////////////////////////////////
/**
* build the editor
*/
public java.awt.Component getCustomEditor()
{
_theHolder = new JPanel();
final java.awt.BorderLayout bl1 = new java.awt.BorderLayout();
bl1.setVgap(0);
bl1.setHgap(0);
final java.awt.BorderLayout bl2 = new java.awt.BorderLayout();
bl2.setVgap(0);
bl2.setHgap(0);
final JPanel lPanel = new JPanel();
lPanel.setLayout(bl1);
final JPanel rPanel = new JPanel();
rPanel.setLayout(bl2);
_theHolder.setLayout(new java.awt.GridLayout(0, 2));
_theDate = new JTextField();
_theDate.setToolTipText("Format: " + NULL_DATE);
_theTime = new JTextField();
_theTime.setToolTipText("Format: " + NULL_TIME);
lPanel.add("Center", new JLabel("Date:", JLabel.RIGHT));
lPanel.add("East", _theDate);
rPanel.add("Center", new JLabel("Time:", JLabel.RIGHT));
rPanel.add("East", _theTime);
_theHolder.add(lPanel);
_theHolder.add(rPanel);
// get the fields to select the full text when they're selected
_theDate.addFocusListener(this);
_theTime.addFocusListener(this);
// right, just see if we are in hi-res DTG editing mode
if (HiResDate.inHiResProcessingMode())
{
// ok, add a button to allow the user to enter DTG data
final JButton editMicros = new JButton("Micros");
editMicros.addActionListener(new ActionListener()
{
public void actionPerformed(final ActionEvent e)
{
editMicrosPressed();
}
});
// ok, we'
_theMicrosTxt = new JLabel("..");
_theHolder.add(_theMicrosTxt);
_theHolder.add(editMicros);
}
resetData();
return _theHolder;
}
/**
* user wants to edit the microseconds. give him a popup
*/
void editMicrosPressed()
{
//To change body of created methods use File | Settings | File Templates.
final Integer res = DialogFactory.getInteger("Edit microseconds", "Enter microseconds",(int) _theMicros);
// did user enter anything?
if(res != null)
{
// store the data
_theMicros = res.intValue();
// and update the screen
resetData();
}
}
/**
* get the date text as a string
*/
protected String getDateText()
{
return _theDate.getText();
}
/**
* get the date text as a string
*/
protected String getTimeText()
{
return _theTime.getText();
}
/**
* set the date text in string form
*/
protected void setDateText(final String val)
{
if (_theHolder != null)
{
_theDate.setText(val);
}
}
/**
* set the time text in string form
*/
protected void setTimeText(final String val)
{
if (_theHolder != null)
{
_theTime.setText(val);
}
}
/**
* show the user how many microseconds there are
*
* @param val
*/
protected void setMicroText(final long val)
{
// output the number of microseconds
_theMicrosTxt.setText(DebriefFormatDateTime.formatMicros(new HiResDate(0, val)) + " micros");
}
/////////////////////////////
// focus listener support classes
/////////////////////////////
/**
* Invoked when a component gains the keyboard focus.
*/
public void focusGained(final FocusEvent e)
{
final java.awt.Component c = e.getComponent();
if (c instanceof JTextField)
{
final JTextField jt = (JTextField) c;
jt.setSelectionStart(0);
jt.setSelectionEnd(jt.getText().length());
}
}
/**
* Invoked when a component loses the keyboard focus.
*/
public void focusLost(final FocusEvent e)
{
}
}
| alastrina123/debrief | org.mwc.cmap.legacy/src/MWC/GUI/Properties/Swing/SwingDatePropertyEditor.java | Java | epl-1.0 | 7,774 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2012 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "Polar/Polar.hpp"
#include "Engine/GlideSolvers/PolarCoefficients.hpp"
#include "Units/System.hpp"
#include <stdlib.h>
#include <cstdio>
PolarCoefficients
PolarInfo::CalculateCoefficients() const
{
return PolarCoefficients::From3VW(v1, v2, v3, w1, w2, w3);
}
bool
PolarInfo::IsValid() const
{
return CalculateCoefficients().IsValid();
}
void
PolarInfo::GetString(TCHAR* line, size_t size, bool include_v_no) const
{
fixed V1, V2, V3;
V1 = Units::ToUserUnit(v1, Unit::KILOMETER_PER_HOUR);
V2 = Units::ToUserUnit(v2, Unit::KILOMETER_PER_HOUR);
V3 = Units::ToUserUnit(v3, Unit::KILOMETER_PER_HOUR);
if (include_v_no)
_sntprintf(line, size, _T("%.0f,%.0f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f"),
(double)reference_mass, (double)max_ballast, (double)V1, (double)w1,
(double)V2, (double)w2, (double)V3, (double)w3,
(double)wing_area, (double)v_no);
else
_sntprintf(line, size, _T("%.0f,%.0f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f"),
(double)reference_mass, (double)max_ballast, (double)V1, (double)w1,
(double)V2, (double)w2, (double)V3, (double)w3,
(double)wing_area);
}
bool
PolarInfo::ReadString(const TCHAR *line)
{
PolarInfo polar;
// Example:
// *LS-3 WinPilot POLAR file: MassDryGross[kg], MaxWaterBallast[liters], Speed1[km/h], Sink1[m/s], Speed2, Sink2, Speed3, Sink3
// 403, 101, 115.03, -0.86, 174.04, -1.76, 212.72, -3.4
if (line[0] == _T('*'))
/* a comment */
return false;
TCHAR *p;
polar.reference_mass = fixed(_tcstod(line, &p));
if (*p != _T(','))
return false;
polar.max_ballast = fixed(_tcstod(p + 1, &p));
if (*p != _T(','))
return false;
polar.v1 = Units::ToSysUnit(fixed(_tcstod(p + 1, &p)), Unit::KILOMETER_PER_HOUR);
if (*p != _T(','))
return false;
polar.w1 = fixed(_tcstod(p + 1, &p));
if (*p != _T(','))
return false;
polar.v2 = Units::ToSysUnit(fixed(_tcstod(p + 1, &p)), Unit::KILOMETER_PER_HOUR);
if (*p != _T(','))
return false;
polar.w2 = fixed(_tcstod(p + 1, &p));
if (*p != _T(','))
return false;
polar.v3 = Units::ToSysUnit(fixed(_tcstod(p + 1, &p)), Unit::KILOMETER_PER_HOUR);
if (*p != _T(','))
return false;
polar.w3 = fixed(_tcstod(p + 1, &p));
polar.wing_area = (*p != _T(',')) ? fixed_zero : fixed(_tcstod(p + 1, &p));
polar.v_no = (*p != _T(',')) ? fixed_zero : fixed(_tcstod(p + 1, &p));
*this = polar;
return true;
}
| damianob/xcsoar_mess | src/Polar/Polar.cpp | C++ | gpl-2.0 | 3,382 |
package io.mycat.backend.postgresql;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.NetworkChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import io.mycat.backend.jdbc.ShowVariables;
import io.mycat.backend.mysql.CharsetUtil;
import io.mycat.backend.mysql.nio.MySQLConnectionHandler;
import io.mycat.backend.mysql.nio.handler.ResponseHandler;
import io.mycat.backend.postgresql.packet.Query;
import io.mycat.backend.postgresql.packet.Terminate;
import io.mycat.backend.postgresql.utils.PIOUtils;
import io.mycat.backend.postgresql.utils.PacketUtils;
import io.mycat.backend.postgresql.utils.PgSqlApaterUtils;
import io.mycat.config.Isolations;
import io.mycat.net.BackendAIOConnection;
import io.mycat.route.RouteResultsetNode;
import io.mycat.server.ServerConnection;
import io.mycat.server.parser.ServerParse;
import io.mycat.util.exception.UnknownTxIsolationException;
/*************************************************************
* PostgreSQL Native Connection impl
*
* @author Coollf
*
*/
public class PostgreSQLBackendConnection extends BackendAIOConnection {
public static enum BackendConnectionState {
closed, connected, connecting
}
private static class StatusSync {
private final Boolean autocommit;
private final Integer charsetIndex;
private final String schema;
private final AtomicInteger synCmdCount;
private final Integer txtIsolation;
private final boolean xaStarted;
public StatusSync(boolean xaStarted, String schema, Integer charsetIndex, Integer txtIsolation,
Boolean autocommit, int synCount) {
super();
this.xaStarted = xaStarted;
this.schema = schema;
this.charsetIndex = charsetIndex;
this.txtIsolation = txtIsolation;
this.autocommit = autocommit;
this.synCmdCount = new AtomicInteger(synCount);
}
public boolean synAndExecuted(PostgreSQLBackendConnection conn) {
int remains = synCmdCount.decrementAndGet();
if (remains == 0) {// syn command finished
this.updateConnectionInfo(conn);
conn.metaDataSyned = true;
return false;
} else if (remains < 0) {
return true;
}
return false;
}
private void updateConnectionInfo(PostgreSQLBackendConnection conn)
{
conn.xaStatus = (xaStarted) ? 1 : 0;
if (schema != null) {
conn.schema = schema;
conn.oldSchema = conn.schema;
}
if (charsetIndex != null) {
conn.setCharset(CharsetUtil.getCharset(charsetIndex));
}
if (txtIsolation != null) {
conn.txIsolation = txtIsolation;
}
if (autocommit != null) {
conn.autocommit = autocommit;
}
}
}
private static final Query _COMMIT = new Query("commit");
private static final Query _ROLLBACK = new Query("rollback");
private static void getCharsetCommand(StringBuilder sb, int clientCharIndex) {
sb.append("SET names '").append(CharsetUtil.getCharset(clientCharIndex).toUpperCase()).append("';");
}
/**
* 获取 更改事物级别sql
*
* @param
* @param txIsolation
*/
private static void getTxIsolationCommand(StringBuilder sb, int txIsolation) {
switch (txIsolation) {
case Isolations.READ_UNCOMMITTED:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
return;
case Isolations.READ_COMMITTED:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;");
return;
case Isolations.REPEATED_READ:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
return;
case Isolations.SERIALIZABLE:
sb.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;");
return;
default:
throw new UnknownTxIsolationException("txIsolation:" + txIsolation);
}
}
private Object attachment;
private volatile boolean autocommit=true;
private volatile boolean borrowed;
protected volatile String charset = "utf8";
/***
* 当前事物ID
*/
private volatile String currentXaTxId;
/**
* 来自子接口
*/
private volatile boolean fromSlaveDB;
/****
* PG是否在事物中
*/
private volatile boolean inTransaction = false;
private AtomicBoolean isQuit = new AtomicBoolean(false);
private volatile long lastTime;
/**
* 元数据同步
*/
private volatile boolean metaDataSyned = true;
private volatile boolean modifiedSQLExecuted = false;
private volatile String oldSchema;
/**
* 密码
*/
private volatile String password;
/**
* 数据源配置
*/
private PostgreSQLDataSource pool;
/***
* 响应handler
*/
private volatile ResponseHandler responseHandler;
/***
* 对应数据库空间
*/
private volatile String schema;
// PostgreSQL服务端密码
private volatile int serverSecretKey;
private volatile BackendConnectionState state = BackendConnectionState.connecting;
private volatile StatusSync statusSync;
private volatile int txIsolation;
/***
* 用户名
*/
private volatile String user;
private volatile int xaStatus;
public PostgreSQLBackendConnection(NetworkChannel channel, boolean fromSlaveDB) {
super(channel);
this.fromSlaveDB = fromSlaveDB;
}
@Override
public void commit() {
ByteBuffer buf = this.allocate();
_COMMIT.write(buf);
this.write(buf);
}
@Override
public void execute(RouteResultsetNode rrn, ServerConnection sc, boolean autocommit) throws IOException {
int sqlType = rrn.getSqlType();
String orgin = rrn.getStatement();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{}查询任务。。。。{}", id, rrn.getStatement());
LOGGER.debug(orgin);
}
//FIX BUG https://github.com/MyCATApache/Mycat-Server/issues/1185
if (sqlType == ServerParse.SELECT || sqlType == ServerParse.SHOW) {
if (sqlType == ServerParse.SHOW) {
//此处进行部分SHOW 语法适配
String _newSql = PgSqlApaterUtils.apater(orgin);
if(_newSql.trim().substring(0,4).equalsIgnoreCase("show")){//未能适配成功
ShowVariables.execute(sc, orgin, this);
return;
}
} else if ("SELECT CONNECTION_ID()".equalsIgnoreCase(orgin)) {
ShowVariables.justReturnValue(sc, String.valueOf(sc.getId()), this);
return;
}
}
if (!modifiedSQLExecuted && rrn.isModifySQL()) {
modifiedSQLExecuted = true;
}
String xaTXID = sc.getSession2().getXaTXID();
synAndDoExecute(xaTXID, rrn, sc.getCharsetIndex(), sc.getTxIsolation(), autocommit);
}
@Override
public Object getAttachment() {
return attachment;
}
private void getAutocommitCommand(StringBuilder sb, boolean autoCommit) {
if (autoCommit) {
sb.append(/*"SET autocommit=1;"*/"");//Fix bug 由于 PG9.0 开始不支持此选项,默认是为自动提交逻辑。
} else {
sb.append("begin transaction;");
}
}
@Override
public long getLastTime() {
return lastTime;
}
public String getPassword() {
return password;
}
public PostgreSQLDataSource getPool() {
return pool;
}
public ResponseHandler getResponseHandler() {
return responseHandler;
}
@Override
public String getSchema() {
return this.schema;
}
public int getServerSecretKey() {
return serverSecretKey;
}
public BackendConnectionState getState() {
return state;
}
@Override
public int getTxIsolation() {
return txIsolation;
}
public String getUser() {
return user;
}
@Override
public boolean isAutocommit() {
return autocommit;
}
@Override
public boolean isBorrowed() {
return borrowed;
}
@Override
public boolean isClosedOrQuit() {
return isClosed() || isQuit.get();
}
@Override
public boolean isFromSlaveDB() {
return fromSlaveDB;
}
public boolean isInTransaction() {
return inTransaction;
}
@Override
public boolean isModifiedSQLExecuted() {
return modifiedSQLExecuted;
}
@Override
public void onConnectFailed(Throwable t) {
if (handler instanceof MySQLConnectionHandler) {
}
}
@Override
public void onConnectfinish() {
LOGGER.debug("连接后台真正完成");
try {
SocketChannel chan = (SocketChannel) this.channel;
ByteBuffer buf = PacketUtils.makeStartUpPacket(user, schema);
buf.flip();
chan.write(buf);
} catch (Exception e) {
LOGGER.error("Connected PostgreSQL Send StartUpPacket ERROR", e);
throw new RuntimeException(e);
}
}
protected final int getPacketLength(ByteBuffer buffer, int offset) {
// Pg 协议获取包长度的方法和mysql 不一样
return PIOUtils.redInteger4(buffer, offset + 1) + 1;
}
/**********
* 此查询用于心跳检查和获取连接后的健康检查
*/
@Override
public void query(String query) throws UnsupportedEncodingException {
RouteResultsetNode rrn = new RouteResultsetNode("default", ServerParse.SELECT, query);
synAndDoExecute(null, rrn, this.charsetIndex, this.txIsolation, true);
}
@Override
public void quit() {
if (isQuit.compareAndSet(false, true) && !isClosed()) {
if (state == BackendConnectionState.connected) {// 断开 与PostgreSQL连接
Terminate terminate = new Terminate();
ByteBuffer buf = this.allocate();
terminate.write(buf);
write(buf);
} else {
close("normal");
}
}
}
/*******
* 记录sql执行信息
*/
@Override
public void recordSql(String host, String schema, String statement) {
LOGGER.debug(String.format("executed sql: host=%s,schema=%s,statement=%s", host, schema, statement));
}
@Override
public void release() {
if (!metaDataSyned) {/*
* indicate connection not normalfinished ,and
* we can't know it's syn status ,so close it
*/
LOGGER.warn("can't sure connection syn result,so close it " + this);
this.responseHandler = null;
this.close("syn status unkown ");
return;
}
metaDataSyned = true;
attachment = null;
statusSync = null;
modifiedSQLExecuted = false;
setResponseHandler(null);
pool.releaseChannel(this);
}
@Override
public void rollback() {
ByteBuffer buf = this.allocate();
_ROLLBACK.write(buf);
this.write(buf);
}
@Override
public void setAttachment(Object attachment) {
this.attachment = attachment;
}
@Override
public void setBorrowed(boolean borrowed) {
this.borrowed = borrowed;
}
public void setInTransaction(boolean inTransaction) {
this.inTransaction = inTransaction;
}
@Override
public void setLastTime(long currentTimeMillis) {
this.lastTime = currentTimeMillis;
}
public void setPassword(String password) {
this.password = password;
}
public void setPool(PostgreSQLDataSource pool) {
this.pool = pool;
}
@Override
public boolean setResponseHandler(ResponseHandler commandHandler) {
this.responseHandler = commandHandler;
return true;
}
@Override
public void setSchema(String newSchema) {
String curSchema = schema;
if (curSchema == null) {
this.schema = newSchema;
this.oldSchema = newSchema;
} else {
this.oldSchema = curSchema;
this.schema = newSchema;
}
}
public void setServerSecretKey(int serverSecretKey) {
this.serverSecretKey = serverSecretKey;
}
public void setState(BackendConnectionState state) {
this.state = state;
}
public void setUser(String user) {
this.user = user;
}
private void synAndDoExecute(String xaTxID, RouteResultsetNode rrn, int clientCharSetIndex, int clientTxIsoLation,
boolean clientAutoCommit) {
String xaCmd = null;
boolean conAutoComit = this.autocommit;
String conSchema = this.schema;
// never executed modify sql,so auto commit
boolean expectAutocommit = !modifiedSQLExecuted || isFromSlaveDB() || clientAutoCommit;
if (!expectAutocommit && xaTxID != null && xaStatus == 0) {
clientTxIsoLation = Isolations.SERIALIZABLE;
xaCmd = "XA START " + xaTxID + ';';
currentXaTxId = xaTxID;
}
int schemaSyn = conSchema.equals(oldSchema) ? 0 : 1;
int charsetSyn = (this.charsetIndex == clientCharSetIndex) ? 0 : 1;
int txIsoLationSyn = (txIsolation == clientTxIsoLation) ? 0 : 1;
int autoCommitSyn = (conAutoComit == expectAutocommit) ? 0 : 1;
int synCount = schemaSyn + charsetSyn + txIsoLationSyn + autoCommitSyn;
if (synCount == 0) {
String sql = rrn.getStatement();
Query query = new Query(PgSqlApaterUtils.apater(sql));
ByteBuffer buf = this.allocate();// XXX 此处处理问题
query.write(buf);
this.write(buf);
return;
}
// TODO COOLLF 此处大锅待实现. 相关 事物, 切换 库,自动提交等功能实现
StringBuilder sb = new StringBuilder();
if (charsetSyn == 1) {
getCharsetCommand(sb, clientCharSetIndex);
}
if (txIsoLationSyn == 1) {
getTxIsolationCommand(sb, clientTxIsoLation);
}
if (autoCommitSyn == 1) {
getAutocommitCommand(sb, expectAutocommit);
}
if (xaCmd != null) {
sb.append(xaCmd);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("con need syn ,total syn cmd " + synCount + " commands " + sb.toString() + "schema change:"
+ ("" != null) + " con:" + this);
}
metaDataSyned = false;
statusSync = new StatusSync(xaCmd != null, conSchema, clientCharSetIndex, clientTxIsoLation, expectAutocommit,
synCount);
String sql = sb.append(PgSqlApaterUtils.apater(rrn.getStatement())).toString();
if(LOGGER.isDebugEnabled()){
LOGGER.debug("con={}, SQL={}", this, sql);
}
Query query = new Query(sql);
ByteBuffer buf = allocate();// 申请ByetBuffer
query.write(buf);
this.write(buf);
metaDataSyned = true;
}
public void close(String reason) {
if (!isClosed.get()) {
isQuit.set(true);
super.close(reason);
pool.connectionClosed(this);
if (this.responseHandler != null) {
this.responseHandler.connectionClose(this, reason);
responseHandler = null;
}
}
}
@Override
public boolean syncAndExcute() {
StatusSync sync = this.statusSync;
if (sync != null) {
boolean executed = sync.synAndExecuted(this);
if (executed) {
statusSync = null;
}
return executed;
}
return true;
}
@Override
public String toString() {
return "PostgreSQLBackendConnection [id=" + id + ", host=" + host + ", port=" + port + ", localPort="
+ localPort + "]";
}
}
| inspur-iop/Mycat-Server | src/main/java/io/mycat/backend/postgresql/PostgreSQLBackendConnection.java | Java | gpl-2.0 | 14,050 |
<?php
// @codingStandardsIgnoreFile
namespace Drupal\Tests\Component\Annotation\Doctrine;
use Drupal\Component\Annotation\Doctrine\DocParser;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\Annotation\Target;
use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants;
use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants;
use Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \Drupal\Component\Annotation\Doctrine\DocParser
*
* This class is a near-copy of
* Doctrine\Tests\Common\Annotations\DocParserTest, which is part of the
* Doctrine project: <http://www.doctrine-project.org>. It was copied from
* version 1.2.7.
*
* The supporting test fixture classes in
* core/tests/Drupal/Tests/Component/Annotation/Doctrine/Fixtures were also
* copied from version 1.2.7.
*
* @group Annotation
*/
class DocParserTest extends TestCase
{
public function testNestedArraysWithNestedAnnotation()
{
$parser = $this->createTestParser();
// Nested arrays with nested annotations
$result = $parser->parse('@Name(foo={1,2, {"key"=@Name}})');
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertNull($annot->value);
$this->assertEquals(3, count($annot->foo));
$this->assertEquals(1, $annot->foo[0]);
$this->assertEquals(2, $annot->foo[1]);
$this->assertTrue(is_array($annot->foo[2]));
$nestedArray = $annot->foo[2];
$this->assertTrue(isset($nestedArray['key']));
$this->assertTrue($nestedArray['key'] instanceof Name);
}
public function testBasicAnnotations()
{
$parser = $this->createTestParser();
// Marker annotation
$result = $parser->parse("@Name");
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertNull($annot->value);
$this->assertNull($annot->foo);
// Associative arrays
$result = $parser->parse('@Name(foo={"key1" = "value1"})');
$annot = $result[0];
$this->assertNull($annot->value);
$this->assertTrue(is_array($annot->foo));
$this->assertTrue(isset($annot->foo['key1']));
// Numerical arrays
$result = $parser->parse('@Name({2="foo", 4="bar"})');
$annot = $result[0];
$this->assertTrue(is_array($annot->value));
$this->assertEquals('foo', $annot->value[2]);
$this->assertEquals('bar', $annot->value[4]);
$this->assertFalse(isset($annot->value[0]));
$this->assertFalse(isset($annot->value[1]));
$this->assertFalse(isset($annot->value[3]));
// Multiple values
$result = $parser->parse('@Name(@Name, @Name)');
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertTrue(is_array($annot->value));
$this->assertTrue($annot->value[0] instanceof Name);
$this->assertTrue($annot->value[1] instanceof Name);
// Multiple types as values
$result = $parser->parse('@Name(foo="Bar", @Name, {"key1"="value1", "key2"="value2"})');
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertTrue(is_array($annot->value));
$this->assertTrue($annot->value[0] instanceof Name);
$this->assertTrue(is_array($annot->value[1]));
$this->assertEquals('value1', $annot->value[1]['key1']);
$this->assertEquals('value2', $annot->value[1]['key2']);
// Complete docblock
$docblock = <<<DOCBLOCK
/**
* Some nifty class.
*
* @author Mr.X
* @Name(foo="bar")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(1, count($result));
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertEquals("bar", $annot->foo);
$this->assertNull($annot->value);
}
public function testDefaultValueAnnotations()
{
$parser = $this->createTestParser();
// Array as first value
$result = $parser->parse('@Name({"key1"="value1"})');
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertTrue(is_array($annot->value));
$this->assertEquals('value1', $annot->value['key1']);
// Array as first value and additional values
$result = $parser->parse('@Name({"key1"="value1"}, foo="bar")');
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertTrue(is_array($annot->value));
$this->assertEquals('value1', $annot->value['key1']);
$this->assertEquals('bar', $annot->foo);
}
public function testNamespacedAnnotations()
{
$parser = new DocParser;
$parser->setIgnoreNotImportedAnnotations(true);
$docblock = <<<DOCBLOCK
/**
* Some nifty class.
*
* @package foo
* @subpackage bar
* @author Mr.X <mr@x.com>
* @Drupal\Tests\Component\Annotation\Doctrine\Name(foo="bar")
* @ignore
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(1, count($result));
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertEquals("bar", $annot->foo);
}
/**
* @group debug
*/
public function testTypicalMethodDocBlock()
{
$parser = $this->createTestParser();
$docblock = <<<DOCBLOCK
/**
* Some nifty method.
*
* @since 2.0
* @Drupal\Tests\Component\Annotation\Doctrine\Name(foo="bar")
* @param string \$foo This is foo.
* @param mixed \$bar This is bar.
* @return string Foo and bar.
* @This is irrelevant
* @Marker
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(2, count($result));
$this->assertTrue(isset($result[0]));
$this->assertTrue(isset($result[1]));
$annot = $result[0];
$this->assertTrue($annot instanceof Name);
$this->assertEquals("bar", $annot->foo);
$marker = $result[1];
$this->assertTrue($marker instanceof Marker);
}
public function testAnnotationWithoutConstructor()
{
$parser = $this->createTestParser();
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor("Some data")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertNotNull($annot);
$this->assertTrue($annot instanceof SomeAnnotationClassNameWithoutConstructor);
$this->assertNull($annot->name);
$this->assertNotNull($annot->data);
$this->assertEquals($annot->data, "Some data");
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor(name="Some Name", data = "Some data")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertNotNull($annot);
$this->assertTrue($annot instanceof SomeAnnotationClassNameWithoutConstructor);
$this->assertEquals($annot->name, "Some Name");
$this->assertEquals($annot->data, "Some data");
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor(data = "Some data")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertEquals($annot->data, "Some data");
$this->assertNull($annot->name);
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor(name = "Some name")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertEquals($annot->name, "Some name");
$this->assertNull($annot->data);
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor("Some data")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertEquals($annot->data, "Some data");
$this->assertNull($annot->name);
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor("Some data",name = "Some name")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertEquals($annot->name, "Some name");
$this->assertEquals($annot->data, "Some data");
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationWithConstructorWithoutParams(name = "Some name")
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$annot = $result[0];
$this->assertEquals($annot->name, "Some name");
$this->assertEquals($annot->data, "Some data");
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructorAndProperties()
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertEquals(count($result), 1);
$this->assertTrue($result[0] instanceof SomeAnnotationClassNameWithoutConstructorAndProperties);
}
public function testAnnotationTarget()
{
$parser = new DocParser;
$parser->setImports(array(
'__NAMESPACE__' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures',
));
$class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithValidAnnotationTarget');
$context = 'class ' . $class->getName();
$docComment = $class->getDocComment();
$parser->setTarget(Target::TARGET_CLASS);
$this->assertNotNull($parser->parse($docComment,$context));
$property = $class->getProperty('foo');
$docComment = $property->getDocComment();
$context = 'property ' . $class->getName() . "::\$" . $property->getName();
$parser->setTarget(Target::TARGET_PROPERTY);
$this->assertNotNull($parser->parse($docComment,$context));
$method = $class->getMethod('someFunction');
$docComment = $property->getDocComment();
$context = 'method ' . $class->getName() . '::' . $method->getName() . '()';
$parser->setTarget(Target::TARGET_METHOD);
$this->assertNotNull($parser->parse($docComment,$context));
try {
$class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtClass');
$context = 'class ' . $class->getName();
$docComment = $class->getDocComment();
$parser->setTarget(Target::TARGET_CLASS);
$parser->parse($docComment, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertNotNull($exc->getMessage());
}
try {
$class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtMethod');
$method = $class->getMethod('functionName');
$docComment = $method->getDocComment();
$context = 'method ' . $class->getName() . '::' . $method->getName() . '()';
$parser->setTarget(Target::TARGET_METHOD);
$parser->parse($docComment, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertNotNull($exc->getMessage());
}
try {
$class = new \ReflectionClass('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithInvalidAnnotationTargetAtProperty');
$property = $class->getProperty('foo');
$docComment = $property->getDocComment();
$context = 'property ' . $class->getName() . "::\$" . $property->getName();
$parser->setTarget(Target::TARGET_PROPERTY);
$parser->parse($docComment, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertNotNull($exc->getMessage());
}
}
public function getAnnotationVarTypeProviderValid()
{
//({attribute name}, {attribute value})
return array(
// mixed type
array('mixed', '"String Value"'),
array('mixed', 'true'),
array('mixed', 'false'),
array('mixed', '1'),
array('mixed', '1.2'),
array('mixed', '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll'),
// boolean type
array('boolean', 'true'),
array('boolean', 'false'),
// alias for internal type boolean
array('bool', 'true'),
array('bool', 'false'),
// integer type
array('integer', '0'),
array('integer', '1'),
array('integer', '123456789'),
array('integer', '9223372036854775807'),
// alias for internal type double
array('float', '0.1'),
array('float', '1.2'),
array('float', '123.456'),
// string type
array('string', '"String Value"'),
array('string', '"true"'),
array('string', '"123"'),
// array type
array('array', '{@AnnotationExtendsAnnotationTargetAll}'),
array('array', '{@AnnotationExtendsAnnotationTargetAll,@AnnotationExtendsAnnotationTargetAll}'),
array('arrayOfIntegers', '1'),
array('arrayOfIntegers', '{1}'),
array('arrayOfIntegers', '{1,2,3,4}'),
array('arrayOfAnnotations', '@AnnotationExtendsAnnotationTargetAll'),
array('arrayOfAnnotations', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll}'),
array('arrayOfAnnotations', '{@AnnotationExtendsAnnotationTargetAll, @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll}'),
// annotation instance
array('annotation', '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll'),
array('annotation', '@AnnotationExtendsAnnotationTargetAll'),
);
}
public function getAnnotationVarTypeProviderInvalid()
{
//({attribute name}, {type declared type}, {attribute value} , {given type or class})
return array(
// boolean type
array('boolean','boolean','1','integer'),
array('boolean','boolean','1.2','double'),
array('boolean','boolean','"str"','string'),
array('boolean','boolean','{1,2,3}','array'),
array('boolean','boolean','@Name', 'an instance of Drupal\Tests\Component\Annotation\Doctrine\Name'),
// alias for internal type boolean
array('bool','bool', '1','integer'),
array('bool','bool', '1.2','double'),
array('bool','bool', '"str"','string'),
array('bool','bool', '{"str"}','array'),
// integer type
array('integer','integer', 'true','boolean'),
array('integer','integer', 'false','boolean'),
array('integer','integer', '1.2','double'),
array('integer','integer', '"str"','string'),
array('integer','integer', '{"str"}','array'),
array('integer','integer', '{1,2,3,4}','array'),
// alias for internal type double
array('float','float', 'true','boolean'),
array('float','float', 'false','boolean'),
array('float','float', '123','integer'),
array('float','float', '"str"','string'),
array('float','float', '{"str"}','array'),
array('float','float', '{12.34}','array'),
array('float','float', '{1,2,3}','array'),
// string type
array('string','string', 'true','boolean'),
array('string','string', 'false','boolean'),
array('string','string', '12','integer'),
array('string','string', '1.2','double'),
array('string','string', '{"str"}','array'),
array('string','string', '{1,2,3,4}','array'),
// annotation instance
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'true','boolean'),
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'false','boolean'),
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '12','integer'),
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '1.2','double'),
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{"str"}','array'),
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{1,2,3,4}','array'),
array('annotation','Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '@Name','an instance of Drupal\Tests\Component\Annotation\Doctrine\Name'),
);
}
public function getAnnotationVarTypeArrayProviderInvalid()
{
//({attribute name}, {type declared type}, {attribute value} , {given type or class})
return array(
array('arrayOfIntegers', 'integer', 'true', 'boolean'),
array('arrayOfIntegers', 'integer', 'false', 'boolean'),
array('arrayOfIntegers', 'integer', '{true,true}', 'boolean'),
array('arrayOfIntegers', 'integer', '{1,true}', 'boolean'),
array('arrayOfIntegers', 'integer', '{1,2,1.2}', 'double'),
array('arrayOfIntegers', 'integer', '{1,2,"str"}', 'string'),
array('arrayOfStrings', 'string', 'true', 'boolean'),
array('arrayOfStrings', 'string', 'false', 'boolean'),
array('arrayOfStrings', 'string', '{true,true}', 'boolean'),
array('arrayOfStrings', 'string', '{"foo",true}', 'boolean'),
array('arrayOfStrings', 'string', '{"foo","bar",1.2}', 'double'),
array('arrayOfStrings', 'string', '1', 'integer'),
array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'true', 'boolean'),
array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', 'false', 'boolean'),
array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,true}', 'boolean'),
array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,true}', 'boolean'),
array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,1.2}', 'double'),
array('arrayOfAnnotations', 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll', '{@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll,@AnnotationExtendsAnnotationTargetAll,"str"}', 'string'),
);
}
/**
* @dataProvider getAnnotationVarTypeProviderValid
*/
public function testAnnotationWithVarType($attribute, $value)
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::$invalidProperty.';
$docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value);
$parser->setTarget(Target::TARGET_PROPERTY);
$result = $parser->parse($docblock, $context);
$this->assertTrue(sizeof($result) === 1);
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType', $result[0]);
$this->assertNotNull($result[0]->$attribute);
}
/**
* @dataProvider getAnnotationVarTypeProviderInvalid
*/
public function testAnnotationWithVarTypeError($attribute,$type,$value,$given)
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value);
$parser->setTarget(Target::TARGET_PROPERTY);
try {
$parser->parse($docblock, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType declared on property SomeClassName::invalidProperty. expects a(n) $type, but got $given.", $exc->getMessage());
}
}
/**
* @dataProvider getAnnotationVarTypeArrayProviderInvalid
*/
public function testAnnotationWithVarTypeArrayError($attribute,$type,$value,$given)
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType(%s = %s)',$attribute, $value);
$parser->setTarget(Target::TARGET_PROPERTY);
try {
$parser->parse($docblock, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithVarType declared on property SomeClassName::invalidProperty. expects either a(n) $type, or an array of {$type}s, but got $given.", $exc->getMessage());
}
}
/**
* @dataProvider getAnnotationVarTypeProviderValid
*/
public function testAnnotationWithAttributes($attribute, $value)
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::$invalidProperty.';
$docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value);
$parser->setTarget(Target::TARGET_PROPERTY);
$result = $parser->parse($docblock, $context);
$this->assertTrue(sizeof($result) === 1);
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes', $result[0]);
$getter = "get".ucfirst($attribute);
$this->assertNotNull($result[0]->$getter());
}
/**
* @dataProvider getAnnotationVarTypeProviderInvalid
*/
public function testAnnotationWithAttributesError($attribute,$type,$value,$given)
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value);
$parser->setTarget(Target::TARGET_PROPERTY);
try {
$parser->parse($docblock, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes declared on property SomeClassName::invalidProperty. expects a(n) $type, but got $given.", $exc->getMessage());
}
}
/**
* @dataProvider getAnnotationVarTypeArrayProviderInvalid
*/
public function testAnnotationWithAttributesWithVarTypeArrayError($attribute,$type,$value,$given)
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$docblock = sprintf('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes(%s = %s)',$attribute, $value);
$parser->setTarget(Target::TARGET_PROPERTY);
try {
$parser->parse($docblock, $context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains("[Type Error] Attribute \"$attribute\" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithAttributes declared on property SomeClassName::invalidProperty. expects either a(n) $type, or an array of {$type}s, but got $given.", $exc->getMessage());
}
}
public function testAnnotationWithRequiredAttributes()
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$parser->setTarget(Target::TARGET_PROPERTY);
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes("Some Value", annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)';
$result = $parser->parse($docblock);
$this->assertTrue(sizeof($result) === 1);
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes', $result[0]);
$this->assertEquals("Some Value",$result[0]->getValue());
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation', $result[0]->getAnnot());
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes("Some Value")';
try {
$result = $parser->parse($docblock,$context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains('Attribute "annot" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes declared on property SomeClassName::invalidProperty. expects a(n) Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation. This value should not be null.', $exc->getMessage());
}
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes(annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)';
try {
$result = $parser->parse($docblock,$context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains('Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributes declared on property SomeClassName::invalidProperty. expects a(n) string. This value should not be null.', $exc->getMessage());
}
}
public function testAnnotationWithRequiredAttributesWithoutContructor()
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$parser->setTarget(Target::TARGET_PROPERTY);
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor("Some Value", annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)';
$result = $parser->parse($docblock);
$this->assertTrue(sizeof($result) === 1);
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor', $result[0]);
$this->assertEquals("Some Value", $result[0]->value);
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation', $result[0]->annot);
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor("Some Value")';
try {
$result = $parser->parse($docblock,$context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains('Attribute "annot" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor declared on property SomeClassName::invalidProperty. expects a(n) Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation. This value should not be null.', $exc->getMessage());
}
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor(annot = @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAnnotation)';
try {
$result = $parser->parse($docblock,$context);
$this->fail();
} catch (\Doctrine\Common\Annotations\AnnotationException $exc) {
$this->assertContains('Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithRequiredAttributesWithoutContructor declared on property SomeClassName::invalidProperty. expects a(n) string. This value should not be null.', $exc->getMessage());
}
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnum declared on property SomeClassName::invalidProperty. accept only [ONE, TWO, THREE], but got FOUR.
*/
public function testAnnotationEnumeratorException()
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnum("FOUR")';
$parser->setIgnoreNotImportedAnnotations(false);
$parser->setTarget(Target::TARGET_PROPERTY);
$parser->parse($docblock, $context);
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage Attribute "value" of @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteral declared on property SomeClassName::invalidProperty. accept only [AnnotationEnumLiteral::ONE, AnnotationEnumLiteral::TWO, AnnotationEnumLiteral::THREE], but got 4.
*/
public function testAnnotationEnumeratorLiteralException()
{
$parser = $this->createTestParser();
$context = 'property SomeClassName::invalidProperty.';
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteral(4)';
$parser->setIgnoreNotImportedAnnotations(false);
$parser->setTarget(Target::TARGET_PROPERTY);
$parser->parse($docblock, $context);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage @Enum supports only scalar values "array" given.
*/
public function testAnnotationEnumInvalidTypeDeclarationException()
{
$parser = $this->createTestParser();
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumInvalid("foo")';
$parser->setIgnoreNotImportedAnnotations(false);
$parser->parse($docblock);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Undefined enumerator value "3" for literal "AnnotationEnumLiteral::THREE".
*/
public function testAnnotationEnumInvalidLiteralDeclarationException()
{
$parser = $this->createTestParser();
$docblock = '@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationEnumLiteralInvalid("foo")';
$parser->setIgnoreNotImportedAnnotations(false);
$parser->parse($docblock);
}
public function getConstantsProvider()
{
$provider[] = array(
'@AnnotationWithConstants(PHP_EOL)',
PHP_EOL
);
$provider[] = array(
'@AnnotationWithConstants(AnnotationWithConstants::INTEGER)',
AnnotationWithConstants::INTEGER
);
$provider[] = array(
'@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants(AnnotationWithConstants::STRING)',
AnnotationWithConstants::STRING
);
$provider[] = array(
'@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::FLOAT)',
AnnotationWithConstants::FLOAT
);
$provider[] = array(
'@AnnotationWithConstants(ClassWithConstants::SOME_VALUE)',
ClassWithConstants::SOME_VALUE
);
$provider[] = array(
'@AnnotationWithConstants(ClassWithConstants::OTHER_KEY_)',
ClassWithConstants::OTHER_KEY_
);
$provider[] = array(
'@AnnotationWithConstants(ClassWithConstants::OTHER_KEY_2)',
ClassWithConstants::OTHER_KEY_2
);
$provider[] = array(
'@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants::SOME_VALUE)',
ClassWithConstants::SOME_VALUE
);
$provider[] = array(
'@AnnotationWithConstants(IntefaceWithConstants::SOME_VALUE)',
IntefaceWithConstants::SOME_VALUE
);
$provider[] = array(
'@AnnotationWithConstants(\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_VALUE)',
IntefaceWithConstants::SOME_VALUE
);
$provider[] = array(
'@AnnotationWithConstants({AnnotationWithConstants::STRING, AnnotationWithConstants::INTEGER, AnnotationWithConstants::FLOAT})',
array(AnnotationWithConstants::STRING, AnnotationWithConstants::INTEGER, AnnotationWithConstants::FLOAT)
);
$provider[] = array(
'@AnnotationWithConstants({
AnnotationWithConstants::STRING = AnnotationWithConstants::INTEGER
})',
array(AnnotationWithConstants::STRING => AnnotationWithConstants::INTEGER)
);
$provider[] = array(
'@AnnotationWithConstants({
Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_KEY = AnnotationWithConstants::INTEGER
})',
array(IntefaceWithConstants::SOME_KEY => AnnotationWithConstants::INTEGER)
);
$provider[] = array(
'@AnnotationWithConstants({
\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants::SOME_KEY = AnnotationWithConstants::INTEGER
})',
array(IntefaceWithConstants::SOME_KEY => AnnotationWithConstants::INTEGER)
);
$provider[] = array(
'@AnnotationWithConstants({
AnnotationWithConstants::STRING = AnnotationWithConstants::INTEGER,
ClassWithConstants::SOME_KEY = ClassWithConstants::SOME_VALUE,
Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants::SOME_KEY = IntefaceWithConstants::SOME_VALUE
})',
array(
AnnotationWithConstants::STRING => AnnotationWithConstants::INTEGER,
ClassWithConstants::SOME_KEY => ClassWithConstants::SOME_VALUE,
ClassWithConstants::SOME_KEY => IntefaceWithConstants::SOME_VALUE
)
);
$provider[] = array(
'@AnnotationWithConstants(AnnotationWithConstants::class)',
'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants'
);
$provider[] = array(
'@AnnotationWithConstants({AnnotationWithConstants::class = AnnotationWithConstants::class})',
array('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants')
);
$provider[] = array(
'@AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::class)',
'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants'
);
$provider[] = array(
'@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants(Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants::class)',
'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants'
);
return $provider;
}
/**
* @dataProvider getConstantsProvider
*/
public function testSupportClassConstants($docblock, $expected)
{
$parser = $this->createTestParser();
$parser->setImports(array(
'classwithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\ClassWithConstants',
'intefacewithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\IntefaceWithConstants',
'annotationwithconstants' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants'
));
$result = $parser->parse($docblock);
$this->assertInstanceOf('\Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithConstants', $annotation = $result[0]);
$this->assertEquals($expected, $annotation->value);
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage The annotation @SomeAnnotationClassNameWithoutConstructorAndProperties declared on does not accept any values, but got {"value":"Foo"}.
*/
public function testWithoutConstructorWhenIsNotDefaultValue()
{
$parser = $this->createTestParser();
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructorAndProperties("Foo")
*/
DOCBLOCK;
$parser->setTarget(Target::TARGET_CLASS);
$parser->parse($docblock);
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage The annotation @SomeAnnotationClassNameWithoutConstructorAndProperties declared on does not accept any values, but got {"value":"Foo"}.
*/
public function testWithoutConstructorWhenHasNoProperties()
{
$parser = $this->createTestParser();
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructorAndProperties(value = "Foo")
*/
DOCBLOCK;
$parser->setTarget(Target::TARGET_CLASS);
$parser->parse($docblock);
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage Expected namespace separator or identifier, got ')' at position 24 in class @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithTargetSyntaxError.
*/
public function testAnnotationTargetSyntaxError()
{
$parser = $this->createTestParser();
$context = 'class ' . 'SomeClassName';
$docblock = <<<DOCBLOCK
/**
* @Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationWithTargetSyntaxError()
*/
DOCBLOCK;
$parser->setTarget(Target::TARGET_CLASS);
$parser->parse($docblock,$context);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid Target "Foo". Available targets: [ALL, CLASS, METHOD, PROPERTY, ANNOTATION]
*/
public function testAnnotationWithInvalidTargetDeclarationError()
{
$parser = $this->createTestParser();
$context = 'class ' . 'SomeClassName';
$docblock = <<<DOCBLOCK
/**
* @AnnotationWithInvalidTargetDeclaration()
*/
DOCBLOCK;
$parser->setTarget(Target::TARGET_CLASS);
$parser->parse($docblock,$context);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage @Target expects either a string value, or an array of strings, "NULL" given.
*/
public function testAnnotationWithTargetEmptyError()
{
$parser = $this->createTestParser();
$context = 'class ' . 'SomeClassName';
$docblock = <<<DOCBLOCK
/**
* @AnnotationWithTargetEmpty()
*/
DOCBLOCK;
$parser->setTarget(Target::TARGET_CLASS);
$parser->parse($docblock,$context);
}
/**
* @group DDC-575
*/
public function testRegressionDDC575()
{
$parser = $this->createTestParser();
$docblock = <<<DOCBLOCK
/**
* @Name
*
* Will trigger error.
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertInstanceOf("Drupal\Tests\Component\Annotation\Doctrine\Name", $result[0]);
$docblock = <<<DOCBLOCK
/**
* @Name
* @Marker
*
* Will trigger error.
*/
DOCBLOCK;
$result = $parser->parse($docblock);
$this->assertInstanceOf("Drupal\Tests\Component\Annotation\Doctrine\Name", $result[0]);
}
/**
* @group DDC-77
*/
public function testAnnotationWithoutClassIsIgnoredWithoutWarning()
{
$parser = new DocParser();
$parser->setIgnoreNotImportedAnnotations(true);
$result = $parser->parse("@param");
$this->assertEquals(0, count($result));
}
/**
* @group DCOM-168
*/
public function testNotAnAnnotationClassIsIgnoredWithoutWarning()
{
$parser = new DocParser();
$parser->setIgnoreNotImportedAnnotations(true);
$parser->setIgnoredAnnotationNames(array('PHPUnit_Framework_TestCase' => true));
$result = $parser->parse('@PHPUnit_Framework_TestCase');
$this->assertEquals(0, count($result));
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage Expected PlainValue, got ''' at position 10.
*/
public function testAnnotationDontAcceptSingleQuotes()
{
$parser = $this->createTestParser();
$parser->parse("@Name(foo='bar')");
}
/**
* @group DCOM-41
*/
public function testAnnotationDoesntThrowExceptionWhenAtSignIsNotFollowedByIdentifier()
{
$parser = new DocParser();
$result = $parser->parse("'@'");
$this->assertEquals(0, count($result));
}
/**
* @group DCOM-41
* @expectedException \Doctrine\Common\Annotations\AnnotationException
*/
public function testAnnotationThrowsExceptionWhenAtSignIsNotFollowedByIdentifierInNestedAnnotation()
{
$parser = new DocParser();
$parser->parse("@Drupal\Tests\Component\Annotation\Doctrine\Name(@')");
}
/**
* @group DCOM-56
*/
public function testAutoloadAnnotation()
{
$this->assertFalse(class_exists('Drupal\Tests\Component\Annotation\Doctrine\Fixture\Annotation\Autoload', false), 'Pre-condition: Drupal\Tests\Component\Annotation\Doctrine\Fixture\Annotation\Autoload not allowed to be loaded.');
$parser = new DocParser();
AnnotationRegistry::registerAutoloadNamespace('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation', __DIR__ . '/../../../../');
$parser->setImports(array(
'autoload' => 'Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\Autoload',
));
$annotations = $parser->parse('@Autoload');
$this->assertEquals(1, count($annotations));
$this->assertInstanceOf('Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\Autoload', $annotations[0]);
}
public function createTestParser()
{
$parser = new DocParser();
$parser->setIgnoreNotImportedAnnotations(true);
$parser->setImports(array(
'name' => 'Drupal\Tests\Component\Annotation\Doctrine\Name',
'__NAMESPACE__' => 'Drupal\Tests\Component\Annotation\Doctrine',
));
return $parser;
}
/**
* @group DDC-78
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage Expected PlainValue, got ''' at position 10 in class \Drupal\Tests\Component\Annotation\Doctrine\Name
*/
public function testSyntaxErrorWithContextDescription()
{
$parser = $this->createTestParser();
$parser->parse("@Name(foo='bar')", "class \Drupal\Tests\Component\Annotation\Doctrine\Name");
}
/**
* @group DDC-183
*/
public function testSyntaxErrorWithUnknownCharacters()
{
$docblock = <<<DOCBLOCK
/**
* @test at.
*/
class A {
}
DOCBLOCK;
//$lexer = new \Doctrine\Common\Annotations\Lexer();
//$lexer->setInput(trim($docblock, '/ *'));
//var_dump($lexer);
try {
$parser = $this->createTestParser();
$result = $parser->parse($docblock);
$this->assertTrue(is_array($result) && empty($result));
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
}
/**
* @group DCOM-14
*/
public function testIgnorePHPDocThrowTag()
{
$docblock = <<<DOCBLOCK
/**
* @throws \RuntimeException
*/
class A {
}
DOCBLOCK;
try {
$parser = $this->createTestParser();
$result = $parser->parse($docblock);
$this->assertTrue(is_array($result) && empty($result));
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
}
/**
* @group DCOM-38
*/
public function testCastInt()
{
$parser = $this->createTestParser();
$result = $parser->parse("@Name(foo=1234)");
$annot = $result[0];
$this->assertInternalType('int', $annot->foo);
}
/**
* @group DCOM-38
*/
public function testCastNegativeInt()
{
$parser = $this->createTestParser();
$result = $parser->parse("@Name(foo=-1234)");
$annot = $result[0];
$this->assertInternalType('int', $annot->foo);
}
/**
* @group DCOM-38
*/
public function testCastFloat()
{
$parser = $this->createTestParser();
$result = $parser->parse("@Name(foo=1234.345)");
$annot = $result[0];
$this->assertInternalType('float', $annot->foo);
}
/**
* @group DCOM-38
*/
public function testCastNegativeFloat()
{
$parser = $this->createTestParser();
$result = $parser->parse("@Name(foo=-1234.345)");
$annot = $result[0];
$this->assertInternalType('float', $annot->foo);
$result = $parser->parse("@Marker(-1234.345)");
$annot = $result[0];
$this->assertInternalType('float', $annot->value);
}
public function testReservedKeywordsInAnnotations()
{
if (PHP_VERSION_ID >= 70000) {
$this->markTestSkipped('This test requires PHP 5.6 or lower.');
}
require 'ReservedKeywordsClasses.php';
$parser = $this->createTestParser();
$result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\True');
$this->assertTrue($result[0] instanceof True);
$result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\False');
$this->assertTrue($result[0] instanceof False);
$result = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\Null');
$this->assertTrue($result[0] instanceof Null);
$result = $parser->parse('@True');
$this->assertTrue($result[0] instanceof True);
$result = $parser->parse('@False');
$this->assertTrue($result[0] instanceof False);
$result = $parser->parse('@Null');
$this->assertTrue($result[0] instanceof Null);
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage [Creation Error] The annotation @SomeAnnotationClassNameWithoutConstructor declared on some class does not have a property named "invalidaProperty". Available properties: data, name
*/
public function testSetValuesExeption()
{
$docblock = <<<DOCBLOCK
/**
* @SomeAnnotationClassNameWithoutConstructor(invalidaProperty = "Some val")
*/
DOCBLOCK;
$this->createTestParser()->parse($docblock, 'some class');
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage [Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_IDENTIFIER or Doctrine\Common\Annotations\DocLexer::T_TRUE or Doctrine\Common\Annotations\DocLexer::T_FALSE or Doctrine\Common\Annotations\DocLexer::T_NULL, got '3.42' at position 5.
*/
public function testInvalidIdentifierInAnnotation()
{
$parser = $this->createTestParser();
$parser->parse('@Foo\3.42');
}
public function testTrailingCommaIsAllowed()
{
$parser = $this->createTestParser();
$annots = $parser->parse('@Name({
"Foo",
"Bar",
})');
$this->assertEquals(1, count($annots));
$this->assertEquals(array('Foo', 'Bar'), $annots[0]->value);
}
public function testDefaultAnnotationValueIsNotOverwritten()
{
$parser = $this->createTestParser();
$annots = $parser->parse('@Drupal\Tests\Component\Annotation\Doctrine\Fixtures\Annotation\AnnotWithDefaultValue');
$this->assertEquals(1, count($annots));
$this->assertEquals('bar', $annots[0]->foo);
}
public function testArrayWithColon()
{
$parser = $this->createTestParser();
$annots = $parser->parse('@Name({"foo": "bar"})');
$this->assertEquals(1, count($annots));
$this->assertEquals(array('foo' => 'bar'), $annots[0]->value);
}
/**
* @expectedException \Doctrine\Common\Annotations\AnnotationException
* @expectedExceptionMessage [Semantical Error] Couldn't find constant foo.
*/
public function testInvalidContantName()
{
$parser = $this->createTestParser();
$parser->parse('@Name(foo: "bar")');
}
/**
* Tests parsing empty arrays.
*/
public function testEmptyArray()
{
$parser = $this->createTestParser();
$annots = $parser->parse('@Name({"foo": {}})');
$this->assertEquals(1, count($annots));
$this->assertEquals(array('foo' => array()), $annots[0]->value);
}
public function testKeyHasNumber()
{
$parser = $this->createTestParser();
$annots = $parser->parse('@SettingsAnnotation(foo="test", bar2="test")');
$this->assertEquals(1, count($annots));
$this->assertEquals(array('foo' => 'test', 'bar2' => 'test'), $annots[0]->settings);
}
/**
* @group 44
*/
public function testSupportsEscapedQuotedValues()
{
$result = $this->createTestParser()->parse('@Drupal\Tests\Component\Annotation\Doctrine\Name(foo="""bar""")');
$this->assertCount(1, $result);
$this->assertTrue($result[0] instanceof Name);
$this->assertEquals('"bar"', $result[0]->foo);
}
}
/** @Annotation */
class SettingsAnnotation
{
public $settings;
public function __construct($settings)
{
$this->settings = $settings;
}
}
/** @Annotation */
class SomeAnnotationClassNameWithoutConstructor
{
public $data;
public $name;
}
/** @Annotation */
class SomeAnnotationWithConstructorWithoutParams
{
function __construct()
{
$this->data = "Some data";
}
public $data;
public $name;
}
/** @Annotation */
class SomeAnnotationClassNameWithoutConstructorAndProperties{}
/**
* @Annotation
* @Target("Foo")
*/
class AnnotationWithInvalidTargetDeclaration{}
/**
* @Annotation
* @Target
*/
class AnnotationWithTargetEmpty{}
/** @Annotation */
class AnnotationExtendsAnnotationTargetAll extends \Drupal\Tests\Component\Annotation\Doctrine\Fixtures\AnnotationTargetAll
{
}
/** @Annotation */
class Name extends \Doctrine\Common\Annotations\Annotation {
public $foo;
}
/** @Annotation */
class Marker {
public $value;
}
namespace Drupal\Tests\Component\Annotation\Doctrine\FooBar;
/** @Annotation */
class Name extends \Doctrine\Common\Annotations\Annotation {
}
| savaslabs/durham-civil-rights-map | core/tests/Drupal/Tests/Component/Annotation/Doctrine/DocParserTest.php | PHP | gpl-2.0 | 52,547 |
/*
* Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/>
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.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 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
*/
#include "MovementPacketBuilder.h"
#include "MoveSpline.h"
#include "ByteBuffer.h"
namespace Movement
{
inline void operator << (ByteBuffer& b, const Vector3& v)
{
b << v.x << v.y << v.z;
}
inline void operator >> (ByteBuffer& b, Vector3& v)
{
b >> v.x >> v.y >> v.z;
}
enum MonsterMoveType
{
MonsterMoveNormal = 0,
MonsterMoveStop = 1,
MonsterMoveFacingSpot = 2,
MonsterMoveFacingTarget = 3,
MonsterMoveFacingAngle = 4
};
void PacketBuilder::WriteCommonMonsterMovePart(const MoveSpline& move_spline, ByteBuffer& data)
{
MoveSplineFlag splineflags = move_spline.splineflags;
data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40)
data << move_spline.spline.getPoint(move_spline.spline.first());
data << move_spline.GetId();
switch (splineflags & MoveSplineFlag::Mask_Final_Facing)
{
case MoveSplineFlag::Final_Target:
data << uint8(MonsterMoveFacingTarget);
data << move_spline.facing.target;
break;
case MoveSplineFlag::Final_Angle:
data << uint8(MonsterMoveFacingAngle);
data << move_spline.facing.angle;
break;
case MoveSplineFlag::Final_Point:
data << uint8(MonsterMoveFacingSpot);
data << move_spline.facing.f.x << move_spline.facing.f.y << move_spline.facing.f.z;
break;
default:
data << uint8(MonsterMoveNormal);
break;
}
// add fake Enter_Cycle flag - needed for client-side cyclic movement (client will erase first spline vertex after first cycle done)
splineflags.enter_cycle = move_spline.isCyclic();
data << uint32(splineflags & uint32(~MoveSplineFlag::Mask_No_Monster_Move));
if (splineflags.animation)
{
data << splineflags.getAnimationId();
data << move_spline.effect_start_time;
}
data << move_spline.Duration();
if (splineflags.parabolic)
{
data << move_spline.vertical_acceleration;
data << move_spline.effect_start_time;
}
}
void PacketBuilder::WriteStopMovement(Vector3 const& pos, uint32 splineId, ByteBuffer& data)
{
data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40)
data << pos;
data << splineId;
data << uint8(MonsterMoveStop);
}
void WriteLinearPath(const Spline<int32>& spline, ByteBuffer& data)
{
uint32 last_idx = spline.getPointCount() - 3;
const Vector3 * real_path = &spline.getPoint(1);
data << last_idx;
data << real_path[last_idx]; // destination
if (last_idx > 1)
{
Vector3 middle = (real_path[0] + real_path[last_idx]) / 2.f;
Vector3 offset;
// first and last points already appended
for (uint32 i = 1; i < last_idx; ++i)
{
offset = middle - real_path[i];
data.appendPackXYZ(offset.x, offset.y, offset.z);
}
}
}
void WriteCatmullRomPath(const Spline<int32>& spline, ByteBuffer& data)
{
uint32 count = spline.getPointCount() - 3;
data << count;
data.append<Vector3>(&spline.getPoint(2), count);
}
void WriteCatmullRomCyclicPath(const Spline<int32>& spline, ByteBuffer& data)
{
uint32 count = spline.getPointCount() - 3;
data << uint32(count + 1);
data << spline.getPoint(1); // fake point, client will erase it from the spline after first cycle done
data.append<Vector3>(&spline.getPoint(1), count);
}
void PacketBuilder::WriteMonsterMove(const MoveSpline& move_spline, ByteBuffer& data)
{
WriteCommonMonsterMovePart(move_spline, data);
const Spline<int32>& spline = move_spline.spline;
MoveSplineFlag splineflags = move_spline.splineflags;
if (splineflags & MoveSplineFlag::Mask_CatmullRom)
{
if (splineflags.cyclic)
WriteCatmullRomCyclicPath(spline, data);
else
WriteCatmullRomPath(spline, data);
}
else
WriteLinearPath(spline, data);
}
void PacketBuilder::WriteCreate(const MoveSpline& move_spline, ByteBuffer& data)
{
//WriteClientStatus(mov, data);
//data.append<float>(&mov.m_float_values[SpeedWalk], SpeedMaxCount);
//if (mov.SplineEnabled())
{
MoveSplineFlag const& splineFlags = move_spline.splineflags;
data << splineFlags.raw();
if (splineFlags.final_angle)
{
data << move_spline.facing.angle;
}
else if (splineFlags.final_target)
{
data << move_spline.facing.target;
}
else if (splineFlags.final_point)
{
data << move_spline.facing.f.x << move_spline.facing.f.y << move_spline.facing.f.z;
}
data << move_spline.timePassed();
data << move_spline.Duration();
data << move_spline.GetId();
data << float(1.f); // splineInfo.duration_mod; added in 3.1
data << float(1.f); // splineInfo.duration_mod_next; added in 3.1
data << move_spline.vertical_acceleration; // added in 3.1
data << move_spline.effect_start_time; // added in 3.1
uint32 nodes = move_spline.getPath().size();
data << nodes;
data.append<Vector3>(&move_spline.getPath()[0], nodes);
data << uint8(move_spline.spline.mode()); // added in 3.1
data << (move_spline.isCyclic() ? Vector3::zero() : move_spline.FinalDestination());
}
}
}
| ironhead123/DeathCore_3.3.5 | src/server/game/Movement/Spline/MovementPacketBuilder.cpp | C++ | gpl-2.0 | 6,925 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "RBAC.h"
#include "AccountMgr.h"
#include "DatabaseEnv.h"
#include "Log.h"
namespace rbac
{
std::string GetDebugPermissionString(RBACPermissionContainer const& perms)
{
std::string str = "";
if (!perms.empty())
{
std::ostringstream o;
RBACPermissionContainer::const_iterator itr = perms.begin();
o << (*itr);
for (++itr; itr != perms.end(); ++itr)
o << ", " << uint32(*itr);
str = o.str();
}
return str;
}
RBACCommandResult RBACData::GrantPermission(uint32 permissionId, int32 realmId /* = 0*/)
{
// Check if permission Id exists
RBACPermission const* perm = sAccountMgr->GetRBACPermission(permissionId);
if (!perm)
{
TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission does not exists",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_ID_DOES_NOT_EXISTS;
}
// Check if already added in denied list
if (HasDeniedPermission(permissionId))
{
TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission in deny list",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_IN_DENIED_LIST;
}
// Already added?
if (HasGrantedPermission(permissionId))
{
TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission already granted",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_CANT_ADD_ALREADY_ADDED;
}
AddGrantedPermission(permissionId);
// Do not save to db when loading data from DB (realmId = 0)
if (realmId)
{
TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated",
GetId(), GetName().c_str(), permissionId, realmId);
SavePermission(permissionId, true, realmId);
CalculateNewPermissions();
}
else
TC_LOG_TRACE("rbac", "RBACData::GrantPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_OK;
}
RBACCommandResult RBACData::DenyPermission(uint32 permissionId, int32 realmId /* = 0*/)
{
// Check if permission Id exists
RBACPermission const* perm = sAccountMgr->GetRBACPermission(permissionId);
if (!perm)
{
TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission does not exists",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_ID_DOES_NOT_EXISTS;
}
// Check if already added in granted list
if (HasGrantedPermission(permissionId))
{
TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission in grant list",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_IN_GRANTED_LIST;
}
// Already added?
if (HasDeniedPermission(permissionId))
{
TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Permission already denied",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_CANT_ADD_ALREADY_ADDED;
}
AddDeniedPermission(permissionId);
// Do not save to db when loading data from DB (realmId = 0)
if (realmId)
{
TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated",
GetId(), GetName().c_str(), permissionId, realmId);
SavePermission(permissionId, false, realmId);
CalculateNewPermissions();
}
else
TC_LOG_TRACE("rbac", "RBACData::DenyPermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_OK;
}
void RBACData::SavePermission(uint32 permission, bool granted, int32 realmId)
{
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_RBAC_ACCOUNT_PERMISSION);
stmt->setUInt32(0, GetId());
stmt->setUInt32(1, permission);
stmt->setBool(2, granted);
stmt->setInt32(3, realmId);
LoginDatabase.Execute(stmt);
}
RBACCommandResult RBACData::RevokePermission(uint32 permissionId, int32 realmId /* = 0*/)
{
// Check if it's present in any list
if (!HasGrantedPermission(permissionId) && !HasDeniedPermission(permissionId))
{
TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Not granted or revoked",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_CANT_REVOKE_NOT_IN_LIST;
}
RemoveGrantedPermission(permissionId);
RemoveDeniedPermission(permissionId);
// Do not save to db when loading data from DB (realmId = 0)
if (realmId)
{
TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok and DB updated",
GetId(), GetName().c_str(), permissionId, realmId);
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_RBAC_ACCOUNT_PERMISSION);
stmt->setUInt32(0, GetId());
stmt->setUInt32(1, permissionId);
stmt->setInt32(2, realmId);
LoginDatabase.Execute(stmt);
CalculateNewPermissions();
}
else
TC_LOG_TRACE("rbac", "RBACData::RevokePermission [Id: %u Name: %s] (Permission %u, RealmId %d). Ok",
GetId(), GetName().c_str(), permissionId, realmId);
return RBAC_OK;
}
void RBACData::LoadFromDB()
{
ClearData();
TC_LOG_DEBUG("rbac", "RBACData::LoadFromDB [Id: %u Name: %s]: Loading permissions", GetId(), GetName().c_str());
// Load account permissions (granted and denied) that affect current realm
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_RBAC_ACCOUNT_PERMISSIONS);
stmt->setUInt32(0, GetId());
stmt->setInt32(1, GetRealmId());
PreparedQueryResult result = LoginDatabase.Query(stmt);
if (result)
{
do
{
Field* fields = result->Fetch();
if (fields[1].GetBool())
GrantPermission(fields[0].GetUInt32());
else
DenyPermission(fields[0].GetUInt32());
}
while (result->NextRow());
}
// Add default permissions
RBACPermissionContainer const& permissions = sAccountMgr->GetRBACDefaultPermissions(_secLevel);
for (RBACPermissionContainer::const_iterator itr = permissions.begin(); itr != permissions.end(); ++itr)
GrantPermission(*itr);
// Force calculation of permissions
CalculateNewPermissions();
}
void RBACData::CalculateNewPermissions()
{
TC_LOG_TRACE("rbac", "RBACData::CalculateNewPermissions [Id: %u Name: %s]", GetId(), GetName().c_str());
// Get the list of granted permissions
_globalPerms = GetGrantedPermissions();
ExpandPermissions(_globalPerms);
RBACPermissionContainer revoked = GetDeniedPermissions();
ExpandPermissions(revoked);
RemovePermissions(_globalPerms, revoked);
}
void RBACData::AddPermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo)
{
for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr)
permsTo.insert(*itr);
}
void RBACData::RemovePermissions(RBACPermissionContainer const& permsFrom, RBACPermissionContainer& permsTo)
{
for (RBACPermissionContainer::const_iterator itr = permsFrom.begin(); itr != permsFrom.end(); ++itr)
permsTo.erase(*itr);
}
void RBACData::ExpandPermissions(RBACPermissionContainer& permissions)
{
RBACPermissionContainer toCheck = permissions;
permissions.clear();
while (!toCheck.empty())
{
// remove the permission from original list
uint32 permissionId = *toCheck.begin();
toCheck.erase(toCheck.begin());
RBACPermission const* permission = sAccountMgr->GetRBACPermission(permissionId);
if (!permission)
continue;
// insert into the final list (expanded list)
permissions.insert(permissionId);
// add all linked permissions (that are not already expanded) to the list of permissions to be checked
RBACPermissionContainer const& linkedPerms = permission->GetLinkedPermissions();
for (RBACPermissionContainer::const_iterator itr = linkedPerms.begin(); itr != linkedPerms.end(); ++itr)
if (permissions.find(*itr) == permissions.end())
toCheck.insert(*itr);
}
TC_LOG_DEBUG("rbac", "RBACData::ExpandPermissions: Expanded: %s", GetDebugPermissionString(permissions).c_str());
}
void RBACData::ClearData()
{
_grantedPerms.clear();
_deniedPerms.clear();
_globalPerms.clear();
}
}
| fuhongxue/TrinityCore | src/server/game/Accounts/RBAC.cpp | C++ | gpl-2.0 | 10,027 |
<?php
/**
* @file
* Contains \Drupal\commerce\AvailabilityCheckerInterface.
*/
namespace Drupal\commerce;
/**
* Defines the interface for availability checkers.
*/
interface AvailabilityCheckerInterface {
/**
* Determines whether the checker applies to the given purchasable entity.
*
* @param \Drupal\commerce\PurchasableEntityInterface $entity
* The purchasable entity.
*
* @return bool
* TRUE if the checker applies to the given purchasable entity, FALSE
* otherwise.
*/
public function applies(PurchasableEntityInterface $entity);
/**
* Checks the availability of the given purchasable entity.
*
* @param \Drupal\commerce\PurchasableEntityInterface $entity
* The purchasable entity.
* @param int $quantity
* The quantity.
*
* @return bool|null
* TRUE if the entity is available, FALSE if it's unavailable,
* or NULL if it has no opinion.
*/
public function check(PurchasableEntityInterface $entity, $quantity = 1);
}
| tom-fallon/free-commerce | modules/contrib/commerce/src/AvailabilityCheckerInterface.php | PHP | gpl-2.0 | 1,014 |
<?php
/*
** Zabbix
** Copyright (C) 2001-2014 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
/**
* Class that holds processed (created and updated) host and template IDs during the current import.
*/
class CImportedObjectContainer {
/**
* @var array with created and updated hosts.
*/
protected $hostIds = array();
/**
* @var array with created and updated templates.
*/
protected $templateIds = array();
/**
* Add host IDs that have been created and updated.
*
* @param array $hostIds
*/
public function addHostIds(array $hostIds) {
foreach ($hostIds as $hostId) {
$this->hostIds[$hostId] = $hostId;
}
}
/**
* Add template IDs that have been created and updated.
*
* @param array $templateIds
*/
public function addTemplateIds(array $templateIds) {
foreach ($templateIds as $templateId) {
$this->templateIds[$templateId] = $templateId;
}
}
/**
* Checks if host has been created and updated during the current import.
*
* @param string $hostId
*
* @return bool
*/
public function isHostProcessed($hostId) {
return isset($this->hostIds[$hostId]);
}
/**
* Checks if template has been created and updated during the current import.
*
* @param string $templateId
*
* @return bool
*/
public function isTemplateProcessed($templateId) {
return isset($this->templateIds[$templateId]);
}
/**
* Get array of created and updated hosts IDs.
*
* @return array
*/
public function getHostIds() {
return array_values($this->hostIds);
}
/**
* Get array of created and updated template IDs.
*
* @return array
*/
public function getTemplateIds() {
return array_values($this->templateIds);
}
}
| qinglan2014/Zabbix | frontends/php/include/classes/import/CImportedObjectContainer.php | PHP | gpl-2.0 | 2,382 |
using System;
using System.Collections.Generic;
using System.Text;
namespace BarcodeLib.Symbologies
{
class ISBN : BarcodeCommon, IBarcode
{
public ISBN(string input)
{
Raw_Data = input;
}
/// <summary>
/// Encode the raw data using the Bookland/ISBN algorithm.
/// </summary>
private string Encode_ISBN_Bookland()
{
if (!BarcodeLib.Barcode.CheckNumericOnly(Raw_Data))
Error("EBOOKLANDISBN-1: Numeric Data Only");
string type = "UNKNOWN";
if (Raw_Data.Length == 10 || Raw_Data.Length == 9)
{
if (Raw_Data.Length == 10) Raw_Data = Raw_Data.Remove(9, 1);
Raw_Data = "978" + Raw_Data;
type = "ISBN";
}//if
else if (Raw_Data.Length == 12 && Raw_Data.StartsWith("978"))
{
type = "BOOKLAND-NOCHECKDIGIT";
}//else if
else if (Raw_Data.Length == 13 && Raw_Data.StartsWith("978"))
{
type = "BOOKLAND-CHECKDIGIT";
Raw_Data = Raw_Data.Remove(12, 1);
}//else if
//check to see if its an unknown type
if (type == "UNKNOWN") Error("EBOOKLANDISBN-2: Invalid input. Must start with 978 and be length must be 9, 10, 12, 13 characters.");
EAN13 ean13 = new EAN13(Raw_Data);
return ean13.Encoded_Value;
}//Encode_ISBN_Bookland
#region IBarcode Members
public string Encoded_Value
{
get { return Encode_ISBN_Bookland(); }
}
#endregion
}
}
| marhazk/HazTechClass | QRbit4/Sources/BarCodes/Symbologies/ISBN.cs | C# | gpl-2.0 | 1,721 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'basicstyles', 'en-gb', {
bold: 'Bold',
italic: 'Italic',
strike: 'Strike Through',
subscript: 'Subscript',
superscript: 'Superscript',
underline: 'Underline'
} );
| SeeyaSia/www | web/libraries/ckeditor/plugins/basicstyles/lang/en-gb.js | JavaScript | gpl-2.0 | 339 |
/*
* #%L
* Fork of MDB Tools (Java port).
* %%
* Copyright (C) 2008 - 2013 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/*
* Created on Jan 14, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package mdbtools.libmdb06util;
/**
* @author calvin
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class mdbver
{
public static void main(String[] args)
{
}
}
| ctrueden/bioformats | components/forks/mdbtools/src/mdbtools/libmdb06util/mdbver.java | Java | gpl-2.0 | 1,360 |
/*
* Copyright 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
class Optimizer VALUE_OBJ_CLASS_SPEC {
private:
IR* _ir;
public:
Optimizer(IR* ir);
IR* ir() const { return _ir; }
// optimizations
void eliminate_conditional_expressions();
void eliminate_blocks();
void eliminate_null_checks();
};
| guanxiaohua/TransGC | src/share/vm/c1/c1_Optimizer.hpp | C++ | gpl-2.0 | 1,342 |
namespace Server.Items
{
public class DestroyingAngel : BaseReagent, ICommodity
{
int ICommodity.DescriptionNumber { get { return LabelNumber; } }
bool ICommodity.IsDeedable { get { return true; } }
[Constructable]
public DestroyingAngel() : this( 1 )
{
}
[Constructable]
public DestroyingAngel( int amount ) : base( 0xE1F )
{
Stackable = true;
Weight = 0.0;
Amount = amount;
Name = "Destroying Angel";
Hue = 0x290;
}
public DestroyingAngel( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
public class PetrafiedWood : BaseReagent, ICommodity
{
int ICommodity.DescriptionNumber { get { return LabelNumber; } }
bool ICommodity.IsDeedable { get { return true; } }
[Constructable]
public PetrafiedWood() : this( 1 )
{
}
[Constructable]
public PetrafiedWood( int amount ) : base( 0x97A )
{
Stackable = true;
Weight = 0.0;
Amount = amount;
Name = "Petrafied Wood";
Hue = 0x46C;
}
public PetrafiedWood( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
public class SpringWater : BaseReagent, ICommodity
{
int ICommodity.DescriptionNumber { get { return LabelNumber; } }
bool ICommodity.IsDeedable { get { return true; } }
[Constructable]
public SpringWater() : this( 1 )
{
}
[Constructable]
public SpringWater( int amount ) : base( 0xE24 )
{
Stackable = true;
Weight = 0.0;
Amount = amount;
Name = "Spring Water";
Hue = 0x47F;
}
public SpringWater( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | cmileto/neverybody | Scripts/Custom/New Systems/OWLTR/New/Druid Reagents.cs | C# | gpl-2.0 | 2,326 |
/**
* Drupal-specific JS helper functions and utils. Not to be confused with the
* Recline library, which should live in your libraries directory.
*/
;(function ($) {
// Constants.
var MAX_LABEL_WIDTH = 77;
var LABEL_MARGIN = 5;
// Undefined variables.
var dataset, views, datasetOptions, fileSize, fileType, router;
var dataExplorerSettings, state, $explorer, dataExplorer, maxSizePreview;
var datastoreStatus;
// Create drupal behavior
Drupal.behaviors.Recline = {
attach: function (context) {
$explorer = $('.data-explorer');
// Local scoped variables.
Drupal.settings.recline = Drupal.settings.recline || {};
fileSize = Drupal.settings.recline.fileSize;
fileType = Drupal.settings.recline.fileType;
maxSizePreview = Drupal.settings.recline.maxSizePreview;
datastoreStatus = Drupal.settings.recline.datastoreStatus;
dataExplorerSettings = {
grid: Drupal.settings.recline.grid,
graph: Drupal.settings.recline.graph,
map: Drupal.settings.recline.map
};
// This is the very basic state collection.
state = recline.View.parseQueryString(decodeURIComponent(window.location.hash));
if ('#map' in state) {
state.currentView = 'map';
} else if ('#graph' in state) {
state.currentView = 'graph';
}
// Init the explorer.
init();
// Attach toogle event.
$('.recline-embed a.embed-link').on('click', function(){
$(this).parents('.recline-embed').find('.embed-code-wrapper').toggle();
return false;
});
}
}
// make Explorer creation / initialization in a function so we can call it
// again and again
function createExplorer (dataset, state, settings) {
// Remove existing data explorer view.
dataExplorer && dataExplorer.remove();
var $el = $('<div />');
$el.appendTo($explorer);
var views = [];
if (settings.grid) {
views.push({
id: 'grid',
label: 'Grid',
view: new recline.View.SlickGrid({
model: dataset
})
});
}
if (settings.graph) {
state.graphOptions = {
xaxis: {
tickFormatter: tickFormatter(dataset),
},
hooks:{
processOffset: [processOffset(dataset)],
bindEvents: [bindEvents],
}
};
views.push({
id: 'graph',
label: 'Graph',
view: new recline.View.Graph({
model: dataset,
state: state
})
});
}
if (settings.map) {
views.push({
id: 'map',
label: 'Map',
view: new recline.View.Map({
model: dataset,
options: {
mapTilesURL: '//stamen-tiles-{s}.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png',
}
})
});
}
// Multiview settings
var multiviewOptions = {
model: dataset,
el: $el,
state: state,
views: views
};
// Getting base embed url.
var urlBaseEmbed = $('.embed-code').text();
var iframeOptions = {src: urlBaseEmbed, width:850, height:400};
// Attaching router to dataexplorer state.
dataExplorer = new recline.View.MultiView(multiviewOptions);
router = new recline.DeepLink.Router(dataExplorer);
// Adding router listeners.
var changeEmbedCode = getEmbedCode(iframeOptions);
router.on('init', changeEmbedCode);
router.on('stateChange', changeEmbedCode);
// Add map dependency just for map views.
_.each(dataExplorer.pageViews, function(item, index){
if(item.id && item.id === 'map'){
var map = dataExplorer.pageViews[index].view.map;
router.addDependency(new recline.DeepLink.Deps.Map(map, router));
}
});
// Start to track state chages.
router.start();
$.event.trigger('createDataExplorer');
return views;
}
// Returns the dataset configuration.
function getDatasetOptions () {
var datasetOptions = {};
var delimiter = Drupal.settings.recline.delimiter;
var file = Drupal.settings.recline.file;
var uuid = Drupal.settings.recline.uuid;
// Get correct file location, make sure not local
file = (getOrigin(window.location) !== getOrigin(file)) ? '/node/' + Drupal.settings.recline.uuid + '/data' : file;
// Select the backend to use
switch(getBackend(datastoreStatus, fileType)) {
case 'csv':
datasetOptions = {
backend: 'csv',
url: file,
delimiter: delimiter
};
break;
case 'tsv':
datasetOptions = {
backend: 'csv',
url: file,
delimiter: delimiter
};
break;
case 'txt':
datasetOptions = {
backend: 'csv',
url: file,
delimiter: delimiter
};
break;
case 'ckan':
datasetOptions = {
endpoint: 'api',
id: uuid,
backend: 'ckan'
};
break;
case 'xls':
datasetOptions = {
backend: 'xls',
url: file
};
break;
case 'dataproxy':
datasetOptions = {
url: file,
backend: 'dataproxy'
};
break;
default:
showError('File type ' + fileType + ' not supported for preview.');
break;
}
return datasetOptions;
}
// Correct for fact that IE does not provide .origin
function getOrigin(u) {
var url = parseURL(u);
return url.protocol + '//' + url.hostname + (url.port ? (':' + url.port) : '');
}
// Parse a simple URL string to get its properties
function parseURL(url) {
var parser = document.createElement('a');
parser.href = url;
return {
protocol: parser.protocol,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
hash: parser.hash,
host: parser.host
}
}
// Retrieve a backend given a file type and and a datastore status.
function getBackend (datastoreStatus, fileType) {
// If it's inside the datastore then we use the dkan API
if (datastoreStatus) return 'ckan';
var formats = {
'csv': ['text/csv', 'csv'],
'xls': ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
'tsv': ['text/tab-separated-values', 'text/tsv', 'tsv', 'tab'],
'txt': ['text/plain', 'txt'],
};
var backend = _.findKey(formats, function(format) { return _.include(format, fileType) });
// If the backend is a txt but the delimiter is not a tab, we don't need
// to show it using the backend.
if (Drupal.settings.recline.delimiter !== "\t" && backend === 'txt') {return '';}
// If the backend is an xls but the browser version is prior 9 then
// we need to fallback to dataproxy
if (backend === 'xls' && document.documentMode < 9) return 'dataproxy';
return backend;
}
// Displays an error retrieved from the response object.
function showRequestError (response) {
// Actually dkan doesn't provide standarization over
// error handling responses. For example: if you request
// unexistent resources it will retrive an array with a
// message inside.
// Recline backends will return an object with an error.
try {
var ro = (typeof response === 'string') ? JSON.parse(response) : response;
if(ro.error) {
showError(ro.error.message)
} else if(ro instanceof Array) {
showError(ro[0]);
}
} catch (error) {
showError(response);
}
}
// Displays an error.
function showError (message) {
$explorer.html('<div class="messages error">' + message + '</div>');
}
// Creates the embed code.
function getEmbedCode (options){
return function(state){
var iframeOptions = _.clone(options);
var iframeTmpl = _.template('<iframe width="<%= width %>" height="<%= height %>" src="<%= src %>" frameborder="0"></iframe>');
var previewTmpl = _.template('<%= src %>');
_.extend(iframeOptions, {src: iframeOptions.src + '#' + (state.serializedState || '')});
var html = iframeTmpl(iframeOptions);
$('.embed-code').text(html);
var preview = previewTmpl(iframeOptions);
$('.preview-code').text(preview);
};
}
// Creates the preview url code.
function getPreviewCode (options){
return function(state){
var previewOptions = _.clone(options);
var previewTmpl = _.template('<%= src %>');
_.extend(previewOptions, {src: previewOptions.src + '#' + (state.serializedState || '')});
var html = previewTmpl(previewOptions);
$('.preview-url').text(html);
};
}
// Check if a chart has their axis inverted.
function isInverted (){
return dataExplorer.pageViews[1].view.state.attributes.graphType === 'bars';
}
// Computes the width of a chart.
function computeWidth (plot, labels) {
var biggerLabel = '';
for( var i = 0; i < labels.length; i++){
if(labels[i].length > biggerLabel.length && !_.isUndefined(labels[i])){
biggerLabel = labels[i];
}
}
var canvas = plot.getCanvas();
var ctx = canvas.getContext('2d');
ctx.font = 'sans-serif smaller';
return ctx.measureText(biggerLabel).width;
}
// Resize a chart.
function resize (plot) {
var itemWidth = computeWidth(plot, _.pluck(plot.getXAxes()[0].ticks, 'label'));
var graph = dataExplorer.pageViews[1];
if(!isInverted() && $('#prevent-label-overlapping').is(':checked')){
var canvasWidth = Math.min(itemWidth + LABEL_MARGIN, MAX_LABEL_WIDTH) * plot.getXAxes()[0].ticks.length;
var canvasContainerWith = $('.panel.graph').parent().width();
if(canvasWidth < canvasContainerWith){
canvasWidth = canvasContainerWith;
}
$('.panel.graph').width(canvasWidth);
$('.recline-flot').css({overflow:'auto'});
}else{
$('.recline-flot').css({overflow:'hidden'});
$('.panel.graph').css({width: '100%'});
}
plot.resize();
plot.setupGrid();
plot.draw();
}
// Bind events after chart resizes.
function bindEvents (plot, eventHolder) {
var p = plot || dataExplorer.pageViews[1].view.plot;
resize(p);
setTimeout(addCheckbox, 0);
}
// Compute the chart offset to display ticks properly.
function processOffset (dataset) {
return function(plot, offset) {
if(dataExplorer.pageViews[1].view.xvaluesAreIndex){
var series = plot.getData();
for (var i = 0; i < series.length; i++) {
var numTicks = Math.min(dataset.records.length, 200);
var ticks = [];
for (var j = 0; j < dataset.records.length; j++) {
ticks.push(parseInt(j, 10));
}
if(isInverted()){
series[i].yaxis.options.ticks = ticks;
}else{
series[i].xaxis.options.ticks = ticks;
}
}
}
};
}
// Format ticks base on previews computations.
function tickFormatter (dataset){
return function (x) {
x = parseInt(x, 10);
try {
if(isInverted()) return x;
var field = dataExplorer.pageViews[1].view.state.get('group');
var label = dataset.records.models[x].get(field) || '';
if(!moment(String(label)).isValid() && !isNaN(parseInt(label, 10))){
label = parseInt(label, 10) - 1;
}
return label;
} catch(e) {
return x;
}
};
}
// Add checkbox to control resize behavior.
function addCheckbox () {
$control = $('.form-stacked:visible').find('#prevent-label-overlapping');
if(!$control.length){
$form = $('.form-stacked');
$checkboxDiv = $('<div class="checkbox"></div>').appendTo($form);
$label = $('<label />', { 'for': 'prevent-label-overlapping', text: 'Resize graph to prevent label overlapping' }).appendTo($checkboxDiv);
$label.prepend($('<input />', { type: 'checkbox', id: 'prevent-label-overlapping', value: '' }));
$control = $('#prevent-label-overlapping');
$control.on('change', function(){
resize(dataExplorer.pageViews[1].view.plot);
});
}
}
// Init the multiview.
function init () {
if(fileSize < maxSizePreview || datastoreStatus) {
dataset = new recline.Model.Dataset(getDatasetOptions());
dataset.fetch().fail(showRequestError);
views = createExplorer(dataset, state, dataExplorerSettings);
views.forEach(function(view) { view.id === 'map' && view.view.redraw('refresh') });
} else {
showError('File was too large or unavailable for preview.');
}
}
})(jQuery);
| NuCivic/recline | recline.js | JavaScript | gpl-2.0 | 13,387 |
<?php
/**
* File containing the eZContentOperationCollection class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version //autogentag//
* @package kernel
*/
/*!
\class eZContentOperationCollection ezcontentoperationcollection.php
\brief The class eZContentOperationCollection does
*/
class eZContentOperationCollection
{
/**
* Use by {@see beginTransaction()} and {@see commitTransaction()} to handle nested publish operations
*/
private static $operationsStack = 0;
static public function readNode( $nodeID )
{
}
static public function readObject( $nodeID, $userID, $languageCode )
{
if ( $languageCode != '' )
{
$node = eZContentObjectTreeNode::fetch( $nodeID, $languageCode );
}
else
{
$node = eZContentObjectTreeNode::fetch( $nodeID );
}
if ( $node === null )
// return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' );
return false;
$object = $node->attribute( 'object' );
if ( $object === null )
// return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' );
{
return false;
}
/*
if ( !$object->attribute( 'can_read' ) )
{
// return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' );
return false;
}
*/
return array( 'status' => true, 'object' => $object, 'node' => $node );
}
static public function loopNodes( $nodeID )
{
return array( 'parameters' => array( array( 'parent_node_id' => 3 ),
array( 'parent_node_id' => 5 ),
array( 'parent_node_id' => 12 ) ) );
}
static public function loopNodeAssignment( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$version = $object->version( $versionNum );
$nodeAssignmentList = $version->attribute( 'node_assignments' );
$parameters = array();
foreach ( $nodeAssignmentList as $nodeAssignment )
{
if ( $nodeAssignment->attribute( 'parent_node' ) > 0 )
{
if ( $nodeAssignment->attribute( 'is_main' ) == 1 )
{
$mainNodeID = self::publishNode( $nodeAssignment->attribute( 'parent_node' ), $objectID, $versionNum, false );
}
else
{
$parameters[] = array( 'parent_node_id' => $nodeAssignment->attribute( 'parent_node' ) );
}
}
}
for ( $i = 0; $i < count( $parameters ); $i++ )
{
$parameters[$i]['main_node_id'] = $mainNodeID;
}
return array( 'parameters' => $parameters );
}
function publishObjectExtensionHandler( $contentObjectID, $contentObjectVersion )
{
eZContentObjectEditHandler::executePublish( $contentObjectID, $contentObjectVersion );
}
/**
* Starts a database transaction.
*/
static public function beginTransaction()
{
// We only start a transaction if another content publish operation hasn't been started
if ( ++self::$operationsStack === 1 )
{
eZDB::instance()->begin();
}
}
/**
* Commit a previously started database transaction.
*/
static public function commitTransaction()
{
if ( --self::$operationsStack === 0 )
{
eZDB::instance()->commit();
}
}
static public function setVersionStatus( $objectID, $versionNum, $status )
{
$object = eZContentObject::fetch( $objectID );
if ( !$versionNum )
{
$versionNum = $object->attribute( 'current_version' );
}
$version = $object->version( $versionNum );
if ( !$version )
return;
$version->setAttribute( 'status', $status );
$version->store();
}
static public function setObjectStatusPublished( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$version = $object->version( $versionNum );
$db = eZDB::instance();
$db->begin();
$object->setAttribute( 'status', eZContentObject::STATUS_PUBLISHED );
$version->setAttribute( 'status', eZContentObjectVersion::STATUS_PUBLISHED );
$object->setAttribute( 'current_version', $versionNum );
$objectIsAlwaysAvailable = $object->isAlwaysAvailable();
$object->setAttribute( 'language_mask', eZContentLanguage::maskByLocale( $version->translationList( false, false ), $objectIsAlwaysAvailable ) );
if ( $object->attribute( 'published' ) == 0 )
{
$object->setAttribute( 'published', time() );
}
$object->setAttribute( 'modified', time() );
$classID = $object->attribute( 'contentclass_id' );
$class = eZContentClass::fetch( $classID );
$objectName = $class->contentObjectName( $object );
$object->setName( $objectName, $versionNum );
$existingTranslations = $version->translations( false );
foreach( $existingTranslations as $translation )
{
$translatedName = $class->contentObjectName( $object, $versionNum, $translation );
$object->setName( $translatedName, $versionNum, $translation );
}
if ( $objectIsAlwaysAvailable )
{
$initialLanguageID = $object->attribute( 'initial_language_id' );
$object->setAlwaysAvailableLanguageID( $initialLanguageID );
}
$version->store();
$object->store();
eZContentObjectTreeNode::setVersionByObjectID( $objectID, $versionNum );
$nodes = $object->assignedNodes();
foreach ( $nodes as $node )
{
$node->setName( $object->attribute( 'name' ) );
$node->updateSubTreePath();
}
$db->commit();
/* Check if current class is the user class, and if so, clean up the user-policy cache */
if ( in_array( $classID, eZUser::contentClassIDs() ) )
{
eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) );
}
}
static public function attributePublishAction( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$nodes = $object->assignedNodes();
$version = $object->version( $versionNum );
$contentObjectAttributes = $object->contentObjectAttributes( true, $versionNum, $version->initialLanguageCode(), false );
foreach ( $contentObjectAttributes as $contentObjectAttribute )
{
$contentObjectAttribute->onPublish( $object, $nodes );
}
}
/*!
\static
Generates the related viewcaches (PreGeneration) for the content object.
It will only do this if [ContentSettings]/PreViewCache in site.ini is enabled.
\param $objectID The ID of the content object to generate caches for.
*/
static public function generateObjectViewCache( $objectID )
{
eZContentCacheManager::generateObjectViewCache( $objectID );
}
/*!
\static
Clears the related viewcaches for the content object using the smart viewcache system.
\param $objectID The ID of the content object to clear caches for
\param $versionNum The version of the object to use or \c true for current version
\param $additionalNodeList An array with node IDs to add to clear list,
or \c false for no additional nodes.
*/
static public function clearObjectViewCache( $objectID, $versionNum = true, $additionalNodeList = false )
{
eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeList );
}
static public function publishNode( $parentNodeID, $objectID, $versionNum, $mainNodeID )
{
$object = eZContentObject::fetch( $objectID );
$nodeAssignment = eZNodeAssignment::fetch( $objectID, $versionNum, $parentNodeID );
$version = $object->version( $versionNum );
$fromNodeID = $nodeAssignment->attribute( 'from_node_id' );
$originalObjectID = $nodeAssignment->attribute( 'contentobject_id' );
$nodeID = $nodeAssignment->attribute( 'parent_node' );
$opCode = $nodeAssignment->attribute( 'op_code' );
$parentNode = eZContentObjectTreeNode::fetch( $nodeID );
// if parent doesn't exist, return. See issue #18320
if ( !$parentNode instanceof eZContentObjectTreeNode )
{
eZDebug::writeError( "Parent node doesn't exist. object id: $objectID, node_assignment id: " . $nodeAssignment->attribute( 'id' ), __METHOD__ );
return;
}
$parentNodeID = $parentNode->attribute( 'node_id' );
$existingNode = null;
$db = eZDB::instance();
$db->begin();
if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 )
{
$existingNode = eZContentObjectTreeNode::fetchByRemoteID( $nodeAssignment->attribute( 'parent_remote_id' ) );
}
if ( !$existingNode );
{
$existingNode = eZContentObjectTreeNode::findNode( $nodeID , $object->attribute( 'id' ), true );
}
$updateSectionID = false;
// now we check the op_code to see what to do
if ( ( $opCode & 1 ) == eZNodeAssignment::OP_CODE_NOP )
{
// There is nothing to do so just return
$db->commit();
if ( $mainNodeID == false )
{
return $object->attribute( 'main_node_id' );
}
return;
}
$updateFields = false;
if ( $opCode == eZNodeAssignment::OP_CODE_MOVE ||
$opCode == eZNodeAssignment::OP_CODE_CREATE )
{
// if ( $fromNodeID == 0 || $fromNodeID == -1)
if ( $opCode == eZNodeAssignment::OP_CODE_CREATE ||
$opCode == eZNodeAssignment::OP_CODE_SET )
{
// If the node already exists it means we have a conflict (for 'CREATE').
// We resolve this by leaving node-assignment data be.
if ( $existingNode == null )
{
$parentNode = eZContentObjectTreeNode::fetch( $nodeID );
$user = eZUser::currentUser();
if ( !eZSys::isShellExecution() and !$user->isAnonymous() )
{
eZContentBrowseRecent::createNew( $user->id(), $parentNode->attribute( 'node_id' ), $parentNode->attribute( 'name' ) );
}
$updateFields = true;
$existingNode = $parentNode->addChild( $object->attribute( 'id' ), true );
if ( $fromNodeID == -1 )
{
$updateSectionID = true;
}
}
elseif ( $opCode == eZNodeAssignment::OP_CODE_SET )
{
$updateFields = true;
}
}
elseif ( $opCode == eZNodeAssignment::OP_CODE_MOVE )
{
if ( $fromNodeID == 0 || $fromNodeID == -1 )
{
eZDebug::writeError( "NodeAssignment '" . $nodeAssignment->attribute( 'id' ) . "' is marked with op_code='$opCode' but has no data in from_node_id. Cannot use it for moving node.", __METHOD__ );
}
else
{
// clear cache for old placement.
$additionalNodeIDList = array( $fromNodeID );
eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeIDList );
$originalNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $fromNodeID );
if ( $originalNode->attribute( 'main_node_id' ) == $originalNode->attribute( 'node_id' ) )
{
$updateSectionID = true;
}
$originalNode->move( $parentNodeID );
$existingNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $parentNodeID );
$updateFields = true;
}
}
}
elseif ( $opCode == eZNodeAssignment::OP_CODE_REMOVE )
{
$db->commit();
return;
}
if ( $updateFields )
{
if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 )
{
$existingNode->setAttribute( 'remote_id', $nodeAssignment->attribute( 'parent_remote_id' ) );
}
if ( $nodeAssignment->attribute( 'is_hidden' ) )
{
$existingNode->setAttribute( 'is_hidden', 1 );
$existingNode->setAttribute( 'is_invisible', 1 );
}
$existingNode->setAttribute( 'priority', $nodeAssignment->attribute( 'priority' ) );
$existingNode->setAttribute( 'sort_field', $nodeAssignment->attribute( 'sort_field' ) );
$existingNode->setAttribute( 'sort_order', $nodeAssignment->attribute( 'sort_order' ) );
}
$existingNode->setAttribute( 'contentobject_is_published', 1 );
eZDebug::createAccumulatorGroup( 'nice_urls_total', 'Nice urls' );
if ( $mainNodeID > 0 )
{
$existingNodeID = $existingNode->attribute( 'node_id' );
if ( $existingNodeID != $mainNodeID )
{
eZContentBrowseRecent::updateNodeID( $existingNodeID, $mainNodeID );
}
$existingNode->setAttribute( 'main_node_id', $mainNodeID );
}
else
{
$existingNode->setAttribute( 'main_node_id', $existingNode->attribute( 'node_id' ) );
}
$existingNode->store();
if ( $updateSectionID )
{
eZContentOperationCollection::updateSectionID( $objectID, $versionNum );
}
$db->commit();
if ( $mainNodeID == false )
{
return $existingNode->attribute( 'node_id' );
}
}
static public function updateSectionID( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$version = $object->version( $versionNum );
if ( $versionNum == 1 or
$object->attribute( 'current_version' ) == $versionNum )
{
$newMainAssignment = null;
$newMainAssignments = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 );
if ( isset( $newMainAssignments[0] ) )
{
$newMainAssignment = $newMainAssignments[0];
}
// we should not update section id for toplevel nodes
if ( $newMainAssignment && $newMainAssignment->attribute( 'parent_node' ) != 1 )
{
// We should check if current object already has been updated for section_id
// If yes we should not update object section_id by $parentNodeSectionID
$sectionID = $object->attribute( 'section_id' );
if ( $sectionID > 0 )
return;
$newParentObject = $newMainAssignment->getParentObject();
if ( !$newParentObject )
{
return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED );
}
$parentNodeSectionID = $newParentObject->attribute( 'section_id' );
$object->setAttribute( 'section_id', $parentNodeSectionID );
$object->store();
}
return;
}
$newMainAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 );
$newMainAssignment = ( count( $newMainAssignmentList ) ) ? array_pop( $newMainAssignmentList ) : null;
$currentVersion = $object->attribute( 'current' );
// Here we need to fetch published nodes and not old node assignments.
$oldMainNode = $object->mainNode();
if ( $newMainAssignment && $oldMainNode
&& $newMainAssignment->attribute( 'parent_node' ) != $oldMainNode->attribute( 'parent_node_id' ) )
{
$oldMainParentNode = $oldMainNode->attribute( 'parent' );
if ( $oldMainParentNode )
{
$oldParentObject = $oldMainParentNode->attribute( 'object' );
$oldParentObjectSectionID = $oldParentObject->attribute( 'section_id' );
if ( $oldParentObjectSectionID == $object->attribute( 'section_id' ) )
{
$newParentNode = $newMainAssignment->attribute( 'parent_node_obj' );
if ( !$newParentNode )
return;
$newParentObject = $newParentNode->attribute( 'object' );
if ( !$newParentObject )
return;
$newSectionID = $newParentObject->attribute( 'section_id' );
if ( $newSectionID != $object->attribute( 'section_id' ) )
{
$oldSectionID = $object->attribute( 'section_id' );
$object->setAttribute( 'section_id', $newSectionID );
$db = eZDB::instance();
$db->begin();
$object->store();
$mainNodeID = $object->attribute( 'main_node_id' );
if ( $mainNodeID > 0 )
{
eZContentObjectTreeNode::assignSectionToSubTree( $mainNodeID,
$newSectionID,
$oldSectionID );
}
$db->commit();
}
}
}
}
}
static public function removeOldNodes( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
if ( !$object instanceof eZContentObject )
{
eZDebug::writeError( 'Unable to find object #' . $objectID, __METHOD__ );
return;
}
$version = $object->version( $versionNum );
if ( !$version instanceof eZContentObjectVersion )
{
eZDebug::writeError( 'Unable to find version #' . $versionNum . ' for object #' . $objectID, __METHOD__ );
return;
}
$moveToTrash = true;
$assignedExistingNodes = $object->attribute( 'assigned_nodes' );
$curentVersionNodeAssignments = $version->attribute( 'node_assignments' );
$removeParentNodeList = array();
$removeAssignmentsList = array();
foreach ( $curentVersionNodeAssignments as $nodeAssignment )
{
$nodeAssignmentOpcode = $nodeAssignment->attribute( 'op_code' );
if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE ||
$nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE_NOP )
{
$removeAssignmentsList[] = $nodeAssignment->attribute( 'id' );
if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE )
{
$removeParentNodeList[] = $nodeAssignment->attribute( 'parent_node' );
}
}
}
$db = eZDB::instance();
$db->begin();
foreach ( $assignedExistingNodes as $node )
{
if ( in_array( $node->attribute( 'parent_node_id' ), $removeParentNodeList ) )
{
eZContentObjectTreeNode::removeSubtrees( array( $node->attribute( 'node_id' ) ), $moveToTrash );
}
}
if ( count( $removeAssignmentsList ) > 0 )
{
eZNodeAssignment::purgeByID( $removeAssignmentsList );
}
$db->commit();
}
// New function which resets the op_code field when the object is published.
static public function resetNodeassignmentOpcodes( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$version = $object->version( $versionNum );
$nodeAssignments = $version->attribute( 'node_assignments' );
foreach ( $nodeAssignments as $nodeAssignment )
{
if ( ( $nodeAssignment->attribute( 'op_code' ) & 1 ) == eZNodeAssignment::OP_CODE_EXECUTE )
{
$nodeAssignment->setAttribute( 'op_code', ( $nodeAssignment->attribute( 'op_code' ) & ~1 ) );
$nodeAssignment->store();
}
}
}
/**
* Registers the object in search engine.
*
* @note Transaction unsafe. If you call several transaction unsafe methods you must enclose
* the calls within a db transaction; thus within db->begin and db->commit.
*
* @param int $objectID Id of the object.
* @param int $version Operation collection passes this default param. Not used in the method
* @param bool $isMoved true if node is being moved
*/
static public function registerSearchObject( $objectID, $version = null, $isMoved = false )
{
$objectID = (int)$objectID;
eZDebug::createAccumulatorGroup( 'search_total', 'Search Total' );
$ini = eZINI::instance( 'site.ini' );
$insertPendingAction = false;
$object = null;
switch ( $ini->variable( 'SearchSettings', 'DelayedIndexing' ) )
{
case 'enabled':
$insertPendingAction = true;
break;
case 'classbased':
$classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' );
$object = eZContentObject::fetch( $objectID );
if ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) )
{
$insertPendingAction = true;
}
}
if ( $insertPendingAction )
{
$action = $isMoved ? 'index_moved_node' : 'index_object';
eZDB::instance()->query( "INSERT INTO ezpending_actions( action, param ) VALUES ( '$action', '$objectID' )" );
return;
}
if ( $object === null )
$object = eZContentObject::fetch( $objectID );
// Register the object in the search engine.
$needCommit = eZSearch::needCommit();
if ( eZSearch::needRemoveWithUpdate() )
{
eZDebug::accumulatorStart( 'remove_object', 'search_total', 'remove object' );
eZSearch::removeObjectById( $objectID );
eZDebug::accumulatorStop( 'remove_object' );
}
eZDebug::accumulatorStart( 'add_object', 'search_total', 'add object' );
if ( !eZSearch::addObject( $object, $needCommit ) )
{
eZDebug::writeError( "Failed adding object ID {$object->attribute( 'id' )} in the search engine", __METHOD__ );
}
eZDebug::accumulatorStop( 'add_object' );
}
/*!
\note Transaction unsafe. If you call several transaction unsafe methods you must enclose
the calls within a db transaction; thus within db->begin and db->commit.
*/
static public function createNotificationEvent( $objectID, $versionNum )
{
$event = eZNotificationEvent::create( 'ezpublish', array( 'object' => $objectID,
'version' => $versionNum ) );
$event->store();
}
/*!
Copies missing translations from published version to the draft.
*/
static public function copyTranslations( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
if ( !$object instanceof eZContentObject )
{
return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED );
}
$publishedVersionNum = $object->attribute( 'current_version' );
if ( !$publishedVersionNum )
{
return;
}
$publishedVersion = $object->version( $publishedVersionNum );
$publishedVersionTranslations = $publishedVersion->translations();
$publishedLanguages = eZContentLanguage::languagesByMask( $object->attribute( 'language_mask' ) );
$publishedLanguageCodes = array_keys( $publishedLanguages );
$version = $object->version( $versionNum );
$versionTranslationList = array_keys( eZContentLanguage::languagesByMask( $version->attribute( 'language_mask' ) ) );
foreach ( $publishedVersionTranslations as $translation )
{
$translationLanguageCode = $translation->attribute( 'language_code' );
if ( in_array( $translationLanguageCode, $versionTranslationList )
|| !in_array( $translationLanguageCode, $publishedLanguageCodes ) )
{
continue;
}
foreach ( $translation->objectAttributes() as $attribute )
{
$clonedAttribute = $attribute->cloneContentObjectAttribute( $versionNum, $publishedVersionNum, $objectID );
$clonedAttribute->sync();
}
}
$version->updateLanguageMask();
}
/*!
Updates non-translatable attributes.
*/
static public function updateNontranslatableAttributes( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$version = $object->version( $versionNum );
$nonTranslatableAttributes = $version->nonTranslatableAttributesToUpdate();
if ( $nonTranslatableAttributes )
{
$attributes = $version->contentObjectAttributes( $version->initialLanguageCode() );
$attributeByClassAttrID = array();
foreach ( $attributes as $attribute )
{
$attributeByClassAttrID[$attribute->attribute( 'contentclassattribute_id' )] = $attribute;
}
foreach ( $nonTranslatableAttributes as $attributeToUpdate )
{
$originalAttribute =& $attributeByClassAttrID[$attributeToUpdate->attribute( 'contentclassattribute_id' )];
if ( $originalAttribute )
{
unset( $tmp );
$tmp = $attributeToUpdate;
$tmp->initialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute );
$tmp->setAttribute( 'id', $attributeToUpdate->attribute( 'id' ) );
$tmp->setAttribute( 'language_code', $attributeToUpdate->attribute( 'language_code' ) );
$tmp->setAttribute( 'language_id', $attributeToUpdate->attribute( 'language_id' ) );
$tmp->setAttribute( 'attribute_original_id', $originalAttribute->attribute( 'id' ) );
$tmp->store();
$tmp->postInitialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute );
}
}
}
}
static public function removeTemporaryDrafts( $objectID, $versionNum )
{
$object = eZContentObject::fetch( $objectID );
$object->cleanupInternalDrafts( eZUser::currentUserID() );
}
/**
* Moves a node
*
* @param int $nodeID
* @param int $objectID
* @param int $newParentNodeID
*
* @return array An array with operation status, always true
*/
static public function moveNode( $nodeID, $objectID, $newParentNodeID )
{
if( !eZContentObjectTreeNodeOperations::move( $nodeID, $newParentNodeID ) )
{
eZDebug::writeError( "Failed to move node $nodeID as child of parent node $newParentNodeID",
__METHOD__ );
return array( 'status' => false );
}
eZContentObject::fixReverseRelations( $objectID, 'move' );
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentOperationCollection::registerSearchObject( $objectID );
}
return array( 'status' => true );
}
/**
* Adds a new nodeAssignment
*
* @param int $nodeID
* @param int $objectId
* @param array $selectedNodeIDArray
*
* @return array An array with operation status, always true
*/
static public function addAssignment( $nodeID, $objectID, $selectedNodeIDArray )
{
$userClassIDArray = eZUser::contentClassIDs();
$object = eZContentObject::fetch( $objectID );
$class = $object->contentClass();
$nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false );
$assignedNodes = $object->assignedNodes();
$parentNodeIDArray = array();
foreach ( $assignedNodes as $assignedNode )
{
$append = false;
foreach ( $nodeAssignmentList as $nodeAssignment )
{
if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) )
{
$append = true;
break;
}
}
if ( $append )
{
$parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' );
}
}
$db = eZDB::instance();
$db->begin();
$locationAdded = false;
$node = eZContentObjectTreeNode::fetch( $nodeID );
foreach ( $selectedNodeIDArray as $selectedNodeID )
{
if ( !in_array( $selectedNodeID, $parentNodeIDArray ) )
{
$parentNode = eZContentObjectTreeNode::fetch( $selectedNodeID );
$parentNodeObject = $parentNode->attribute( 'object' );
$canCreate = ( ( $parentNode->checkAccess( 'create', $class->attribute( 'id' ), $parentNodeObject->attribute( 'contentclass_id' ) ) == 1 ) ||
( $parentNode->canAddLocation() && $node->canRead() ) );
if ( $canCreate )
{
$insertedNode = $object->addLocation( $selectedNodeID, true );
// Now set is as published and fix main_node_id
$insertedNode->setAttribute( 'contentobject_is_published', 1 );
$insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) );
$insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) );
// Make sure the url alias is set updated.
$insertedNode->updateSubTreePath();
$insertedNode->sync();
$locationAdded = true;
}
}
}
if ( $locationAdded )
{
//call appropriate method from search engine
eZSearch::addNodeAssignment( $nodeID, $objectID, $selectedNodeIDArray );
// clear user policy cache if this was a user object
if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) )
{
eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) );
}
}
$db->commit();
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentOperationCollection::registerSearchObject( $objectID );
}
return array( 'status' => true );
}
/**
* Removes nodes
*
* This function does not check about permissions, this is the responsibility of the caller!
*
* @param array $removeNodeIdList Array of Node ID to remove
*
* @return array An array with operation status, always true
*/
static public function removeNodes( array $removeNodeIdList )
{
$mainNodeChanged = array();
$nodeAssignmentIdList = array();
$objectIdList = array();
$db = eZDB::instance();
$db->begin();
foreach ( $removeNodeIdList as $nodeId )
{
$node = eZContentObjectTreeNode::fetch($nodeId);
$objectId = $node->attribute( 'contentobject_id' );
foreach ( eZNodeAssignment::fetchForObject( $objectId,
eZContentObject::fetch( $objectId )->attribute( 'current_version' ),
0, false ) as $nodeAssignmentKey => $nodeAssignment )
{
if ( $nodeAssignment['parent_node'] == $node->attribute( 'parent_node_id' ) )
{
$nodeAssignmentIdList[$nodeAssignment['id']] = 1;
}
}
if ( $nodeId == $node->attribute( 'main_node_id' ) )
$mainNodeChanged[$objectId] = 1;
$node->removeThis();
if ( !isset( $objectIdList[$objectId] ) )
$objectIdList[$objectId] = eZContentObject::fetch( $objectId );
}
eZNodeAssignment::purgeByID( array_keys( $nodeAssignmentIdList ) );
foreach ( array_keys( $mainNodeChanged ) as $objectId )
{
$allNodes = $objectIdList[$objectId]->assignedNodes();
// Registering node that will be promoted as 'main'
if ( isset( $allNodes[0] ) )
{
$mainNodeChanged[$objectId] = $allNodes[0];
eZContentObjectTreeNode::updateMainNodeID( $allNodes[0]->attribute( 'node_id' ), $objectId, false, $allNodes[0]->attribute( 'parent_node_id' ) );
}
}
// Give other search engines that the default one a chance to reindex
// when removing locations.
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
foreach ( array_keys( $objectIdList ) as $objectId )
eZContentOperationCollection::registerSearchObject( $objectId );
}
$db->commit();
//call appropriate method from search engine
eZSearch::removeNodes( $removeNodeIdList );
$userClassIdList = eZUser::contentClassIDs();
foreach ( $objectIdList as $objectId => $object )
{
eZContentCacheManager::clearObjectViewCacheIfNeeded( $objectId );
// clear user policy cache if this was a user object
if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIdList ) )
{
eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) );
}
// Give other search engines that the default one a chance to reindex
// when removing locations.
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentOperationCollection::registerSearchObject( $objectId );
}
}
// Triggering content/cache filter for Http cache purge
ezpEvent::getInstance()->filter( 'content/cache', $removeNodeIdList, array_keys( $objectIdList ) );
// we don't clear template block cache here since it's cleared in eZContentObjectTreeNode::removeNode()
return array( 'status' => true );
}
/**
* Deletes a content object, or a list of content objects
*
* @param array $deleteIDArray
* @param bool $moveToTrash
*
* @return array An array with operation status, always true
*/
static public function deleteObject( $deleteIDArray, $moveToTrash = false )
{
$ini = eZINI::instance();
$aNodes = eZContentObjectTreeNode::fetch( $deleteIDArray );
if( !is_array( $aNodes ) )
{
$aNodes = array( $aNodes );
}
$delayedIndexingValue = $ini->variable( 'SearchSettings', 'DelayedIndexing' );
if ( $delayedIndexingValue === 'enabled' || $delayedIndexingValue === 'classbased' )
{
$pendingActionsToDelete = array();
$classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); // Will be used below if DelayedIndexing is classbased
$assignedNodesByObject = array();
$nodesToDeleteByObject = array();
foreach ( $aNodes as $node )
{
$object = $node->object();
$objectID = $object->attribute( 'id' );
$assignedNodes = $object->attribute( 'assigned_nodes' );
// Only delete pending action if this is the last object's node that is requested for deletion
// But $deleteIDArray can also contain all the object's node (mainly if this method is called programmatically)
// So if this is not the last node, then store its id in a temp array
// This temp array will then be compared to the whole object's assigned nodes array
if ( count( $assignedNodes ) > 1 )
{
// $assignedNodesByObject will be used as a referent to check if we want to delete all lasting nodes
if ( !isset( $assignedNodesByObject[$objectID] ) )
{
$assignedNodesByObject[$objectID] = array();
foreach ( $assignedNodes as $assignedNode )
{
$assignedNodesByObject[$objectID][] = $assignedNode->attribute( 'node_id' );
}
}
// Store the node assignment we want to delete
// Then compare the array to the referent node assignment array
$nodesToDeleteByObject[$objectID][] = $node->attribute( 'node_id' );
$diff = array_diff( $assignedNodesByObject[$objectID], $nodesToDeleteByObject[$objectID] );
if ( !empty( $diff ) ) // We still have more node assignments for object, pending action is not to be deleted considering this iteration
{
continue;
}
}
if ( $delayedIndexingValue !== 'classbased' ||
( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) )
{
$pendingActionsToDelete[] = $objectID;
}
}
if ( !empty( $pendingActionsToDelete ) )
{
$filterConds = array( 'param' => array ( $pendingActionsToDelete ) );
eZPendingActions::removeByAction( 'index_object', $filterConds );
}
}
// Add assigned nodes to the clear cache list
// This allows to clear assigned nodes separately (e.g. in reverse proxies)
// as once content is removed, there is no more assigned nodes, and http cache clear is not possible any more.
// See https://jira.ez.no/browse/EZP-22447
foreach ( $aNodes as $node )
{
eZContentCacheManager::addAdditionalNodeIDPerObject( $node->attribute( 'contentobject_id' ), $node->attribute( 'node_id' ) );
}
eZContentObjectTreeNode::removeSubtrees( $deleteIDArray, $moveToTrash );
return array( 'status' => true );
}
/**
* Changes an contentobject's status
*
* @param int $nodeID
*
* @return array An array with operation status, always true
*/
static public function changeHideStatus( $nodeID )
{
$action = 'hide';
$curNode = eZContentObjectTreeNode::fetch( $nodeID );
if ( is_object( $curNode ) )
{
if ( $curNode->attribute( 'is_hidden' ) )
{
eZContentObjectTreeNode::unhideSubTree( $curNode );
$action = 'show';
}
else
eZContentObjectTreeNode::hideSubTree( $curNode );
}
//call appropriate method from search engine
eZSearch::updateNodeVisibility( $nodeID, $action );
return array( 'status' => true );
}
/**
* Swap a node with another one
*
* @param int $nodeID
* @param int $selectedNodeID
* @param array $nodeIdList
*
* @return array An array with operation status, always true
*/
static public function swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() )
{
$userClassIDArray = eZUser::contentClassIDs();
$node = eZContentObjectTreeNode::fetch( $nodeID );
$selectedNode = eZContentObjectTreeNode::fetch( $selectedNodeID );
$object = $node->object();
$nodeParentNodeID = $node->attribute( 'parent_node_id' );
$nodeParent = $node->attribute( 'parent' );
$objectID = $object->attribute( 'id' );
$objectVersion = $object->attribute( 'current_version' );
$selectedObject = $selectedNode->object();
$selectedObjectID = $selectedObject->attribute( 'id' );
$selectedObjectVersion = $selectedObject->attribute( 'current_version' );
$selectedNodeParentNodeID = $selectedNode->attribute( 'parent_node_id' );
$selectedNodeParent = $selectedNode->attribute( 'parent' );
$db = eZDB::instance();
$db->begin();
$node->setAttribute( 'contentobject_id', $selectedObjectID );
$node->setAttribute( 'contentobject_version', $selectedObjectVersion );
$selectedNode->setAttribute( 'contentobject_id', $objectID );
$selectedNode->setAttribute( 'contentobject_version', $objectVersion );
// fix main node id
if ( $node->isMain() && !$selectedNode->isMain() )
{
$node->setAttribute( 'main_node_id', $selectedNode->attribute( 'main_node_id' ) );
$selectedNode->setAttribute( 'main_node_id', $selectedNode->attribute( 'node_id' ) );
}
else if ( $selectedNode->isMain() && !$node->isMain() )
{
$selectedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) );
$node->setAttribute( 'main_node_id', $node->attribute( 'node_id' ) );
}
$node->store();
$selectedNode->store();
// clear user policy cache if this was a user object
if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) )
{
eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) );
}
if ( in_array( $selectedObject->attribute( 'contentclass_id' ), $userClassIDArray ) )
{
eZUser::purgeUserCacheByUserId( $selectedObject->attribute( 'id' ) );
}
// modify path string
$changedOriginalNode = eZContentObjectTreeNode::fetch( $nodeID );
$changedOriginalNode->updateSubTreePath();
$changedTargetNode = eZContentObjectTreeNode::fetch( $selectedNodeID );
$changedTargetNode->updateSubTreePath();
// modify section
if ( $changedOriginalNode->isMain() )
{
$changedOriginalObject = $changedOriginalNode->object();
$parentObject = $nodeParent->object();
if ( $changedOriginalObject->attribute( 'section_id' ) != $parentObject->attribute( 'section_id' ) )
{
eZContentObjectTreeNode::assignSectionToSubTree( $changedOriginalNode->attribute( 'main_node_id' ),
$parentObject->attribute( 'section_id' ),
$changedOriginalObject->attribute( 'section_id' ) );
}
}
if ( $changedTargetNode->isMain() )
{
$changedTargetObject = $changedTargetNode->object();
$selectedParentObject = $selectedNodeParent->object();
if ( $changedTargetObject->attribute( 'section_id' ) != $selectedParentObject->attribute( 'section_id' ) )
{
eZContentObjectTreeNode::assignSectionToSubTree( $changedTargetNode->attribute( 'main_node_id' ),
$selectedParentObject->attribute( 'section_id' ),
$changedTargetObject->attribute( 'section_id' ) );
}
}
eZContentObject::fixReverseRelations( $objectID, 'swap' );
eZContentObject::fixReverseRelations( $selectedObjectID, 'swap' );
$db->commit();
// clear cache for new placement.
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentOperationCollection::registerSearchObject( $objectID );
}
eZSearch::swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() );
return array( 'status' => true );
}
/**
* Assigns a node to a section
*
* @param int $nodeID
* @param int $selectedSectionID
* @param bool $updateSearchIndexes
*
* @return void
*/
static public function updateSection( $nodeID, $selectedSectionID, $updateSearchIndexes = true )
{
eZContentObjectTreeNode::assignSectionToSubTree( $nodeID, $selectedSectionID, false, $updateSearchIndexes );
}
/**
* Changes the status of a translation
*
* @param int $objectID
* @param int $status
*
* @return array An array with operation status, always true
*/
static public function changeTranslationAvailableStatus( $objectID, $status = false )
{
$object = eZContentObject::fetch( $objectID );
if ( !$object->canEdit() )
{
return array( 'status' => false );
}
if ( $object->isAlwaysAvailable() & $status == false )
{
$object->setAlwaysAvailableLanguageID( false );
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
}
else if ( !$object->isAlwaysAvailable() & $status == true )
{
$object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) );
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
}
return array( 'status' => true );
}
/**
* Changes the sort order for a node
*
* @param int $nodeID
* @param string $sortingField
* @param bool $sortingOrder
*
* @return array An array with operation status, always true
*/
static public function changeSortOrder( $nodeID, $sortingField, $sortingOrder = false )
{
$curNode = eZContentObjectTreeNode::fetch( $nodeID );
if ( is_object( $curNode ) )
{
$db = eZDB::instance();
$db->begin();
$curNode->setAttribute( 'sort_field', $sortingField );
$curNode->setAttribute( 'sort_order', $sortingOrder );
$curNode->store();
$db->commit();
$object = $curNode->object();
eZContentCacheManager::clearContentCacheIfNeeded( $object->attribute( 'id' ) );
}
return array( 'status' => true );
}
/**
* Updates the priority of a node
*
* @param int $parentNodeID
* @param array $priorityArray
* @param array $priorityIDArray
*
* @return array An array with operation status, always true
*/
static public function updatePriority( $parentNodeID, $priorityArray = array(), $priorityIDArray = array() )
{
$curNode = eZContentObjectTreeNode::fetch( $parentNodeID );
if ( $curNode instanceof eZContentObjectTreeNode )
{
$objectIDs = array();
$db = eZDB::instance();
$db->begin();
for ( $i = 0, $l = count( $priorityArray ); $i < $l; $i++ )
{
$priority = (int) $priorityArray[$i];
$nodeID = (int) $priorityIDArray[$i];
$node = eZContentObjectTreeNode::fetch( $nodeID );
if ( !$node instanceof eZContentObjectTreeNode )
{
continue;
}
$objectIDs[] = $node->attribute( 'contentobject_id' );
$db->query( "UPDATE
ezcontentobject_tree
SET
priority={$priority}
WHERE
node_id={$nodeID} AND parent_node_id={$parentNodeID}" );
}
$curNode->updateAndStoreModified();
$db->commit();
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentCacheManager::clearContentCacheIfNeeded( $objectIDs );
foreach ( $objectIDs as $objectID )
{
eZContentOperationCollection::registerSearchObject( $objectID );
}
}
}
return array( 'status' => true );
}
/**
* Update a node's main assignment
*
* @param int $mainAssignmentID
* @param int $objectID
* @param int $mainAssignmentParentID
*
* @return array An array with operation status, always true
*/
static public function updateMainAssignment( $mainAssignmentID, $objectID, $mainAssignmentParentID )
{
eZContentObjectTreeNode::updateMainNodeID( $mainAssignmentID, $objectID, false, $mainAssignmentParentID );
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentOperationCollection::registerSearchObject( $objectID );
}
return array( 'status' => true );
}
/**
* Updates an contentobject's initial language
*
* @param int $objectID
* @param int $newInitialLanguageID
*
* @return array An array with operation status, always true
*/
static public function updateInitialLanguage( $objectID, $newInitialLanguageID )
{
$object = eZContentObject::fetch( $objectID );
$language = eZContentLanguage::fetch( $newInitialLanguageID );
if ( $language and !$language->attribute( 'disabled' ) )
{
$object->setAttribute( 'initial_language_id', $newInitialLanguageID );
$objectName = $object->name( false, $language->attribute( 'locale' ) );
$object->setAttribute( 'name', $objectName );
$object->store();
if ( $object->isAlwaysAvailable() )
{
$object->setAlwaysAvailableLanguageID( $newInitialLanguageID );
}
$nodes = $object->assignedNodes();
foreach ( $nodes as $node )
{
$node->updateSubTreePath();
}
}
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
return array( 'status' => true );
}
/**
* Set the always available flag for a content object
*
* @param int $objectID
* @param int $newAlwaysAvailable
* @return array An array with operation status, always true
*/
static public function updateAlwaysAvailable( $objectID, $newAlwaysAvailable )
{
$object = eZContentObject::fetch( $objectID );
$change = false;
if ( $object->isAlwaysAvailable() & $newAlwaysAvailable == false )
{
$object->setAlwaysAvailableLanguageID( false );
$change = true;
}
else if ( !$object->isAlwaysAvailable() & $newAlwaysAvailable == true )
{
$object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) );
$change = true;
}
if ( $change )
{
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
if ( !eZSearch::getEngine() instanceof eZSearchEngine )
{
eZContentOperationCollection::registerSearchObject( $objectID );
}
}
return array( 'status' => true );
}
/**
* Removes a translation for a contentobject
*
* @param int $objectID
* @param array
* @return array An array with operation status, always true
*/
static public function removeTranslation( $objectID, $languageIDArray )
{
$object = eZContentObject::fetch( $objectID );
foreach( $languageIDArray as $languageID )
{
if ( !$object->removeTranslation( $languageID ) )
{
eZDebug::writeError( "Object with id $objectID: cannot remove the translation with language id $languageID!",
__METHOD__ );
}
}
eZContentOperationCollection::registerSearchObject( $objectID );
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
return array( 'status' => true );
}
/**
* Update a contentobject's state
*
* @param int $objectID
* @param int $selectedStateIDList
*
* @return array An array with operation status, always true
*/
static public function updateObjectState( $objectID, $selectedStateIDList )
{
$object = eZContentObject::fetch( $objectID );
// we don't need to re-assign states the object currently already has assigned
$currentStateIDArray = $object->attribute( 'state_id_array' );
$selectedStateIDList = array_diff( $selectedStateIDList, $currentStateIDArray );
// filter out any states the current user is not allowed to assign
$canAssignStateIDList = $object->attribute( 'allowed_assign_state_id_list' );
$selectedStateIDList = array_intersect( $selectedStateIDList, $canAssignStateIDList );
foreach ( $selectedStateIDList as $selectedStateID )
{
$state = eZContentObjectState::fetchById( $selectedStateID );
$object->assignState( $state );
}
eZAudit::writeAudit( 'state-assign', array( 'Content object ID' => $object->attribute( 'id' ),
'Content object name' => $object->attribute( 'name' ),
'Selected State ID Array' => implode( ', ' , $selectedStateIDList ),
'Comment' => 'Updated states of the current object: eZContentOperationCollection::updateObjectState()' ) );
//call appropriate method from search engine
eZSearch::updateObjectState($objectID, $selectedStateIDList);
// Triggering content/state/assign event for persistence cache purge
ezpEvent::getInstance()->notify( 'content/state/assign', array( $objectID, $selectedStateIDList ) );
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
return array( 'status' => true );
}
/**
* Executes the pre-publish trigger for this object, and handles
* specific return statuses from the workflow
*
* @param int $objectID Object ID
* @param int $version Version number
*
* @since 4.2
*/
static public function executePrePublishTrigger( $objectID, $version )
{
}
/**
* Creates a RSS/ATOM Feed export for a node
*
* @param int $nodeID Node ID
*
* @since 4.3
*/
static public function createFeedForNode( $nodeID )
{
$hasExport = eZRSSFunctionCollection::hasExportByNode( $nodeID );
if ( isset( $hasExport['result'] ) && $hasExport['result'] )
{
eZDebug::writeError( 'There is already a rss/atom export feed for this node: ' . $nodeID, __METHOD__ );
return array( 'status' => false );
}
$node = eZContentObjectTreeNode::fetch( $nodeID );
$currentClassIdentifier = $node->attribute( 'class_identifier' );
$config = eZINI::instance( 'site.ini' );
$feedItemClasses = $config->variable( 'RSSSettings', 'DefaultFeedItemClasses' );
if ( !$feedItemClasses || !isset( $feedItemClasses[ $currentClassIdentifier ] ) )
{
eZDebug::writeError( "EnableRSS: content class $currentClassIdentifier is not defined in site.ini[RSSSettings]DefaultFeedItemClasses[<class_id>].", __METHOD__ );
return array( 'status' => false );
}
$object = $node->object();
$objectID = $object->attribute('id');
$currentUserID = eZUser::currentUserID();
$rssExportItems = array();
$db = eZDB::instance();
$db->begin();
$rssExport = eZRSSExport::create( $currentUserID );
$rssExport->setAttribute( 'access_url', 'rss_feed_' . $nodeID );
$rssExport->setAttribute( 'node_id', $nodeID );
$rssExport->setAttribute( 'main_node_only', '1' );
$rssExport->setAttribute( 'number_of_objects', $config->variable( 'RSSSettings', 'NumberOfObjectsDefault' ) );
$rssExport->setAttribute( 'rss_version', $config->variable( 'RSSSettings', 'DefaultVersion' ) );
$rssExport->setAttribute( 'status', eZRSSExport::STATUS_VALID );
$rssExport->setAttribute( 'title', $object->name() );
$rssExport->store();
$rssExportID = $rssExport->attribute( 'id' );
foreach( explode( ';', $feedItemClasses[$currentClassIdentifier] ) as $classIdentifier )
{
$iniSection = 'RSSSettings_' . $classIdentifier;
if ( $config->hasVariable( $iniSection, 'FeedObjectAttributeMap' ) )
{
$feedObjectAttributeMap = $config->variable( $iniSection, 'FeedObjectAttributeMap' );
$subNodesMap = $config->hasVariable( $iniSection, 'Subnodes' ) ? $config->variable( $iniSection, 'Subnodes' ) : array();
$rssExportItem = eZRSSExportItem::create( $rssExportID );
$rssExportItem->setAttribute( 'class_id', eZContentObjectTreeNode::classIDByIdentifier( $classIdentifier ) );
$rssExportItem->setAttribute( 'title', $feedObjectAttributeMap['title'] );
if ( isset( $feedObjectAttributeMap['description'] ) )
$rssExportItem->setAttribute( 'description', $feedObjectAttributeMap['description'] );
if ( isset( $feedObjectAttributeMap['category'] ) )
$rssExportItem->setAttribute( 'category', $feedObjectAttributeMap['category'] );
if ( isset( $feedObjectAttributeMap['enclosure'] ) )
$rssExportItem->setAttribute( 'enclosure', $feedObjectAttributeMap['enclosure'] );
$rssExportItem->setAttribute( 'source_node_id', $nodeID );
$rssExportItem->setAttribute( 'status', eZRSSExport::STATUS_VALID );
$rssExportItem->setAttribute( 'subnodes', isset( $subNodesMap[$currentClassIdentifier] ) && $subNodesMap[$currentClassIdentifier] === 'true' );
$rssExportItem->store();
}
else
{
eZDebug::writeError( "site.ini[$iniSection]Source[] setting is not defined.", __METHOD__ );
}
}
$db->commit();
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
return array( 'status' => true );
}
/**
* Removes a RSS/ATOM Feed export for a node
*
* @param int $nodeID Node ID
*
* @since 4.3
*/
static public function removeFeedForNode( $nodeID )
{
$rssExport = eZPersistentObject::fetchObject( eZRSSExport::definition(),
null,
array( 'node_id' => $nodeID,
'status' => eZRSSExport::STATUS_VALID ),
true );
if ( !$rssExport instanceof eZRSSExport )
{
eZDebug::writeError( 'DisableRSS: There is no rss/atom feeds left to delete for this node: '. $nodeID, __METHOD__ );
return array( 'status' => false );
}
$node = eZContentObjectTreeNode::fetch( $nodeID );
if ( !$node instanceof eZContentObjectTreeNode )
{
eZDebug::writeError( 'DisableRSS: Could not fetch node: '. $nodeID, __METHOD__ );
return array( 'status' => false );
}
$objectID = $node->attribute('contentobject_id');
$rssExport->removeThis();
eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
return array( 'status' => true );
}
/**
* Sends the published object/version for publishing to the queue
* Used by the content/publish operation
* @param int $objectId
* @param int $version
*
* @return array( status => int )
* @since 4.5
*/
public static function sendToPublishingQueue( $objectId, $version )
{
$behaviour = ezpContentPublishingBehaviour::getBehaviour();
if ( $behaviour->disableAsynchronousPublishing )
$asyncEnabled = false;
else
$asyncEnabled = ( eZINI::instance( 'content.ini' )->variable( 'PublishingSettings', 'AsynchronousPublishing' ) == 'enabled' );
$accepted = true;
if ( $asyncEnabled === true )
{
// Filter handlers
$ini = eZINI::instance( 'content.ini' );
$filterHandlerClasses = $ini->variable( 'PublishingSettings', 'AsynchronousPublishingFilters' );
if ( count( $filterHandlerClasses ) )
{
$versionObject = eZContentObjectVersion::fetchVersion( $version, $objectId );
foreach( $filterHandlerClasses as $filterHandlerClass )
{
if ( !class_exists( $filterHandlerClass ) )
{
eZDebug::writeError( "Unknown asynchronous publishing filter handler class '$filterHandlerClass'", __METHOD__ );
continue;
}
$handler = new $filterHandlerClass( $versionObject );
if ( !( $handler instanceof ezpAsynchronousPublishingFilterInterface ) )
{
eZDebug::writeError( "Asynchronous publishing filter handler class '$filterHandlerClass' does not implement ezpAsynchronousPublishingFilterInterface", __METHOD__ );
continue;
}
$accepted = $handler->accept();
if ( !$accepted )
{
eZDebugSetting::writeDebug( "Object #{$objectId}/{$version} was excluded from asynchronous publishing by $filterHandlerClass", __METHOD__ );
break;
}
}
}
unset( $filterHandlerClasses, $handler );
}
if ( $asyncEnabled && $accepted )
{
// if the object is already in the process queue, we move ahead
// this test should NOT be necessary since http://issues.ez.no/17840 was fixed
if ( ezpContentPublishingQueue::isQueued( $objectId, $version ) )
{
return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE );
}
// the object isn't in the process queue, this means this is the first time we execute this method
// the object must be queued
else
{
ezpContentPublishingQueue::add( $objectId, $version );
return array( 'status' => eZModuleOperationInfo::STATUS_HALTED, 'redirect_url' => "content/queued/{$objectId}/{$version}" );
}
}
else
{
return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE );
}
}
}
?>
| pbek/ezpublish-legacy | kernel/content/ezcontentoperationcollection.php | PHP | gpl-2.0 | 64,392 |
<?php
/**
* AliPay IPN Handler.
*
* Copyright: © 2009-2011
* {@link http://www.websharks-inc.com/ WebSharks, Inc.}
* (coded in the USA)
*
* This WordPress plugin (s2Member Pro) is comprised of two parts:
*
* o (1) Its PHP code is licensed under the GPL license, as is WordPress.
* You should have received a copy of the GNU General Public License,
* along with this software. In the main directory, see: /licensing/
* If not, see: {@link http://www.gnu.org/licenses/}.
*
* o (2) All other parts of (s2Member Pro); including, but not limited to:
* the CSS code, some JavaScript code, images, and design;
* are licensed according to the license purchased.
* See: {@link http://www.s2member.com/prices/}
*
* Unless you have our prior written consent, you must NOT directly or indirectly license,
* sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module;
* or make an offer to do any of these things. All of these things are strictly
* prohibited with part (2) of the s2Member Pro Module.
*
* Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com
* (i.e. new features, bug fixes, updates, improvements); along with full access
* to our video tutorial library: {@link http://www.s2member.com/videos/}
*
* @package s2Member\AliPay
* @since 1.5
*/
if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"]))
exit("Do not access this file directly.");
if (!class_exists ("c_ws_plugin__s2member_pro_alipay_notify"))
{
/**
* AliPay IPN Handler.
*
* @package s2Member\AliPay
* @since 1.5
*/
class c_ws_plugin__s2member_pro_alipay_notify
{
/**
* Handles AliPay IPN URL processing.
*
* @package s2Member\AliPay
* @since 1.5
*
* @attaches-to ``add_action("init");``
*
* @return null|inner Return-value of inner routine.
*/
public static function alipay_notify ()
{
if (!empty($_POST["notify_type"]) && preg_match ("/^trade_status_sync$/i", $_POST["notify_type"]))
{
return c_ws_plugin__s2member_pro_alipay_notify_in::alipay_notify ();
}
}
}
}
?> | kydrenw/boca | wp-content/plugins/s2member-pro/includes/classes/gateways/alipay/alipay-notify.inc.php | PHP | gpl-2.0 | 2,106 |
<?php
/**
* Preview class.
*
* @package WPForms
* @author WPForms
* @since 1.1.5
* @license GPL-2.0+
* @copyright Copyright (c) 2016, WPForms LLC
*/
class WPForms_Preview {
/**
* Primary class constructor.
*
* @since 1.1.5
*/
public function __construct() {
// Maybe load a preview page
add_action( 'init', array( $this, 'init' ) );
// Hide preview page from admin
add_action( 'pre_get_posts', array( $this, 'form_preview_hide' ) );
}
/**
* Determing if the user should see a preview page, if so, party on.
*
* @since 1.1.5
*/
public function init() {
// Check for preview param with allowed values
if ( empty( $_GET['wpforms_preview'] ) || !in_array( $_GET['wpforms_preview'], array( 'print', 'form' ) ) ) {
return;
}
// Check for authenticated user with correct capabilities
if ( !is_user_logged_in() || !current_user_can( apply_filters( 'wpforms_manage_cap', 'manage_options' ) ) ) {
return;
}
// Print preview
if ( 'print' == $_GET['wpforms_preview'] && !empty( $_GET['entry_id'] ) ) {
$this->print_preview();
}
// Form preview
if ( 'form' == $_GET['wpforms_preview'] && !empty( $_GET['form_id'] ) ) {
$this->form_preview();
}
}
/**
* Print Preview.
*
* @since 1.1.5
*/
public function print_preview() {
// Load entry details
$entry = wpforms()->entry->get( absint( $_GET['entry_id'] ) );
// Double check that we found a real entry
if ( ! $entry || empty( $entry ) ) {
return;
}
// Get form details
$form_data = wpforms()->form->get( $entry->form_id, array( 'content_only' => true ) );
// Double check that we found a valid entry
if ( ! $form_data || empty( $form_data ) ) {
return;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>WPForms Print Preview - <?php echo ucfirst( sanitize_text_field( $form_data['settings']['form_title'] ) ); ?> </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow,noarchive">
<link rel="stylesheet" href="<?php echo includes_url('css/buttons.min.css'); ?>" type="text/css">
<link rel="stylesheet" href="<?php echo WPFORMS_PLUGIN_URL; ?>assets/css/wpforms-preview.css" type="text/css">
<script type="text/javascript" src="<?php echo includes_url('js/jquery/jquery.js'); ?>"></script>
<script type="text/javascript" src="<?php echo WPFORMS_PLUGIN_URL; ?>assets/js/wpforms-preview.js"></script>
</head>
<body class="wp-core-ui">
<div class="wpforms-preview" id="print">
<h1>
<?php echo sanitize_text_field( $form_data['settings']['form_title'] ); ?> <span> - <?php printf( __( 'Entry #%d', 'wpforms' ), absint( $entry->entry_id ) ); ?></span>
<div class="buttons">
<a href="" class="button button-secondary close-window">Close</a>
<a href="" class="button button-primary print">Print</a>
</div>
</h1>
<?php
$fields = apply_filters( 'wpforms_entry_single_data', wpforms_decode( $entry->fields ), $entry, $form_data );
if ( empty( $fields ) ) {
// Whoops, no fields! This shouldn't happen under normal use cases.
echo '<p class="no-fields">' . __( 'This entry does not have any fields', 'wpforms' ) . '</p>';
} else {
echo '<div class="fields">';
// Display the fields and their values
foreach ( $fields as $key => $field ) {
$field_value = apply_filters( 'wpforms_html_field_value', wp_strip_all_tags( $field['value'] ), $field, $form_data );
$field_class = sanitize_html_class( 'wpforms-field-' . $field['type'] );
$field_class .= empty( $field_value ) ? ' empty' : '';
echo '<div class="wpforms-entry-field ' . $field_class . '">';
// Field name
echo '<p class="wpforms-entry-field-name">';
echo !empty( $field['name'] ) ? wp_strip_all_tags( $field['name'] ) : sprintf( __( 'Field ID #%d', 'wpforms' ), absint( $field['id'] ) );
echo '</p>';
// Field value
echo '<p class="wpforms-entry-field-value">';
echo !empty( $field_value ) ? nl2br( make_clickable( $field_value ) ) : __( 'Empty', 'wpforms' );
echo '</p>';
echo '</div>';
}
echo '</div>';
}
?>
</div><!-- .wrap -->
<p class="site"><a href="<?php echo home_url(); ?>"><?php echo get_bloginfo( 'name'); ?></a></p>
</body>
<?php
exit();
}
/**
* Check if preview page exists, if not create it.
*
* @since 1.1.9
*/
public function form_preview_check() {
if ( !is_admin() )
return;
// Verify page exits
$preview = get_option( 'wpforms_preview_page' );
if ( $preview ) {
$preview_page = get_post( $preview );
// Check to see if the visibility has been changed, if so correct it
if ( !empty( $preview_page ) && 'private' != $preview_page->post_status ) {
$preview_page->post_status = 'private';
wp_update_post( $preview_page );
return;
} elseif ( !empty( $preview_page ) ) {
return;
}
}
// Create the custom preview page
$content = '<p>' . __( 'This is the WPForms preview page. All your form previews will be handled on this page.', 'wpforms' ) . '</p>';
$content .= '<p>' . __( 'The page is set to private, so it is not publically accessible. Please do not delete this page :) .', 'wpforms' ) . '</p>';
$args = array(
'post_type' => 'page',
'post_name' => 'wpforms-preview',
'post_author' => 1,
'post_title' => __( 'WPForms Preview', 'wpforms' ),
'post_status' => 'private',
'post_content' => $content,
'comment_status' => 'closed'
);
$id = wp_insert_post( $args );
if ( $id ) {
update_option( 'wpforms_preview_page', $id );
}
}
/**
* Preview page URL.
*
* @since 1.1.9
* @param int $form_id
* @return string
*/
public function form_preview_url( $form_id ) {
$id = get_option( 'wpforms_preview_page' );
if ( ! $id ) {
return home_url();
}
$url = get_permalink( $id );
if ( ! $url ) {
return home_url();
}
return add_query_arg( array( 'wpforms_preview' => 'form', 'form_id' => absint( $form_id ) ), $url );
}
/**
* Fires when form preview might be detected.
*
* @since 1.1.9
*/
public function form_preview() {
add_filter( 'the_posts', array( $this, 'form_preview_query' ), 10, 2 );
}
/**
* Tweak the page content for form preview page requests.
*
* @since 1.1.9
* @param array $posts
* @param object $query
* @return array
*/
public function form_preview_query( $posts, $query ) {
// One last cap check, just for fun.
if ( !is_user_logged_in() || !current_user_can( apply_filters( 'wpforms_manage_cap', 'manage_options' ) ) ) {
return $posts;
}
// Only target main query
if ( ! $query->is_main_query() ) {
return $posts;
}
// If our queried object ID does not match the preview page ID, return early.
$preview_id = absint( get_option( 'wpforms_preview_page' ) );
$queried = $query->get_queried_object_id();
if ( $queried && $queried != $preview_id && isset( $query->query_vars['page_id'] ) && $preview_id != $query->query_vars['page_id'] ) {
return $posts;
}
// Get the form details
$form = wpforms()->form->get( absint( $_GET['form_id'] ), array( 'content_only' => true ) );
if ( ! $form || empty( $form ) ) {
return $posts;
}
// Customize the page content
$title = sanitize_text_field( $form['settings']['form_title'] );
$shortcode = '[wpforms id="' . absint( $form['id'] ) . '"]';
$content = __( 'This is a preview of your form. This page not publically accessible.', 'wpforms' );
if ( !empty( $_GET['new_window'] ) ) {
$content .= ' <a href="javascript:window.close();">' . __( 'Close this window', 'wpforms' ) . '.</a>';
}
$posts[0]->post_title = $title . __( ' Preview', 'wpforms' );
$posts[0]->post_content = $content . $shortcode;
$posts[0]->post_status = 'public';
return $posts;
}
/**
* Hide the preview page from admin
*
* @since 1.2.3
* @param object $query
*/
function form_preview_hide( $query ) {
if( $query->is_main_query() && is_admin() && isset( $query->query_vars['post_type'] ) && 'page' == $query->query_vars['post_type'] ) {
$wpforms_preview = intval( get_option( 'wpforms_preview_page' ) );
if( $wpforms_preview ) {
$exclude = $query->query_vars['post__not_in'];
$exclude[] = $wpforms_preview;
$query->set( 'post__not_in', $exclude );
}
}
}
} | kimcarey/beeline-web | wp-content/plugins/wpforms-lite/includes/class-preview.php | PHP | gpl-2.0 | 8,541 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Tax
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Tax rate resource model
*
* @category Mage
* @package Mage_Tax
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Tax_Model_Mysql4_Calculation_Rule extends Mage_Tax_Model_Resource_Calculation_Rule
{
}
| miguelangelramirez/magento.dev | app/code/core/Mage/Tax/Model/Mysql4/Calculation/Rule.php | PHP | gpl-2.0 | 1,202 |
/* StreamHandler.java --
A class for publishing log messages to instances of java.io.OutputStream
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.util.logging;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
/**
* A <code>StreamHandler</code> publishes <code>LogRecords</code> to
* a instances of <code>java.io.OutputStream</code>.
*
* @author Sascha Brawer (brawer@acm.org)
*/
public class StreamHandler
extends Handler
{
private OutputStream out;
private Writer writer;
/**
* Indicates the current state of this StreamHandler. The value
* should be one of STATE_FRESH, STATE_PUBLISHED, or STATE_CLOSED.
*/
private int streamState = STATE_FRESH;
/**
* streamState having this value indicates that the StreamHandler
* has been created, but the publish(LogRecord) method has not been
* called yet. If the StreamHandler has been constructed without an
* OutputStream, writer will be null, otherwise it is set to a
* freshly created OutputStreamWriter.
*/
private static final int STATE_FRESH = 0;
/**
* streamState having this value indicates that the publish(LocRecord)
* method has been called at least once.
*/
private static final int STATE_PUBLISHED = 1;
/**
* streamState having this value indicates that the close() method
* has been called.
*/
private static final int STATE_CLOSED = 2;
/**
* Creates a <code>StreamHandler</code> without an output stream.
* Subclasses can later use {@link
* #setOutputStream(java.io.OutputStream)} to associate an output
* stream with this StreamHandler.
*/
public StreamHandler()
{
this(null, null);
}
/**
* Creates a <code>StreamHandler</code> that formats log messages
* with the specified Formatter and publishes them to the specified
* output stream.
*
* @param out the output stream to which the formatted log messages
* are published.
*
* @param formatter the <code>Formatter</code> that will be used
* to format log messages.
*/
public StreamHandler(OutputStream out, Formatter formatter)
{
this(out, "java.util.logging.StreamHandler", Level.INFO,
formatter, SimpleFormatter.class);
}
StreamHandler(
OutputStream out,
String propertyPrefix,
Level defaultLevel,
Formatter formatter, Class defaultFormatterClass)
{
this.level = LogManager.getLevelProperty(propertyPrefix + ".level",
defaultLevel);
this.filter = (Filter) LogManager.getInstanceProperty(
propertyPrefix + ".filter",
/* must be instance of */ Filter.class,
/* default: new instance of */ null);
if (formatter != null)
this.formatter = formatter;
else
this.formatter = (Formatter) LogManager.getInstanceProperty(
propertyPrefix + ".formatter",
/* must be instance of */ Formatter.class,
/* default: new instance of */ defaultFormatterClass);
try
{
String enc = LogManager.getLogManager().getProperty(propertyPrefix
+ ".encoding");
/* make sure enc actually is a valid encoding */
if ((enc != null) && (enc.length() > 0))
new String(new byte[0], enc);
this.encoding = enc;
}
catch (Exception _)
{
}
if (out != null)
{
try
{
changeWriter(out, getEncoding());
}
catch (UnsupportedEncodingException uex)
{
/* This should never happen, since the validity of the encoding
* name has been checked above.
*/
throw new RuntimeException(uex.getMessage());
}
}
}
private void checkOpen()
{
if (streamState == STATE_CLOSED)
throw new IllegalStateException(this.toString() + " has been closed");
}
private void checkFresh()
{
checkOpen();
if (streamState != STATE_FRESH)
throw new IllegalStateException("some log records have been published to " + this);
}
private void changeWriter(OutputStream out, String encoding)
throws UnsupportedEncodingException
{
OutputStreamWriter writer;
/* The logging API says that a null encoding means the default
* platform encoding. However, java.io.OutputStreamWriter needs
* another constructor for the default platform encoding,
* passing null would throw an exception.
*/
if (encoding == null)
writer = new OutputStreamWriter(out);
else
writer = new OutputStreamWriter(out, encoding);
/* Closing the stream has side effects -- do this only after
* creating a new writer has been successful.
*/
if ((streamState != STATE_FRESH) || (this.writer != null))
close();
this.writer = writer;
this.out = out;
this.encoding = encoding;
streamState = STATE_FRESH;
}
/**
* Sets the character encoding which this handler uses for publishing
* log records. The encoding of a <code>StreamHandler</code> must be
* set before any log records have been published.
*
* @param encoding the name of a character encoding, or <code>null</code>
* for the default encoding.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control the
* the logging infrastructure.
*
* @exception IllegalStateException if any log records have been
* published to this <code>StreamHandler</code> before. Please
* be aware that this is a pecularity of the GNU implementation.
* While the API specification indicates that it is an error
* if the encoding is set after records have been published,
* it does not mandate any specific behavior for that case.
*/
public void setEncoding(String encoding)
throws SecurityException, UnsupportedEncodingException
{
/* The inherited implementation first checks whether the invoking
* code indeed has the permission to control the logging infra-
* structure, and throws a SecurityException if this was not the
* case.
*
* Next, it verifies that the encoding is supported and throws
* an UnsupportedEncodingExcpetion otherwise. Finally, it remembers
* the name of the encoding.
*/
super.setEncoding(encoding);
checkFresh();
/* If out is null, setEncoding is being called before an output
* stream has been set. In that case, we need to check that the
* encoding is valid, and remember it if this is the case. Since
* this is exactly what the inherited implementation of
* Handler.setEncoding does, we can delegate.
*/
if (out != null)
{
/* The logging API says that a null encoding means the default
* platform encoding. However, java.io.OutputStreamWriter needs
* another constructor for the default platform encoding, passing
* null would throw an exception.
*/
if (encoding == null)
writer = new OutputStreamWriter(out);
else
writer = new OutputStreamWriter(out, encoding);
}
}
/**
* Changes the output stream to which this handler publishes
* logging records.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure.
*
* @throws NullPointerException if <code>out</code>
* is <code>null</code>.
*/
protected void setOutputStream(OutputStream out)
throws SecurityException
{
LogManager.getLogManager().checkAccess();
/* Throw a NullPointerException if out is null. */
out.getClass();
try
{
changeWriter(out, getEncoding());
}
catch (UnsupportedEncodingException ex)
{
/* This seems quite unlikely to happen, unless the underlying
* implementation of java.io.OutputStreamWriter changes its
* mind (at runtime) about the set of supported character
* encodings.
*/
throw new RuntimeException(ex.getMessage());
}
}
/**
* Publishes a <code>LogRecord</code> to the associated output
* stream, provided the record passes all tests for being loggable.
* The <code>StreamHandler</code> will localize the message of the
* log record and substitute any message parameters.
*
* <p>Most applications do not need to call this method directly.
* Instead, they will use use a {@link Logger}, which will create
* LogRecords and distribute them to registered handlers.
*
* <p>In case of an I/O failure, the <code>ErrorManager</code>
* of this <code>Handler</code> will be informed, but the caller
* of this method will not receive an exception.
*
* <p>If a log record is being published to a
* <code>StreamHandler</code> that has been closed earlier, the Sun
* J2SE 1.4 reference can be observed to silently ignore the
* call. The GNU implementation, however, intentionally behaves
* differently by informing the <code>ErrorManager</code> associated
* with this <code>StreamHandler</code>. Since the condition
* indicates a programming error, the programmer should be
* informed. It also seems extremely unlikely that any application
* would depend on the exact behavior in this rather obscure,
* erroneous case -- especially since the API specification does not
* prescribe what is supposed to happen.
*
* @param record the log event to be published.
*/
public void publish(LogRecord record)
{
String formattedMessage;
if (!isLoggable(record))
return;
if (streamState == STATE_FRESH)
{
try
{
writer.write(formatter.getHead(this));
}
catch (java.io.IOException ex)
{
reportError(null, ex, ErrorManager.WRITE_FAILURE);
return;
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.GENERIC_FAILURE);
return;
}
streamState = STATE_PUBLISHED;
}
try
{
formattedMessage = formatter.format(record);
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
return;
}
try
{
writer.write(formattedMessage);
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.WRITE_FAILURE);
}
}
/**
* Checks whether or not a <code>LogRecord</code> would be logged
* if it was passed to this <code>StreamHandler</code> for publication.
*
* <p>The <code>StreamHandler</code> implementation first checks
* whether a writer is present and the handler's level is greater
* than or equal to the severity level threshold. In a second step,
* if a {@link Filter} has been installed, its {@link
* Filter#isLoggable(LogRecord) isLoggable} method is
* invoked. Subclasses of <code>StreamHandler</code> can override
* this method to impose their own constraints.
*
* @param record the <code>LogRecord</code> to be checked.
*
* @return <code>true</code> if <code>record</code> would
* be published by {@link #publish(LogRecord) publish},
* <code>false</code> if it would be discarded.
*
* @see #setLevel(Level)
* @see #setFilter(Filter)
* @see Filter#isLoggable(LogRecord)
*
* @throws NullPointerException if <code>record</code> is
* <code>null</code>. */
public boolean isLoggable(LogRecord record)
{
return (writer != null) && super.isLoggable(record);
}
/**
* Forces any data that may have been buffered to the underlying
* output device.
*
* <p>In case of an I/O failure, the <code>ErrorManager</code>
* of this <code>Handler</code> will be informed, but the caller
* of this method will not receive an exception.
*
* <p>If a <code>StreamHandler</code> that has been closed earlier
* is closed a second time, the Sun J2SE 1.4 reference can be
* observed to silently ignore the call. The GNU implementation,
* however, intentionally behaves differently by informing the
* <code>ErrorManager</code> associated with this
* <code>StreamHandler</code>. Since the condition indicates a
* programming error, the programmer should be informed. It also
* seems extremely unlikely that any application would depend on the
* exact behavior in this rather obscure, erroneous case --
* especially since the API specification does not prescribe what is
* supposed to happen.
*/
public void flush()
{
try
{
checkOpen();
if (writer != null)
writer.flush();
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.FLUSH_FAILURE);
}
}
/**
* Closes this <code>StreamHandler</code> after having forced any
* data that may have been buffered to the underlying output
* device.
*
* <p>As soon as <code>close</code> has been called,
* a <code>Handler</code> should not be used anymore. Attempts
* to publish log records, to flush buffers, or to modify the
* <code>Handler</code> in any other way may throw runtime
* exceptions after calling <code>close</code>.</p>
*
* <p>In case of an I/O failure, the <code>ErrorManager</code>
* of this <code>Handler</code> will be informed, but the caller
* of this method will not receive an exception.</p>
*
* <p>If a <code>StreamHandler</code> that has been closed earlier
* is closed a second time, the Sun J2SE 1.4 reference can be
* observed to silently ignore the call. The GNU implementation,
* however, intentionally behaves differently by informing the
* <code>ErrorManager</code> associated with this
* <code>StreamHandler</code>. Since the condition indicates a
* programming error, the programmer should be informed. It also
* seems extremely unlikely that any application would depend on the
* exact behavior in this rather obscure, erroneous case --
* especially since the API specification does not prescribe what is
* supposed to happen.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure.
*/
public void close()
throws SecurityException
{
LogManager.getLogManager().checkAccess();
try
{
/* Although flush also calls checkOpen, it catches
* any exceptions and reports them to the ErrorManager
* as flush failures. However, we want to report
* a closed stream as a close failure, not as a
* flush failure here. Therefore, we call checkOpen()
* before flush().
*/
checkOpen();
flush();
if (writer != null)
{
if (formatter != null)
{
/* Even if the StreamHandler has never published a record,
* it emits head and tail upon closing. An earlier version
* of the GNU Classpath implementation did not emitted
* anything. However, this had caused XML log files to be
* entirely empty instead of containing no log records.
*/
if (streamState == STATE_FRESH)
writer.write(formatter.getHead(this));
if (streamState != STATE_CLOSED)
writer.write(formatter.getTail(this));
}
streamState = STATE_CLOSED;
writer.close();
}
}
catch (Exception ex)
{
reportError(null, ex, ErrorManager.CLOSE_FAILURE);
}
}
}
| aosm/gcc_40 | libjava/java/util/logging/StreamHandler.java | Java | gpl-2.0 | 16,999 |
<?php
/**
* @file
* Contains \Drupal\Console\Command\Debug\UpdateCommand.
*/
namespace Drupal\Console\Command\Debug;
use Drupal\Console\Command\Shared\UpdateTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Core\Command\Command;
use Drupal\Core\Update\UpdateRegistry;
use Drupal\Console\Utils\Site;
class UpdateCommand extends Command
{
use UpdateTrait;
/**
* @var Site
*/
protected $site;
/**
* @var UpdateRegistry
*/
protected $postUpdateRegistry;
/**
* DebugCommand constructor.
*
* @param Site $site
* @param UpdateRegistry $postUpdateRegistry
*/
public function __construct(
Site $site,
UpdateRegistry $postUpdateRegistry
) {
$this->site = $site;
$this->postUpdateRegistry = $postUpdateRegistry;
parent::__construct();
}
/**
* @inheritdoc
*/
protected function configure()
{
$this
->setName('debug:update')
->setDescription($this->trans('commands.debug.update.description'))
->setAliases(['du']);
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->site->loadLegacyFile('/core/includes/update.inc');
$this->site->loadLegacyFile('/core/includes/install.inc');
drupal_load_updates();
update_fix_compatibility();
$requirements = update_check_requirements();
$severity = drupal_requirements_severity($requirements);
$updates = update_get_update_list();
$postUpdates = $this->postUpdateRegistry->getPendingUpdateInformation();
$this->getIo()->newLine();
if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING)) {
$this->populateRequirements($requirements);
} elseif (empty($updates) && empty($postUpdates)) {
$this->getIo()->info($this->trans('commands.debug.update.messages.no-updates'));
} else {
$this->showUpdateTable($updates, $this->trans('commands.debug.update.messages.module-list'));
$this->showPostUpdateTable($postUpdates, $this->trans('commands.debug.update.messages.module-list-post-update'));
}
}
/**
* @param $requirements
*/
private function populateRequirements($requirements)
{
$this->getIo()->info($this->trans('commands.debug.update.messages.requirements-error'));
$tableHeader = [
$this->trans('commands.debug.update.messages.severity'),
$this->trans('commands.debug.update.messages.title'),
$this->trans('commands.debug.update.messages.value'),
$this->trans('commands.debug.update.messages.description'),
];
$tableRows = [];
foreach ($requirements as $requirement) {
$minimum = in_array(
$requirement['minimum schema'],
[REQUIREMENT_ERROR, REQUIREMENT_WARNING]
);
if ((isset($requirement['minimum schema'])) && ($minimum)) {
$tableRows[] = [
$requirement['severity'],
$requirement['title'],
$requirement['value'],
$requirement['description'],
];
}
}
$this->getIo()->table($tableHeader, $tableRows);
}
}
| maskedjellybean/tee-prop | vendor/drupal/console/src/Command/Debug/UpdateCommand.php | PHP | gpl-2.0 | 3,484 |
<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2016 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct accees
defined ('_JEXEC') or die ('restricted aceess');
class SppagebuilderAddonEmpty_space extends SppagebuilderAddons{
public function render() {
$class = (isset($this->addon->settings->class) && $this->addon->settings->class) ? $this->addon->settings->class : '';
return '<div class="sppb-empty-space ' . $class . ' clearfix"></div>';
}
public function css() {
$addon_id = '#sppb-addon-' . $this->addon->id;
$gap = (isset($this->addon->settings->gap) && $this->addon->settings->gap) ? 'padding-bottom: ' . (int) $this->addon->settings->gap . 'px;': '';
if($gap) {
$css = $addon_id . ' .sppb-empty-space {';
$css .= $gap;
$css .= '}';
}
return $css;
}
}
| cchin013/uecsite2017 | components/com_sppagebuilder/addons/empty_space/site.php | PHP | gpl-2.0 | 916 |
<?
require_once("../../lib/bd/basedatosAdo.php");
class mysreportes
{
var $rep;
var $bd;
function mysreportes()
{
$this->rep="";
$this->bd=new basedatosAdo();
}
function sqlreporte()
{
$sql="select refcom as referencia, codpre as codigo_presupuestario, monimp as monto from cpimpcom order by refcom";
return $sql;
}
function getAncho($pos)
{
$anchos=array();
$anchos[0]=75;
$anchos[1]=60;
$anchos[2]=20;
$anchos[3]=30;
$anchos[4]=30;
$anchos[5]=30;
$anchos[6]=30;
/* $anchos[7]=30;
$anchos[8]=30;
$anchos[9]=30;
$anchos[10]=30;
$anchos[11]=30;*/
return $anchos[$pos];
}
function getAncho2($pos)
{
$anchos2=array();
$anchos2[0]=20;
$anchos2[1]=20;
$anchos2[2]=20;
$anchos2[3]=20;
$anchos2[4]=40;
$anchos2[5]=30;
$anchos2[6]=30;
$anchos2[7]=30;
$anchos2[8]=30;
$anchos2[9]=30;
$anchos2[10]=30;
$anchos2[11]=30;
return $anchos2[$pos];
}
}
?> | cidesa/siga-universitario | web/reportes/reportes/tesoreria/anchoTSRRELBAN.php | PHP | gpl-2.0 | 987 |
const express = require('express');
const path = require('path');
const compression = require('compression');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpack = require('webpack');
// Dev middleware
const addDevMiddlewares = (app, options) => {
const compiler = webpack(options);
const middleware = webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: options.output.publicPath,
silent: true,
});
app.use(middleware);
app.use(webpackHotMiddleware(compiler));
// Since webpackDevMiddleware uses memory-fs internally to store build
// artifacts, we use it instead
const fs = middleware.fileSystem;
app.get('*', (req, res) => {
const file = fs.readFileSync(path.join(compiler.outputPath, 'index.html'));
res.send(file.toString());
});
};
// Production middlewares
const addProdMiddlewares = (app, options) => {
// compression middleware compresses your server responses which makes them
// smaller (applies also to assets). You can read more about that technique
// and other good practices on official Express.js docs http://mxs.is/googmy
app.use(compression());
app.use(options.output.publicPath, express.static(options.output.path));
app.get('*', (req, res) => res.sendFile(path.join(options.output.path, 'index.html')));
};
/**
* Front-end middleware
*/
module.exports = (options) => {
const isProd = process.env.NODE_ENV === 'production';
const app = express();
if (isProd) {
addProdMiddlewares(app, options);
} else {
addDevMiddlewares(app, options);
}
return app;
};
| unicesi/pascani-library | web/dashboard/server/middlewares/frontendMiddleware.js | JavaScript | gpl-2.0 | 1,618 |
import unittest
from PyFoam.Basics.MatplotlibTimelines import MatplotlibTimelines
theSuite=unittest.TestSuite()
| Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam | unittests/Basics/test_MatplotlibTimelines.py | Python | gpl-2.0 | 114 |
/* $Id: VBoxUsbRt.cpp $ */
/** @file
* VBox USB R0 runtime
*/
/*
* Copyright (C) 2011 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "VBoxUsbCmn.h"
#include "../cmn/VBoxUsbIdc.h"
#include "../cmn/VBoxUsbTool.h"
#include <VBox/usblib-win.h>
#include <iprt/assert.h>
#include <VBox/log.h>
#define _USBD_
#define USBD_DEFAULT_PIPE_TRANSFER 0x00000008
#define VBOXUSB_MAGIC 0xABCF1423
typedef struct VBOXUSB_URB_CONTEXT
{
PURB pUrb;
PMDL pMdlBuf;
PVBOXUSBDEV_EXT pDevExt;
PVOID pOut;
ULONG ulTransferType;
ULONG ulMagic;
} VBOXUSB_URB_CONTEXT, * PVBOXUSB_URB_CONTEXT;
typedef struct VBOXUSB_SETUP
{
uint8_t bmRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} VBOXUSB_SETUP, *PVBOXUSB_SETUP;
static bool vboxUsbRtCtxSetOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj)
{
bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, pFObj, NULL);
if (bRc)
{
Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) acquired\n", pFObj));
}
else
{
Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) FAILED!!\n", pFObj));
}
return bRc;
}
static bool vboxUsbRtCtxReleaseOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj)
{
bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, NULL, pFObj);
if (bRc)
{
Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) released\n", pFObj));
}
else
{
Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) release: is NOT an owner\n", pFObj));
}
return bRc;
}
static bool vboxUsbRtCtxIsOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj)
{
PFILE_OBJECT pOwner = (PFILE_OBJECT)ASMAtomicReadPtr((void *volatile *)(&pDevExt->Rt.pOwner));
return pOwner == pFObj;
}
static NTSTATUS vboxUsbRtIdcSubmit(ULONG uCtl, void *pvBuffer)
{
/* we just reuse the standard usb tooling for simplicity here */
NTSTATUS Status = VBoxUsbToolIoInternalCtlSendSync(g_VBoxUsbGlobals.RtIdc.pDevice, uCtl, pvBuffer, NULL);
Assert(Status == STATUS_SUCCESS);
return Status;
}
static NTSTATUS vboxUsbRtIdcInit()
{
UNICODE_STRING UniName;
RtlInitUnicodeString(&UniName, USBMON_DEVICE_NAME_NT);
NTSTATUS Status = IoGetDeviceObjectPointer(&UniName, FILE_ALL_ACCESS, &g_VBoxUsbGlobals.RtIdc.pFile, &g_VBoxUsbGlobals.RtIdc.pDevice);
if (NT_SUCCESS(Status))
{
VBOXUSBIDC_VERSION Version;
vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION, &Version);
if (NT_SUCCESS(Status))
{
if (Version.u32Major == VBOXUSBIDC_VERSION_MAJOR
&& Version.u32Minor >= VBOXUSBIDC_VERSION_MINOR)
return STATUS_SUCCESS;
AssertFailed();
}
else
{
AssertFailed();
}
/* this will as well dereference the dev obj */
ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile);
}
else
{
AssertFailed();
}
memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc));
return Status;
}
static VOID vboxUsbRtIdcTerm()
{
Assert(g_VBoxUsbGlobals.RtIdc.pFile);
Assert(g_VBoxUsbGlobals.RtIdc.pDevice);
ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile);
memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc));
}
static NTSTATUS vboxUsbRtIdcReportDevStart(PDEVICE_OBJECT pPDO, HVBOXUSBIDCDEV *phDev)
{
VBOXUSBIDC_PROXY_STARTUP Start;
Start.u.pPDO = pPDO;
*phDev = NULL;
NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP, &Start);
Assert(Status == STATUS_SUCCESS);
if (!NT_SUCCESS(Status))
return Status;
*phDev = Start.u.hDev;
return STATUS_SUCCESS;
}
static NTSTATUS vboxUsbRtIdcReportDevStop(HVBOXUSBIDCDEV hDev)
{
VBOXUSBIDC_PROXY_TEARDOWN Stop;
Stop.hDev = hDev;
NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN, &Stop);
Assert(Status == STATUS_SUCCESS);
return Status;
}
DECLHIDDEN(NTSTATUS) vboxUsbRtGlobalsInit()
{
return vboxUsbRtIdcInit();
}
DECLHIDDEN(VOID) vboxUsbRtGlobalsTerm()
{
vboxUsbRtIdcTerm();
}
DECLHIDDEN(NTSTATUS) vboxUsbRtInit(PVBOXUSBDEV_EXT pDevExt)
{
RtlZeroMemory(&pDevExt->Rt, sizeof (pDevExt->Rt));
NTSTATUS Status = IoRegisterDeviceInterface(pDevExt->pPDO, &GUID_CLASS_VBOXUSB,
NULL, /* IN PUNICODE_STRING ReferenceString OPTIONAL */
&pDevExt->Rt.IfName);
Assert(Status == STATUS_SUCCESS);
if (NT_SUCCESS(Status))
{
Status = vboxUsbRtIdcReportDevStart(pDevExt->pPDO, &pDevExt->Rt.hMonDev);
Assert(Status == STATUS_SUCCESS);
if (NT_SUCCESS(Status))
{
Assert(pDevExt->Rt.hMonDev);
return STATUS_SUCCESS;
}
NTSTATUS tmpStatus = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE);
Assert(tmpStatus == STATUS_SUCCESS);
if (NT_SUCCESS(tmpStatus))
{
RtlFreeUnicodeString(&pDevExt->Rt.IfName);
}
}
return Status;
}
/**
* Free cached USB device/configuration descriptors
*
* @param pDevExt USB DevExt pointer
*/
static void vboxUsbRtFreeCachedDescriptors(PVBOXUSBDEV_EXT pDevExt)
{
if (pDevExt->Rt.devdescr)
{
vboxUsbMemFree(pDevExt->Rt.devdescr);
pDevExt->Rt.devdescr = NULL;
}
for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i)
{
if (pDevExt->Rt.cfgdescr[i])
{
vboxUsbMemFree(pDevExt->Rt.cfgdescr[i]);
pDevExt->Rt.cfgdescr[i] = NULL;
}
}
}
/**
* Free per-device interface info
*
* @param pDevExt USB DevExt pointer
* @param fAbortPipes If true, also abort any open pipes
*/
static void vboxUsbRtFreeInterfaces(PVBOXUSBDEV_EXT pDevExt, BOOLEAN fAbortPipes)
{
unsigned i;
unsigned j;
/*
* Free old interface info
*/
if (pDevExt->Rt.pVBIfaceInfo)
{
for (i=0;i<pDevExt->Rt.uNumInterfaces;i++)
{
if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo)
{
if (fAbortPipes)
{
for(j=0; j<pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++)
{
Log(("Aborting Pipe %d handle %x address %x\n", j,
pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle,
pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress));
VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle, FALSE);
}
}
vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo);
}
pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = NULL;
if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo)
vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo);
pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL;
}
vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo);
pDevExt->Rt.pVBIfaceInfo = NULL;
}
}
DECLHIDDEN(VOID) vboxUsbRtClear(PVBOXUSBDEV_EXT pDevExt)
{
vboxUsbRtFreeCachedDescriptors(pDevExt);
vboxUsbRtFreeInterfaces(pDevExt, FALSE);
}
DECLHIDDEN(NTSTATUS) vboxUsbRtRm(PVBOXUSBDEV_EXT pDevExt)
{
if (!pDevExt->Rt.IfName.Buffer)
return STATUS_SUCCESS;
NTSTATUS Status = vboxUsbRtIdcReportDevStop(pDevExt->Rt.hMonDev);
Assert(Status == STATUS_SUCCESS);
Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE);
Assert(Status == STATUS_SUCCESS);
if (NT_SUCCESS(Status))
{
RtlFreeUnicodeString(&pDevExt->Rt.IfName);
pDevExt->Rt.IfName.Buffer = NULL;
}
return Status;
}
DECLHIDDEN(NTSTATUS) vboxUsbRtStart(PVBOXUSBDEV_EXT pDevExt)
{
NTSTATUS Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, TRUE);
Assert(Status == STATUS_SUCCESS);
return Status;
}
static NTSTATUS vboxUsbRtCacheDescriptors(PVBOXUSBDEV_EXT pDevExt)
{
NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES;
// uint32_t uTotalLength;
// unsigned i;
/* Read device descriptor */
Assert(!pDevExt->Rt.devdescr);
pDevExt->Rt.devdescr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_DEVICE_DESCRIPTOR));
if (pDevExt->Rt.devdescr)
{
memset(pDevExt->Rt.devdescr, 0, sizeof (USB_DEVICE_DESCRIPTOR));
Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.devdescr, sizeof (USB_DEVICE_DESCRIPTOR), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT);
if (NT_SUCCESS(Status))
{
Assert(pDevExt->Rt.devdescr->bNumConfigurations > 0);
PUSB_CONFIGURATION_DESCRIPTOR pDr = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_CONFIGURATION_DESCRIPTOR));
Assert(pDr);
if (pDr)
{
UCHAR i = 0;
for (; i < pDevExt->Rt.devdescr->bNumConfigurations; ++i)
{
Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof (USB_CONFIGURATION_DESCRIPTOR), USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT);
if (!NT_SUCCESS(Status))
{
break;
}
USHORT uTotalLength = pDr->wTotalLength;
pDevExt->Rt.cfgdescr[i] = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(uTotalLength);
if (!pDevExt->Rt.cfgdescr[i])
{
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.cfgdescr[i], uTotalLength, USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT);
if (!NT_SUCCESS(Status))
{
break;
}
}
vboxUsbMemFree(pDr);
if (NT_SUCCESS(Status))
return Status;
/* recources will be freed in vboxUsbRtFreeCachedDescriptors below */
}
}
vboxUsbRtFreeCachedDescriptors(pDevExt);
}
/* shoud be only on fail here */
Assert(!NT_SUCCESS(Status));
return Status;
}
static NTSTATUS vboxUsbRtDispatchClaimDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_CLAIMDEV pDev = (PUSBSUP_CLAIMDEV)pIrp->AssociatedIrp.SystemBuffer;
ULONG cbOut = 0;
NTSTATUS Status = STATUS_SUCCESS;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if ( !pDev
|| pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pDev)
|| pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pDev))
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxSetOwner(pDevExt, pFObj))
{
AssertFailed();
pDev->fClaimed = false;
cbOut = sizeof (*pDev);
break;
}
vboxUsbRtFreeCachedDescriptors(pDevExt);
Status = vboxUsbRtCacheDescriptors(pDevExt);
if (NT_SUCCESS(Status))
{
pDev->fClaimed = true;
cbOut = sizeof (*pDev);
}
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, cbOut);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtDispatchReleaseDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
NTSTATUS Status= STATUS_SUCCESS;
if (vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
vboxUsbRtFreeCachedDescriptors(pDevExt);
bool bRc = vboxUsbRtCtxReleaseOwner(pDevExt, pFObj);
Assert(bRc);
}
else
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
}
VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0);
vboxUsbDdiStateRelease(pDevExt);
return STATUS_SUCCESS;
}
static NTSTATUS vboxUsbRtGetDeviceDescription(PVBOXUSBDEV_EXT pDevExt)
{
NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES;
PUSB_DEVICE_DESCRIPTOR pDr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAllocZ(sizeof (USB_DEVICE_DESCRIPTOR));
if (pDr)
{
Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof(*pDr), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT);
if (NT_SUCCESS(Status))
{
pDevExt->Rt.idVendor = pDr->idVendor;
pDevExt->Rt.idProduct = pDr->idProduct;
pDevExt->Rt.bcdDevice = pDr->bcdDevice;
pDevExt->Rt.szSerial[0] = 0;
if (pDr->iSerialNumber
#ifdef DEBUG
|| pDr->iProduct || pDr->iManufacturer
#endif
)
{
int langId;
Status = VBoxUsbToolGetLangID(pDevExt->pLowerDO, &langId, RT_INDEFINITE_WAIT);
if (NT_SUCCESS(Status))
{
Status = VBoxUsbToolGetStringDescriptorA(pDevExt->pLowerDO, pDevExt->Rt.szSerial, sizeof (pDevExt->Rt.szSerial), pDr->iSerialNumber, langId, RT_INDEFINITE_WAIT);
}
else
{
Status = STATUS_SUCCESS;
}
}
}
vboxUsbMemFree(pDr);
}
return Status;
}
static NTSTATUS vboxUsbRtDispatchGetDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PUSBSUP_GETDEV pDev = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status = STATUS_SUCCESS;
ULONG cbOut = 0;
/* don't check for owner since this request is allowed for non-owners as well */
if (pDev && pSl->Parameters.DeviceIoControl.InputBufferLength == sizeof (*pDev)
&& pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pDev))
{
Status = VBoxUsbToolGetDeviceSpeed(pDevExt->pLowerDO, &pDevExt->Rt.fIsHighSpeed);
if (NT_SUCCESS(Status))
{
pDev->hDevice = pDevExt->Rt.hMonDev;
pDev->fAttached = true;
pDev->fHiSpeed = pDevExt->Rt.fIsHighSpeed;
cbOut = sizeof (*pDev);
}
}
else
{
Status = STATUS_INVALID_PARAMETER;
}
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, cbOut);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtDispatchUsbReset(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_GETDEV pDev = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status = STATUS_SUCCESS;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
break;
}
if (pIrp->AssociatedIrp.SystemBuffer
|| pSl->Parameters.DeviceIoControl.InputBufferLength
|| pSl->Parameters.DeviceIoControl.OutputBufferLength)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = VBoxUsbToolIoInternalCtlSendSync(pDevExt->pLowerDO, IOCTL_INTERNAL_USB_RESET_PORT, NULL, NULL);
Assert(NT_SUCCESS(Status));
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static PUSB_CONFIGURATION_DESCRIPTOR vboxUsbRtFindConfigDesc(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration)
{
PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = NULL;
for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i)
{
if (pDevExt->Rt.cfgdescr[i])
{
if (pDevExt->Rt.cfgdescr[i]->bConfigurationValue == uConfiguration)
{
pCfgDr = pDevExt->Rt.cfgdescr[i];
break;
}
}
}
return pCfgDr;
}
static NTSTATUS vboxUsbRtSetConfig(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration)
{
PURB pUrb = NULL;
NTSTATUS Status = STATUS_SUCCESS;
uint32_t i;
if (!uConfiguration)
{
pUrb = VBoxUsbToolUrbAllocZ(URB_FUNCTION_SELECT_CONFIGURATION, sizeof (struct _URB_SELECT_CONFIGURATION));
if(!pUrb)
{
AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n"));
return STATUS_INSUFFICIENT_RESOURCES;
}
vboxUsbRtFreeInterfaces(pDevExt, TRUE);
pUrb->UrbSelectConfiguration.ConfigurationDescriptor = NULL;
Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT);
if(NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status))
{
pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle;
pDevExt->Rt.uConfigValue = uConfiguration;
}
else
{
AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
}
VBoxUsbToolUrbFree(pUrb);
return Status;
}
PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, uConfiguration);
if (!pCfgDr)
{
AssertMsgFailed((__FUNCTION__": VBoxUSBFindConfigDesc did not find cfg (%d)\n", uConfiguration));
return STATUS_INVALID_PARAMETER;
}
PUSBD_INTERFACE_LIST_ENTRY pIfLe = (PUSBD_INTERFACE_LIST_ENTRY)vboxUsbMemAllocZ((pCfgDr->bNumInterfaces + 1) * sizeof(USBD_INTERFACE_LIST_ENTRY));
if (!pIfLe)
{
AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ for pIfLe failed\n"));
return STATUS_INSUFFICIENT_RESOURCES;
}
for (i = 0; i < pCfgDr->bNumInterfaces; i++)
{
pIfLe[i].InterfaceDescriptor = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, i, 0, -1, -1, -1);
if (!pIfLe[i].InterfaceDescriptor)
{
AssertMsgFailed((__FUNCTION__": interface %d not found\n", i));
Status = STATUS_INVALID_PARAMETER;
break;
}
}
if (NT_SUCCESS(Status))
{
pUrb = USBD_CreateConfigurationRequestEx(pCfgDr, pIfLe);
if (pUrb)
{
Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT);
if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status))
{
vboxUsbRtFreeInterfaces(pDevExt, FALSE);
pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle;
pDevExt->Rt.uConfigValue = uConfiguration;
pDevExt->Rt.uNumInterfaces = pCfgDr->bNumInterfaces;
pDevExt->Rt.pVBIfaceInfo = (VBOXUSB_IFACE_INFO*)vboxUsbMemAllocZ(pDevExt->Rt.uNumInterfaces * sizeof (VBOXUSB_IFACE_INFO));
if (pDevExt->Rt.pVBIfaceInfo)
{
Assert(NT_SUCCESS(Status));
for (i = 0; i < pDevExt->Rt.uNumInterfaces; i++)
{
uint32_t uTotalIfaceInfoLength = sizeof (struct _URB_SELECT_INTERFACE) + ((pIfLe[i].Interface->NumberOfPipes > 0) ? (pIfLe[i].Interface->NumberOfPipes - 1) : 0) * sizeof(USBD_PIPE_INFORMATION);
pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength);
if (!pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo)
{
AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n"));
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
if (pIfLe[i].Interface->NumberOfPipes > 0)
{
pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = (VBOXUSB_PIPE_INFO *)vboxUsbMemAlloc(pIfLe[i].Interface->NumberOfPipes * sizeof(VBOXUSB_PIPE_INFO));
if (!pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo)
{
AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n"));
Status = STATUS_NO_MEMORY;
break;
}
}
else
{
pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL;
}
*pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = *pIfLe[i].Interface;
for (ULONG j = 0; j < pIfLe[i].Interface->NumberOfPipes; j++)
{
pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j] = pIfLe[i].Interface->Pipes[j];
pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress = pIfLe[i].Interface->Pipes[j].EndpointAddress;
pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].NextScheduledFrame = 0;
}
}
// if (NT_SUCCESS(Status))
// {
//
// }
}
else
{
AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ failed\n"));
Status = STATUS_NO_MEMORY;
}
}
else
{
AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
}
ExFreePool(pUrb);
}
else
{
AssertMsgFailed((__FUNCTION__": USBD_CreateConfigurationRequestEx failed\n"));
Status = STATUS_INSUFFICIENT_RESOURCES;
}
}
vboxUsbMemFree(pIfLe);
return Status;
}
static NTSTATUS vboxUsbRtDispatchUsbSetConfig(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_SET_CONFIG pCfg = (PUSBSUP_SET_CONFIG)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status = STATUS_SUCCESS;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
break;
}
if ( !pCfg
|| pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCfg)
|| pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
{
AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = vboxUsbRtSetConfig(pDevExt, pCfg->bConfigurationValue);
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtSetInterface(PVBOXUSBDEV_EXT pDevExt, uint32_t InterfaceNumber, int AlternateSetting)
{
if (!pDevExt->Rt.uConfigValue)
{
AssertMsgFailed((__FUNCTION__": Can't select an interface without an active configuration\n"));
return STATUS_INVALID_PARAMETER;
}
if (InterfaceNumber >= pDevExt->Rt.uNumInterfaces)
{
AssertMsgFailed((__FUNCTION__": InterfaceNumber %d too high!!\n", InterfaceNumber));
return STATUS_INVALID_PARAMETER;
}
PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, pDevExt->Rt.uConfigValue);
if (!pCfgDr)
{
AssertMsgFailed((__FUNCTION__": configuration %d not found!!\n", pDevExt->Rt.uConfigValue));
return STATUS_INVALID_PARAMETER;
}
PUSB_INTERFACE_DESCRIPTOR pIfDr = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, InterfaceNumber, AlternateSetting, -1, -1, -1);
if (!pIfDr)
{
AssertMsgFailed((__FUNCTION__": invalid interface %d or alternate setting %d\n", InterfaceNumber, AlternateSetting));
return STATUS_UNSUCCESSFUL;
}
USHORT uUrbSize = GET_SELECT_INTERFACE_REQUEST_SIZE(pIfDr->bNumEndpoints);
ULONG uTotalIfaceInfoLength = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints);
NTSTATUS Status = STATUS_SUCCESS;
PURB pUrb = VBoxUsbToolUrbAllocZ(0, uUrbSize);
if (!pUrb)
{
AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n"));
return STATUS_NO_MEMORY;
}
/*
* Free old interface and pipe info, allocate new again
*/
if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo)
{
/* Clear pipes associated with the interface, else Windows may hang. */
for(ULONG i = 0; i < pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->NumberOfPipes; i++)
{
VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i].PipeHandle, FALSE);
}
vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo);
}
if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo)
{
vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo);
}
pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength);
if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo)
{
if (pIfDr->bNumEndpoints > 0)
{
pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = (VBOXUSB_PIPE_INFO*)vboxUsbMemAlloc(pIfDr->bNumEndpoints * sizeof(VBOXUSB_PIPE_INFO));
if (!pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo)
{
AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n"));
Status = STATUS_NO_MEMORY;
}
}
else
{
pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = NULL;
}
if (NT_SUCCESS(Status))
{
UsbBuildSelectInterfaceRequest(pUrb, uUrbSize, pDevExt->Rt.hConfiguration, InterfaceNumber, AlternateSetting);
pUrb->UrbSelectInterface.Interface.Length = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints);
Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT);
if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status))
{
USBD_INTERFACE_INFORMATION *pIfInfo = &pUrb->UrbSelectInterface.Interface;
memcpy(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo, pIfInfo, GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints));
Assert(pIfInfo->NumberOfPipes == pIfDr->bNumEndpoints);
for(ULONG i = 0; i < pIfInfo->NumberOfPipes; i++)
{
pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i] = pIfInfo->Pipes[i];
pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].EndpointAddress = pIfInfo->Pipes[i].EndpointAddress;
pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].NextScheduledFrame = 0;
}
}
else
{
AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x) usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
}
}
}
else
{
AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n"));
Status = STATUS_NO_MEMORY;
}
VBoxUsbToolUrbFree(pUrb);
return Status;
}
static NTSTATUS vboxUsbRtDispatchUsbSelectInterface(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_SELECT_INTERFACE pIf = (PUSBSUP_SELECT_INTERFACE)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
break;
}
if ( !pIf
|| pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pIf)
|| pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
{
AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = vboxUsbRtSetInterface(pDevExt, pIf->bInterfaceNumber, pIf->bAlternateSetting);
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static HANDLE vboxUsbRtGetPipeHandle(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress)
{
for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++)
{
for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++)
{
/* Note that bit 7 determines pipe direction, but is still significant
* because endpoints may be numbered like 0x01, 0x81, 0x02, 0x82 etc.
*/
if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress == EndPointAddress)
return pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle;
}
}
return 0;
}
static VBOXUSB_PIPE_INFO* vboxUsbRtGetPipeInfo(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress)
{
for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++)
{
for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++)
{
if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress == EndPointAddress)
return &pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j];
}
}
return NULL;
}
static NTSTATUS vboxUsbRtClearEndpoint(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress, bool fReset)
{
NTSTATUS Status = VBoxUsbToolPipeClear(pDevExt->pLowerDO, vboxUsbRtGetPipeHandle(pDevExt, EndPointAddress), fReset);
if (!NT_SUCCESS(Status))
{
AssertMsgFailed((__FUNCTION__": VBoxUsbToolPipeClear failed Status (0x%x)\n", Status));
}
return Status;
}
static NTSTATUS vboxUsbRtDispatchUsbClearEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
break;
}
if ( !pCe
|| pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe)
|| pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
{
AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, TRUE);
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtDispatchUsbAbortEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
break;
}
if ( !pCe
|| pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe)
|| pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
{
AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
Status = STATUS_INVALID_PARAMETER;
break;
}
Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, FALSE);
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtUrbSendCompletion(PDEVICE_OBJECT pDevObj, IRP *pIrp, void *pvContext)
{
if (!pvContext)
{
AssertMsgFailed((__FUNCTION__": context is NULL\n"));
pIrp->IoStatus.Information = 0;
return STATUS_CONTINUE_COMPLETION;
}
PVBOXUSB_URB_CONTEXT pContext = (PVBOXUSB_URB_CONTEXT)pvContext;
if (pContext->ulMagic != VBOXUSB_MAGIC)
{
AssertMsgFailed((__FUNCTION__": Invalid context magic\n"));
pIrp->IoStatus.Information = 0;
return STATUS_CONTINUE_COMPLETION;
}
PURB pUrb = pContext->pUrb;
PMDL pMdlBuf = pContext->pMdlBuf;
PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pContext->pOut;
PVBOXUSBDEV_EXT pDevExt = pContext->pDevExt;
if (!pUrb || !pMdlBuf || !pUrbInfo | !pDevExt)
{
AssertMsgFailed((__FUNCTION__": Invalid args\n"));
if (pDevExt)
vboxUsbDdiStateRelease(pDevExt);
pIrp->IoStatus.Information = 0;
return STATUS_CONTINUE_COMPLETION;
}
NTSTATUS Status = pIrp->IoStatus.Status;
if (Status == STATUS_SUCCESS)
{
switch(pUrb->UrbHeader.Status)
{
case USBD_STATUS_CRC:
pUrbInfo->error = USBSUP_XFER_CRC;
break;
case USBD_STATUS_SUCCESS:
pUrbInfo->error = USBSUP_XFER_OK;
break;
case USBD_STATUS_STALL_PID:
pUrbInfo->error = USBSUP_XFER_STALL;
break;
case USBD_STATUS_INVALID_URB_FUNCTION:
case USBD_STATUS_INVALID_PARAMETER:
AssertMsgFailed((__FUNCTION__": sw error, urb Status (0x%x)\n", pUrb->UrbHeader.Status));
case USBD_STATUS_DEV_NOT_RESPONDING:
default:
pUrbInfo->error = USBSUP_XFER_DNR;
break;
}
switch(pContext->ulTransferType)
{
case USBSUP_TRANSFER_TYPE_CTRL:
case USBSUP_TRANSFER_TYPE_MSG:
pUrbInfo->len = pUrb->UrbControlTransfer.TransferBufferLength;
if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_MSG)
{
/* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special
* the first 8 bytes of the buffer is the setup packet so the real
* data length is therefore urb->len - 8
*/
pUrbInfo->len += sizeof (pUrb->UrbControlTransfer.SetupPacket);
}
break;
case USBSUP_TRANSFER_TYPE_ISOC:
pUrbInfo->len = pUrb->UrbIsochronousTransfer.TransferBufferLength;
break;
case USBSUP_TRANSFER_TYPE_BULK:
case USBSUP_TRANSFER_TYPE_INTR:
if (pUrbInfo->dir == USBSUP_DIRECTION_IN && pUrbInfo->error == USBSUP_XFER_OK
&& !(pUrbInfo->flags & USBSUP_FLAG_SHORT_OK)
&& pUrbInfo->len > pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength
)
{
/* If we don't use the USBD_SHORT_TRANSFER_OK flag, the returned buffer lengths are
* wrong for short transfers (always a multiple of max packet size?). So we just figure
* out if this was a data underrun on our own.
*/
pUrbInfo->error = USBSUP_XFER_UNDERRUN;
}
pUrbInfo->len = pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength;
break;
default:
break;
}
}
else
{
pUrbInfo->len = 0;
Log((__FUNCTION__": URB failed Status (0x%x) urb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
#ifdef DEBUG
switch(pContext->ulTransferType)
{
case USBSUP_TRANSFER_TYPE_CTRL:
case USBSUP_TRANSFER_TYPE_MSG:
LogRel(("Ctrl/Msg length=%d\n", pUrb->UrbControlTransfer.TransferBufferLength));
break;
case USBSUP_TRANSFER_TYPE_ISOC:
LogRel(("ISOC length=%d\n", pUrb->UrbIsochronousTransfer.TransferBufferLength));
break;
case USBSUP_TRANSFER_TYPE_BULK:
case USBSUP_TRANSFER_TYPE_INTR:
LogRel(("BULK/INTR length=%d\n", pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength));
break;
}
#endif
switch(pUrb->UrbHeader.Status)
{
case USBD_STATUS_CRC:
pUrbInfo->error = USBSUP_XFER_CRC;
Status = STATUS_SUCCESS;
break;
case USBD_STATUS_STALL_PID:
pUrbInfo->error = USBSUP_XFER_STALL;
Status = STATUS_SUCCESS;
break;
case USBD_STATUS_DEV_NOT_RESPONDING:
pUrbInfo->error = USBSUP_XFER_DNR;
Status = STATUS_SUCCESS;
break;
case ((USBD_STATUS)0xC0010000L): // USBD_STATUS_CANCELED - too bad usbdi.h and usb.h aren't consistent!
// TODO: What the heck are we really supposed to do here?
pUrbInfo->error = USBSUP_XFER_STALL;
Status = STATUS_SUCCESS;
break;
case USBD_STATUS_BAD_START_FRAME: // This one really shouldn't happen
case USBD_STATUS_ISOCH_REQUEST_FAILED:
pUrbInfo->error = USBSUP_XFER_NAC;
Status = STATUS_SUCCESS;
break;
default:
AssertMsgFailed((__FUNCTION__": err Status (0x%x) (0x%x)\n", Status, pUrb->UrbHeader.Status));
pUrbInfo->error = USBSUP_XFER_DNR;
Status = STATUS_SUCCESS;
break;
}
}
// For isochronous transfers, always update the individual packets
if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_ISOC)
{
Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets);
for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i)
{
Assert(pUrbInfo->aIsoPkts[i].off == pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset);
pUrbInfo->aIsoPkts[i].cb = (uint16_t)pUrb->UrbIsochronousTransfer.IsoPacket[i].Length;
switch (pUrb->UrbIsochronousTransfer.IsoPacket[i].Status)
{
case USBD_STATUS_SUCCESS:
pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_OK;
break;
case USBD_STATUS_NOT_ACCESSED:
pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_NAC;
break;
default:
pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_STALL;
break;
}
}
}
MmUnlockPages(pMdlBuf);
IoFreeMdl(pMdlBuf);
vboxUsbMemFree(pContext);
vboxUsbDdiStateRelease(pDevExt);
Assert(pIrp->IoStatus.Status != STATUS_IO_TIMEOUT);
pIrp->IoStatus.Information = sizeof(*pUrbInfo);
pIrp->IoStatus.Status = Status;
return STATUS_CONTINUE_COMPLETION;
}
static NTSTATUS vboxUsbRtUrbSend(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp, PUSBSUP_URB pUrbInfo)
{
NTSTATUS Status = STATUS_SUCCESS;
PVBOXUSB_URB_CONTEXT pContext = NULL;
PMDL pMdlBuf = NULL;
ULONG cbUrb;
Assert(pUrbInfo);
if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_ISOC)
{
Assert(pUrbInfo->numIsoPkts <= 8);
cbUrb = GET_ISO_URB_SIZE(pUrbInfo->numIsoPkts);
}
else
cbUrb = sizeof (URB);
do
{
pContext = (PVBOXUSB_URB_CONTEXT)vboxUsbMemAllocZ(cbUrb + sizeof (VBOXUSB_URB_CONTEXT));
if (!pContext)
{
AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n"));
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
PURB pUrb = (PURB)(pContext + 1);
HANDLE hPipe = NULL;
if (pUrbInfo->ep)
{
hPipe = vboxUsbRtGetPipeHandle(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00));
if (!hPipe)
{
AssertMsgFailed((__FUNCTION__": vboxUsbRtGetPipeHandle failed for endpoint (0x%x)\n", pUrbInfo->ep));
Status = STATUS_INVALID_PARAMETER;
break;
}
}
pMdlBuf = IoAllocateMdl(pUrbInfo->buf, (ULONG)pUrbInfo->len, FALSE, FALSE, NULL);
if (!pMdlBuf)
{
AssertMsgFailed((__FUNCTION__": IoAllocateMdl failed for buffer (0x%p) length (%d)\n", pUrbInfo->buf, pUrbInfo->len));
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
__try
{
MmProbeAndLockPages(pMdlBuf, KernelMode, IoModifyAccess);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
Status = GetExceptionCode();
IoFreeMdl(pMdlBuf);
pMdlBuf = NULL;
AssertMsgFailed((__FUNCTION__": Exception Code (0x%x)\n", Status));
break;
}
/* For some reason, passing a MDL in the URB does not work reliably. Notably
* the iPhone when used with iTunes fails.
*/
PVOID pBuffer = MmGetSystemAddressForMdlSafe(pMdlBuf, NormalPagePriority);
if (!pBuffer)
{
AssertMsgFailed((__FUNCTION__": MmGetSystemAddressForMdlSafe failed\n"));
Status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
switch (pUrbInfo->type)
{
case USBSUP_TRANSFER_TYPE_CTRL:
case USBSUP_TRANSFER_TYPE_MSG:
{
pUrb->UrbHeader.Function = URB_FUNCTION_CONTROL_TRANSFER;
pUrb->UrbHeader.Length = sizeof (struct _URB_CONTROL_TRANSFER);
pUrb->UrbControlTransfer.PipeHandle = hPipe;
pUrb->UrbControlTransfer.TransferBufferLength = (ULONG)pUrbInfo->len;
pUrb->UrbControlTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT);
pUrb->UrbControlTransfer.UrbLink = 0;
if (!hPipe)
pUrb->UrbControlTransfer.TransferFlags |= USBD_DEFAULT_PIPE_TRANSFER;
if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_MSG)
{
/* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special
* the first 8 bytes of the buffer is the setup packet so the real
* data length is therefore pUrb->len - 8
*/
PVBOXUSB_SETUP pSetup = (PVBOXUSB_SETUP)pUrb->UrbControlTransfer.SetupPacket;
memcpy(pUrb->UrbControlTransfer.SetupPacket, pBuffer, min(sizeof (pUrb->UrbControlTransfer.SetupPacket), pUrbInfo->len));
if (pUrb->UrbControlTransfer.TransferBufferLength <= sizeof (pUrb->UrbControlTransfer.SetupPacket))
pUrb->UrbControlTransfer.TransferBufferLength = 0;
else
pUrb->UrbControlTransfer.TransferBufferLength -= sizeof (pUrb->UrbControlTransfer.SetupPacket);
pUrb->UrbControlTransfer.TransferBuffer = (uint8_t *)pBuffer + sizeof(pUrb->UrbControlTransfer.SetupPacket);
pUrb->UrbControlTransfer.TransferBufferMDL = 0;
pUrb->UrbControlTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK;
}
else
{
pUrb->UrbControlTransfer.TransferBuffer = 0;
pUrb->UrbControlTransfer.TransferBufferMDL = pMdlBuf;
}
break;
}
case USBSUP_TRANSFER_TYPE_ISOC:
{
Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK);
Assert(hPipe);
VBOXUSB_PIPE_INFO *pPipeInfo = vboxUsbRtGetPipeInfo(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00));
if (pPipeInfo == NULL)
{
/* Can happen if the isoc request comes in too early or late. */
AssertMsgFailed((__FUNCTION__": pPipeInfo not found\n"));
Status = STATUS_INVALID_PARAMETER;
break;
}
pUrb->UrbHeader.Function = URB_FUNCTION_ISOCH_TRANSFER;
pUrb->UrbHeader.Length = (USHORT)cbUrb;
pUrb->UrbIsochronousTransfer.PipeHandle = hPipe;
pUrb->UrbIsochronousTransfer.TransferBufferLength = (ULONG)pUrbInfo->len;
pUrb->UrbIsochronousTransfer.TransferBufferMDL = 0;
pUrb->UrbIsochronousTransfer.TransferBuffer = pBuffer;
pUrb->UrbIsochronousTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT);
pUrb->UrbIsochronousTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK; // May be implied already
pUrb->UrbIsochronousTransfer.NumberOfPackets = pUrbInfo->numIsoPkts;
pUrb->UrbIsochronousTransfer.ErrorCount = 0;
pUrb->UrbIsochronousTransfer.UrbLink = 0;
Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets);
for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i)
{
pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset = pUrbInfo->aIsoPkts[i].off;
pUrb->UrbIsochronousTransfer.IsoPacket[i].Length = pUrbInfo->aIsoPkts[i].cb;
}
/* We have to schedule the URBs ourselves. There is an ASAP flag but
* that can only be reliably used after pipe creation/reset, ie. it's
* almost completely useless.
*/
ULONG iFrame, iStartFrame;
VBoxUsbToolCurrentFrame(pDevExt->pLowerDO, pIrp, &iFrame);
iFrame += 2;
iStartFrame = pPipeInfo->NextScheduledFrame;
if ((iFrame < iStartFrame) || (iStartFrame > iFrame + 512))
iFrame = iStartFrame;
pPipeInfo->NextScheduledFrame = iFrame + pUrbInfo->numIsoPkts;
pUrb->UrbIsochronousTransfer.StartFrame = iFrame;
break;
}
case USBSUP_TRANSFER_TYPE_BULK:
case USBSUP_TRANSFER_TYPE_INTR:
{
Assert(pUrbInfo->dir != USBSUP_DIRECTION_SETUP);
Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK);
Assert(hPipe);
pUrb->UrbHeader.Function = URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER;
pUrb->UrbHeader.Length = sizeof (struct _URB_BULK_OR_INTERRUPT_TRANSFER);
pUrb->UrbBulkOrInterruptTransfer.PipeHandle = hPipe;
pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength = (ULONG)pUrbInfo->len;
pUrb->UrbBulkOrInterruptTransfer.TransferBufferMDL = 0;
pUrb->UrbBulkOrInterruptTransfer.TransferBuffer = pBuffer;
pUrb->UrbBulkOrInterruptTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT);
if (pUrb->UrbBulkOrInterruptTransfer.TransferFlags & USBD_TRANSFER_DIRECTION_IN)
pUrb->UrbBulkOrInterruptTransfer.TransferFlags |= (USBD_SHORT_TRANSFER_OK);
pUrb->UrbBulkOrInterruptTransfer.UrbLink = 0;
break;
}
default:
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
}
if (!NT_SUCCESS(Status))
{
break;
}
pContext->pDevExt = pDevExt;
pContext->pMdlBuf = pMdlBuf;
pContext->pUrb = pUrb;
pContext->pOut = pUrbInfo;
pContext->ulTransferType = pUrbInfo->type;
pContext->ulMagic = VBOXUSB_MAGIC;
PIO_STACK_LOCATION pSl = IoGetNextIrpStackLocation(pIrp);
pSl->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
pSl->Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB;
pSl->Parameters.Others.Argument1 = pUrb;
pSl->Parameters.Others.Argument2 = NULL;
IoSetCompletionRoutine(pIrp, vboxUsbRtUrbSendCompletion, pContext, TRUE, TRUE, TRUE);
IoMarkIrpPending(pIrp);
Status = IoCallDriver(pDevExt->pLowerDO, pIrp);
AssertMsg(NT_SUCCESS(Status), (__FUNCTION__": IoCallDriver failed Status (0x%x)\n", Status));
return STATUS_PENDING;
} while (0);
Assert(!NT_SUCCESS(Status));
if (pMdlBuf)
{
MmUnlockPages(pMdlBuf);
IoFreeMdl(pMdlBuf);
}
if (pContext)
vboxUsbMemFree(pContext);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtDispatchSendUrb(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status;
do
{
if (!pFObj)
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
{
AssertFailed();
Status = STATUS_ACCESS_DENIED;
break;
}
if ( !pUrbInfo
|| pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pUrbInfo)
|| pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pUrbInfo))
{
AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
Status = STATUS_INVALID_PARAMETER;
break;
}
return vboxUsbRtUrbSend(pDevExt, pIrp, pUrbInfo);
} while (0);
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, 0);
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtDispatchIsOperational(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0);
vboxUsbDdiStateRelease(pDevExt);
return STATUS_SUCCESS;
}
static NTSTATUS vboxUsbRtDispatchGetVersion(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PUSBSUP_VERSION pVer= (PUSBSUP_VERSION)pIrp->AssociatedIrp.SystemBuffer;
NTSTATUS Status = STATUS_SUCCESS;
if (pVer && pSl->Parameters.DeviceIoControl.InputBufferLength == 0
&& pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pVer))
{
pVer->u32Major = USBDRV_MAJOR_VERSION;
pVer->u32Minor = USBDRV_MINOR_VERSION;
}
else
{
AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
Status = STATUS_INVALID_PARAMETER;
}
Assert(Status != STATUS_PENDING);
VBoxDrvToolIoComplete(pIrp, Status, sizeof (*pVer));
vboxUsbDdiStateRelease(pDevExt);
return Status;
}
static NTSTATUS vboxUsbRtDispatchDefault(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
VBoxDrvToolIoComplete(pIrp, STATUS_INVALID_DEVICE_REQUEST, 0);
vboxUsbDdiStateRelease(pDevExt);
return STATUS_INVALID_DEVICE_REQUEST;
}
DECLHIDDEN(NTSTATUS) vboxUsbRtCreate(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
if (!pFObj)
{
AssertFailed();
return STATUS_INVALID_PARAMETER;
}
return STATUS_SUCCESS;
}
DECLHIDDEN(NTSTATUS) vboxUsbRtClose(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFObj = pSl->FileObject;
Assert(pFObj);
vboxUsbRtCtxReleaseOwner(pDevExt, pFObj);
return STATUS_SUCCESS;
}
DECLHIDDEN(NTSTATUS) vboxUsbRtDispatch(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
switch (pSl->Parameters.DeviceIoControl.IoControlCode)
{
case SUPUSB_IOCTL_USB_CLAIM_DEVICE:
{
return vboxUsbRtDispatchClaimDevice(pDevExt, pIrp);
}
case SUPUSB_IOCTL_USB_RELEASE_DEVICE:
{
return vboxUsbRtDispatchReleaseDevice(pDevExt, pIrp);
}
case SUPUSB_IOCTL_GET_DEVICE:
{
return vboxUsbRtDispatchGetDevice(pDevExt, pIrp);
}
case SUPUSB_IOCTL_USB_RESET:
{
return vboxUsbRtDispatchUsbReset(pDevExt, pIrp);
}
case SUPUSB_IOCTL_USB_SET_CONFIG:
{
return vboxUsbRtDispatchUsbSetConfig(pDevExt, pIrp);
}
case SUPUSB_IOCTL_USB_SELECT_INTERFACE:
{
return vboxUsbRtDispatchUsbSelectInterface(pDevExt, pIrp);
}
case SUPUSB_IOCTL_USB_CLEAR_ENDPOINT:
{
return vboxUsbRtDispatchUsbClearEndpoint(pDevExt, pIrp);
}
case SUPUSB_IOCTL_USB_ABORT_ENDPOINT:
{
return vboxUsbRtDispatchUsbAbortEndpoint(pDevExt, pIrp);
}
case SUPUSB_IOCTL_SEND_URB:
{
return vboxUsbRtDispatchSendUrb(pDevExt, pIrp);
}
case SUPUSB_IOCTL_IS_OPERATIONAL:
{
return vboxUsbRtDispatchIsOperational(pDevExt, pIrp);
}
case SUPUSB_IOCTL_GET_VERSION:
{
return vboxUsbRtDispatchGetVersion(pDevExt, pIrp);
}
default:
{
return vboxUsbRtDispatchDefault(pDevExt, pIrp);
}
}
}
| evanphx/yoke | src/VBox/HostDrivers/VBoxUSB/win/dev/VBoxUsbRt.cpp | C++ | gpl-2.0 | 55,450 |
//-----------------------------------------------------------------------------
//
// Vampire - A code for atomistic simulation of magnetic materials
//
// Copyright (C) 2009-2012 R.F.L.Evans
//
// Email:richard.evans@york.ac.uk
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
//
// ----------------------------------------------------------------------------
//
// Headers
#include "errors.hpp"
#include "demag.hpp"
#include "voronoi.hpp"
#include "material.hpp"
#include "sim.hpp"
#include "random.hpp"
#include "vio.hpp"
#include "vmath.hpp"
#include "vmpi.hpp"
#include <cmath>
#include <iostream>
#include <sstream>
//==========================================================
// Namespace material_parameters
//==========================================================
namespace mp{
//----------------------------------
// Material Container
//----------------------------------
//const int max_materials=100;
int num_materials=1;
std::vector <materials_t> material(1);
//----------------------------------
//Input Integration parameters
//----------------------------------
double dt_SI;
double gamma_SI = 1.76E11;
//----------------------------------
//Derived Integration parameters
//----------------------------------
double dt;
double half_dt;
// Unrolled material parameters for speed
std::vector <double> MaterialMuSSIArray(0);
std::vector <zkval_t> MaterialScalarAnisotropyArray(0);
std::vector <zkten_t> MaterialTensorAnisotropyArray(0);
std::vector <double> material_second_order_anisotropy_constant_array(0);
std::vector <double> material_sixth_order_anisotropy_constant_array(0);
std::vector <double> material_spherical_harmonic_constants_array(0);
std::vector <double> MaterialCubicAnisotropyArray(0);
///
/// @brief Function to initialise program variables prior to system creation.
///
/// @section License
/// Use of this code, either in source or compiled form, is subject to license from the authors.
/// Copyright \htmlonly © \endhtmlonly Richard Evans, 2009-2010. All Rights Reserved.
///
/// @section Information
/// @author Richard Evans, rfle500@york.ac.uk
/// @version 1.0
/// @date 19/01/2010
///
/// @param[in] infile Main input file name for system initialisation
/// @return EXIT_SUCCESS
///
/// @internal
/// Created: 19/01/2010
/// Revision: ---
///=====================================================================================
///
int initialise(std::string const infile){
//----------------------------------------------------------
// check calling of routine if error checking is activated
//----------------------------------------------------------
if(err::check==true){std::cout << "initialise_variables has been called" << std::endl;}
if(vmpi::my_rank==0){
std::cout << "================================================================================" << std::endl;
std::cout << "Initialising system variables" << std::endl;
}
// Setup default system settings
mp::default_system();
// Read values from input files
int iostat = vin::read(infile);
if(iostat==EXIT_FAILURE){
terminaltextcolor(RED);
std::cerr << "Error - input file \'" << infile << "\' not found, exiting" << std::endl;
terminaltextcolor(WHITE);
err::vexit();
}
// Print out material properties
//mp::material[0].print();
// Check for keyword parameter overide
if(cs::single_spin==true){
mp::single_spin_system();
}
// Set derived system parameters
mp::set_derived_parameters();
// Return
return EXIT_SUCCESS;
}
int default_system(){
// Initialise system creation flags to zero
for (int i=0;i<10;i++){
cs::system_creation_flags[i] = 0;
sim::hamiltonian_simulation_flags[i] = 0;
}
// Set system dimensions !Angstroms
cs::unit_cell_size[0] = 3.0;
cs::unit_cell_size[1] = 3.0;
cs::unit_cell_size[2] = 3.0;
cs::system_dimensions[0] = 100.0;
cs::system_dimensions[1] = 100.0;
cs::system_dimensions[2] = 100.0;
cs::particle_scale = 50.0;
cs::particle_spacing = 10.0;
cs::particle_creation_parity=0;
cs::crystal_structure = "sc";
// Voronoi Variables
create_voronoi::voronoi_sd=0.1;
create_voronoi::parity=0;
// Setup Hamiltonian Flags
sim::hamiltonian_simulation_flags[0] = 1; /// Exchange
sim::hamiltonian_simulation_flags[1] = 1; /// Anisotropy
sim::hamiltonian_simulation_flags[2] = 1; /// Applied
sim::hamiltonian_simulation_flags[3] = 1; /// Thermal
sim::hamiltonian_simulation_flags[4] = 0; /// Dipolar
//Integration parameters
dt_SI = 1.0e-15; // seconds
dt = dt_SI*mp::gamma_SI; // Must be set before Hth
half_dt = 0.5*dt;
//------------------------------------------------------------------------------
// Material Definitions
//------------------------------------------------------------------------------
num_materials=1;
material.resize(num_materials);
//-------------------------------------------------------
// Material 0
//-------------------------------------------------------
material[0].name="Co";
material[0].alpha=0.1;
material[0].Jij_matrix_SI[0]=-11.2e-21;
material[0].mu_s_SI=1.5*9.27400915e-24;
material[0].Ku1_SI=-4.644e-24;
material[0].gamma_rel=1.0;
material[0].element="Ag ";
// Disable Error Checking
err::check=false;
// Initialise random number generator
mtrandom::grnd.seed(2106975519);
return EXIT_SUCCESS;
}
int single_spin_system(){
// Reset system creation flags to zero
for (int i=0;i<10;i++){
cs::system_creation_flags[i] = 0;
}
// Set system dimensions !Angstroms
cs::unit_cell_size[0] = 3.0;
cs::unit_cell_size[1] = 3.0;
cs::unit_cell_size[2] = 3.0;
cs::system_dimensions[0] = 2.0;
cs::system_dimensions[1] = 2.0;
cs::system_dimensions[2] = 2.0;
cs::particle_scale = 50.0;
cs::particle_spacing = 10.0;
cs::particle_creation_parity=0;
cs::crystal_structure = "sc";
// Turn off multi-spin Flags
sim::hamiltonian_simulation_flags[0] = 0; /// Exchange
sim::hamiltonian_simulation_flags[4] = 0; /// Dipolar
// MPI Mode (Homogeneous execution)
//vmpi::mpi_mode=0;
//mpi_create_variables::mpi_interaction_range=2; // Unit cells
//mpi_create_variables::mpi_comms_identify=false;
return EXIT_SUCCESS;
}
// Simple function to check for valid input for hysteresis loop parameters
void check_hysteresis_loop_parameters(){
// Only applies to hysteresis loop programs, all others return
if(sim::program!=12) return;
double min=sim::Hmin;
double max=sim::Hmax;
double inc=sim::Hinc;
// + + +
if(min>=0 && max>=0 && inc>0){
if(max<min){
if(vmpi::my_rank==0){
terminaltextcolor(RED);
std::cout << "Error in hysteresis-loop parameters:" << std::endl;
std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl;
std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl;
std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl;
std::cout << "Minimum and maximum fields are both positive, but minimum > maximum with a positive increment, causing an infinite loop. Exiting." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl;
zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl;
zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl;
zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl;
zlog << zTs() << "Minimum and maximum fields are both positive, but minimum > maximum with a positive increment, causing an infinite loop. Exiting." << std::endl;
err::vexit();
}
}
}
// + + -
else if(min>=0 && max>=0 && inc<0){
if(max>min){
if(vmpi::my_rank==0){
terminaltextcolor(RED);
std::cout << "Error in hysteresis-loop parameters:" << std::endl;
std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl;
std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl;
std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl;
std::cout << "Minimum and maximum fields are both positive, but maximum > minimum with a negative increment, causing an infinite loop. Exiting." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl;
zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl;
zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl;
zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl;
zlog << zTs() << "Minimum and maximum fields are both positive, but maximum > minimum with a negative increment, causing an infinite loop. Exiting." << std::endl;
err::vexit();
}
}
}
// + - +
else if(min>=0 && max<0 && inc>0){
if(vmpi::my_rank==0){
terminaltextcolor(RED);
std::cout << "Error in hysteresis-loop parameters:" << std::endl;
std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl;
std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl;
std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl;
std::cout << "Minimum field is positive and maximum field is negative with a positive increment, causing an infinite loop. Exiting." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl;
zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl;
zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl;
zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl;
zlog << zTs() << "Minimum field is positive and maximum field is negative with a positive increment, causing an infinite loop. Exiting." << std::endl;
err::vexit();
}
}
// - + -
else if(min<0 && max>=0 && inc<0){
if(vmpi::my_rank==0){
terminaltextcolor(RED);
std::cout << "Error in hysteresis-loop parameters:" << std::endl;
std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl;
std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl;
std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl;
std::cout << "Minimum field is negative and maximum field is positive with a negative increment, causing an infinite loop. Exiting." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl;
zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl;
zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl;
zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl;
zlog << zTs() << "Minimum field is negative and maximum field is positive with a negative increment, causing an infinite loop. Exiting." << std::endl;
err::vexit();
}
}
// - - -
else if(min<0 && max<0 && inc<0){
if(max>min){
if(vmpi::my_rank==0){
terminaltextcolor(RED);
std::cout << "Error in hysteresis-loop parameters:" << std::endl;
std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl;
std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl;
std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl;
std::cout << "Minimum and maximum fields are both negative, but minimum < maximum with a negative increment, causing an infinite loop. Exiting." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl;
zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl;
zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl;
zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl;
zlog << zTs() << "Minimum and maximum fields are both negative, but minimum < maximum with a negative increment, causing an infinite loop. Exiting." << std::endl;
err::vexit();
}
}
}
// - - +
else if(min<0 && max<0 && inc>0){
if(max<min){
if(vmpi::my_rank==0){
terminaltextcolor(RED);
std::cout << "Error in hysteresis-loop parameters:" << std::endl;
std::cout << "\t sim:minimum-applied-field-strength = " << min << std::endl;
std::cout << "\t sim:maximum-applied-field-strength = " << max << std::endl;
std::cout << "\t sim:applied-field-strength-increment = " << inc << std::endl;
std::cout << "Minimum and maximum fields are both negative, but maximum < minimum with a positive increment, causing an infinite loop. Exiting." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error in hysteresis-loop parameters:" << std::endl;
zlog << zTs() << "\t sim:minimum-applied-field-strength = " << min << std::endl;
zlog << zTs() << "\t sim:maximum-applied-field-strength = " << max << std::endl;
zlog << zTs() << "\t sim:applied-field-strength-increment = " << inc << std::endl;
zlog << zTs() << "Minimum and maximum fields are both positive, but maximum < minimum with a positive increment, causing an infinite loop. Exiting." << std::endl;
err::vexit();
}
}
}
return;
}
int set_derived_parameters(){
// Set integration constants
mp::dt = mp::dt_SI*mp::gamma_SI; // Must be set before Hth
mp::half_dt = 0.5*mp::dt;
// Check to see if field direction is set by angle
if(sim::applied_field_set_by_angle){
sim::H_vec[0]=sin(sim::applied_field_angle_phi*M_PI/180.0)*cos(sim::applied_field_angle_theta*M_PI/180.0);
sim::H_vec[1]=sin(sim::applied_field_angle_phi*M_PI/180.0)*sin(sim::applied_field_angle_theta*M_PI/180.0);
sim::H_vec[2]=cos(sim::applied_field_angle_phi*M_PI/180.0);
}
// Check for valid particle array offsets
if(cs::particle_array_offset_x >= cs::system_dimensions[0]){
terminaltextcolor(RED);
std::cerr << "Warning: requested particle-array-offset-x is greater than system dimensions." << std::endl;
std::cerr << "Info: This will probably lead to no particles being created and generate an error." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Warning: requested particle-array-offset-x is greater than system dimensions." << std::endl;
zlog << zTs() << "Info: This will probably lead to no particles being created and generate an error." << std::endl;
}
if(cs::particle_array_offset_y >= cs::system_dimensions[1]){
terminaltextcolor(RED);
std::cerr << "Warning: requested particle-array-offset-y is greater than system dimensions." << std::endl;
std::cerr << "Info: This will probably lead to no particles being created and generate an error." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Warning: requested particle-array-offset-y is greater than system dimensions." << std::endl;
zlog << zTs() << "Info: This will probably lead to no particles being created and generate an error." << std::endl;
}
check_hysteresis_loop_parameters();
// Ensure H vector is unit length
// **RE edit 21.11.12 - no longer necessary as value checked on user input**
//double mod_H=1.0/sqrt(sim::H_vec[0]*sim::H_vec[0]+sim::H_vec[1]*sim::H_vec[1]+sim::H_vec[2]*sim::H_vec[2]);
//sim::H_vec[0]*=mod_H;
//sim::H_vec[1]*=mod_H;
//sim::H_vec[2]*=mod_H;
// Calculate moment, magnetisation, and anisotropy constants
/*for(int mat=0;mat<mp::num_materials;mat++){
double V=cs::unit_cell_size[0]*cs::unit_cell_size[1]*cs::unit_cell_size[2];
// Set magnetisation from mu_s and a
if(material[mat].moment_flag==true){
//material[mat].magnetisation=num_atoms_per_unit_cell*material[mat].mu_s_SI/V;
}
// Set mu_s from magnetisation and a
else {
//material[mat].mu_s_SI=material[mat].magnetisation*V/num_atoms_per_unit_cell;
}
// Set K as energy/atom
if(material[mat].anis_flag==false){
material[mat].Ku1_SI=material[mat].Ku1_SI*V/num_atoms_per_unit_cell;
std::cout << "setting " << material[mat].Ku1_SI << std::endl;
}
}*/
const string blank="";
// Check for symmetry of exchange matrix
for(int mi = 0; mi < mp::num_materials; mi++){
for(int mj = 0; mj < mp::num_materials; mj++){
// Check for non-zero value (avoids divide by zero)
if(fabs(material[mi].Jij_matrix_SI[mj]) > 0.0){
// Calculate ratio of i->j / j-> exchange constants
double ratio = material[mj].Jij_matrix_SI[mi]/material[mi].Jij_matrix_SI[mj];
// Check that ratio ~ 1.0 for symmetric exchange interactions
if( (ratio < 0.99999) || (ratio > 1.00001) ){
// Error found - report to user and terminate program
terminaltextcolor(RED);
std::cerr << "Error! Non-symmetric exchange interactions for materials " << mi+1 << " and " << mj+1 << ". Exiting" << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Error! Non-symmetric exchange interactions for materials " << mi+1 << " and " << mj+1 << std::endl;
zlog << zTs() << "\tmaterial[" << mi+1 << "]:exchange-matrix[" << mj+1 << "] = " << material[mi].Jij_matrix_SI[mj] << std::endl;
zlog << zTs() << "\tmaterial[" << mj+1 << "]:exchange-matrix[" << mi+1 << "] = " << material[mj].Jij_matrix_SI[mi] << std::endl;
zlog << zTs() << "\tThe definition of Heisenberg exchange requires that these values are the same. Exiting." << std::endl;
err::vexit();
}
}
}
}
// Set derived material parameters
for(int mat=0;mat<mp::num_materials;mat++){
mp::material[mat].one_oneplusalpha_sq = -mp::material[mat].gamma_rel/(1.0+mp::material[mat].alpha*mp::material[mat].alpha);
mp::material[mat].alpha_oneplusalpha_sq = mp::material[mat].alpha*mp::material[mat].one_oneplusalpha_sq;
for(int j=0;j<mp::num_materials;j++){
material[mat].Jij_matrix[j] = mp::material[mat].Jij_matrix_SI[j]/mp::material[mat].mu_s_SI;
}
mp::material[mat].Ku = mp::material[mat].Ku1_SI/mp::material[mat].mu_s_SI;
mp::material[mat].Ku2 = mp::material[mat].Ku2_SI/mp::material[mat].mu_s_SI;
mp::material[mat].Ku3 = mp::material[mat].Ku3_SI/mp::material[mat].mu_s_SI;
mp::material[mat].Klatt = mp::material[mat].Klatt_SI/mp::material[mat].mu_s_SI;
mp::material[mat].Kc = mp::material[mat].Kc1_SI/mp::material[mat].mu_s_SI;
mp::material[mat].Ks = mp::material[mat].Ks_SI/mp::material[mat].mu_s_SI;
mp::material[mat].H_th_sigma = sqrt(2.0*mp::material[mat].alpha*1.3806503e-23/
(mp::material[mat].mu_s_SI*mp::material[mat].gamma_rel*dt));
// Rename un-named materials with material id
std::string defname="material#n";
if(mp::material[mat].name==defname){
std::stringstream newname;
newname << "material" << mat+1;
mp::material[mat].name=newname.str();
}
// initialise lattice anisotropy initialisation
if(sim::lattice_anisotropy_flag==true) mp::material[mat].lattice_anisotropy.set_interpolation_table();
// output interpolated data to file
//mp::material[mat].lattice_anisotropy.output_interpolated_function(mat);
}
// Check for which anisotropy function(s) are to be used
if(sim::TensorAnisotropy==true){
sim::UniaxialScalarAnisotropy=false; // turn off scalar anisotropy calculation
// loop over materials and convert all scalar anisotropy to tensor (along z)
for(int mat=0;mat<mp::num_materials; mat++){
const double one_o_mu=1.0/mp::material[mat].mu_s_SI;
// If tensor is unset
if(mp::material.at(mat).KuVec_SI.size()==0){
const double ex = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(0);
const double ey = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(1);
const double ez = mp::material.at(mat).UniaxialAnisotropyUnitVector.at(2);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ex);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ey);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ex*ez);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ex);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ey);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ey*ez);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ex);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ey);
mp::material.at(mat).KuVec.push_back(mp::material[mat].Ku*ez*ez);
}
else if(mp::material.at(mat).KuVec_SI.size()==9){
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(0)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(1)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(2)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(3)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(4)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(5)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(6)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(7)*one_o_mu);
mp::material.at(mat).KuVec.push_back(mp::material.at(mat).KuVec_SI.at(8)*one_o_mu);
}
}
}
// Unroll anisotropy values for speed
if(sim::UniaxialScalarAnisotropy==true){
zlog << zTs() << "Setting scalar uniaxial anisotropy." << std::endl;
// Set global anisotropy type
sim::AnisotropyType=0;
MaterialScalarAnisotropyArray.resize(mp::num_materials);
for(int mat=0;mat<mp::num_materials; mat++) MaterialScalarAnisotropyArray[mat].K=mp::material[mat].Ku;
}
else if(sim::TensorAnisotropy==true){
zlog << zTs() << "Setting tensor uniaxial anisotropy." << std::endl;
// Set global anisotropy type
sim::AnisotropyType=1;
MaterialTensorAnisotropyArray.resize(mp::num_materials);
for(int mat=0;mat<mp::num_materials; mat++){
MaterialTensorAnisotropyArray[mat].K[0][0]=mp::material.at(mat).KuVec.at(0);
MaterialTensorAnisotropyArray[mat].K[0][1]=mp::material.at(mat).KuVec.at(1);
MaterialTensorAnisotropyArray[mat].K[0][2]=mp::material.at(mat).KuVec.at(2);
MaterialTensorAnisotropyArray[mat].K[1][0]=mp::material.at(mat).KuVec.at(3);
MaterialTensorAnisotropyArray[mat].K[1][1]=mp::material.at(mat).KuVec.at(4);
MaterialTensorAnisotropyArray[mat].K[1][2]=mp::material.at(mat).KuVec.at(5);
MaterialTensorAnisotropyArray[mat].K[2][0]=mp::material.at(mat).KuVec.at(6);
MaterialTensorAnisotropyArray[mat].K[2][1]=mp::material.at(mat).KuVec.at(7);
MaterialTensorAnisotropyArray[mat].K[2][2]=mp::material.at(mat).KuVec.at(8);
}
}
// Unroll second order uniaxial anisotropy values for speed
if(sim::second_order_uniaxial_anisotropy==true){
zlog << zTs() << "Setting scalar second order uniaxial anisotropy." << std::endl;
mp::material_second_order_anisotropy_constant_array.resize(mp::num_materials);
for(int mat=0;mat<mp::num_materials; mat++) mp::material_second_order_anisotropy_constant_array.at(mat)=mp::material[mat].Ku2;
}
// Unroll sixth order uniaxial anisotropy values for speed
if(sim::second_order_uniaxial_anisotropy==true){
zlog << zTs() << "Setting scalar sixth order uniaxial anisotropy." << std::endl;
mp::material_sixth_order_anisotropy_constant_array.resize(mp::num_materials);
for(int mat=0;mat<mp::num_materials; mat++) mp::material_sixth_order_anisotropy_constant_array.at(mat)=mp::material[mat].Ku3;
}
// Unroll spherical harmonic anisotropy constants for speed
if(sim::spherical_harmonics==true){
zlog << zTs() << "Setting spherical harmonics for uniaxial anisotropy" << std::endl;
mp::material_spherical_harmonic_constants_array.resize(3*mp::num_materials);
for(int mat=0; mat<mp::num_materials; mat++){
mp::material_spherical_harmonic_constants_array.at(3*mat+0)=mp::material[mat].sh2/mp::material[mat].mu_s_SI;
mp::material_spherical_harmonic_constants_array.at(3*mat+1)=mp::material[mat].sh4/mp::material[mat].mu_s_SI;
mp::material_spherical_harmonic_constants_array.at(3*mat+2)=mp::material[mat].sh6/mp::material[mat].mu_s_SI;
}
}
// Unroll cubic anisotropy values for speed
if(sim::CubicScalarAnisotropy==true){
zlog << zTs() << "Setting scalar cubic anisotropy." << std::endl;
MaterialCubicAnisotropyArray.resize(mp::num_materials);
for(int mat=0;mat<mp::num_materials; mat++) MaterialCubicAnisotropyArray.at(mat)=mp::material[mat].Kc;
}
// Loop over materials to check for invalid input and warn appropriately
for(int mat=0;mat<mp::num_materials;mat++){
const double lmin=material[mat].min;
const double lmax=material[mat].max;
for(int nmat=0;nmat<mp::num_materials;nmat++){
if(nmat!=mat){
double min=material[nmat].min;
double max=material[nmat].max;
if(((lmin>min) && (lmin<max)) || ((lmax>min) && (lmax<max))){
terminaltextcolor(RED);
std::cerr << "Warning: Overlapping material heights found. Check log for details." << std::endl;
terminaltextcolor(WHITE);
zlog << zTs() << "Warning: material " << mat+1 << " overlaps material " << nmat+1 << "." << std::endl;
zlog << zTs() << "If you have defined geometry then this may be OK, or possibly you meant to specify alloy keyword instead." << std::endl;
zlog << zTs() << "----------------------------------------------------" << std::endl;
zlog << zTs() << " Material "<< mat+1 << ":minimum-height = " << lmin << std::endl;
zlog << zTs() << " Material "<< mat+1 << ":maximum-height = " << lmax << std::endl;
zlog << zTs() << " Material "<< nmat+1 << ":minimum-height = " << min << std::endl;
zlog << zTs() << " Material "<< nmat+1 << ":maximum-height = " << max << std::endl;
}
}
}
}
return EXIT_SUCCESS;
}
} // end of namespace mp
| pchureemart/vampire | src/main/initialise_variables.cpp | C++ | gpl-2.0 | 27,475 |
(function( $ ) {
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( '.site-title a' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.site-description' ).text( to );
} );
} );
})( jQuery ); | thekirankumardash/bijithemecustomizer | project_downloads/2.5/js/theme-customizer.js | JavaScript | gpl-2.0 | 298 |
#!/bin/python
import os, subprocess
import logging
from autotest.client import test
from autotest.client.shared import error, software_manager
sm = software_manager.SoftwareManager()
class sblim_sfcb(test.test):
"""
Autotest module for testing basic functionality
of sblim_sfcb
@author Wang Tao <wangttao@cn.ibm.com>
"""
version = 1
nfail = 0
path = ''
def initialize(self, test_path=''):
"""
Sets the overall failure counter for the test.
"""
self.nfail = 0
if not sm.check_installed('gcc'):
logging.debug("gcc missing - trying to install")
sm.install('gcc')
ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path))
ret_val.communicate()
if ret_val.returncode != 0:
self.nfail += 1
logging.info('\n Test initialize successfully')
def run_once(self, test_path=''):
"""
Trigger test run
"""
try:
os.environ["LTPBIN"] = "%s/shared" %(test_path)
ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path))
ret_val.communicate()
if ret_val.returncode != 0:
self.nfail += 1
except error.CmdError, e:
self.nfail += 1
logging.error("Test Failed: %s", e)
def postprocess(self):
if self.nfail != 0:
logging.info('\n nfails is non-zero')
raise error.TestError('\nTest failed')
else:
logging.info('\n Test completed successfully ')
| rajashreer7/autotest-client-tests | linux-tools/sblim_sfcb/sblim_sfcb.py | Python | gpl-2.0 | 1,610 |
/*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "halls_of_reflection.h"
#include "Player.h"
enum Yells
{
SAY_JAINA_INTRO_1 = 0,
SAY_JAINA_INTRO_2 = 1,
SAY_JAINA_INTRO_3 = 2,
SAY_JAINA_INTRO_4 = 3,
SAY_JAINA_INTRO_5 = 4,
SAY_JAINA_INTRO_6 = 5,
SAY_JAINA_INTRO_7 = 6,
SAY_JAINA_INTRO_8 = 7,
SAY_JAINA_INTRO_9 = 8,
SAY_JAINA_INTRO_10 = 9,
SAY_JAINA_INTRO_11 = 10,
SAY_JAINA_INTRO_END = 11,
SAY_SYLVANAS_INTRO_1 = 0,
SAY_SYLVANAS_INTRO_2 = 1,
SAY_SYLVANAS_INTRO_3 = 2,
SAY_SYLVANAS_INTRO_4 = 3,
SAY_SYLVANAS_INTRO_5 = 4,
SAY_SYLVANAS_INTRO_6 = 5,
SAY_SYLVANAS_INTRO_7 = 6,
SAY_SYLVANAS_INTRO_8 = 7,
SAY_SYLVANAS_INTRO_END = 8,
SAY_UTHER_INTRO_A2_1 = 0,
SAY_UTHER_INTRO_A2_2 = 1,
SAY_UTHER_INTRO_A2_3 = 2,
SAY_UTHER_INTRO_A2_4 = 3,
SAY_UTHER_INTRO_A2_5 = 4,
SAY_UTHER_INTRO_A2_6 = 5,
SAY_UTHER_INTRO_A2_7 = 6,
SAY_UTHER_INTRO_A2_8 = 7,
SAY_UTHER_INTRO_A2_9 = 8,
SAY_UTHER_INTRO_H2_1 = 9,
SAY_UTHER_INTRO_H2_2 = 10,
SAY_UTHER_INTRO_H2_3 = 11,
SAY_UTHER_INTRO_H2_4 = 12,
SAY_UTHER_INTRO_H2_5 = 13,
SAY_UTHER_INTRO_H2_6 = 14,
SAY_UTHER_INTRO_H2_7 = 15,
SAY_LK_INTRO_1 = 0,
SAY_LK_INTRO_2 = 1,
SAY_LK_INTRO_3 = 2,
SAY_FALRIC_INTRO_1 = 5,
SAY_FALRIC_INTRO_2 = 6,
SAY_MARWYN_INTRO_1 = 4
};
enum Events
{
EVENT_NONE,
EVENT_START_INTRO,
EVENT_SKIP_INTRO,
EVENT_INTRO_A2_1,
EVENT_INTRO_A2_2,
EVENT_INTRO_A2_3,
EVENT_INTRO_A2_4,
EVENT_INTRO_A2_5,
EVENT_INTRO_A2_6,
EVENT_INTRO_A2_7,
EVENT_INTRO_A2_8,
EVENT_INTRO_A2_9,
EVENT_INTRO_A2_10,
EVENT_INTRO_A2_11,
EVENT_INTRO_A2_12,
EVENT_INTRO_A2_13,
EVENT_INTRO_A2_14,
EVENT_INTRO_A2_15,
EVENT_INTRO_A2_16,
EVENT_INTRO_A2_17,
EVENT_INTRO_A2_18,
EVENT_INTRO_A2_19,
EVENT_INTRO_H2_1,
EVENT_INTRO_H2_2,
EVENT_INTRO_H2_3,
EVENT_INTRO_H2_4,
EVENT_INTRO_H2_5,
EVENT_INTRO_H2_6,
EVENT_INTRO_H2_7,
EVENT_INTRO_H2_8,
EVENT_INTRO_H2_9,
EVENT_INTRO_H2_10,
EVENT_INTRO_H2_11,
EVENT_INTRO_H2_12,
EVENT_INTRO_H2_13,
EVENT_INTRO_H2_14,
EVENT_INTRO_H2_15,
EVENT_INTRO_LK_1,
EVENT_INTRO_LK_2,
EVENT_INTRO_LK_3,
EVENT_INTRO_LK_4,
EVENT_INTRO_LK_5,
EVENT_INTRO_LK_6,
EVENT_INTRO_LK_7,
EVENT_INTRO_LK_8,
EVENT_INTRO_LK_9,
EVENT_INTRO_END,
};
enum eEnum
{
ACTION_START_INTRO,
ACTION_SKIP_INTRO,
QUEST_DELIVRANCE_FROM_THE_PIT_A2 = 24710,
QUEST_DELIVRANCE_FROM_THE_PIT_H2 = 24712,
QUEST_WRATH_OF_THE_LICH_KING_A2 = 24500,
QUEST_WRATH_OF_THE_LICH_KING_H2 = 24802,
};
const Position HallsofReflectionLocs[]=
{
{5283.234863f, 1990.946777f, 707.695679f, 0.929097f}, // 2 Loralen Follows
{5408.031250f, 2102.918213f, 707.695251f, 0.792756f}, // 9 Sylvanas Follows
{5401.866699f, 2110.837402f, 707.695251f, 0.800610f}, // 10 Loralen follows
};
const Position SpawnPos = {5262.540527f, 1949.693726f, 707.695007f, 0.808736f}; // Jaina/Sylvanas Beginning Position
const Position MoveThronePos = {5306.952148f, 1998.499023f, 709.341431f, 1.277278f}; // Jaina/Sylvanas walks to throne
const Position UtherSpawnPos = {5308.310059f, 2003.857178f, 709.341431f, 4.650315f};
const Position LichKingSpawnPos = {5362.917480f, 2062.307129f, 707.695374f, 3.945812f};
const Position LichKingMoveThronePos = {5312.080566f, 2009.172119f, 709.341431f, 3.973301f}; // Lich King walks to throne
const Position LichKingMoveAwayPos = {5400.069824f, 2102.7131689f, 707.69525f, 0.843803f}; // Lich King walks away
class npc_jaina_or_sylvanas_hor : public CreatureScript
{
private:
bool m_isSylvana;
public:
npc_jaina_or_sylvanas_hor(bool isSylvana, const char* name) : CreatureScript(name), m_isSylvana(isSylvana) { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->CLOSE_GOSSIP_MENU();
if (creature->AI())
creature->AI()->DoAction(ACTION_START_INTRO);
creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
break;
case GOSSIP_ACTION_INFO_DEF+2:
player->CLOSE_GOSSIP_MENU();
if (creature->AI())
creature->AI()->DoAction(ACTION_SKIP_INTRO);
creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
break;
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (creature->isQuestGiver())
player->PrepareQuestMenu(creature->GetGUID());
QuestStatus status = player->GetQuestStatus(m_isSylvana ? QUEST_DELIVRANCE_FROM_THE_PIT_H2 : QUEST_DELIVRANCE_FROM_THE_PIT_A2);
if (status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED)
player->ADD_GOSSIP_ITEM( 0, "Can you remove the sword?", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
// once last quest is completed, she offers this shortcut of the starting event
status = player->GetQuestStatus(m_isSylvana ? QUEST_WRATH_OF_THE_LICH_KING_H2 : QUEST_WRATH_OF_THE_LICH_KING_A2);
if (status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED)
player->ADD_GOSSIP_ITEM( 0, "Dark Lady, I think I hear Arthas coming. Whatever you're going to do, do it quickly.", GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID());
return true;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_jaina_or_sylvanas_horAI(creature);
}
// AI of Part1: handle the intro till start of gauntlet event.
struct npc_jaina_or_sylvanas_horAI : public ScriptedAI
{
npc_jaina_or_sylvanas_horAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
}
InstanceScript* instance;
uint64 utherGUID;
uint64 lichkingGUID;
EventMap events;
void Reset()
{
events.Reset();
utherGUID = 0;
lichkingGUID = 0;
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
me->SetStandState(UNIT_STAND_STATE_STAND);
me->SetVisible(true);
}
void DoAction(const int32 actionId)
{
switch (actionId)
{
case ACTION_START_INTRO:
events.ScheduleEvent(EVENT_START_INTRO, 0);
break;
case ACTION_SKIP_INTRO:
events.ScheduleEvent(EVENT_SKIP_INTRO, 0);
break;
}
}
void UpdateAI(const uint32 diff)
{
events.Update(diff);
switch (events.ExecuteEvent())
{
case EVENT_START_INTRO:
me->GetMotionMaster()->MovePoint(0, MoveThronePos);
// Begining of intro is differents between fActions as the speech sequence and timers are differents.
if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE)
events.ScheduleEvent(EVENT_INTRO_A2_1, 0);
else
events.ScheduleEvent(EVENT_INTRO_H2_1, 0);
break;
// A2 Intro Events
case EVENT_INTRO_A2_1:
Talk(SAY_JAINA_INTRO_3);
events.ScheduleEvent(EVENT_INTRO_A2_2, 5000);
break;
case EVENT_INTRO_A2_2:
Talk(SAY_JAINA_INTRO_4);
events.ScheduleEvent(EVENT_INTRO_A2_3, 10000);
break;
case EVENT_INTRO_A2_3:
// TODO: she's doing some kind of spell casting emote
instance->HandleGameObject(instance->GetData64(DATA_FROSTMOURNE), true);
events.ScheduleEvent(EVENT_INTRO_A2_4, 10000);
break;
case EVENT_INTRO_A2_4:
// spawn UTHER during speach 2
if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN))
{
uther->GetMotionMaster()->MoveIdle();
uther->SetReactState(REACT_PASSIVE); // be sure he will not aggro arthas
utherGUID = uther->GetGUID();
}
events.ScheduleEvent(EVENT_INTRO_A2_5, 2000);
break;
case EVENT_INTRO_A2_5:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_1);
events.ScheduleEvent(EVENT_INTRO_A2_6, 3000);
break;
case EVENT_INTRO_A2_6:
Talk(SAY_JAINA_INTRO_5);
events.ScheduleEvent(EVENT_INTRO_A2_7, 6000);
break;
case EVENT_INTRO_A2_7:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_2);
events.ScheduleEvent(EVENT_INTRO_A2_8, 6500);
break;
case EVENT_INTRO_A2_8:
Talk(SAY_JAINA_INTRO_6);
events.ScheduleEvent(EVENT_INTRO_A2_9, 2000);
break;
case EVENT_INTRO_A2_9:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_3);
events.ScheduleEvent(EVENT_INTRO_A2_10, 9000);
break;
case EVENT_INTRO_A2_10:
Talk(SAY_JAINA_INTRO_7);
events.ScheduleEvent(EVENT_INTRO_A2_11, 5000);
break;
case EVENT_INTRO_A2_11:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_4);
events.ScheduleEvent(EVENT_INTRO_A2_12, 11000);
break;
case EVENT_INTRO_A2_12:
Talk(SAY_JAINA_INTRO_8);
events.ScheduleEvent(EVENT_INTRO_A2_13, 4000);
break;
case EVENT_INTRO_A2_13:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_5);
events.ScheduleEvent(EVENT_INTRO_A2_14, 12500);
break;
case EVENT_INTRO_A2_14:
Talk(SAY_JAINA_INTRO_9);
events.ScheduleEvent(EVENT_INTRO_A2_15, 10000);
break;
case EVENT_INTRO_A2_15:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_6);
events.ScheduleEvent(EVENT_INTRO_A2_16, 22000);
break;
case EVENT_INTRO_A2_16:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_A2_7);
events.ScheduleEvent(EVENT_INTRO_A2_17, 4000);
break;
case EVENT_INTRO_A2_17:
Talk(SAY_JAINA_INTRO_10);
events.ScheduleEvent(EVENT_INTRO_A2_18, 2000);
break;
case EVENT_INTRO_A2_18:
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
uther->HandleEmoteCommand(EMOTE_ONESHOT_NO);
uther->AI()->Talk(SAY_UTHER_INTRO_A2_8);
}
events.ScheduleEvent(EVENT_INTRO_A2_19, 11000);
break;
case EVENT_INTRO_A2_19:
Talk(SAY_JAINA_INTRO_11);
events.ScheduleEvent(EVENT_INTRO_LK_1, 2000);
break;
// H2 Intro Events
case EVENT_INTRO_H2_1:
Talk(SAY_SYLVANAS_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_H2_2, 8000);
break;
case EVENT_INTRO_H2_2:
Talk(SAY_SYLVANAS_INTRO_2);
events.ScheduleEvent(EVENT_INTRO_H2_3, 6000);
break;
case EVENT_INTRO_H2_3:
Talk(SAY_SYLVANAS_INTRO_3);
// TODO: she's doing some kind of spell casting emote
events.ScheduleEvent(EVENT_INTRO_H2_4, 6000);
break;
case EVENT_INTRO_H2_4:
// spawn UTHER during speach 2
if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN))
{
uther->GetMotionMaster()->MoveIdle();
uther->SetReactState(REACT_PASSIVE); // be sure he will not aggro arthas
utherGUID = uther->GetGUID();
}
events.ScheduleEvent(EVENT_INTRO_H2_5, 2000);
break;
case EVENT_INTRO_H2_5:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_1);
events.ScheduleEvent(EVENT_INTRO_H2_6, 11000);
break;
case EVENT_INTRO_H2_6:
Talk(SAY_SYLVANAS_INTRO_4);
events.ScheduleEvent(EVENT_INTRO_H2_7, 3000);
break;
case EVENT_INTRO_H2_7:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_2);
events.ScheduleEvent(EVENT_INTRO_H2_8, 6000);
break;
case EVENT_INTRO_H2_8:
Talk(SAY_SYLVANAS_INTRO_5);
events.ScheduleEvent(EVENT_INTRO_H2_9, 5000);
break;
case EVENT_INTRO_H2_9:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_3);
events.ScheduleEvent(EVENT_INTRO_H2_10, 19000);
break;
case EVENT_INTRO_H2_10:
Talk(SAY_SYLVANAS_INTRO_6);
events.ScheduleEvent(EVENT_INTRO_H2_11, 1500);
break;
case EVENT_INTRO_H2_11:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_4);
events.ScheduleEvent(EVENT_INTRO_H2_12, 19500);
break;
case EVENT_INTRO_H2_12:
Talk(SAY_SYLVANAS_INTRO_7);
events.ScheduleEvent(EVENT_INTRO_H2_13, 2000);
break;
case EVENT_INTRO_H2_13:
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
uther->HandleEmoteCommand(EMOTE_ONESHOT_NO);
uther->AI()->Talk(SAY_UTHER_INTRO_H2_5);
}
events.ScheduleEvent(EVENT_INTRO_H2_14, 12000);
break;
case EVENT_INTRO_H2_14:
if (Creature* uther = me->GetCreature(*me, utherGUID))
uther->AI()->Talk(SAY_UTHER_INTRO_H2_6);
events.ScheduleEvent(EVENT_INTRO_H2_15, 8000);
break;
case EVENT_INTRO_H2_15:
Talk(SAY_SYLVANAS_INTRO_8);
events.ScheduleEvent(EVENT_INTRO_LK_1, 2000);
break;
// Remaining Intro Events common for both faction
case EVENT_INTRO_LK_1:
// Spawn LK in front of door, and make him move to the sword.
if (Creature* lichking = me->SummonCreature(NPC_LICH_KING_EVENT, LichKingSpawnPos, TEMPSUMMON_MANUAL_DESPAWN))
{
lichking->GetMotionMaster()->MovePoint(0, LichKingMoveThronePos);
lichking->SetReactState(REACT_PASSIVE);
lichkingGUID = lichking->GetGUID();
}
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE)
uther->AI()->Talk(SAY_UTHER_INTRO_A2_9);
else
uther->AI()->Talk(SAY_UTHER_INTRO_H2_7);
}
events.ScheduleEvent(EVENT_INTRO_LK_2, 11000);
break;
case EVENT_INTRO_LK_2:
if (Creature* lichking = me->GetCreature(*me, lichkingGUID))
lichking->AI()->Talk(SAY_LK_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_LK_3, 2000);
break;
case EVENT_INTRO_LK_3:
// The Lich King banishes Uther to the abyss.
if (Creature* uther = me->GetCreature(*me, utherGUID))
{
uther->DisappearAndDie();
utherGUID = 0;
}
// He steps forward and removes the runeblade from the heap of skulls.
events.ScheduleEvent(EVENT_INTRO_LK_4, 4000);
break;
case EVENT_INTRO_LK_4:
if (Creature* lichking = me->GetCreature(*me, lichkingGUID))
lichking->AI()->Talk(SAY_LK_INTRO_2);
events.ScheduleEvent(EVENT_INTRO_LK_5, 10000);
break;
case EVENT_INTRO_LK_5:
// summon Falric and Marwyn. then go back to the door
if (Creature* pFalric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
pFalric->SetVisible(true);
if (Creature* pMarwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN)))
pMarwyn->SetVisible(true);
if (Creature* lichking = me->GetCreature(*me, lichkingGUID))
{
lichking->GetMotionMaster()->MovePoint(0, LichKingSpawnPos);
lichking->AI()->Talk(SAY_LK_INTRO_3);
}
events.ScheduleEvent(EVENT_INTRO_LK_6, 8000);
break;
case EVENT_INTRO_LK_6:
if (Creature* falric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
falric->AI()->Talk(SAY_FALRIC_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_LK_7, 2000);
break;
case EVENT_INTRO_LK_7:
if (Creature* marwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN)))
marwyn->AI()->Talk(SAY_MARWYN_INTRO_1);
events.ScheduleEvent(EVENT_INTRO_LK_8, 2000);
break;
case EVENT_INTRO_LK_8:
if (Creature* falric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
falric->AI()->Talk(SAY_FALRIC_INTRO_2);
events.ScheduleEvent(EVENT_INTRO_LK_9, 5000);
break;
case EVENT_INTRO_LK_9:
if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE)
Talk(SAY_JAINA_INTRO_END);
else
Talk(SAY_SYLVANAS_INTRO_END);
me->GetMotionMaster()->MovePoint(0, LichKingSpawnPos);
// TODO: Loralen/Koreln shall run also
events.ScheduleEvent(EVENT_INTRO_END, 10000);
break;
case EVENT_INTRO_END:
if (instance)
instance->SetData(DATA_WAVE_COUNT, SPECIAL); // start first wave
// Loralen or Koreln disappearAndDie()
me->DisappearAndDie();
break;
case EVENT_SKIP_INTRO:
// TODO: implement
if (Creature* pFalric = me->GetCreature(*me, instance->GetData64(DATA_FALRIC)))
pFalric->SetVisible(true);
if (Creature* pMarwyn = me->GetCreature(*me, instance->GetData64(DATA_MARWYN)))
pMarwyn->SetVisible(true);
me->GetMotionMaster()->MovePoint(0, LichKingSpawnPos);
// TODO: Loralen/Koreln shall run also
events.ScheduleEvent(EVENT_INTRO_END, 15000);
break;
}
}
};
};
enum TrashSpells
{
// Ghostly Priest
SPELL_SHADOW_WORD_PAIN = 72318,
SPELL_CIRCLE_OF_DESTRUCTION = 72320,
SPELL_COWER_IN_FEAR = 72321,
SPELL_DARK_MENDING = 72322,
// Phantom Mage
SPELL_FIREBALL = 72163,
SPELL_FLAMESTRIKE = 72169,
SPELL_FROSTBOLT = 72166,
SPELL_CHAINS_OF_ICE = 72121,
SPELL_HALLUCINATION = 72342,
// Phantom Hallucination (same as phantom mage + HALLUCINATION_2 when dies)
SPELL_HALLUCINATION_2 = 72344,
// Shadowy Mercenary
SPELL_SHADOW_STEP = 72326,
SPELL_DEADLY_POISON = 72329,
SPELL_ENVENOMED_DAGGER_THROW = 72333,
SPELL_KIDNEY_SHOT = 72335,
// Spectral Footman
SPELL_SPECTRAL_STRIKE = 72198,
SPELL_SHIELD_BASH = 72194,
SPELL_TORTURED_ENRAGE = 72203,
// Tortured Rifleman
SPELL_SHOOT = 72208,
SPELL_CURSED_ARROW = 72222,
SPELL_FROST_TRAP = 72215,
SPELL_ICE_SHOT = 72268,
};
enum TrashEvents
{
EVENT_TRASH_NONE,
// Ghostly Priest
EVENT_SHADOW_WORD_PAIN,
EVENT_CIRCLE_OF_DESTRUCTION,
EVENT_COWER_IN_FEAR,
EVENT_DARK_MENDING,
// Phantom Mage
EVENT_FIREBALL,
EVENT_FLAMESTRIKE,
EVENT_FROSTBOLT,
EVENT_CHAINS_OF_ICE,
EVENT_HALLUCINATION,
// Shadowy Mercenary
EVENT_SHADOW_STEP,
EVENT_DEADLY_POISON,
EVENT_ENVENOMED_DAGGER_THROW,
EVENT_KIDNEY_SHOT,
// Spectral Footman
EVENT_SPECTRAL_STRIKE,
EVENT_SHIELD_BASH,
EVENT_TORTURED_ENRAGE,
// Tortured Rifleman
EVENT_SHOOT,
EVENT_CURSED_ARROW,
EVENT_FROST_TRAP,
EVENT_ICE_SHOT,
};
class npc_ghostly_priest : public CreatureScript
{
public:
npc_ghostly_priest() : CreatureScript("npc_ghostly_priest") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_ghostly_priestAI(creature);
}
struct npc_ghostly_priestAI: public ScriptedAI
{
npc_ghostly_priestAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 8000); // TODO: adjust timers
events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12000);
events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10000);
events.ScheduleEvent(EVENT_DARK_MENDING, 20000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOW_WORD_PAIN:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_SHADOW_WORD_PAIN);
events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 8000);
return;
case EVENT_CIRCLE_OF_DESTRUCTION:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_CIRCLE_OF_DESTRUCTION);
events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12000);
return;
case EVENT_COWER_IN_FEAR:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_COWER_IN_FEAR);
events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10000);
return;
case EVENT_DARK_MENDING:
// find an ally with missing HP
if (Unit* target = DoSelectLowestHpFriendly(40, DUNGEON_MODE(30000, 50000)))
{
DoCast(target, SPELL_DARK_MENDING);
events.ScheduleEvent(EVENT_DARK_MENDING, 20000);
}
else
{
// no friendly unit with missing hp. re-check in just 5 sec.
events.ScheduleEvent(EVENT_DARK_MENDING, 5000);
}
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_phantom_mage : public CreatureScript
{
public:
npc_phantom_mage() : CreatureScript("npc_phantom_mage") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_phantom_mageAI(creature);
}
struct npc_phantom_mageAI: public ScriptedAI
{
npc_phantom_mageAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_FIREBALL, 3000); // TODO: adjust timers
events.ScheduleEvent(EVENT_FLAMESTRIKE, 6000);
events.ScheduleEvent(EVENT_FROSTBOLT, 9000);
events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 12000);
events.ScheduleEvent(EVENT_HALLUCINATION, 40000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FIREBALL:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_FIREBALL);
events.ScheduleEvent(EVENT_FIREBALL, 15000);
return;
case EVENT_FLAMESTRIKE:
DoCast(SPELL_FLAMESTRIKE);
events.ScheduleEvent(EVENT_FLAMESTRIKE, 15000);
return;
case EVENT_FROSTBOLT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_FROSTBOLT);
events.ScheduleEvent(EVENT_FROSTBOLT, 15000);
return;
case EVENT_CHAINS_OF_ICE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_CHAINS_OF_ICE);
events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 15000);
return;
case EVENT_HALLUCINATION:
DoCast(SPELL_HALLUCINATION);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_phantom_hallucination : public CreatureScript
{
public:
npc_phantom_hallucination() : CreatureScript("npc_phantom_hallucination") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_phantom_hallucinationAI(creature);
}
struct npc_phantom_hallucinationAI : public npc_phantom_mage::npc_phantom_mageAI
{
npc_phantom_hallucinationAI(Creature* creature) : npc_phantom_mage::npc_phantom_mageAI(creature)
{
}
void JustDied(Unit* /*killer*/)
{
DoCast(SPELL_HALLUCINATION_2);
}
};
};
class npc_shadowy_mercenary : public CreatureScript
{
public:
npc_shadowy_mercenary() : CreatureScript("npc_shadowy_mercenary") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_shadowy_mercenaryAI(creature);
}
struct npc_shadowy_mercenaryAI: public ScriptedAI
{
npc_shadowy_mercenaryAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SHADOW_STEP, 8000); // TODO: adjust timers
events.ScheduleEvent(EVENT_DEADLY_POISON, 5000);
events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10000);
events.ScheduleEvent(EVENT_KIDNEY_SHOT, 12000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOW_STEP:
DoCast(SPELL_SHADOW_STEP);
events.ScheduleEvent(EVENT_SHADOW_STEP, 8000);
return;
case EVENT_DEADLY_POISON:
DoCast(me->getVictim(), SPELL_DEADLY_POISON);
events.ScheduleEvent(EVENT_DEADLY_POISON, 10000);
return;
case EVENT_ENVENOMED_DAGGER_THROW:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_ENVENOMED_DAGGER_THROW);
events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10000);
return;
case EVENT_KIDNEY_SHOT:
DoCast(me->getVictim(), SPELL_KIDNEY_SHOT);
events.ScheduleEvent(EVENT_KIDNEY_SHOT, 10000);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_spectral_footman : public CreatureScript
{
public:
npc_spectral_footman() : CreatureScript("npc_spectral_footman") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_spectral_footmanAI(creature);
}
struct npc_spectral_footmanAI: public ScriptedAI
{
npc_spectral_footmanAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5000); // TODO: adjust timers
events.ScheduleEvent(EVENT_SHIELD_BASH, 10000);
events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SPECTRAL_STRIKE:
DoCast(me->getVictim(), SPELL_SPECTRAL_STRIKE);
events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5000);
return;
case EVENT_SHIELD_BASH:
DoCast(me->getVictim(), SPELL_SHIELD_BASH);
events.ScheduleEvent(EVENT_SHIELD_BASH, 5000);
return;
case EVENT_TORTURED_ENRAGE:
DoCast(SPELL_TORTURED_ENRAGE);
events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15000);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
class npc_tortured_rifleman : public CreatureScript
{
public:
npc_tortured_rifleman() : CreatureScript("npc_tortured_rifleman") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_tortured_riflemanAI(creature);
}
struct npc_tortured_riflemanAI : public ScriptedAI
{
npc_tortured_riflemanAI(Creature* creature) : ScriptedAI(creature)
{
}
EventMap events;
void Reset()
{
events.Reset();
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_SHOOT, 2000); // TODO: adjust timers
events.ScheduleEvent(EVENT_CURSED_ARROW, 10000);
events.ScheduleEvent(EVENT_FROST_TRAP, 1000);
events.ScheduleEvent(EVENT_ICE_SHOT, 15000);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHOOT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_SHOOT);
events.ScheduleEvent(EVENT_SHOOT, 2000);
return;
case EVENT_CURSED_ARROW:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_CURSED_ARROW);
events.ScheduleEvent(EVENT_CURSED_ARROW, 10000);
return;
case EVENT_FROST_TRAP:
DoCast(SPELL_FROST_TRAP);
events.ScheduleEvent(EVENT_FROST_TRAP, 30000);
return;
case EVENT_ICE_SHOT:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM))
DoCast(target, SPELL_ICE_SHOT);
events.ScheduleEvent(EVENT_ICE_SHOT, 15000);
return;
}
}
DoMeleeAttackIfReady();
}
};
};
void AddSC_halls_of_reflection()
{
new npc_jaina_or_sylvanas_hor(true, "npc_sylvanas_hor_part1");
new npc_jaina_or_sylvanas_hor(false, "npc_jaina_hor_part1");
new npc_ghostly_priest();
new npc_phantom_mage();
new npc_phantom_hallucination();
new npc_shadowy_mercenary();
new npc_spectral_footman();
new npc_tortured_rifleman();
}
| LORDofDOOM/MMOCore | src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp | C++ | gpl-2.0 | 37,732 |
"""
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsddb
from bsddb3 import db, hashopen, btopen, rnopen
class CompatibilityTestCase(unittest.TestCase):
def setUp(self):
self.filename = tempfile.mktemp()
def tearDown(self):
try:
os.remove(self.filename)
except os.error:
pass
def test01_btopen(self):
self.do_bthash_test(btopen, 'btopen')
def test02_hashopen(self):
self.do_bthash_test(hashopen, 'hashopen')
def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.")
if verbose:
print "\nTesting: rnopen"
f = rnopen(self.filename, 'c')
for x in range(len(data)):
f[x+1] = data[x]
getTest = (f[1], f[2], f[3])
if verbose:
print '%s %s %s' % getTest
assert getTest[1] == 'quick', 'data mismatch!'
f[25] = 'twenty-five'
f.close()
del f
f = rnopen(self.filename, 'w')
f[20] = 'twenty'
def noRec(f):
rec = f[15]
self.assertRaises(KeyError, noRec, f)
def badKey(f):
rec = f['a string']
self.assertRaises(TypeError, badKey, f)
del f[3]
rec = f.first()
while rec:
if verbose:
print rec
try:
rec = f.next()
except KeyError:
break
f.close()
def test04_n_flag(self):
f = hashopen(self.filename, 'n')
f.close()
def do_bthash_test(self, factory, what):
if verbose:
print '\nTesting: ', what
f = factory(self.filename, 'c')
if verbose:
print 'creation...'
# truth test
if f:
if verbose: print "truth test: true"
else:
if verbose: print "truth test: false"
f['0'] = ''
f['a'] = 'Guido'
f['b'] = 'van'
f['c'] = 'Rossum'
f['d'] = 'invented'
f['f'] = 'Python'
if verbose:
print '%s %s %s' % (f['a'], f['b'], f['c'])
if verbose:
print 'key ordering...'
f.set_location(f.first()[0])
while 1:
try:
rec = f.next()
except KeyError:
assert rec == f.last(), 'Error, last <> last!'
f.previous()
break
if verbose:
print rec
assert f.has_key('f'), 'Error, missing key!'
f.sync()
f.close()
# truth test
try:
if f:
if verbose: print "truth test: true"
else:
if verbose: print "truth test: false"
except db.DBError:
pass
else:
self.fail("Exception expected")
del f
if verbose:
print 'modification...'
f = factory(self.filename, 'w')
f['d'] = 'discovered'
if verbose:
print 'access...'
for key in f.keys():
word = f[key]
if verbose:
print word
def noRec(f):
rec = f['no such key']
self.assertRaises(KeyError, noRec, f)
def badKey(f):
rec = f[15]
self.assertRaises(TypeError, badKey, f)
f.close()
#----------------------------------------------------------------------
def test_suite():
return unittest.makeSuite(CompatibilityTestCase)
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| trivoldus28/pulsarch-verilog | tools/local/bas-release/bas,3.9/lib/python/lib/python2.3/bsddb/test/test_compat.py | Python | gpl-2.0 | 3,862 |
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
jimport('joomla.application.component.view');
/**
* Description of SocialcountViewSocialcount
*
* @author stuart
*/
class SocialstreamsViewStream extends JView {
function display($tpl = null) {
if(!$this->get(ucfirst($this->network) . 'Cache')){
$adminmodel = &$this->getModel();
}
$this->assignRef('cache', $cache);
parent::display($tpl);
}
}
?>
| appsol/socialstreams-joomla-25 | com_socialstreams/views/stream/view.html.php | PHP | gpl-2.0 | 583 |
/*
* Copyright (c) 2006 Boudewijn Rempt <boud@valdyas.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kis_transparency_mask.h"
#include "kis_debug.h"
#include <KoIcon.h>
#include <KoColor.h>
#include <KoColorSpace.h>
#include <KoCompositeOpRegistry.h>
#include "kis_paint_device.h"
#include "kis_painter.h"
#include "kis_node_visitor.h"
#include "kis_processing_visitor.h"
KisTransparencyMask::KisTransparencyMask()
: KisEffectMask()
{
}
KisTransparencyMask::KisTransparencyMask(const KisTransparencyMask& rhs)
: KisEffectMask(rhs)
{
}
KisTransparencyMask::~KisTransparencyMask()
{
}
bool KisTransparencyMask::allowAsChild(KisNodeSP node) const
{
Q_UNUSED(node);
return false;
}
QRect KisTransparencyMask::decorateRect(KisPaintDeviceSP &src,
KisPaintDeviceSP &dst,
const QRect & rc) const
{
if (src != dst) {
KisPainter gc(dst);
gc.setCompositeOp(src->colorSpace()->compositeOp(COMPOSITE_COPY));
gc.bitBlt(rc.topLeft(), src, rc);
src->fill(rc, KoColor(Qt::transparent, src->colorSpace()));
}
return rc;
}
QRect KisTransparencyMask::extent() const
{
return parent() ? parent()->extent() : QRect();
}
QRect KisTransparencyMask::exactBounds() const
{
return parent() ? parent()->exactBounds() : QRect();
}
QRect KisTransparencyMask::changeRect(const QRect &rect, PositionToFilthy pos) const
{
/**
* Selection on transparency masks have no special meaning:
* They do crop both: change and need area
*/
return KisMask::changeRect(rect, pos);
}
QRect KisTransparencyMask::needRect(const QRect &rect, PositionToFilthy pos) const
{
/**
* Selection on transparency masks have no special meaning:
* They do crop both: change and need area
*/
return KisMask::needRect(rect, pos);
}
QIcon KisTransparencyMask::icon() const
{
return koIcon("view-filter");
}
bool KisTransparencyMask::accept(KisNodeVisitor &v)
{
return v.visit(this);
}
void KisTransparencyMask::accept(KisProcessingVisitor &visitor, KisUndoAdapter *undoAdapter)
{
return visitor.visit(this, undoAdapter);
}
#include "kis_transparency_mask.moc"
| harshitamistry/calligraRepository | krita/image/kis_transparency_mask.cc | C++ | gpl-2.0 | 2,935 |
<?php
/**
* @version $Id: imgmanager.php 46 2009-05-26 16:59:42Z happynoodleboy $
* @package JCE
* @copyright Copyright (C) 2005 - 2009 Ryan Demmer. All rights reserved.
* @author Ryan Demmer
* @license GNU/GPL
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
defined('_JEXEC') or die('Restricted access');
require_once(JCE_LIBRARIES .DS. 'classes' .DS. 'manager.php');
class ImageManager extends Manager
{
var $_ext = 'image=jpg,jpeg,gif,png';
/**
* @access protected
*/
function __construct()
{
parent::__construct();
// Set the file type map from parameters
$this->setFileTypes($this->getPluginParam('imgmanager_extensions', $this->_ext));
// Init plugin
$this->init();
}
/**
* Returns a reference to a editor object
*
* This method must be invoked as:
* <pre> $browser = &JCE::getInstance();</pre>
*
* @access public
* @return JCE The editor object.
* @since 1.5
*/
function &getInstance()
{
static $instance;
if (!is_object($instance)) {
$instance = new ImageManager();
}
return $instance;
}
/**
* Initialise the plugin
*/
function init()
{
// check the user/group has editor permissions
$this->checkPlugin() or die(JError::raiseError(403, JText::_('Access Forbidden')));
parent::init();
// Setup plugin XHR callback functions
$this->setXHR(array($this, 'getDimensions'));
// Set javascript file array
$this->script(array('imgmanager'), 'plugins');
// Set css file array
$this->css(array('imgmanager'), 'plugins');
// Load extensions if any
$this->loadExtensions();
}
/**
* Get the dimensions of an image
* @return array Dimensions as array
* @param object $file Relative path to image
*/
function getDimensions($file)
{
$path = Utils::makePath($this->getBaseDir(), rawurldecode($file));
$h = array(
'width' => '',
'height' => ''
);
if (file_exists($path)) {
$dim = @getimagesize($path);
$h = array(
'width' => $dim[0],
'height' => $dim[1]
);
}
return $h;
}
/**
* Get list of uploadable extensions
* @return Mapped extension list (list mapped to type object eg: 'images', 'jpeg,jpg,gif,png')
*/
function getUploadFileTypes()
{
$list = $this->getPluginParam('imgmanager_extensions', 'image=jpg,jpeg,gif,png');
return $this->mapUploadFileTypes($list);
}
}
?> | jahama/cbhondarribia.com | plugins/editors/jce/tiny_mce/plugins/imgmanager/classes/imgmanager.php | PHP | gpl-2.0 | 2,679 |
/*
EventON Generate Google maps function
*/
(function($){
$.fn.evoGenmaps = function(opt){
var defaults = {
delay: 0,
fnt: 1,
cal: '',
mapSpotId: '',
_action:''
};
var options = $.extend({}, defaults, opt);
var geocoder;
// popup lightbox generation
if(options._action=='lightbox'){
var cur_window_top = parseInt($(window).scrollTop()) + 50;
$('.evo_popin').css({'margin-top':cur_window_top});
$('.evo_pop_body').html('');
var event_list = this.closest('.eventon_events_list');
var content = this.siblings('.event_description').html();
var content_front = this.html();
var _content = $(content).not('.evcal_close');
// RTL
if(event_list.hasClass('evortl')){
$('.evo_popin').addClass('evortl');
}
$('.evo_pop_body').append('<div class="evopop_top">'+content_front+'</div>').append(_content);
var this_map = $('.evo_pop_body').find('.evcal_gmaps');
var idd = this_map.attr('id');
this_map.attr({'id':idd+'_evop'});
$('.evo_popup').fadeIn(300);
$('.evo_popbg').fadeIn(300);
// check if gmaps should run
if( this.attr('data-gmtrig')=='1' && this.attr('data-gmap_status')!='null'){
var cal = this.closest('div.ajde_evcal_calendar ');
loadl_gmaps_in(this, cal, idd+'_evop');
}
}
// functions
if(options.fnt==1){
this.each(function(){
var eventcard = $(this).attr('eventcard');
if(eventcard=='1'){
$(this).find('a.desc_trig').each(function(elm){
//$(this).siblings('.event_description').slideDown();
var obj = $(this);
if(options.delay==0){
load_googlemaps_here(obj);
}else{
setTimeout(load_googlemaps_here, options.delay, obj);
}
});
}
});
}
if(options.fnt==2){
if(options.delay==0){
load_googlemaps_here(this);
}else{
setTimeout(load_googlemaps_here, options.delay, this);
}
}
if(options.fnt==3){
loadl_gmaps_in(this, options.cal, '');
}
// gmaps on popup
if(options.fnt==4){
// check if gmaps should run
if( this.attr('data-gmtrig')=='1' && this.attr('data-gmap_status')!='null'){
var cal = this.closest('div.ajde_evcal_calendar ');
loadl_gmaps_in(this, cal, options.mapSpotId);
}
}
// function to load google maps for eventcard
function load_googlemaps_here(obj){
if( obj.data('gmstat')!= '1'){
obj.attr({'data-gmstat':'1'});
}
var cal = obj.closest('div.ajde_evcal_calendar ');
if( obj.attr('data-gmtrig')=='1' && obj.attr('data-gmap_status')!='null'){
loadl_gmaps_in(obj, cal, '');
}
}
// Load the google map on the object
function loadl_gmaps_in(obj, cal, mapId){
var evodata = cal.find('.evo-data');
var mapformat = evodata.data('mapformat');
var ev_location = obj.find('.evcal_desc');
var location_type = ev_location.attr('data-location_type');
if(location_type=='address'){
var address = ev_location.attr('data-location_address');
var location_type = 'add';
}else{
var address = ev_location.attr('data-latlng');
var location_type = 'latlng';
}
var map_canvas_id= (mapId!=='')?
mapId:
obj.siblings('.event_description').find('.evcal_gmaps').attr('id');
// google maps styles
// @since 2.2.22
var styles = '';
if(gmapstyles != 'default'){
styles = $.parseJSON(gmapstyles);
}
var zoom = evodata.data('mapzoom');
var zoomlevel = (typeof zoom !== 'undefined' && zoom !== false)? parseInt(zoom):12;
var scroll = evodata.data('mapscroll');
//console.log(map_canvas_id+' '+mapformat+' '+ location_type +' '+scroll +' '+ address);
//obj.siblings('.event_description').find('.evcal_gmaps').html(address);
initialize(map_canvas_id, address, mapformat, zoomlevel, location_type, scroll, styles);
}
//console.log(options);
};
}(jQuery)); | sabdev1/sabhoa | wp-content/plugins/eventON/assets/js/maps/eventon_gen_maps.js | JavaScript | gpl-2.0 | 4,157 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_admin
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Script file of Joomla CMS
*
* @since 1.6.4
*/
class JoomlaInstallerScript
{
/**
* Method to update Joomla!
*
* @param JInstallerAdapterFile $installer The class calling this method
*
* @return void
*/
public function update($installer)
{
$options['format'] = '{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}';
$options['text_file'] = 'joomla_update.php';
JLog::addLogger($options, JLog::INFO, array('Update', 'databasequery', 'jerror'));
JLog::add(JText::_('COM_JOOMLAUPDATE_UPDATE_LOG_DELETE_FILES'), JLog::INFO, 'Update');
// This needs to stay for 2.5 update compatibility
$this->deleteUnexistingFiles();
$this->updateManifestCaches();
$this->updateDatabase();
$this->clearRadCache();
$this->updateAssets();
$this->clearStatsCache();
$this->convertTablesToUtf8mb4(true);
$this->cleanJoomlaCache();
// VERY IMPORTANT! THIS METHOD SHOULD BE CALLED LAST, SINCE IT COULD
// LOGOUT ALL THE USERS
$this->flushSessions();
}
/**
* Method to clear our stats plugin cache to ensure we get fresh data on Joomla Update
*
* @return void
*
* @since 3.5
*/
protected function clearStatsCache()
{
$db = JFactory::getDbo();
try
{
// Get the params for the stats plugin
$params = $db->setQuery(
$db->getQuery(true)
->select($db->quoteName('params'))
->from($db->quoteName('#__extensions'))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('stats'))
)->loadResult();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
$params = json_decode($params, true);
// Reset the last run parameter
if (isset($params['lastrun']))
{
$params['lastrun'] = '';
}
$params = json_encode($params);
$query = $db->getQuery(true)
->update($db->quoteName('#__extensions'))
->set($db->quoteName('params') . ' = ' . $db->quote($params))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('stats'));
try
{
$db->setQuery($query)->execute();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
}
/**
* Method to update Database
*
* @return void
*/
protected function updateDatabase()
{
$db = JFactory::getDbo();
if (strpos($db->name, 'mysql') !== false)
{
$this->updateDatabaseMysql();
}
$this->uninstallEosPlugin();
}
/**
* Method to update MySQL Database
*
* @return void
*/
protected function updateDatabaseMysql()
{
$db = JFactory::getDbo();
$db->setQuery('SHOW ENGINES');
try
{
$results = $db->loadObjectList();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
foreach ($results as $result)
{
if ($result->Support != 'DEFAULT')
{
continue;
}
$db->setQuery('ALTER TABLE #__update_sites_extensions ENGINE = ' . $result->Engine);
try
{
$db->execute();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
break;
}
}
/**
* Uninstall the 2.5 EOS plugin
*
* @return void
*/
protected function uninstallEosPlugin()
{
$db = JFactory::getDbo();
// Check if the 2.5 EOS plugin is present and uninstall it if so
$id = $db->setQuery(
$db->getQuery(true)
->select('extension_id')
->from('#__extensions')
->where('name = ' . $db->quote('PLG_EOSNOTIFY'))
)->loadResult();
if (!$id)
{
return;
}
// We need to unprotect the plugin so we can uninstall it
$db->setQuery(
$db->getQuery(true)
->update('#__extensions')
->set('protected = 0')
->where($db->quoteName('extension_id') . ' = ' . $id)
)->execute();
$installer = new JInstaller;
$installer->uninstall('plugin', $id);
}
/**
* Update the manifest caches
*
* @return void
*/
protected function updateManifestCaches()
{
$extensions = array(
// Components
// `type`, `element`, `folder`, `client_id`
array('component', 'com_mailto', '', 0),
array('component', 'com_wrapper', '', 0),
array('component', 'com_admin', '', 1),
array('component', 'com_ajax', '', 1),
array('component', 'com_banners', '', 1),
array('component', 'com_cache', '', 1),
array('component', 'com_categories', '', 1),
array('component', 'com_checkin', '', 1),
array('component', 'com_contact', '', 1),
array('component', 'com_cpanel', '', 1),
array('component', 'com_installer', '', 1),
array('component', 'com_languages', '', 1),
array('component', 'com_login', '', 1),
array('component', 'com_media', '', 1),
array('component', 'com_menus', '', 1),
array('component', 'com_messages', '', 1),
array('component', 'com_modules', '', 1),
array('component', 'com_newsfeeds', '', 1),
array('component', 'com_plugins', '', 1),
array('component', 'com_search', '', 1),
array('component', 'com_templates', '', 1),
array('component', 'com_content', '', 1),
array('component', 'com_config', '', 1),
array('component', 'com_redirect', '', 1),
array('component', 'com_users', '', 1),
array('component', 'com_finder', '', 1),
array('component', 'com_tags', '', 1),
array('component', 'com_contenthistory', '', 1),
array('component', 'com_postinstall', '', 1),
array('component', 'com_joomlaupdate', '', 1),
// Libraries
array('library', 'phputf8', '', 0),
array('library', 'joomla', '', 0),
array('library', 'idna_convert', '', 0),
array('library', 'fof', '', 0),
array('library', 'phpass', '', 0),
// Modules
// - Site
array('module', 'mod_articles_archive', '', 0),
array('module', 'mod_articles_latest', '', 0),
array('module', 'mod_articles_popular', '', 0),
array('module', 'mod_banners', '', 0),
array('module', 'mod_breadcrumbs', '', 0),
array('module', 'mod_custom', '', 0),
array('module', 'mod_feed', '', 0),
array('module', 'mod_footer', '', 0),
array('module', 'mod_login', '', 0),
array('module', 'mod_menu', '', 0),
array('module', 'mod_articles_news', '', 0),
array('module', 'mod_random_image', '', 0),
array('module', 'mod_related_items', '', 0),
array('module', 'mod_search', '', 0),
array('module', 'mod_stats', '', 0),
array('module', 'mod_syndicate', '', 0),
array('module', 'mod_users_latest', '', 0),
array('module', 'mod_whosonline', '', 0),
array('module', 'mod_wrapper', '', 0),
array('module', 'mod_articles_category', '', 0),
array('module', 'mod_articles_categories', '', 0),
array('module', 'mod_languages', '', 0),
array('module', 'mod_tags_popular', '', 0),
array('module', 'mod_tags_similar', '', 0),
// - Administrator
array('module', 'mod_custom', '', 1),
array('module', 'mod_feed', '', 1),
array('module', 'mod_latest', '', 1),
array('module', 'mod_logged', '', 1),
array('module', 'mod_login', '', 1),
array('module', 'mod_menu', '', 1),
array('module', 'mod_popular', '', 1),
array('module', 'mod_quickicon', '', 1),
array('module', 'mod_stats_admin', '', 1),
array('module', 'mod_status', '', 1),
array('module', 'mod_submenu', '', 1),
array('module', 'mod_title', '', 1),
array('module', 'mod_toolbar', '', 1),
array('module', 'mod_multilangstatus', '', 1),
// Plugins
array('plugin', 'gmail', 'authentication', 0),
array('plugin', 'joomla', 'authentication', 0),
array('plugin', 'ldap', 'authentication', 0),
array('plugin', 'contact', 'content', 0),
array('plugin', 'emailcloak', 'content', 0),
array('plugin', 'loadmodule', 'content', 0),
array('plugin', 'pagebreak', 'content', 0),
array('plugin', 'pagenavigation', 'content', 0),
array('plugin', 'vote', 'content', 0),
array('plugin', 'codemirror', 'editors', 0),
array('plugin', 'none', 'editors', 0),
array('plugin', 'tinymce', 'editors', 0),
array('plugin', 'article', 'editors-xtd', 0),
array('plugin', 'image', 'editors-xtd', 0),
array('plugin', 'pagebreak', 'editors-xtd', 0),
array('plugin', 'readmore', 'editors-xtd', 0),
array('plugin', 'categories', 'search', 0),
array('plugin', 'contacts', 'search', 0),
array('plugin', 'content', 'search', 0),
array('plugin', 'newsfeeds', 'search', 0),
array('plugin', 'tags', 'search', 0),
array('plugin', 'languagefilter', 'system', 0),
array('plugin', 'p3p', 'system', 0),
array('plugin', 'cache', 'system', 0),
array('plugin', 'debug', 'system', 0),
array('plugin', 'log', 'system', 0),
array('plugin', 'redirect', 'system', 0),
array('plugin', 'remember', 'system', 0),
array('plugin', 'sef', 'system', 0),
array('plugin', 'logout', 'system', 0),
array('plugin', 'contactcreator', 'user', 0),
array('plugin', 'joomla', 'user', 0),
array('plugin', 'profile', 'user', 0),
array('plugin', 'joomla', 'extension', 0),
array('plugin', 'joomla', 'content', 0),
array('plugin', 'languagecode', 'system', 0),
array('plugin', 'joomlaupdate', 'quickicon', 0),
array('plugin', 'extensionupdate', 'quickicon', 0),
array('plugin', 'recaptcha', 'captcha', 0),
array('plugin', 'categories', 'finder', 0),
array('plugin', 'contacts', 'finder', 0),
array('plugin', 'content', 'finder', 0),
array('plugin', 'newsfeeds', 'finder', 0),
array('plugin', 'tags', 'finder', 0),
array('plugin', 'totp', 'twofactorauth', 0),
array('plugin', 'yubikey', 'twofactorauth', 0),
array('plugin', 'updatenotification', 'system', 0),
array('plugin', 'module', 'editors-xtd', 0),
array('plugin', 'stats', 'system', 0),
array('plugin', 'packageinstaller', 'installer', 0),
array('plugin', 'folderinstaller', 'installer', 0),
array('plugin', 'urlinstaller', 'installer', 0),
array('plugin', 'phpversioncheck', 'quickicon', 0),
array('plugin', 'menu', 'editors-xtd', 0),
array('plugin', 'contact', 'editors-xtd', 0),
// Templates
array('template', 'beez3', '', 0),
array('template', 'hathor', '', 1),
array('template', 'protostar', '', 0),
array('template', 'isis', '', 1),
// Languages
array('language', 'en-GB', '', 0),
array('language', 'en-GB', '', 1),
// Files
array('file', 'joomla', '', 0),
// Packages
array('package', 'pkg_en-GB', '', 0),
);
// Attempt to refresh manifest caches
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__extensions');
foreach ($extensions as $extension)
{
$query->where(
'type=' . $db->quote($extension[0])
. ' AND element=' . $db->quote($extension[1])
. ' AND folder=' . $db->quote($extension[2])
. ' AND client_id=' . $extension[3], 'OR'
);
}
$db->setQuery($query);
try
{
$extensions = $db->loadObjectList();
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return;
}
$installer = new JInstaller;
foreach ($extensions as $extension)
{
if (!$installer->refreshManifestCache($extension->extension_id))
{
echo JText::sprintf('FILES_JOOMLA_ERROR_MANIFEST', $extension->type, $extension->element, $extension->name, $extension->client_id) . '<br />';
}
}
}
/**
* Delete files that should not exist
*
* @return void
*/
public function deleteUnexistingFiles()
{
$files = array(
// Joomla 1.6 - 1.7 - 2.5
'/libraries/cms/cmsloader.php',
'/libraries/joomla/database/databaseexception.php',
'/libraries/joomla/database/databasequery.php',
'/libraries/joomla/environment/response.php',
'/libraries/joomla/form/fields/templatestyle.php',
'/libraries/joomla/form/fields/user.php',
'/libraries/joomla/form/fields/menu.php',
'/libraries/joomla/form/fields/helpsite.php',
'/libraries/joomla/github/gists.php',
'/libraries/joomla/github/issues.php',
'/libraries/joomla/github/pulls.php',
'/libraries/joomla/log/logentry.php',
'/administrator/components/com_admin/sql/updates/mysql/1.7.0.sql',
'/administrator/components/com_admin/sql/updates/sqlsrv/2.5.2-2012-03-05.sql',
'/administrator/components/com_admin/sql/updates/sqlsrv/2.5.3-2012-03-13.sql',
'/administrator/components/com_admin/sql/updates/sqlsrv/index.html',
'/administrator/components/com_content/models/fields/filters.php',
'/administrator/components/com_users/controllers/config.php',
'/administrator/components/com_users/helpers/levels.php',
'/administrator/language/en-GB/en-GB.plg_system_finder.ini',
'/administrator/language/en-GB/en-GB.plg_system_finder.sys.ini',
'/administrator/modules/mod_quickicon/tmpl/default_button.php',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/print/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/save/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/editor_plugin_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/editor_template_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/editor_template_src.js',
'/media/editors/tinymce/jscripts/tiny_mce/tiny_mce_src.js',
'/media/com_finder/images/calendar.png',
'/media/com_finder/images/mime/index.html',
'/media/com_finder/images/mime/pdf.png',
'/components/com_media/controller.php',
'/components/com_media/helpers/index.html',
'/components/com_media/helpers/media.php',
// Joomla 3.0
'/administrator/components/com_admin/sql/updates/mysql/1.7.0-2011-06-06-2.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.0-2011-06-06.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.0.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-2.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-3.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15-4.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-15.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-17.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.1-2011-09-20.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-10-15.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-10-19.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.3-2011-11-10.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-11-19.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-11-23.sql',
'/administrator/components/com_admin/sql/updates/mysql/1.7.4-2011-12-12.sql',
'/administrator/components/com_admin/views/sysinfo/tmpl/default_navigation.php',
'/administrator/components/com_categories/config.xml',
'/administrator/components/com_categories/helpers/categoriesadministrator.php',
'/administrator/components/com_contact/elements/contact.php',
'/administrator/components/com_contact/elements/index.html',
'/administrator/components/com_content/elements/article.php',
'/administrator/components/com_content/elements/author.php',
'/administrator/components/com_content/elements/index.html',
'/administrator/components/com_installer/models/fields/client.php',
'/administrator/components/com_installer/models/fields/group.php',
'/administrator/components/com_installer/models/fields/index.html',
'/administrator/components/com_installer/models/fields/search.php',
'/administrator/components/com_installer/models/forms/index.html',
'/administrator/components/com_installer/models/forms/manage.xml',
'/administrator/components/com_installer/views/install/tmpl/default_form.php',
'/administrator/components/com_installer/views/manage/tmpl/default_filter.php',
'/administrator/components/com_languages/views/installed/tmpl/default_ftp.php',
'/administrator/components/com_languages/views/installed/tmpl/default_navigation.php',
'/administrator/components/com_modules/models/fields/index.html',
'/administrator/components/com_modules/models/fields/moduleorder.php',
'/administrator/components/com_modules/models/fields/moduleposition.php',
'/administrator/components/com_newsfeeds/elements/index.html',
'/administrator/components/com_newsfeeds/elements/newsfeed.php',
'/administrator/components/com_templates/views/prevuuw/index.html',
'/administrator/components/com_templates/views/prevuuw/tmpl/default.php',
'/administrator/components/com_templates/views/prevuuw/tmpl/index.html',
'/administrator/components/com_templates/views/prevuuw/view.html.php',
'/administrator/includes/menu.php',
'/administrator/includes/router.php',
'/administrator/manifests/packages/pkg_joomla.xml',
'/administrator/modules/mod_submenu/helper.php',
'/administrator/templates/hathor/css/ie6.css',
'/administrator/templates/hathor/html/mod_submenu/index.html',
'/administrator/templates/hathor/html/mod_submenu/default.php',
'/components/com_media/controller.php',
'/components/com_media/helpers/index.html',
'/components/com_media/helpers/media.php',
'/includes/menu.php',
'/includes/pathway.php',
'/includes/router.php',
'/language/en-GB/en-GB.pkg_joomla.sys.ini',
'/libraries/cms/controller/index.html',
'/libraries/cms/controller/legacy.php',
'/libraries/cms/model/index.html',
'/libraries/cms/model/legacy.php',
'/libraries/cms/schema/changeitemmysql.php',
'/libraries/cms/schema/changeitemsqlazure.php',
'/libraries/cms/schema/changeitemsqlsrv.php',
'/libraries/cms/view/index.html',
'/libraries/cms/view/legacy.php',
'/libraries/joomla/application/application.php',
'/libraries/joomla/application/categories.php',
'/libraries/joomla/application/cli/daemon.php',
'/libraries/joomla/application/cli/index.html',
'/libraries/joomla/application/component/controller.php',
'/libraries/joomla/application/component/controlleradmin.php',
'/libraries/joomla/application/component/controllerform.php',
'/libraries/joomla/application/component/helper.php',
'/libraries/joomla/application/component/index.html',
'/libraries/joomla/application/component/model.php',
'/libraries/joomla/application/component/modeladmin.php',
'/libraries/joomla/application/component/modelform.php',
'/libraries/joomla/application/component/modelitem.php',
'/libraries/joomla/application/component/modellist.php',
'/libraries/joomla/application/component/view.php',
'/libraries/joomla/application/helper.php',
'/libraries/joomla/application/input.php',
'/libraries/joomla/application/input/cli.php',
'/libraries/joomla/application/input/cookie.php',
'/libraries/joomla/application/input/files.php',
'/libraries/joomla/application/input/index.html',
'/libraries/joomla/application/menu.php',
'/libraries/joomla/application/module/helper.php',
'/libraries/joomla/application/module/index.html',
'/libraries/joomla/application/pathway.php',
'/libraries/joomla/application/web/webclient.php',
'/libraries/joomla/base/node.php',
'/libraries/joomla/base/object.php',
'/libraries/joomla/base/observable.php',
'/libraries/joomla/base/observer.php',
'/libraries/joomla/base/tree.php',
'/libraries/joomla/cache/storage/eaccelerator.php',
'/libraries/joomla/cache/storage/helpers/helper.php',
'/libraries/joomla/cache/storage/helpers/index.html',
'/libraries/joomla/database/database/index.html',
'/libraries/joomla/database/database/mysql.php',
'/libraries/joomla/database/database/mysqlexporter.php',
'/libraries/joomla/database/database/mysqli.php',
'/libraries/joomla/database/database/mysqliexporter.php',
'/libraries/joomla/database/database/mysqliimporter.php',
'/libraries/joomla/database/database/mysqlimporter.php',
'/libraries/joomla/database/database/mysqliquery.php',
'/libraries/joomla/database/database/mysqlquery.php',
'/libraries/joomla/database/database/sqlazure.php',
'/libraries/joomla/database/database/sqlazurequery.php',
'/libraries/joomla/database/database/sqlsrv.php',
'/libraries/joomla/database/database/sqlsrvquery.php',
'/libraries/joomla/database/exception.php',
'/libraries/joomla/database/table.php',
'/libraries/joomla/database/table/asset.php',
'/libraries/joomla/database/table/category.php',
'/libraries/joomla/database/table/content.php',
'/libraries/joomla/database/table/extension.php',
'/libraries/joomla/database/table/index.html',
'/libraries/joomla/database/table/language.php',
'/libraries/joomla/database/table/menu.php',
'/libraries/joomla/database/table/menutype.php',
'/libraries/joomla/database/table/module.php',
'/libraries/joomla/database/table/session.php',
'/libraries/joomla/database/table/update.php',
'/libraries/joomla/database/table/user.php',
'/libraries/joomla/database/table/usergroup.php',
'/libraries/joomla/database/table/viewlevel.php',
'/libraries/joomla/database/tablenested.php',
'/libraries/joomla/environment/request.php',
'/libraries/joomla/environment/uri.php',
'/libraries/joomla/error/error.php',
'/libraries/joomla/error/exception.php',
'/libraries/joomla/error/index.html',
'/libraries/joomla/error/log.php',
'/libraries/joomla/error/profiler.php',
'/libraries/joomla/filesystem/archive.php',
'/libraries/joomla/filesystem/archive/bzip2.php',
'/libraries/joomla/filesystem/archive/gzip.php',
'/libraries/joomla/filesystem/archive/index.html',
'/libraries/joomla/filesystem/archive/tar.php',
'/libraries/joomla/filesystem/archive/zip.php',
'/libraries/joomla/form/fields/category.php',
'/libraries/joomla/form/fields/componentlayout.php',
'/libraries/joomla/form/fields/contentlanguage.php',
'/libraries/joomla/form/fields/editor.php',
'/libraries/joomla/form/fields/editors.php',
'/libraries/joomla/form/fields/media.php',
'/libraries/joomla/form/fields/menuitem.php',
'/libraries/joomla/form/fields/modulelayout.php',
'/libraries/joomla/html/editor.php',
'/libraries/joomla/html/html/access.php',
'/libraries/joomla/html/html/batch.php',
'/libraries/joomla/html/html/behavior.php',
'/libraries/joomla/html/html/category.php',
'/libraries/joomla/html/html/content.php',
'/libraries/joomla/html/html/contentlanguage.php',
'/libraries/joomla/html/html/date.php',
'/libraries/joomla/html/html/email.php',
'/libraries/joomla/html/html/form.php',
'/libraries/joomla/html/html/grid.php',
'/libraries/joomla/html/html/image.php',
'/libraries/joomla/html/html/index.html',
'/libraries/joomla/html/html/jgrid.php',
'/libraries/joomla/html/html/list.php',
'/libraries/joomla/html/html/menu.php',
'/libraries/joomla/html/html/number.php',
'/libraries/joomla/html/html/rules.php',
'/libraries/joomla/html/html/select.php',
'/libraries/joomla/html/html/sliders.php',
'/libraries/joomla/html/html/string.php',
'/libraries/joomla/html/html/tabs.php',
'/libraries/joomla/html/html/tel.php',
'/libraries/joomla/html/html/user.php',
'/libraries/joomla/html/pagination.php',
'/libraries/joomla/html/pane.php',
'/libraries/joomla/html/parameter.php',
'/libraries/joomla/html/parameter/element.php',
'/libraries/joomla/html/parameter/element/calendar.php',
'/libraries/joomla/html/parameter/element/category.php',
'/libraries/joomla/html/parameter/element/componentlayouts.php',
'/libraries/joomla/html/parameter/element/contentlanguages.php',
'/libraries/joomla/html/parameter/element/editors.php',
'/libraries/joomla/html/parameter/element/filelist.php',
'/libraries/joomla/html/parameter/element/folderlist.php',
'/libraries/joomla/html/parameter/element/helpsites.php',
'/libraries/joomla/html/parameter/element/hidden.php',
'/libraries/joomla/html/parameter/element/imagelist.php',
'/libraries/joomla/html/parameter/element/index.html',
'/libraries/joomla/html/parameter/element/languages.php',
'/libraries/joomla/html/parameter/element/list.php',
'/libraries/joomla/html/parameter/element/menu.php',
'/libraries/joomla/html/parameter/element/menuitem.php',
'/libraries/joomla/html/parameter/element/modulelayouts.php',
'/libraries/joomla/html/parameter/element/password.php',
'/libraries/joomla/html/parameter/element/radio.php',
'/libraries/joomla/html/parameter/element/spacer.php',
'/libraries/joomla/html/parameter/element/sql.php',
'/libraries/joomla/html/parameter/element/templatestyle.php',
'/libraries/joomla/html/parameter/element/text.php',
'/libraries/joomla/html/parameter/element/textarea.php',
'/libraries/joomla/html/parameter/element/timezones.php',
'/libraries/joomla/html/parameter/element/usergroup.php',
'/libraries/joomla/html/parameter/index.html',
'/libraries/joomla/html/toolbar.php',
'/libraries/joomla/html/toolbar/button.php',
'/libraries/joomla/html/toolbar/button/confirm.php',
'/libraries/joomla/html/toolbar/button/custom.php',
'/libraries/joomla/html/toolbar/button/help.php',
'/libraries/joomla/html/toolbar/button/index.html',
'/libraries/joomla/html/toolbar/button/link.php',
'/libraries/joomla/html/toolbar/button/popup.php',
'/libraries/joomla/html/toolbar/button/separator.php',
'/libraries/joomla/html/toolbar/button/standard.php',
'/libraries/joomla/html/toolbar/index.html',
'/libraries/joomla/image/filters/brightness.php',
'/libraries/joomla/image/filters/contrast.php',
'/libraries/joomla/image/filters/edgedetect.php',
'/libraries/joomla/image/filters/emboss.php',
'/libraries/joomla/image/filters/grayscale.php',
'/libraries/joomla/image/filters/index.html',
'/libraries/joomla/image/filters/negate.php',
'/libraries/joomla/image/filters/sketchy.php',
'/libraries/joomla/image/filters/smooth.php',
'/libraries/joomla/language/help.php',
'/libraries/joomla/language/latin_transliterate.php',
'/libraries/joomla/log/logexception.php',
'/libraries/joomla/log/loggers/database.php',
'/libraries/joomla/log/loggers/echo.php',
'/libraries/joomla/log/loggers/formattedtext.php',
'/libraries/joomla/log/loggers/index.html',
'/libraries/joomla/log/loggers/messagequeue.php',
'/libraries/joomla/log/loggers/syslog.php',
'/libraries/joomla/log/loggers/w3c.php',
'/libraries/joomla/methods.php',
'/libraries/joomla/session/storage/eaccelerator.php',
'/libraries/joomla/string/stringnormalize.php',
'/libraries/joomla/utilities/date.php',
'/libraries/joomla/utilities/simplecrypt.php',
'/libraries/joomla/utilities/simplexml.php',
'/libraries/joomla/utilities/string.php',
'/libraries/joomla/utilities/xmlelement.php',
'/media/plg_quickicon_extensionupdate/extensionupdatecheck.js',
'/media/plg_quickicon_joomlaupdate/jupdatecheck.js',
// Joomla! 3.1
'/libraries/joomla/application/router.php',
'/libraries/joomla/form/rules/boolean.php',
'/libraries/joomla/form/rules/color.php',
'/libraries/joomla/form/rules/email.php',
'/libraries/joomla/form/rules/equals.php',
'/libraries/joomla/form/rules/index.html',
'/libraries/joomla/form/rules/options.php',
'/libraries/joomla/form/rules/rules.php',
'/libraries/joomla/form/rules/tel.php',
'/libraries/joomla/form/rules/url.php',
'/libraries/joomla/form/rules/username.php',
'/libraries/joomla/html/access.php',
'/libraries/joomla/html/behavior.php',
'/libraries/joomla/html/content.php',
'/libraries/joomla/html/date.php',
'/libraries/joomla/html/email.php',
'/libraries/joomla/html/form.php',
'/libraries/joomla/html/grid.php',
'/libraries/joomla/html/html.php',
'/libraries/joomla/html/index.html',
'/libraries/joomla/html/jgrid.php',
'/libraries/joomla/html/list.php',
'/libraries/joomla/html/number.php',
'/libraries/joomla/html/rules.php',
'/libraries/joomla/html/select.php',
'/libraries/joomla/html/sliders.php',
'/libraries/joomla/html/string.php',
'/libraries/joomla/html/tabs.php',
'/libraries/joomla/html/tel.php',
'/libraries/joomla/html/user.php',
'/libraries/joomla/html/language/index.html',
'/libraries/joomla/html/language/en-GB/en-GB.jhtmldate.ini',
'/libraries/joomla/html/language/en-GB/index.html',
'/libraries/joomla/installer/adapters/component.php',
'/libraries/joomla/installer/adapters/file.php',
'/libraries/joomla/installer/adapters/index.html',
'/libraries/joomla/installer/adapters/language.php',
'/libraries/joomla/installer/adapters/library.php',
'/libraries/joomla/installer/adapters/module.php',
'/libraries/joomla/installer/adapters/package.php',
'/libraries/joomla/installer/adapters/plugin.php',
'/libraries/joomla/installer/adapters/template.php',
'/libraries/joomla/installer/extension.php',
'/libraries/joomla/installer/helper.php',
'/libraries/joomla/installer/index.html',
'/libraries/joomla/installer/librarymanifest.php',
'/libraries/joomla/installer/packagemanifest.php',
'/libraries/joomla/pagination/index.html',
'/libraries/joomla/pagination/object.php',
'/libraries/joomla/pagination/pagination.php',
'/libraries/legacy/html/contentlanguage.php',
'/libraries/legacy/html/index.html',
'/libraries/legacy/html/menu.php',
'/libraries/legacy/menu/index.html',
'/libraries/legacy/menu/menu.php',
'/libraries/legacy/pathway/index.html',
'/libraries/legacy/pathway/pathway.php',
'/media/system/css/mooRainbow.css',
'/media/system/js/mooRainbow-uncompressed.js',
'/media/system/js/mooRainbow.js',
'/media/system/js/swf-uncompressed.js',
'/media/system/js/swf.js',
'/media/system/js/uploader-uncompressed.js',
'/media/system/js/uploader.js',
'/media/system/swf/index.html',
'/media/system/swf/uploader.swf',
// Joomla! 3.2
'/administrator/components/com_contact/models/fields/modal/contacts.php',
'/administrator/components/com_newsfeeds/models/fields/modal/newsfeeds.php',
'/libraries/idna_convert/example.php',
'/media/editors/tinymce/jscripts/tiny_mce/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/license.txt',
'/media/editors/tinymce/jscripts/tiny_mce/tiny_mce.js',
'/media/editors/tinymce/jscripts/tiny_mce/tiny_mce_popup.js',
'/media/editors/tinymce/jscripts/tiny_mce/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/rule.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/css/advhr.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/js/rule.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advhr/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/css/advimage.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/img/sample.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/js/image.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advimage/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/css/advlink.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/js/advlink.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlink/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/advlist/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autolink/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autoresize/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/autosave/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/bbcode/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/editable_selects.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/form_utils.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/mctabs.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/tiny_mce_popup.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/compat3x/validate.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/contextmenu/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/directionality/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/emotions.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-cool.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-cry.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-embarassed.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-foot-in-mouth.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-frown.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-innocent.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-kiss.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-laughing.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-money-mouth.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-sealed.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-smile.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-surprised.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-tongue-out.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-undecided.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-wink.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/img/smiley-yell.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/js/emotions.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/emotions/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/fullpage.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/css/fullpage.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/js/fullpage.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullpage/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/fullscreen/fullscreen.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/iespell/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/template.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/window.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/alert.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/button.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/confirm.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/corners.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/horizontal.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/inlinepopups/skins/clearlooks2/img/vertical.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/insertdatetime/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/layer/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/lists/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/media.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/moxieplayer.swf',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/css/media.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/embed.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/js/media.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/media/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/nonbreaking/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/noneditable/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/pagebreak/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/pastetext.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/pastetext.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/pastetext.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/js/pasteword.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/paste/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/example.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/preview.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/jscripts/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/preview/jscripts/embed.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/print/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/print/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/save/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/save/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/searchreplace.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/css/searchreplace.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/js/searchreplace.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/searchreplace/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/css/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/spellchecker/img/wline.gif',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/props.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/readme.txt',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/css/props.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/js/props.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/style/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/tabfocus/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/cell.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/merge_cells.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/row.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/table.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/cell.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/row.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/css/table.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/cell.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/merge_cells.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/row.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/js/table.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/table/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/blank.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/template.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/css/template.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/js/template.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/template/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualblocks/css/visualblocks.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/visualchars/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/wordcount/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/abbr.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/acronym.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/attributes.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/cite.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/del.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/editor_plugin.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/ins.htm',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/attributes.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/css/popup.css',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/abbr.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/acronym.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/attributes.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/cite.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/del.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/element_common.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/js/ins.js',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/about.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/anchor.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/charmap.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/color_picker.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/editor_template.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/image.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/link.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/shortcuts.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/source_editor.htm',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/colorpicker.jpg',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/flash.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/icons.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/iframe.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/pagebreak.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/quicktime.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/realmedia.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/shockwave.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/trans.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/video.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/img/windowsmedia.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/about.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/anchor.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/charmap.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/color_picker.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/image.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/link.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/js/source_editor.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/langs/en_dlg.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/dialog.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/buttons.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/items.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/menu_arrow.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/menu_check.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/progress.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/default/img/tabs.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/dialog.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/highcontrast/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/dialog.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui_black.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/ui_silver.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg_black.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/advanced/skins/o2k7/img/button_bg_silver.png',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/editor_template.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/img/icons.gif',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/langs/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/langs/en.js',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/default/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/content.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/ui.css',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/img/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/themes/simple/skins/o2k7/img/button_bg.png',
'/media/editors/tinymce/jscripts/tiny_mce/utils/index.html',
'/media/editors/tinymce/jscripts/tiny_mce/utils/editable_selects.js',
'/media/editors/tinymce/jscripts/tiny_mce/utils/form_utils.js',
'/media/editors/tinymce/jscripts/tiny_mce/utils/mctabs.js',
'/media/editors/tinymce/jscripts/tiny_mce/utils/validate.js',
'/administrator/components/com_banners/models/fields/ordering.php',
'/administrator/components/com_contact/models/fields/ordering.php',
'/administrator/components/com_newsfeeds/models/fields/ordering.php',
'/administrator/components/com_plugins/models/fields/ordering.php',
'/administrator/components/com_weblinks/models/fields/ordering.php',
'/administrator/includes/application.php',
'/includes/application.php',
'/libraries/legacy/application/helper.php',
'/libraries/joomla/plugin/helper.php',
'/libraries/joomla/plugin/index.html',
'/libraries/joomla/plugin/plugin.php',
'/libraries/legacy/component/helper.php',
'/libraries/legacy/component/index.html',
'/libraries/legacy/module/helper.php',
'/libraries/legacy/module/index.html',
'/administrator/components/com_templates/controllers/source.php',
'/administrator/components/com_templates/models/source.php',
'/administrator/components/com_templates/views/source/index.html',
'/administrator/components/com_templates/views/source/tmpl/edit.php',
'/administrator/components/com_templates/views/source/tmpl/edit_ftp.php',
'/administrator/components/com_templates/views/source/tmpl/index.html',
'/administrator/components/com_templates/views/source/view.html.php',
'/media/editors/codemirror/css/csscolors.css',
'/media/editors/codemirror/css/jscolors.css',
'/media/editors/codemirror/css/phpcolors.css',
'/media/editors/codemirror/css/sparqlcolors.css',
'/media/editors/codemirror/css/xmlcolors.css',
'/media/editors/codemirror/js/basefiles-uncompressed.js',
'/media/editors/codemirror/js/basefiles.js',
'/media/editors/codemirror/js/codemirror-uncompressed.js',
'/media/editors/codemirror/js/editor.js',
'/media/editors/codemirror/js/highlight.js',
'/media/editors/codemirror/js/mirrorframe.js',
'/media/editors/codemirror/js/parsecss.js',
'/media/editors/codemirror/js/parsedummy.js',
'/media/editors/codemirror/js/parsehtmlmixed.js',
'/media/editors/codemirror/js/parsejavascript.js',
'/media/editors/codemirror/js/parsephp.js',
'/media/editors/codemirror/js/parsephphtmlmixed.js',
'/media/editors/codemirror/js/parsesparql.js',
'/media/editors/codemirror/js/parsexml.js',
'/media/editors/codemirror/js/select.js',
'/media/editors/codemirror/js/stringstream.js',
'/media/editors/codemirror/js/tokenize.js',
'/media/editors/codemirror/js/tokenizejavascript.js',
'/media/editors/codemirror/js/tokenizephp.js',
'/media/editors/codemirror/js/undo.js',
'/media/editors/codemirror/js/util.js',
'/administrator/components/com_weblinks/models/fields/index.html',
'/plugins/user/joomla/postinstall/actions.php',
'/plugins/user/joomla/postinstall/index.html',
'/media/com_finder/js/finder.js',
'/media/com_finder/js/highlighter.js',
'/libraries/joomla/registry/format.php',
'/libraries/joomla/registry/index.html',
'/libraries/joomla/registry/registry.php',
'/libraries/joomla/registry/format/index.html',
'/libraries/joomla/registry/format/ini.php',
'/libraries/joomla/registry/format/json.php',
'/libraries/joomla/registry/format/php.php',
'/libraries/joomla/registry/format/xml.php',
// Joomla 3.3.1
'/administrator/templates/isis/html/message.php',
// Joomla 3.3.6
'/media/editors/tinymce/plugins/compat3x/editable_selects.js',
'/media/editors/tinymce/plugins/compat3x/form_utils.js',
'/media/editors/tinymce/plugins/compat3x/mctabs.js',
'/media/editors/tinymce/plugins/compat3x/tiny_mce_popup.js',
'/media/editors/tinymce/plugins/compat3x/validate.js',
// Joomla! 3.4
'/administrator/components/com_tags/helpers/html/index.html',
'/administrator/components/com_tags/models/fields/index.html',
'/administrator/manifests/libraries/phpmailer.xml',
'/administrator/templates/hathor/html/com_finder/filter/index.html',
'/administrator/templates/hathor/html/com_finder/statistics/index.html',
'/components/com_contact/helpers/icon.php',
'/language/en-GB/en-GB.lib_phpmailer.sys.ini',
'/libraries/compat/jsonserializable.php',
'/libraries/compat/password/lib/index.html',
'/libraries/compat/password/lib/password.php',
'/libraries/compat/password/lib/version_test.php',
'/libraries/compat/password/index.html',
'/libraries/compat/password/LICENSE.md',
'/libraries/compat/index.html',
'/libraries/fof/controller.php',
'/libraries/fof/dispatcher.php',
'/libraries/fof/inflector.php',
'/libraries/fof/input.php',
'/libraries/fof/model.php',
'/libraries/fof/query.abstract.php',
'/libraries/fof/query.element.php',
'/libraries/fof/query.mysql.php',
'/libraries/fof/query.mysqli.php',
'/libraries/fof/query.sqlazure.php',
'/libraries/fof/query.sqlsrv.php',
'/libraries/fof/render.abstract.php',
'/libraries/fof/render.joomla.php',
'/libraries/fof/render.joomla3.php',
'/libraries/fof/render.strapper.php',
'/libraries/fof/string.utils.php',
'/libraries/fof/table.php',
'/libraries/fof/template.utils.php',
'/libraries/fof/toolbar.php',
'/libraries/fof/view.csv.php',
'/libraries/fof/view.html.php',
'/libraries/fof/view.json.php',
'/libraries/fof/view.php',
'/libraries/framework/Joomla/Application/Cli/Output/Processor/ColorProcessor.php',
'/libraries/framework/Joomla/Application/Cli/Output/Processor/ProcessorInterface.php',
'/libraries/framework/Joomla/Application/Cli/Output/Stdout.php',
'/libraries/framework/Joomla/Application/Cli/Output/Xml.php',
'/libraries/framework/Joomla/Application/Cli/CliOutput.php',
'/libraries/framework/Joomla/Application/Cli/ColorProcessor.php',
'/libraries/framework/Joomla/Application/Cli/ColorStyle.php',
'/libraries/framework/index.html',
'/libraries/framework/Joomla/DI/Exception/DependencyResolutionException.php',
'/libraries/framework/Joomla/DI/Exception/index.html',
'/libraries/framework/Joomla/DI/Container.php',
'/libraries/framework/Joomla/DI/ContainerAwareInterface.php',
'/libraries/framework/Joomla/DI/index.html',
'/libraries/framework/Joomla/DI/ServiceProviderInterface.php',
'/libraries/framework/Joomla/Registry/Format/index.html',
'/libraries/framework/Joomla/Registry/Format/Ini.php',
'/libraries/framework/Joomla/Registry/Format/Json.php',
'/libraries/framework/Joomla/Registry/Format/Php.php',
'/libraries/framework/Joomla/Registry/Format/Xml.php',
'/libraries/framework/Joomla/Registry/Format/Yaml.php',
'/libraries/framework/Joomla/Registry/AbstractRegistryFormat.php',
'/libraries/framework/Joomla/Registry/index.html',
'/libraries/framework/Joomla/Registry/Registry.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/DumpException.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/ExceptionInterface.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/index.html',
'/libraries/framework/Symfony/Component/Yaml/Exception/ParseException.php',
'/libraries/framework/Symfony/Component/Yaml/Exception/RuntimeException.php',
'/libraries/framework/Symfony/Component/Yaml/Dumper.php',
'/libraries/framework/Symfony/Component/Yaml/Escaper.php',
'/libraries/framework/Symfony/Component/Yaml/index.html',
'/libraries/framework/Symfony/Component/Yaml/Inline.php',
'/libraries/framework/Symfony/Component/Yaml/LICENSE',
'/libraries/framework/Symfony/Component/Yaml/Parser.php',
'/libraries/framework/Symfony/Component/Yaml/Unescaper.php',
'/libraries/framework/Symfony/Component/Yaml/Yaml.php',
'/libraries/joomla/string/inflector.php',
'/libraries/joomla/string/normalise.php',
'/libraries/phpmailer/language/index.html',
'/libraries/phpmailer/language/phpmailer.lang-joomla.php',
'/libraries/phpmailer/index.html',
'/libraries/phpmailer/LICENSE',
'/libraries/phpmailer/phpmailer.php',
'/libraries/phpmailer/pop.php',
'/libraries/phpmailer/smtp.php',
'/media/editors/codemirror/css/ambiance.css',
'/media/editors/codemirror/css/codemirror.css',
'/media/editors/codemirror/css/configuration.css',
'/media/editors/codemirror/css/index.html',
'/media/editors/codemirror/js/brace-fold.js',
'/media/editors/codemirror/js/clike.js',
'/media/editors/codemirror/js/closebrackets.js',
'/media/editors/codemirror/js/closetag.js',
'/media/editors/codemirror/js/codemirror.js',
'/media/editors/codemirror/js/css.js',
'/media/editors/codemirror/js/foldcode.js',
'/media/editors/codemirror/js/foldgutter.js',
'/media/editors/codemirror/js/fullscreen.js',
'/media/editors/codemirror/js/htmlmixed.js',
'/media/editors/codemirror/js/indent-fold.js',
'/media/editors/codemirror/js/index.html',
'/media/editors/codemirror/js/javascript.js',
'/media/editors/codemirror/js/less.js',
'/media/editors/codemirror/js/matchbrackets.js',
'/media/editors/codemirror/js/matchtags.js',
'/media/editors/codemirror/js/php.js',
'/media/editors/codemirror/js/xml-fold.js',
'/media/editors/codemirror/js/xml.js',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.svg',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.ttf',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.woff',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.eot',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.svg',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.ttf',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon-small.woff',
'/media/editors/tinymce/skins/lightgray/fonts/readme.md',
'/media/editors/tinymce/skins/lightgray/fonts/tinymce.dev.svg',
'/media/editors/tinymce/skins/lightgray/fonts/tinymce-small.dev.svg',
'/media/editors/tinymce/skins/lightgray/img/wline.gif',
'/plugins/editors/codemirror/styles.css',
'/plugins/editors/codemirror/styles.min.css',
// Joomla! 3.4.1
'/libraries/joomla/environment/request.php',
'/media/editors/tinymce/templates/template_list.js',
'/media/editors/codemirror/lib/addons-uncompressed.js',
'/media/editors/codemirror/lib/codemirror-uncompressed.css',
'/media/editors/codemirror/lib/codemirror-uncompressed.js',
'/administrator/help/en-GB/Components_Banners_Banners.html',
'/administrator/help/en-GB/Components_Banners_Banners_Edit.html',
'/administrator/help/en-GB/Components_Banners_Categories.html',
'/administrator/help/en-GB/Components_Banners_Category_Edit.html',
'/administrator/help/en-GB/Components_Banners_Clients.html',
'/administrator/help/en-GB/Components_Banners_Clients_Edit.html',
'/administrator/help/en-GB/Components_Banners_Tracks.html',
'/administrator/help/en-GB/Components_Contact_Categories.html',
'/administrator/help/en-GB/Components_Contact_Category_Edit.html',
'/administrator/help/en-GB/Components_Contacts_Contacts.html',
'/administrator/help/en-GB/Components_Contacts_Contacts_Edit.html',
'/administrator/help/en-GB/Components_Content_Categories.html',
'/administrator/help/en-GB/Components_Content_Category_Edit.html',
'/administrator/help/en-GB/Components_Messaging_Inbox.html',
'/administrator/help/en-GB/Components_Messaging_Read.html',
'/administrator/help/en-GB/Components_Messaging_Write.html',
'/administrator/help/en-GB/Components_Newsfeeds_Categories.html',
'/administrator/help/en-GB/Components_Newsfeeds_Category_Edit.html',
'/administrator/help/en-GB/Components_Newsfeeds_Feeds.html',
'/administrator/help/en-GB/Components_Newsfeeds_Feeds_Edit.html',
'/administrator/help/en-GB/Components_Redirect_Manager.html',
'/administrator/help/en-GB/Components_Redirect_Manager_Edit.html',
'/administrator/help/en-GB/Components_Search.html',
'/administrator/help/en-GB/Components_Weblinks_Categories.html',
'/administrator/help/en-GB/Components_Weblinks_Category_Edit.html',
'/administrator/help/en-GB/Components_Weblinks_Links.html',
'/administrator/help/en-GB/Components_Weblinks_Links_Edit.html',
'/administrator/help/en-GB/Content_Article_Manager.html',
'/administrator/help/en-GB/Content_Article_Manager_Edit.html',
'/administrator/help/en-GB/Content_Featured_Articles.html',
'/administrator/help/en-GB/Content_Media_Manager.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Discover.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Install.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Manage.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Update.html',
'/administrator/help/en-GB/Extensions_Extension_Manager_Warnings.html',
'/administrator/help/en-GB/Extensions_Language_Manager_Content.html',
'/administrator/help/en-GB/Extensions_Language_Manager_Edit.html',
'/administrator/help/en-GB/Extensions_Language_Manager_Installed.html',
'/administrator/help/en-GB/Extensions_Module_Manager.html',
'/administrator/help/en-GB/Extensions_Module_Manager_Edit.html',
'/administrator/help/en-GB/Extensions_Plugin_Manager.html',
'/administrator/help/en-GB/Extensions_Plugin_Manager_Edit.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Styles.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Styles_Edit.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Templates.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Templates_Edit.html',
'/administrator/help/en-GB/Extensions_Template_Manager_Templates_Edit_Source.html',
'/administrator/help/en-GB/Glossary.html',
'/administrator/help/en-GB/Menus_Menu_Item_Manager.html',
'/administrator/help/en-GB/Menus_Menu_Item_Manager_Edit.html',
'/administrator/help/en-GB/Menus_Menu_Manager.html',
'/administrator/help/en-GB/Menus_Menu_Manager_Edit.html',
'/administrator/help/en-GB/Site_Global_Configuration.html',
'/administrator/help/en-GB/Site_Maintenance_Clear_Cache.html',
'/administrator/help/en-GB/Site_Maintenance_Global_Check-in.html',
'/administrator/help/en-GB/Site_Maintenance_Purge_Expired_Cache.html',
'/administrator/help/en-GB/Site_System_Information.html',
'/administrator/help/en-GB/Start_Here.html',
'/administrator/help/en-GB/Users_Access_Levels.html',
'/administrator/help/en-GB/Users_Access_Levels_Edit.html',
'/administrator/help/en-GB/Users_Debug_Users.html',
'/administrator/help/en-GB/Users_Groups.html',
'/administrator/help/en-GB/Users_Groups_Edit.html',
'/administrator/help/en-GB/Users_Mass_Mail_Users.html',
'/administrator/help/en-GB/Users_User_Manager.html',
'/administrator/help/en-GB/Users_User_Manager_Edit.html',
'/administrator/components/com_config/views/index.html',
'/administrator/components/com_config/views/application/index.html',
'/administrator/components/com_config/views/application/view.html.php',
'/administrator/components/com_config/views/application/tmpl/default.php',
'/administrator/components/com_config/views/application/tmpl/default_cache.php',
'/administrator/components/com_config/views/application/tmpl/default_cookie.php',
'/administrator/components/com_config/views/application/tmpl/default_database.php',
'/administrator/components/com_config/views/application/tmpl/default_debug.php',
'/administrator/components/com_config/views/application/tmpl/default_filters.php',
'/administrator/components/com_config/views/application/tmpl/default_ftp.php',
'/administrator/components/com_config/views/application/tmpl/default_ftplogin.php',
'/administrator/components/com_config/views/application/tmpl/default_locale.php',
'/administrator/components/com_config/views/application/tmpl/default_mail.php',
'/administrator/components/com_config/views/application/tmpl/default_metadata.php',
'/administrator/components/com_config/views/application/tmpl/default_navigation.php',
'/administrator/components/com_config/views/application/tmpl/default_permissions.php',
'/administrator/components/com_config/views/application/tmpl/default_seo.php',
'/administrator/components/com_config/views/application/tmpl/default_server.php',
'/administrator/components/com_config/views/application/tmpl/default_session.php',
'/administrator/components/com_config/views/application/tmpl/default_site.php',
'/administrator/components/com_config/views/application/tmpl/default_system.php',
'/administrator/components/com_config/views/application/tmpl/index.html',
'/administrator/components/com_config/views/close/index.html',
'/administrator/components/com_config/views/close/view.html.php',
'/administrator/components/com_config/views/component/index.html',
'/administrator/components/com_config/views/component/view.html.php',
'/administrator/components/com_config/views/component/tmpl/default.php',
'/administrator/components/com_config/views/component/tmpl/index.html',
'/administrator/components/com_config/models/fields/filters.php',
'/administrator/components/com_config/models/fields/index.html',
'/administrator/components/com_config/models/forms/application.xml',
'/administrator/components/com_config/models/forms/index.html',
// Joomla 3.4.2
'/libraries/composer_autoload.php',
'/administrator/templates/hathor/html/com_categories/categories/default_batch.php',
'/administrator/templates/hathor/html/com_tags/tags/default_batch.php',
'/media/editors/codemirror/mode/clike/scala.html',
'/media/editors/codemirror/mode/css/less.html',
'/media/editors/codemirror/mode/css/less_test.js',
'/media/editors/codemirror/mode/css/scss.html',
'/media/editors/codemirror/mode/css/scss_test.js',
'/media/editors/codemirror/mode/css/test.js',
'/media/editors/codemirror/mode/gfm/test.js',
'/media/editors/codemirror/mode/haml/test.js',
'/media/editors/codemirror/mode/javascript/json-ld.html',
'/media/editors/codemirror/mode/javascript/test.js',
'/media/editors/codemirror/mode/javascript/typescript.html',
'/media/editors/codemirror/mode/markdown/test.js',
'/media/editors/codemirror/mode/php/test.js',
'/media/editors/codemirror/mode/ruby/test.js',
'/media/editors/codemirror/mode/shell/test.js',
'/media/editors/codemirror/mode/slim/test.js',
'/media/editors/codemirror/mode/stex/test.js',
'/media/editors/codemirror/mode/textile/test.js',
'/media/editors/codemirror/mode/verilog/test.js',
'/media/editors/codemirror/mode/xml/test.js',
'/media/editors/codemirror/mode/xquery/test.js',
// Joomla 3.4.3
'/libraries/classloader.php',
'/libraries/ClassLoader.php',
// Joomla 3.4.6
'/components/com_wrapper/views/wrapper/metadata.xml',
// Joomla 3.5.0
'/media/com_joomlaupdate/default.js',
'/media/com_joomlaupdate/encryption.js',
'/media/com_joomlaupdate/json2.js',
'/media/com_joomlaupdate/update.js',
'/media/com_finder/css/finder-rtl.css',
'/media/com_finder/css/selectfilter.css',
'/media/com_finder/css/sliderfilter.css',
'/media/com_finder/js/sliderfilter.js',
'/media/editors/codemirror/mode/kotlin/kotlin.js',
'/media/editors/codemirror/mode/kotlin/kotlin.min.js',
'/media/editors/tinymce/plugins/compat3x/editable_selects.js',
'/media/editors/tinymce/plugins/compat3x/form_utils.js',
'/media/editors/tinymce/plugins/compat3x/mctabs.js',
'/media/editors/tinymce/plugins/compat3x/tiny_mce_popup.js',
'/media/editors/tinymce/plugins/compat3x/validate.js',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Dumper.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Escaper.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Inline.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/LICENSE',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Parser.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Unescaper.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Yaml.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.php',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php',
'/libraries/vendor/phpmailer/phpmailer/extras/class.html2text.php',
'/libraries/joomla/document/error/error.php',
'/libraries/joomla/document/feed/feed.php',
'/libraries/joomla/document/html/html.php',
'/libraries/joomla/document/image/image.php',
'/libraries/joomla/document/json/json.php',
'/libraries/joomla/document/opensearch/opensearch.php',
'/libraries/joomla/document/raw/raw.php',
'/libraries/joomla/document/xml/xml.php',
'/plugins/editors/tinymce/fields/skins.php',
'/plugins/user/profile/fields/dob.php',
'/plugins/user/profile/fields/tos.php',
'/administrator/components/com_installer/views/languages/tmpl/default_filter.php',
'/administrator/components/com_joomlaupdate/helpers/download.php',
'/administrator/components/com_config/controller/application/refreshhelp.php',
'/administrator/components/com_media/models/forms/index.html',
// Joomla 3.6.0
'/libraries/simplepie/README.txt',
'/libraries/simplepie/simplepie.php',
'/libraries/simplepie/LICENSE.txt',
'/libraries/simplepie/idn/LICENCE',
'/libraries/simplepie/idn/ReadMe.txt',
'/libraries/simplepie/idn/idna_convert.class.php',
'/libraries/simplepie/idn/npdata.ser',
'/administrator/manifests/libraries/simplepie.xml',
'/administrator/templates/isis/js/jquery.js',
'/administrator/templates/isis/js/bootstrap.min.js',
'/media/system/js/permissions.min.js',
'/libraries/platform.php',
'/plugins/user/profile/fields/tos.php',
'/libraries/joomla/application/web/client.php',
// Joomla! 3.6.1
'/libraries/joomla/database/iterator/azure.php',
'/media/editors/tinymce/skins/lightgray/fonts/icomoon.eot',
// Joomla! 3.6.3
'/media/editors/codemirror/mode/jade/jade.js',
'/media/editors/codemirror/mode/jade/jade.min.js',
// Joomla __DEPLOY_VERSION__
'/libraries/joomla/user/authentication.php',
'/libraries/platform.php',
'/libraries/joomla/data/data.php',
'/libraries/joomla/data/dumpable.php',
'/libraries/joomla/data/set.php',
'/administrator/components/com_banners/views/banners/tmpl/default_batch.php',
'/administrator/components/com_categories/views/category/tmpl/edit_extrafields.php',
'/administrator/components/com_categories/views/category/tmpl/edit_options.php',
'/administrator/components/com_categories/views/categories/tmpl/default_batch.php',
'/administrator/components/com_content/views/articles/tmpl/default_batch.php',
'/administrator/components/com_menus/views/items/tmpl/default_batch.php',
'/administrator/components/com_modules/views/modules/tmpl/default_batch.php',
'/administrator/components/com_newsfeeds/views/newsfeeds/tmpl/default_batch.php',
'/administrator/components/com_redirect/views/links/tmpl/default_batch.php',
'/administrator/components/com_tags/views/tags/tmpl/default_batch.php',
'/administrator/components/com_users/views/users/tmpl/default_batch.php',
);
// TODO There is an issue while deleting folders using the ftp mode
$folders = array(
'/administrator/components/com_admin/sql/updates/sqlsrv',
'/media/com_finder/images/mime',
'/media/com_finder/images',
'/components/com_media/helpers',
// Joomla 3.0
'/administrator/components/com_contact/elements',
'/administrator/components/com_content/elements',
'/administrator/components/com_newsfeeds/elements',
'/administrator/components/com_templates/views/prevuuw/tmpl',
'/administrator/components/com_templates/views/prevuuw',
'/libraries/cms/controller',
'/libraries/cms/model',
'/libraries/cms/view',
'/libraries/joomla/application/cli',
'/libraries/joomla/application/component',
'/libraries/joomla/application/input',
'/libraries/joomla/application/module',
'/libraries/joomla/cache/storage/helpers',
'/libraries/joomla/database/table',
'/libraries/joomla/database/database',
'/libraries/joomla/error',
'/libraries/joomla/filesystem/archive',
'/libraries/joomla/html/html',
'/libraries/joomla/html/toolbar',
'/libraries/joomla/html/toolbar/button',
'/libraries/joomla/html/parameter',
'/libraries/joomla/html/parameter/element',
'/libraries/joomla/image/filters',
'/libraries/joomla/log/loggers',
// Joomla! 3.1
'/libraries/joomla/form/rules',
'/libraries/joomla/html/language/en-GB',
'/libraries/joomla/html/language',
'/libraries/joomla/html',
'/libraries/joomla/installer/adapters',
'/libraries/joomla/installer',
'/libraries/joomla/pagination',
'/libraries/legacy/html',
'/libraries/legacy/menu',
'/libraries/legacy/pathway',
'/media/system/swf/',
'/media/editors/tinymce/jscripts',
// Joomla! 3.2
'/libraries/joomla/plugin',
'/libraries/legacy/component',
'/libraries/legacy/module',
'/administrator/components/com_weblinks/models/fields',
'/plugins/user/joomla/postinstall',
'/libraries/joomla/registry/format',
'/libraries/joomla/registry',
// Joomla! 3.3
'/plugins/user/profile/fields',
'/media/editors/tinymce/plugins/compat3x',
// Joomla! 3.4
'/administrator/components/com_tags/helpers/html',
'/administrator/components/com_tags/models/fields',
'/administrator/templates/hathor/html/com_finder/filter',
'/administrator/templates/hathor/html/com_finder/statistics',
'/libraries/compat/password/lib',
'/libraries/compat/password',
'/libraries/compat',
'/libraries/framework/Joomla/Application/Cli/Output/Processor',
'/libraries/framework/Joomla/Application/Cli/Output',
'/libraries/framework/Joomla/Application/Cli',
'/libraries/framework/Joomla/Application',
'/libraries/framework/Joomla/DI/Exception',
'/libraries/framework/Joomla/DI',
'/libraries/framework/Joomla/Registry/Format',
'/libraries/framework/Joomla/Registry',
'/libraries/framework/Joomla',
'/libraries/framework/Symfony/Component/Yaml/Exception',
'/libraries/framework/Symfony/Component/Yaml',
'/libraries/framework',
'/libraries/phpmailer/language',
'/libraries/phpmailer',
'/media/editors/codemirror/css',
'/media/editors/codemirror/js',
'/media/com_banners',
// Joomla! 3.4.1
'/administrator/components/com_config/views',
'/administrator/components/com_config/models/fields',
'/administrator/components/com_config/models/forms',
// Joomla! 3.4.2
'/media/editors/codemirror/mode/smartymixed',
// Joomla! 3.5
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml/Exception',
'/libraries/vendor/symfony/yaml/Symfony/Component/Yaml',
'/libraries/vendor/symfony/yaml/Symfony/Component',
'/libraries/vendor/symfony/yaml/Symfony',
'/libraries/joomla/document/error',
'/libraries/joomla/document/image',
'/libraries/joomla/document/json',
'/libraries/joomla/document/opensearch',
'/libraries/joomla/document/raw',
'/libraries/joomla/document/xml',
'/administrator/components/com_media/models/forms',
'/media/editors/codemirror/mode/kotlin',
'/media/editors/tinymce/plugins/compat3x',
'/plugins/editors/tinymce/fields',
'/plugins/user/profile/fields',
// Joomla 3.6
'/libraries/simplepie/idn',
'/libraries/simplepie',
// Joomla! 3.6.3
'/media/editors/codemirror/mode/jade',
// Joomla __DEPLOY_VERSION__
'/libraries/joomla/data',
);
jimport('joomla.filesystem.file');
foreach ($files as $file)
{
if (JFile::exists(JPATH_ROOT . $file) && !JFile::delete(JPATH_ROOT . $file))
{
echo JText::sprintf('FILES_JOOMLA_ERROR_FILE_FOLDER', $file) . '<br />';
}
}
jimport('joomla.filesystem.folder');
foreach ($folders as $folder)
{
if (JFolder::exists(JPATH_ROOT . $folder) && !JFolder::delete(JPATH_ROOT . $folder))
{
echo JText::sprintf('FILES_JOOMLA_ERROR_FILE_FOLDER', $folder) . '<br />';
}
}
/*
* Needed for updates post-3.4
* If com_weblinks doesn't exist then assume we can delete the weblinks package manifest (included in the update packages)
*/
if (!JFile::exists(JPATH_ROOT . '/administrator/components/com_weblinks/weblinks.php')
&& JFile::exists(JPATH_ROOT . '/administrator/manifests/packages/pkg_weblinks.xml'))
{
JFile::delete(JPATH_ROOT . '/administrator/manifests/packages/pkg_weblinks.xml');
}
}
/**
* Clears the RAD layer's table cache.
*
* The cache vastly improves performance but needs to be cleared every time you update the database schema.
*
* @return void
*
* @since 3.2
*/
protected function clearRadCache()
{
jimport('joomla.filesystem.file');
if (JFile::exists(JPATH_ROOT . '/cache/fof/cache.php'))
{
JFile::delete(JPATH_ROOT . '/cache/fof/cache.php');
}
}
/**
* Method to create assets for newly installed components
*
* @return boolean
*
* @since 3.2
*/
public function updateAssets()
{
// List all components added since 1.6
$newComponents = array(
'com_finder',
'com_joomlaupdate',
'com_tags',
'com_contenthistory',
'com_ajax',
'com_postinstall'
);
foreach ($newComponents as $component)
{
/** @var JTableAsset $asset */
$asset = JTable::getInstance('Asset');
if ($asset->loadByName($component))
{
continue;
}
$asset->name = $component;
$asset->parent_id = 1;
$asset->rules = '{}';
$asset->title = $component;
$asset->setLocation(1, 'last-child');
if (!$asset->store())
{
// Install failed, roll back changes
$this->parent->abort(JText::sprintf('JLIB_INSTALLER_ABORT_COMP_INSTALL_ROLLBACK', $asset->stderr(true)));
return false;
}
}
return true;
}
/**
* If we migrated the session from the previous system, flush all the active sessions.
* Otherwise users will be logged in, but not able to do anything since they don't have
* a valid session
*
* @return boolean
*/
public function flushSessions()
{
/**
* The session may have not been started yet (e.g. CLI-based Joomla! update scripts). Let's make sure we do
* have a valid session.
*/
$session = JFactory::getSession();
/**
* Restarting the Session require a new login for the current user so lets check if we have an active session
* and only restart it if not.
* For B/C reasons we need to use getState as isActive is not available in 2.5
*/
if ($session->getState() !== 'active')
{
$session->restart();
}
// If $_SESSION['__default'] is no longer set we do not have a migrated session, therefore we can quit.
if (!isset($_SESSION['__default']))
{
return true;
}
$db = JFactory::getDbo();
try
{
switch ($db->name)
{
// MySQL database, use TRUNCATE (faster, more resilient)
case 'pdomysql':
case 'mysql':
case 'mysqli':
$db->truncateTable('#__session');
break;
// Non-MySQL databases, use a simple DELETE FROM query
default:
$query = $db->getQuery(true)
->delete($db->qn('#__session'));
$db->setQuery($query)->execute();
break;
}
}
catch (Exception $e)
{
echo JText::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()) . '<br />';
return false;
}
return true;
}
/**
* Converts the site's database tables to support UTF-8 Multibyte.
*
* @param boolean $doDbFixMsg Flag if message to be shown to check db fix
*
* @return void
*
* @since 3.5
*/
public function convertTablesToUtf8mb4($doDbFixMsg = false)
{
$db = JFactory::getDbo();
// This is only required for MySQL databases
$serverType = $db->getServerType();
if ($serverType != 'mysql')
{
return;
}
// Set required conversion status
if ($db->hasUTF8mb4Support())
{
$converted = 2;
}
else
{
$converted = 1;
}
// Check conversion status in database
$db->setQuery('SELECT ' . $db->quoteName('converted')
. ' FROM ' . $db->quoteName('#__utf8_conversion')
);
try
{
$convertedDB = $db->loadResult();
}
catch (Exception $e)
{
// Render the error message from the Exception object
JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
if ($doDbFixMsg)
{
// Show an error message telling to check database problems
JFactory::getApplication()->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_UPGRADE_FAILED'), 'error');
}
return;
}
// Nothing to do, saved conversion status from DB is equal to required
if ($convertedDB == $converted)
{
return;
}
// Step 1: Drop indexes later to be added again with column lengths limitations at step 2
$fileName1 = JPATH_ROOT . "/administrator/components/com_admin/sql/others/mysql/utf8mb4-conversion-01.sql";
if (is_file($fileName1))
{
$fileContents1 = @file_get_contents($fileName1);
$queries1 = $db->splitSql($fileContents1);
if (!empty($queries1))
{
foreach ($queries1 as $query1)
{
try
{
$db->setQuery($query1)->execute();
}
catch (Exception $e)
{
// If the query fails we will go on. It just means the index to be dropped does not exist.
}
}
}
}
// Step 2: Perform the index modifications and conversions
$fileName2 = JPATH_ROOT . "/administrator/components/com_admin/sql/others/mysql/utf8mb4-conversion-02.sql";
if (is_file($fileName2))
{
$fileContents2 = @file_get_contents($fileName2);
$queries2 = $db->splitSql($fileContents2);
if (!empty($queries2))
{
foreach ($queries2 as $query2)
{
try
{
$db->setQuery($db->convertUtf8mb4QueryToUtf8($query2))->execute();
}
catch (Exception $e)
{
$converted = 0;
// Still render the error message from the Exception object
JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');
}
}
}
}
if ($doDbFixMsg && $converted == 0)
{
// Show an error message telling to check database problems
JFactory::getApplication()->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_UPGRADE_FAILED'), 'error');
}
// Set flag in database if the update is done.
$db->setQuery('UPDATE ' . $db->quoteName('#__utf8_conversion')
. ' SET ' . $db->quoteName('converted') . ' = ' . $converted . ';')->execute();
}
/**
* This method clean the Joomla Cache using the method `clean` from the com_cache model
*
* @return void
*
* @since 3.5.1
*/
private function cleanJoomlaCache()
{
JModelLegacy::addIncludePath(JPATH_ROOT . '/administrator/components/com_cache/models');
$model = JModelLegacy::getInstance('cache', 'CacheModel');
// Clean frontend cache
$model->clean();
// Clean admin cache
$model->setState('client_id', 1);
$model->clean();
}
}
| demis-palma/joomla-cms | administrator/components/com_admin/script.php | PHP | gpl-2.0 | 93,249 |
<?php
/**
* LDAP configuration test class
*
* PHP version 5
*
* Copyright (C) Villanova University 2010.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind
* @package Tests
* @author Franck Borel <franck.borel@gbv.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/unit_tests Wiki
*/
require_once dirname(__FILE__) . '/../../prepend.inc.php';
require_once 'PEAR.php';
require_once 'sys/authn/LDAPConfigurationParameter.php';
/**
* LDAP configuration test class
*
* @category VuFind
* @package Tests
* @author Franck Borel <franck.borel@gbv.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/unit_tests Wiki
*/
class LDAPConfigurationParameterTest extends PHPUnit_Framework_TestCase
{
/**
* Standard setup method.
*
* @return void
* @access public
*/
public function setUp()
{
$this->pathToTestConfigurationFiles = dirname(__FILE__) . '/../../conf';
}
/**
* Verify that missing host causes failure.
*
* @return void
* @access public
*/
public function testWithMissingHost()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-host-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that missing port causes failure.
*
* @return void
* @access public
*/
public function testWithMissingPort()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-port-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that missing baseDN causes failure.
*
* @return void
* @access public
*/
public function testWithMissingBaseDN()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-basedn-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that missing UID causes failure.
*
* @return void
* @access public
*/
public function testWithMissingUid()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/without-ldap-uid-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
} catch (InvalidArgumentException $expected) {
return;
}
$this->fail('An expected InvalidArgumentException has not been raised');
}
/**
* Verify that good parameters parse correctly.
*
* @return void
* @access public
*/
public function testWithWorkingParameters()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter();
$parameters = $ldapConfigurationParameter->getParameter();
$this->assertTrue(is_array($parameters));
} catch (InvalidArgumentException $unexpected) {
$this->fail(
"An unexpected InvalidArgumentException has been raised: " .
$unexpected
);
}
}
/**
* Verify lowercasing of parameter values.
*
* @return void
* @access public
*/
public function testIfParametersAreConvertedToLowercase()
{
try {
$ldapConfigurationParameter = new LDAPConfigurationParameter(
$this->pathToTestConfigurationFiles .
"/authn/ldap/unconverted-parameter-values-config.ini"
);
$parameters = $ldapConfigurationParameter->getParameter();
foreach ($parameters as $index => $value) {
if ($index == "username") {
$this->assertTrue($value == "uid");
}
if ($index == "college") {
$this->assertTrue($value == "employeetype");
}
}
} catch (InvalidArgumentException $unexpected) {
$this->fail(
"An unexpected InvalidArgumentException has been raised: " .
$unexpected
);
}
}
}
?>
| marktriggs/vufind | tests/web/sys/authn/LDAPConfigurationParameterTest.php | PHP | gpl-2.0 | 5,799 |
/* Copyright (C) 2013 Rainmeter Project Developers
*
* This Source Code Form is subject to the terms of the GNU General Public
* License; either version 2 of the License, or (at your option) any later
* version. If a copy of the GPL was not distributed with this file, You can
* obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */
#include "StdAfx.h"
#include "StringUtil.h"
namespace {
// Is the character a end of sentence punctuation character?
// English only?
bool IsEOSPunct(wchar_t ch)
{
return ch == '?' || ch == '!' || ch == '.';
}
}
namespace StringUtil {
std::string Narrow(const WCHAR* str, int strLen, int cp)
{
std::string narrowStr;
if (str && *str)
{
if (strLen == -1)
{
strLen = (int)wcslen(str);
}
int bufLen = WideCharToMultiByte(cp, 0, str, strLen, nullptr, 0, nullptr, nullptr);
if (bufLen > 0)
{
narrowStr.resize(bufLen);
WideCharToMultiByte(cp, 0, str, strLen, &narrowStr[0], bufLen, nullptr, nullptr);
}
}
return narrowStr;
}
std::wstring Widen(const char* str, int strLen, int cp)
{
std::wstring wideStr;
if (str && *str)
{
if (strLen == -1)
{
strLen = (int)strlen(str);
}
int bufLen = MultiByteToWideChar(cp, 0, str, strLen, nullptr, 0);
if (bufLen > 0)
{
wideStr.resize(bufLen);
MultiByteToWideChar(cp, 0, str, strLen, &wideStr[0], bufLen);
}
}
return wideStr;
}
void ToLowerCase(std::wstring& str)
{
WCHAR* srcAndDest = &str[0];
int strAndDestLen = (int)str.length();
LCMapString(LOCALE_USER_DEFAULT, LCMAP_LOWERCASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen);
}
void ToUpperCase(std::wstring& str)
{
WCHAR* srcAndDest = &str[0];
int strAndDestLen = (int)str.length();
LCMapString(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen);
}
void ToProperCase(std::wstring& str)
{
WCHAR* srcAndDest = &str[0];
int strAndDestLen = (int)str.length();
LCMapString(LOCALE_USER_DEFAULT, LCMAP_TITLECASE, srcAndDest, strAndDestLen, srcAndDest, strAndDestLen);
}
void ToSentenceCase(std::wstring& str)
{
if (!str.empty())
{
ToLowerCase(str);
bool isCapped = false;
for (size_t i = 0; i < str.length(); ++i)
{
if (IsEOSPunct(str[i])) isCapped = false;
if (!isCapped && iswalpha(str[i]) != 0)
{
WCHAR* srcAndDest = &str[i];
LCMapString(LOCALE_USER_DEFAULT, LCMAP_UPPERCASE, srcAndDest, 1, srcAndDest, 1);
isCapped = true;
}
}
}
}
/*
** Escapes reserved PCRE regex metacharacters.
*/
void EscapeRegExp(std::wstring& str)
{
size_t start = 0;
while ((start = str.find_first_of(L"\\^$|()[{.+*?", start)) != std::wstring::npos)
{
str.insert(start, L"\\");
start += 2;
}
}
/*
** Escapes reserved URL characters.
*/
void EncodeUrl(std::wstring& str)
{
size_t pos = 0;
while ((pos = str.find_first_of(L" !*'();:@&=+$,/?#[]", pos)) != std::wstring::npos)
{
WCHAR buffer[3];
_snwprintf_s(buffer, _countof(buffer), L"%.2X", str[pos]);
str[pos] = L'%';
str.insert(pos + 1, buffer);
pos += 3;
}
}
/*
** Case insensitive comparison of strings. If equal, strip str2 from str1 and any leading whitespace.
*/
bool CaseInsensitiveCompareN(std::wstring& str1, const std::wstring& str2)
{
size_t pos = str2.length();
if (_wcsnicmp(str1.c_str(), str2.c_str(), pos) == 0)
{
str1 = str1.substr(pos); // remove str2 from str1
str1.erase(0, str1.find_first_not_of(L" \t\r\n")); // remove any leading whitespace
return true;
}
return false;
}
} // namespace StringUtil
| haroruhomer/rainmeter | Common/StringUtil.cpp | C++ | gpl-2.0 | 3,637 |
var icms = icms || {};
icms.wall = (function ($) {
var self = this;
this.add = function (parent_id) {
var form = $('#wall_add_form');
if (typeof (parent_id) === 'undefined') {
parent_id = 0;
}
$('#wall_widget #wall_add_link').show();
$('#wall_widget #entries_list .links *').removeClass('disabled');
if (parent_id == 0){
$('#wall_widget #wall_add_link').hide();
form.detach().prependTo('#wall_widget #entries_list');
} else {
$('#wall_widget #entries_list #entry_'+parent_id+' > .media-body > .links .reply').addClass('disabled');
form.detach().appendTo('#wall_widget #entries_list #entry_'+parent_id+' > .media-body');
}
form.show();
$('input[name=parent_id]', form).val(parent_id);
$('input[name=id]', form).val('');
$('input[name=action]', form).val('add');
$('input[name=submit]', form).val( LANG_SEND );
icms.forms.wysiwygInit('content').wysiwygInsertText('content', '');
return false;
};
this.submit = function (action) {
var form = $('#wall_add_form form');
var form_data = icms.forms.toJSON( form );
var url = form.attr('action');
if (action) {form_data.action = action;}
$('.buttons > *', form).addClass('disabled');
$('.button-'+form_data.action, form).addClass('is-busy');
$('textarea', form).prop('disabled', true);
$.post(url, form_data, function(result){
if (form_data.action === 'add') { self.result(result);}
if (form_data.action === 'preview') { self.previewResult(result);}
if (form_data.action === 'update') { self.updateResult(result);}
}, "json");
};
this.preview = function () {
this.submit('preview');
};
this.previewResult = function (result) {
if (result.error){
this.error(result.message);
return;
}
var form = $('#wall_add_form');
var preview_box = $('.preview_box', form).html(result.html);
$(preview_box).addClass('shadow').removeClass('d-none');
setTimeout(function (){ $(preview_box).removeClass('shadow'); }, 1000);
this.restoreForm(false);
};
this.more = function(){
var widget = $('#wall_widget');
$('.show_more', widget).hide();
$('.entry', widget).show();
$('.wall_pages', widget).show();
return false;
};
this.replies = function(id, callback){
var e = $('#wall_widget #entry_'+id);
if (!e.data('replies')) { return false; }
var url = $('#wall_urls').data('replies-url');
$('.icms-wall-item__btn_replies', e).addClass('is-busy');
$.post(url, {id: id}, function(result){
$('.icms-wall-item__btn_replies', e).removeClass('is-busy').hide();
if (result.error){
self.error(result.message);
return false;
}
$('.replies', e).html( result.html );
if (typeof(callback)=='function'){
callback();
}
}, "json");
return false;
};
this.append = function(entry){
$('#wall_widget #entries_list .no_entries').remove();
if (entry.parent_id == 0){
$('#wall_widget #entries_list').prepend( entry.html );
return;
}
if (entry.parent_id > 0){
$('#wall_widget #entry_'+entry.parent_id+' .replies').append( entry.html );
return;
}
};
this.result = function(result){
if (result.error){
this.error(result.message);
return;
}
this.append(result);
this.restoreForm();
};
this.updateResult = function(result){
if (result.error){
this.error(result.message);
return;
}
$('#entries_list #entry_'+result.id+'> .media-body > .icms-wall-html').html(result.html);
this.restoreForm();
};
this.edit = function (id){
var form = $('#wall_add_form');
$('#wall_widget #wall_add_link').show();
$('#wall_widget #entries_list .links *').removeClass('disabled');
$('#wall_widget #entries_list #entry_'+id+' > .media-body > .links .edit').addClass('is-busy disabled');
form.detach().insertAfter('#wall_widget #entries_list #entry_'+id+' > .media-body > .links').show();
$('input[name=id]', form).val(id);
$('input[name=action]', form).val('update');
$('input[name=submit]', form).val( LANG_SAVE );
$('textarea', form).prop('disabled', true);
icms.forms.wysiwygInit('content');
var url = $('#wall_urls').data('get-url');
$.post(url, {id: id}, function(result){
$('#wall_widget #entries_list #entry_'+id+' > .media-body > .links .edit').removeClass('is-busy');
if (result.error){
self.error(result.message);
return;
}
self.restoreForm(false);
icms.forms.wysiwygInsertText('content', result.html);
}, 'json');
return false;
};
this.remove = function (id){
var c = $('#entries_list #entry_'+id);
var username = $('> .media-body > h6 .user', c).text();
if (!confirm(LANG_WALL_ENTRY_DELETE_CONFIRM.replace('%s', username))) {
return false;
}
var url = $('#wall_urls').data('delete-url');
$.post(url, {id: id}, function(result){
if (result.error){
self.error(result.message);
return;
}
c.remove();
self.restoreForm();
}, "json");
return false;
};
this.show = function(id, reply_id, go_reply){
var e = $('#entry_'+id);
if (e.length){
$.scrollTo( e, 500, {
offset: {
left:0,
top:-10
},
onAfter: function(){
self.replies(id, function(){
if (reply_id>0){
self.show(reply_id);
}
});
if (go_reply){
self.add(id);
}
}
});
} else {
if (go_reply){
$.scrollTo( $('#wall_widget'), 500, {
offset: {
left:0,
top:-10
},
onAfter: function(){
self.add();
}
});
}
}
return false;
};
this.error = function(message){
icms.modal.alert(message);
this.restoreForm(false);
};
this.restoreForm = function(clear_text){
if (typeof (clear_text) === 'undefined') {
clear_text = true;
}
var form = $('#wall_add_form');
$('.buttons *', form).removeClass('disabled is-busy');
$('textarea', form).prop('disabled', false);
if (clear_text) {
form.hide();
icms.forms.wysiwygInsertText('content', '');
$('#wall_widget #wall_add_link').show();
$('#wall_widget #entries_list .links *').removeClass('disabled');
$('.preview_box', form).html('').hide();
}
};
return this;
}).call(icms.wall || {},jQuery); | Loadir/icms2 | templates/modern/js/wall.js | JavaScript | gpl-2.0 | 7,610 |
/***************************************************************************
qgsnewnamedialog.cpp
-------------------
begin : May, 2015
copyright : (C) 2015 Radim Blazek
email : radim.blazek@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. *
* *
***************************************************************************/
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QRegExpValidator>
#include <QSizePolicy>
#include "qgslogger.h"
#include "qgsnewnamedialog.h"
QgsNewNameDialog::QgsNewNameDialog( const QString& source, const QString& initial,
const QStringList& extensions, const QStringList& existing,
const QRegExp& regexp, Qt::CaseSensitivity cs,
QWidget *parent, Qt::WindowFlags flags )
: QgsDialog( parent, flags, QDialogButtonBox::Ok | QDialogButtonBox::Cancel )
, mExiting( existing )
, mExtensions( extensions )
, mCaseSensitivity( cs )
, mNamesLabel( 0 )
, mRegexp( regexp )
{
setWindowTitle( tr( "New name" ) );
QDialog::layout()->setSizeConstraint( QLayout::SetMinimumSize );
layout()->setSizeConstraint( QLayout::SetMinimumSize );
layout()->setSpacing( 6 );
mOkString = buttonBox()->button( QDialogButtonBox::Ok )->text();
QString hintString;
QString nameDesc = mExtensions.isEmpty() ? tr( "name" ) : tr( "base name" );
if ( source.isEmpty() )
{
hintString = tr( "Enter new %1" ).arg( nameDesc );
}
else
{
hintString = tr( "Enter new %1 for %2" ).arg( nameDesc ).arg( source );
}
QLabel* hintLabel = new QLabel( hintString, this );
layout()->addWidget( hintLabel );
mLineEdit = new QLineEdit( initial, this );
if ( !regexp.isEmpty() )
{
QRegExpValidator *validator = new QRegExpValidator( regexp, this );
mLineEdit->setValidator( validator );
}
connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( nameChanged() ) );
layout()->addWidget( mLineEdit );
mNamesLabel = new QLabel( " ", this );
mNamesLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
if ( !mExtensions.isEmpty() )
{
mNamesLabel->setWordWrap( true );
layout()->addWidget( mNamesLabel );
}
mErrorLabel = new QLabel( " ", this );
mErrorLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
mErrorLabel->setWordWrap( true );
layout()->addWidget( mErrorLabel );
nameChanged();
}
QString QgsNewNameDialog::highlightText( const QString& text )
{
return "<b>" + text + "</b>";
}
void QgsNewNameDialog::nameChanged()
{
QgsDebugMsg( "entered" );
QString namesString = tr( "Full names" ) + ": ";
if ( !mExtensions.isEmpty() )
{
mNamesLabel->setText( namesString );
}
mErrorLabel->setText( " " ); // space to keep vertical space
QPushButton* okButton = buttonBox()->button( QDialogButtonBox::Ok );
okButton->setText( mOkString );
okButton->setEnabled( true );
QString newName = name();
if ( newName.length() == 0 || ( !mRegexp.isEmpty() && !mRegexp.exactMatch( newName ) ) )
{
//mErrorLabel->setText( highlightText( tr( "Enter new name" ) );
okButton->setEnabled( false );
return;
}
QStringList newNames = fullNames( newName, mExtensions );
if ( !mExtensions.isEmpty() )
{
namesString += " " + newNames.join( ", " );
mNamesLabel->setText( namesString );
}
QStringList conflicts = matching( newNames, mExiting, mCaseSensitivity );
if ( !conflicts.isEmpty() )
{
mErrorLabel->setText( highlightText( tr( "%n Name(s) %1 exists", 0, conflicts.size() ).arg( conflicts.join( ", " ) ) ) );
okButton->setText( tr( "Overwrite" ) );
return;
}
}
QString QgsNewNameDialog::name() const
{
return mLineEdit->text().trimmed();
}
QStringList QgsNewNameDialog::fullNames( const QString& name, const QStringList& extensions )
{
QStringList list;
foreach ( QString ext, extensions )
{
list << name + ext;
}
if ( list.isEmpty() )
{
list << name;
}
return list;
}
QStringList QgsNewNameDialog::matching( const QStringList& newNames, const QStringList& existingNames,
Qt::CaseSensitivity cs )
{
QStringList list;
foreach ( QString newName, newNames )
{
foreach ( QString existingName, existingNames )
{
if ( existingName.compare( newName, cs ) == 0 )
{
list << existingName;
}
}
}
return list;
}
bool QgsNewNameDialog::exists( const QString& name, const QStringList& extensions,
const QStringList& existing, Qt::CaseSensitivity cs )
{
QStringList newNames = fullNames( name, extensions );
QStringList conflicts = matching( newNames, existing, cs );
return conflicts.size() > 0;
}
| michaelkirk/QGIS | src/gui/qgsnewnamedialog.cpp | C++ | gpl-2.0 | 5,422 |
<?php
/**
* Download a package by passing in its location
*
* @var modX $this->modx
*
* @package modx
* @subpackage processors.workspace.packages.rest
*/
class modPackageDownloadProcessor extends modProcessor {
/** @var modTransportProvider $provider */
public $provider;
/** @var string $location The actual file location of the download */
public $location;
/** @var string $signature The signature of the transport package */
public $signature;
/** @var modTransportPackage $package */
public $package;
/**
* Ensure user has access to do this
*
* {@inheritDoc}
* @return boolean
*/
public function checkPermissions() {
return $this->modx->hasPermission('packages');
}
/**
* The language topics to load
*
* {@inheritDoc}
* @return array
*/
public function getLanguageTopics() {
return array('workspace');
}
/**
* Ensure the info was properly passed and initialize the processor
*
* {@inheritDoc}
* @return boolean
*/
public function initialize() {
@set_time_limit(0);
$info = $this->getProperty('info','');
if (empty($info)) return $this->modx->lexicon('package_download_err_ns');
if (!$this->parseInfo($info)) {
return $this->modx->lexicon('invalid_data');
}
return parent::initialize();
}
/**
* Run the processor, downloading and transferring the package, and creating the metadata in the database
* {@inheritDoc}
* @return mixed
*/
public function process() {
if (!$this->loadProvider()) {
return $this->failure($this->modx->lexicon('provider_err_nf'));
}
$this->package = $this->provider->transfer($this->signature, null, array('location' => $this->location));
if (!$this->package) {
return $this->failure($this->modx->lexicon('package_download_err_create', array('signature' => $this->signature)));
}
return $this->success('', $this->package);
}
/**
* Load the provider for the package
* @return boolean
*/
public function loadProvider() {
$provider = $this->getProperty('provider');
if (empty($provider)) {
$c = $this->modx->newQuery('transport.modTransportProvider');
$c->where(array(
'name:=' => 'modxcms.com',
'OR:name:=' => 'modx.com',
));
$this->provider = $this->modx->getObject('transport.modTransportProvider',$c);
if (!empty($this->provider)) {
$this->setProperty('provider',$this->provider->get('id'));
}
} else {
$this->provider = $this->modx->getObject('transport.modTransportProvider',$provider);
}
return !empty($this->provider);
}
/**
* Parse the information sent to the processor
* @param string $info
* @return boolean
*/
public function parseInfo($info) {
$parsed = false;
$parsedInfo = explode('::',$info);
if (!empty($parsedInfo) && !empty($parsedInfo[1])) {
$this->location = $parsedInfo[0];
$this->signature = $parsedInfo[1];
$parsed = true;
}
return $parsed;
}
}
return 'modPackageDownloadProcessor';
| sergeiforward/gl | core_gl_xVCs4l0eEu/model/modx/processors/workspace/packages/rest/download.class.php | PHP | gpl-2.0 | 3,377 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'find', 'cs', {
find: 'Hledat',
findOptions: 'Možnosti hledání',
findWhat: 'Co hledat:',
matchCase: 'Rozlišovat velikost písma',
matchCyclic: 'Procházet opakovaně',
matchWord: 'Pouze celá slova',
notFoundMsg: 'Hledaný text nebyl nalezen.',
replace: 'Nahradit',
replaceAll: 'Nahradit vše',
replaceSuccessMsg: '%1 nahrazení.',
replaceWith: 'Čím nahradit:',
title: 'Najít a nahradit'
} );
| shophelfer/shophelfer.com-shop | admin/includes/modules/ckeditor/plugins/find/lang/cs.js | JavaScript | gpl-2.0 | 581 |
//>>built
define("dojox/editor/plugins/nls/zh-tw/SafePaste",({"instructions":"已停用直接貼上。請使用標準瀏覽器鍵盤或功能表貼上控制項,在這個對話框中貼上內容。當您滿意要插入的內容之後,請按貼上按鈕。若要中斷插入內容,請按取消按鈕。"}));
| hariomkumarmth/champaranexpress | wp-content/plugins/dojo/dojox/editor/plugins/nls/zh-tw/SafePaste.js | JavaScript | gpl-2.0 | 314 |
// This file has been generated by the GUI designer. Do not modify.
namespace Smuxi.Frontend.Gnome
{
public partial class EngineAssistantNameWidget
{
private global::Gtk.VBox vbox2;
private global::Gtk.VBox vbox3;
private global::Gtk.Label f_EngineNameLabel;
private global::Gtk.Entry f_EngineNameEntry;
private global::Gtk.Label label2;
private global::Gtk.VBox vbox4;
private global::Gtk.Label label7;
private global::Gtk.CheckButton f_MakeDefaultEngineCheckButton;
private global::Gtk.Label label8;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Smuxi.Frontend.Gnome.EngineAssistantNameWidget
global::Stetic.BinContainer.Attach (this);
this.Name = "Smuxi.Frontend.Gnome.EngineAssistantNameWidget";
// Container child Smuxi.Frontend.Gnome.EngineAssistantNameWidget.Gtk.Container+ContainerChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 10;
this.vbox2.BorderWidth = ((uint)(5));
// Container child vbox2.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.f_EngineNameLabel = new global::Gtk.Label ();
this.f_EngineNameLabel.Name = "f_EngineNameLabel";
this.f_EngineNameLabel.Xalign = 0f;
this.f_EngineNameLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("_Engine Name:");
this.f_EngineNameLabel.UseUnderline = true;
this.vbox3.Add (this.f_EngineNameLabel);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.f_EngineNameLabel]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.f_EngineNameEntry = new global::Gtk.Entry ();
this.f_EngineNameEntry.CanFocus = true;
this.f_EngineNameEntry.Name = "f_EngineNameEntry";
this.f_EngineNameEntry.IsEditable = true;
this.f_EngineNameEntry.InvisibleChar = '●';
this.vbox3.Add (this.f_EngineNameEntry);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.f_EngineNameEntry]));
w2.Position = 1;
w2.Expand = false;
w2.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.Xpad = 50;
this.label2.Xalign = 0f;
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size=\"small\">Profile name of the new engine</span>");
this.label2.UseMarkup = true;
this.vbox3.Add (this.label2);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label2]));
w3.Position = 2;
w3.Expand = false;
w3.Fill = false;
this.vbox2.Add (this.vbox3);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.vbox3]));
w4.Position = 0;
w4.Expand = false;
w4.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 6;
this.vbox4.BorderWidth = ((uint)(5));
// Container child vbox4.Gtk.Box+BoxChild
this.label7 = new global::Gtk.Label ();
this.label7.Name = "label7";
this.label7.Xalign = 0f;
this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("_Default Engine:");
this.label7.UseUnderline = true;
this.vbox4.Add (this.label7);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label7]));
w5.Position = 0;
w5.Expand = false;
w5.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.f_MakeDefaultEngineCheckButton = new global::Gtk.CheckButton ();
this.f_MakeDefaultEngineCheckButton.CanFocus = true;
this.f_MakeDefaultEngineCheckButton.Name = "f_MakeDefaultEngineCheckButton";
this.f_MakeDefaultEngineCheckButton.Label = global::Mono.Unix.Catalog.GetString ("Use as new default engine");
this.f_MakeDefaultEngineCheckButton.DrawIndicator = true;
this.f_MakeDefaultEngineCheckButton.UseUnderline = true;
this.vbox4.Add (this.f_MakeDefaultEngineCheckButton);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.f_MakeDefaultEngineCheckButton]));
w6.Position = 1;
w6.Expand = false;
w6.Fill = false;
// Container child vbox4.Gtk.Box+BoxChild
this.label8 = new global::Gtk.Label ();
this.label8.Name = "label8";
this.label8.Xpad = 50;
this.label8.Xalign = 0f;
this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("<span size=\"small\">If enabled, the current engine will be the default next time Smuxi is started</span>");
this.label8.UseMarkup = true;
this.label8.Wrap = true;
this.vbox4.Add (this.label8);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label8]));
w7.Position = 2;
w7.Expand = false;
w7.Fill = false;
this.vbox2.Add (this.vbox4);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.vbox4]));
w8.Position = 1;
w8.Expand = false;
w8.Fill = false;
this.Add (this.vbox2);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.f_EngineNameLabel.MnemonicWidget = this.f_EngineNameEntry;
this.label7.MnemonicWidget = this.f_MakeDefaultEngineCheckButton;
this.Hide ();
}
}
}
| tuukka/smuxi | src/Frontend-GNOME/gtk-gui/Smuxi.Frontend.Gnome.EngineAssistantNameWidget.cs | C# | gpl-2.0 | 5,273 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.threshd;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.xml.event.Event;
import org.springframework.util.Assert;
/**
* Implements a relative change threshold check. A 'value' setting of
* less than 1.0 means that a threshold will fire if the current value
* is less than or equal to the previous value multiplied by the 'value'
* setting. A 'value' setting greater than 1.0 causes the threshold to
* fire if the current value is greater than or equal to the previous
* value multiplied by the 'value' setting. A 'value' setting of 1.0
* (unity) is not allowed, as it represents no change. Zero valued
* samples (0.0) are ignored, as 0.0 multiplied by anything is 0.0 (if
* they were not ignored, an interface that gets no traffic would always
* trigger a threshold, for example).
*
* @author ranger
* @version $Id: $
*/
public class ThresholdEvaluatorRelativeChange implements ThresholdEvaluator {
private static final String TYPE = "relativeChange";
/** {@inheritDoc} */
@Override
public ThresholdEvaluatorState getThresholdEvaluatorState(BaseThresholdDefConfigWrapper threshold) {
return new ThresholdEvaluatorStateRelativeChange(threshold);
}
/** {@inheritDoc} */
@Override
public boolean supportsType(String type) {
return TYPE.equals(type);
}
public static class ThresholdEvaluatorStateRelativeChange extends AbstractThresholdEvaluatorState {
private BaseThresholdDefConfigWrapper m_thresholdConfig;
private double m_multiplier;
private double m_lastSample = 0.0;
private double m_previousTriggeringSample;
public ThresholdEvaluatorStateRelativeChange(BaseThresholdDefConfigWrapper threshold) {
Assert.notNull(threshold, "threshold argument cannot be null");
setThresholdConfig(threshold);
}
public void setThresholdConfig(BaseThresholdDefConfigWrapper thresholdConfig) {
Assert.notNull(thresholdConfig.getType(), "threshold must have a 'type' value set");
Assert.notNull(thresholdConfig.getDatasourceExpression(), "threshold must have a 'ds-name' value set");
Assert.notNull(thresholdConfig.getDsType(), "threshold must have a 'ds-type' value set");
Assert.isTrue(thresholdConfig.hasValue(), "threshold must have a 'value' value set");
Assert.isTrue(thresholdConfig.hasRearm(), "threshold must have a 'rearm' value set");
Assert.isTrue(thresholdConfig.hasTrigger(), "threshold must have a 'trigger' value set");
Assert.isTrue(TYPE.equals(thresholdConfig.getType()), "threshold for ds-name '" + thresholdConfig.getDatasourceExpression() + "' has type of '" + thresholdConfig.getType() + "', but this evaluator only supports thresholds with a 'type' value of '" + TYPE + "'");
Assert.isTrue(!Double.isNaN(thresholdConfig.getValue()), "threshold must have a 'value' value that is a number");
Assert.isTrue(thresholdConfig.getValue() != Double.POSITIVE_INFINITY && thresholdConfig.getValue() != Double.NEGATIVE_INFINITY, "threshold must have a 'value' value that is not positive or negative infinity");
Assert.isTrue(thresholdConfig.getValue() != 1.0, "threshold must not be unity (1.0)");
m_thresholdConfig = thresholdConfig;
setMultiplier(thresholdConfig.getValue());
}
@Override
public BaseThresholdDefConfigWrapper getThresholdConfig() {
return m_thresholdConfig;
}
@Override
public Status evaluate(double dsValue) {
//Fix for Bug 2275 so we handle negative numbers
//It will not handle values which cross the 0 boundary (from - to +, or v.v.) properly, but
// after some discussion, we can't come up with a sensible scenario when that would actually happen.
// If such a scenario eventuates, reconsider
dsValue=Math.abs(dsValue);
if (getLastSample() != 0.0) {
double threshold = getMultiplier() * getLastSample();
if (getMultiplier() < 1.0) {
if (dsValue <= threshold) {
setPreviousTriggeringSample(getLastSample());
setLastSample(dsValue);
return Status.TRIGGERED;
}
} else {
if (dsValue >= threshold) {
setPreviousTriggeringSample(getLastSample());
setLastSample(dsValue);
return Status.TRIGGERED;
}
}
setLastSample(dsValue);
}
setLastSample(dsValue);
return Status.NO_CHANGE;
}
public Double getLastSample() {
return m_lastSample;
}
public void setLastSample(double lastSample) {
m_lastSample = lastSample;
}
@Override
public Event getEventForState(Status status, Date date, double dsValue, CollectionResourceWrapper resource) {
if (status == Status.TRIGGERED) {
String uei=getThresholdConfig().getTriggeredUEI();
if(uei==null || "".equals(uei)) {
uei=EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI;
}
return createBasicEvent(uei, date, dsValue, resource);
} else {
return null;
}
}
private Event createBasicEvent(String uei, Date date, double dsValue, CollectionResourceWrapper resource) {
Map<String,String> params = new HashMap<String,String>();
params.put("previousValue", formatValue(getPreviousTriggeringSample()));
params.put("multiplier", Double.toString(getThresholdConfig().getValue()));
// params.put("trigger", Integer.toString(getThresholdConfig().getTrigger()));
// params.put("rearm", Double.toString(getThresholdConfig().getRearm()));
return createBasicEvent(uei, date, dsValue, resource, params);
}
public double getPreviousTriggeringSample() {
return m_previousTriggeringSample;
}
public void setPreviousTriggeringSample(double previousTriggeringSample) {
m_previousTriggeringSample = previousTriggeringSample;
}
public double getMultiplier() {
return m_multiplier;
}
public void setMultiplier(double multiplier) {
m_multiplier = multiplier;
}
@Override
public ThresholdEvaluatorState getCleanClone() {
return new ThresholdEvaluatorStateRelativeChange(m_thresholdConfig);
}
// FIXME This must be implemented correctly
@Override
public boolean isTriggered() {
return false;
}
// FIXME This must be implemented correctly
@Override
public void clearState() {
}
}
}
| rfdrake/opennms | opennms-services/src/main/java/org/opennms/netmgt/threshd/ThresholdEvaluatorRelativeChange.java | Java | gpl-2.0 | 8,358 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class add_o32_rAX_Id extends Executable
{
final int immd;
public add_o32_rAX_Id(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
immd = Modrm.Id(input);
}
public Branch execute(Processor cpu)
{
cpu.flagOp1 = cpu.r_eax.get32();
cpu.flagOp2 = immd;
cpu.flagResult = (cpu.flagOp1 + cpu.flagOp2);
cpu.r_eax.set32(cpu.flagResult);
cpu.flagIns = UCodes.ADD32;
cpu.flagStatus = OSZAPC;
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ianopolous/JPC | src/org/jpc/emulator/execution/opcodes/vm/add_o32_rAX_Id.java | Java | gpl-2.0 | 1,923 |
/******************************************************************************
* Warmux is a convivial mass murder game.
* Copyright (C) 2001-2011 Warmux Team.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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
******************************************************************************
* Team handling
*****************************************************************************/
#include <algorithm>
#include <iostream>
#include <WARMUX_file_tools.h>
#include <WARMUX_team_config.h>
#include "character/character.h"
#include "character/body_list.h"
#include "game/config.h"
#include "network/network.h"
#include "network/randomsync.h"
#include "team/team.h"
#include "team/team_energy.h"
#include "team/teams_list.h"
#include "tool/ansi_convert.h"
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
TeamsList::TeamsList():
full_list(),
playing_list(),
selection(),
groups(),
active_group(groups.end())
{
LoadList();
}
TeamsList::~TeamsList()
{
UnloadGamingData();
Clear();
for (full_iterator it = full_list.begin(); it != full_list.end(); ++it)
delete (*it);
full_list.clear();
groups.clear();
}
//-----------------------------------------------------------------------------
void TeamsList::NextTeam()
{
ActiveCharacter().StopPlaying();
Team* next = GetNextTeam();
SetActive(next->GetId());
next->NextCharacter(true);
printf("\nPlaying character : %i %s\n", ActiveCharacter().GetCharacterIndex(), ActiveCharacter().GetName().c_str());
printf("Playing team : %i %s\n", ActiveCharacter().GetTeamIndex(), ActiveTeam().GetName().c_str());
printf("Alive characters: %i / %i\n\n", ActiveTeam().NbAliveCharacter(),ActiveTeam().GetNbCharacters());
}
//-----------------------------------------------------------------------------
Team* TeamsList::GetNextTeam()
{
// Next group
GroupList::iterator git = active_group;
std::vector<Team*>::iterator it;
do {
++git;
if (git == groups.end())
git = groups.begin();
it = git->second.active_team;
do {
++it;
if (it == git->second.end())
it = git->second.begin();
} while (!(*it)->NbAliveCharacter() && it != git->second.active_team);
} while (git != active_group && !(*it)->NbAliveCharacter());
return (*it);
}
//-----------------------------------------------------------------------------
Team& TeamsList::ActiveTeam()
{
return **(active_group->second.active_team);
}
//-----------------------------------------------------------------------------
bool TeamsList::LoadOneTeam(const std::string &dir, const std::string &team_name)
{
// Skip '.', '..' and hidden files
if (team_name[0] == '.' || team_name == "SVN~1")
return false;
// Is it a directory ?
if (!DoesFolderExist(dir+team_name))
return false;
// Add the team
std::string real_name = ANSIToUTF8(dir, team_name);
std::string error;
Team *team = Team::LoadTeam(dir, real_name, error);
if (team) {
full_list.push_back(team);
std::cout << ((1<full_list.size())?", ":" ") << real_name;
std::cout.flush();
return true;
}
std::cerr << std::endl
<< Format(_("Error loading team :")) << real_name <<":"<< error
<< std::endl;
return false;
}
//-----------------------------------------------------------------------------
void TeamsList::LoadList()
{
playing_list.clear();
std::cout << "o " << _("Load teams:");
const Config * config = Config::GetInstance();
// Load Warmux teams
std::string dirname = config->GetDataDir() + "team" PATH_SEPARATOR;
FolderSearch *f = OpenFolder(dirname);
if (f) {
const char *name;
bool search_file = false;
while ((name = FolderSearchNext(f, search_file)) != NULL)
LoadOneTeam(dirname, name);
CloseFolder(f);
} else {
Error(Format(_("Cannot open teams directory (%s)!"), dirname.c_str()));
}
// Load personal teams
dirname = config->GetPersonalDataDir() + "team" PATH_SEPARATOR;
f = OpenFolder(dirname);
if (f) {
bool search_files = false;
const char *name;
while ((name = FolderSearchNext(f, search_files)) != NULL)
LoadOneTeam(dirname, name);
CloseFolder(f);
} else {
std::cerr << std::endl
<< Format(_("Cannot open personal teams directory (%s)!"), dirname.c_str())
<< std::endl;
}
full_list.sort(compareTeams);
// We need at least 2 teams
if (full_list.size() < 2)
Error(_("You need at least two valid teams!"));
// Default selection
std::list<uint> nv_selection;
nv_selection.push_back(0);
nv_selection.push_back(1);
ChangeSelection(nv_selection);
std::cout << std::endl;
InitList(Config::GetInstance()->AccessTeamList());
}
//-----------------------------------------------------------------------------
void TeamsList::LoadGamingData(WeaponsList * weapons_list)
{
//std::sort(playing_list.begin(), playing_list.end(), compareTeams); // needed to fix bug #9820
iterator it=playing_list.begin(), end=playing_list.end();
// Load the data of all teams
for (; it != end; ++it) {
(*it)->LoadGamingData(weapons_list);
}
groups.clear();
for (it=playing_list.begin(); it != end; ++it) {
groups[ (*it)->GetGroup() ].push_back(*it);
if ((*it)->IsLocalAI())
(*it)->LoadAI();
}
}
void TeamsList::RandomizeFirstPlayer()
{
MSG_DEBUG("random.get", "TeamList::RandomizeFirstPlayer()");
int skip = RandomSync().GetInt(0, groups.size()-1);
for (GroupList::iterator git = groups.begin(); git != groups.end(); ++git) {
if (!(skip--))
active_group = git;
TeamGroup& g = git->second;
int skip2 = RandomSync().GetInt(1, g.size());
g.active_team = g.begin();
while (--skip2)
g.active_team++;
}
}
//-----------------------------------------------------------------------------
void TeamsList::UnloadGamingData()
{
groups.clear();
// Iterate over all teams not just he playing ones
// in order to unload leaver teams.
full_iterator it=full_list.begin(), end = full_list.end();
// Unload the data of all teams
for (; it != end; ++it)
(**it).UnloadGamingData();
// Run this now as no reference from Character are left
BodyList::GetRef().FreeMem();
}
//-----------------------------------------------------------------------------
Team *TeamsList::FindById(const std::string &id, int &pos)
{
full_iterator it=full_list.begin(), end = full_list.end();
int i=0;
for (; it != end; ++it, ++i) {
if ((*it)->GetId() == id) {
pos = i;
return (*it);
}
}
pos = -1;
return NULL;
}
//-----------------------------------------------------------------------------
Team *TeamsList::FindByIndex(uint index)
{
if (full_list.size() < index+1) {
ASSERT(false);
return NULL;
}
full_iterator it = full_list.begin(), end = full_list.end();
uint i=0;
for (; it != end; ++it, ++i) {
if (i == index)
return (*it);
}
return NULL;
}
//-----------------------------------------------------------------------------
Team* TeamsList::FindPlayingById(const std::string &id, int &index)
{
iterator it = playing_list.begin(), end = playing_list.end();
index=0;
for (; it != end; ++it, ++index) {
if ((*it) -> GetId() == id)
return *it;
}
index = -1;
ASSERT(false);
return NULL;
}
//-----------------------------------------------------------------------------
void TeamsList::InitList(const std::list<ConfigTeam> &lst)
{
Clear();
std::list<ConfigTeam>::const_iterator it=lst.begin(), end=lst.end();
for (; it != end; ++it)
AddTeam(*it, true, false);
}
//-----------------------------------------------------------------------------
void TeamsList::InitEnergy()
{
// Looking at team with the greatest energy
// (in case teams does not have same amount of character)
iterator it = playing_list.begin(), end = playing_list.end();
uint max = 0;
for (; it != end; ++it) {
if ((**it).ReadEnergy() > max)
max = (**it).ReadEnergy();
}
// Init each team's energy bar
it=playing_list.begin();
for (; it != end; ++it)
(**it).InitEnergy(max);
// Initial ranking
it=playing_list.begin();
for (; it != end; ++it) {
uint rank = 0;
iterator it2=playing_list.begin();
for (; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() > (**it).ReadEnergy())
++rank;
}
(**it).energy.rank_tmp = rank;
}
it=playing_list.begin();
for (; it != end; ++it) {
uint rank = (**it).energy.rank_tmp;
iterator it2=playing_list.begin();
for (it2 = it; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() == (**it).ReadEnergy())
++rank;
}
(**it).energy.SetRanking(rank);
}
}
//-----------------------------------------------------------------------------
void TeamsList::RefreshEnergy()
{
// In the order of the priorit :
// - finish current action
// - change a teams energy
// - change ranking
// - prepare energy bar for next event
iterator it=playing_list.begin(), end = playing_list.end();
energy_t status;
bool waiting = true; // every energy bar are waiting
for (; it != end; ++it) {
if ((**it).energy.status != EnergyStatusWait) {
waiting = false;
break;
}
}
// one of the energy bar is changing ?
if (!waiting) {
status = EnergyStatusOK;
// change an energy bar value ?
for (it=playing_list.begin(); it != end; ++it) {
if ((**it).energy.status == EnergyStatusValueChange) {
status = EnergyStatusValueChange;
break;
}
}
// change a ranking ?
for (it=playing_list.begin(); it != end; ++it) {
if ((**it).energy.status == EnergyStatusRankChange
&& ((**it).energy.IsMoving() || status == EnergyStatusOK)) {
status = EnergyStatusRankChange;
break;
}
}
}
else {
// every energy bar are waiting
// -> set state ready for a new event
status = EnergyStatusOK;
}
// Setting event to process in every energy bar
if (status != EnergyStatusOK || waiting) {
it = playing_list.begin();
for (; it != end; ++it) {
(**it).energy.status = status;
}
}
// Actualisation des valeurs (pas d'actualisation de l'affichage)
for (it=playing_list.begin(); it != end; ++it) {
(**it).UpdateEnergyBar();
}
RefreshSort();
}
//-----------------------------------------------------------------------------
void TeamsList::RefreshSort()
{
iterator it=playing_list.begin(), end = playing_list.end();
uint rank;
// Find a ranking without taking acount of the equalities
it = playing_list.begin();
for (; it != end; ++it) {
rank = 0;
iterator it2=playing_list.begin();
for (; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() > (**it).ReadEnergy())
++rank;
}
(**it).energy.rank_tmp = rank;
}
// Fix equalities
it = playing_list.begin();
for (; it != end; ++it) {
rank = (**it).energy.rank_tmp;
iterator it2=playing_list.begin();
for (it2 = it; it2 != end; ++it2) {
if (it != it2 && (**it2).ReadEnergy() == (**it).ReadEnergy())
++rank;
}
(**it).energy.NewRanking(rank);
}
}
//-----------------------------------------------------------------------------
void TeamsList::ChangeSelection(const std::list<uint>& nv_selection)
{
selection = nv_selection;
selection_iterator it=selection.begin(), end = selection.end();
playing_list.clear();
for (; it != end; ++it)
playing_list.push_back(FindByIndex(*it));
}
//-----------------------------------------------------------------------------
bool TeamsList::IsSelected(uint index)
{
selection_iterator pos = std::find(selection.begin(), selection.end(), index);
return pos != selection.end();
}
//-----------------------------------------------------------------------------
void TeamsList::AddTeam(Team* the_team, int pos, const ConfigTeam &the_team_cfg,
bool is_local)
{
ASSERT(the_team != NULL);
the_team->SetRemote(!is_local);
UpdateTeam(the_team, the_team_cfg);
selection.push_back(pos);
playing_list.push_back(the_team);
}
void TeamsList::AddTeam(const ConfigTeam &the_team_cfg, bool is_local,
bool generate_error)
{
MSG_DEBUG("team", "%s, local: %d\n", the_team_cfg.id.c_str(), is_local);
int pos;
Team *the_team = FindById(the_team_cfg.id, pos);
if (the_team != NULL) {
AddTeam(the_team, pos, the_team_cfg, is_local);
} else {
std::string msg = Format(_("Can't find team %s!"), the_team_cfg.id.c_str());
if (generate_error)
Error (msg);
else
std::cout << "! " << msg << std::endl;
}
}
//-----------------------------------------------------------------------------
void TeamsList::UpdateTeam(Team* the_team, const ConfigTeam &the_team_cfg)
{
ASSERT(the_team);
// set the player name and number of characters
the_team->SetPlayerName(the_team_cfg.player_name);
the_team->SetNbCharacters(the_team_cfg.nb_characters);
the_team->SetAIName(the_team_cfg.ai);
the_team->SetGroup(the_team_cfg.group);
}
Team* TeamsList::UpdateTeam(const std::string& old_team_id,
const ConfigTeam &the_team_cfg)
{
int pos;
Team *the_team = NULL;
MSG_DEBUG("team", "%s/%s\n", old_team_id.c_str(), the_team_cfg.id.c_str());
if (old_team_id == the_team_cfg.id) {
// this is a simple update
the_team = FindById(the_team_cfg.id, pos);
if (the_team) {
UpdateTeam(the_team, the_team_cfg);
} else {
Error(Format(_("Can't find team %s!"), the_team_cfg.id.c_str()));
}
return the_team;
}
// here we are replacing a team by another one
Team *the_old_team = FindById(old_team_id, pos);
if (!the_old_team) {
Error(Format(_("Can't find team %s!"), old_team_id.c_str()));
return NULL;
}
the_team = FindById(the_team_cfg.id, pos);
if (!the_team) {
Error(Format(_("Can't find team %s!"), old_team_id.c_str()));
return NULL;
}
bool is_local = the_old_team->IsLocal();
DelTeam(the_old_team);
AddTeam(the_team, pos, the_team_cfg, is_local);
return the_team;
}
//-----------------------------------------------------------------------------
void TeamsList::DelTeam(Team* the_team)
{
uint pos = 0;
ASSERT(the_team);
MSG_DEBUG("team", "%s\n", the_team->GetId().c_str());
the_team->SetDefaultPlayingConfig();
selection_iterator it = std::find(selection.begin(), selection.end(), pos);
if (it != selection.end())
selection.erase(it);
iterator playing_it = std::find(playing_list.begin(), playing_list.end(), the_team);
ASSERT(playing_it != playing_list.end());
if (playing_it != playing_list.end())
playing_list.erase(playing_it);
}
void TeamsList::DelTeam(const std::string &id)
{
int pos;
Team *the_team = FindById(id, pos);
DelTeam(the_team);
}
//-----------------------------------------------------------------------------
void TeamsList::SetActive(const std::string &id)
{
for (GroupList::iterator git = groups.begin(); git != groups.end(); ++git) {
for (TeamGroup::iterator it = git->second.begin(); it != git->second.end(); ++it) {
if ((*it)->GetId() == id) {
active_group = git;
git->second.active_team = it;
(*it)->PrepareTurn();
return;
}
}
}
Error(Format(_("Can't find team %s!"), id.c_str()));
}
Character& ActiveCharacter()
{
return ActiveTeam().ActiveCharacter();
}
bool compareTeams(const Team *a, const Team *b)
{
return a->GetName() < b->GetName();
}
| yeKcim/warmux | trunk/src/team/teams_list.cpp | C++ | gpl-2.0 | 16,291 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class fdiv_ST1_ST1 extends Executable
{
public fdiv_ST1_ST1(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(1);
double freg1 = cpu.fpu.ST(1);
if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1)))
cpu.fpu.setInvalidOperation();
if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1))
cpu.fpu.setZeroDivide();
cpu.fpu.setST(1, freg0/freg1);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/vm/fdiv_ST1_ST1.java | Java | gpl-2.0 | 2,046 |
<?php
/**
* Joomla! component Creative Contact Form
*
* @version $Id: 2012-04-05 14:30:25 svn $
* @author creative-solutions.net
* @package Creative Contact Form
* @subpackage com_creativecontactform
* @license GNU/GPL
*
*/
// no direct access
defined('_JEXEC') or die('Restircted access');
abstract class JHtmlCreativeForm
{
/**
* @param int $value The featured value
* @param int $i
* @param bool $canChange Whether the value can be changed or not
*
* @return string The anchor tag to toggle featured/unfeatured contacts.
* @since 1.6
*/
static function featured($value = 0, $i, $canChange = true)
{
// Array of image, task, title, action
$states = array(
0 => array('disabled.png', 'creativeforms.featured', 'COM_CREATIVECONTACTFORM_UNFEATURED', 'COM_CREATIVECONTACTFORM_UNFEATURED'),
1 => array('featured.png', 'creativeforms.unfeatured', 'COM_CREATIVECONTACTFORM_FEATURED', 'COM_CREATIVECONTACTFORM_FEATURED'),
);
$state = JArrayHelper::getValue($states, (int) $value, $states[1]);
$html = JHtml::_('image', 'admin/'.$state[0], JText::_($state[2]), NULL, true);
if ($canChange) {
$html = '<a href="#" onclick="return listItemTask(\'cb'.$i.'\',\''.$state[1].'\')" title="'.JText::_($state[3]).'">'
. $html .'</a>';
}
return $html;
}
}
| ankibalyan/businesssetup | administrator/components/com_creativecontactform/helpers/html/creativeform.php | PHP | gpl-2.0 | 1,299 |
<?php
class FrmListEntries extends WP_Widget {
function __construct() {
$widget_ops = array( 'description' => __( "Display a list of Formidable entries", 'formidable') );
$this->WP_Widget('frm_list_items', __('Formidable Entries List', 'formidable'), $widget_ops);
}
function widget( $args, $instance ) {
global $frmdb, $wpdb, $frm_entry, $frmpro_display, $frm_entry_meta;
extract($args);
$display = $frmpro_display->getOne($instance['display_id'], false, true);
$title = apply_filters('widget_title', (empty($instance['title']) and $display) ? $display->post_title : $instance['title']);
$limit = empty($instance['limit']) ? ' LIMIT 100' : " LIMIT {$instance['limit']}";
$post_id = (!$display or empty($display->frm_post_id)) ? $instance['post_id'] : $display->frm_post_id;
$page_url = get_permalink($post_id);
$order_by = '';
if ($display && is_numeric($display->frm_form_id) && !empty($display->frm_form_id) ) {
//Set up order for Entries List Widget
if ( isset($display->frm_order_by) && !empty($display->frm_order_by) ) {
//Get only the first order field and order
$order_field = reset($display->frm_order_by);
$order = reset($display->frm_order);
if ( $order_field == 'rand' ) {//If random is set, set the order to random
$order_by = ' RAND()';
} else if ( is_numeric($order_field) ) {//If ordering by a field
//Get all post IDs for this form
$posts = $wpdb->get_results($wpdb->prepare("SELECT id, post_id FROM {$wpdb->prefix}frm_items WHERE form_id=%d and post_id>%d AND is_draft=%d", $display->frm_form_id, 1, 0));
$linked_posts = array();
foreach ( $posts as $post_meta ) {
$linked_posts[$post_meta->post_id] = $post_meta->id;
}
//Get all field information
$frm_field = new FrmField();
$o_field = $frm_field->getOne($order_field);
//create query with ordered values
if ( isset($o_field->field_options['post_field']) and $o_field->field_options['post_field'] ) { //if field is some type of post field
if ( $o_field->field_options['post_field'] == 'post_custom' && ! empty($linked_posts) ) { //if field is custom field
$query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->postmeta} pm ON pm.post_id=m.post_id AND pm.meta_key='". $o_field->field_options['custom_field']."' WHERE pm.post_id in (". implode(',', array_keys($linked_posts)).") ORDER BY CASE when pm.meta_value IS NULL THEN 1 ELSE 0 END, pm.meta_value {$order}";
} else if ( $o_field->field_options['post_field'] != 'post_category' && ! empty($linked_posts) ) {//if field is a non-category post field
$query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->posts} p ON p.ID=m.post_id WHERE p.ID in (". implode(',', array_keys($linked_posts)).") ORDER BY CASE p.".$o_field->field_options['post_field']." WHEN '' THEN 1 ELSE 0 END, p.".$o_field->field_options['post_field']." {$order}";
}
} else { //if field is a normal, non-post field
$query = "SELECT m.id FROM {$wpdb->prefix}frm_items m INNER JOIN {$wpdb->prefix}frm_item_metas em ON em.item_id=m.id WHERE em.field_id=$o_field->id ORDER BY CASE when em.meta_value IS NULL THEN 1 ELSE 0 END, em.meta_value".($o_field->type == 'number' ? ' +0 ' : '')." {$order}";
}
//Get ordered values
$metas = $wpdb->get_results($query);
unset($query);
if (is_array($metas) and !empty($metas)){
$desc_order = ' DESC';
foreach ($metas as $meta)
$order_by .= $wpdb->prepare('it.id=%d'. $desc_order.', ', $meta->id);
$order_by = rtrim($order_by, ', ');
} else {
$order_by .= 'it.created_at '. $order;
}
} else if ( !empty($order_field) ) { //If ordering by created_at or updated_at
$order_by = 'it.'.$order_field.' '.$order;
}
if ( !empty($order_by) ) {
$order_by = ' ORDER BY '. $order_by;
}
}
if (isset($instance['cat_list']) and (int)$instance['cat_list'] == 1 and is_numeric($instance['cat_id'])){
global $frm_field;
if ($cat_field = $frm_field->getOne($instance['cat_id']))
$categories = maybe_unserialize($cat_field->options);
}
}
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
echo "<ul id='frm_entry_list". (($display) ? $display->frm_form_id : '') ."'>\n";
//if Listing entries by category
if ( isset($instance['cat_list']) and (int)$instance['cat_list'] == 1 and isset($categories) and is_array($categories) ) {
foreach ($categories as $cat_order => $cat){
if ($cat == '') continue;
echo '<li>';
if (isset($instance['cat_name']) and (int)$instance['cat_name'] == 1)
echo '<a href="'. add_query_arg(array('frm_cat' => $cat_field->field_key, 'frm_cat_id' => $cat_order), $page_url) .'">';
echo $cat;
if (isset($instance['cat_count']) and (int)$instance['cat_count'] == 1)
echo ' ('. FrmProFieldsHelper::get_field_stats($instance['cat_id'], 'count', false, $cat) .')';
if (isset($instance['cat_name']) and (int)$instance['cat_name'] == 1){
echo '</a>';
}else{
$entry_ids = $frm_entry_meta->getEntryIds("meta_value LIKE '%$cat%' and fi.id=". $instance['cat_id']);
$items = false;
if ($entry_ids)
$items = $frm_entry->getAll("it.id in (". implode(',', $entry_ids) .") and it.form_id =". (int)$display->frm_form_id, $order_by, $limit);
if ($items){
echo '<ul>';
foreach ($items as $item){
$url_id = $display->frm_type == 'id' ? $item->id : $item->item_key;
$current = (isset($_GET[$display->frm_param]) and $_GET[$display->frm_param] == $url_id) ? ' class="current_page"' : '';
if($item->post_id)
$entry_link = get_permalink($item->post_id);
else
$entry_link = add_query_arg(array($display->frm_param => $url_id), $page_url);
echo '<li'. $current .'><a href="'. $entry_link .'">'. $item->name .'</a></li>'. "\n";
}
echo '</ul>';
}
}
echo '</li>';
}
}else{ // if not listing entries by category
if($display)
$items = $frm_entry->getAll(array('it.form_id' => $display->frm_form_id, 'is_draft' => '0'), $order_by, $limit);
else
$items = array();
foreach ($items as $item){
$url_id = $display->frm_type == 'id' ? $item->id : $item->item_key;
$current = (isset($_GET[$display->frm_param]) and $_GET[$display->frm_param] == $url_id) ? ' class="current_page"' : '';
echo "<li". $current ."><a href='".add_query_arg(array($display->frm_param => $url_id), $page_url)."'>". $item->name ."</a></li>\n";
}
}
echo "</ul>\n";
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
return $new_instance;
}
function form( $instance ) {
global $frmpro_display;
$pages = get_posts( array('post_type' => 'page', 'post_status' => 'publish', 'numberposts' => 999, 'order_by' => 'post_title', 'order' => 'ASC'));
$displays = $frmpro_display->getAll(array('meta_key' => 'show_count', 'meta_value' => 'dynamic'));
//Defaults
$instance = wp_parse_args( (array) $instance, array('title' => false, 'display_id' => false, 'post_id' => false, 'title_id' => false, 'cat_list' => false, 'cat_name' => false, 'cat_count' => false, 'cat_id' => false, 'limit' => false) );
$cat_opts = false;
if ($instance['display_id']){
global $frm_field;
$selected_display = $frmpro_display->getOne($instance['display_id']);
if($selected_display){
$selected_form_id = get_post_meta($selected_display->ID, 'frm_form_id', true);
$title_opts = $frm_field->getAll("fi.form_id=". (int)$selected_form_id ." and type not in ('divider','captcha','break','html')", ' ORDER BY field_order');
$instance['display_id'] = $selected_display->ID;
}
}
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'formidable') ?>:</label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr( stripslashes($instance['title']) ); ?>" /></p>
<p><label for="<?php echo $this->get_field_id('display_id'); ?>"><?php _e('Use Settings from View', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('display_id'); ?>" id="<?php echo $this->get_field_id('display_id'); ?>" class="widefat" onchange="frm_get_display_fields(this.value)">
<option value=""></option>
<?php foreach ($displays as $display)
echo "<option value=". $display->ID . selected( $instance['display_id'], $display->ID ) .">" . $display->post_title . "</option>";
?>
</select>
</p>
<p class="description"><?php _e('Views with a "Both (Dynamic)" format will show here.', 'formidable') ?></p>
<p><label for="<?php echo $this->get_field_id('post_id'); ?>"><?php _e('Page if not specified in View settings', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('post_id'); ?>" id="<?php echo $this->get_field_id('post_id'); ?>" class="widefat">
<option value=""></option>
<?php foreach ($pages as $page)
echo "<option value=". $page->ID . selected( $instance['post_id'], $page->ID ) . ">" . $page->post_title . "</option>";
?>
</select>
</p>
<p><label for="<?php echo $this->get_field_id('title_id'); ?>"><?php _e('Title Field', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('title_id'); ?>" id="<?php echo $this->get_field_id('title_id'); ?>" class="widefat">
<option value=""></option>
<?php
if (isset($title_opts) and $title_opts){
foreach ($title_opts as $title_opt)
if($title_opt->type != 'checkbox')
echo "<option value=". $title_opt->id . selected( $instance['title_id'], $title_opt->id ) . ">" . $title_opt->name . "</option>";
}
?>
</select>
</p>
<p><label for="<?php echo $this->get_field_id('cat_list'); ?>"><input class="checkbox" type="checkbox" <?php checked($instance['cat_list'], true) ?> id="<?php echo $this->get_field_id('cat_list'); ?>" name="<?php echo $this->get_field_name('cat_list'); ?>" value="1" onclick="frm_toggle_cat_opt(this.checked)"/>
<?php _e('List Entries by Category', 'formidable') ?></label></p>
<div id="<?php echo $this->get_field_id('hide_cat_opts'); ?>">
<p><label for="<?php echo $this->get_field_id('cat_id'); ?>"><?php _e('Category Field', 'formidable') ?>:</label>
<select name="<?php echo $this->get_field_name('cat_id'); ?>" id="<?php echo $this->get_field_id('cat_id'); ?>" class="widefat">
<option value=""></option>
<?php
if (isset($title_opts) and $title_opts){
foreach ($title_opts as $title_opt){
if(in_array($title_opt->type, array('select', 'radio', 'checkbox')))
echo "<option value=". $title_opt->id . selected( $instance['cat_id'], $title_opt->id ) . ">" . $title_opt->name . "</option>";
}
}
?>
</select>
</p>
<p><label for="<?php echo $this->get_field_id('cat_count'); ?>"><input class="checkbox" type="checkbox" <?php checked($instance['cat_count'], true) ?> id="<?php echo $this->get_field_id('cat_count'); ?>" name="<?php echo $this->get_field_name('cat_count'); ?>" value="1" />
<?php _e('Show Entry Counts', 'formidable') ?></label></p>
<p><input class="checkbox" type="radio" <?php checked($instance['cat_name'], 1) ?> id="<?php echo $this->get_field_id('cat_name'); ?>" name="<?php echo $this->get_field_name('cat_name'); ?>" value="1" />
<label for="<?php echo $this->get_field_id('cat_name'); ?>"><?php _e('Show Only Category Name', 'formidable') ?></label><br/>
<input class="checkbox" type="radio" <?php checked($instance['cat_name'], 0) ?> id="<?php echo $this->get_field_id('cat_name'); ?>" name="<?php echo $this->get_field_name('cat_name'); ?>" value="0" />
<label for="<?php echo $this->get_field_id('cat_name'); ?>"><?php _e('Show Entries Beneath Categories', 'formidable') ?></label></p>
</div>
<p><label for="<?php echo $this->get_field_id('limit'); ?>"><?php _e('Entry Limit (leave blank to list all)', 'formidable') ?>:</label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" value="<?php echo esc_attr( $instance['limit'] ); ?>" /></p>
<script type="text/javascript">
jQuery(document).ready(function($){
jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").hide();
if (jQuery("#<?php echo $this->get_field_id('cat_list'); ?>").attr("checked"))
jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").show();
});
function frm_toggle_cat_opt(checked){
if (checked) jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").fadeIn('slow');
else jQuery("#<?php echo $this->get_field_id('hide_cat_opts') ?>").fadeOut('slow');
}
function frm_get_display_fields(display_id){
if (display_id != ''){
jQuery.ajax({ type:"POST", url:"<?php echo admin_url('admin-ajax.php') ?>",
data:"action=frm_get_cat_opts&display_id="+display_id,
success:function(msg){jQuery("#<?php echo $this->get_field_id('cat_id'); ?>").html(msg);}
});
jQuery.ajax({ type:"POST", url:"<?php echo admin_url('admin-ajax.php') ?>",
data:"action=frm_get_title_opts&display_id="+display_id,
success:function(msg){jQuery("#<?php echo $this->get_field_id('title_id'); ?>").html(msg);}
});
}
}
</script>
<?php
}
}
?> | rafapires/souza-aranha | wp-content/plugins/formidable/pro/classes/widgets/FrmListEntries.php | PHP | gpl-2.0 | 15,104 |
<?php defined('_JEXEC') or die('Restricted access'); ?>
<?php $form = @$this->form; ?>
<?php $row = @$this->row;
JFilterOutput::objectHTMLSafe( $row );
?>
<form action="<?php echo JRoute::_( @$form['action'] ) ?>" method="post" class="adminform" name="adminForm" >
<fieldset>
<legend><?php echo JText::_('Form'); ?></legend>
<table class="admintable">
<tr>
<td width="100" align="right" class="key">
<label for="tax_class_name">
<?php echo JText::_( 'Name' ); ?>:
</label>
</td>
<td>
<input type="text" name="tax_class_name" id="tax_class_name" size="48" maxlength="250" value="<?php echo @$row->tax_class_name; ?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="tax_class_description">
<?php echo JText::_( 'Description' ); ?>:
</label>
</td>
<td>
<textarea name="tax_class_description" id="tax_class_description" rows="10" cols="25"><?php echo @$row->tax_class_description; ?></textarea>
</td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo @$row->tax_class_id; ?>" />
<input type="hidden" name="task" value="" />
</fieldset>
</form> | zuverza/se | tmp/install_4f46ab24b6733/admin/views/taxclasses/tmpl/form.php | PHP | gpl-2.0 | 1,203 |
<?php
class FlipMegazineImageHelper
{
/**
* @param int $parentNodeId
* @param eZCLI $cli
*/
public static function deleteThumb( $parentNodeId, $cli = null )
{
/** @var eZContentObjectTreeNode[] $children */
$children = eZContentObjectTreeNode::subTreeByNodeID(
array( 'ClassFilterType' => 'include',
'ClassFilterArray' => array( 'image' ) ),
$parentNodeId
);
if ( count( $children ) > 0 )
{
$message = "Remove " . count( $children ) . " images from node $parentNodeId";
if ( $cli )
{
$cli->output( $message );
}
else
{
eZDebug::writeNotice( $message , __METHOD__ );
}
foreach ( $children as $node )
{
$node->removeNodeFromTree();
}
}
}
/**
* @param string $directory
* @param string $imageName
* @param string $parentNodeId
* @return eZContentObject|false
*/
public static function createThumb( $directory, $imageName, $parentNodeId )
{
$user = eZUser::currentUser();
$params = array();
$params['class_identifier'] = 'image';
$params['creator_id'] = $user->attribute( 'contentobject_id' );
$params['parent_node_id'] = $parentNodeId;
$params['storage_dir'] = eZSys::rootDir() . eZSys::fileSeparator() . $directory . '/';
$attributesData = array ( ) ;
$attributesData['name'] = $imageName;
$attributesData['image'] = $imageName;
$params['attributes'] = $attributesData;
$imageContentObject = eZContentFunctions::createAndPublishObject($params);
return $imageContentObject;
}
}
?>
| Opencontent/ezflip | classes/handlers/megazine/megazineimagehelper.php | PHP | gpl-2.0 | 1,790 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.icmp;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>SinglePingResponseCallback class.</p>
*
* @author <a href="mailto:ranger@opennms.org">Ben Reed</a>
* @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a>
*/
public class SinglePingResponseCallback implements PingResponseCallback {
private static final Logger LOG = LoggerFactory
.getLogger(SinglePingResponseCallback.class);
/**
* Value of round-trip-time for the ping in microseconds.
*/
private Long m_responseTime = null;
private InetAddress m_host;
private Throwable m_error = null;
private CountDownLatch m_latch = new CountDownLatch(1);
/**
* <p>Constructor for SinglePingResponseCallback.</p>
*
* @param host a {@link java.net.InetAddress} object.
*/
public SinglePingResponseCallback(InetAddress host) {
m_host = host;
}
/** {@inheritDoc} */
@Override
public void handleResponse(InetAddress address, EchoPacket response) {
try {
info("got response for address " + address + ", thread " + response.getIdentifier() + ", seq " + response.getSequenceNumber() + " with a responseTime "+response.elapsedTime(TimeUnit.MILLISECONDS)+"ms");
m_responseTime = (long)Math.round(response.elapsedTime(TimeUnit.MICROSECONDS));
} finally {
m_latch.countDown();
}
}
/** {@inheritDoc} */
@Override
public void handleTimeout(InetAddress address, EchoPacket request) {
try {
assert(request != null);
info("timed out pinging address " + address + ", thread " + request.getIdentifier() + ", seq " + request.getSequenceNumber());
} finally {
m_latch.countDown();
}
}
/** {@inheritDoc} */
@Override
public void handleError(InetAddress address, EchoPacket request, Throwable t) {
try {
m_error = t;
info("an error occurred pinging " + address, t);
} finally {
m_latch.countDown();
}
}
/**
* <p>waitFor</p>
*
* @param timeout a long.
* @throws java.lang.InterruptedException if any.
*/
public void waitFor(long timeout) throws InterruptedException {
m_latch.await(timeout, TimeUnit.MILLISECONDS);
}
/**
* <p>waitFor</p>
*
* @throws java.lang.InterruptedException if any.
*/
public void waitFor() throws InterruptedException {
info("waiting for ping to "+m_host+" to finish");
m_latch.await();
info("finished waiting for ping to "+m_host+" to finish");
}
public void rethrowError() throws Exception {
if (m_error instanceof Error) {
throw (Error)m_error;
} else if (m_error instanceof Exception) {
throw (Exception)m_error;
}
}
/**
* <p>Getter for the field <code>responseTime</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getResponseTime() {
return m_responseTime;
}
public Throwable getError() {
return m_error;
}
/**
* <p>info</p>
*
* @param msg a {@link java.lang.String} object.
*/
public void info(String msg) {
LOG.info(msg);
}
/**
* <p>info</p>
*
* @param msg a {@link java.lang.String} object.
* @param t a {@link java.lang.Throwable} object.
*/
public void info(String msg, Throwable t) {
LOG.info(msg, t);
}
}
| rfdrake/opennms | opennms-icmp/opennms-icmp-api/src/main/java/org/opennms/netmgt/icmp/SinglePingResponseCallback.java | Java | gpl-2.0 | 4,879 |
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Layer.js
*/
/**
* Class: OpenLayers.Layer.Markers
*
* Inherits from:
* - <OpenLayers.Layer>
*/
OpenLayers.Layer.Markers = OpenLayers.Class(OpenLayers.Layer, {
/**
* APIProperty: isBaseLayer
* {Boolean} Markers layer is never a base layer.
*/
isBaseLayer: false,
/**
* APIProperty: markers
* {Array(<OpenLayers.Marker>)} internal marker list
*/
markers: null,
/**
* Property: drawn
* {Boolean} internal state of drawing. This is a workaround for the fact
* that the map does not call moveTo with a zoomChanged when the map is
* first starting up. This lets us catch the case where we have *never*
* drawn the layer, and draw it even if the zoom hasn't changed.
*/
drawn: false,
/**
* Constructor: OpenLayers.Layer.Markers
* Create a Markers layer.
*
* Parameters:
* name - {String}
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, options) {
OpenLayers.Layer.prototype.initialize.apply(this, arguments);
this.markers = [];
},
/**
* APIMethod: destroy
*/
destroy: function() {
this.clearMarkers();
this.markers = null;
OpenLayers.Layer.prototype.destroy.apply(this, arguments);
},
/**
* APIMethod: setOpacity
* Sets the opacity for all the markers.
*
* Parameter:
* opacity - {Float}
*/
setOpacity: function(opacity) {
if (opacity != this.opacity) {
this.opacity = opacity;
for (var i=0, len=this.markers.length; i<len; i++) {
this.markers[i].setOpacity(this.opacity);
}
}
},
/**
* Method: moveTo
*
* Parameters:
* bounds - {<OpenLayers.Bounds>}
* zoomChanged - {Boolean}
* dragging - {Boolean}
*/
moveTo:function(bounds, zoomChanged, dragging) {
OpenLayers.Layer.prototype.moveTo.apply(this, arguments);
if (zoomChanged || !this.drawn) {
for(var i=0, len=this.markers.length; i<len; i++) {
this.drawMarker(this.markers[i]);
}
this.drawn = true;
}
},
/**
* APIMethod: addMarker
*
* Parameters:
* marker - {<OpenLayers.Marker>}
*/
addMarker: function(marker) {
this.markers.push(marker);
if (this.opacity != null) {
marker.setOpacity(this.opacity);
}
if (this.map && this.map.getExtent()) {
marker.map = this.map;
this.drawMarker(marker);
}
},
/**
* APIMethod: removeMarker
*
* Parameters:
* marker - {<OpenLayers.Marker>}
*/
removeMarker: function(marker) {
if (this.markers && this.markers.length) {
OpenLayers.Util.removeItem(this.markers, marker);
marker.erase();
}
},
/**
* Method: clearMarkers
* This method removes all markers from a layer. The markers are not
* destroyed by this function, but are removed from the list of markers.
*/
clearMarkers: function() {
if (this.markers != null) {
while(this.markers.length > 0) {
this.removeMarker(this.markers[0]);
}
}
},
/**
* Method: drawMarker
* Calculate the pixel location for the marker, create it, and
* add it to the layer's div
*
* Parameters:
* marker - {<OpenLayers.Marker>}
*/
drawMarker: function(marker) {
var px = this.map.getLayerPxFromLonLat(marker.lonlat);
if (px == null) {
marker.display(false);
} else {
if (!marker.isDrawn()) {
var markerImg = marker.draw(px);
this.div.appendChild(markerImg);
} else if(marker.icon) {
marker.icon.moveTo(px);
}
}
},
/**
* APIMethod: getDataExtent
* Calculates the max extent which includes all of the markers.
*
* Returns:
* {<OpenLayers.Bounds>}
*/
getDataExtent: function () {
var maxExtent = null;
if ( this.markers && (this.markers.length > 0)) {
var maxExtent = new OpenLayers.Bounds();
for(var i=0, len=this.markers.length; i<len; i++) {
var marker = this.markers[i];
maxExtent.extend(marker.lonlat);
}
}
return maxExtent;
},
CLASS_NAME: "OpenLayers.Layer.Markers"
});
| blahoink/grassroots | phpmyadmin/js/openlayers/src/openlayers/lib/OpenLayers/Layer/Markers.js | JavaScript | gpl-2.0 | 5,107 |
<?php
/**
* Add Site Administration Screen
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
/** WordPress Translation Install API */
require_once( ABSPATH . 'wp-admin/includes/translation-install.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_sites' ) )
wp_die( __( 'You do not have sufficient permissions to add sites to this network.' ) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('This screen is for Super Admins to add new sites to the network. This is not affected by the registration settings.') . '</p>' .
'<p>' . __('If the admin email for the new site does not exist in the database, a new user will also be created.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="https://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
if ( wp_validate_action( 'add-site' ) ) {
check_admin_referer( 'add-blog', '_wpnonce_add-blog' );
if ( ! is_array( $_POST['blog'] ) )
wp_die( __( 'Can’t create an empty site.' ) );
$blog = $_POST['blog'];
$domain = '';
if ( preg_match( '|^([a-zA-Z0-9-])+$|', $blog['domain'] ) )
$domain = strtolower( $blog['domain'] );
// If not a subdomain install, make sure the domain isn't a reserved word
if ( ! is_subdomain_install() ) {
/** This filter is documented in wp-includes/ms-functions.php */
$subdirectory_reserved_names = apply_filters( 'subdirectory_reserved_names', array( 'page', 'comments', 'blog', 'files', 'feed', 'wp-admin', 'wp-content', 'wp-includes' ) );
if ( in_array( $domain, $subdirectory_reserved_names ) )
wp_die( sprintf( __('The following words are reserved for use by WordPress functions and cannot be used as blog names: <code>%s</code>' ), implode( '</code>, <code>', $subdirectory_reserved_names ) ) );
}
$title = $blog['title'];
$meta = array(
'public' => 1
);
// Handle translation install for the new site.
if ( ! empty( $_POST['WPLANG'] ) && wp_can_install_language_pack() ) {
$language = wp_download_language_pack( wp_unslash( $_POST['WPLANG'] ) );
if ( $language ) {
$meta['WPLANG'] = $language;
}
}
if ( empty( $domain ) )
wp_die( __( 'Missing or invalid site address.' ) );
if ( isset( $blog['email'] ) && '' === trim( $blog['email'] ) ) {
wp_die( __( 'Missing email address.' ) );
}
$email = sanitize_email( $blog['email'] );
if ( ! is_email( $email ) ) {
wp_die( __( 'Invalid email address.' ) );
}
if ( is_subdomain_install() ) {
$newdomain = $domain . '.' . preg_replace( '|^www\.|', '', $current_site->domain );
$path = $current_site->path;
} else {
$newdomain = $current_site->domain;
$path = $current_site->path . $domain . '/';
}
$password = 'N/A';
$user_id = email_exists($email);
if ( !$user_id ) { // Create a new user with a random password
$password = wp_generate_password( 12, false );
$user_id = wpmu_create_user( $domain, $password, $email );
if ( false === $user_id )
wp_die( __( 'There was an error creating the user.' ) );
else
wp_new_user_notification( $user_id, null, 'both' );
}
$wpdb->hide_errors();
$id = wpmu_create_blog( $newdomain, $path, $title, $user_id, $meta, $current_site->id );
$wpdb->show_errors();
if ( ! is_wp_error( $id ) ) {
if ( ! is_super_admin( $user_id ) && !get_user_option( 'primary_blog', $user_id ) ) {
update_user_option( $user_id, 'primary_blog', $id, true );
}
$content_mail = sprintf(
/* translators: 1: user login, 2: site url, 3: site name/title */
__( 'New site created by %1$s
Address: %2$s
Name: %3$s' ),
$current_user->user_login,
get_site_url( $id ),
wp_unslash( $title )
);
wp_mail( get_site_option('admin_email'), sprintf( __( '[%s] New Site Created' ), $current_site->site_name ), $content_mail, 'From: "Site Admin" <' . get_site_option( 'admin_email' ) . '>' );
wpmu_welcome_notification( $id, $user_id, $password, $title, array( 'public' => 1 ) );
wp_redirect( add_query_arg( array( 'update' => 'added', 'id' => $id ), 'site-new.php' ) );
exit;
} else {
wp_die( $id->get_error_message() );
}
}
if ( isset($_GET['update']) ) {
$messages = array();
if ( 'added' == $_GET['update'] )
$messages[] = sprintf(
/* translators: 1: dashboard url, 2: network admin edit url */
__( 'Site added. <a href="%1$s">Visit Dashboard</a> or <a href="%2$s">Edit Site</a>' ),
esc_url( get_admin_url( absint( $_GET['id'] ) ) ),
network_admin_url( 'site-info.php?id=' . absint( $_GET['id'] ) )
);
}
$title = __('Add New Site');
$parent_file = 'sites.php';
wp_enqueue_script( 'user-suggest' );
require( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h1 id="add-new-site"><?php _e( 'Add New Site' ); ?></h1>
<?php
if ( ! empty( $messages ) ) {
foreach ( $messages as $msg )
echo '<div id="message" class="updated notice is-dismissible"><p>' . $msg . '</p></div>';
} ?>
<form method="post" action="<?php echo network_admin_url( 'site-new.php?action=add-site' ); ?>" novalidate="novalidate">
<?php wp_nonce_field( 'add-blog', '_wpnonce_add-blog' ) ?>
<table class="form-table">
<tr class="form-field form-required">
<th scope="row"><label for="site-address"><?php _e( 'Site Address' ) ?></label></th>
<td>
<?php if ( is_subdomain_install() ) { ?>
<input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off"/><span class="no-break">.<?php echo preg_replace( '|^www\.|', '', $current_site->domain ); ?></span>
<?php } else {
echo $current_site->domain . $current_site->path ?><input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off" />
<?php }
echo '<p id="site-address-desc">' . __( 'Only lowercase letters (a-z) and numbers are allowed.' ) . '</p>';
?>
</td>
</tr>
<tr class="form-field form-required">
<th scope="row"><label for="site-title"><?php _e( 'Site Title' ) ?></label></th>
<td><input name="blog[title]" type="text" class="regular-text" id="site-title" /></td>
</tr>
<?php
$languages = get_available_languages();
$translations = wp_get_available_translations();
if ( ! empty( $languages ) || ! empty( $translations ) ) :
?>
<tr class="form-field form-required">
<th scope="row"><label for="site-language"><?php _e( 'Site Language' ); ?></label></th>
<td>
<?php
// Network default.
$lang = get_site_option( 'WPLANG' );
// Use English if the default isn't available.
if ( ! in_array( $lang, $languages ) ) {
$lang = '';
}
wp_dropdown_languages( array(
'name' => 'WPLANG',
'id' => 'site-language',
'selected' => $lang,
'languages' => $languages,
'translations' => $translations,
'show_available_translations' => wp_can_install_language_pack(),
) );
?>
</td>
</tr>
<?php endif; // Languages. ?>
<tr class="form-field form-required">
<th scope="row"><label for="admin-email"><?php _e( 'Admin Email' ) ?></label></th>
<td><input name="blog[email]" type="email" class="regular-text wp-suggest-user" id="admin-email" data-autocomplete-type="search" data-autocomplete-field="user_email" /></td>
</tr>
<tr class="form-field">
<td colspan="2"><?php _e( 'A new user will be created if the above email address is not in the database.' ) ?><br /><?php _e( 'The username and password will be mailed to this email address.' ) ?></td>
</tr>
</table>
<?php submit_button( __('Add Site'), 'primary', 'add-site' ); ?>
</form>
</div>
<?php
require( ABSPATH . 'wp-admin/admin-footer.php' );
| pk0nstantin/WordPress | wp-admin/network/site-new.php | PHP | gpl-2.0 | 8,230 |
<?php
birch_ns( 'birchschedule.upgrader', function( $ns ) {
$ns->init = function() use ( $ns ) {
add_action( 'birchschedule_upgrade_core_after', array( $ns, 'upgrade_core' ) );
};
$ns->get_staff_all_schedule_1_0 = function( $staff ) {
$schedule = $staff['_birs_staff_schedule'];
if ( !isset( $schedule ) ) {
$schedule = array();
} else {
$schedule = unserialize( $schedule );
}
$schedule = $schedule ? $schedule : array();
return $schedule;
};
$ns->upgrade_staff_schedule_from_1_0_to_1_1 = function() use ( $ns ) {
global $birchpress;
$version = $ns->get_staff_schedule_version();
if ( $version != '1.0' ) {
return;
}
$staff = $birchpress->db->query(
array(
'post_type' => 'birs_staff'
),
array(
'meta_keys' => array(
'_birs_staff_schedule'
),
'base_keys' => array()
)
);
foreach ( $staff as $thestaff ) {
$schedules = $ns->get_staff_all_schedule_1_0( $thestaff );
$new_all_schedules = array();
foreach ( $schedules as $location_id => $schedule ) {
if ( isset( $schedule['exceptions'] ) ) {
$exceptions = $schedule['exceptions'];
} else {
$exceptions = array();
}
$new_schedules = array();
foreach ( $schedule as $week_day => $day_schedule ) {
if ( isset( $day_schedule['enabled'] ) ) {
$start = $day_schedule['minutes_start'];
$end = $day_schedule['minutes_end'];
$new_schedule = array(
'minutes_start' => $day_schedule['minutes_start'],
'minutes_end' => $day_schedule['minutes_end'],
'weeks' => array(
$week_day => 'on'
)
);
if ( isset( $new_schedules['s'. $start. $end] ) ) {
$new_schedules['s'. $start. $end]['weeks'][$week_day] = 'on';
} else {
$new_schedules['s'. $start. $end] = $new_schedule;
}
}
}
$new_loc_schedules = array();
foreach ( $new_schedules as $tmp_id => $new_schedule ) {
$uid = uniqid();
$new_loc_schedules[$uid] = $new_schedule;
}
$new_all_schedules[$location_id] = array(
'schedules' => $new_loc_schedules,
'exceptions' => $exceptions
);
update_post_meta( $thestaff['ID'], '_birs_staff_schedule', serialize( $new_all_schedules ) );
}
}
update_option( 'birs_staff_schedule_version', '1.1' );
};
$ns->get_staff_schedule_version = function() {
return get_option( 'birs_staff_schedule_version', '1.0' );
};
$ns->upgrade_appointment_from_1_0_to_1_1 = function() use ( $ns ) {
global $birchpress, $birchschedule;
$version = $ns->get_db_version_appointment();
if ( $version != '1.0' ) {
return;
}
$appointment_fields = array(
'_birs_appointment_price', '_birs_appointment_client',
'_birs_appointment_notes', '_birs_appointment_payment_status',
'_birs_appointment_reminded'
);
$appointment1on1_fields = array(
'_birs_appointment_id',
'_birs_client_id',
'_birs_appointment1on1_payment_status',
'_birs_appointment1on1_reminded',
'_birs_appointment1on1_price',
'_birs_appointment1on1_uid'
);
$appointment1on1_custom_fields = array(
'_birs_appointment_notes'
);
$options = get_option( 'birchschedule_options_form' );
if ( $options != false ) {
$fields_options = $options['fields'];
foreach ( $fields_options as $field_id => $field ) {
if ( $field['belong_to'] == 'appointment' ) {
$meta_key = '_birs_' . $field_id;
if ( !in_array( $meta_key, array( '_birs_appointment_notes' ) ) ) {
$appointment_fields[] = $meta_key;
$appointment1on1_custom_fields[] = $meta_key;
}
}
}
}
$appointments = $birchschedule->model->query(
array(
'post_type' => 'birs_appointment',
'post_status' => array( 'publish', 'pending' )
),
array(
'base_keys' => array(),
'meta_keys' => $appointment_fields
)
);
foreach ( $appointments as $appointment ) {
if ( isset( $appointment['ID'] ) && isset( $appointment['_birs_appointment_client'] ) ) {
$appointment1on1 = array(
'post_type' => 'birs_appointment1on1',
'_birs_appointment_id' => $appointment['ID'],
'_birs_client_id' => $appointment['_birs_appointment_client']
);
if ( isset( $appointment['_birs_appointment_price'] ) ) {
$appointment1on1['_birs_appointment1on1_price'] = $appointment['_birs_appointment_price'];
}
if ( isset( $appointment['_birs_appointment_payment_status'] ) ) {
$appointment1on1['_birs_appointment1on1_payment_status'] =
$appointment['_birs_appointment_payment_status'];
}
if ( isset( $appointment['_birs_appointment_reminded'] ) ) {
$appointment1on1['_birs_appointment1on1_reminded'] = $appointment['_birs_appointment_reminded'];
}
$appointment1on1['_birs_appointment1on1_uid'] = uniqid();
foreach ( $appointment1on1_custom_fields as $appointment1on1_custom_field ) {
if ( isset( $appointment[$appointment1on1_custom_field] ) ) {
$appointment1on1[$appointment1on1_custom_field] =
$appointment[$appointment1on1_custom_field];
}
}
$appointment1on1_meta_keys = array_merge( $appointment1on1_fields, $appointment1on1_custom_fields );
$birchpress->db->save( $appointment1on1, array(
'base_keys' => array(),
'meta_keys' => $appointment1on1_meta_keys
)
);
foreach ( $appointment1on1_custom_fields as $appointment1on1_custom_field ) {
delete_post_meta( $appointment['ID'], $appointment1on1_custom_field );
}
delete_post_meta( $appointment['ID'], '_birs_appointment_client' );
delete_post_meta( $appointment['ID'], '_birs_appointment_notes' );
delete_post_meta( $appointment['ID'], '_birs_appointment_reminded' );
delete_post_meta( $appointment['ID'], '_birs_appointment_price' );
delete_post_meta( $appointment['ID'], '_birs_appointment_payment_status' );
}
}
update_option( 'birs_db_version_appointment', '1.1' );
};
$ns->upgrade_appointment_from_1_1_to_1_2 = function() use ( $ns ) {
global $birchpress, $birchschedule;
$version = $ns->get_db_version_appointment();
if ( $version != '1.1' ) {
return;
}
$appointments = $birchschedule->model->query(
array(
'post_type' => 'birs_appointment',
'post_status' => array( 'any' )
),
array(
'base_keys' => array( 'post_author' ),
'meta_keys' => array( '_birs_appointment_staff' )
)
);
if ( $appointments ) {
foreach ( $appointments as $appointment_id => $appointment ) {
$staff = $birchschedule->model->get( $appointment['_birs_appointment_staff'],
array(
'base_keys' => array(),
'meta_keys' => array( '_birs_staff_email' )
)
);
if ( $staff ) {
$user = WP_User::get_data_by( 'email', $staff['_birs_staff_email'] );
if ( $user ) {
$appointment['post_author'] = $user->ID;
$birchschedule->model->save( $appointment, array(
'base_keys' => array( 'post_author' ),
'meta_keys' => array()
) );
}
}
}
}
update_option( 'birs_db_version_appointment', '1.2' );
};
$ns->get_db_version_appointment = function() {
return get_option( 'birs_db_version_appointment', '1.0' );
};
$ns->upgrade_core = function() use ( $ns ) {
$ns->upgrade_staff_schedule_from_1_0_to_1_1();
$ns->upgrade_appointment_from_1_0_to_1_1();
$ns->upgrade_appointment_from_1_1_to_1_2();
};
} );
| stanislav-chechun/campus-rize | wp-content/plugins/birchschedule/includes/upgrader/package.php | PHP | gpl-2.0 | 7,346 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Silverpine_Forest
SD%Complete: 100
SDComment: Quest support: 435
SDCategory: Silverpine Forest
EndScriptData */
/* ContentData
npc_deathstalker_erland
EndContentData */
#include "ScriptMgr.h"
#include "Player.h"
#include "ScriptedEscortAI.h"
/*######
## npc_deathstalker_erland
######*/
enum eErland
{
SAY_QUESTACCEPT = 0,
SAY_START = 1,
SAY_AGGRO = 2,
SAY_PROGRESS = 3,
SAY_LAST = 4,
SAY_RANE = 0,
SAY_RANE_ANSWER = 5,
SAY_MOVE_QUINN = 6,
SAY_QUINN = 7,
SAY_QUINN_ANSWER = 0,
SAY_BYE = 8,
QUEST_ESCORTING = 435,
NPC_RANE = 1950,
NPC_QUINN = 1951
};
class npc_deathstalker_erland : public CreatureScript
{
public:
npc_deathstalker_erland() : CreatureScript("npc_deathstalker_erland") { }
struct npc_deathstalker_erlandAI : public EscortAI
{
npc_deathstalker_erlandAI(Creature* creature) : EscortAI(creature) { }
void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override
{
Player* player = GetPlayerForEscort();
if (!player)
return;
switch (waypointId)
{
case 1:
Talk(SAY_START, player);
break;
case 10:
Talk(SAY_PROGRESS);
break;
case 13:
Talk(SAY_LAST, player);
player->GroupEventHappens(QUEST_ESCORTING, me);
break;
case 15:
if (Creature* rane = me->FindNearestCreature(NPC_RANE, 20.0f))
rane->AI()->Talk(SAY_RANE);
break;
case 16:
Talk(SAY_RANE_ANSWER);
break;
case 17:
Talk(SAY_MOVE_QUINN);
break;
case 24:
Talk(SAY_QUINN);
break;
case 25:
if (Creature* quinn = me->FindNearestCreature(NPC_QUINN, 20.0f))
quinn->AI()->Talk(SAY_QUINN_ANSWER);
break;
case 26:
Talk(SAY_BYE);
break;
}
}
void Reset() override { }
void EnterCombat(Unit* who) override
{
Talk(SAY_AGGRO, who);
}
void QuestAccept(Player* player, Quest const* quest) override
{
if (quest->GetQuestId() == QUEST_ESCORTING)
{
Talk(SAY_QUESTACCEPT, player);
Start(true, false, player->GetGUID());
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_deathstalker_erlandAI(creature);
}
};
/*######
## AddSC
######*/
void AddSC_silverpine_forest()
{
new npc_deathstalker_erland();
}
| Nalliestrasza/LegionHearth | src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp | C++ | gpl-2.0 | 3,786 |
<?php
if (cfr('CUSTMAP')) {
$altCfg = $ubillingConfig->getAlter();
if ($altCfg['CUSTMAP_ENABLED']) {
$custmaps = new CustomMaps();
// new custom map creation
if (wf_CheckPost(array('newmapname'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->mapCreate($_POST['newmapname']);
rcms_redirect('?module=custmaps');
} else {
show_error(__('Permission denied'));
}
}
//custom map deletion
if (wf_CheckGet(array('deletemap'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->mapDelete($_GET['deletemap']);
rcms_redirect('?module=custmaps');
} else {
show_error(__('Permission denied'));
}
}
//editing existing custom map name
if (wf_CheckPost(array('editmapid', 'editmapname'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->mapEdit($_POST['editmapid'], $_POST['editmapname']);
rcms_redirect('?module=custmaps');
} else {
show_error(__('Permission denied'));
}
}
//creating new map item
if (wf_CheckPost(array('newitemgeo', 'newitemtype'))) {
if (wf_CheckGet(array('showmap'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->itemCreate($_GET['showmap'], $_POST['newitemtype'], $_POST['newitemgeo'], $_POST['newitemname'], $_POST['newitemlocation']);
rcms_redirect('?module=custmaps&showmap=' . $_GET['showmap'] . '&mapedit=true');
} else {
show_error(__('Permission denied'));
}
}
}
//deleting map item
if (wf_CheckGet(array('deleteitem'))) {
if (cfr('CUSTMAPEDIT')) {
$deleteResult = $custmaps->itemDelete($_GET['deleteitem']);
rcms_redirect('?module=custmaps&showitems=' . $deleteResult);
} else {
show_error(__('Permission denied'));
}
}
//items upload as KML
if (wf_CheckPost(array('itemsUploadTypes'))) {
$custmaps->catchFileUpload();
}
if (!wf_CheckGet(array('showmap'))) {
if (!wf_CheckGet(array('showitems'))) {
if (!wf_CheckGet(array('edititem'))) {
//render existing custom maps list
show_window(__('Available custom maps'), $custmaps->renderMapList());
zb_BillingStats(true);
} else {
$editItemId = $_GET['edititem'];
//editing item
if (wf_CheckPost(array('edititemid', 'edititemtype'))) {
if (cfr('CUSTMAPEDIT')) {
$custmaps->itemEdit($editItemId, $_POST['edititemtype'], $_POST['edititemgeo'], $_POST['edititemname'], $_POST['edititemlocation']);
rcms_redirect('?module=custmaps&edititem=' . $editItemId);
} else {
show_error(__('Permission denied'));
}
}
//show item edit form
show_window(__('Edit'), $custmaps->itemEditForm($editItemId));
//photostorage link
if ($altCfg['PHOTOSTORAGE_ENABLED']) {
$imageControl = wf_Link('?module=photostorage&scope=CUSTMAPSITEMS&itemid=' . $editItemId . '&mode=list', wf_img('skins/photostorage.png') . ' ' . __('Upload images'), false, 'ubButton');
show_window('', $imageControl);
}
//additional comments
if ($altCfg['ADCOMMENTS_ENABLED']) {
$adcomments = new ADcomments('CUSTMAPITEMS');
show_window(__('Additional comments'), $adcomments->renderComments($editItemId));
}
}
} else {
if (!wf_CheckGet(array('duplicates'))) {
//render items list json data in background
if (wf_CheckGet(array('ajax'))) {
$custmaps->renderItemsListJsonData($_GET['showitems']);
}
//render map items list container
show_window(__('Objects') . ': ' . $custmaps->mapGetName($_GET['showitems']), $custmaps->renderItemsListFast($_GET['showitems']));
} else {
//show duplicate map objects
show_window(__('Show duplicates') . ': ' . $custmaps->mapGetName($_GET['showitems']), $custmaps->renderItemDuplicateList($_GET['showitems']));
}
}
} else {
$mapId = $_GET['showmap'];
$placemarks = '';
//additional centering and zoom
if (wf_CheckGet(array('locateitem', 'zoom'))) {
$custmaps->setCenter($_GET['locateitem']);
$custmaps->setZoom($_GET['zoom']);
$searchRadius = 30;
$placemarks.=$custmaps->mapAddCircle($_GET['locateitem'], $searchRadius, __('Search area radius') . ' ' . $searchRadius . ' ' . __('meters'), __('Search area'));
}
$placemarks.= $custmaps->mapGetPlacemarks($mapId);
//custom map layers processing
if (wf_CheckGet(array('cl'))) {
if (!empty($_GET['cl'])) {
$custLayers = explode('z', $_GET['cl']);
if (!empty($custLayers)) {
foreach ($custLayers as $eachCustLayerId) {
if (!empty($eachCustLayerId)) {
$placemarks.=$custmaps->mapGetPlacemarks($eachCustLayerId);
}
}
}
}
}
if (wf_CheckGet(array('layers'))) {
$layers = $_GET['layers'];
//switches layer
if (ispos($layers, 'sw')) {
$placemarks.=sm_MapDrawSwitches();
}
//switches uplinks layer
if (ispos($layers, 'ul')) {
$placemarks.=sm_MapDrawSwitchUplinks();
}
//builds layer
if (ispos($layers, 'bs')) {
$placemarks.=um_MapDrawBuilds();
}
}
if (wf_CheckGet(array('mapedit', 'showmap'))) {
$editor = $custmaps->mapLocationEditor();
} else {
$editor = '';
}
show_window($custmaps->mapGetName($mapId), $custmaps->mapInit($placemarks, $editor));
}
} else {
show_error(__('This module is disabled'));
}
} else {
show_error(__('Access denied'));
}
?> | l1ght13aby/Ubilling | modules/general/custmaps/index.php | PHP | gpl-2.0 | 6,971 |
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores
* CA 94065 USA or visit www.oracle.com if you need additional information or
* have any questions.
*/
package com.codename1.ui;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.animations.Transition;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Rectangle;
import com.codename1.impl.VirtualKeyboardInterface;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.plaf.Style;
import com.codename1.ui.plaf.UIManager;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* This class represent the Codename One Light Weight Virtual Keyboard
*
* @author Chen Fishbein
*/
public class VirtualKeyboard extends Dialog implements VirtualKeyboardInterface{
private static final String MARKER_COMMIT_ON_DISPOSE = "$VKB_COM$";
private static final String MARKER_TINT_COLOR = "$VKB_TINT$";
private static final String MARKER_VKB = "$VKB$";
private static Transition transitionIn = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500);
private static Transition transitionOut = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500);
private int inputType;
/**
* This keymap represents qwerty keyboard
*/
public static final String[][] DEFAULT_QWERTY = new String[][]{
{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"},
{"a", "s", "d", "f", "g", "h", "j", "k", "l"},
{"$Shift$", "z", "x", "c", "v", "b", "n", "m", "$Delete$"},
{"$Mode$", "$T9$", "$Space$", "$OK$"}
};
/**
* This keymap represents numbers keyboard
*/
public static final String[][] DEFAULT_NUMBERS = new String[][]{
{"1", "2", "3",},
{"4", "5", "6",},
{"7", "8", "9",},
{"*", "0", "#",},
{"$Mode$", "$Space$", "$Delete$", "$OK$"}
};
/**
* This keymap represents numbers and symbols keyboard
*/
public static final String[][] DEFAULT_NUMBERS_SYMBOLS = new String[][]{
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"},
{"-", "/", ":", ";", "(", ")", "$", "&", "@"},
{".", ",", "?", "!", "'", "\"", "$Delete$"},
{"$Mode$", "$Space$", "$OK$"}
};
/**
* This keymap represents symbols keyboard
*/
public static final String[][] DEFAULT_SYMBOLS = new String[][]{
{"[", "]", "{", "}", "#", "%", "^", "*", "+", "="},
{"_", "\\", "|", "~", "<", ">", "\u00A3", "\u00A5"},
{":-0", ";-)", ":-)", ":-(", ":P", ":D", "$Delete$"},
{"$Mode$", "$Space$", "$OK$"}
};
/**
* The String that represent the qwerty mode.
*/
public static final String QWERTY_MODE = "ABC";
/**
* The String that represent the numbers mode.
*/
public static final String NUMBERS_MODE = "123";
/**
* The String that represent the numbers sybols mode.
*/
public static final String NUMBERS_SYMBOLS_MODE = ".,123";
/**
* The String that represent the symbols mode.
*/
public static final String SYMBOLS_MODE = ".,?";
private static Hashtable modesMap = new Hashtable();
private static String[] defaultInputModeOrder = {QWERTY_MODE,
NUMBERS_SYMBOLS_MODE, NUMBERS_MODE, SYMBOLS_MODE};
private String currentMode = defaultInputModeOrder[0];
private String[] inputModeOrder = defaultInputModeOrder;
private TextField inputField;
private Container buttons = new Container(new BoxLayout(BoxLayout.Y_AXIS));
private TextPainter txtPainter = new TextPainter();
private boolean upperCase = false;
private Button currentButton;
public static final int INSERT_CHAR = 1;
public static final int DELETE_CHAR = 2;
public static final int CHANGE_MODE = 3;
public static final int SHIFT = 4;
public static final int OK = 5;
public static final int SPACE = 6;
public static final int T9 = 7;
private Hashtable specialButtons = new Hashtable();
private TextArea field;
private boolean finishedT9Edit = true;
private String originalText;
private boolean useSoftKeys = false;
private static boolean showTooltips = true;
private boolean okPressed;
private static Class vkbClass;
private VirtualKeyboard vkb;
public final static String NAME = "CodenameOne_VirtualKeyboard";
private boolean isShowing = false;
private static Hashtable defaultInputModes = null;
/**
* Creates a new instance of VirtualKeyboard
*/
public VirtualKeyboard() {
setLayout(new BorderLayout());
setDialogUIID("Container");
getContentPane().setUIID("VKB");
setAutoDispose(false);
setDisposeWhenPointerOutOfBounds(true);
setTransitionInAnimator(transitionIn);
setTransitionOutAnimator(transitionOut);
getTitleComponent().getParent().removeComponent(getTitleComponent());
if(showTooltips) {
setGlassPane(txtPainter);
}
}
public void setInputType(int inputType) {
if((inputType & TextArea.NUMERIC) == TextArea.NUMERIC ||
(inputType & TextArea.PHONENUMBER) == TextArea.PHONENUMBER) {
setInputModeOrder(new String []{NUMBERS_MODE});
return;
}
if((inputType & TextArea.DECIMAL) == TextArea.DECIMAL) {
setInputModeOrder(new String []{NUMBERS_SYMBOLS_MODE});
return;
}
setInputModeOrder(defaultInputModeOrder);
}
static class InputField extends TextField {
private TextArea field;
InputField(TextArea field) {
this.field = field;
setInputMode(field.getInputMode());
setConstraint(field.getConstraint());
}
public boolean hasFocus() {
return true;
}
public String getUIID() {
return "VKBTextInput";
}
public void deleteChar() {
super.deleteChar();
field.setText(getText());
if (field instanceof TextField) {
((TextField) field).setCursorPosition(getCursorPosition());
}
}
public void setCursorPosition(int i) {
super.setCursorPosition(i);
// this can happen since this method is invoked from a constructor of the base class...
if(field != null && field.getText().length() > i && field instanceof TextField) {
((TextField) field).setCursorPosition(i);
}
}
public void setText(String t) {
super.setText(t);
// this can happen since this method is invoked from a constructor of the base class...
if(field != null) {
// mirror events into the parent
field.setText(t);
}
}
public boolean validChar(String c) {
if (field instanceof TextField) {
return ((TextField) field).validChar(c);
}
return true;
}
}
/**
* Invoked internally by the implementation to indicate the text field that will be
* edited by the virtual keyboard
*
* @param field the text field instance
*/
public void setTextField(final TextArea field) {
this.field = field;
removeAll();
okPressed = false;
if(field instanceof TextField){
useSoftKeys = ((TextField)field).isUseSoftkeys();
((TextField)field).setUseSoftkeys(false);
}
originalText = field.getText();
inputField = new InputField(field);
inputField.setText(originalText);
inputField.setCursorPosition(field.getCursorPosition());
inputField.setConstraint(field.getConstraint());
inputField.setInputModeOrder(new String[]{"ABC"});
inputField.setMaxSize(field.getMaxSize());
initModes();
setInputType(field.getConstraint());
initSpecialButtons();
addComponent(BorderLayout.NORTH, inputField);
buttons.getStyle().setPadding(0, 0, 0, 0);
addComponent(BorderLayout.CENTER, buttons);
initInputButtons(upperCase);
inputField.setUseSoftkeys(false);
applyRTL(false);
}
/**
* @inheritDoc
*/
public void show() {
super.showPacked(BorderLayout.SOUTH, true);
}
/**
* @inheritDoc
*/
protected void autoAdjust(int w, int h) {
//if the t9 input is currently editing do not dispose dialog
if (finishedT9Edit) {
setTransitionOutAnimator(CommonTransitions.createEmpty());
dispose();
}
}
/**
* init all virtual keyboard modes, such as QWERTY_MODE, NUMBERS_SYMBOLS_MODE...
* to add an addtitional mode a developer needs to override this method and
* add a mode by calling addInputMode method
*/
protected void initModes() {
addInputMode(QWERTY_MODE, DEFAULT_QWERTY);
addInputMode(NUMBERS_SYMBOLS_MODE, DEFAULT_NUMBERS_SYMBOLS);
addInputMode(SYMBOLS_MODE, DEFAULT_SYMBOLS);
addInputMode(NUMBERS_MODE, DEFAULT_NUMBERS);
if(defaultInputModes != null) {
Enumeration e = defaultInputModes.keys();
while(e.hasMoreElements()) {
String key = (String)e.nextElement();
addInputMode(key, (String[][])defaultInputModes.get(key));
}
}
}
/**
* Sets the current virtual keyboard mode.
*
* @param mode the String that represents the mode(QWERTY_MODE,
* SYMBOLS_MODE, ...)
*/
protected void setCurrentMode(String mode) {
this.currentMode = mode;
}
/**
* Gets the current mode.
*
* @return the String that represents the current mode(QWERTY_MODE,
* SYMBOLS_MODE, ...)
*/
protected String getCurrentMode() {
return currentMode;
}
private void initInputButtons(boolean upperCase) {
buttons.removeAll();
int largestLine = 0;
String[][] currentKeyboardChars = (String[][]) modesMap.get(currentMode);
for (int i = 1; i < currentKeyboardChars.length; i++) {
if (currentKeyboardChars[i].length > currentKeyboardChars[largestLine].length) {
largestLine = i;
}
}
int length = currentKeyboardChars[largestLine].length;
if(length == 0) {
return;
}
Button dummy = createButton(new Command("dummy"), 0);
int buttonMargins = dummy.getUnselectedStyle().getMargin(dummy.isRTL(), LEFT) +
dummy.getUnselectedStyle().getMargin(dummy.isRTL(), RIGHT);
Container row = null;
int rowW = (Display.getInstance().getDisplayWidth() -
getDialogStyle().getPadding(false, LEFT) -
getDialogStyle().getPadding(false, RIGHT) -
getDialogStyle().getMargin(false, LEFT) -
getDialogStyle().getMargin(false, RIGHT));
int availableSpace = rowW - length * buttonMargins;
int buttonSpace = (availableSpace) / length;
for (int i = 0; i < currentKeyboardChars.length; i++) {
int rowWidth = rowW;
row = new Container(new BoxLayout(BoxLayout.X_AXIS));
row.getUnselectedStyle().setMargin(0, 0, 0, 0);
Vector specialsButtons = new Vector();
for (int j = 0; j < currentKeyboardChars[i].length; j++) {
String txt = currentKeyboardChars[i][j];
Button b = null;
if (txt.startsWith("$") && txt.endsWith("$") && txt.length() > 1) {
//add a special button
Button cmd = (Button) specialButtons.get(txt.substring(1, txt.length() - 1));
Command c = null;
int prefW = 0;
if(cmd != null){
c = cmd.getCommand();
int space = ((Integer) cmd.getClientProperty("space")).intValue();
if (space != -1) {
prefW = availableSpace * space / 100;
}
}
b = createButton(c, prefW, "VKBSpecialButton");
if (prefW != 0) {
rowWidth -= (b.getPreferredW() + buttonMargins);
} else {
//if we can't determind the size at this stage, wait until
//the loops ends and give the remains size to the special
//button
specialsButtons.addElement(b);
}
} else {
if (upperCase) {
txt = txt.toUpperCase();
}
b = createInputButton(txt, buttonSpace);
rowWidth -= (b.getPreferredW() + buttonMargins);
}
if (currentButton != null) {
if (currentButton.getCommand() != null &&
b.getCommand() != null &&
currentButton.getCommand().getId() == b.getCommand().getId()) {
currentButton = b;
}
if (currentButton.getText().equals(b.getText())) {
currentButton = b;
}
}
row.addComponent(b);
}
int emptySpace = Math.max(rowWidth, 0);
//if we have special buttons on the keyboard give them the size or
//else give the remain size to the row margins
if (specialsButtons.size() > 0) {
int prefW = emptySpace / specialsButtons.size();
for (int j = 0; j < specialsButtons.size(); j++) {
Button special = (Button) specialsButtons.elementAt(j);
special.setPreferredW(prefW);
}
} else {
row.getUnselectedStyle().setPadding(Component.LEFT, 0);
row.getUnselectedStyle().setPadding(Component.RIGHT, 0);
row.getUnselectedStyle().setMarginUnit(new byte[]{Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS,
Style.UNIT_TYPE_PIXELS});
row.getUnselectedStyle().setMargin(Component.LEFT, emptySpace / 2);
row.getUnselectedStyle().setMargin(Component.RIGHT, emptySpace / 2);
}
buttons.addComponent(row);
}
applyRTL(false);
}
private Button createInputButton(String text, int prefSize) {
Button b = createButton(new Command(text, INSERT_CHAR), prefSize);
b.putClientProperty("glasspane", "true");
return b;
}
private Button createButton(Command cmd, int prefSize) {
return createButton(cmd, prefSize, "VKBButton");
}
private Button createButton(Command cmd, int prefSize, String uiid) {
Button btn;
if(cmd != null){
btn = new Button(cmd);
}else{
btn = new Button();
btn.setVisible(false);
}
final Button b = btn;
b.setUIID(uiid);
b.setEndsWith3Points(false);
b.setAlignment(Component.CENTER);
prefSize = Math.max(prefSize, b.getPreferredW());
b.setPreferredW(prefSize);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
currentButton = b;
}
});
return b;
}
/**
* Add an input mode to the virtual keyboard
*
* @param mode a string that represents the identifier of the mode
* @param inputChars 2 dimensional String array that contains buttons String
* and special buttons (a special button is identified with $...$ marks
* e.g: "$Space$")
*/
public static void addDefaultInputMode(String mode, String[][] inputChars) {
if(defaultInputModes == null) {
defaultInputModes = new Hashtable();
}
defaultInputModes.put(mode, inputChars);
}
/**
* Add an input mode to the virtual keyboard
*
* @param mode a string that represents the identifier of the mode
* @param inputChars 2 dimentional String array that contains buttons String
* and special buttons (a special button is identified with $...$ marks
* e.g: "$Space$")
*/
public void addInputMode(String mode, String[][] inputChars) {
modesMap.put(mode, inputChars);
}
/**
* This method adds a special button to the virtual keyboard
*
* @param key the string identifier from within the relevant input mode
* @param cmd the Command to invoke when this button is invoked.
*/
public void addSpecialButton(String key, Command cmd) {
addSpecialButton(key, cmd, -1);
}
/**
* This method adds a special button to the virtual keyboard
*
* @param key the string identifier from within the relevant input mode
* @param cmd the Command to invoke when this button is invoked.
* @param space how much space in percentage from the overall row
* the special button should occupy
*/
public void addSpecialButton(String key, Command cmd, int space) {
Button b = new Button(cmd);
b.putClientProperty("space", new Integer(space));
specialButtons.put(key, b);
}
private String getNextMode(String current) {
for (int i = 0; i < inputModeOrder.length - 1; i++) {
String mode = inputModeOrder[i];
if(mode.equals(current)){
return inputModeOrder[i + 1];
}
}
return inputModeOrder[0];
}
/**
* @inheritDoc
*/
public void pointerPressed(int x, int y) {
super.pointerPressed(x, y);
Component cmp = getComponentAt(x, y);
if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) {
txtPainter.showButtonOnGlasspane((Button) cmp);
}
}
/**
* @inheritDoc
*/
public void pointerDragged(int x, int y) {
super.pointerDragged(x, y);
Component cmp = getComponentAt(x, y);
if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) {
txtPainter.showButtonOnGlasspane((Button) cmp);
}
}
/**
* @inheritDoc
*/
public void pointerReleased(int x, int y) {
if(showTooltips) {
txtPainter.clear();
}
super.pointerReleased(x, y);
}
/**
* This method initialize all the virtual keyboard special buttons.
*/
protected void initSpecialButtons() {
//specialButtons.clear();
addSpecialButton("Shift", new Command("SH", SHIFT), 15);
addSpecialButton("Delete", new Command("Del", DELETE_CHAR), 15);
addSpecialButton("T9", new Command("T9", T9), 15);
addSpecialButton("Mode", new Command(getNextMode(currentMode), CHANGE_MODE));
addSpecialButton("Space", new Command("Space", SPACE), 50);
addSpecialButton("OK", new Command("Ok", OK));
}
/**
* Returns the order in which input modes are toggled
*
* @return the order of the input modes
*/
public String[] getInputModeOrder() {
return inputModeOrder;
}
/**
* Sets the order in which input modes are toggled and allows disabling/hiding
* an input mode
*
* @param order the order for the input modes in this field
*/
public void setInputModeOrder(String[] order) {
inputModeOrder = order;
setCurrentMode(order[0]);
}
/**
* Returns the order in which input modes are toggled by default
*
* @return the default order of the input mode
*/
public static String[] getDefaultInputModeOrder() {
return defaultInputModeOrder;
}
/**
* Sets the order in which input modes are toggled by default and allows
* disabling/hiding an input mode
*
* @param order the order for the input modes in all future created fields
*/
public static void setDefaultInputModeOrder(String[] order) {
defaultInputModeOrder = order;
}
class TextPainter implements Painter {
private Label label = new Label();
private boolean paint = true;
public TextPainter() {
label = new Label();
label.setUIID("VKBtooltip");
}
public void showButtonOnGlasspane(Button button) {
if(label.getText().equals(button.getText())){
return;
}
paint = true;
repaint(label.getAbsoluteX()-2,
label.getAbsoluteY()-2,
label.getWidth()+4,
label.getHeight()+4);
label.setText(button.getText());
label.setSize(label.getPreferredSize());
label.setX(button.getAbsoluteX() + (button.getWidth() - label.getWidth()) / 2);
label.setY(button.getAbsoluteY() - label.getPreferredH() * 4 / 3);
repaint(label.getAbsoluteX()-2,
label.getAbsoluteY()-2,
label.getPreferredW()+4,
label.getPreferredH()+4);
}
public void paint(Graphics g, Rectangle rect) {
if (paint) {
label.paintComponent(g);
}
}
private void clear() {
paint = false;
repaint();
}
}
private void updateText(String txt) {
field.setText(txt);
if(field instanceof TextField){
((TextField)field).setCursorPosition(txt.length());
}
if(okPressed){
field.fireActionEvent();
if(field instanceof TextField){
((TextField)field).fireDoneEvent();
}
}
}
/**
* @inheritDoc
*/
protected void actionCommand(Command cmd) {
super.actionCommand(cmd);
switch (cmd.getId()) {
case OK:
okPressed = true;
updateText(inputField.getText());
dispose();
break;
case INSERT_CHAR:
Button btn = currentButton;
String text = btn.getText();
if (inputField.getText().length() == 0) {
inputField.setText(text);
inputField.setCursorPosition(text.length());
} else {
inputField.insertChars(text);
}
break;
case SPACE:
if (inputField.getText().length() == 0) {
inputField.setText(" ");
} else {
inputField.insertChars(" ");
}
break;
case DELETE_CHAR:
inputField.deleteChar();
break;
case CHANGE_MODE:
currentMode = getNextMode(currentMode);
Display.getInstance().callSerially(new Runnable() {
public void run() {
initInputButtons(upperCase);
String next = getNextMode(currentMode);
currentButton.setText(next);
currentButton.getCommand().setCommandName(next);
setTransitionOutAnimator(CommonTransitions.createEmpty());
setTransitionInAnimator(CommonTransitions.createEmpty());
revalidate();
show();
}
});
return;
case SHIFT:
if (currentMode.equals(QWERTY_MODE)) {
upperCase = !upperCase;
Display.getInstance().callSerially(new Runnable() {
public void run() {
initInputButtons(upperCase);
revalidate();
}
});
}
return;
case T9:
finishedT9Edit = false;
if(field != null){
Display.getInstance().editString(field, field.getMaxSize(), field.getConstraint(), field.getText());
}else{
Display.getInstance().editString(inputField, inputField.getMaxSize(), inputField.getConstraint(), inputField.getText());
}
dispose();
finishedT9Edit = true;
}
}
/**
* @inheritDoc
*/
public void dispose() {
if (field != null) {
if (!okPressed && !isCommitOnDispose(field) && finishedT9Edit) {
field.setText(originalText);
}
if(field instanceof TextField){
((TextField)field).setUseSoftkeys(useSoftKeys);
}
setTransitionInAnimator(transitionIn);
field = null;
}
currentMode = inputModeOrder[0];
super.dispose();
}
/**
* @inheritDoc
*/
protected void onShow() {
super.onShow();
setTransitionOutAnimator(transitionOut);
}
/**
* This method returns the Virtual Keyboard TextField.
*
* @return the the Virtual Keyboard TextField.
*/
protected TextField getInputField() {
return inputField;
}
/**
* Indicates whether the VKB should commit changes to the text field when the VKB
* is closed not via the OK button. This might be useful for some situations such
* as searches
*
* @param tf the text field to mark as commit on dispose
* @param b the value of commit on dispose, true to always commit changes
*/
public static void setCommitOnDispose(TextField tf, boolean b) {
tf.putClientProperty(MARKER_COMMIT_ON_DISPOSE, new Boolean(b));
}
/**
* This method is used to bind a specific instance of a virtual keyboard to a specific TextField.
* For example if a specific TextField requires only numeric input consider using this method as follows:
*
* TextField tf = new TextField();
* tf.setConstraint(TextField.NUMERIC);
* tf.setInputModeOrder(new String[]{"123"});
* VirtualKeyboard vkb = new VirtualKeyboard();
* vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE});
* VirtualKeyboard.bindVirtualKeyboard(tf, vkb);
*
* @param t the TextField to bind a VirualKeyboard to.
* @param vkb the binded VirualKeyboard.
*/
public static void bindVirtualKeyboard(TextArea t, VirtualKeyboard vkb) {
t.putClientProperty(MARKER_VKB, vkb);
}
/**
* This method returns the Textfield associated VirtualKeyboard,
* see bindVirtualKeyboard(TextField tf, VirtualKeyboard vkb) method.
*
* @param t a TextField.that might have an associated VirtualKeyboard instance
* @return a VirtualKeyboard instance or null if not exists.
*/
public static VirtualKeyboard getVirtualKeyboard(TextArea t) {
return (VirtualKeyboard) t.getClientProperty(MARKER_VKB);
}
/**
* Indicates whether the given text field should commit on dispose
*
* @param tf the text field
* @return true if the text field should save the data despite the fact that it
* was disposed in an irregular way
*/
public static boolean isCommitOnDispose(TextArea tf) {
Boolean b = (Boolean)tf.getClientProperty(MARKER_COMMIT_ON_DISPOSE);
return (b != null) && b.booleanValue();
}
/**
* Sets the tint color for the virtual keyboard when shown on top of this text field
* see the form tint methods for more information
*
* @param tf the relevant text field
* @param tint the tint color with an alpha channel
*/
public static void setVKBTint(TextField tf, int tint) {
tf.putClientProperty(MARKER_TINT_COLOR, new Integer(tint));
}
/**
* The tint color for the virtual keyboard when shown on top of this text field
* see the form tint methods for more information
*
* @param tf the relevant text field
* @return the tint color with an alpha channel
*/
public static int getVKBTint(TextArea tf) {
Integer v = (Integer)tf.getClientProperty(MARKER_TINT_COLOR);
if(v != null) {
return v.intValue();
}
Form current = Display.getInstance().getCurrent();
return current.getUIManager().getLookAndFeel().getDefaultFormTintColor();
}
/**
* Indicates whether tooltips should be shown when the keys in the VKB are pressed
*
* @return the showTooltips
*/
public static boolean isShowTooltips() {
return showTooltips;
}
/**
* Indicates whether tooltips should be shown when the keys in the VKB are pressed
*
* @param aShowTooltips true to show tooltips
*/
public static void setShowTooltips(boolean aShowTooltips) {
showTooltips = aShowTooltips;
}
/**
* The transition in for the VKB
*
* @return the transitionIn
*/
public static Transition getTransitionIn() {
return transitionIn;
}
/**
* The transition in for the VKB
*
* @param aTransitionIn the transitionIn to set
*/
public static void setTransitionIn(Transition aTransitionIn) {
transitionIn = aTransitionIn;
}
/**
* The transition out for the VKB
*
* @return the transitionOut
*/
public static Transition getTransitionOut() {
return transitionOut;
}
/**
* The transition out for the VKB
*
* @param aTransitionOut the transitionOut to set
*/
public static void setTransitionOut(Transition aTransitionOut) {
transitionOut = aTransitionOut;
}
/**
* Shows the virtual keyboard that is assoiciated with the displayed TextField
* or displays the default virtual keyboard.
*
* @param show it show is true open the relevant keyboard, if close dispose
* the displayed keyboard
*/
public void showKeyboard(boolean show) {
isShowing = show;
Form current = Display.getInstance().getCurrent();
if (show) {
Component foc = current.getFocused();
if(foc instanceof Container) {
foc = ((Container)foc).getLeadComponent();
}
TextArea txtCmp = (TextArea) foc;
if (txtCmp != null) {
if(vkb != null && vkb.contains(txtCmp)){
return;
}
vkb = VirtualKeyboard.getVirtualKeyboard(txtCmp);
if(vkb == null){
vkb = createVirtualKeyboard();
}
vkb.setTextField(txtCmp);
int oldTint = current.getTintColor();
current.setTintColor(VirtualKeyboard.getVKBTint(txtCmp));
boolean third = com.codename1.ui.Display.getInstance().isThirdSoftButton();
com.codename1.ui.Display.getInstance().setThirdSoftButton(false);
boolean qwerty = txtCmp.isQwertyInput();
if(txtCmp instanceof TextField){
((TextField) txtCmp).setQwertyInput(true);
}
vkb.showDialog();
if (txtCmp instanceof TextField) {
((TextField) txtCmp).setQwertyInput(qwerty);
}
com.codename1.ui.Display.getInstance().setThirdSoftButton(third);
current.setTintColor(oldTint);
}
}
}
/**
* Sets the default virtual keyboard class for the com.codename1.ui.VirtualKeyboard
* type
* This class is used as the default virtual keyboard class if the current
* platform VirtualKeyboard is com.codename1.ui.VirtualKeyboard.
* Platform VirtualKeyboard is defined here:
* Display.getIntance().setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb)
*
* @param vkbClazz this class must extend VirtualKeyboard.
*/
public static void setDefaultVirtualKeyboardClass(Class vkbClazz){
vkbClass = vkbClazz;
}
private VirtualKeyboard createVirtualKeyboard() {
try {
if(vkbClass != null){
return (VirtualKeyboard) vkbClass.newInstance();
}else{
return new VirtualKeyboard();
}
} catch (Exception ex) {
ex.printStackTrace();
return new VirtualKeyboard();
}
}
/**
* @see VirtualKeyboardInterface
*/
public String getVirtualKeyboardName() {
return NAME;
}
/**
* @see VirtualKeyboardInterface
*/
public boolean isVirtualKeyboardShowing() {
return isShowing;
}
}
| skyHALud/codenameone | CodenameOne/src/com/codename1/ui/VirtualKeyboard.java | Java | gpl-2.0 | 34,489 |
/*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.lir.asm;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import org.graalvm.compiler.core.common.type.DataPointerConstant;
/**
* Class for chunks of data that go into the data section.
*/
public class ArrayDataPointerConstant extends DataPointerConstant {
private final byte[] data;
public ArrayDataPointerConstant(byte[] array, int alignment) {
super(alignment);
data = array.clone();
}
public ArrayDataPointerConstant(short[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 2);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asShortBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(int[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asIntBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(float[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asFloatBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(double[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asDoubleBuffer().put(array);
data = byteBuffer.array();
}
public ArrayDataPointerConstant(long[] array, int alignment) {
super(alignment);
ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
byteBuffer.order(ByteOrder.nativeOrder());
byteBuffer.asLongBuffer().put(array);
data = byteBuffer.array();
}
@Override
public boolean isDefaultForKind() {
return false;
}
@Override
public void serialize(ByteBuffer buffer) {
buffer.put(data);
}
@Override
public int getSerializedSize() {
return data.length;
}
@Override
public String toValueString() {
return "ArrayDataPointerConstant" + Arrays.toString(data);
}
}
| md-5/jdk10 | src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir/src/org/graalvm/compiler/lir/asm/ArrayDataPointerConstant.java | Java | gpl-2.0 | 3,453 |
<style type="text/css">
<!--
.msg {
text-align:left;
color: blue;
display: block;
padding: 5px 0;
}
.emsg {
text-align:left;
color: red;
display: block;
padding: 5px 0;
}
#loader{
visibility:hidden;
}
#f1_error{
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight:bold;
color:#FF0000;
}
#f1_ok{
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight:bold;
color:#00FF00;
}
#f1_upload_process {
z-index:100;
visibility:hidden;
position:absolute;
margin: 10px 0 0;
width:220px;
}
#f1_upload_process span { display: block; padding-left: 7px; }
-->
</style>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, msg, src){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span>';
var ed = tinyMCE.get('jform_content'); // get editor instance
var newNode = ed.getDoc().createElement ( "img" ); // create img node
newNode.src = src; // add src attribute
ed.execCommand('mceInsertContent', false, newNode.outerHTML);
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span>';
}
result += '<input type="hidden" name="path_2_upload" value="<?php echo base64_encode(JPATH_ROOT . DS . 'tmp' . DS . session_id() . DS); ?>" />';
result += '<input type="hidden" name="link_2_upload" value="<?php echo base64_encode(JURI::root() . 'tmp/' . session_id() .'/'); ?>" />';
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + '<input name="myfile" type="file" size="30" style="float:left;" /><input type="button" name="submitBtn" id="submitBtn" class="sbtn" value="Upload" style="float: left;" />';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
window.addEvent('domready', function(){
// $$('#submitBtn').addEvent('click', function(e){
document.body.addEvent('click:relay(#submitBtn)', function(e){
var action = '<?php echo JURI::base(); ?>jelibs/ajaxupload/upload.php';
var formAction = $$('form[name="userForm"]').get('action');
$$('form[name="userForm"]').set('target', 'upload_target').set('action', action);
startUpload();
document.userForm.submit();
$$('form[name="userForm"]').set('target', '').set('action', formAction);
});
});
//-->
</script>
<?php
/**
* @version $Id: images2content.php 21097 2011-04-07 15:38:03Z dextercowley $
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
/**
* Bannerclient Field class for the Joomla Framework.
*
* @package Joomla.Administrator
* @subpackage com_banners
* @since 1.6
*/
class JFormFieldFront_Images2Content extends JFormFieldList
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type = 'Front_Images2Content';
public function getInput()
{
$html = '<div>';
$html .= '<p id="f1_upload_process"><span>Loading...</span><img src="'.JURI::base().'jelibs/ajaxupload/loader.gif" /><br/></p>
<p id="f1_upload_form" align="center">
<br />
<span style="float: left;">Upload images to content</span>
<br/>
<input name="myfile" type="file" size="30" style="float: left;" />
<input type="hidden" name="path_2_upload" value="'.base64_encode(JPATH_ROOT . DS . 'tmp' . DS . session_id() . DS) .'" />
<input type="hidden" name="link_2_upload" value="'.base64_encode(JURI::root() . 'tmp/' . session_id() . '/') .'" />
<input type="button" name="submitBtn" id="submitBtn" class="sbtn" value="Upload" style="float: left;" />
</p>
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
';
$html .= '<div class="clr"></div></div>';
return $html;
}
}
| ngxuanmui/9trip.vn | administrator/components/com_ntrip/models/fields/front/images2content.php | PHP | gpl-2.0 | 4,610 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit562156c4d0b385426dfb2e9042c495a5::getLoader();
| tumanob/Lib.KG | wp-content/plugins/wp-filebase/vendor/autoload.php | PHP | gpl-2.0 | 183 |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2014 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
require_once CLASS_EX_REALDIR . 'page_extends/admin/LC_Page_Admin_Ex.php';
/**
* オーナーズストア:認証キー設定 のページクラス.
*
* @package Page
* @author LOCKON CO.,LTD.
* @version $Id: LC_Page_Admin_OwnersStore_Settings.php 23546 2014-06-12 14:47:59Z shutta $
*/
class LC_Page_Admin_OwnersStore_Settings extends LC_Page_Admin_Ex
{
/** SC_FormParamのインスタンス */
public $objForm;
/** リクエストパラメーターを格納する連想配列 */
public $arrForm;
/** バリデーションエラー情報を格納する連想配列 */
public $arrErr;
/**
* Page を初期化する.
*
* @return void
*/
public function init()
{
parent::init();
$this->tpl_mainpage = 'ownersstore/settings.tpl';
$this->tpl_mainno = 'ownersstore';
$this->tpl_subno = 'settings';
$this->tpl_maintitle = 'オーナーズストア';
$this->tpl_subtitle = '認証キー設定';
$this->httpCacheControl('nocache');
}
/**
* Page のプロセス.
*
* @return void
*/
public function process()
{
$this->action();
$this->sendResponse();
}
/**
* Page のアクション.
*
* @return void
*/
public function action()
{
switch ($this->getMode()) {
// 入力内容をDBへ登録する
case 'register':
$this->execRegisterMode();
break;
// 初回表示
default:
$this->execDefaultMode();
}
}
/**
* registerアクションの実行.
* 入力内容をDBへ登録する.
*
* @param void
* @return void
*/
public function execRegisterMode()
{
// パラメーターオブジェクトの初期化
$this->initRegisterMode();
// POSTされたパラメーターの検証
$arrErr = $this->validateRegistermode();
// エラー時の処理
if (!empty($arrErr)) {
$this->arrErr = $arrErr;
$this->arrForm = $this->objForm->getHashArray();
return;
}
// エラーがなければDBへ登録
$arrForm = $this->objForm->getHashArray();
$this->registerOwnersStoreSettings($arrForm);
$this->arrForm = $arrForm;
$this->tpl_onload = "alert('登録しました。')";
}
/**
* registerアクションの初期化.
* SC_FormParamを初期化しメンバ変数にセットする.
*
* @param void
* @return void
*/
public function initRegisterMode()
{
// 前後の空白を削除
if (isset($_POST['public_key'])) {
$_POST['public_key'] = trim($_POST['public_key']);
}
$objForm = new SC_FormParam_Ex();
$objForm->addParam('認証キー', 'public_key', LTEXT_LEN, '', array('EXIST_CHECK', 'ALNUM_CHECK', 'MAX_LENGTH_CHECK'));
$objForm->setParam($_POST);
$this->objForm = $objForm;
}
/**
* registerアクションのパラメーターを検証する.
*
* @param void
* @return array エラー情報を格納した連想配列
*/
public function validateRegistermode()
{
return $this->objForm->checkError();
}
/**
* defaultアクションの実行.
* DBから登録内容を取得し表示する.
*
* @param void
* @return void
*/
public function execDefaultMode()
{
$this->arrForm = $this->getOwnersStoreSettings();
}
/**
* DBへ入力内容を登録する.
*
* @param array $arrSettingsData オーナーズストア設定の連想配列
* @return void
*/
public function registerOwnersStoreSettings($arrSettingsData)
{
$table = 'dtb_ownersstore_settings';
$objQuery =& SC_Query_Ex::getSingletonInstance();
$exists = $objQuery->exists($table);
if ($exists) {
$objQuery->update($table, $arrSettingsData);
} else {
$objQuery->insert($table, $arrSettingsData);
}
}
/**
* DBから登録内容を取得する.
*
* @param void
* @return array
*/
public function getOwnersStoreSettings()
{
$table = 'dtb_ownersstore_settings';
$colmuns = '*';
$objQuery =& SC_Query_Ex::getSingletonInstance();
$arrRet = $objQuery->select($colmuns, $table);
if (isset($arrRet[0])) return $arrRet[0];
return array();
}
}
| shoheiworks/Labo-EcCube | data/class/pages/admin/ownersstore/LC_Page_Admin_OwnersStore_Settings.php | PHP | gpl-2.0 | 5,480 |
<?php
/**
* ClickBank® API Constants *(for site owners)*.
*
* Copyright: © 2009-2011
* {@link http://www.websharks-inc.com/ WebSharks, Inc.}
* (coded in the USA)
*
* This WordPress® plugin (s2Member Pro) is comprised of two parts:
*
* o (1) Its PHP code is licensed under the GPL license, as is WordPress®.
* You should have received a copy of the GNU General Public License,
* along with this software. In the main directory, see: /licensing/
* If not, see: {@link http://www.gnu.org/licenses/}.
*
* o (2) All other parts of (s2Member Pro); including, but not limited to:
* the CSS code, some JavaScript code, images, and design;
* are licensed according to the license purchased.
* See: {@link http://www.s2member.com/prices/}
*
* Unless you have our prior written consent, you must NOT directly or indirectly license,
* sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module;
* or make an offer to do any of these things. All of these things are strictly
* prohibited with part (2) of the s2Member Pro Module.
*
* Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com
* (i.e. new features, bug fixes, updates, improvements); along with full access
* to our video tutorial library: {@link http://www.s2member.com/videos/}
*
* @package s2Member\API_Constants
* @since 1.5
*/
if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"]))
exit("Do not access this file directly.");
if (!class_exists ("c_ws_plugin__s2member_pro_clickbank_constants"))
{
/**
* ClickBank® API Constants *(for site owners)*.
*
* @package s2Member\API_Constants
* @since 1.5
*/
class c_ws_plugin__s2member_pro_clickbank_constants
{
/**
* ClickBank® API Constants *(for site owners)*.
*
* @package s2Member\API_Constants
* @since 1.5
*
* @attaches-to ``add_filter("ws_plugin__s2member_during_constants_c");``
*
* @param array $c Checksum array should be passed through by the Filter.
* @param array $vars Array of defined variables, passed through by the Filter.
* @return array Checksum array with new indexes for Constant values.
*/
public static function clickbank_constants ($c = FALSE, $vars = FALSE)
{
/**
* Flag indicating the ClickBank® Gateway is active.
*
* @package s2Member\API_Constants
* @since 1.5
*
* @var bool
*/
if (!defined ("S2MEMBER_PRO_CLICKBANK_GATEWAY"))
define ("S2MEMBER_PRO_CLICKBANK_GATEWAY", ($c[] = true));
return $c; // Return $c calculation values.
}
}
}
?> | foxydot/walker | wp-content/plugins/s2member-pro/includes/classes/gateways/clickbank/clickbank-constants.inc.php | PHP | gpl-2.0 | 2,593 |