repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
rom1sqr/miasm
|
test/arch/x86/unit/mn_pshufb.py
|
619
|
#! /usr/bin/env python
import sys
from asm_test import Asm_Test_32
class Test_PSHUFB(Asm_Test_32):
TXT = '''
main:
CALL next
.byte 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11
.byte 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0
next:
POP EBP
MOVQ MM0, QWORD PTR [EBP]
MOVQ MM1, MM0
PSHUFB MM1, QWORD PTR [EBP+0x8]
RET
'''
def check(self):
assert self.myjit.cpu.MM0 == 0x1122334455667788L
assert self.myjit.cpu.MM1 == 0x8877665544332211L
if __name__ == "__main__":
[test(*sys.argv[1:])() for test in [Test_PSHUFB]]
|
gpl-2.0
|
tbewley10310/Land-of-Archon
|
Scripts.LV3/AprilArmorWeaponPack/Black Knight Armor/BlackKnightsGorget.cs
|
1071
|
using System;
using Server;
namespace Server.Items
{
public class Blackknightsgorget : PlateGorget
{
public override int ArtifactRarity{ get{ return 20; } }
public override int InitMinHits{ get{ return 300; } }
public override int InitMaxHits{ get{ return 600; } }
[Constructable]
public Blackknightsgorget()
{
Weight = 3.0;
Name = "Black Knights Gorget";
Hue = 4455;
Attributes.BonusHits = 3;
Attributes.DefendChance = 10;
Attributes.Luck = 10;
Attributes.WeaponDamage = 4;
Attributes.WeaponSpeed = 10;
ArmorAttributes.SelfRepair = 10;
ColdBonus = 2;
EnergyBonus = 8;
FireBonus = 3;
PhysicalBonus = 8;
PoisonBonus = 6;
StrRequirement = 55;
}
public Blackknightsgorget( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
}
|
gpl-2.0
|
kenyaehrs/accounting
|
api/src/main/java/org/openmrs/module/accounting/api/model/IncomeReceipt.java
|
5065
|
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.accounting.api.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Type;
@Entity
@Table(name = "accounting_income_receipt")
public class IncomeReceipt {
@Id
@GeneratedValue
@Column(name = "income_receipt_id")
private Integer id;
@Column(name = "receipt_no")
private String receiptNo;
@Column(name = "description")
private String description;
@Temporal(TemporalType.DATE)
@Column(name = "receipt_date")
private Date receiptDate;
@Column(name = "created_date")
@Type(type = "timestamp")
private Date createdDate;
@Column(name = "created_by")
private int createdBy;
@Column(name = "voided")
private boolean voided;
@Column(name = "voided_date")
@Type(type = "timestamp")
private Date voideddDate;
@Column(name = "voided_by")
private int voidedBy;
@Column(name ="updated_by")
private int updatedBy;
@Column(name = "updated_date")
@Type(type="timestamp")
private Date updatedDate;
@Enumerated(EnumType.STRING)
@Column(name = "status")
private GeneralStatus status;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "receipt", targetEntity = IncomeReceiptItem.class)
private Set<IncomeReceiptItem> receiptItems;
public IncomeReceipt(String receiptNo, String description){
this.voided = false;
this.receiptNo = receiptNo;
this.description = description;
}
public IncomeReceipt(){
this.voided = false;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReceiptNo() {
return receiptNo;
}
public void setReceiptNo(String receiptNo) {
this.receiptNo = receiptNo;
}
public Date getReceiptDate() {
return receiptDate;
}
public void setReceiptDate(Date receiptDate) {
this.receiptDate = receiptDate;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public int getCreatedBy() {
return createdBy;
}
public void setCreatedBy(int createdBy) {
this.createdBy = createdBy;
}
public boolean isVoided() {
return voided;
}
public void setVoided(boolean voided) {
this.voided = voided;
}
public Date getVoideddDate() {
return voideddDate;
}
public void setVoideddDate(Date voideddDate) {
this.voideddDate = voideddDate;
}
public int getVoidedBy() {
return voidedBy;
}
public void setVoidedBy(int voidedBy) {
this.voidedBy = voidedBy;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(int updatedBy) {
this.updatedBy = updatedBy;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
@Override
public String toString() {
return "IncomeReceipt [id=" + id + ", receiptNo=" + receiptNo + ", description=" + description + ", receiptDate="
+ receiptDate + ", createdDate=" + createdDate + ", createdBy=" + createdBy + ", voided=" + voided
+ ", voideddDate=" + voideddDate + ", voidedBy=" + voidedBy + ", updatedBy=" + updatedBy + ", updatedDate="
+ updatedDate + "]";
}
public Set<IncomeReceiptItem> getReceiptItems() {
return receiptItems;
}
public void setReceiptItems(Set<IncomeReceiptItem> receiptItems) {
this.receiptItems = receiptItems;
}
public void addReceiptItem(IncomeReceiptItem item){
if (receiptItems == null) {
receiptItems = new HashSet<IncomeReceiptItem>();
}
receiptItems.add(item);
}
public GeneralStatus getStatus() {
return status;
}
public void setStatus(GeneralStatus status) {
this.status = status;
}
}
|
gpl-2.0
|
alfasado/mt-static-min
|
mt-static/jqueryui/i18n/jquery.ui.datepicker-sk.js
|
718
|
jQuery(function($){$.datepicker.regional['sk']={closeText:'Zavrieลฅ',prevText:'<Predchรกdzajรบci',nextText:'Nasledujรบci>',currentText:'Dnes',monthNames:['Januรกr','Februรกr','Marec','Aprรญl','Mรกj','Jรบn','Jรบl','August','September','Oktรณber','November','December'],monthNamesShort:['Jan','Feb','Mar','Apr','Mรกj','Jรบn','Jรบl','Aug','Sep','Okt','Nov','Dec'],dayNames:['Nedeฤพa','Pondelok','Utorok','Streda','ล tvrtok','Piatok','Sobota'],dayNamesShort:['Ned','Pon','Uto','Str','ล tv','Pia','Sob'],dayNamesMin:['Ne','Po','Ut','St','ล t','Pia','So'],weekHeader:'Ty',dateFormat:'dd.mm.yy',firstDay:1,isRTL:false,showMonthAfterYear:false,yearSuffix:''};$.datepicker.setDefaults($.datepicker.regional['sk']);});
|
gpl-2.0
|
elfmz/far2l
|
SimpleIndent/src/SimpleIndent.cpp
|
4734
|
/*
Simple Indent plugin for FAR Manager
Based on:
Block Indent plugin for FAR Manager
Copyright (C) 2001-2004 Alex Yaroslavsky
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 "plugin_123.hpp"
#include "version.hpp"
#ifdef FAR3
// {52d8eecb-acae-42de-9b2f-f1e909948272}
static const GUID MainGuid =
{ 0x52d8eecb, 0xacae, 0x42de, { 0x9b, 0x2f, 0xf1, 0xe9, 0x09, 0x94, 0x82, 0x72 } };
#endif
ADD_GETGLOBALINFO;
static struct PluginStartupInfo Info;
SHAREDSYMBOL void WINAPI WIDE_SUFFIX(SetStartupInfo)(const struct PluginStartupInfo *Info)
{
::Info=*Info;
}
SHAREDSYMBOL void WINAPI WIDE_SUFFIX(GetPluginInfo)(struct PluginInfo *Info)
{
Info->StructSize=sizeof(*Info);
Info->Flags=PF_DISABLEPANELS;
Info->PluginMenuStringsNumber=0;
}
OPENPLUGIN
{
return INVALID_HANDLE_VALUE;
}
PROCESSEDITORINPUT
{
const INPUT_RECORD* Rec = PROCESSEDITORINPUT_REC;
if (Rec->EventType==KEY_EVENT &&
Rec->Event.KeyEvent.bKeyDown &&
(Rec->Event.KeyEvent.wVirtualKeyCode & 0x7FFF) == 9 &&
(Rec->Event.KeyEvent.dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED | RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) == 0)
{
bool rev = !!(Rec->Event.KeyEvent.dwControlKeyState & (SHIFT_PRESSED));
struct EditorInfo ei;
INITSIZE(ei);
Info.EditorControl(ECTL_GETINFO, &ei);
{
struct EditorGetString egs;
INITSIZE(egs);
egs.StringNumber = -1;
Info.EditorControl(ECTL_GETSTRING, &egs);
if (ei.BlockType != BTYPE_STREAM || // Ignore block selection
egs.SelStart != 0 || // Only activate if selection starts on a line start
ei.CurPos != 0) // Only activate if the cursor is at the line start
return 0;
}
#ifdef FAR2
struct EditorUndoRedo eur;
INITSIZE(eur);
eur.Command = EUR_BEGIN;
Info.EditorControl(ECTL_UNDOREDO, &eur);
#endif
TCHAR IndentStr[2];
IndentStr[0] = '\t';
IndentStr[1] = '\0';
int line;
for (line = (int)ei.BlockStartLine; line < ei.TotalLines; line++)
{
struct EditorSetPosition esp;
INITSIZE(esp);
esp.CurLine = line;
esp.CurPos = esp.Overtype = 0;
esp.CurTabPos = esp.TopScreenLine = esp.LeftPos = -1;
Info.EditorControl(ECTL_SETPOSITION, &esp);
struct EditorGetString egs;
INITSIZE(egs);
egs.StringNumber = -1;
Info.EditorControl(ECTL_GETSTRING, &egs);
if (egs.SelStart == -1 || egs.SelStart == egs.SelEnd)
break; // Stop when reaching the end of the text selection
if (!rev) // Indent
{
if (egs.StringLength > 0)
Info.EditorControl(ECTL_INSERTTEXT, IndentStr);
}
else // Unindent
{
if (egs.StringLength > 0)
{
int n = 0;
if (egs.StringText[0]=='\t')
n = 1;
else
while (egs.StringText[n]==' ' && n < ei.TabSize)
n++;
for (int i=0; i<n; i++)
Info.EditorControl(ECTL_DELETECHAR, NULL);
}
}
}
{
struct EditorSetPosition esp;
INITSIZE(esp);
esp.CurLine = ei.CurLine;
esp.CurPos = ei.CurPos;
esp.TopScreenLine = ei.TopScreenLine;
esp.LeftPos = ei.LeftPos;
esp.Overtype = ei.Overtype;
esp.CurTabPos = -1;
Info.EditorControl(ECTL_SETPOSITION, &esp);
}
{
// Restore selection to how it was before the insertion
struct EditorSelect es;
INITSIZE(es);
es.BlockType = ei.BlockType;
es.BlockStartLine = ei.BlockStartLine;
es.BlockStartPos = 0;
es.BlockWidth = 0;
es.BlockHeight = line - ei.BlockStartLine + 1;
Info.EditorControl(ECTL_SELECT, &es);
}
#ifdef FAR2
eur.Command = EUR_END;
Info.EditorControl(ECTL_UNDOREDO, &eur);
#endif
Info.EditorControl(ECTL_REDRAW, NULL);
return 1;
}
return 0;
}
|
gpl-2.0
|
AlmasB/mmorpg
|
src/uk/ac/brighton/uni/ab607/mmorpg/common/Attribute.java
|
1743
|
package uk.ac.brighton.uni.ab607.mmorpg.common;
/**
* 9 primary attributes of a game character
*
* @author Almas Baimagambetov (ab607@uni.brighton.ac.uk)
* @version 1.0
*
*/
public enum Attribute {
STRENGTH, VITALITY, DEXTERITY, AGILITY, INTELLECT, WISDOM, WILLPOWER, PERCEPTION, LUCK;
@Override
public String toString() {
return this.name().length() > 3 ? this.name().substring(0, 3) : this.name();
}
/**
* Data structure for an info object that contains
* values of all the attributes
*/
public static class AttributeInfo {
public int str = 1, vit = 1, dex = 1,
agi = 1, int_ = 1, wis = 1,
wil = 1, per = 1, luc = 1;
public AttributeInfo str(final int value) {
str = value;
return this;
}
public AttributeInfo vit(final int value) {
vit = value;
return this;
}
public AttributeInfo dex(final int value) {
dex = value;
return this;
}
public AttributeInfo agi(final int value) {
agi = value;
return this;
}
public AttributeInfo int_(final int value) {
int_ = value;
return this;
}
public AttributeInfo wis(final int value) {
wis = value;
return this;
}
public AttributeInfo wil(final int value) {
wil = value;
return this;
}
public AttributeInfo per(final int value) {
per = value;
return this;
}
public AttributeInfo luc(final int value) {
luc = value;
return this;
}
}
}
|
gpl-2.0
|
xxMRXxx/M-R-X
|
plugins/h3.lua
|
1456
|
--Dev:> แนแนแบ .. @memo_cool
do
local function run(msg, matches)
if is_momod(msg) and matches[1]== "m3" then
return [[
ุงูุงู
ุฑ ุงูุญู
ุงูุฉ ูู ุงูู
ุฌู
ูุนุฉ โ
ูููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููู
๐ูุณุชุฎุฏู
๐ููู _ ููููู
๐ูุชุญ _ ูููุชุญ
ูููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููู
๐ุงูุฑูุงุจุท _ ๐ซ
๐ุงูุชูุฑุงุฑ _ ๐ซ
๐ุงูุณุจุงู
_ ๐ซ
๐ุงูุนุฑุจูุฉ _ ๐ซ
๐ุงูุงูููุด _ ๐ซ
๐ุงูุฏุฎูู _ ๐ซ
๐ุงูุฏุฎูู ุนุจุฑ ุงูุฑุงุจุท _๐ซ
๐ุงุดุนุงุฑุงุช ุงูุฏุฎูู _ ๐ซ
๐ุงูุงุถุงูุฉ _ ๐ซ
๐ ุงูู
ุบุงุฏุฑุฉ _๐ซ
๐ุงูููุฒููู
_ (@) ๐ซ
๐ุงูุชุงู _ (#) ๐ซ
๐ุงูุฑุฏ _ ๐ซ
๐ุงูููู
ุงุช ุงูุณูุฆุฉ _ ๐ซ
๐ุงูุญู
ุงูุฉ _ ๐ซ
ููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููููู
ุงู ุดู ุชุญุชุงุฌุฉ ุฑุงุณู ุงูู
ุทูุฑูู
--Dev:> แนแนแบ .. @memo_cool
--Dev:> @K_R_A_l_J
]]
end
if not is_momod(msg) then
return "Only managers ๐โ๏ธ"
end
end
return {
description = "Help list",
usage = "Help list",
patterns = {
"(m3)"
},
run = run
}
end
--Dev:> แนแนแบ .. @memo_cool
|
gpl-2.0
|
hd4fans/nexus
|
v6player.php
|
2819
|
<?php if(!isset($_GET['id'])|| !isset($_GET['u'])){
exit;
}
$id = $_GET['id'];
$u = $_GET['u'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div style="text-align:center">v6Speedๅๆญๆพๆไปถ <a href="http://www.hd4fans.org/v6speed.exe">ไธ่ฝฝ</a></div>
<object
classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"
width="0"
height="0"
id="vlc"
events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.hd4fans.org/v6speed.exe"
type="application/x-vlc-plugin"
version="VideoLAN.VLCPlugin.2"
width="0"
height="0"
toolbar="true"
align="left"
loop="true"
text="Waiting for video"
name="vlc"></EMBED>
</object>
<script language="javascript">
function getOs()
{
var OsObject = "";
if(navigator.userAgent.indexOf("MSIE")>0) {
return "MSIE";
}
if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){
return "Firefox";
}
if(isSafari=navigator.userAgent.indexOf("Safari")>0) {
return "Safari";
}
if(isCamino=navigator.userAgent.indexOf("Camino")>0){
return "Camino";
}
if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){
return "Gecko";
}
}
var s="MSIE";
if(getOs()==s)
{
var vlcObj = document.getElementById("vlc");
if( vlcObj.object != null ){
window.location.href = "v6player://<?php echo $id;?>&ty=1&ro=2&url=www.hd4fans.org&id=<?php echo $id;?>&ua=<?php echo $u; ?>";
}
else {
alert("่ฏทๅ
ๅฎ่ฃ
v6Speedๅๆญๆพๆไปถ");
window.location.href="http://www.hd4fans.org/v6speed.exe";
}
}
else
{
if(!navigator.plugins["VLC Web Plugin"])
{
alert("่ฏทๅ
ๅฎ่ฃ
v6Speedๅๆญๆพๆไปถ");
window.location.href="http://www.hd4fans.org/v6speed.exe";
}
else
{
window.location.href = "v6player://<?php echo $id;?>&ty=1&ro=2&url=www.hd4fans.org&id=<?php echo $id;?>&ua=<?php echo $u; ?>"
}
}
//window.location.href = "v6player://<?php echo $id;?>&ty=1&ro=2&url=www.hd4fans.org&id=<?php echo $id;?>&ua=<?php echo $u; ?>";
</script>
</body>
</html>
</body>
</html>
|
gpl-2.0
|
librelab/qtmoko-test
|
qtopiacore/qt/doc/src/snippets/code/src_qt3support_dialogs_q3progressdialog.cpp
|
2843
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
//! [0]
Q3ProgressDialog progress("Copying files...", "Abort Copy", numFiles,
this, "progress", true);
for (int i = 0; i < numFiles; i++) {
progress.setProgress(i);
qApp->processEvents();
if (progress.wasCanceled())
break;
//... copy one file
}
progress.setProgress(numFiles);
//! [0]
//! [1]
Operation::Operation(QObject *parent = 0)
: QObject(parent), steps(0)
{
pd = new Q3ProgressDialog("Operation in progress.", "Cancel", 100);
connect(pd, SIGNAL(canceled()), this, SLOT(cancel()));
t = new QTimer(this);
connect(t, SIGNAL(timeout()), this, SLOT(perform()));
t->start(0);
}
void Operation::perform()
{
pd->setProgress(steps);
//... perform one percent of the operation
steps++;
if (steps > pd->totalSteps())
t->stop();
}
void Operation::cancel()
{
t->stop();
//... cleanup
}
//! [1]
|
gpl-2.0
|
JGrubb/Almond-Tree
|
wp-content/themes/thesis_17/lib/admin/file_editor.php
|
8129
|
<?php
/**
* Outputs the Thesis Custom File Editor
*
* @package Thesis
* @since 1.6
*/
class thesis_custom_editor {
function get_custom_files() {
$files = array();
$directory = opendir(THESIS_CUSTOM); // Open the directory
$exts = array('.php', '.css', '.js', '.txt', '.inc', '.htaccess', '.html', '.htm'); // What type of files do we want?
while ($file = readdir($directory)) { // Read the files
if ($file != '.' && $file != '..') { // Only list files within the _current_ directory
$extension = substr($file, strrpos($file, '.')); // Get the extension of the file
if ($extension && in_array($extension, $exts)) // Verify extension of the file; we can't edit images!
$files[] = $file; // Add the file to the array
}
}
closedir($directory); // Close the directory
return $files; // Return the array of editable files
}
function is_custom_writable($file, $files) {
if (!in_array($file, $files))
$error = "<p><strong>" . __('Attention!', 'thesis') . '</strong> ' . __('For security reasons, the file you are attempting to edit cannot be modified via this screen.', 'thesis') . '</p>';
elseif (!file_exists(THESIS_CUSTOM)) // The custom/ directory does not exist
$error = "<p><strong>" . __('Attention!', 'thesis') . '</strong> ' . __('Your <code>custom/</code> directory does not appear to exist. Have you remembered to rename <code>/custom-sample</code>?', 'thesis') . '</p>';
elseif (!is_file(THESIS_CUSTOM . '/' . $file)) // The selected file does not exist
$error = "<p><strong>" . __('Attention!', 'thesis') . '</strong> ' . __('The file you are attempting does not appear to exist.', 'thesis') . '</p>';
elseif (!is_writable(THESIS_CUSTOM . '/custom.css')) // The selected file is not writable
$error = "<p><strong>" . __('Attention!', 'thesis') . '</strong> ' . sprintf(__('Your <code>/custom/%s</code> file is not writable by the server, and in order to modify the file via the admin panel, Thesis needs to be able to write to this file. All you have to do is set this file’s permissions to 666, and you’ll be good to go.', 'thesis'), $file) . '</p>';
if ($error) { // Return the error + markup, if required
$error = "<div class=\"warning\">\n\t$error\n</div>\n";
return $error;
}
return false;
}
function save_file() {
if (!current_user_can('edit_themes'))
wp_die(__('Easy there, homey. You don’t have admin privileges to access theme options.', 'thesis'));
$custom_editor = new thesis_custom_editor;
if (isset($_POST['custom_file_submit'])) {
$contents = stripslashes($_POST['newcontent']); // Get new custom content
$file = $_POST['file']; // Which file?
$allowed_files = $custom_editor->get_custom_files(); // Get list of allowed files
if (!in_array($file, $allowed_files)) // Is the file allowed? If not, get outta here!
wp_die(__('You have attempted to modify an ineligible file. Only files within the Thesis <code>/custom</code> folder may be modified via this interface. Thank you.', 'thesis'));
$file_open = fopen(THESIS_CUSTOM . '/' . $file, 'w+'); // Open the file
if ($file_open !== false) // If possible, write new custom file
fwrite($file_open, $contents);
fclose($file_open); // Close the file
$updated = '&updated=true'; // Display updated message
}
if (isset($_POST['custom_file_jump'])) {
$file = $_POST['custom_files'];
$updated = '';
}
wp_redirect(admin_url("admin.php?page=thesis-file-editor$updated&file=$file"));
}
function options_page() {
global $thesis_site;
$custom_editor = new thesis_custom_editor;
?>
<div id="thesis_options" class="wrap<?php if (get_bloginfo('text_direction') == 'rtl') { echo ' rtl'; } ?>">
<?php
thesis_version_indicator();
thesis_options_title(__('Thesis Custom File Editor', 'thesis'), false);
thesis_options_nav();
thesis_options_status_check();
if (version_compare($thesis_site->version, thesis_version()) != 0) {
?>
<form id="upgrade_needed" action="<?php echo admin_url('admin-post.php?action=thesis_upgrade'); ?>" method="post">
<h3><?php _e('Oooh, Exciting!', 'thesis'); ?></h3>
<p><?php _e('It’s time to upgrade your Thesis, which means there’s new awesomeness in your immediate future. Click the button below to fast-track your way to the awesomeness!', 'thesis'); ?></p>
<p><input type="submit" class="upgrade_button" id="teh_upgrade" name="upgrade" value="<?php _e('Upgrade Thesis', 'thesis'); ?>" /></p>
</form>
<?php
}
elseif (file_exists(THESIS_CUSTOM)) {
// Determine which file we're editing. Default to something harmless, like custom.css.
$file = ($_GET['file']) ? $_GET['file'] : 'custom.css';
$files = $custom_editor->get_custom_files();
$extension = substr($file, strrpos($file, '.'));
// Determine if the custom file exists and is writable. Otherwise, this page is useless.
$error = $custom_editor->is_custom_writable($file, $files);
if ($error)
echo $error;
else {
// Get contents of custom.css
if (filesize(THESIS_CUSTOM . '/' . $file) > 0) {
$content = fopen(THESIS_CUSTOM . '/' . $file, 'r');
$content = fread($content, filesize(THESIS_CUSTOM . '/' . $file));
$content = htmlspecialchars($content);
}
else
$content = '';
}
// Highlighting for which language?
$lang = (function_exists('codepress_get_lang')) ? codepress_get_lang($file) : '';
?>
<div class="one_col">
<form method="post" id="file-jump" name="file-jump" action="<?php echo admin_url('admin-post.php?action=thesis_file_editor'); ?>">
<h3><?php printf(__('Currently editing: <code>%s</code>', 'thesis'), "custom/$file"); ?></h3>
<?php
if (function_exists('use_codepress')) {
if (use_codepress())
echo "\t\t\t<a class=\"syntax\" id=\"codepress-off\" href=\"admin.php?page=thesis-file-editor&codepress=off&file=$file\">" . __('Disable syntax highlighting', 'thesis') . "</a>\n";
else
echo "\t\t\t<a class=\"syntax\" id=\"codepress-on\" href=\"admin.php?page=thesis-file-editor&codepress=on&file=$file\">". __('Enable syntax highlighting', 'thesis') . "</a></p>\n";
}
?>
<p>
<select id="custom_files" name="custom_files">
<option value="<?php echo $file; ?>"><?php echo $file; ?></option>
<?php
foreach ($files as $f) // An option for each available file
if ($f != $file) echo "\t\t\t\t\t<option value=\"$f\">$f</option>\n";
?>
</select>
<input type="submit" id="custom_file_jump" name="custom_file_jump" value="<?php _e('Edit selected file', 'thesis'); ?>" />
</p>
<?php
if ($extension == '.php')
echo "\t\t\t<p class=\"alert\">" . __('<strong>Note:</strong> If you make a mistake in your code while modifying a <acronym title="PHP: Hypertext Preprocessor">PHP</acronym> file, saving this page <em>may</em> result your site becoming temporarily unusable. Prior to editing such files, be sure to have access to the file via <acronym title="File Transfer Protocol">FTP</acronym> or other means so that you can correct the error.', 'thesis') . "</p>\n";
?>
</form>
<form class="file_editor" method="post" id="template" name="template" action="<?php echo admin_url('admin-post.php?action=thesis_file_editor'); ?>">
<input type="hidden" id="file" name="file" value="<?php echo $file; ?>" />
<p><textarea id="newcontent" name="newcontent" rows="25" cols="50" class="large-text codepress <?php echo $lang; ?>"><?php echo $content; ?></textarea></p>
<p>
<input type="submit" class="save_button" id="custom_file_submit" name="custom_file_submit" value="<?php thesis_save_button_text(); ?>" />
<input class="color" type="text" id="handy-color-picker" name="handy-color-picker" value="ffffff" maxlength="6" />
<label class="inline" for="handy-color-picker"><?php _e('quick color reference', 'thesis'); ?></label>
</p>
</form>
</div>
<?php
}
else
echo "<div class=\"warning\">\n\t<p><strong>" . __('Attention!', 'thesis') . '</strong> ' . __('In order to edit your custom files, you’ll need to change the name of your <code>custom-sample</code> folder to <code>custom</code>.', 'thesis') . "</p>\n</div>\n";
?>
</div>
<?php
}
}
|
gpl-2.0
|
Aracthor/super_zappy
|
server/srcs/map/Hoopla.cpp
|
302
|
//
// Hoopla.cpp for super_zappy in /home/aracthor/programs/projects/hub/super_zappy/server
//
// Made by
// Login <aracthor@epitech.net>
//
// Started on Sun Oct 12 07:37:06 2014
// Last Update Sun Oct 12 07:55:46 2014
//
#include "map/Hoopla.hh"
Hoopla::Hoopla()
{
}
Hoopla::~Hoopla()
{
}
|
gpl-2.0
|
Ponsietta/sitc-qrable-webapp
|
webroot/base.js
|
974
|
(function ($) {
'use strict';
//Form submission
function submit() {
$.post('qr_proc.php', {
'qr': $('[name="qr"]').val(),
'submit': 1
}, response);
return false;
}
function response(data) {
if (data === '1') {
var score = localStorage.getItem('score');
if (score) {
localStorage.setItem('score', score + 1);
} else {
localStorage.setItem('score', 1);
}
}
}
$('#qr_form').submit(submit);
//QR conversion
window.URL = window.URL || window.webkitURL;
function showDialog() {
$('#load_qr').click();
}
function start() {
var files = this.files;
if (!files) {
alert('We\'re sorry but file reader not supported!');
return;
}
if (!files.length) {
return;
}
var imageURL = URL.createObjectURL(files[0]);
qrcode.decode(imageURL);
}
function converted(qr) {
$('#qr').val(qr);
}
$('#get_qr').click(showDialog);
$('#load_qr').on('change', start);
qrcode.callback = converted;
})(jQuery);
|
gpl-2.0
|
hexmode/wikipathways.org
|
wpi/extensions/BrowsePathways/BrowsePathways.php
|
1049
|
<?php
# Not a valid entry point, skip unless MEDIAWIKI is defined
if (!defined('MEDIAWIKI')) {
echo <<<EOT
To install BrowsePathways, put the following line in LocalSettings.php:
require_once( "$IP/extensions/BrowsePathway/BrowsePathway.php" );
EOT;
exit( 1 );
}
$wgAutoloadClasses['BasePathwaysPager'] = dirname(__FILE__) . '/Pager.php';
$wgAutoloadClasses['PathwaysPagerFactory'] = dirname(__FILE__) . '/Pager.php';
$wgAutoloadClasses['ListPathwaysPager'] = dirname(__FILE__) . '/Pager.php';
$wgAutoloadClasses['SinglePathwaysPager'] = dirname(__FILE__) . '/Pager.php';
$wgAutoloadClasses['ThumbPathwaysPager'] = dirname(__FILE__) . '/Pager.php';
$wgAutoloadClasses['BrowsePathways'] = dirname(__FILE__) . '/BrowsePathways_body.php';
$wgAutoloadClasses['LegacyBrowsePathways'] = dirname(__FILE__) . '/BrowsePathways_body.php';
$wgSpecialPages['BrowsePathwaysPage'] = 'LegacyBrowsePathways';
$wgSpecialPages['BrowsePathways'] = 'BrowsePathways';
$wgExtensionMessagesFiles['BrowsePathways'] = dirname( __FILE__ ) . '/BrowsePathways.i18n.php';
|
gpl-2.0
|
Snuffelneus/Android-App
|
src/com/schriek/snuffelneus/PairedKoppelActivity.java
|
2841
|
package com.schriek.snuffelneus;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* Activity die gekoppelde apparaten weer geeft. Niet echt van groot belang maar handig voor ons
* @author Schriek
*
*/
public class PairedKoppelActivity extends Activity {
private BluetoothAdapter btAdapter = null;
private OutputStream outStream = null;
private BluetoothSocket socket = null;
private List<String> devices = new ArrayList<String>();
private ArrayAdapter<String> devices_adapter = null;
private IntentFilter iFilter;
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.paired_koppel_activity);
setResult(RESULT_CANCELED);
ListView devices_list = (ListView) findViewById(R.id.paired);
devices_adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, devices);
devices_list.setAdapter(devices_adapter);
devices_list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String val = (String) ((TextView) arg1).getText();
String adres = val.substring(val.length() - 17);
Intent returnIntent = new Intent();
returnIntent.putExtra("adres", adres);
returnIntent.putExtra("name",
val.substring(0, val.indexOf("\n")));
PairedKoppelActivity.this.setResult(RESULT_OK, returnIntent);
finish();
}
});
Set<BluetoothDevice> neuzen = getBondedSnuffelneuzen();
List<String> namesList = new ArrayList<String>();
for (BluetoothDevice dev : neuzen) {
namesList.add(dev.getName() + "\n" + dev.getAddress());
}
devices.addAll(namesList);
devices_adapter.notifyDataSetChanged();
}
private Set<BluetoothDevice> getBondedSnuffelneuzen() {
Set<BluetoothDevice> pairedDevices = BluetoothAdapter
.getDefaultAdapter().getBondedDevices();
Set<BluetoothDevice> snuffelneuzen = new LinkedHashSet<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
if (device.getName().startsWith("snuffelneus"))
snuffelneuzen.add(device);
}
return snuffelneuzen;
}
}
|
gpl-2.0
|
ikoula/cloudstack
|
api/src/com/cloud/vm/snapshot/VMSnapshotService.java
|
1969
|
// 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 com.cloud.vm.snapshot;
import java.util.List;
import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.uservm.UserVm;
import com.cloud.vm.VirtualMachine;
public interface VMSnapshotService {
List<? extends VMSnapshot> listVMSnapshots(ListVMSnapshotCmd cmd);
VMSnapshot getVMSnapshotById(Long id);
VMSnapshot creatVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm);
VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDescription, Boolean snapshotMemory) throws ResourceAllocationException;
boolean deleteVMSnapshot(Long vmSnapshotId);
UserVm revertToSnapshot(Long vmSnapshotId) throws InsufficientServerCapacityException, InsufficientCapacityException, ResourceUnavailableException,
ConcurrentOperationException;
VirtualMachine getVMBySnapshotId(Long id);
}
|
gpl-2.0
|
JozefAB/neoacu
|
components/com_guru/controllers/guruMedia.php
|
16053
|
<?php
/*------------------------------------------------------------------------
# com_guru
# ------------------------------------------------------------------------
# author iJoomla
# copyright Copyright (C) 2013 ijoomla.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.ijoomla.com
# Technical Support: Forum - http://www.ijoomla.com.com/forum/index/
-------------------------------------------------------------------------*/
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport ('joomla.application.component.controller');
class guruControllerguruMedia extends guruController {
var $_model = null;
function __construct () {
parent::__construct();
$this->registerTask ("add", "edit");
$this->registerTask ("", "listMedia");
$this->_model = $this->getModel("guruMedia");
$this->registerTask ("unpublish", "publish");
$this->registerTask('ajax_add_video', 'ajaxAddVideo');
$this->registerTask('ajax_add_mass_video', 'ajaxAddMassVideo');
}
function listMedia() {
$view = $this->getView("guruMedia", "html");
$view->setModel($this->_model, true);
$view->display();
}
function upload() {
JRequest::setVar ("hidemainmenu", 1);
$view = $this->getView("guruMedia", "html");
$view->setLayout("editForm");
$view->setModel($this->_model, true);
$model = $this->getModel("adagencyConfig");
$view->setModel($model);
$view->uploadflash();
$view->editForm();
}
function edit () {
JRequest::setVar ("hidemainmenu", 1);
$view = $this->getView("guruMedia", "html");
$view->setLayout("editForm");
$view->setModel($this->_model, true);
//$model = $this->getModel("adagencyConfig");
//$view->setModel($model);
$view->editForm();
}
function changes() {
JRequest::setVar ("hidemainmenu", 1);
$view = $this->getView("guruMedia", "html");
$view->setLayout("editForm");
$view->setModel($this->_model, true);
$view->editForm();
}
function save () {
if ($this->_model->store() ) {
$msg = JText::_('AD_ADSAVED');
} else {
$msg = JText::_('AD_ADSAVEFAIL');
}
$link = "index.php?option=com_guru&view=guruMedia";
$this->setRedirect($link, $msg);
}
function cancel () {
$msg = JText::_('AD_SAVECANCEL');
$link = "index.php?option=com_guru&view=guruMedia";
$this->setRedirect($link, $msg);
}
function publish () {
$res = $this->_model->publish();
if (!$res) {
$msg = JText::_('PACKAGEBLOCKERR');
} elseif ($res == -1) {
$msg = JText::_('PACKAGEUNPUB');
} elseif ($res == 1) {
$msg = JText::_('PACKAGEPUB');
} else {
$msg = JText::_('PACKAGEUNSPEC');
}
$link = "index.php?option=com_guru&view=guruMedia";
$this->setRedirect($link, $msg);
}
function unpublish () {
$res = $this->_model->unpublish();
if (!$res) {
$msg = JText::_('PACKAGEBLOCKERR');
} elseif ($res == -1) {
$msg = JText::_('PACKAGEUNPUB');
} elseif ($res == 1) {
$msg = JText::_('PACKAGEPUB');
} else {
$msg = JText::_('PACKAGEUNSPEC');
}
$link = "index.php?option=com_guru&view=guruMedia";
$this->setRedirect($link, $msg);
}
static public function getDetailsFromVideo($url , $raw = false , $headerOnly = false){
if (!$url){
return false;
}
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true );
if($raw){
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true );
}
$response = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
if ($curl_errno!=0){
/*$mainframe = JFactory::getApplication();
$err = 'CURL error : '.$curl_errno.' '.$curl_error;
$mainframe->enqueueMessage($err, 'error');*/
}
$code = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
// For redirects, we need to handle this properly instead of using CURLOPT_FOLLOWLOCATION
// as it doesn't work with safe_mode or openbase_dir set.
if( $code == 301 || $code == 302 ){
list( $headers , $body ) = explode( "\r\n\r\n" , $response , 2 );
preg_match( "/(Location:|URI:|location)(.*?)\n/" , $headers , $matches );
if( !empty( $matches ) && isset( $matches[2] ) ){
$url = JString::trim( $matches[2] );
curl_setopt( $ch , CURLOPT_URL , $url );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch , CURLOPT_HEADER, true );
$response = curl_exec( $ch );
}
}
if(!$raw){
if(isset($response)){
@list($headers, $body) = @explode("\r\n\r\n", $response, 2);
}
}
$ret = $raw ? $response : $body;
$ret = $headerOnly ? $headers : $ret;
curl_close($ch);
return $ret;
}
// CURL unavailable on this install
return false;
}
function str_ireplace($search, $replace, $str, $count = NULL) {
if ($count === FALSE) {
return self::_utf8_ireplace($search, $replace, $str);
} else {
return self::_utf8_ireplace($search, $replace, $str, $count);
}
}
public function _utf8_ireplace($search, $replace, $str, $count = NULL) {
if (!is_array($search)) {
$slen = strlen($search);
$lendif = strlen($replace) - $slen;
if ($slen == 0) {
return $str;
}
$search = JString::strtolower($search);
$search = preg_quote($search, '/');
$lstr = JString::strtolower($str);
$i = 0;
$matched = 0;
while (preg_match('/(.*)' . $search . '/Us', $lstr, $matches)) {
if ($i === $count) {
break;
}
$mlen = strlen($matches[0]);
$lstr = substr($lstr, $mlen);
$str = substr_replace($str, $replace, $matched + strlen($matches[1]), $slen);
$matched += $mlen + $lendif;
$i++;
}
return $str;
} else {
foreach (array_keys($search) as $k) {
if (is_array($replace)) {
if (array_key_exists($k, $replace)) {
$str = $this->_utf8_ireplace($search[$k], $replace[$k], $str, $count);
} else {
$str = $this->_utf8_ireplace($search[$k], '', $str, $count);
}
} else {
$str = $this->_utf8_ireplace($search[$k], $replace, $str, $count);
}
}
return $str;
}
}
public function getProvider($videoLink)
{
$providerName = 'invalid';
if (! empty($videoLink))
{
$origvideolink = $videoLink;
//if it using https
$videoLink = $this->str_ireplace( 'https://' , 'http://' , $videoLink );
$videoLink = $this->str_ireplace( 'http://' , '' , $videoLink );
//$this->str_ireplace issue fix for J1.6
if($videoLink === $origvideolink) $videoLink = str_ireplace( 'http://' , '' , $videoLink );
$videoLink = 'http://'. $videoLink;
$parsedLink = parse_url( $videoLink );
preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $parsedLink['host'], $matches);
if ( !empty($matches['domain'])){
$domain = $matches['domain'];
$provider = explode('.', $domain);
$providerName = JString::strtolower($provider[0]);
// For youtube, they might be using youtu.be address
if($domain == 'youtu.be')
{
$providerName = 'youtube';
}
if($parsedLink['host'] === 'new.myspace.com')
{
$providerName = 'invalid';
}
}
}
$libraryPath = JPATH_ROOT .'/components/com_guru/helpers/videos' .'/'. $providerName . '.php';
if (!JFile::exists($libraryPath)){
$providerName = 'invalid';
$libraryPath = JPATH_ROOT .'/components/com_guru/helpers/videos/invalid.php';
}
require_once(JPATH_ROOT .'/components/com_guru/helpers/videos/helper.php');
require_once($libraryPath);
$className = 'PTableVideo' . JString::ucfirst($providerName);
$table = new $className();
return $table;
}
function transformDuration($seconds){
$timer = "00:00";
if($seconds >= 60){
$minutes = (int)($seconds / 60);
$seconds = $seconds % 60;
if(strlen($minutes) == 1){
$minutes = "0".$minutes;
}
if(strlen($seconds) == 1){
$seconds = "0".$seconds;
}
$timer = $minutes.":".$seconds;
}
else{
$timer = "00:".$seconds;
}
if($timer == "00" || $timer == "00:" || $timer == "00:0" || $timer == "00:00"){
$timer = "N/A";
}
return $timer;
}
function ajaxAddVideo(){
$url = JRequest::getVar("url", "");
if(strpos(" ".$url, "http") === FALSE){
$url = "http://".$url;
}
if(strpos($url, "youtube") !== FALSE){
$url = str_replace("watch", "", $url);
}
$provider = $this->getProvider($url);
$provider->url = $url;
$provider->videoId = $provider->getId();
$video_details = $this->getDetailsFromVideo($provider->getFeedUrl());
$provider->xmlContent = $video_details;
$isValid = $provider->isValid();
if($isValid){
$this->title = $provider->getTitle();
$this->type = $provider->getType();
$this->video_id = $provider->getId();
$this->duration = $provider->getDuration();
$this->status = 'ready';
$this->thumb = $provider->getThumbnail();
$this->path = $url;
$this->description= $provider->getDescription();
$this->status = 'ready';
}
$title = $provider->getTitle();
$image = $provider->getThumbnail();
$duration = $this->transformDuration($provider->getDuration());
$description = $provider->getDescription();
$return = '';
$return .= '<div class="hasTip hasTooltip" data-toggle="tooltip" title="" data-placement="top" data-original-title="'.trim($description).'">
<div class="row-fluid">
<div class="cVideo-Thumb span3 g_margin_top">
<img alt="'.trim($title).'" src="'.trim($image).'">
<input type="hidden" name="video-name" id="video-name" value="'.trim($title).'" />
<input type="hidden" name="image_url" id="image_url" value="'.trim($image).'" />
<input type="hidden" name="duration" id="duration" value="'.trim($duration).'" />
<b>'.trim($duration).'</b>
</div>
<div class="cVideo-Content span8">
<b>'.trim($title).'</b>
<div><a href="#" onclick="javascript:changeVideo(); return false;" class="uk-button uk-button-small creator-change-video">Change Video</a></div>
<input type="hidden" id="video-description" name="video-description" value="'.str_replace('"', '\"', trim($description)).'" />
</div>
</div>
</div>
';
echo $return;
die();
}
function ajaxAddMassVideo(){
$host = JRequest::getVar("host", "0");
$playlist_id = JRequest::getVar("list", "");
$api = JRequest::getVar("api", "");
$page = JRequest::getVar("page", "1");
$start_with = JRequest::getVar("start_with", "1");
$per_page = JRequest::getVar("per_page", "25");
if($host == "1"){ // YouTube
$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=".intval($per_page)."&playlistId=".$playlist_id."&key=".$api;
$data = json_decode(file_get_contents($url), true); // data for page 1
if($start_with > 1){
// start pagination
for($i=2; $i<=$start_with; $i++){
if(isset($data["nextPageToken"])){
$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=".intval($per_page)."&pageToken=".trim($data["nextPageToken"])."&playlistId=".$playlist_id."&key=".$api;
$data = json_decode(file_get_contents($url), true); // data for page $i
}
}
}
$video = $data["items"];
$nVideo = count($video);
$table = '<table class="table table-striped table-bordered adminlist">
<tr>
<th width="5%" class="center">#</th>
<th width="5%" class="center">
<input type="checkbox" onclick="Joomla.checkAll(this)" checked="checked" name="toggle" value="" />
<span class="lbl"></span>
</th>
<th width="30%">'.JText::_("GURU_THUMBNAIL").'</th>
<th width="30%">'.JText::_("GURU_TITLE").'</th>
<th width="30%">'.JText::_("GURU_DESCRIPTION").'</th>
</tr>';
if($nVideo > 0){
for($i=0; $i<$nVideo; $i++){
$breaks = array("<br />","<br>","<br/>");
$video[$i]['snippet']['description'] = str_ireplace($breaks, "\r\n", $video[$i]['snippet']['description']);
$table .= ' <tr>
<td class="center">'.($i+1).'</td>
<td class="center">
<input type="checkbox" checked="checked" onclick="Joomla.isChecked(this.checked);" value="'.$i.'" name="cid[]" id="cb'.$i.'">
<span class="lbl"></span>
</td>
<td>
<img src="'.$video[$i]['snippet']['thumbnails']["default"]['url'].'" />
<input type="hidden" name="image[]" value="'.$video[$i]['snippet']['thumbnails']["default"]['url'].'" />
</td>
<td>
<textarea name="title[]">'.$video[$i]['snippet']['title'].'</textarea>
<input type="hidden" name="url[]" value="https://www.youtube.com/watch?v='.$video[$i]['snippet']["resourceId"]['videoId'].'" />
</td>
<td>
<textarea name="description[]">'.$video[$i]['snippet']['description'].'</textarea>
</td>
</tr>';
}
}
$table .= '</table>';
}
elseif($host == 2){ // Vimeo
$url = "http://vimeo.com/api/v2/album/".$playlist_id."/videos.json?page=".intval($page);
$data = json_decode(file_get_contents($url), true);
$nVideo = count($data);
$table = '<table class="table table-striped table-bordered adminlist">
<tr>
<th width="5%" class="center">#</th>
<th width="5%" class="center">
<input type="checkbox" checked="checked" onclick="Joomla.checkAll(this)" name="toggle" value="" />
<span class="lbl"></span>
</th>
<th width="30%">'.JText::_("GURU_THUMBNAIL").'</th>
<th width="30%">'.JText::_("GURU_TITLE").'</th>
<th width="30%">'.JText::_("GURU_DESCRIPTION").'</th>
</tr>';
if($nVideo > 0){
for($i=0; $i<$nVideo; $i++){
$breaks = array("<br />","<br>","<br/>");
$data[$i]['description'] = str_ireplace($breaks, "\r\n", $data[$i]['description']);
$table .= ' <tr>
<td class="center">'.($i+1).'</td>
<td class="center">
<input type="checkbox" checked="checked" onclick="Joomla.isChecked(this.checked);" value="'.$i.'" name="cid[]" id="cb'.$i.'">
<span class="lbl"></span>
</td>
<td>
<img src="'.$data[$i]['thumbnail_small'].'" />
<input type="hidden" name="image[]" value="'.$data[$i]['thumbnail_small'].'" />
</td>
<td>
<textarea name="title[]">'.$data[$i]['title'].'</textarea>
<input type="hidden" name="url[]" value="'.$data[$i]["url"].'" />
</td>
<td>
<textarea name="description[]">'.$data[$i]['description'].'</textarea>
</td>
</tr>';
}
}
else{
echo '<div class="alert alert-error">
<h4 class="alert-heading"></h4>
<p>'.JText::_("GURU_NO_FOUND_FETCH_VIDEO").'</p>
<ul>
<li>
'.JText::_("GURU_NO_FOUND_FETCH_VIDEO1").'
</li>
<li>
'.JText::_("GURU_NO_FOUND_FETCH_VIDEO2").'
</li>
</ul>
</div>';
}
$table .= '</table>';
}
echo $table;
die();
}
};
?>
|
gpl-2.0
|
guylangston/SokoSolve
|
src/SokoSolve.Core/Solver/Queue/SolverQueue.cs
|
1598
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace SokoSolve.Core.Solver.Queue
{
public class SolverQueue : BaseComponent, ISolverQueue
{
private readonly Queue<SolverNode> inner;
public SolverQueue()
{
inner = new Queue<SolverNode>();
}
public virtual SolverNode? FindMatch(SolverNode find) => inner.FirstOrDefault(x => x != null && x.Equals(find));
public int Count => inner.Count;
public virtual bool IsThreadSafe => false;
public void Init(SolverQueueMode mode) {}
public virtual void Enqueue(SolverNode node)
{
if (node == null) throw new ArgumentNullException(nameof(node));
Statistics.TotalNodes++;
inner.Enqueue(node);
}
public virtual void Enqueue(IEnumerable<SolverNode> nodes)
{
foreach (var node in nodes) Enqueue(node);
}
public virtual SolverNode? Dequeue()
{
if (inner.Count > 0)
{
Statistics.TotalNodes--;
return inner.Dequeue();
}
return null;
}
public virtual bool Dequeue(int count, List<SolverNode> dequeueInto)
{
var cc = 0;
while (cc < count)
{
var d = Dequeue();
if (d == null) return cc > 0;
dequeueInto.Add(d);
cc++;
}
return true;
}
}
}
|
gpl-2.0
|
z81/PolarOSApps
|
test/node_modules/es6-loader/node_modules/es6-transpiler/build/es5/transpiler/destructuring.js
|
11590
|
"use strict";
var assert = require("assert");
var core = require("./core");
var error = require("./../lib/error");
function getline(node) {
return node.loc.start.line;
}
function isEmptyDestructuring(node) {
if ( core.is.isObjectPattern(node) ) {
return node.properties.length === 0;
}
if ( core.is.isArrayPattern(node) ) {
return node.elements.length === 0
|| node.elements.every(function(node) { return node === null })
;
}
return false;
}
var plugin = module.exports = {
reset: function() {
}
, setup: function(alter, ast, options) {
if( !this.__isInit ) {
this.reset();
this.__isInit = true;
}
this.alter = alter;
this.options = options;
}
, ':: ObjectPattern,ArrayPattern': function replaceDestructuringVariableDeclaration(node) {
var parentNode, declarationNode;
{
parentNode = node.$parent;
if( parentNode.type === "VariableDeclarator" ) {
declarationNode = parentNode.$parent;
if ( core.is.isForInOf(declarationNode.$parent) ) {
//TODO::
}
else if ( core.is.isVarConstLet(declarationNode) ) {
this.__replaceDeclaration(parentNode, node);
}
}
else if( parentNode.type === "AssignmentExpression" ) {
this.__replaceAssignment(parentNode, node);
}
}
}
, __replaceDeclaration: function replaceDeclaration(declarator, declaratorId) {
var declaratorInit = declarator.init;
if( declaratorInit == null ) {
error(getline(declarator), "destructuring must have an initializer");
return;
}
var declarationString = this.unwrapDestructuring("var", declaratorId, declaratorInit);
var isFirstVar = declarationString.substring(0, 4) === "var ";
// replace destructuring with simple variable declaration
this.alter.replace(
declarator.range[0]
, declarator.range[1]
, (isFirstVar ? declarationString.substr(4) : declarationString)//remove first "var " if needed
);
}
, __replaceAssignment: function(assignment, assignmentLeft) {
var assignmentRight = assignment.right;
var declarationString = this.unwrapDestructuring("", assignmentLeft, assignmentRight);
// replace destructuring with simple variable assignment
this.alter.replace(
assignment.range[0]
, assignment.range[1]
, declarationString
);
}
, unwrapDestructuring: function unwrapDestructuring(kind, definitionNode, valueNode, newVariables, newDefinitions) {
var isObjectPattern = core.is.isObjectPattern(definitionNode);
assert(isObjectPattern || core.is.isArrayPattern(definitionNode));
if( !newVariables )newVariables = [];
assert(Array.isArray(newVariables));
newDefinitions = newDefinitions || [];
if( isEmptyDestructuring(definitionNode) ) {
// an empty destructuring
var placeholderVarName = core.getScopeTempVar(definitionNode, definitionNode.$scope.closestHoistScope());
core.setScopeTempVar(placeholderVarName, definitionNode, definitionNode.$scope.closestHoistScope());
var newDefinition = {
"type": "VariableDeclarator",
"id": {
"type": "Identifier",
"name": placeholderVarName
}
};
newDefinitions.push(newDefinition);
return placeholderVarName;
}
this.__unwrapDestructuring(kind === "var" ? 1 : 0, definitionNode, valueNode, newVariables, newDefinitions);
kind = (kind ? kind + " " : "");
var destructurisationString = kind;
var needsFirstComma = false;
for(var index = 0, len = newDefinitions.length ; index < len ; index++ ){
var definition = newDefinitions[index];
// inherit scope from original VariableDefinitions node
definition.$scope = definitionNode.$scope;
assert( definition.type === "VariableDeclarator" );
var delimiter = void 0;
if( needsFirstComma ) {
delimiter = ", ";
needsFirstComma = false;
}
else {
delimiter = "";
}
assert( typeof definition["$raw"] === "string" );//"$raw" defined in this.__unwrapDestructuring
destructurisationString += ( delimiter + definition["$raw"] + (definition["$lineBreaks"] || '') );
if( definition["$assignmentExpressionResult"] === true ) {
var $parent = valueNode.$parent;
if( $parent && ($parent = $parent.$parent) && ($parent = $parent.$parent) && !core.is.isBodyStatement($parent) && !core.is.isBinaryExpression($parent) ) {
var isExpressionStatementWithoutBrackets = this.alter.getRange(valueNode.range[1], valueNode.$parent.$parent.range[1]) !== ')';
if( isExpressionStatementWithoutBrackets ) {
destructurisationString = '(' + destructurisationString + ')';
}
}
}
needsFirstComma = true;
}
return destructurisationString;
}
, __unwrapDestructuring: function(type, definitionNode, valueNode, newVariables, newDefinitions, hoistScope) {
var isTemporaryVariable = false, valueIdentifierName, temporaryVariableIndexOrName, valueIdentifierDefinition;
var isTemporaryValueAssignment = false;
var isObjectPattern = core.is.isObjectPattern(definitionNode)
, valueNode_isArrayPattern = core.is.isArrayPattern(valueNode)
, valueNode_isObjectPattern = core.is.isObjectPattern(valueNode)
, elementsList = isObjectPattern ? definitionNode.properties : definitionNode.elements
, localFreeVariables
, isLocalFreeVariable = type === 1
;
assert(elementsList.length);
if( isLocalFreeVariable || valueNode_isArrayPattern || valueNode_isObjectPattern ) {
//TODO:: tests
//TODO:: get only last variable name
localFreeVariables = core.getNodeVariableNames(definitionNode);
}
if( typeof valueNode["$raw"] === "string" ) {
valueIdentifierName = valueNode["$raw"];
if( valueIdentifierName.indexOf("[") !== -1 || valueIdentifierName.indexOf(".") !== -1 ) {
isTemporaryVariable = true;
valueIdentifierDefinition = valueIdentifierName;
}
}
else if( valueNode.type === "Identifier" ) {
valueIdentifierName = valueNode.name;
if( valueIdentifierName.indexOf("[") !== -1 || valueIdentifierName.indexOf(".") !== -1 ) {
isTemporaryVariable = true;
valueIdentifierDefinition = valueIdentifierName;
}
}
else {
isTemporaryVariable = true;
if( valueNode_isArrayPattern || valueNode_isObjectPattern ) {
valueIdentifierDefinition = localFreeVariables.pop();
}
else {
var isSequenceExpression = valueNode.type === "SequenceExpression";
valueIdentifierDefinition = (isSequenceExpression ? "(" : "") + this.alter.get(valueNode.range[0], valueNode.range[1]) + (isSequenceExpression ? ")" : "");
}
}
if( isTemporaryVariable ) {
if( valueNode.type === "Identifier" || isLocalFreeVariable ) {
if( elementsList.length < 2 ) {
isTemporaryVariable = false;
}
if( isTemporaryVariable === false ) {
if( valueIdentifierDefinition.charAt(0) !== "(") {
valueIdentifierName = "(" + valueIdentifierDefinition + ")";
}
else {
valueIdentifierName = valueIdentifierDefinition;
}
}
}
}
if( isTemporaryVariable ) {
if( isLocalFreeVariable ) {
valueIdentifierName = localFreeVariables.pop();
}
else {
valueIdentifierName = null;
}
if( !valueIdentifierName ) {
isLocalFreeVariable = false;
if( !hoistScope ) {
hoistScope = definitionNode.$scope.closestHoistScope();
}
valueIdentifierName = core.getScopeTempVar(definitionNode, hoistScope);
}
else {
isLocalFreeVariable = true;
}
temporaryVariableIndexOrName = valueIdentifierName;
valueIdentifierName = "(" + valueIdentifierName + " = " + valueIdentifierDefinition + ")";
isTemporaryValueAssignment = true;
}
var lastElement;
for( var k = 0, len = elementsList.length, lineBreaksFrom = definitionNode.range[0] ; k < len ; k++ ) {
var element = elementsList[k], elementId = isObjectPattern ? element.value : element;
var lineBreaks = "";
if ( element ) {
lineBreaks = (this.alter.getRange(lineBreaksFrom, element.range[0]).match(/[\r\n]/g) || []).join("");
lineBreaks += (valueNode["$lineBreaks"] || "");
lineBreaksFrom = element.range[1];
lastElement = element;
}
if ( element ) {
if ( core.is.isObjectPattern(elementId) || core.is.isArrayPattern(elementId) ) {
this.__unwrapDestructuring(
1
, isObjectPattern ? element.value : element
, {
type: "Identifier"
, name: valueIdentifierName + (isObjectPattern ? core.PropertyToString(element.key) : ("[" + k + "]"))
, "$lineBreaks": lineBreaks
}
, newVariables
, newDefinitions
, hoistScope
);
}
else {
var renamingOptions = elementId.$renamingOptions;
if( renamingOptions ) {// turn off changes were made by 'letConst' transpiler
renamingOptions.inactive = true;
}
var newDefinition = {
"type": "VariableDeclarator",
"id": elementId,
"init": {
"type": "MemberExpression",
"computed": element.computed,
"object": {
"type": "Identifier",
"name": valueIdentifierName
}
}
};
newDefinition.$scope = definitionNode.$scope;
if( isObjectPattern ) {
newDefinition["init"]["property"] = element.key;
}
else {
newDefinition["computed"] = true;
newDefinition["init"]["property"] = {
"type": "Literal",
"value": k,
"raw": k + ""
}
}
// TODO::
// if( type === 0 ) {
// newDefinition["type"] = "AssignmentExpression";
// newDefinition["left"] = newDefinition["id"];
// delete newDefinition["id"];
// newDefinition["right"] = newDefinition["init"];
// delete newDefinition["init"];
// }
if( element.type === "SpreadElement" ) {
newDefinition["$raw"] = core.unwrapRestDeclaration(element.argument, valueIdentifierName, k);
newDefinition["$lineBreaks"] = lineBreaks;
}
else {
// if( type === 1 ) {//VariableDeclarator
newDefinition["$raw"] = core.VariableDeclaratorString(newDefinition);
// }
// else {//AssignmentExpression
// newDefinition["$raw"] = core.AssignmentExpressionString(newDefinition);
// }
}
newDefinition["$lineBreaks"] = lineBreaks;
newDefinitions.push(newDefinition);
}
if( isTemporaryValueAssignment ) {
valueIdentifierName = temporaryVariableIndexOrName;
isTemporaryValueAssignment = false;
}
}
}
var lastLineBreaks = "";
if ( lastElement ) {
var start = definitionNode.range[1]
, end = valueNode.range && valueNode.range[0]
;
var lineBreaksBetween =
end
&& (start < end)
&& (this.alter.getRange(start, end).match(/[\r\n]/g))
|| []
;
start = lastElement.range[1];
end = definitionNode.range[1];
lastLineBreaks = lineBreaksBetween.concat(
(start < end)
&& this.alter.getRange(start, end).match(/[\r\n]/g) || []
);
lastLineBreaks = lastLineBreaks.join("")
}
if( type === 0 ) {//AssignmentExpression
newDefinitions.push({
"type": "VariableDeclarator"
, "$raw": temporaryVariableIndexOrName || valueIdentifierName
, "$assignmentExpressionResult": true
, "$lineBreaks": lastLineBreaks + (valueNode["$lineBreaks"] || "")
});
}
else {
assert(newDefinitions.length);
newDefinitions[newDefinitions.length - 1]["$lineBreaks"] += lastLineBreaks;
}
assert(!isTemporaryValueAssignment);
if( !isLocalFreeVariable && isTemporaryVariable && temporaryVariableIndexOrName != void 0 ) {
core.setScopeTempVar(temporaryVariableIndexOrName, valueNode, hoistScope, true);
}
}
};
for(var i in plugin) if( plugin.hasOwnProperty(i) && typeof plugin[i] === "function" ) {
plugin[i] = plugin[i].bind(plugin);
}
|
gpl-2.0
|
ExtendOnline/client
|
src/gui/windows/charcreatedialog.cpp
|
20431
|
/*
* The ManaPlus Client
* Copyright (C) 2004-2009 The Mana World Development Team
* Copyright (C) 2009-2010 The Mana Developers
* Copyright (C) 2011-2015 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* 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
* 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 "gui/windows/charcreatedialog.h"
#include "configuration.h"
#include "enums/being/beingdirection.h"
#include "gui/windows/okdialog.h"
#include "gui/widgets/button.h"
#include "gui/windows/charselectdialog.h"
#include "gui/widgets/createwidget.h"
#include "gui/widgets/label.h"
#include "gui/widgets/playerbox.h"
#include "gui/widgets/slider.h"
#include "gui/widgets/tabstrip.h"
#include "gui/widgets/textfield.h"
#include "net/charserverhandler.h"
#include "resources/iteminfo.h"
#include "resources/db/chardb.h"
#include "resources/db/colordb.h"
#include "resources/db/itemdb.h"
#include "utils/delete2.h"
#include "utils/gettext.h"
#include "debug.h"
#undef ERROR
extern Configuration config;
static bool haveRaceSelection = false;
static bool haveLookSelection = false;
static bool haveCreateCharGender = false;
static const BeingActionT actions[] =
{
BeingAction::STAND,
BeingAction::SIT,
BeingAction::MOVE,
BeingAction::ATTACK,
BeingAction::DEAD
};
static const uint8_t directions[] =
{
BeingDirection::DOWN,
BeingDirection::RIGHT,
BeingDirection::UP,
BeingDirection::LEFT
};
CharCreateDialog::CharCreateDialog(CharSelectDialog *const parent,
const int slot) :
// TRANSLATORS: char create dialog name
Window(_("New Character"), Modal_true, parent, "charcreate.xml"),
ActionListener(),
KeyListener(),
mCharSelectDialog(parent),
mNameField(new TextField(this, "")),
// TRANSLATORS: char create dialog label
mNameLabel(new Label(this, _("Name:"))),
// TRANSLATORS: This is a narrow symbol used to denote 'next'.
// You may change this symbol if your language uses another.
// TRANSLATORS: char create dialog button
mNextHairColorButton(new Button(this, _(">"), "nextcolor", this)),
// TRANSLATORS: This is a narrow symbol used to denote 'previous'.
// You may change this symbol if your language uses another.
// TRANSLATORS: char create dialog button
mPrevHairColorButton(new Button(this, _("<"), "prevcolor", this)),
// TRANSLATORS: char create dialog label
mHairColorLabel(new Label(this, _("Hair color:"))),
mHairColorNameLabel(new Label(this, "")),
// TRANSLATORS: char create dialog button
mNextHairStyleButton(new Button(this, _(">"), "nextstyle", this)),
// TRANSLATORS: char create dialog button
mPrevHairStyleButton(new Button(this, _("<"), "prevstyle", this)),
// TRANSLATORS: char create dialog label
mHairStyleLabel(new Label(this, _("Hair style:"))),
mHairStyleNameLabel(new Label(this, "")),
mNextRaceButton(nullptr),
mPrevRaceButton(nullptr),
mRaceLabel(nullptr),
mRaceNameLabel(nullptr),
mNextLookButton(nullptr),
mPrevLookButton(nullptr),
mLookLabel(nullptr),
mLookNameLabel(nullptr),
// TRANSLATORS: char create dialog button
mActionButton(new Button(this, _("^"), "action", this)),
// TRANSLATORS: char create dialog button
mRotateButton(new Button(this, _(">"), "rotate", this)),
mAttributeSlider(),
mAttributeLabel(),
mAttributeValue(),
mAttributesLeft(new Label(this,
// TRANSLATORS: char create dialog label
strprintf(_("Please distribute %d points"), 99))),
// TRANSLATORS: char create dialog button
mCreateButton(new Button(this, _("Create"), "create", this)),
// TRANSLATORS: char create dialog button
mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
mPlayer(new Being(BeingId_zero,
ActorType::Player,
BeingTypeId_zero,
nullptr)),
mPlayerBox(new PlayerBox(this, mPlayer, "charcreate_playerbox.xml",
"charcreate_selectedplayerbox.xml")),
mGenderStrip(nullptr),
mMaxPoints(0),
mUsedPoints(0),
mRace(CharDB::getMinRace()),
mLook(0),
mMinLook(CharDB::getMinLook()),
mMaxLook(CharDB::getMaxLook()),
mMinRace(CharDB::getMinRace()),
mMaxRace(CharDB::getMaxRace()),
mHairStyle(0),
mHairColor(0),
mSlot(slot),
mDefaultGender(Gender::FEMALE),
mGender(Gender::UNSPECIFIED),
maxHairColor(CharDB::getMaxHairColor()),
minHairColor(CharDB::getMinHairColor()),
maxHairStyle(CharDB::getMaxHairStyle()),
minHairStyle(CharDB::getMinHairStyle()),
mAction(0),
mDirection(0)
{
setStickyButtonLock(true);
setSticky(true);
setWindowName("NewCharacter");
const int w = 480;
const int h = 350;
setContentSize(w, h);
mPlayer->setGender(Gender::MALE);
const std::vector<int> &items = CharDB::getDefaultItems();
int i = 1;
for (std::vector<int>::const_iterator it = items.begin(),
it_end = items.end();
it != it_end; ++ it, i ++)
{
mPlayer->setSprite(i, *it);
}
if (!maxHairColor)
maxHairColor = ColorDB::getHairSize();
if (!maxHairStyle)
maxHairStyle = mPlayer->getNumOfHairstyles();
if (maxHairStyle)
{
mHairStyle = (static_cast<unsigned int>(rand())
% maxHairStyle) + minHairStyle;
}
else
{
mHairStyle = 0;
}
if (maxHairColor)
{
mHairColor = (static_cast<unsigned int>(rand())
% maxHairColor) + minHairColor;
}
else
{
mHairColor = 0;
}
mNameField->setMaximum(24);
if (haveRaceSelection)
{
// TRANSLATORS: char create dialog button
mNextRaceButton = new Button(this, _(">"), "nextrace", this);
// TRANSLATORS: char create dialog button
mPrevRaceButton = new Button(this, _("<"), "prevrace", this);
// TRANSLATORS: char create dialog label
mRaceLabel = new Label(this, _("Race:"));
mRaceNameLabel = new Label(this, "");
}
if (haveLookSelection && mMinLook < mMaxLook)
{
// TRANSLATORS: char create dialog button
mNextLookButton = new Button(this, _(">"), "nextlook", this);
// TRANSLATORS: char create dialog button
mPrevLookButton = new Button(this, _("<"), "prevlook", this);
// TRANSLATORS: char create dialog label
mLookLabel = new Label(this, _("Look:"));
mLookNameLabel = new Label(this, "");
}
if (haveCreateCharGender)
{
const int size = config.getIntValue("fontSize");
mGenderStrip = new TabStrip(this,
"gender_" + getWindowName(),
size + 16);
mGenderStrip->setPressFirst(false);
mGenderStrip->addActionListener(this);
mGenderStrip->setActionEventId("gender_");
// TRANSLATORS: one char size female character gender
mGenderStrip->addButton(_("F"), "f", false);
// TRANSLATORS: one char size male character gender
mGenderStrip->addButton(_("M"), "m", false);
// TRANSLATORS: one char size unknown character gender
mGenderStrip->addButton(_("U"), "u", true);
mGenderStrip->setVisible(Visible_true);
add(mGenderStrip);
mGenderStrip->setPosition(385, 130);
mGenderStrip->setWidth(500);
mGenderStrip->setHeight(50);
}
mPlayerBox->setWidth(74);
mNameField->setActionEventId("create");
mNameField->addActionListener(this);
mPlayerBox->setDimension(Rect(360, 0, 110, 90));
mActionButton->setPosition(385, 100);
mRotateButton->setPosition(415, 100);
mNameLabel->setPosition(5, 2);
mNameField->setDimension(
Rect(60, 2, 300, mNameField->getHeight()));
const int leftX = 120;
const int rightX = 300;
const int labelX = 5;
const int nameX = 145;
int y = 30;
mPrevHairColorButton->setPosition(leftX, y);
mNextHairColorButton->setPosition(rightX, y);
y += 5;
mHairColorLabel->setPosition(labelX, y);
mHairColorNameLabel->setPosition(nameX, y);
y += 24;
mPrevHairStyleButton->setPosition(leftX, y);
mNextHairStyleButton->setPosition(rightX, y);
y += 5;
mHairStyleLabel->setPosition(labelX, y);
mHairStyleNameLabel->setPosition(nameX, y);
if (haveLookSelection && mMinLook < mMaxLook)
{
y += 24;
if (mPrevLookButton)
mPrevLookButton->setPosition(leftX, y);
if (mNextLookButton)
mNextLookButton->setPosition(rightX, y);
y += 5;
if (mLookLabel)
mLookLabel->setPosition(labelX, y);
if (mLookNameLabel)
mLookNameLabel->setPosition(nameX, y); // 93
}
if (haveRaceSelection)
{
y += 24;
if (mPrevRaceButton)
mPrevRaceButton->setPosition(leftX, y);
if (mNextRaceButton)
mNextRaceButton->setPosition(rightX, y);
y += 5;
if (mRaceLabel)
mRaceLabel->setPosition(labelX, y);
if (mRaceNameLabel)
mRaceNameLabel->setPosition(nameX, y);
}
updateSliders();
setButtonsPosition(w, h);
add(mPlayerBox);
add(mNameField);
add(mNameLabel);
add(mNextHairColorButton);
add(mPrevHairColorButton);
add(mHairColorLabel);
add(mHairColorNameLabel);
add(mNextHairStyleButton);
add(mPrevHairStyleButton);
add(mHairStyleLabel);
add(mHairStyleNameLabel);
add(mActionButton);
add(mRotateButton);
if (haveLookSelection && mMinLook < mMaxLook)
{
add(mNextLookButton);
add(mPrevLookButton);
add(mLookLabel);
add(mLookNameLabel);
}
if (haveRaceSelection)
{
add(mNextRaceButton);
add(mPrevRaceButton);
add(mRaceLabel);
add(mRaceNameLabel);
}
add(mAttributesLeft);
add(mCreateButton);
add(mCancelButton);
center();
setVisible(Visible_true);
mNameField->requestFocus();
updateHair();
if (haveRaceSelection)
updateRace();
if (haveLookSelection && mMinLook < mMaxLook)
updateLook();
updatePlayer();
addKeyListener(this);
}
CharCreateDialog::~CharCreateDialog()
{
delete2(mPlayer);
if (charServerHandler)
charServerHandler->setCharCreateDialog(nullptr);
}
void CharCreateDialog::action(const ActionEvent &event)
{
const std::string &id = event.getId();
if (id == "create")
{
if (getName().length() >= 4 && getName().length() < 24)
{
// Attempt to create the character
mCreateButton->setEnabled(false);
std::vector<int> atts;
for (size_t i = 0, sz = mAttributeSlider.size(); i < sz; i++)
{
atts.push_back(static_cast<int>(
mAttributeSlider[i]->getValue()));
}
const int characterSlot = mSlot;
charServerHandler->newCharacter(getName(),
characterSlot,
mGender,
mHairStyle,
mHairColor,
static_cast<unsigned char>(mRace),
static_cast<unsigned char>(mLook),
atts);
}
else
{
CREATEWIDGET(OkDialog,
// TRANSLATORS: char creation error
_("Error"),
// TRANSLATORS: char creation error
_("Wrong name."),
// TRANSLATORS: ok dialog button
_("OK"),
DialogType::ERROR,
Modal_true,
ShowCenter_true,
nullptr,
260);
}
}
else if (id == "cancel")
{
scheduleDelete();
}
else if (id == "nextcolor")
{
mHairColor ++;
updateHair();
}
else if (id == "prevcolor")
{
mHairColor --;
updateHair();
}
else if (id == "nextstyle")
{
mHairStyle ++;
updateHair();
}
else if (id == "prevstyle")
{
mHairStyle --;
updateHair();
}
else if (id == "nextrace")
{
mRace ++;
updateRace();
}
else if (id == "prevrace")
{
mRace --;
updateRace();
}
else if (id == "nextlook")
{
mLook ++;
updateLook();
}
else if (id == "prevlook")
{
mLook --;
updateLook();
}
else if (id == "statslider")
{
updateSliders();
}
else if (id == "action")
{
mAction ++;
if (mAction >= 5)
mAction = 0;
updatePlayer();
}
else if (id == "rotate")
{
mDirection ++;
if (mDirection >= 4)
mDirection = 0;
updatePlayer();
}
else if (id == "gender_m")
{
mGender = Gender::MALE;
mPlayer->setGender(Gender::MALE);
}
else if (id == "gender_f")
{
mGender = Gender::FEMALE;
mPlayer->setGender(Gender::FEMALE);
}
else if (id == "gender_u")
{
mGender = Gender::UNSPECIFIED;
mPlayer->setGender(mDefaultGender);
}
}
std::string CharCreateDialog::getName() const
{
std::string name = mNameField->getText();
trim(name);
return name;
}
void CharCreateDialog::updateSliders()
{
for (size_t i = 0, sz = mAttributeSlider.size(); i < sz; i++)
{
// Update captions
mAttributeValue[i]->setCaption(
toString(static_cast<int>(mAttributeSlider[i]->getValue())));
mAttributeValue[i]->adjustSize();
}
// Update distributed points
const int pointsLeft = mMaxPoints - getDistributedPoints();
if (pointsLeft == 0)
{
// TRANSLATORS: char create dialog label
mAttributesLeft->setCaption(_("Character stats OK"));
mCreateButton->setEnabled(true);
}
else
{
mCreateButton->setEnabled(false);
if (pointsLeft > 0)
{
mAttributesLeft->setCaption(
// TRANSLATORS: char create dialog label
strprintf(_("Please distribute %d points"), pointsLeft));
}
else
{
mAttributesLeft->setCaption(
// TRANSLATORS: char create dialog label
strprintf(_("Please remove %d points"), -pointsLeft));
}
}
mAttributesLeft->adjustSize();
}
void CharCreateDialog::unlock()
{
mCreateButton->setEnabled(true);
}
int CharCreateDialog::getDistributedPoints() const
{
int points = 0;
for (size_t i = 0, sz = mAttributeSlider.size(); i < sz; i++)
points += static_cast<int>(mAttributeSlider[i]->getValue());
return points;
}
void CharCreateDialog::setAttributes(const StringVect &labels,
const int available,
const int min, const int max)
{
mMaxPoints = available;
for (size_t i = 0; i < mAttributeLabel.size(); i++)
{
remove(mAttributeLabel[i]);
delete2(mAttributeLabel[i])
remove(mAttributeSlider[i]);
delete2(mAttributeSlider[i])
remove(mAttributeValue[i]);
delete2(mAttributeValue[i])
}
mAttributeLabel.resize(labels.size());
mAttributeSlider.resize(labels.size());
mAttributeValue.resize(labels.size());
const int w = 480;
int h = 350;
const int y = 118 + 29;
for (unsigned i = 0, sz = static_cast<unsigned>(labels.size());
i < sz; i++)
{
mAttributeLabel[i] = new Label(this, labels[i]);
mAttributeLabel[i]->setWidth(70);
mAttributeLabel[i]->setPosition(5, y + i * 24);
mAttributeLabel[i]->adjustSize();
add(mAttributeLabel[i]);
mAttributeSlider[i] = new Slider(this, min, max, 1.0);
mAttributeSlider[i]->setDimension(Rect(140, y + i * 24, 150, 12));
mAttributeSlider[i]->setActionEventId("statslider");
mAttributeSlider[i]->addActionListener(this);
add(mAttributeSlider[i]);
mAttributeValue[i] = new Label(this, toString(min));
mAttributeValue[i]->setPosition(295, y + i * 24);
add(mAttributeValue[i]);
}
updateSliders();
if (!available)
{
mAttributesLeft->setVisible(Visible_false);
h = y;
setContentSize(w, h);
}
if (haveCreateCharGender && y < 160)
{
h = 160;
setContentSize(w, h);
}
setButtonsPosition(w, h);
}
void CharCreateDialog::setDefaultGender(const GenderT gender)
{
mDefaultGender = gender;
mPlayer->setGender(gender);
}
void CharCreateDialog::updateHair()
{
if (mHairStyle <= 0)
mHairStyle = Being::getNumOfHairstyles() - 1;
else
mHairStyle %= Being::getNumOfHairstyles();
if (mHairStyle < static_cast<signed>(minHairStyle)
|| mHairStyle > static_cast<signed>(maxHairStyle))
{
mHairStyle = minHairStyle;
}
const ItemInfo &item = ItemDB::get(-mHairStyle);
mHairStyleNameLabel->setCaption(item.getName());
mHairStyleNameLabel->resizeTo(150, 150);
if (ColorDB::getHairSize())
mHairColor %= ColorDB::getHairSize();
else
mHairColor = 0;
if (mHairColor < 0)
mHairColor += ColorDB::getHairSize();
if (mHairColor < static_cast<signed>(minHairColor)
|| mHairColor > static_cast<signed>(maxHairColor))
{
mHairColor = minHairColor;
}
mHairColorNameLabel->setCaption(ColorDB::getHairColorName(mHairColor));
mHairColorNameLabel->resizeTo(150, 150);
mPlayer->setSprite(charServerHandler->hairSprite(),
mHairStyle * -1,
item.getDyeColorsString(mHairColor));
}
void CharCreateDialog::updateRace()
{
if (mRace < mMinRace)
mRace = mMaxRace;
else if (mRace > mMaxRace)
mRace = mMinRace;
updateLook();
}
void CharCreateDialog::updateLook()
{
const ItemInfo &item = ItemDB::get(-100 - mRace);
const int sz = item.getColorsSize();
if (sz > 0 && haveLookSelection)
{
if (mLook < 0)
mLook = sz - 1;
if (mLook > mMaxLook)
mLook = mMinLook;
if (mLook >= sz)
mLook = mMinLook;
}
else
{
mLook = 0;
}
mPlayer->setSubtype(mRace, static_cast<uint8_t>(mLook));
if (mRaceNameLabel)
{
mRaceNameLabel->setCaption(item.getName());
mRaceNameLabel->resizeTo(150, 150);
}
if (mLookNameLabel)
{
mLookNameLabel->setCaption(item.getColorName(mLook));
mLookNameLabel->resizeTo(150, 150);
}
}
void CharCreateDialog::logic()
{
BLOCK_START("CharCreateDialog::logic")
if (mPlayer)
mPlayer->logic();
BLOCK_END("CharCreateDialog::logic")
}
void CharCreateDialog::updatePlayer()
{
if (mPlayer)
{
mPlayer->setDirection(directions[mDirection]);
mPlayer->setAction(actions[mAction], 0);
}
}
void CharCreateDialog::keyPressed(KeyEvent &event)
{
const InputActionT actionId = event.getActionId();
switch (actionId)
{
case InputAction::GUI_CANCEL:
event.consume();
action(ActionEvent(mCancelButton,
mCancelButton->getActionEventId()));
break;
default:
break;
}
}
void CharCreateDialog::setButtonsPosition(const int w, const int h)
{
if (mainGraphics->getHeight() < 480)
{
mCreateButton->setPosition(340, 150);
mCancelButton->setPosition(340, 160 + mCreateButton->getHeight());
}
else
{
mCancelButton->setPosition(
w / 2,
h - 5 - mCancelButton->getHeight());
mCreateButton->setPosition(
mCancelButton->getX() - 5 - mCreateButton->getWidth(),
h - 5 - mCancelButton->getHeight());
}
mAttributesLeft->setPosition(15, 260 + 29);
}
|
gpl-2.0
|
Delta-SH/iPemCollector
|
iPem.Model/DbEntity.cs
|
1113
|
๏ปฟusing iPem.Core;
using System;
namespace iPem.Model {
/// <summary>
/// ๆฐๆฎๅบไฟกๆฏ
/// </summary>
public partial class DbEntity {
/// <summary>
/// ๅฏไธๆ ่ฏ
/// </summary>
public string Id { get; set; }
/// <summary>
/// ๅ็งฐ
/// </summary>
public string Name { get; set; }
/// <summary>
/// ๆฐๆฎๅบ็ฑปๅ
/// </summary>
public DatabaseType Type { get; set; }
/// <summary>
/// ๆๅกๅจๅฐๅ
/// </summary>
public string IP { get; set; }
/// <summary>
/// ๆฐๆฎๅบ็ซฏๅฃ
/// </summary>
public int Port { get; set; }
/// <summary>
/// ็ปๅฝ็จๆท
/// </summary>
public string Uid { get; set; }
/// <summary>
/// ็ปๅฝๅฏ็
/// </summary>
public string Password { get; set; }
/// <summary>
/// ๆฐๆฎๅบๅ็งฐ
/// </summary>
public string Db { get; set; }
}
}
|
gpl-2.0
|
jeromerobert/hmat-oss
|
src/json.cpp
|
5619
|
/*
HMat-OSS (HMatrix library, open source software)
Copyright (C) 2014-2017 Airbus SAS
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.
http://github.com/jeromerobert/hmat-oss
*/
#include "json.hpp"
#include "cluster_tree.hpp"
#include "h_matrix.hpp"
using namespace std;
namespace hmat {
void JSONDumper::dumpSubTree(int _depth) {
string prefix(" ");
for (int i = 0; i < _depth; i++) {
prefix += " ";
}
AxisAlignedBoundingBox rows_bbox(*rows_);
AxisAlignedBoundingBox cols_bbox(*cols_);
const int rows_dimension(rows_->coordinates()->dimension());
const int cols_dimension(cols_->coordinates()->dimension());
out_ << prefix << "{\"depth\": " << _depth << "," << endl
<< prefix << " \"rows\": "
<< "{\"offset\": " << rows_->offset() << ", \"n\": " << rows_->size() << ", "
<< "\"boundingBox\": [[" << rows_bbox.bbMin()[0];
for (int dim = 1; dim < rows_dimension; ++dim) {
out_ << ", " << rows_bbox.bbMin()[dim];
}
out_ << "], [" << rows_bbox.bbMax()[0];
for (int dim = 1; dim < rows_dimension; ++dim) {
out_ << ", " << rows_bbox.bbMax()[dim];
}
out_ << "]]}," << endl
<< prefix << " \"cols\": "
<< "{\"offset\": " << cols_->offset() << ", \"n\": " << cols_->size() << ", "
<< "\"boundingBox\": [[" << cols_bbox.bbMin()[0];
for (int dim = 1; dim < cols_dimension; ++dim) {
out_ << ", " << cols_bbox.bbMin()[dim];
}
out_ << "], [" << cols_bbox.bbMax()[0];
for (int dim = 1; dim < cols_dimension; ++dim) {
out_ << ", " << cols_bbox.bbMax()[dim];
}
out_ << "]]}";
const std::string extra_info = nodeInfo_.str();
if (!extra_info.empty()) {
out_ << "," << endl << prefix << extra_info;
}
if (nrChild_ > 0) {
out_ << "," << endl << prefix << " \"children\": [" << endl;
loopOnChildren(_depth);
out_ << endl << prefix << " ]";
}
out_ << "}";
}
void JSONDumper::nextChild(bool last) {
if(!last)
out_ << "," << endl;
nodeInfo_.str("");
}
static void
dump_points(std::ostream& out, const std::string name, const DofCoordinates* points) {
string delimiter;
const int dimension = points->dimension();
out << " \"" << name << "\": [" << endl;
delimiter = " ";
for (int i = 0; i < points->numberOfDof(); i++) {
out << delimiter << "[";
if (dimension > 0) {
out << points->spanCenter(i, 0);
for (int dim = 1; dim < dimension; ++dim) {
out << ", " << points->spanCenter(i, dim);
}
}
out << "]" << endl;
delimiter = " ,";
}
out << " ]," << endl;
}
static void
dump_mapping(std::ostream& out, const std::string name, int numberOfDof, const int* indices) {
// Mapping
string delimiter;
out << " \"" << name << "\": [" << endl
<< " ";
delimiter = "";
for (int i = 0; i < numberOfDof; i++) {
out << delimiter << indices[i];
delimiter = " ,";
}
out << "]," << endl;
}
void JSONDumper::dumpPoints() {
dump_points(out_, "points", rows_->coordinates());
dump_mapping(out_, "mapping", rows_->coordinates()->numberOfDof(), rows_->indices());
if (rows_ != cols_) {
dump_points(out_, "points_cols", cols_->coordinates());
dump_mapping(out_, "mapping_cols", cols_->coordinates()->numberOfDof(), cols_->indices());
}
}
void JSONDumper::dump() {
out_ << "{" << endl;
dumpMeta();
out_ << " \"tree\":" << endl;
dumpSubTree(0);
out_ << "}" << endl;
}
template<typename T> void HMatrixJSONDumper<T>::dumpMeta() {
dumpPoints();
}
template<typename T> void HMatrixJSONDumper<T>::update() {
rows_ = current_->rows();
cols_ = current_->cols();
nrChild_ = current_->nrChild();
if (current_->isFullMatrix()) {
nodeInfo_ << " \"leaf_type\": \"Full\"";
} else if (current_->isRkMatrix()) {
nodeInfo_ << " \"leaf_type\": \"Rk\", \"k\": " << current_->rank() << ",";
nodeInfo_ << " \"epsilon\": " << current_->lowRankEpsilon() << ",";
nodeInfo_ << " \"approxK\": " << current_->approximateRank();
}
}
template<typename T>
void HMatrixJSONDumper<T>::loopOnChildren(int depth) {
const HMatrix<T> * toLoopOn = current_;
int last = toLoopOn->nrChild() - 1;
while(last >= 0 && NULL == toLoopOn->getChild(last))
--last;
for (int i = 0; i <= last; i++) {
current_ = toLoopOn->getChild(i);
if(current_ != NULL) {
update();
dumpSubTree(depth + 1);
nextChild(i == last);
}
}
}
template<typename T>
HMatrixJSONDumper<T>::HMatrixJSONDumper(const HMatrix<T> * m, std::ostream & out)
: JSONDumper(out), current_(m) {
update();
}
template class HMatrixJSONDumper<S_t>;
template class HMatrixJSONDumper<D_t>;
template class HMatrixJSONDumper<C_t>;
template class HMatrixJSONDumper<Z_t>;
}
|
gpl-2.0
|
amberGit/justTest
|
mod.lua
|
19
|
a=-180
print(a%360)
|
gpl-2.0
|
Baahoot/wars
|
images.php
|
534
|
<?php session_start() ?>
<?php require 'connect.php' ?>
<body>
<div align="center "id="SubPage">Images</div>
<div align="Center" id="SettingsBlock">
<div id="SettingsName">Add Image: <span id="AddImage"></span></div>
<div align="left">
<span class="FormText">Image URL: </span>
<input type="text" value="<?php echo $image ?>" id="new_image" />
<input type="submit" value="Add" onClick="AddImage()" />
</div>
</div>
<div align="center" style="width: 600px;">
<div align="left" id="UserImages"><?php include 'image.php' ?></div>
</div>
|
gpl-2.0
|
Programming-Club/Learning-to-Mod
|
iceCraft/lib/config/ConfigHandler.java
|
2963
|
package iceCraft.lib.config;
import java.io.File;
import net.minecraftforge.common.Configuration;
public class ConfigHandler {
public static void init(File configFile) {
Configuration config = new Configuration(configFile);
// Categories
final String BOOLEANS = config.CATEGORY_GENERAL
+ config.CATEGORY_SPLITTER + "booleans";
final String FLUIDS = "liquids";
config.load();
// Items are shifted 256, so we subtract 256 to compensate
// Items
Ids.iceShard_actual = config.getItem(config.CATEGORY_ITEM,
Names.iceShard_name, Ids.iceShard_default).getInt() - 256;
Ids.icePick_actual = config.getItem(config.CATEGORY_ITEM,
Names.icePick_name, Ids.icePick_default).getInt() - 256;
Ids.mud_actual = config.getItem(config.CATEGORY_ITEM, Names.mud_name,
Ids.mud_default).getInt() - 256;
Ids.mudBrick_actual = config.getItem(config.CATEGORY_ITEM,
Names.mudBrick_name, Ids.mudBrick_actual).getInt() - 256;
Ids.bacon_actual = config.getItem(config.CATEGORY_ITEM,
Names.bacon_name, Ids.bacon_default).getInt() - 256;
Ids.rawBacon_actual = config.getItem(config.CATEGORY_ITEM,
Names.rawBacon_name, Ids.rawBacon_default).getInt() - 256;
// Ice tool set
Ids.iceSword_actual = config.getItem(config.CATEGORY_ITEM,
Names.iceSword_name, Ids.iceSword_default).getInt() - 256;
Ids.icePickaxe_actual = config.getItem(config.CATEGORY_ITEM,
Names.icePickaxe_name, Ids.icePickaxe_default).getInt() - 256;
Ids.iceAxe_actual = config.getItem(config.CATEGORY_ITEM,
Names.iceAxe_name, Ids.iceAxe_default).getInt() - 256;
Ids.iceSpade_actual = config.getItem(config.CATEGORY_ITEM,
Names.iceSpade_name, Ids.iceSpade_default).getInt() - 256;
Ids.iceHoe_actual = config.getItem(config.CATEGORY_ITEM,
Names.iceHoe_name, Ids.iceHoe_default).getInt() - 256;
// Blocks
Ids.wetIce_actual = config.getItem(config.CATEGORY_BLOCK,
Names.wetIce_name, Ids.wetIce_default).getInt() - 256;
Ids.mudBrickBlock_actual = config.getItem(config.CATEGORY_BLOCK,
Names.mudBrickBlock_name, Ids.mudBrickBlock_default).getInt() - 256;
Ids.refrigerator_actual = config.getItem(config.CATEGORY_BLOCK,
Names.refrigerator_name, Ids.refrigerator_default).getInt() - 256;
// Fluids
Ids.liquidIceBlock_actual = config.getItem(FLUIDS, Names.liquidIce_name,
Ids.liquidIceBlock_default).getInt() - 256;
Ids.liquidIceBucket_actual = config.getItem(FLUIDS,
Names.liquidIceBucket_name, Ids.liquidIceBucket_default)
.getInt() - 256;
// Booleans
ConfigBooleans.enableBurnables = config.get(BOOLEANS,
ConfigBooleans.enableBurnables_name,
ConfigBooleans.enableBurnables_default).getBoolean(
ConfigBooleans.enableBurnables_default);
ConfigBooleans.enableIceTools = config.get(BOOLEANS,
ConfigBooleans.enableIceTools_name,
ConfigBooleans.enableIceTools_default).getBoolean(
ConfigBooleans.enableIceTools_default);
// Save the config
config.save();
}
}
|
gpl-2.0
|
Ragebones/StormCore
|
src/server/game/DataStores/DB2Stores.cpp
|
88519
|
/*
* Copyright (C) 2014-2017 StormCore
*
* 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 "DB2Stores.h"
#include "Common.h"
#include "Containers.h"
#include "DatabaseEnv.h"
#include "DB2LoadInfo.h"
#include "Log.h"
#include "TransportMgr.h"
#include "World.h"
DB2Storage<AchievementEntry> sAchievementStore("Achievement.db2", AchievementLoadInfo::Instance());
DB2Storage<AnimKitEntry> sAnimKitStore("AnimKit.db2", AnimKitLoadInfo::Instance());
DB2Storage<AreaGroupMemberEntry> sAreaGroupMemberStore("AreaGroupMember.db2", AreaGroupMemberLoadInfo::Instance());
DB2Storage<AreaTableEntry> sAreaTableStore("AreaTable.db2", AreaTableLoadInfo::Instance());
DB2Storage<AreaTriggerEntry> sAreaTriggerStore("AreaTrigger.db2", AreaTriggerLoadInfo::Instance());
DB2Storage<ArmorLocationEntry> sArmorLocationStore("ArmorLocation.db2", ArmorLocationLoadInfo::Instance());
DB2Storage<ArtifactEntry> sArtifactStore("Artifact.db2", ArtifactLoadInfo::Instance());
DB2Storage<ArtifactAppearanceEntry> sArtifactAppearanceStore("ArtifactAppearance.db2", ArtifactAppearanceLoadInfo::Instance());
DB2Storage<ArtifactAppearanceSetEntry> sArtifactAppearanceSetStore("ArtifactAppearanceSet.db2", ArtifactAppearanceSetLoadInfo::Instance());
DB2Storage<ArtifactCategoryEntry> sArtifactCategoryStore("ArtifactCategory.db2", ArtifactCategoryLoadInfo::Instance());
DB2Storage<ArtifactPowerEntry> sArtifactPowerStore("ArtifactPower.db2", ArtifactPowerLoadInfo::Instance());
DB2Storage<ArtifactPowerLinkEntry> sArtifactPowerLinkStore("ArtifactPowerLink.db2", ArtifactPowerLinkLoadInfo::Instance());
DB2Storage<ArtifactPowerRankEntry> sArtifactPowerRankStore("ArtifactPowerRank.db2", ArtifactPowerRankLoadInfo::Instance());
DB2Storage<ArtifactQuestXPEntry> sArtifactQuestXPStore("ArtifactQuestXP.db2", ArtifactQuestXpLoadInfo::Instance());
DB2Storage<AuctionHouseEntry> sAuctionHouseStore("AuctionHouse.db2", AuctionHouseLoadInfo::Instance());
DB2Storage<BankBagSlotPricesEntry> sBankBagSlotPricesStore("BankBagSlotPrices.db2", BankBagSlotPricesLoadInfo::Instance());
DB2Storage<BannedAddOnsEntry> sBannedAddOnsStore("BannedAddOns.db2", BannedAddonsLoadInfo::Instance());
DB2Storage<BarberShopStyleEntry> sBarberShopStyleStore("BarberShopStyle.db2", BarberShopStyleLoadInfo::Instance());
DB2Storage<BattlePetBreedQualityEntry> sBattlePetBreedQualityStore("BattlePetBreedQuality.db2", BattlePetBreedQualityLoadInfo::Instance());
DB2Storage<BattlePetBreedStateEntry> sBattlePetBreedStateStore("BattlePetBreedState.db2", BattlePetBreedStateLoadInfo::Instance());
DB2Storage<BattlePetSpeciesEntry> sBattlePetSpeciesStore("BattlePetSpecies.db2", BattlePetSpeciesLoadInfo::Instance());
DB2Storage<BattlePetSpeciesStateEntry> sBattlePetSpeciesStateStore("BattlePetSpeciesState.db2", BattlePetSpeciesStateLoadInfo::Instance());
DB2Storage<BattlemasterListEntry> sBattlemasterListStore("BattlemasterList.db2", BattlemasterListLoadInfo::Instance());
DB2Storage<BroadcastTextEntry> sBroadcastTextStore("BroadcastText.db2", BroadcastTextLoadInfo::Instance());
DB2Storage<CharSectionsEntry> sCharSectionsStore("CharSections.db2", CharSectionsLoadInfo::Instance());
DB2Storage<CharStartOutfitEntry> sCharStartOutfitStore("CharStartOutfit.db2", CharStartOutfitLoadInfo::Instance());
DB2Storage<CharTitlesEntry> sCharTitlesStore("CharTitles.db2", CharTitlesLoadInfo::Instance());
DB2Storage<ChatChannelsEntry> sChatChannelsStore("ChatChannels.db2", ChatChannelsLoadInfo::Instance());
DB2Storage<ChrClassesEntry> sChrClassesStore("ChrClasses.db2", ChrClassesLoadInfo::Instance());
DB2Storage<ChrClassesXPowerTypesEntry> sChrClassesXPowerTypesStore("ChrClassesXPowerTypes.db2", ChrClassesXPowerTypesLoadInfo::Instance());
DB2Storage<ChrRacesEntry> sChrRacesStore("ChrRaces.db2", ChrRacesLoadInfo::Instance());
DB2Storage<ChrSpecializationEntry> sChrSpecializationStore("ChrSpecialization.db2", ChrSpecializationLoadInfo::Instance());
DB2Storage<CinematicSequencesEntry> sCinematicSequencesStore("CinematicSequences.db2", CinematicSequencesLoadInfo::Instance());
DB2Storage<CreatureDisplayInfoEntry> sCreatureDisplayInfoStore("CreatureDisplayInfo.db2", CreatureDisplayInfoLoadInfo::Instance());
DB2Storage<CreatureDisplayInfoExtraEntry> sCreatureDisplayInfoExtraStore("CreatureDisplayInfoExtra.db2", CreatureDisplayInfoExtraLoadInfo::Instance());
DB2Storage<CreatureFamilyEntry> sCreatureFamilyStore("CreatureFamily.db2", CreatureFamilyLoadInfo::Instance());
DB2Storage<CreatureModelDataEntry> sCreatureModelDataStore("CreatureModelData.db2", CreatureModelDataLoadInfo::Instance());
DB2Storage<CreatureTypeEntry> sCreatureTypeStore("CreatureType.db2", CreatureTypeLoadInfo::Instance());
DB2Storage<CriteriaEntry> sCriteriaStore("Criteria.db2", CriteriaLoadInfo::Instance());
DB2Storage<CriteriaTreeEntry> sCriteriaTreeStore("CriteriaTree.db2", CriteriaTreeLoadInfo::Instance());
DB2Storage<CurrencyTypesEntry> sCurrencyTypesStore("CurrencyTypes.db2", CurrencyTypesLoadInfo::Instance());
DB2Storage<CurveEntry> sCurveStore("Curve.db2", CurveLoadInfo::Instance());
DB2Storage<CurvePointEntry> sCurvePointStore("CurvePoint.db2", CurvePointLoadInfo::Instance());
DB2Storage<DestructibleModelDataEntry> sDestructibleModelDataStore("DestructibleModelData.db2", DestructibleModelDataLoadInfo::Instance());
DB2Storage<DifficultyEntry> sDifficultyStore("Difficulty.db2", DifficultyLoadInfo::Instance());
DB2Storage<DungeonEncounterEntry> sDungeonEncounterStore("DungeonEncounter.db2", DungeonEncounterLoadInfo::Instance());
DB2Storage<DurabilityCostsEntry> sDurabilityCostsStore("DurabilityCosts.db2", DurabilityCostsLoadInfo::Instance());
DB2Storage<DurabilityQualityEntry> sDurabilityQualityStore("DurabilityQuality.db2", DurabilityQualityLoadInfo::Instance());
DB2Storage<EmotesEntry> sEmotesStore("Emotes.db2", EmotesLoadInfo::Instance());
DB2Storage<EmotesTextEntry> sEmotesTextStore("EmotesText.db2", EmotesTextLoadInfo::Instance());
DB2Storage<EmotesTextSoundEntry> sEmotesTextSoundStore("EmotesTextSound.db2", EmotesTextSoundLoadInfo::Instance());
DB2Storage<FactionEntry> sFactionStore("Faction.db2", FactionLoadInfo::Instance());
DB2Storage<FactionTemplateEntry> sFactionTemplateStore("FactionTemplate.db2", FactionTemplateLoadInfo::Instance());
DB2Storage<GameObjectsEntry> sGameObjectsStore("GameObjects.db2", GameobjectsLoadInfo::Instance());
DB2Storage<GameObjectDisplayInfoEntry> sGameObjectDisplayInfoStore("GameObjectDisplayInfo.db2", GameobjectDisplayInfoLoadInfo::Instance());
DB2Storage<GarrAbilityEntry> sGarrAbilityStore("GarrAbility.db2", GarrAbilityLoadInfo::Instance());
DB2Storage<GarrBuildingEntry> sGarrBuildingStore("GarrBuilding.db2", GarrBuildingLoadInfo::Instance());
DB2Storage<GarrBuildingPlotInstEntry> sGarrBuildingPlotInstStore("GarrBuildingPlotInst.db2", GarrBuildingPlotInstLoadInfo::Instance());
DB2Storage<GarrClassSpecEntry> sGarrClassSpecStore("GarrClassSpec.db2", GarrClassSpecLoadInfo::Instance());
DB2Storage<GarrFollowerEntry> sGarrFollowerStore("GarrFollower.db2", GarrFollowerLoadInfo::Instance());
DB2Storage<GarrFollowerXAbilityEntry> sGarrFollowerXAbilityStore("GarrFollowerXAbility.db2", GarrFollowerXAbilityLoadInfo::Instance());
DB2Storage<GarrPlotBuildingEntry> sGarrPlotBuildingStore("GarrPlotBuilding.db2", GarrPlotBuildingLoadInfo::Instance());
DB2Storage<GarrPlotEntry> sGarrPlotStore("GarrPlot.db2", GarrPlotLoadInfo::Instance());
DB2Storage<GarrPlotInstanceEntry> sGarrPlotInstanceStore("GarrPlotInstance.db2", GarrPlotInstanceLoadInfo::Instance());
DB2Storage<GarrSiteLevelEntry> sGarrSiteLevelStore("GarrSiteLevel.db2", GarrSiteLevelLoadInfo::Instance());
DB2Storage<GarrSiteLevelPlotInstEntry> sGarrSiteLevelPlotInstStore("GarrSiteLevelPlotInst.db2", GarrSiteLevelPlotInstLoadInfo::Instance());
DB2Storage<GemPropertiesEntry> sGemPropertiesStore("GemProperties.db2", GemPropertiesLoadInfo::Instance());
DB2Storage<GlyphBindableSpellEntry> sGlyphBindableSpellStore("GlyphBindableSpell.db2", GlyphBindableSpellLoadInfo::Instance());
DB2Storage<GlyphPropertiesEntry> sGlyphPropertiesStore("GlyphProperties.db2", GlyphPropertiesLoadInfo::Instance());
DB2Storage<GlyphRequiredSpecEntry> sGlyphRequiredSpecStore("GlyphRequiredSpec.db2", GlyphRequiredSpecLoadInfo::Instance());
DB2Storage<GuildColorBackgroundEntry> sGuildColorBackgroundStore("GuildColorBackground.db2", GuildColorBackgroundLoadInfo::Instance());
DB2Storage<GuildColorBorderEntry> sGuildColorBorderStore("GuildColorBorder.db2", GuildColorBorderLoadInfo::Instance());
DB2Storage<GuildColorEmblemEntry> sGuildColorEmblemStore("GuildColorEmblem.db2", GuildColorEmblemLoadInfo::Instance());
DB2Storage<GuildPerkSpellsEntry> sGuildPerkSpellsStore("GuildPerkSpells.db2", GuildPerkSpellsLoadInfo::Instance());
DB2Storage<HeirloomEntry> sHeirloomStore("Heirloom.db2", HeirloomLoadInfo::Instance());
DB2Storage<HolidaysEntry> sHolidaysStore("Holidays.db2", HolidaysLoadInfo::Instance());
DB2Storage<ImportPriceArmorEntry> sImportPriceArmorStore("ImportPriceArmor.db2", ImportPriceArmorLoadInfo::Instance());
DB2Storage<ImportPriceQualityEntry> sImportPriceQualityStore("ImportPriceQuality.db2", ImportPriceQualityLoadInfo::Instance());
DB2Storage<ImportPriceShieldEntry> sImportPriceShieldStore("ImportPriceShield.db2", ImportPriceShieldLoadInfo::Instance());
DB2Storage<ImportPriceWeaponEntry> sImportPriceWeaponStore("ImportPriceWeapon.db2", ImportPriceWeaponLoadInfo::Instance());
DB2Storage<ItemAppearanceEntry> sItemAppearanceStore("ItemAppearance.db2", ItemAppearanceLoadInfo::Instance());
DB2Storage<ItemArmorQualityEntry> sItemArmorQualityStore("ItemArmorQuality.db2", ItemArmorQualityLoadInfo::Instance());
DB2Storage<ItemArmorShieldEntry> sItemArmorShieldStore("ItemArmorShield.db2", ItemArmorShieldLoadInfo::Instance());
DB2Storage<ItemArmorTotalEntry> sItemArmorTotalStore("ItemArmorTotal.db2", ItemArmorTotalLoadInfo::Instance());
DB2Storage<ItemBagFamilyEntry> sItemBagFamilyStore("ItemBagFamily.db2", ItemBagFamilyLoadInfo::Instance());
DB2Storage<ItemBonusEntry> sItemBonusStore("ItemBonus.db2", ItemBonusLoadInfo::Instance());
DB2Storage<ItemBonusListLevelDeltaEntry> sItemBonusListLevelDeltaStore("ItemBonusListLevelDelta.db2", ItemBonusListLevelDeltaLoadInfo::Instance());
DB2Storage<ItemBonusTreeNodeEntry> sItemBonusTreeNodeStore("ItemBonusTreeNode.db2", ItemBonusTreeNodeLoadInfo::Instance());
DB2Storage<ItemChildEquipmentEntry> sItemChildEquipmentStore("ItemChildEquipment.db2", ItemChildEquipmentLoadInfo::Instance());
DB2Storage<ItemClassEntry> sItemClassStore("ItemClass.db2", ItemClassLoadInfo::Instance());
DB2Storage<ItemCurrencyCostEntry> sItemCurrencyCostStore("ItemCurrencyCost.db2", ItemCurrencyCostLoadInfo::Instance());
DB2Storage<ItemDamageAmmoEntry> sItemDamageAmmoStore("ItemDamageAmmo.db2", ItemDamageAmmoLoadInfo::Instance());
DB2Storage<ItemDamageOneHandEntry> sItemDamageOneHandStore("ItemDamageOneHand.db2", ItemDamageOneHandLoadInfo::Instance());
DB2Storage<ItemDamageOneHandCasterEntry> sItemDamageOneHandCasterStore("ItemDamageOneHandCaster.db2", ItemDamageOneHandCasterLoadInfo::Instance());
DB2Storage<ItemDamageTwoHandEntry> sItemDamageTwoHandStore("ItemDamageTwoHand.db2", ItemDamageTwoHandLoadInfo::Instance());
DB2Storage<ItemDamageTwoHandCasterEntry> sItemDamageTwoHandCasterStore("ItemDamageTwoHandCaster.db2", ItemDamageTwoHandCasterLoadInfo::Instance());
DB2Storage<ItemDisenchantLootEntry> sItemDisenchantLootStore("ItemDisenchantLoot.db2", ItemDisenchantLootLoadInfo::Instance());
DB2Storage<ItemEffectEntry> sItemEffectStore("ItemEffect.db2", ItemEffectLoadInfo::Instance());
DB2Storage<ItemEntry> sItemStore("Item.db2", ItemLoadInfo::Instance());
DB2Storage<ItemExtendedCostEntry> sItemExtendedCostStore("ItemExtendedCost.db2", ItemExtendedCostLoadInfo::Instance());
DB2Storage<ItemLimitCategoryEntry> sItemLimitCategoryStore("ItemLimitCategory.db2", ItemLimitCategoryLoadInfo::Instance());
DB2Storage<ItemModifiedAppearanceEntry> sItemModifiedAppearanceStore("ItemModifiedAppearance.db2", ItemModifiedAppearanceLoadInfo::Instance());
DB2Storage<ItemPriceBaseEntry> sItemPriceBaseStore("ItemPriceBase.db2", ItemPriceBaseLoadInfo::Instance());
DB2Storage<ItemRandomPropertiesEntry> sItemRandomPropertiesStore("ItemRandomProperties.db2", ItemRandomPropertiesLoadInfo::Instance());
DB2Storage<ItemRandomSuffixEntry> sItemRandomSuffixStore("ItemRandomSuffix.db2", ItemRandomSuffixLoadInfo::Instance());
DB2Storage<ItemSearchNameEntry> sItemSearchNameStore("ItemSearchName.db2", ItemSearchNameLoadInfo::Instance());
DB2Storage<ItemSetEntry> sItemSetStore("ItemSet.db2", ItemSetLoadInfo::Instance());
DB2Storage<ItemSetSpellEntry> sItemSetSpellStore("ItemSetSpell.db2", ItemSetSpellLoadInfo::Instance());
DB2Storage<ItemSparseEntry> sItemSparseStore("Item-sparse.db2", ItemSparseLoadInfo::Instance());
DB2Storage<ItemSpecEntry> sItemSpecStore("ItemSpec.db2", ItemSpecLoadInfo::Instance());
DB2Storage<ItemSpecOverrideEntry> sItemSpecOverrideStore("ItemSpecOverride.db2", ItemSpecOverrideLoadInfo::Instance());
DB2Storage<ItemUpgradeEntry> sItemUpgradeStore("ItemUpgrade.db2", ItemUpgradeLoadInfo::Instance());
DB2Storage<ItemXBonusTreeEntry> sItemXBonusTreeStore("ItemXBonusTree.db2", ItemXBonusTreeLoadInfo::Instance());
DB2Storage<KeyChainEntry> sKeyChainStore("KeyChain.db2", KeyChainLoadInfo::Instance());
DB2Storage<LfgDungeonsEntry> sLfgDungeonsStore("LfgDungeons.db2", LfgDungeonsLoadInfo::Instance());
DB2Storage<LightEntry> sLightStore("Light.db2", LightLoadInfo::Instance());
DB2Storage<LiquidTypeEntry> sLiquidTypeStore("LiquidType.db2", LiquidTypeLoadInfo::Instance());
DB2Storage<LockEntry> sLockStore("Lock.db2", LockLoadInfo::Instance());
DB2Storage<MailTemplateEntry> sMailTemplateStore("MailTemplate.db2", MailTemplateLoadInfo::Instance());
DB2Storage<MapEntry> sMapStore("Map.db2", MapLoadInfo::Instance());
DB2Storage<MapDifficultyEntry> sMapDifficultyStore("MapDifficulty.db2", MapDifficultyLoadInfo::Instance());
DB2Storage<ModifierTreeEntry> sModifierTreeStore("ModifierTree.db2", ModifierTreeLoadInfo::Instance());
DB2Storage<MountCapabilityEntry> sMountCapabilityStore("MountCapability.db2", MountCapabilityLoadInfo::Instance());
DB2Storage<MountEntry> sMountStore("Mount.db2", MountLoadInfo::Instance());
DB2Storage<MountTypeXCapabilityEntry> sMountTypeXCapabilityStore("MountTypeXCapability.db2", MountTypeXCapabilityLoadInfo::Instance());
DB2Storage<MovieEntry> sMovieStore("Movie.db2", MovieLoadInfo::Instance());
DB2Storage<NameGenEntry> sNameGenStore("NameGen.db2", NameGenLoadInfo::Instance());
DB2Storage<NamesProfanityEntry> sNamesProfanityStore("NamesProfanity.db2", NamesProfanityLoadInfo::Instance());
DB2Storage<NamesReservedEntry> sNamesReservedStore("NamesReserved.db2", NamesReservedLoadInfo::Instance());
DB2Storage<NamesReservedLocaleEntry> sNamesReservedLocaleStore("NamesReservedLocale.db2", NamesReservedLocaleLoadInfo::Instance());
DB2Storage<OverrideSpellDataEntry> sOverrideSpellDataStore("OverrideSpellData.db2", OverrideSpellDataLoadInfo::Instance());
DB2Storage<PhaseEntry> sPhaseStore("Phase.db2", PhaseLoadInfo::Instance());
DB2Storage<PhaseXPhaseGroupEntry> sPhaseXPhaseGroupStore("PhaseXPhaseGroup.db2", PhaseXPhaseGroupLoadInfo::Instance());
DB2Storage<PlayerConditionEntry> sPlayerConditionStore("PlayerCondition.db2", PlayerConditionLoadInfo::Instance());
DB2Storage<PowerDisplayEntry> sPowerDisplayStore("PowerDisplay.db2", PowerDisplayLoadInfo::Instance());
DB2Storage<PowerTypeEntry> sPowerTypeStore("PowerType.db2", PowerTypeLoadInfo::Instance());
DB2Storage<PvpDifficultyEntry> sPvpDifficultyStore("PvpDifficulty.db2", PvpDifficultyLoadInfo::Instance());
DB2Storage<QuestFactionRewardEntry> sQuestFactionRewardStore("QuestFactionReward.db2", QuestFactionRewardLoadInfo::Instance());
DB2Storage<QuestMoneyRewardEntry> sQuestMoneyRewardStore("QuestMoneyReward.db2", QuestMoneyRewardLoadInfo::Instance());
DB2Storage<QuestPackageItemEntry> sQuestPackageItemStore("QuestPackageItem.db2", QuestPackageItemLoadInfo::Instance());
DB2Storage<QuestSortEntry> sQuestSortStore("QuestSort.db2", QuestSortLoadInfo::Instance());
DB2Storage<QuestV2Entry> sQuestV2Store("QuestV2.db2", QuestV2LoadInfo::Instance());
DB2Storage<QuestXPEntry> sQuestXPStore("QuestXP.db2", QuestXpLoadInfo::Instance());
DB2Storage<RandPropPointsEntry> sRandPropPointsStore("RandPropPoints.db2", RandPropPointsLoadInfo::Instance());
DB2Storage<RulesetItemUpgradeEntry> sRulesetItemUpgradeStore("RulesetItemUpgrade.db2", RulesetItemUpgradeLoadInfo::Instance());
DB2Storage<ScalingStatDistributionEntry> sScalingStatDistributionStore("ScalingStatDistribution.db2", ScalingStatDistributionLoadInfo::Instance());
DB2Storage<ScenarioEntry> sScenarioStore("Scenario.db2", ScenarioLoadInfo::Instance());
DB2Storage<ScenarioStepEntry> sScenarioStepStore("ScenarioStep.db2", ScenarioStepLoadInfo::Instance());
DB2Storage<SceneScriptEntry> sSceneScriptStore("SceneScript.db2", SceneScriptLoadInfo::Instance());
DB2Storage<SceneScriptPackageEntry> sSceneScriptPackageStore("SceneScriptPackage.db2", SceneScriptPackageLoadInfo::Instance());
DB2Storage<SkillLineEntry> sSkillLineStore("SkillLine.db2", SkillLineLoadInfo::Instance());
DB2Storage<SkillLineAbilityEntry> sSkillLineAbilityStore("SkillLineAbility.db2", SkillLineAbilityLoadInfo::Instance());
DB2Storage<SkillRaceClassInfoEntry> sSkillRaceClassInfoStore("SkillRaceClassInfo.db2", SkillRaceClassInfoLoadInfo::Instance());
DB2Storage<SoundKitEntry> sSoundKitStore("SoundKit.db2", SoundKitLoadInfo::Instance());
DB2Storage<SpecializationSpellsEntry> sSpecializationSpellsStore("SpecializationSpells.db2", SpecializationSpellsLoadInfo::Instance());
DB2Storage<SpellEntry> sSpellStore("Spell.db2", SpellLoadInfo::Instance());
DB2Storage<SpellAuraOptionsEntry> sSpellAuraOptionsStore("SpellAuraOptions.db2", SpellAuraOptionsLoadInfo::Instance());
DB2Storage<SpellAuraRestrictionsEntry> sSpellAuraRestrictionsStore("SpellAuraRestrictions.db2", SpellAuraRestrictionsLoadInfo::Instance());
DB2Storage<SpellCastTimesEntry> sSpellCastTimesStore("SpellCastTimes.db2", SpellCastTimesLoadInfo::Instance());
DB2Storage<SpellCastingRequirementsEntry> sSpellCastingRequirementsStore("SpellCastingRequirements.db2", SpellCastingRequirementsLoadInfo::Instance());
DB2Storage<SpellCategoriesEntry> sSpellCategoriesStore("SpellCategories.db2", SpellCategoriesLoadInfo::Instance());
DB2Storage<SpellCategoryEntry> sSpellCategoryStore("SpellCategory.db2", SpellCategoryLoadInfo::Instance());
DB2Storage<SpellClassOptionsEntry> sSpellClassOptionsStore("SpellClassOptions.db2", SpellClassOptionsLoadInfo::Instance());
DB2Storage<SpellCooldownsEntry> sSpellCooldownsStore("SpellCooldowns.db2", SpellCooldownsLoadInfo::Instance());
DB2Storage<SpellDurationEntry> sSpellDurationStore("SpellDuration.db2", SpellDurationLoadInfo::Instance());
DB2Storage<SpellEffectEntry> sSpellEffectStore("SpellEffect.db2", SpellEffectLoadInfo::Instance());
DB2Storage<SpellEffectScalingEntry> sSpellEffectScalingStore("SpellEffectScaling.db2", SpellEffectScalingLoadInfo::Instance());
DB2Storage<SpellEquippedItemsEntry> sSpellEquippedItemsStore("SpellEquippedItems.db2", SpellEquippedItemsLoadInfo::Instance());
DB2Storage<SpellFocusObjectEntry> sSpellFocusObjectStore("SpellFocusObject.db2", SpellFocusObjectLoadInfo::Instance());
DB2Storage<SpellInterruptsEntry> sSpellInterruptsStore("SpellInterrupts.db2", SpellInterruptsLoadInfo::Instance());
DB2Storage<SpellItemEnchantmentEntry> sSpellItemEnchantmentStore("SpellItemEnchantment.db2", SpellItemEnchantmentLoadInfo::Instance());
DB2Storage<SpellItemEnchantmentConditionEntry> sSpellItemEnchantmentConditionStore("SpellItemEnchantmentCondition.db2", SpellItemEnchantmentConditionLoadInfo::Instance());
DB2Storage<SpellLearnSpellEntry> sSpellLearnSpellStore("SpellLearnSpell.db2", SpellLearnSpellLoadInfo::Instance());
DB2Storage<SpellLevelsEntry> sSpellLevelsStore("SpellLevels.db2", SpellLevelsLoadInfo::Instance());
DB2Storage<SpellMiscEntry> sSpellMiscStore("SpellMisc.db2", SpellMiscLoadInfo::Instance());
DB2Storage<SpellPowerEntry> sSpellPowerStore("SpellPower.db2", SpellPowerLoadInfo::Instance());
DB2Storage<SpellPowerDifficultyEntry> sSpellPowerDifficultyStore("SpellPowerDifficulty.db2", SpellPowerDifficultyLoadInfo::Instance());
DB2Storage<SpellProcsPerMinuteEntry> sSpellProcsPerMinuteStore("SpellProcsPerMinute.db2", SpellProcsPerMinuteLoadInfo::Instance());
DB2Storage<SpellProcsPerMinuteModEntry> sSpellProcsPerMinuteModStore("SpellProcsPerMinuteMod.db2", SpellProcsPerMinuteModLoadInfo::Instance());
DB2Storage<SpellRadiusEntry> sSpellRadiusStore("SpellRadius.db2", SpellRadiusLoadInfo::Instance());
DB2Storage<SpellRangeEntry> sSpellRangeStore("SpellRange.db2", SpellRangeLoadInfo::Instance());
DB2Storage<SpellReagentsEntry> sSpellReagentsStore("SpellReagents.db2", SpellReagentsLoadInfo::Instance());
DB2Storage<SpellScalingEntry> sSpellScalingStore("SpellScaling.db2", SpellScalingLoadInfo::Instance());
DB2Storage<SpellShapeshiftEntry> sSpellShapeshiftStore("SpellShapeshift.db2", SpellShapeshiftLoadInfo::Instance());
DB2Storage<SpellShapeshiftFormEntry> sSpellShapeshiftFormStore("SpellShapeshiftForm.db2", SpellShapeshiftFormLoadInfo::Instance());
DB2Storage<SpellTargetRestrictionsEntry> sSpellTargetRestrictionsStore("SpellTargetRestrictions.db2", SpellTargetRestrictionsLoadInfo::Instance());
DB2Storage<SpellTotemsEntry> sSpellTotemsStore("SpellTotems.db2", SpellTotemsLoadInfo::Instance());
DB2Storage<SpellXSpellVisualEntry> sSpellXSpellVisualStore("SpellXSpellVisual.db2", SpellXSpellVisualLoadInfo::Instance());
DB2Storage<SummonPropertiesEntry> sSummonPropertiesStore("SummonProperties.db2", SummonPropertiesLoadInfo::Instance());
DB2Storage<TactKeyEntry> sTactKeyStore("TactKey.db2", TactKeyLoadInfo::Instance());
DB2Storage<TalentEntry> sTalentStore("Talent.db2", TalentLoadInfo::Instance());
DB2Storage<TaxiNodesEntry> sTaxiNodesStore("TaxiNodes.db2", TaxiNodesLoadInfo::Instance());
DB2Storage<TaxiPathEntry> sTaxiPathStore("TaxiPath.db2", TaxiPathLoadInfo::Instance());
DB2Storage<TaxiPathNodeEntry> sTaxiPathNodeStore("TaxiPathNode.db2", TaxiPathNodeLoadInfo::Instance());
DB2Storage<TotemCategoryEntry> sTotemCategoryStore("TotemCategory.db2", TotemCategoryLoadInfo::Instance());
DB2Storage<ToyEntry> sToyStore("Toy.db2", ToyLoadInfo::Instance());
DB2Storage<TransportAnimationEntry> sTransportAnimationStore("TransportAnimation.db2", TransportAnimationLoadInfo::Instance());
DB2Storage<TransportRotationEntry> sTransportRotationStore("TransportRotation.db2", TransportRotationLoadInfo::Instance());
DB2Storage<UnitPowerBarEntry> sUnitPowerBarStore("UnitPowerBar.db2", UnitPowerBarLoadInfo::Instance());
DB2Storage<VehicleEntry> sVehicleStore("Vehicle.db2", VehicleLoadInfo::Instance());
DB2Storage<VehicleSeatEntry> sVehicleSeatStore("VehicleSeat.db2", VehicleSeatLoadInfo::Instance());
DB2Storage<WMOAreaTableEntry> sWMOAreaTableStore("WMOAreaTable.db2", WmoAreaTableLoadInfo::Instance());
DB2Storage<WorldMapAreaEntry> sWorldMapAreaStore("WorldMapArea.db2", WorldMapAreaLoadInfo::Instance());
DB2Storage<WorldMapOverlayEntry> sWorldMapOverlayStore("WorldMapOverlay.db2", WorldMapOverlayLoadInfo::Instance());
DB2Storage<WorldMapTransformsEntry> sWorldMapTransformsStore("WorldMapTransforms.db2", WorldMapTransformsLoadInfo::Instance());
DB2Storage<WorldSafeLocsEntry> sWorldSafeLocsStore("WorldSafeLocs.db2", WorldSafeLocsLoadInfo::Instance());
TaxiMask sTaxiNodesMask;
TaxiMask sOldContinentsNodesMask;
TaxiMask sHordeTaxiNodesMask;
TaxiMask sAllianceTaxiNodesMask;
TaxiPathSetBySource sTaxiPathSetBySource;
TaxiPathNodesByPath sTaxiPathNodesByPath;
typedef std::vector<std::string> DB2StoreProblemList;
uint32 DB2FilesCount = 0;
template<class T, template<class> class DB2>
inline void LoadDB2(uint32& availableDb2Locales, DB2StoreProblemList& errlist, DB2Manager::StorageMap& stores, DB2StorageBase* storage, std::string const& db2Path, uint32 defaultLocale, DB2<T> const& /*hint*/)
{
// validate structure
DB2LoadInfo const* loadInfo = storage->GetLoadInfo();
{
std::string clientMetaString, ourMetaString;
for (std::size_t i = 0; i < loadInfo->Meta->FieldCount; ++i)
for (std::size_t j = 0; j < loadInfo->Meta->ArraySizes[i]; ++j)
clientMetaString += loadInfo->Meta->Types[i];
for (std::size_t i = loadInfo->Meta->HasIndexFieldInData() ? 0 : 1; i < loadInfo->FieldCount; ++i)
ourMetaString += char(std::tolower(loadInfo->Fields[i].Type));
ASSERT(clientMetaString == ourMetaString, "C++ structure fields %s do not match generated types from the client %s", ourMetaString.c_str(), clientMetaString.c_str());
// compatibility format and C++ structure sizes
ASSERT(loadInfo->Meta->GetRecordSize() == sizeof(T),
"Size of '%s' set by format string (%u) not equal size of C++ structure (" SZFMTD ").",
storage->GetFileName().c_str(), loadInfo->Meta->GetRecordSize(), sizeof(T));
}
++DB2FilesCount;
if (storage->Load(db2Path + localeNames[defaultLocale] + '/', defaultLocale))
{
storage->LoadFromDB();
// LoadFromDB() always loads strings into enUS locale, other locales are expected to have data in corresponding _locale tables
// so we need to make additional call to load that data in case said locale is set as default by worldserver.conf (and we do not want to load all this data from .db2 file again)
if (defaultLocale != LOCALE_enUS)
storage->LoadStringsFromDB(defaultLocale);
for (uint32 i = 0; i < TOTAL_LOCALES; ++i)
{
if (defaultLocale == i || i == LOCALE_none)
continue;
if (availableDb2Locales & (1 << i))
if (!storage->LoadStringsFrom((db2Path + localeNames[i] + '/'), i))
availableDb2Locales &= ~(1 << i); // mark as not available for speedup next checks
storage->LoadStringsFromDB(i);
}
}
else
{
// sort problematic db2 to (1) non compatible and (2) nonexistent
if (FILE* f = fopen((db2Path + localeNames[defaultLocale] + '/' + storage->GetFileName()).c_str(), "rb"))
{
std::ostringstream stream;
stream << storage->GetFileName() << " exists, and has " << storage->GetFieldCount() << " field(s) (expected " << loadInfo->Meta->FieldCount
<< "). Extracted file might be from wrong client version.";
std::string buf = stream.str();
errlist.push_back(buf);
fclose(f);
}
else
errlist.push_back(storage->GetFileName());
}
stores[storage->GetTableHash()] = storage;
}
DB2Manager& DB2Manager::Instance()
{
static DB2Manager instance;
return instance;
}
void DB2Manager::LoadStores(std::string const& dataPath, uint32 defaultLocale)
{
uint32 oldMSTime = getMSTime();
std::string db2Path = dataPath + "dbc/";
DB2StoreProblemList bad_db2_files;
uint32 availableDb2Locales = 0xFF;
#define LOAD_DB2(store) LoadDB2(availableDb2Locales, bad_db2_files, _stores, &store, db2Path, defaultLocale, store)
LOAD_DB2(sAchievementStore);
LOAD_DB2(sAnimKitStore);
LOAD_DB2(sAreaGroupMemberStore);
LOAD_DB2(sAreaTableStore);
LOAD_DB2(sAreaTriggerStore);
LOAD_DB2(sArmorLocationStore);
LOAD_DB2(sArtifactStore);
LOAD_DB2(sArtifactAppearanceStore);
LOAD_DB2(sArtifactAppearanceSetStore);
LOAD_DB2(sArtifactCategoryStore);
LOAD_DB2(sArtifactPowerStore);
LOAD_DB2(sArtifactPowerLinkStore);
LOAD_DB2(sArtifactPowerRankStore);
LOAD_DB2(sAuctionHouseStore);
LOAD_DB2(sBankBagSlotPricesStore);
LOAD_DB2(sBannedAddOnsStore);
LOAD_DB2(sBarberShopStyleStore);
LOAD_DB2(sBattlePetBreedQualityStore);
LOAD_DB2(sBattlePetBreedStateStore);
LOAD_DB2(sBattlePetSpeciesStore);
LOAD_DB2(sBattlePetSpeciesStateStore);
LOAD_DB2(sBattlemasterListStore);
LOAD_DB2(sBroadcastTextStore);
LOAD_DB2(sCharSectionsStore);
LOAD_DB2(sCharStartOutfitStore);
LOAD_DB2(sCharTitlesStore);
LOAD_DB2(sChatChannelsStore);
LOAD_DB2(sChrClassesStore);
LOAD_DB2(sChrClassesXPowerTypesStore);
LOAD_DB2(sChrRacesStore);
LOAD_DB2(sChrSpecializationStore);
LOAD_DB2(sCinematicSequencesStore);
LOAD_DB2(sCreatureDisplayInfoStore);
LOAD_DB2(sCreatureDisplayInfoExtraStore);
LOAD_DB2(sCreatureFamilyStore);
LOAD_DB2(sCreatureModelDataStore);
LOAD_DB2(sCreatureTypeStore);
LOAD_DB2(sCriteriaStore);
LOAD_DB2(sCriteriaTreeStore);
LOAD_DB2(sCurrencyTypesStore);
LOAD_DB2(sCurveStore);
LOAD_DB2(sCurvePointStore);
LOAD_DB2(sDestructibleModelDataStore);
LOAD_DB2(sDifficultyStore);
LOAD_DB2(sDungeonEncounterStore);
LOAD_DB2(sDurabilityCostsStore);
LOAD_DB2(sDurabilityQualityStore);
LOAD_DB2(sEmotesStore);
LOAD_DB2(sEmotesTextStore);
LOAD_DB2(sEmotesTextSoundStore);
LOAD_DB2(sFactionStore);
LOAD_DB2(sFactionTemplateStore);
LOAD_DB2(sGameObjectsStore);
LOAD_DB2(sGameObjectDisplayInfoStore);
LOAD_DB2(sGarrAbilityStore);
LOAD_DB2(sGarrBuildingStore);
LOAD_DB2(sGarrBuildingPlotInstStore);
LOAD_DB2(sGarrClassSpecStore);
LOAD_DB2(sGarrFollowerStore);
LOAD_DB2(sGarrFollowerXAbilityStore);
LOAD_DB2(sGarrPlotBuildingStore);
LOAD_DB2(sGarrPlotStore);
LOAD_DB2(sGarrPlotInstanceStore);
LOAD_DB2(sGarrSiteLevelStore);
LOAD_DB2(sGarrSiteLevelPlotInstStore);
LOAD_DB2(sGemPropertiesStore);
LOAD_DB2(sGlyphBindableSpellStore);
LOAD_DB2(sGlyphPropertiesStore);
LOAD_DB2(sGlyphRequiredSpecStore);
LOAD_DB2(sGuildColorBackgroundStore);
LOAD_DB2(sGuildColorBorderStore);
LOAD_DB2(sGuildColorEmblemStore);
LOAD_DB2(sGuildPerkSpellsStore);
LOAD_DB2(sHeirloomStore);
LOAD_DB2(sHolidaysStore);
LOAD_DB2(sImportPriceArmorStore);
LOAD_DB2(sImportPriceQualityStore);
LOAD_DB2(sImportPriceShieldStore);
LOAD_DB2(sImportPriceWeaponStore);
LOAD_DB2(sItemAppearanceStore);
LOAD_DB2(sItemArmorQualityStore);
LOAD_DB2(sItemArmorShieldStore);
LOAD_DB2(sItemArmorTotalStore);
LOAD_DB2(sItemBagFamilyStore);
LOAD_DB2(sItemBonusStore);
LOAD_DB2(sItemBonusListLevelDeltaStore);
LOAD_DB2(sItemBonusTreeNodeStore);
LOAD_DB2(sItemChildEquipmentStore);
LOAD_DB2(sItemClassStore);
LOAD_DB2(sItemCurrencyCostStore);
LOAD_DB2(sItemDamageAmmoStore);
LOAD_DB2(sItemDamageOneHandStore);
LOAD_DB2(sItemDamageOneHandCasterStore);
LOAD_DB2(sItemDamageTwoHandStore);
LOAD_DB2(sItemDamageTwoHandCasterStore);
LOAD_DB2(sItemDisenchantLootStore);
LOAD_DB2(sItemEffectStore);
LOAD_DB2(sItemStore);
LOAD_DB2(sItemExtendedCostStore);
LOAD_DB2(sItemLimitCategoryStore);
LOAD_DB2(sItemModifiedAppearanceStore);
LOAD_DB2(sItemPriceBaseStore);
LOAD_DB2(sItemRandomPropertiesStore);
LOAD_DB2(sItemRandomSuffixStore);
LOAD_DB2(sItemSearchNameStore);
LOAD_DB2(sItemSetStore);
LOAD_DB2(sItemSetSpellStore);
LOAD_DB2(sItemSparseStore);
LOAD_DB2(sItemSpecStore);
LOAD_DB2(sItemSpecOverrideStore);
LOAD_DB2(sItemUpgradeStore);
LOAD_DB2(sItemXBonusTreeStore);
LOAD_DB2(sKeyChainStore);
LOAD_DB2(sLfgDungeonsStore);
LOAD_DB2(sLightStore);
LOAD_DB2(sLiquidTypeStore);
LOAD_DB2(sLockStore);
LOAD_DB2(sMailTemplateStore);
LOAD_DB2(sMapStore);
LOAD_DB2(sMapDifficultyStore);
LOAD_DB2(sModifierTreeStore);
LOAD_DB2(sMountCapabilityStore);
LOAD_DB2(sMountStore);
LOAD_DB2(sMountTypeXCapabilityStore);
LOAD_DB2(sMovieStore);
LOAD_DB2(sNameGenStore);
LOAD_DB2(sNamesProfanityStore);
LOAD_DB2(sNamesReservedStore);
LOAD_DB2(sNamesReservedLocaleStore);
LOAD_DB2(sOverrideSpellDataStore);
LOAD_DB2(sPhaseStore);
LOAD_DB2(sPhaseXPhaseGroupStore);
LOAD_DB2(sPlayerConditionStore);
LOAD_DB2(sPowerDisplayStore);
LOAD_DB2(sPowerTypeStore);
LOAD_DB2(sPvpDifficultyStore);
LOAD_DB2(sQuestFactionRewardStore);
LOAD_DB2(sQuestMoneyRewardStore);
LOAD_DB2(sQuestPackageItemStore);
LOAD_DB2(sQuestSortStore);
LOAD_DB2(sQuestV2Store);
LOAD_DB2(sQuestXPStore);
LOAD_DB2(sRandPropPointsStore);
LOAD_DB2(sRulesetItemUpgradeStore);
LOAD_DB2(sScalingStatDistributionStore);
LOAD_DB2(sScenarioStore);
LOAD_DB2(sScenarioStepStore);
LOAD_DB2(sSceneScriptStore);
LOAD_DB2(sSceneScriptPackageStore);
LOAD_DB2(sSkillLineStore);
LOAD_DB2(sSkillLineAbilityStore);
LOAD_DB2(sSkillRaceClassInfoStore);
LOAD_DB2(sSoundKitStore);
LOAD_DB2(sSpecializationSpellsStore);
LOAD_DB2(sSpellStore);
LOAD_DB2(sSpellAuraOptionsStore);
LOAD_DB2(sSpellAuraRestrictionsStore);
LOAD_DB2(sSpellCastTimesStore);
LOAD_DB2(sSpellCastingRequirementsStore);
LOAD_DB2(sSpellCategoriesStore);
LOAD_DB2(sSpellCategoryStore);
LOAD_DB2(sSpellClassOptionsStore);
LOAD_DB2(sSpellCooldownsStore);
LOAD_DB2(sSpellDurationStore);
LOAD_DB2(sSpellEffectStore);
LOAD_DB2(sSpellEffectScalingStore);
LOAD_DB2(sSpellEquippedItemsStore);
LOAD_DB2(sSpellFocusObjectStore);
LOAD_DB2(sSpellInterruptsStore);
LOAD_DB2(sSpellItemEnchantmentStore);
LOAD_DB2(sSpellItemEnchantmentConditionStore);
LOAD_DB2(sSpellLearnSpellStore);
LOAD_DB2(sSpellLevelsStore);
LOAD_DB2(sSpellMiscStore);
LOAD_DB2(sSpellPowerStore);
LOAD_DB2(sSpellPowerDifficultyStore);
LOAD_DB2(sSpellProcsPerMinuteStore);
LOAD_DB2(sSpellProcsPerMinuteModStore);
LOAD_DB2(sSpellRadiusStore);
LOAD_DB2(sSpellRangeStore);
LOAD_DB2(sSpellReagentsStore);
LOAD_DB2(sSpellScalingStore);
LOAD_DB2(sSpellShapeshiftStore);
LOAD_DB2(sSpellShapeshiftFormStore);
LOAD_DB2(sSpellTargetRestrictionsStore);
LOAD_DB2(sSpellTotemsStore);
LOAD_DB2(sSpellXSpellVisualStore);
LOAD_DB2(sSummonPropertiesStore);
LOAD_DB2(sTactKeyStore);
LOAD_DB2(sTalentStore);
LOAD_DB2(sTaxiNodesStore);
LOAD_DB2(sTaxiPathStore);
LOAD_DB2(sTaxiPathNodeStore);
LOAD_DB2(sTotemCategoryStore);
LOAD_DB2(sToyStore);
LOAD_DB2(sTransportAnimationStore);
LOAD_DB2(sTransportRotationStore);
LOAD_DB2(sUnitPowerBarStore);
LOAD_DB2(sVehicleStore);
LOAD_DB2(sVehicleSeatStore);
LOAD_DB2(sWMOAreaTableStore);
LOAD_DB2(sWorldMapAreaStore);
LOAD_DB2(sWorldMapOverlayStore);
LOAD_DB2(sWorldMapTransformsStore);
LOAD_DB2(sWorldSafeLocsStore);
#undef LOAD_DB2
for (AreaGroupMemberEntry const* areaGroupMember : sAreaGroupMemberStore)
_areaGroupMembers[areaGroupMember->AreaGroupID].push_back(areaGroupMember->AreaID);
for (ArtifactPowerEntry const* artifactPower : sArtifactPowerStore)
_artifactPowers[artifactPower->ArtifactID].push_back(artifactPower);
for (ArtifactPowerLinkEntry const* artifactPowerLink : sArtifactPowerLinkStore)
{
_artifactPowerLinks[artifactPowerLink->FromArtifactPowerID].insert(artifactPowerLink->ToArtifactPowerID);
_artifactPowerLinks[artifactPowerLink->ToArtifactPowerID].insert(artifactPowerLink->FromArtifactPowerID);
}
for (ArtifactPowerRankEntry const* artifactPowerRank : sArtifactPowerRankStore)
_artifactPowerRanks[std::pair<uint32, uint8>{ artifactPowerRank->ArtifactPowerID, artifactPowerRank->Rank }] = artifactPowerRank;
ASSERT(BATTLE_PET_SPECIES_MAX_ID >= sBattlePetSpeciesStore.GetNumRows(),
"BATTLE_PET_SPECIES_MAX_ID (%d) must be equal to or greater than %u", BATTLE_PET_SPECIES_MAX_ID, sBattlePetSpeciesStore.GetNumRows());
std::unordered_map<uint32, std::set<std::pair<uint8, uint8>>> addedSections;
for (CharSectionsEntry const* charSection : sCharSectionsStore)
{
if (!charSection->Race || !((1 << (charSection->Race - 1)) & RACEMASK_ALL_PLAYABLE)) //ignore Nonplayable races
continue;
// Not all sections are used for low-res models but we need to get all sections for validation since its viewer dependent
uint8 baseSection = charSection->GenType;
switch (baseSection)
{
case SECTION_TYPE_SKIN_LOW_RES:
case SECTION_TYPE_FACE_LOW_RES:
case SECTION_TYPE_FACIAL_HAIR_LOW_RES:
case SECTION_TYPE_HAIR_LOW_RES:
case SECTION_TYPE_UNDERWEAR_LOW_RES:
baseSection = baseSection + SECTION_TYPE_SKIN;
break;
case SECTION_TYPE_SKIN:
case SECTION_TYPE_FACE:
case SECTION_TYPE_FACIAL_HAIR:
case SECTION_TYPE_HAIR:
case SECTION_TYPE_UNDERWEAR:
break;
case SECTION_TYPE_CUSTOM_DISPLAY_1_LOW_RES:
case SECTION_TYPE_CUSTOM_DISPLAY_2_LOW_RES:
case SECTION_TYPE_CUSTOM_DISPLAY_3_LOW_RES:
++baseSection;
break;
case SECTION_TYPE_CUSTOM_DISPLAY_1:
case SECTION_TYPE_CUSTOM_DISPLAY_2:
case SECTION_TYPE_CUSTOM_DISPLAY_3:
break;
default:
break;
}
uint32 sectionKey = baseSection | (charSection->Gender << 8) | (charSection->Race << 16);
std::pair<uint8, uint8> sectionCombination{ charSection->Type, charSection->Color };
if (addedSections[sectionKey].count(sectionCombination))
continue;
addedSections[sectionKey].insert(sectionCombination);
_charSections.insert({ sectionKey, charSection });
}
for (CharStartOutfitEntry const* outfit : sCharStartOutfitStore)
_charStartOutfits[outfit->RaceID | (outfit->ClassID << 8) | (outfit->GenderID << 16)] = outfit;
{
std::set<ChrClassesXPowerTypesEntry const*, ChrClassesXPowerTypesEntryComparator> powers;
for (ChrClassesXPowerTypesEntry const* power : sChrClassesXPowerTypesStore)
powers.insert(power);
for (uint32 i = 0; i < MAX_CLASSES; ++i)
for (uint32 j = 0; j < MAX_POWERS; ++j)
_powersByClass[i][j] = MAX_POWERS;
for (ChrClassesXPowerTypesEntry const* power : powers)
{
uint32 index = 0;
for (uint32 j = 0; j < MAX_POWERS; ++j)
if (_powersByClass[power->ClassID][j] != MAX_POWERS)
++index;
ASSERT(power->PowerType < MAX_POWERS);
_powersByClass[power->ClassID][power->PowerType] = index;
}
}
memset(_chrSpecializationsByIndex, 0, sizeof(_chrSpecializationsByIndex));
for (ChrSpecializationEntry const* chrSpec : sChrSpecializationStore)
{
ASSERT(chrSpec->ClassID < MAX_CLASSES);
ASSERT(chrSpec->OrderIndex < MAX_SPECIALIZATIONS);
uint32 storageIndex = chrSpec->ClassID;
if (chrSpec->Flags & CHR_SPECIALIZATION_FLAG_PET_OVERRIDE_SPEC)
{
ASSERT(!chrSpec->ClassID);
storageIndex = PET_SPEC_OVERRIDE_CLASS_INDEX;
}
_chrSpecializationsByIndex[storageIndex][chrSpec->OrderIndex] = chrSpec;
if (chrSpec->Flags & CHR_SPECIALIZATION_FLAG_RECOMMENDED)
_defaultChrSpecializationsByClass[chrSpec->ClassID] = chrSpec;
}
for (CurvePointEntry const* curvePoint : sCurvePointStore)
if (sCurveStore.LookupEntry(curvePoint->CurveID))
_curvePoints[curvePoint->CurveID].push_back(curvePoint);
for (auto itr = _curvePoints.begin(); itr != _curvePoints.end(); ++itr)
std::sort(itr->second.begin(), itr->second.end(), [](CurvePointEntry const* point1, CurvePointEntry const* point2) { return point1->Index < point2->Index; });
ASSERT(MAX_DIFFICULTY >= sDifficultyStore.GetNumRows(),
"MAX_DIFFICULTY is not large enough to contain all difficulties! (current value %d, required %d)",
MAX_DIFFICULTY, sDifficultyStore.GetNumRows());
for (EmotesTextSoundEntry const* emoteTextSound : sEmotesTextSoundStore)
_emoteTextSounds[EmotesTextSoundContainer::key_type(emoteTextSound->EmotesTextId, emoteTextSound->RaceId, emoteTextSound->SexId, emoteTextSound->ClassId)] = emoteTextSound;
for (FactionEntry const* faction : sFactionStore)
if (faction->ParentFactionID)
_factionTeams[faction->ParentFactionID].push_back(faction->ID);
for (GameObjectDisplayInfoEntry const* gameObjectDisplayInfo : sGameObjectDisplayInfoStore)
{
if (gameObjectDisplayInfo->GeoBoxMax.X < gameObjectDisplayInfo->GeoBoxMin.X)
std::swap(*(float*)(&gameObjectDisplayInfo->GeoBoxMax.X), *(float*)(&gameObjectDisplayInfo->GeoBoxMin.X));
if (gameObjectDisplayInfo->GeoBoxMax.Y < gameObjectDisplayInfo->GeoBoxMin.Y)
std::swap(*(float*)(&gameObjectDisplayInfo->GeoBoxMax.Y), *(float*)(&gameObjectDisplayInfo->GeoBoxMin.Y));
if (gameObjectDisplayInfo->GeoBoxMax.Z < gameObjectDisplayInfo->GeoBoxMin.Z)
std::swap(*(float*)(&gameObjectDisplayInfo->GeoBoxMax.Z), *(float*)(&gameObjectDisplayInfo->GeoBoxMin.Z));
}
for (HeirloomEntry const* heirloom : sHeirloomStore)
_heirlooms[heirloom->ItemID] = heirloom;
for (GlyphBindableSpellEntry const* glyphBindableSpell : sGlyphBindableSpellStore)
_glyphBindableSpells[glyphBindableSpell->GlyphPropertiesID].push_back(glyphBindableSpell->SpellID);
for (GlyphRequiredSpecEntry const* glyphRequiredSpec : sGlyphRequiredSpecStore)
_glyphRequiredSpecs[glyphRequiredSpec->GlyphPropertiesID].push_back(glyphRequiredSpec->ChrSpecializationID);
for (ItemBonusEntry const* bonus : sItemBonusStore)
_itemBonusLists[bonus->BonusListID].push_back(bonus);
for (ItemBonusListLevelDeltaEntry const* itemBonusListLevelDelta : sItemBonusListLevelDeltaStore)
_itemLevelDeltaToBonusListContainer[itemBonusListLevelDelta->Delta] = itemBonusListLevelDelta->ID;
for (ItemBonusTreeNodeEntry const* bonusTreeNode : sItemBonusTreeNodeStore)
{
uint32 bonusTreeId = bonusTreeNode->BonusTreeID;
while (bonusTreeNode)
{
_itemBonusTrees[bonusTreeId].insert(bonusTreeNode);
bonusTreeNode = sItemBonusTreeNodeStore.LookupEntry(bonusTreeNode->SubTreeID);
}
}
for (ItemChildEquipmentEntry const* itemChildEquipment : sItemChildEquipmentStore)
{
ASSERT(_itemChildEquipment.find(itemChildEquipment->ItemID) == _itemChildEquipment.end(), "Item must have max 1 child item.");
_itemChildEquipment[itemChildEquipment->ItemID] = itemChildEquipment;
}
for (ItemClassEntry const* itemClass : sItemClassStore)
{
ASSERT(itemClass->OldEnumValue < _itemClassByOldEnum.size());
ASSERT(!_itemClassByOldEnum[itemClass->OldEnumValue]);
_itemClassByOldEnum[itemClass->OldEnumValue] = itemClass;
}
for (ItemCurrencyCostEntry const* itemCurrencyCost : sItemCurrencyCostStore)
_itemsWithCurrencyCost.insert(itemCurrencyCost->ItemId);
for (ItemModifiedAppearanceEntry const* appearanceMod : sItemModifiedAppearanceStore)
{
ASSERT(appearanceMod->ItemID <= 0xFFFFFF);
_itemModifiedAppearancesByItem[appearanceMod->ItemID | (appearanceMod->AppearanceModID << 24)] = appearanceMod;
auto defaultAppearance = _itemDefaultAppearancesByItem.find(appearanceMod->ItemID);
if (defaultAppearance == _itemDefaultAppearancesByItem.end() || defaultAppearance->second->Index > appearanceMod->Index)
_itemDefaultAppearancesByItem[appearanceMod->ItemID] = appearanceMod;
}
for (ItemSetSpellEntry const* itemSetSpell : sItemSetSpellStore)
_itemSetSpells[itemSetSpell->ItemSetID].push_back(itemSetSpell);
for (ItemSpecOverrideEntry const* itemSpecOverride : sItemSpecOverrideStore)
_itemSpecOverrides[itemSpecOverride->ItemID].push_back(itemSpecOverride);
for (ItemXBonusTreeEntry const* itemBonusTreeAssignment : sItemXBonusTreeStore)
_itemToBonusTree.insert({ itemBonusTreeAssignment->ItemID, itemBonusTreeAssignment->BonusTreeID });
for (MapDifficultyEntry const* entry : sMapDifficultyStore)
_mapDifficulties[entry->MapID][entry->DifficultyID] = entry;
_mapDifficulties[0][0] = _mapDifficulties[1][0]; // map 0 is missing from MapDifficulty.dbc so we cheat a bit
for (MountEntry const* mount : sMountStore)
_mountsBySpellId[mount->SpellId] = mount;
for (MountTypeXCapabilityEntry const* mountTypeCapability : sMountTypeXCapabilityStore)
_mountCapabilitiesByType[mountTypeCapability->MountTypeID].insert(mountTypeCapability);
for (NameGenEntry const* nameGen : sNameGenStore)
_nameGenData[nameGen->Race][nameGen->Sex].push_back(nameGen);
for (NamesProfanityEntry const* namesProfanity : sNamesProfanityStore)
{
ASSERT(namesProfanity->Language < TOTAL_LOCALES || namesProfanity->Language == -1);
std::wstring name;
ASSERT(Utf8toWStr(namesProfanity->Name, name));
if (namesProfanity->Language != -1)
_nameValidators[namesProfanity->Language].emplace_back(name, Trinity::regex::icase | Trinity::regex::optimize);
else
{
for (uint32 i = 0; i < TOTAL_LOCALES; ++i)
{
if (i == LOCALE_none)
continue;
_nameValidators[i].emplace_back(name, Trinity::regex::icase | Trinity::regex::optimize);
}
}
}
for (NamesReservedEntry const* namesReserved : sNamesReservedStore)
{
std::wstring name;
ASSERT(Utf8toWStr(namesReserved->Name, name));
_nameValidators[TOTAL_LOCALES].emplace_back(name, Trinity::regex::icase | Trinity::regex::optimize);
}
for (NamesReservedLocaleEntry const* namesReserved : sNamesReservedLocaleStore)
{
ASSERT(!(namesReserved->LocaleMask & ~((1 << TOTAL_LOCALES) - 1)));
std::wstring name;
ASSERT(Utf8toWStr(namesReserved->Name, name));
for (uint32 i = 0; i < TOTAL_LOCALES; ++i)
{
if (i == LOCALE_none)
continue;
if (namesReserved->LocaleMask & (1 << i))
_nameValidators[i].emplace_back(name, Trinity::regex::icase | Trinity::regex::optimize);
}
}
for (PhaseXPhaseGroupEntry const* group : sPhaseXPhaseGroupStore)
if (PhaseEntry const* phase = sPhaseStore.LookupEntry(group->PhaseID))
_phasesByGroup[group->PhaseGroupID].insert(phase->ID);
for (PowerTypeEntry const* powerType : sPowerTypeStore)
{
ASSERT(powerType->PowerTypeEnum < MAX_POWERS);
ASSERT(!_powerTypes[powerType->PowerTypeEnum]);
_powerTypes[powerType->PowerTypeEnum] = powerType;
}
for (PvpDifficultyEntry const* entry : sPvpDifficultyStore)
{
ASSERT(entry->BracketID < MAX_BATTLEGROUND_BRACKETS, "PvpDifficulty bracket (%d) exceeded max allowed value (%d)", entry->BracketID, MAX_BATTLEGROUND_BRACKETS);
}
for (QuestPackageItemEntry const* questPackageItem : sQuestPackageItemStore)
{
if (questPackageItem->FilterType != QUEST_PACKAGE_FILTER_UNMATCHED)
_questPackages[questPackageItem->QuestPackageID].first.push_back(questPackageItem);
else
_questPackages[questPackageItem->QuestPackageID].second.push_back(questPackageItem);
}
for (RulesetItemUpgradeEntry const* rulesetItemUpgrade : sRulesetItemUpgradeStore)
_rulesetItemUpgrade[rulesetItemUpgrade->ItemID] = rulesetItemUpgrade->ItemUpgradeID;
for (SkillRaceClassInfoEntry const* entry : sSkillRaceClassInfoStore)
if (sSkillLineStore.LookupEntry(entry->SkillID))
_skillRaceClassInfoBySkill.insert(SkillRaceClassInfoContainer::value_type(entry->SkillID, entry));
for (SpecializationSpellsEntry const* specSpells : sSpecializationSpellsStore)
_specializationSpellsBySpec[specSpells->SpecID].push_back(specSpells);
for (SpellPowerEntry const* power : sSpellPowerStore)
{
if (SpellPowerDifficultyEntry const* powerDifficulty = sSpellPowerDifficultyStore.LookupEntry(power->ID))
{
std::vector<SpellPowerEntry const*>& powers = _spellPowerDifficulties[power->SpellID][powerDifficulty->DifficultyID];
if (powers.size() <= powerDifficulty->PowerIndex)
powers.resize(powerDifficulty->PowerIndex + 1);
powers[powerDifficulty->PowerIndex] = power;
}
else
{
std::vector<SpellPowerEntry const*>& powers = _spellPowers[power->SpellID];
if (powers.size() <= power->PowerIndex)
powers.resize(power->PowerIndex + 1);
powers[power->PowerIndex] = power;
}
}
for (SpellProcsPerMinuteModEntry const* ppmMod : sSpellProcsPerMinuteModStore)
_spellProcsPerMinuteMods[ppmMod->SpellProcsPerMinuteID].push_back(ppmMod);
for (TalentEntry const* talentInfo : sTalentStore)
{
ASSERT(talentInfo->ClassID < MAX_CLASSES);
ASSERT(talentInfo->TierID < MAX_TALENT_TIERS, "MAX_TALENT_TIERS must be at least %u", talentInfo->TierID);
ASSERT(talentInfo->ColumnIndex < MAX_TALENT_COLUMNS, "MAX_TALENT_COLUMNS must be at least %u", talentInfo->ColumnIndex);
_talentsByPosition[talentInfo->ClassID][talentInfo->TierID][talentInfo->ColumnIndex].push_back(talentInfo);
}
for (TaxiPathEntry const* entry : sTaxiPathStore)
sTaxiPathSetBySource[entry->From][entry->To] = TaxiPathBySourceAndDestination(entry->ID, entry->Cost);
uint32 pathCount = sTaxiPathStore.GetNumRows();
// Calculate path nodes count
std::vector<uint32> pathLength;
pathLength.resize(pathCount); // 0 and some other indexes not used
for (TaxiPathNodeEntry const* entry : sTaxiPathNodeStore)
if (pathLength[entry->PathID] < entry->NodeIndex + 1u)
pathLength[entry->PathID] = entry->NodeIndex + 1u;
// Set path length
sTaxiPathNodesByPath.resize(pathCount); // 0 and some other indexes not used
for (uint32 i = 0; i < sTaxiPathNodesByPath.size(); ++i)
sTaxiPathNodesByPath[i].resize(pathLength[i]);
// fill data
for (TaxiPathNodeEntry const* entry : sTaxiPathNodeStore)
sTaxiPathNodesByPath[entry->PathID][entry->NodeIndex] = entry;
// Initialize global taxinodes mask
// include existed nodes that have at least single not spell base (scripted) path
{
if (sTaxiNodesStore.GetNumRows())
{
ASSERT(TaxiMaskSize >= ((sTaxiNodesStore.GetNumRows() - 1) / 8) + 1,
"TaxiMaskSize is not large enough to contain all taxi nodes! (current value %d, required %d)",
TaxiMaskSize, (((sTaxiNodesStore.GetNumRows() - 1) / 8) + 1));
}
sTaxiNodesMask.fill(0);
sOldContinentsNodesMask.fill(0);
sHordeTaxiNodesMask.fill(0);
sAllianceTaxiNodesMask.fill(0);
for (TaxiNodesEntry const* node : sTaxiNodesStore)
{
if (!(node->Flags & (TAXI_NODE_FLAG_ALLIANCE | TAXI_NODE_FLAG_HORDE)))
continue;
// valid taxi network node
uint8 field = (uint8)((node->ID - 1) / 8);
uint32 submask = 1 << ((node->ID - 1) % 8);
sTaxiNodesMask[field] |= submask;
if (node->Flags & TAXI_NODE_FLAG_HORDE)
sHordeTaxiNodesMask[field] |= submask;
if (node->Flags & TAXI_NODE_FLAG_ALLIANCE)
sAllianceTaxiNodesMask[field] |= submask;
uint32 nodeMap;
DeterminaAlternateMapPosition(node->MapID, node->Pos.X, node->Pos.Y, node->Pos.Z, &nodeMap);
if (nodeMap < 2)
sOldContinentsNodesMask[field] |= submask;
}
}
for (TransportAnimationEntry const* anim : sTransportAnimationStore)
sTransportMgr->AddPathNodeToTransport(anim->TransportID, anim->TimeIndex, anim);
for (TransportRotationEntry const* rot : sTransportRotationStore)
sTransportMgr->AddPathRotationToTransport(rot->TransportID, rot->TimeIndex, rot);
for (ToyEntry const* toy : sToyStore)
_toys.insert(toy->ItemID);
for (WMOAreaTableEntry const* entry : sWMOAreaTableStore)
_wmoAreaTableLookup[WMOAreaTableKey(entry->WMOID, entry->NameSet, entry->WMOGroupID)] = entry;
for (WorldMapAreaEntry const* worldMapArea : sWorldMapAreaStore)
_worldMapAreaByAreaID[worldMapArea->AreaID] = worldMapArea;
// error checks
if (bad_db2_files.size() >= DB2FilesCount)
{
TC_LOG_ERROR("misc", "\nIncorrect DataDir value in worldserver.conf or ALL required *.db2 files (%d) not found by path: %sdbc/%s/", DB2FilesCount, dataPath.c_str(), localeNames[defaultLocale]);
exit(1);
}
else if (!bad_db2_files.empty())
{
std::string str;
for (auto i = bad_db2_files.begin(); i != bad_db2_files.end(); ++i)
str += *i + "\n";
TC_LOG_ERROR("misc", "\nSome required *.db2 files (%u from %d) not found or not compatible:\n%s", (uint32)bad_db2_files.size(), DB2FilesCount, str.c_str());
exit(1);
}
// Check loaded DB2 files proper version
if (!sAreaTableStore.LookupEntry(8485) || // last area (areaflag) added in 7.0.3 (22594)
!sCharTitlesStore.LookupEntry(486) || // last char title added in 7.0.3 (22594)
!sGemPropertiesStore.LookupEntry(3363) || // last gem property added in 7.0.3 (22594)
!sItemStore.LookupEntry(142526) || // last item added in 7.0.3 (22594)
!sItemExtendedCostStore.LookupEntry(6125) || // last item extended cost added in 7.0.3 (22594)
!sMapStore.LookupEntry(1670) || // last map added in 7.0.3 (22594)
!sSpellStore.LookupEntry(231371)) // last spell added in 7.0.3 (22594)
{
TC_LOG_ERROR("misc", "You have _outdated_ DB2 files. Please extract correct versions from current using client.");
exit(1);
}
TC_LOG_INFO("server.loading", ">> Initialized %d DB2 data stores in %u ms", DB2FilesCount, GetMSTimeDiffToNow(oldMSTime));
}
DB2StorageBase const* DB2Manager::GetStorage(uint32 type) const
{
StorageMap::const_iterator itr = _stores.find(type);
if (itr != _stores.end())
return itr->second;
return nullptr;
}
void DB2Manager::LoadHotfixData()
{
uint32 oldMSTime = getMSTime();
QueryResult result = HotfixDatabase.Query("SELECT TableHash, RecordID, `Timestamp`, Deleted FROM hotfix_data");
if (!result)
{
TC_LOG_INFO("misc", ">> Loaded 0 hotfix info entries.");
return;
}
uint32 count = 0;
_hotfixData.reserve(result->GetRowCount());
do
{
Field* fields = result->Fetch();
HotfixNotify info;
info.TableHash = fields[0].GetUInt32();
info.Entry = fields[1].GetUInt32();
info.Timestamp = fields[2].GetUInt32();
_hotfixData.push_back(info);
if (fields[3].GetBool())
{
auto itr = _stores.find(info.TableHash);
if (itr != _stores.end())
itr->second->EraseRecord(info.Entry);
}
++count;
} while (result->NextRow());
TC_LOG_INFO("misc", ">> Loaded %u hotfix info entries in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
time_t DB2Manager::GetHotfixDate(uint32 entry, uint32 type) const
{
time_t ret = 0;
for (HotfixNotify const& hotfix : _hotfixData)
if (hotfix.Entry == entry && hotfix.TableHash == type)
if (time_t(hotfix.Timestamp) > ret)
ret = time_t(hotfix.Timestamp);
return ret ? ret : time(NULL);
}
std::vector<uint32> DB2Manager::GetAreasForGroup(uint32 areaGroupId) const
{
auto itr = _areaGroupMembers.find(areaGroupId);
if (itr != _areaGroupMembers.end())
return itr->second;
return std::vector<uint32>();
}
std::vector<ArtifactPowerEntry const*> DB2Manager::GetArtifactPowers(uint8 artifactId) const
{
auto itr = _artifactPowers.find(artifactId);
if (itr != _artifactPowers.end())
return itr->second;
return std::vector<ArtifactPowerEntry const*>{};
}
std::unordered_set<uint32> const* DB2Manager::GetArtifactPowerLinks(uint32 artifactPowerId) const
{
auto itr = _artifactPowerLinks.find(artifactPowerId);
if (itr != _artifactPowerLinks.end())
return &itr->second;
return nullptr;
}
ArtifactPowerRankEntry const* DB2Manager::GetArtifactPowerRank(uint32 artifactPowerId, uint8 rank) const
{
auto itr = _artifactPowerRanks.find({ artifactPowerId, rank });
if (itr != _artifactPowerRanks.end())
return itr->second;
return nullptr;
}
char const* DB2Manager::GetBroadcastTextValue(BroadcastTextEntry const* broadcastText, LocaleConstant locale /*= DEFAULT_LOCALE*/, uint8 gender /*= GENDER_MALE*/, bool forceGender /*= false*/)
{
if (gender == GENDER_FEMALE && (forceGender || broadcastText->FemaleText->Str[DEFAULT_LOCALE][0] != '\0'))
{
if (broadcastText->FemaleText->Str[locale][0] != '\0')
return broadcastText->FemaleText->Str[locale];
return broadcastText->FemaleText->Str[DEFAULT_LOCALE];
}
if (broadcastText->MaleText->Str[locale][0] != '\0')
return broadcastText->MaleText->Str[locale];
return broadcastText->MaleText->Str[DEFAULT_LOCALE];
}
CharSectionsEntry const* DB2Manager::GetCharSectionEntry(uint8 race, CharSectionType genType, uint8 gender, uint8 type, uint8 color) const
{
auto eqr = _charSections.equal_range(uint32(genType) | uint32(gender << 8) | uint32(race << 16));
for (auto itr = eqr.first; itr != eqr.second; ++itr)
if (itr->second->Type == type && itr->second->Color == color)
return itr->second;
return nullptr;
}
CharStartOutfitEntry const* DB2Manager::GetCharStartOutfitEntry(uint8 race, uint8 class_, uint8 gender) const
{
auto itr = _charStartOutfits.find(race | (class_ << 8) | (gender << 16));
if (itr == _charStartOutfits.end())
return nullptr;
return itr->second;
}
char const* DB2Manager::GetClassName(uint8 class_, LocaleConstant locale /*= DEFAULT_LOCALE*/)
{
ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_);
if (!classEntry)
return "";
if (classEntry->Name->Str[locale][0] != '\0')
return classEntry->Name->Str[locale];
return classEntry->Name->Str[DEFAULT_LOCALE];
}
uint32 DB2Manager::GetPowerIndexByClass(uint32 powerType, uint32 classId) const
{
return _powersByClass[classId][powerType];
}
char const* DB2Manager::GetChrRaceName(uint8 race, LocaleConstant locale /*= DEFAULT_LOCALE*/)
{
ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race);
if (!raceEntry)
return "";
if (raceEntry->Name->Str[locale][0] != '\0')
return raceEntry->Name->Str[locale];
return raceEntry->Name->Str[DEFAULT_LOCALE];
}
ChrSpecializationEntry const* DB2Manager::GetChrSpecializationByIndex(uint32 class_, uint32 index) const
{
return _chrSpecializationsByIndex[class_][index];
}
ChrSpecializationEntry const* DB2Manager::GetDefaultChrSpecializationForClass(uint32 class_) const
{
auto itr = _defaultChrSpecializationsByClass.find(class_);
if (itr != _defaultChrSpecializationsByClass.end())
return itr->second;
return nullptr;
}
char const* DB2Manager::GetCreatureFamilyPetName(uint32 petfamily, uint32 locale)
{
if (!petfamily)
return nullptr;
CreatureFamilyEntry const* petFamily = sCreatureFamilyStore.LookupEntry(petfamily);
if (!petFamily)
return nullptr;
return petFamily->Name->Str[locale][0] != '\0' ? petFamily->Name->Str[locale] : nullptr;
}
enum class CurveInterpolationMode : uint8
{
Linear = 0,
Cosine = 1,
CatmullRom = 2,
Bezier3 = 3,
Bezier4 = 4,
Bezier = 5,
Constant = 6,
};
static CurveInterpolationMode DetermineCurveType(CurveEntry const* curve, std::vector<CurvePointEntry const*> const& points)
{
switch (curve->Type)
{
case 1:
return points.size() < 4 ? CurveInterpolationMode::Cosine : CurveInterpolationMode::CatmullRom;
case 2:
{
switch (points.size())
{
case 1:
return CurveInterpolationMode::Constant;
case 2:
return CurveInterpolationMode::Linear;
case 3:
return CurveInterpolationMode::Bezier3;
case 4:
return CurveInterpolationMode::Bezier4;
default:
break;
}
return CurveInterpolationMode::Bezier;
}
case 3:
return CurveInterpolationMode::Cosine;
default:
break;
}
return points.size() != 1 ? CurveInterpolationMode::Linear : CurveInterpolationMode::Constant;
}
float DB2Manager::GetCurveValueAt(uint32 curveId, float x) const
{
auto itr = _curvePoints.find(curveId);
if (itr == _curvePoints.end())
return 0.0f;
CurveEntry const* curve = sCurveStore.AssertEntry(curveId);
std::vector<CurvePointEntry const*> const& points = itr->second;
if (points.empty())
return 0.0f;
switch (DetermineCurveType(curve, points))
{
case CurveInterpolationMode::Linear:
{
std::size_t pointIndex = 0;
while (pointIndex < points.size() && points[pointIndex]->X <= x)
++pointIndex;
if (!pointIndex)
return points[0]->Y;
if (pointIndex >= points.size())
return points.back()->Y;
float xDiff = points[pointIndex]->X - points[pointIndex - 1]->X;
if (xDiff == 0.0)
return points[pointIndex]->Y;
return (((x - points[pointIndex - 1]->X) / xDiff) * (points[pointIndex]->Y - points[pointIndex - 1]->Y)) + points[pointIndex - 1]->Y;
}
case CurveInterpolationMode::Cosine:
{
std::size_t pointIndex = 0;
while (pointIndex < points.size() && points[pointIndex]->X <= x)
++pointIndex;
if (!pointIndex)
return points[0]->Y;
if (pointIndex >= points.size())
return points.back()->Y;
float xDiff = points[pointIndex]->X - points[pointIndex - 1]->X;
if (xDiff == 0.0)
return points[pointIndex]->Y;
return ((points[pointIndex]->Y - points[pointIndex - 1]->Y) * (1.0f - std::cos((x - points[pointIndex - 1]->X) / xDiff * float(M_PI))) * 0.5f) + points[pointIndex - 1]->Y;
}
case CurveInterpolationMode::CatmullRom:
{
std::size_t pointIndex = 1;
while (pointIndex < points.size() && points[pointIndex]->X <= x)
++pointIndex;
if (pointIndex == 1)
return points[1]->Y;
if (pointIndex >= points.size() - 1)
return points[points.size() - 2]->Y;
float xDiff = points[pointIndex]->X - points[pointIndex - 1]->X;
if (xDiff == 0.0)
return points[pointIndex]->Y;
float mu = (x - points[pointIndex - 1]->X) / xDiff;
float a0 = -0.5f * points[pointIndex - 2]->Y + 1.5f * points[pointIndex - 1]->Y - 1.5f * points[pointIndex]->Y + 0.5f * points[pointIndex + 1]->Y;
float a1 = points[pointIndex - 2]->Y - 2.5f * points[pointIndex - 1]->Y + 2.0f * points[pointIndex]->Y - 0.5f * points[pointIndex + 1]->Y;
float a2 = -0.5f * points[pointIndex - 2]->Y + 0.5f * points[pointIndex]->Y;
float a3 = points[pointIndex - 1]->Y;
return a0 * mu * mu * mu + a1 * mu * mu + a2 * mu + a3;
}
case CurveInterpolationMode::Bezier3:
{
float xDiff = points[2]->X - points[0]->X;
if (xDiff == 0.0)
return points[1]->Y;
float mu = (x - points[0]->X) / xDiff;
return ((1.0f - mu) * (1.0f - mu) * points[0]->Y) + (1.0f - mu) * 2.0f * mu * points[1]->Y + mu * mu * points[2]->Y;
}
case CurveInterpolationMode::Bezier4:
{
float xDiff = points[3]->X - points[0]->X;
if (xDiff == 0.0)
return points[1]->Y;
float mu = (x - points[0]->X) / xDiff;
return (1.0f - mu) * (1.0f - mu) * (1.0f - mu) * points[0]->Y
+ 3.0f * mu * (1.0f - mu) * (1.0f - mu) * points[1]->Y
+ 3.0f * mu * mu * (1.0f - mu) * points[2]->Y
+ mu * mu * mu * points[3]->Y;
}
case CurveInterpolationMode::Bezier:
{
float xDiff = points.back()->X - points[0]->X;
if (xDiff == 0.0f)
return points.back()->Y;
std::vector<float> tmp(points.size());
for (std::size_t i = 0; i < points.size(); ++i)
tmp[i] = points[i]->Y;
float mu = (x - points[0]->X) / xDiff;
int32 i = int32(points.size()) - 1;
while (i > 0)
{
for (int32 k = 0; k < i; ++k)
{
float val = tmp[k] + mu * (tmp[k + 1] - tmp[k]);
tmp[k] = val;
}
--i;
}
return tmp[0];
}
case CurveInterpolationMode::Constant:
return points[0]->Y;
default:
break;
}
return 0.0f;
}
EmotesTextSoundEntry const* DB2Manager::GetTextSoundEmoteFor(uint32 emote, uint8 race, uint8 gender, uint8 class_) const
{
auto itr = _emoteTextSounds.find(EmotesTextSoundContainer::key_type(emote, race, gender, class_));
if (itr != _emoteTextSounds.end())
return itr->second;
itr = _emoteTextSounds.find(EmotesTextSoundContainer::key_type(emote, race, gender, 0));
if (itr != _emoteTextSounds.end())
return itr->second;
return nullptr;
}
std::vector<uint32> const* DB2Manager::GetFactionTeamList(uint32 faction) const
{
auto itr = _factionTeams.find(faction);
if (itr != _factionTeams.end())
return &itr->second;
return nullptr;
}
HeirloomEntry const* DB2Manager::GetHeirloomByItemId(uint32 itemId) const
{
auto itr = _heirlooms.find(itemId);
if (itr != _heirlooms.end())
return itr->second;
return nullptr;
}
std::vector<uint32> const* DB2Manager::GetGlyphBindableSpells(uint32 glyphPropertiesId) const
{
auto itr = _glyphBindableSpells.find(glyphPropertiesId);
if (itr != _glyphBindableSpells.end())
return &itr->second;
return nullptr;
}
std::vector<uint32> const* DB2Manager::GetGlyphRequiredSpecs(uint32 glyphPropertiesId) const
{
auto itr = _glyphRequiredSpecs.find(glyphPropertiesId);
if (itr != _glyphRequiredSpecs.end())
return &itr->second;
return nullptr;
}
DB2Manager::ItemBonusList const* DB2Manager::GetItemBonusList(uint32 bonusListId) const
{
auto itr = _itemBonusLists.find(bonusListId);
if (itr != _itemBonusLists.end())
return &itr->second;
return nullptr;
}
uint32 DB2Manager::GetItemBonusListForItemLevelDelta(int16 delta) const
{
auto itr = _itemLevelDeltaToBonusListContainer.find(delta);
if (itr != _itemLevelDeltaToBonusListContainer.end())
return itr->second;
return 0;
}
std::set<uint32> DB2Manager::GetItemBonusTree(uint32 itemId, uint32 itemBonusTreeMod) const
{
std::set<uint32> bonusListIDs;
auto itemIdRange = _itemToBonusTree.equal_range(itemId);
if (itemIdRange.first == itemIdRange.second)
return bonusListIDs;
for (auto itemTreeItr = itemIdRange.first; itemTreeItr != itemIdRange.second; ++itemTreeItr)
{
auto treeItr = _itemBonusTrees.find(itemTreeItr->second);
if (treeItr == _itemBonusTrees.end())
continue;
for (ItemBonusTreeNodeEntry const* bonusTreeNode : treeItr->second)
if (bonusTreeNode->BonusTreeModID == itemBonusTreeMod)
bonusListIDs.insert(bonusTreeNode->BonusListID);
}
return bonusListIDs;
}
ItemChildEquipmentEntry const* DB2Manager::GetItemChildEquipment(uint32 itemId) const
{
auto itr = _itemChildEquipment.find(itemId);
if (itr != _itemChildEquipment.end())
return itr->second;
return nullptr;
}
ItemClassEntry const* DB2Manager::GetItemClassByOldEnum(uint32 itemClass) const
{
return _itemClassByOldEnum[itemClass];
}
uint32 DB2Manager::GetItemDisplayId(uint32 itemId, uint32 appearanceModId) const
{
if (ItemModifiedAppearanceEntry const* modifiedAppearance = GetItemModifiedAppearance(itemId, appearanceModId))
if (ItemAppearanceEntry const* itemAppearance = sItemAppearanceStore.LookupEntry(modifiedAppearance->AppearanceID))
return itemAppearance->DisplayID;
return 0;
}
ItemModifiedAppearanceEntry const* DB2Manager::GetItemModifiedAppearance(uint32 itemId, uint32 appearanceModId) const
{
auto itr = _itemModifiedAppearancesByItem.find(itemId | (appearanceModId << 24));
if (itr != _itemModifiedAppearancesByItem.end())
return itr->second;
// Fall back to unmodified appearance
itr = _itemDefaultAppearancesByItem.find(itemId);
if (itr != _itemDefaultAppearancesByItem.end())
return itr->second;
return nullptr;
}
ItemModifiedAppearanceEntry const* DB2Manager::GetDefaultItemModifiedAppearance(uint32 itemId) const
{
auto itr = _itemDefaultAppearancesByItem.find(itemId);
if (itr != _itemDefaultAppearancesByItem.end())
return itr->second;
return nullptr;
}
std::vector<ItemSetSpellEntry const*> const* DB2Manager::GetItemSetSpells(uint32 itemSetId) const
{
auto itr = _itemSetSpells.find(itemSetId);
if (itr != _itemSetSpells.end())
return &itr->second;
return nullptr;
}
std::vector<ItemSpecOverrideEntry const*> const* DB2Manager::GetItemSpecOverrides(uint32 itemId) const
{
auto itr = _itemSpecOverrides.find(itemId);
if (itr != _itemSpecOverrides.end())
return &itr->second;
return nullptr;
}
LfgDungeonsEntry const* DB2Manager::GetLfgDungeon(uint32 mapId, Difficulty difficulty)
{
for (LfgDungeonsEntry const* dungeon : sLfgDungeonsStore)
if (dungeon->MapID == int32(mapId) && Difficulty(dungeon->DifficultyID) == difficulty)
return dungeon;
return nullptr;
}
uint32 DB2Manager::GetDefaultMapLight(uint32 mapId)
{
for (int32 i = sLightStore.GetNumRows(); i >= 0; --i)
{
LightEntry const* light = sLightStore.LookupEntry(uint32(i));
if (!light)
continue;
if (light->MapID == mapId && light->Pos.X == 0.0f && light->Pos.Y == 0.0f && light->Pos.Z == 0.0f)
return uint32(i);
}
return 0;
}
uint32 DB2Manager::GetLiquidFlags(uint32 liquidType)
{
if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(liquidType))
return 1 << liq->Type;
return 0;
}
MapDifficultyEntry const* DB2Manager::GetDefaultMapDifficulty(uint32 mapId, Difficulty* difficulty /*= nullptr*/) const
{
auto itr = _mapDifficulties.find(mapId);
if (itr == _mapDifficulties.end())
return nullptr;
if (itr->second.empty())
return nullptr;
for (auto& p : itr->second)
{
DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(p.first);
if (!difficultyEntry)
continue;
if (difficultyEntry->Flags & DIFFICULTY_FLAG_DEFAULT)
{
if (difficulty)
*difficulty = Difficulty(p.first);
return p.second;
}
}
if (difficulty)
*difficulty = Difficulty(itr->second.begin()->first);
return itr->second.begin()->second;
}
MapDifficultyEntry const* DB2Manager::GetMapDifficultyData(uint32 mapId, Difficulty difficulty) const
{
auto itr = _mapDifficulties.find(mapId);
if (itr == _mapDifficulties.end())
return nullptr;
auto diffItr = itr->second.find(difficulty);
if (diffItr == itr->second.end())
return nullptr;
return diffItr->second;
}
MapDifficultyEntry const* DB2Manager::GetDownscaledMapDifficultyData(uint32 mapId, Difficulty& difficulty) const
{
DifficultyEntry const* diffEntry = sDifficultyStore.LookupEntry(difficulty);
if (!diffEntry)
return GetDefaultMapDifficulty(mapId, &difficulty);
uint32 tmpDiff = difficulty;
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapId, Difficulty(tmpDiff));
while (!mapDiff)
{
tmpDiff = diffEntry->FallbackDifficultyID;
diffEntry = sDifficultyStore.LookupEntry(tmpDiff);
if (!diffEntry)
return GetDefaultMapDifficulty(mapId, &difficulty);
// pull new data
mapDiff = GetMapDifficultyData(mapId, Difficulty(tmpDiff)); // we are 10 normal or 25 normal
}
difficulty = Difficulty(tmpDiff);
return mapDiff;
}
MountEntry const* DB2Manager::GetMount(uint32 spellId) const
{
auto itr = _mountsBySpellId.find(spellId);
if (itr != _mountsBySpellId.end())
return itr->second;
return nullptr;
}
MountEntry const* DB2Manager::GetMountById(uint32 id) const
{
return sMountStore.LookupEntry(id);
}
DB2Manager::MountTypeXCapabilitySet const* DB2Manager::GetMountCapabilities(uint32 mountType) const
{
auto itr = _mountCapabilitiesByType.find(mountType);
if (itr != _mountCapabilitiesByType.end())
return &itr->second;
return nullptr;
}
std::string DB2Manager::GetNameGenEntry(uint8 race, uint8 gender, LocaleConstant locale) const
{
ASSERT(gender < GENDER_NONE);
auto ritr = _nameGenData.find(race);
if (ritr == _nameGenData.end())
return "";
if (ritr->second[gender].empty())
return "";
LocalizedString* data = Trinity::Containers::SelectRandomContainerElement(ritr->second[gender])->Name;
if (*data->Str[locale] != '\0')
return data->Str[locale];
return data->Str[sWorld->GetDefaultDbcLocale()];
}
ResponseCodes DB2Manager::ValidateName(std::wstring const& name, LocaleConstant locale) const
{
for (Trinity::wregex const& regex : _nameValidators[locale])
if (Trinity::regex_search(name, regex))
return CHAR_NAME_PROFANE;
// regexes at TOTAL_LOCALES are loaded from NamesReserved which is not locale specific
for (Trinity::wregex const& regex : _nameValidators[TOTAL_LOCALES])
if (Trinity::regex_search(name, regex))
return CHAR_NAME_RESERVED;
return CHAR_NAME_SUCCESS;
}
PvpDifficultyEntry const* DB2Manager::GetBattlegroundBracketByLevel(uint32 mapid, uint32 level)
{
PvpDifficultyEntry const* maxEntry = NULL; // used for level > max listed level case
for (uint32 i = 0; i < sPvpDifficultyStore.GetNumRows(); ++i)
{
if (PvpDifficultyEntry const* entry = sPvpDifficultyStore.LookupEntry(i))
{
// skip unrelated and too-high brackets
if (entry->MapID != mapid || entry->MinLevel > level)
continue;
// exactly fit
if (entry->MaxLevel >= level)
return entry;
// remember for possible out-of-range case (search higher from existed)
if (!maxEntry || maxEntry->MaxLevel < entry->MaxLevel)
maxEntry = entry;
}
}
return maxEntry;
}
PvpDifficultyEntry const* DB2Manager::GetBattlegroundBracketById(uint32 mapid, BattlegroundBracketId id)
{
for (uint32 i = 0; i < sPvpDifficultyStore.GetNumRows(); ++i)
if (PvpDifficultyEntry const* entry = sPvpDifficultyStore.LookupEntry(i))
if (entry->MapID == mapid && entry->GetBracketId() == id)
return entry;
return nullptr;
}
std::vector<QuestPackageItemEntry const*> const* DB2Manager::GetQuestPackageItems(uint32 questPackageID) const
{
auto itr = _questPackages.find(questPackageID);
if (itr != _questPackages.end())
return &itr->second.first;
return nullptr;
}
std::vector<QuestPackageItemEntry const*> const* DB2Manager::GetQuestPackageItemsFallback(uint32 questPackageID) const
{
auto itr = _questPackages.find(questPackageID);
if (itr != _questPackages.end())
return &itr->second.second;
return nullptr;
}
uint32 DB2Manager::GetQuestUniqueBitFlag(uint32 questId)
{
QuestV2Entry const* v2 = sQuestV2Store.LookupEntry(questId);
if (!v2)
return 0;
return v2->UniqueBitFlag;
}
std::set<uint32> DB2Manager::GetPhasesForGroup(uint32 group) const
{
auto itr = _phasesByGroup.find(group);
if (itr != _phasesByGroup.end())
return itr->second;
return std::set<uint32>();
}
PowerTypeEntry const* DB2Manager::GetPowerTypeEntry(Powers power) const
{
ASSERT(power < MAX_POWERS);
return _powerTypes[power];
}
uint32 DB2Manager::GetRulesetItemUpgrade(uint32 itemId) const
{
auto itr = _rulesetItemUpgrade.find(itemId);
if (itr != _rulesetItemUpgrade.end())
return itr->second;
return 0;
}
SkillRaceClassInfoEntry const* DB2Manager::GetSkillRaceClassInfo(uint32 skill, uint8 race, uint8 class_)
{
auto bounds = _skillRaceClassInfoBySkill.equal_range(skill);
for (auto itr = bounds.first; itr != bounds.second; ++itr)
{
if (itr->second->RaceMask && !(itr->second->RaceMask & (1 << (race - 1))))
continue;
if (itr->second->ClassMask && !(itr->second->ClassMask & (1 << (class_ - 1))))
continue;
return itr->second;
}
return nullptr;
}
std::vector<SpecializationSpellsEntry const*> const* DB2Manager::GetSpecializationSpells(uint32 specId) const
{
auto itr = _specializationSpellsBySpec.find(specId);
if (itr != _specializationSpellsBySpec.end())
return &itr->second;
return nullptr;
}
std::vector<SpellPowerEntry const*> DB2Manager::GetSpellPowers(uint32 spellId, Difficulty difficulty /*= DIFFICULTY_NONE*/, bool* hasDifficultyPowers /*= nullptr*/) const
{
std::vector<SpellPowerEntry const*> powers;
auto difficultyItr = _spellPowerDifficulties.find(spellId);
if (difficultyItr != _spellPowerDifficulties.end())
{
if (hasDifficultyPowers)
*hasDifficultyPowers = true;
DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(difficulty);
while (difficultyEntry)
{
auto powerDifficultyItr = difficultyItr->second.find(difficultyEntry->ID);
if (powerDifficultyItr != difficultyItr->second.end())
{
if (powerDifficultyItr->second.size() > powers.size())
powers.resize(powerDifficultyItr->second.size());
for (SpellPowerEntry const* difficultyPower : powerDifficultyItr->second)
if (!powers[difficultyPower->PowerIndex])
powers[difficultyPower->PowerIndex] = difficultyPower;
}
difficultyEntry = sDifficultyStore.LookupEntry(difficultyEntry->FallbackDifficultyID);
}
}
auto itr = _spellPowers.find(spellId);
if (itr != _spellPowers.end())
{
if (itr->second.size() > powers.size())
powers.resize(itr->second.size());
for (SpellPowerEntry const* power : itr->second)
if (!powers[power->PowerIndex])
powers[power->PowerIndex] = power;
}
return powers;
}
std::vector<SpellProcsPerMinuteModEntry const*> DB2Manager::GetSpellProcsPerMinuteMods(uint32 spellprocsPerMinuteId) const
{
auto itr = _spellProcsPerMinuteMods.find(spellprocsPerMinuteId);
if (itr != _spellProcsPerMinuteMods.end())
return itr->second;
return std::vector<SpellProcsPerMinuteModEntry const*>();
}
std::vector<TalentEntry const*> const& DB2Manager::GetTalentsByPosition(uint32 class_, uint32 tier, uint32 column) const
{
return _talentsByPosition[class_][tier][column];
}
bool DB2Manager::IsTotemCategoryCompatibleWith(uint32 itemTotemCategoryId, uint32 requiredTotemCategoryId)
{
if (requiredTotemCategoryId == 0)
return true;
if (itemTotemCategoryId == 0)
return false;
TotemCategoryEntry const* itemEntry = sTotemCategoryStore.LookupEntry(itemTotemCategoryId);
if (!itemEntry)
return false;
TotemCategoryEntry const* reqEntry = sTotemCategoryStore.LookupEntry(requiredTotemCategoryId);
if (!reqEntry)
return false;
if (itemEntry->CategoryType != reqEntry->CategoryType)
return false;
return (itemEntry->CategoryMask & reqEntry->CategoryMask) == reqEntry->CategoryMask;
}
bool DB2Manager::IsToyItem(uint32 toy) const
{
return _toys.count(toy) > 0;
}
WMOAreaTableEntry const* DB2Manager::GetWMOAreaTable(int32 rootId, int32 adtId, int32 groupId) const
{
auto i = _wmoAreaTableLookup.find(WMOAreaTableKey(int16(rootId), int8(adtId), groupId));
if (i != _wmoAreaTableLookup.end())
return i->second;
return nullptr;
}
uint32 DB2Manager::GetVirtualMapForMapAndZone(uint32 mapId, uint32 zoneId) const
{
if (mapId != 530 && mapId != 571 && mapId != 732) // speed for most cases
return mapId;
auto itr = _worldMapAreaByAreaID.find(zoneId);
if (itr != _worldMapAreaByAreaID.end())
return itr->second->DisplayMapID >= 0 ? itr->second->DisplayMapID : itr->second->MapID;
return mapId;
}
void DB2Manager::Zone2MapCoordinates(uint32 areaId, float& x, float& y) const
{
auto itr = _worldMapAreaByAreaID.find(areaId);
if (itr == _worldMapAreaByAreaID.end())
return;
std::swap(x, y); // at client map coords swapped
x = x*((itr->second->LocBottom - itr->second->LocTop) / 100) + itr->second->LocTop;
y = y*((itr->second->LocRight - itr->second->LocLeft) / 100) + itr->second->LocLeft; // client y coord from top to down
}
void DB2Manager::Map2ZoneCoordinates(uint32 areaId, float& x, float& y) const
{
auto itr = _worldMapAreaByAreaID.find(areaId);
if (itr == _worldMapAreaByAreaID.end())
return;
x = (x - itr->second->LocTop) / ((itr->second->LocBottom - itr->second->LocTop) / 100);
y = (y - itr->second->LocLeft) / ((itr->second->LocRight - itr->second->LocLeft) / 100); // client y coord from top to down
std::swap(x, y); // client have map coords swapped
}
void DB2Manager::DeterminaAlternateMapPosition(uint32 mapId, float x, float y, float z, uint32* newMapId /*= nullptr*/, DBCPosition2D* newPos /*= nullptr*/)
{
ASSERT(newMapId || newPos);
WorldMapTransformsEntry const* transformation = nullptr;
for (WorldMapTransformsEntry const* transform : sWorldMapTransformsStore)
{
if (transform->MapID != mapId)
continue;
if (transform->RegionMin.X > x || transform->RegionMax.X < x)
continue;
if (transform->RegionMin.Y > y || transform->RegionMax.Y < y)
continue;
if (transform->RegionMin.Z > z || transform->RegionMax.Z < z)
continue;
transformation = transform;
break;
}
if (!transformation)
{
if (newMapId)
*newMapId = mapId;
if (newPos)
{
newPos->X = x;
newPos->Y = y;
}
return;
}
if (newMapId)
*newMapId = transformation->NewMapID;
if (!newPos)
return;
if (transformation->RegionScale > 0.0f && transformation->RegionScale < 1.0f)
{
x = (x - transformation->RegionMin.X) * transformation->RegionScale + transformation->RegionMin.X;
y = (y - transformation->RegionMin.Y) * transformation->RegionScale + transformation->RegionMin.Y;
}
newPos->X = x + transformation->RegionOffset.X;
newPos->Y = y + transformation->RegionOffset.Y;
}
bool DB2Manager::ChrClassesXPowerTypesEntryComparator::Compare(ChrClassesXPowerTypesEntry const* left, ChrClassesXPowerTypesEntry const* right)
{
if (left->ClassID != right->ClassID)
return left->ClassID < right->ClassID;
return left->PowerType < right->PowerType;
}
bool DB2Manager::MountTypeXCapabilityEntryComparator::Compare(MountTypeXCapabilityEntry const* left, MountTypeXCapabilityEntry const* right)
{
if (left->MountTypeID == right->MountTypeID)
return left->OrderIndex < right->OrderIndex;
return left->MountTypeID < right->MountTypeID;
}
|
gpl-2.0
|
DanLatimer/killer-logcat
|
DataStore.js
|
774
|
function DataStoreEntry() {
this.count = 0;
this.entries = [];
}
DataStoreEntry.prototype.push = function(entry) {
this.count++;
this.entries.push(entry);
}
function DataStore() {
this.data = {};
}
DataStore.prototype.addEntry = function(indexItem, item) {
var dataItem = this.data[indexItem];
if (dataItem == undefined) {
dataItem = new DataStoreEntry();
}
dataItem.push(item);
this.data[indexItem] = dataItem;
};
DataStore.prototype.distinct = function() {
return Object.keys(this.data);
};
DataStore.prototype.toString = function() {
var string = [];
for (var key in this.data) {
string.push({"key": key, "count": this.data[key].count});
}
return string;
}
module.exports = DataStore;
|
gpl-2.0
|
axelcode/globalreports
|
src/com/globalreports/engine/structure/font/encoding/GRWinAnsiEncoding.java
|
5115
|
/*
* ==========================================================================
* class name : com.globalreports.engine.structure.font.encoding.GRWinAnsiEncoding
*
* Begin :
* Last Update :
*
* Author : Alessandro Baldini - alex.baldini72@gmail.com
* License : GNU-GPL v2 (http://www.gnu.org/licenses/)
* ==========================================================================
*
* GlobalReports
* Copyright (C) 2015 Alessandro Baldini
*
* 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/>.
*
* Linking GlobalReports Engine(C) statically or dynamically with other
* modules is making a combined work based on GlobalReports Engine(C).
* Thus, the terms and conditions of the GNU General Public License cover
* the whole combination.
*
* In addition, as a special exception, the copyright holders
* of GlobalReports Engine(C) give you permission to combine
* GlobalReports Engine(C) program with free software programs or libraries
* that are released under the GNU LGPL.
* You may copy and distribute such a system following the terms of the GNU GPL
* for GlobalReports Engine(C) and the licenses of the other code concerned,
* provided that you include the source code of that other code
* when and as the GNU GPL requires distribution of source code.
*
* Note that people who make modified versions of GlobalReports Engine(C)
* are not obligated to grant this special exception for their modified versions;
* it is their choice whether to do so. The GNU General Public License
* gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version
* which carries forward this exception.
*
*/
package com.globalreports.engine.structure.font.encoding;
public class GRWinAnsiEncoding extends GREncoding {
public final String[] octal = {"00", "01", "02", "03", "04", "05", "06", "07",
"010","011","012","013","014","015","016","017",
"020","021","022","023","024","025","026","027",
"030","031","032","033","034","035","036","037",
"040","041","042","043","044","045","046","047",
"050","051","052","053","054","055","056","057",
"060","061","062","063","064","065","066","067",
"070","071","072","073","074","075","076","077",
"100","101","102","103","104","105","106","107",
"110","111","112","113","114","115","116","117",
"120","121","122","123","124","125","126","127",
"130","131","132","133","134","135","136","137",
"140","141","142","143","144","145","146","147",
"150","151","152","153","154","155","156","157",
"160","161","162","163","164","165","166","167",
"170","171","172","173","174","175","176","177",
"200","201","202","203","204","205","206","207",
"210","211","212","213","214","215","216","217",
"220","221","222","223","224","225","226","227",
"230","231","232","233","234","235","236","237",
"240","241","242","243","244","245","246","247",
"250","251","252","253","254","255","256","257",
"260","261","262","263","264","265","266","267",
"270","271","272","273","274","275","276","277",
"300","301","302","303","304","305","306","307",
"310","311","312","313","314","315","316","317",
"320","321","322","323","324","325","326","327",
"330","331","332","333","334","335","336","337",
"340","341","342","343","344","345","346","347",
"350","351","352","353","354","355","356","357",
"360","361","362","363","364","365","366","367",
"370","371","372","373","374","375","376","377"};
public final String[] octal2 = {"045","050","051","057","074","076","173","175",
"225","260","340","341","350","351","354","355",
"362","363","371","372","012","272"};
public final int[] dec = {37,40,41,47,60,62,123,125,149,176,224,225,232,233,236,237,
242,243,249,250,-1,186};
public GRWinAnsiEncoding() {
type = "WinAnsiEncoding";
}
public int fromOctalToDecimal(String charcode) {
if(charcode.equals("012"))
return -1;
else {
for(int i = 0;i < octal.length;i++) {
if(charcode.equals(octal[i]))
return i;
}
}
return 0;
}
}
|
gpl-2.0
|
tanmoyesolz/edmtunes
|
wp-content/themes/Newspaper/includes/wp_booster/td_widget_builder.php
|
7725
|
<?php
class td_widget_builder {
/**
* @var WP_Widget
*/
var $WP_Widget_this;
var $map_array;
var $map_param_default_array;
function __construct(&$WP_Widget_object_ref) {
$this->WP_Widget_this = $WP_Widget_object_ref;
}
//builds the array - from that arrays the widget's options panel is built
function td_map ($map_array) {
$this->map_array = $map_array;
$widget_ops = array('classname' => 'td_pb_widget', 'description' => '[tagDiv] ' . $map_array['name']);
/**
* overwrite the widget settings, we emulate the WordPress settings. Before 4.3 we called the old php4 constructor again :(
* @see \WP_Widget::__construct
*/
$id_base = $map_array['base'] . '_widget';
$name = '[tagDiv] ' . $map_array['name'];
$widget_options = $widget_ops;
$control_options = array();
$this->WP_Widget_this->id_base = strtolower($id_base);
$this->WP_Widget_this->name = $name;
$this->WP_Widget_this->option_name = 'widget_' . $this->WP_Widget_this->id_base;
$this->WP_Widget_this->widget_options = wp_parse_args( $widget_options, array('classname' => $this->WP_Widget_this->option_name) );
$this->WP_Widget_this->control_options = wp_parse_args( $control_options, array('id_base' => $this->WP_Widget_this->id_base) );
$this->map_param_default_array = $this->build_param_default_values();
}
/*
function build_param_name_value() {
foreach ($this->map_array['params'] as $param) {
$buffy_array[$param['param_name']] = $param['value'];
}
return $buffy_array;
}
*/
function build_param_default_values() {
$buffy_array = array();
if (!empty($this->map_array['params'])) {
foreach ($this->map_array['params'] as $param) {
if ($param['type'] == 'dropdown') {
$buffy_array[$param['param_name']] = '';
} else {
$buffy_array[$param['param_name']] = $param['value'];
}
}
}
return $buffy_array;
}
//shows the widget form in wp-admin
function form($instance) {
$instance = wp_parse_args((array) $instance, $this->map_param_default_array);
//print_r($instance);
if (!empty($this->map_array['params'])) {
foreach ($this->map_array['params'] as $param) {
switch ($param['type']) {
case 'textarea_html':
//print_r($param);
?>
<p>
<label for="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"><?php echo $param['heading']; ?></label>
<textarea class="widefat" name="<?php echo $this->WP_Widget_this->get_field_name($param['param_name']); ?>" id="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>" cols="30" rows="10"><?php echo esc_textarea($instance[$param['param_name']]); ?></textarea>
<div class="td-wpa-info">
<?php echo $param['description']; ?>
</div>
</p>
<?php
break;
case 'textfield':
//print_r($param);
?>
<p>
<label for="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"><?php echo $param['heading']; ?></label>
<input class="widefat" id="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"
name="<?php echo $this->WP_Widget_this->get_field_name($param['param_name']); ?>" type="text"
value="<?php echo $instance[$param['param_name']]; ?>" />
<div class="td-wpa-info">
<?php echo $param['description']; ?>
</div>
</p>
<?php
break;
case 'dropdown':
?>
<p>
<label for="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"><?php echo $param['heading']; ?></label>
<select name="<?php echo $this->WP_Widget_this->get_field_name($param['param_name']); ?>" id="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>" class="widefat">
<?php
foreach ($param['value'] as $param_name => $param_value) {
?>
<option value="<?php echo $param_value; ?>"<?php selected($instance[$param['param_name']], $param_value); ?>><?php echo $param_name; ?></option>
<?php
}
?>
</select>
<div class="td-wpa-info">
<?php echo $param['description']; ?>
</div>
</p>
<?php
break;
case 'colorpicker':
$empty_color_fix = '#';
if (!empty($instance[$param['param_name']])) {
$empty_color_fix = $instance[$param['param_name']];
}
$widget_color_picker_id = td_global::td_generate_unique_id();
?>
<p>
<label for="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"><?php echo $param['heading']; ?></label>
<input data-td-w-color="<?php echo $widget_color_picker_id?>" class="widefat td-color-picker-field" id="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"
name="<?php echo $this->WP_Widget_this->get_field_name($param['param_name']); ?>" type="text"
value="<?php echo $empty_color_fix; ?>" />
<div id="<?php echo $widget_color_picker_id?>" class="td-color-picker-widget" rel="<?php echo $this->WP_Widget_this->get_field_id($param['param_name']); ?>"></div>
</p>
<div class="td-wpa-info">
<?php echo $param['description']; ?>
</div>
<script>
td_widget_attach_color_picker();
</script>
<?php
break;
}
}
}
}
//updates the option
function update($new_instance, $old_instance) {
$instance = $old_instance;
foreach ($this->map_param_default_array as $param_name => $param_value) {
//if we need aditional procesing, we will do it here
$instance[$param_name] = $new_instance[$param_name];
}
return $instance;
}
}
function sample_load_color_picker_script() {
wp_enqueue_script('farbtastic');
}
function sample_load_color_picker_style() {
wp_enqueue_style('farbtastic');
}
add_action('admin_print_scripts-widgets.php', 'sample_load_color_picker_script');
add_action('admin_print_styles-widgets.php', 'sample_load_color_picker_style');
|
gpl-2.0
|
dyarfi/ci_rbac
|
application/modules/admin/views/~template/admin_template.php
|
15536
|
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.1.1
Version: 2.0.2
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: support@keenthemes.com
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<?php
//print_r(Acl::instance()->user);
?>
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en" class="no-js">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8"/>
<title><?=$this->config->item('developer_name');?> | Admin Dashboard</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<meta content="" name="description"/>
<meta content="" name="author"/>
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/>
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL PLUGIN STYLES -->
<link href="<?=admin_theme()?>assets/plugins/gritter/css/jquery.gritter.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/clockface/css/clockface.css"/>
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/bootstrap-datepicker/css/datepicker.css"/>
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/bootstrap-timepicker/css/bootstrap-timepicker.min.css"/>
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css"/>
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/bootstrap-datetimepicker/css/datetimepicker.css"/>
<link href="<?=admin_theme()?>assets/plugins/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" type="text/css"/>
<!--<link href="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/jqvmap.css" rel="stylesheet" type="text/css"/>-->
<link href="<?=admin_theme()?>assets/plugins/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css"/>
<!-- END PAGE LEVEL PLUGIN STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/select2/select2.css"/>
<link rel="stylesheet" type="text/css" href="<?=admin_theme()?>assets/plugins/select2/select2-metronic.css"/>
<link rel="stylesheet" href="<?=admin_theme()?>assets/plugins/data-tables/DT_bootstrap.css"/>
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME STYLES -->
<link href="<?=admin_theme()?>assets/css/style-metronic.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/css/style.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/css/style-responsive.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/css/plugins.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/css/pages/tasks.css" rel="stylesheet" type="text/css"/>
<link href="<?=admin_theme()?>assets/css/themes/default.css" rel="stylesheet" type="text/css" id="style_color"/>
<link href="<?=admin_theme()?>assets/css/print.css" rel="stylesheet" type="text/css" media="print"/>
<link href="<?=admin_theme()?>assets/css/custom.css" rel="stylesheet" type="text/css"/>
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
<script>base_URL = '<?=base_url()?>';</script>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<body class="page-header-fixed">
<!-- BEGIN HEADER -->
<div class="header navbar navbar-fixed-top">
<!-- BEGIN TOP NAVIGATION BAR -->
<div class="header-inner">
<!-- BEGIN LOGO -->
<a class="navbar-brand" href="<?=base_url();?>" target="_blank">
<img src="<?=admin_theme()?>assets/img/logo_small.png" alt="logo" class="img-responsive col-md-7 col-lg-7"/>
</a>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<img src="<?=admin_theme()?>assets/img/menu-toggler.png" alt=""/>
</a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN TOP NAVIGATION MENU -->
<ul class="nav navbar-nav pull-right">
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- END NOTIFICATION DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<li class="dropdown user">
<a href="<?=base_url();?>admin/user/view/<?=ACL::user()->id;?>" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<img alt="" src="<?=base_url()?>assets/img/avatar1_small.jpg"/>
<span class="username">
<?=ACL::user()->name;?>
</span>
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu">
<li>
<a href="<?=base_url();?>admin/user/view/<?=ACL::user()->id;?>"><i class="fa fa-user"></i> Profile</a>
</li>
<li>
<a href="javascript:;">
<i class="fa fa-lock"></i> Last Login <?php echo date('Y-m-d, H:i:s',ACL::user()->last_login);?>
</a>
</li>
<li>
<a href="<?=base_url()?>admin/authenticate/logout">
<i class="fa fa-key"></i> Log Out
</a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
</ul>
<!-- END TOP NAVIGATION MENU -->
</div>
<!-- END TOP NAVIGATION BAR -->
</div>
<!-- END HEADER -->
<div class="clearfix">
</div>
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<div class="page-sidebar navbar-collapse collapse">
<!-- add "navbar-no-scroll" class to disable the scrolling of the sidebar menu -->
<!-- BEGIN SIDEBAR MENU -->
<ul class="page-sidebar-menu" data-auto-scroll="true" data-slide-speed="200">
<li class="sidebar-toggler-wrapper">
<!-- BEGIN SIDEBAR TOGGLER BUTTON -->
<div class="sidebar-toggler hidden-phone"></div>
<!-- BEGIN SIDEBAR TOGGLER BUTTON -->
</li>
<li class="sidebar-search-wrapper">
<!-- BEGIN RESPONSIVE QUICK SEARCH FORM -->
<!-- END RESPONSIVE QUICK SEARCH FORM -->
</li>
<?php /*echo preg_match('/\b'.Request::$current->controller().'\b/i', substr($row_function, 0, strpos($row_function, '/'))) ? 'current' : ''; */ ?>
<!--li class="start <?if(preg_match('/\b'.$this->uri->segment(2).'\b/i', 'dashboard')){?>active<?}?> ">
<a href="<?=base_url(ADMIN.'dashboard/index')?>">
<i class="fa fa-home"></i>
<span class="title">
Dashboard
</span>
<?
if($this->uri->segment(1)=='__admin_dashboard')
{
?>
<span class="selected">
</span>
<?
}
?>
</a>
</li>
<li class="<?if(preg_match('/\b'.$this->uri->segment(2).'\b/i', 'user')){ ?>active<?}?>">
<a href="javascript:;">
<i class="fa fa-user"></i>
<span class="title">
User Control
</span>
<span class="arrow ">
</span>
</a>
<ul class="sub-menu">
<li class="<?if(preg_match('/\b'.$this->uri->segment(2).'\b/i', 'user')){?>active<?}?>">
<a href="<?=base_url(ADMIN.'user/index')?>">
List User
</a>
</li>
<li class="<?if(preg_match('/\b'.$this->uri->segment(2).'\b/i', 'usergroup')){?>active<?}?>">
<a href="<?=base_url(ADMIN.'usergroup/index')?>">
List Groups
</a>
</li>
</ul>
</li-->
<?php
$k = 0;
foreach (Acl::admin_system_modules() as $name => $functions) {
if (is_array($functions) && count($functions) != 0) { ?>
<li class="<?if(preg_match('/\b'.$this->uri->segment(2).'\b/i', strtolower($name))){ ?>active<?}?>">
<a class="" href="#collapse<?php echo $k;?>">
<span class="title"><?php echo $name; ?></span><span class="arrow "></span>
</a>
<ul class="sub-menu">
<?php foreach ($functions as $row_function => $row_label) { ?>
<?php if(Acl::user()->group_id != 1 && $row_label == 'Groups') continue; ?>
<li class="<?php echo preg_match('/\b'.$this->uri->segment(2).'\b/i', substr($row_function, 0, strpos($row_function, '/'))) ? 'active' : ''; ?>">
<a href="<?php echo base_url(ADMIN . $row_function); ?>"><?php echo $row_label; ?></a>
</li>
<?php } ?>
</ul>
</li>
<?php }
$k++;
}
?>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<?=$this->load->view($main);?>
<!-- END CONTENT -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<?php $this->load->view('template/footer'); ?>
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="assets/plugins/respond.min.js"></script>
<script src="assets/plugins/excanvas.min.js"></script>
<![endif]-->
<script src="<?=admin_theme()?>assets/plugins/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui-1.10.3.custom.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="<?=admin_theme()?>assets/plugins/jquery-ui/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<!--script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/jquery.vmap.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/maps/jquery.vmap.russia.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/maps/jquery.vmap.world.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/maps/jquery.vmap.europe.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/maps/jquery.vmap.germany.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/maps/jquery.vmap.usa.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jqvmap/jqvmap/data/jquery.vmap.sampledata.js" type="text/javascript"></script-->
<script src="<?=admin_theme()?>assets/plugins/flot/jquery.flot.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/flot/jquery.flot.resize.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/flot/jquery.flot.categories.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery.pulsate.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/gritter/js/jquery.gritter.js" type="text/javascript"></script>
<!-- IMPORTANT! fullcalendar depends on jquery-ui-1.10.3.custom.min.js for drag & drop support -->
<script src="<?=admin_theme()?>assets/plugins/fullcalendar/fullcalendar/fullcalendar.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery-easy-pie-chart/jquery.easy-pie-chart.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery.sparkline.min.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/plugins/jquery-validation/dist/jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/select2/select2.min.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/data-tables/jquery.dataTables.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/data-tables/DT_bootstrap.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/bootstrap-timepicker/js/bootstrap-timepicker.min.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/clockface/js/clockface.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/bootstrap-daterangepicker/moment.min.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/bootstrap-daterangepicker/daterangepicker.js"></script>
<script type="text/javascript" src="<?=admin_theme()?>assets/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<script src="<?=admin_theme()?>assets/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="<?=admin_theme()?>assets/scripts/core/app.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/scripts/custom/index.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/scripts/custom/tasks.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/scripts/custom/table-managed.js"></script>
<script src="<?=admin_theme()?>assets/scripts/custom/components-pickers.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN USER AJAX JAVASCRIPTS -->
<script src="<?=admin_theme()?>assets/scripts/custom/form-user.js" type="text/javascript"></script>
<script src="<?=admin_theme()?>assets/scripts/custom/form-module.js" type="text/javascript"></script>
<!-- END USER AJAX JAVASCRIPTS -->
<script>
jQuery(document).ready(function() {
App.init(); // initlayout and core plugins
TableManaged.init();
ComponentsPickers.init();
Index.init();
//Index.initJQVMAP(); // init index page's custom scripts
Index.initCalendar(); // init index page's custom scripts
Index.initCharts(); // init index page's custom scripts
Index.initChat();
Index.initMiniCharts();
Index.initDashboardDaterange();
Index.initIntro();
Tasks.initDashboardWidget();
FormUser.init();
FormModule.init();
<?php if ($this->session->flashdata('message')) { ?>
bootbox.alert('<h3><?php echo $this->session->flashdata('message');?></h3>');
<?php } ?>
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
|
gpl-2.0
|
Wolfsblvt/mentions
|
lib/ichord/Caret.js/dist/jquery.caret.js
|
12298
|
/*
Implement Github like autocomplete mentions
http://ichord.github.com/At.js
Copyright (c) 2013 chord.luo@gmail.com
Licensed under the MIT license.
*/
/*
ๆฌๆไปถๆไฝ textarea ๆ่
input ๅ
็ๆๅ
ฅ็ฌฆ
ๅชๅฎ็ฐไบ่ทๅพๆๅ
ฅ็ฌฆๅจๆๆฌๆกไธญ็ไฝ็ฝฎ๏ผๆ่ฎพ็ฝฎ
ๆๅ
ฅ็ฌฆ็ไฝ็ฝฎ.
*/
(function() {
(function(factory) {
if (typeof define === 'function' && define.amd) {
return define(['jquery'], factory);
} else {
return factory(window.jQuery);
}
})(function($) {
"use strict";
var EditableCaret, InputCaret, Mirror, Utils, discoveryIframeOf, methods, oDocument, oFrame, oWindow, pluginName, setContextBy;
pluginName = 'caret';
EditableCaret = (function() {
function EditableCaret($inputor) {
this.$inputor = $inputor;
this.domInputor = this.$inputor[0];
}
EditableCaret.prototype.setPos = function(pos) {
return this.domInputor;
};
EditableCaret.prototype.getIEPosition = function() {
return this.getPosition();
};
EditableCaret.prototype.getPosition = function() {
var inputor_offset, offset;
offset = this.getOffset();
inputor_offset = this.$inputor.offset();
offset.left -= inputor_offset.left;
offset.top -= inputor_offset.top;
return offset;
};
EditableCaret.prototype.getOldIEPos = function() {
var preCaretTextRange, textRange;
textRange = oDocument.selection.createRange();
preCaretTextRange = oDocument.body.createTextRange();
preCaretTextRange.moveToElementText(this.domInputor);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
return preCaretTextRange.text.length;
};
EditableCaret.prototype.getPos = function() {
var clonedRange, pos, range;
if (range = this.range()) {
clonedRange = range.cloneRange();
clonedRange.selectNodeContents(this.domInputor);
clonedRange.setEnd(range.endContainer, range.endOffset);
pos = clonedRange.toString().length;
clonedRange.detach();
return pos;
} else if (oDocument.selection) {
return this.getOldIEPos();
}
};
EditableCaret.prototype.getOldIEOffset = function() {
var range, rect;
range = oDocument.selection.createRange().duplicate();
range.moveStart("character", -1);
rect = range.getBoundingClientRect();
return {
height: rect.bottom - rect.top,
left: rect.left,
top: rect.top
};
};
EditableCaret.prototype.getOffset = function(pos) {
var clonedRange, offset, range, rect, shadowCaret;
if (oWindow.getSelection && (range = this.range())) {
if (range.endOffset - 1 > 0 && range.endContainer === !this.domInputor) {
clonedRange = range.cloneRange();
clonedRange.setStart(range.endContainer, range.endOffset - 1);
clonedRange.setEnd(range.endContainer, range.endOffset);
rect = clonedRange.getBoundingClientRect();
offset = {
height: rect.height,
left: rect.left + rect.width,
top: rect.top
};
clonedRange.detach();
}
if (!offset || (offset != null ? offset.height : void 0) === 0) {
clonedRange = range.cloneRange();
shadowCaret = $(oDocument.createTextNode("|"));
clonedRange.insertNode(shadowCaret[0]);
clonedRange.selectNode(shadowCaret[0]);
rect = clonedRange.getBoundingClientRect();
offset = {
height: rect.height,
left: rect.left,
top: rect.top
};
shadowCaret.remove();
clonedRange.detach();
}
} else if (oDocument.selection) {
offset = this.getOldIEOffset();
}
if (offset) {
offset.top += $(oWindow).scrollTop();
offset.left += $(oWindow).scrollLeft();
}
return offset;
};
EditableCaret.prototype.range = function() {
var sel;
if (!oWindow.getSelection) {
return;
}
sel = oWindow.getSelection();
if (sel.rangeCount > 0) {
return sel.getRangeAt(0);
} else {
return null;
}
};
return EditableCaret;
})();
InputCaret = (function() {
function InputCaret($inputor) {
this.$inputor = $inputor;
this.domInputor = this.$inputor[0];
}
InputCaret.prototype.getIEPos = function() {
var endRange, inputor, len, normalizedValue, pos, range, textInputRange;
inputor = this.domInputor;
range = oDocument.selection.createRange();
pos = 0;
if (range && range.parentElement() === inputor) {
normalizedValue = inputor.value.replace(/\r\n/g, "\n");
len = normalizedValue.length;
textInputRange = inputor.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
endRange = inputor.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
pos = len;
} else {
pos = -textInputRange.moveStart("character", -len);
}
}
return pos;
};
InputCaret.prototype.getPos = function() {
if (oDocument.selection) {
return this.getIEPos();
} else {
return this.domInputor.selectionStart;
}
};
InputCaret.prototype.setPos = function(pos) {
var inputor, range;
inputor = this.domInputor;
if (oDocument.selection) {
range = inputor.createTextRange();
range.move("character", pos);
range.select();
} else if (inputor.setSelectionRange) {
inputor.setSelectionRange(pos, pos);
}
return inputor;
};
InputCaret.prototype.getIEOffset = function(pos) {
var h, textRange, x, y;
textRange = this.domInputor.createTextRange();
pos || (pos = this.getPos());
textRange.move('character', pos);
x = textRange.boundingLeft;
y = textRange.boundingTop;
h = textRange.boundingHeight;
return {
left: x,
top: y,
height: h
};
};
InputCaret.prototype.getOffset = function(pos) {
var $inputor, offset, position;
$inputor = this.$inputor;
if (oDocument.selection) {
offset = this.getIEOffset(pos);
offset.top += $(oWindow).scrollTop() + $inputor.scrollTop();
offset.left += $(oWindow).scrollLeft() + $inputor.scrollLeft();
return offset;
} else {
offset = $inputor.offset();
position = this.getPosition(pos);
return offset = {
left: offset.left + position.left - $inputor.scrollLeft(),
top: offset.top + position.top - $inputor.scrollTop(),
height: position.height
};
}
};
InputCaret.prototype.getPosition = function(pos) {
var $inputor, at_rect, end_range, format, html, mirror, start_range;
$inputor = this.$inputor;
format = function(value) {
return $('<div></div>').text(value).html().replace(/\r\n|\r|\n/g, "<br/>").replace(/\s/g, " ");
};
if (pos === void 0) {
pos = this.getPos();
}
start_range = $inputor.val().slice(0, pos);
end_range = $inputor.val().slice(pos);
html = "<span style='position: relative; display: inline;'>" + format(start_range) + "</span>";
html += "<span id='caret' style='position: relative; display: inline;'>|</span>";
html += "<span style='position: relative; display: inline;'>" + format(end_range) + "</span>";
mirror = new Mirror($inputor);
return at_rect = mirror.create(html).rect();
};
InputCaret.prototype.getIEPosition = function(pos) {
var h, inputorOffset, offset, x, y;
offset = this.getIEOffset(pos);
inputorOffset = this.$inputor.offset();
x = offset.left - inputorOffset.left;
y = offset.top - inputorOffset.top;
h = offset.height;
return {
left: x,
top: y,
height: h
};
};
return InputCaret;
})();
Mirror = (function() {
Mirror.prototype.css_attr = ["borderBottomWidth", "borderLeftWidth", "borderRightWidth", "borderTopStyle", "borderRightStyle", "borderBottomStyle", "borderLeftStyle", "borderTopWidth", "boxSizing", "fontFamily", "fontSize", "fontWeight", "height", "letterSpacing", "lineHeight", "marginBottom", "marginLeft", "marginRight", "marginTop", "outlineWidth", "overflow", "overflowX", "overflowY", "paddingBottom", "paddingLeft", "paddingRight", "paddingTop", "textAlign", "textOverflow", "textTransform", "whiteSpace", "wordBreak", "wordWrap"];
function Mirror($inputor) {
this.$inputor = $inputor;
}
Mirror.prototype.mirrorCss = function() {
var css,
_this = this;
css = {
position: 'absolute',
left: -9999,
top: 0,
zIndex: -20000
};
if (this.$inputor.prop('tagName') === 'TEXTAREA') {
this.css_attr.push('width');
}
$.each(this.css_attr, function(i, p) {
return css[p] = _this.$inputor.css(p);
});
return css;
};
Mirror.prototype.create = function(html) {
this.$mirror = $('<div></div>');
this.$mirror.css(this.mirrorCss());
this.$mirror.html(html);
this.$inputor.after(this.$mirror);
return this;
};
Mirror.prototype.rect = function() {
var $flag, pos, rect;
$flag = this.$mirror.find("#caret");
pos = $flag.position();
rect = {
left: pos.left,
top: pos.top,
height: $flag.height()
};
this.$mirror.remove();
return rect;
};
return Mirror;
})();
Utils = {
contentEditable: function($inputor) {
return !!($inputor[0].contentEditable && $inputor[0].contentEditable === 'true');
}
};
methods = {
pos: function(pos) {
if (pos || pos === 0) {
return this.setPos(pos);
} else {
return this.getPos();
}
},
position: function(pos) {
if (oDocument.selection) {
return this.getIEPosition(pos);
} else {
return this.getPosition(pos);
}
},
offset: function(pos) {
var offset;
offset = this.getOffset(pos);
return offset;
}
};
oDocument = null;
oWindow = null;
oFrame = null;
setContextBy = function(settings) {
var iframe;
if (iframe = settings != null ? settings.iframe : void 0) {
oFrame = iframe;
oWindow = iframe.contentWindow;
return oDocument = iframe.contentDocument || oWindow.document;
} else {
oFrame = void 0;
oWindow = window;
return oDocument = document;
}
};
discoveryIframeOf = function($dom) {
var error;
oDocument = $dom[0].ownerDocument;
oWindow = oDocument.defaultView || oDocument.parentWindow;
try {
return oFrame = oWindow.frameElement;
} catch (_error) {
error = _error;
}
};
$.fn.caret = function(method, value, settings) {
var caret;
if (methods[method]) {
if ($.isPlainObject(value)) {
setContextBy(value);
value = void 0;
} else {
setContextBy(settings);
}
caret = Utils.contentEditable(this) ? new EditableCaret(this) : new InputCaret(this);
return methods[method].apply(caret, [value]);
} else {
return $.error("Method " + method + " does not exist on jQuery.caret");
}
};
$.fn.caret.EditableCaret = EditableCaret;
$.fn.caret.InputCaret = InputCaret;
$.fn.caret.Utils = Utils;
return $.fn.caret.apis = methods;
});
}).call(this);
|
gpl-2.0
|
nicholasio/CursoPHPVolumeIII
|
mod_2/aula_04_php56/constants.php
|
560
|
<?php
const ONE = 1;
const TWO = ONE * 2; //As constantes podem ser inicializadas com expressรตes
class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '. self::THREE;
//Os argumentos default das funรงรตes/mรฉtodos tambรฉm
public function f($a = ONE + self::THREE) {
return $a;
}
}
// Essa sintaxe foi introduzida no PHP 5.5
echo (new C)->f()."\n";
echo C::SENTENCE;
echo '<br />';
//Tambรฉm podemos definir um array constante
const ARR = ['a', 'b'];
echo ARR[0];
|
gpl-2.0
|
joelbrock/PFC_CORE
|
fannie/item/EditItemsFromSearch.php
|
12767
|
<?php
/*******************************************************************************
Copyright 2013 Whole Foods Community Co-op
This file is part of Fannie.
Fannie 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.
Fannie 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
in the file license.txt along with IT CORE; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*********************************************************************************/
include('../config.php');
include_once($FANNIE_ROOT.'classlib2.0/FannieAPI.php');
class EditItemsFromSearch extends FannieRESTfulPage
{
protected $header = 'Edit Search Results';
protected $title = 'Edit Search Results';
protected $window_dressing = false;
private $upcs = array();
private $save_results = array();
function preprocess()
{
$this->__routes[] = 'post<u>';
$this->__routes[] = 'post<save>';
return parent::preprocess();
}
function post_save_handler()
{
global $FANNIE_OP_DB;
$upcs = FormLib::get('upc', array());
if (!is_array($upcs) || empty($upcs)) {
echo 'Error: invalid data';
return false;
}
$dept = FormLib::get('dept');
$tax = FormLib::get('tax');
$local = FormLib::get('local');
$brand = FormLib::get('brand');
$vendor = FormLib::get('vendor');
$dbc = FannieDB::get($FANNIE_OP_DB);
for($i=0; $i<count($upcs); $i++) {
$model = new ProductsModel($dbc);
$upc = BarcodeLib::padUPC($upcs[$i]);
$model->upc($upc);
if (isset($dept[$i])) {
$model->department($dept[$i]);
}
if (isset($tax[$i])) {
$model->tax($tax[$i]);
}
if (isset($local[$i])) {
$model->local($local[$i]);
}
if (in_array($upc, FormLib::get('fs', array()))) {
$model->foodstamp(1);
} else {
$model->foodstamp(0);
}
if (in_array($upc, FormLib::get('disc', array()))) {
$model->discount(1);
} else {
$model->discount(0);
}
if (in_array($upc, FormLib::get('scale', array()))) {
$model->scale(1);
} else {
$model->scale(0);
}
$model->modified(date('Y-m-d H:i:s'));
$try = $model->save();
if ($try) {
$model->pushToLanes();
} else {
$this->save_results[] = 'Error saving item '.$upc;
}
if ((isset($vendor[$i]) && $vendor[$i] != '') || (isset($brand[$i]) && $brand[$i] != '')) {
$extra = new ProdExtraModel($dbc);
$extra->upc($upc);
if (isset($vendor[$i]) && $vendor[$i] != '') {
$extra->distributor($vendor[$i]);
}
if (isset($brand[$i]) && $brand[$i] != '') {
$extra->manufacturer($brand[$i]);
}
$extra->save();
}
$this->upcs[] = $upc;
}
return true;
}
function post_save_view()
{
$ret = '';
if (!empty($this->save_results)) {
$ret .= '<ul style="color:red;">';
foreach($this->save_results as $msg) {
$ret .= '<li>' . $msg . '</li>';
}
$ret .= '</ul>';
} else {
$ret .= '<ul style="color:green;"><li>Saved!</li></ul>';
}
return $ret . $this->post_u_view();
}
function post_u_handler()
{
if (!is_array($this->u)) {
$this->u = array($this->u);
}
foreach($this->u as $postdata) {
if (is_numeric($postdata)) {
$this->upcs[] = BarcodeLib::padUPC($postdata);
}
}
if (empty($this->upcs)) {
echo 'Error: no valid data';
return false;
} else {
return true;
}
}
function post_u_view()
{
global $FANNIE_OP_DB, $FANNIE_URL;
$this->add_script($FANNIE_URL.'/src/jquery/jquery.js');
$this->add_css_file($FANNIE_URL.'/src/style.css');
$ret = '';
$dbc = FannieDB::get($FANNIE_OP_DB);
$taxes = array(0 => 'NoTax');
$taxerates = $dbc->query('SELECT id, description FROM taxrates');
while($row = $dbc->fetch_row($taxerates)) {
$taxes[$row['id']] = $row['description'];
}
$locales = array(0 => 'No');
$origins = $dbc->query('SELECT originID, shortName FROM originName WHERE local=1');
while($row = $dbc->fetch_row($origins)) {
$locales[$row['originID']] = $row['shortName'];
}
$depts = array();
$deptlist = $dbc->query('SELECT dept_no, dept_name FROM departments ORDER BY dept_no');
while($row = $dbc->fetch_row($deptlist)) {
$depts[$row['dept_no']] = $row['dept_name'];
}
$ret .= '<form action="EditItemsFromSearch.php" method="post">';
$ret .= '<table cellpadding="4" cellspacing="0" border="1">';
$ret .= '<tr>
<th>UPC</th>
<th>Description</th>
<th>Brand</th>
<th>Vendor</th>
<th>Department</th>
<th>Tax</th>
<th>FS</th>
<th>Scale</th>
<th>Discountable</th>
<th>Local</th>
</tr>';
$ret .= '<tr><th colspan="2">Change All <input type="reset" /></th>';
/**
List known brands from vendorItems as a drop down selection
rather than free text entry. prodExtra remains an imperfect
solution but this can at least start normalizing that data
*/
$ret .= '<td><select onchange="updateAll(this.value, \'.brandField\');">';
$ret .= '<option value=""></option>';
$brands = $dbc->query('SELECT brand FROM vendorItems
WHERE brand IS NOT NULL AND brand <> \'\'
GROUP BY brand ORDER BY brand');
while($row = $dbc->fetch_row($brands)) {
$ret .= '<option>' . $row['brand'] . '</option>';
}
$ret .= '</select></td>';
/**
See brand above
*/
$ret .= '<td><select onchange="updateAll(this.value, \'.vendorField\');">';
$ret .= '<option value=""></option><option>DIRECT</option>';
$vendors = $dbc->query('SELECT vendorName FROM vendors
GROUP BY vendorName ORDER BY vendorName');
while($row = $dbc->fetch_row($vendors)) {
$ret .= '<option>' . $row['vendorName'] . '</option>';
}
$ret .= '</select></td>';
$ret .= '<td><select onchange="updateAll(this.value, \'.deptSelect\');">';
foreach($depts as $num => $name) {
$ret .= sprintf('<option value="%d">%d %s</option>', $num, $num, $name);
}
$ret .= '</select></td>';
$ret .= '<td><select onchange="updateAll(this.value, \'.taxSelect\');">';
foreach($taxes as $num => $name) {
$ret .= sprintf('<option value="%d">%s</option>', $num, $name);
}
$ret .= '</select></td>';
$ret .= '<td><input type="checkbox" onchange="toggleAll(this, \'.fsCheckBox\');" /></td>';
$ret .= '<td><input type="checkbox" onchange="toggleAll(this, \'.scaleCheckBox\');" /></td>';
$ret .= '<td><input type="checkbox" onchange="toggleAll(this, \'.discCheckBox\');" /></td>';
$ret .= '<td><select onchange="updateAll(this.value, \'.localSelect\');">';
foreach($locales as $num => $name) {
$ret .= sprintf('<option value="%d">%s</option>', $num, $name);
}
$ret .= '</select></td>';
$ret .= '</tr>';
$info = $this->arrayToParams($this->upcs);
$query = 'SELECT p.upc, p.description, p.department, d.dept_name,
p.tax, p.foodstamp, p.discount, p.scale, p.local,
x.manufacturer, x.distributor
FROM products AS p
LEFT JOIN departments AS d ON p.department=d.dept_no
LEFT JOIN prodExtra AS x ON p.upc=x.upc
WHERE p.upc IN (' . $info['in'] . ')
ORDER BY p.upc';
$prep = $dbc->prepare($query);
$result = $dbc->execute($prep, $info['args']);
while($row = $dbc->fetch_row($result)) {
$deptOpts = '';
foreach($depts as $num => $name) {
$deptOpts .= sprintf('<option %s value="%d">%d %s</option>',
($num == $row['department'] ? 'selected' : ''),
$num, $num, $name);
}
$taxOpts = '';
foreach($taxes as $num => $name) {
$taxOpts .= sprintf('<option %s value="%d">%s</option>',
($num == $row['tax'] ? 'selected' : ''),
$num, $name);
}
$localOpts = '';
foreach($locales as $num => $name) {
$localOpts .= sprintf('<option %s value="%d">%s</option>',
($num == $row['local'] ? 'selected' : ''),
$num, $name);
}
$ret .= sprintf('<tr>
<td>
<a href="ItemEditorPage.php?searchupc=%s" target="_edit%s">%s</a>
<input type="hidden" class="upcInput" name="upc[]" value="%s" />
</td>
<td>%s</td>
<td><input type="text" name="brand[]" class="brandField" value="%s" /></td>
<td><input type="text" name="vendor[]" class="vendorField" value="%s" /></td>
<td><select name="dept[]" class="deptSelect">%s</select></td>
<td><select name="tax[]" class="taxSelect">%s</select></td>
<td><input type="checkbox" name="fs[]" class="fsCheckBox" value="%s" %s /></td>
<td><input type="checkbox" name="scale[]" class="scaleCheckBox" value="%s" %s /></td>
<td><input type="checkbox" name="disc[]" class="discCheckBox" value="%s" %s /></td>
<td><select name="local[]" class="localSelect">%s</select></td>
</tr>',
$row['upc'], $row['upc'], $row['upc'],
$row['upc'],
$row['description'],
$row['manufacturer'],
$row['distributor'],
$deptOpts,
$taxOpts,
$row['upc'], ($row['foodstamp'] == 1 ? 'checked' : ''),
$row['upc'], ($row['scale'] == 1 ? 'checked' : ''),
$row['upc'], ($row['discount'] == 1 ? 'checked' : ''),
$localOpts
);
}
$ret .= '</table>';
$ret .= '<br />';
$ret .= '<input type="submit" name="save" value="Save Changes" />';
$ret .= '</form>';
return $ret;
}
function javascript_content()
{
ob_start();
?>
function toggleAll(elem, selector) {
if (elem.checked) {
$(selector).attr('checked', true);
} else {
$(selector).attr('checked', false);
}
}
function updateAll(val, selector) {
$(selector).val(val);
}
<?php
return ob_get_clean();
}
private function arrayToParams($arr) {
$str = '';
$args = array();
foreach($arr as $entry) {
$str .= '?,';
$args[] = $entry;
}
$str = substr($str, 0, strlen($str)-1);
return array('in'=>$str, 'args'=>$args);
}
}
FannieDispatch::conditionalExec();
|
gpl-2.0
|
zsebtanar/zsebtanar-proto
|
src/client/generic/hooks/fetchData.ts
|
2209
|
import { useReducer, Reducer, useEffect, DependencyList } from 'react'
type States = 'pending' | 'loading' | 'success' | 'noResult' | 'error'
interface State<T> {
state: States
error?: Error
result?: T
}
interface Getters {
readonly isPending: boolean
readonly isLoading: boolean
readonly hasError: boolean
readonly isSuccess: boolean
readonly hasNoResult: boolean
}
export interface FetchDataAPI<T> extends State<T>, Getters {}
type Action<T> =
| { type: 'loading' }
| { type: 'success'; payload: { result: T; isEmpty: boolean } }
| { type: 'error'; payload: Error }
interface Options<T> {
isEmpty(data: T): boolean
}
///
const initState: State<never> = {
state: 'pending',
}
export function useFetchData<T>(
loaderFn: () => Promise<T>,
deps: DependencyList = [],
options?: Options<T>,
): FetchDataAPI<T> {
const [state, dispatch] = useReducer<Reducer<State<T>, Action<T>>>(userReducer, initState)
useEffect(() => {
dispatch({ type: 'loading' })
loaderFn()
.then((result) =>
dispatch({
type: 'success',
payload: { result, isEmpty: options?.isEmpty?.(result) ?? isEmpty(result) },
}),
)
.catch((error) => dispatch({ type: 'error', payload: error }))
}, [options?.isEmpty, ...deps])
return {
...state,
get isPending() {
return state.state === 'pending'
},
get isLoading() {
return state.state === 'loading'
},
get hasError() {
return state.state === 'error'
},
get isSuccess() {
return state.state === 'success'
},
get hasNoResult() {
return state.state === 'noResult'
},
}
}
///
function userReducer<T>(state: State<T>, action: Action<T>): State<T> {
switch (action.type) {
case 'loading':
return { state: 'loading', result: undefined, error: undefined }
case 'error':
return { state: 'error', error: action.payload, result: undefined }
case 'success': {
const { result, isEmpty } = action.payload
return { state: isEmpty ? 'noResult' : 'success', error: undefined, result }
}
}
}
///
function isEmpty<T>(data: T) {
return data === undefined || data?.['length'] === 0
}
|
gpl-2.0
|
markosa/hydromon
|
src/main/java/net/hydromon/core/controller/ViewController.java
|
6032
|
package net.hydromon.core.controller;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import net.hydromon.core.dto.SensorDTO;
import net.hydromon.core.dto.SensorValueDTO;
import net.hydromon.core.dto.StatisticsDTO;
import net.hydromon.core.dto.util.DTOUtils;
import net.hydromon.core.dto.util.TimeformatUtil;
import net.hydromon.core.model.Sensor;
import net.hydromon.core.model.SensorValue;
import net.hydromon.core.model.User;
import net.hydromon.core.service.SensorService;
import net.hydromon.core.service.UserService;
import net.hydromon.core.service.ValueService;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Controller
@RequestMapping(value = "/")
public class ViewController {
@Autowired
private SensorService sensorService;
@Autowired
private ValueService valueService;
@Autowired
private UserService userService;
@Autowired
private DTOUtils dtoUtil;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "redirect:/user/markos";
}
public static final int DAY_RESOLUTION = 1; // Select every row = 1 min
// resolution
public static final int WEEK_RESOLUTION = 60; // Select every 60th row = 60
// min resolution
public static final int MONTH_RESOLUTION = 240; // 4 hour resolution
@RequestMapping(value = "/user/{uid}", method = RequestMethod.GET)
public ModelAndView listSensors(@PathVariable String uid) {
ModelAndView mav = new ModelAndView("sensor-list");
User user = userService.getUser(uid);
List<SensorDTO> sensorsDTO = new ArrayList<SensorDTO>();
if (user != null) {
mav.addObject("uid", uid);
List<Sensor> sensors = sensorService.getSensors(user);
for (Sensor s : sensors) {
SensorDTO dto = dtoUtil.convert(s);
dto.setStatus("OK");
dto.setLatestValues(valueService.getLatestSensorValues(s, 3));
SensorValue v = valueService.getLatestSensorValue(s);
if (v != null) {
dto.setLatestValue(v.getValue());
dto.setLatestValueTime(TimeformatUtil.formatDate(v.getTimestamp()));
}
sensorsDTO.add(dto);
}
}
mav.addObject("sensors", sensorsDTO);
return mav;
}
@RequestMapping(value = "/user/{uid}/{id}", method = RequestMethod.GET)
public ModelAndView listValues(@PathVariable String uid, @PathVariable Long id) {
ModelAndView mav = new ModelAndView("sensor-values");
mav.addObject("uid", uid);
User user = userService.getUser(uid);
List<SensorDTO> sensorsDTO = new ArrayList<SensorDTO>();
if (user != null) {
List<Sensor> sensors = sensorService.getSensors(user);
for (Sensor s : sensors) {
SensorDTO dto = dtoUtil.convert(s);
dto.setStatus("OK");
dto.setLatestValues(valueService.getLatestSensorValues(s, 3));
SensorValue v = valueService.getLatestSensorValue(s);
if (v != null) {
dto.setLatestValue(v.getValue());
dto.setLatestValueTime(TimeformatUtil.formatDate(v.getTimestamp()));
}
sensorsDTO.add(dto);
}
}
mav.addObject("sensors", sensorsDTO);
mav.addAllObjects(listValues(id).getModel());
return mav;
}
@RequestMapping(value = "/sensor/{id}", method = RequestMethod.GET)
public ModelAndView listValues(@PathVariable Long id) {
ModelAndView mav = new ModelAndView("sensor-values");
Sensor sensor = sensorService.getSensor(id);
Timestamp now = new Timestamp(new Date().getTime());
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -1);
Timestamp tsDay = new Timestamp(cal.getTimeInMillis());
cal.setTimeInMillis(now.getTime());
cal.add(Calendar.DAY_OF_YEAR, -7);
Timestamp tsWeek = new Timestamp(cal.getTimeInMillis());
cal.setTimeInMillis(now.getTime());
cal.add(Calendar.MONTH, -1);
Timestamp tsMonth = new Timestamp(cal.getTimeInMillis());
List<SensorValue> values = valueService.getValues(sensor, tsMonth, now);
List<SensorValueDTO> day = new ArrayList<SensorValueDTO>();
List<SensorValueDTO> week = new ArrayList<SensorValueDTO>();
List<SensorValueDTO> month = new ArrayList<SensorValueDTO>();
for (SensorValue value : values) {
if (value.getTimestamp().after(tsDay))
day.add(new SensorValueDTO(id, value.getValue(), value.getTimestamp().getTime()));
if (value.getTimestamp().after(tsWeek))
week.add(new SensorValueDTO(id, value.getValue(), value.getTimestamp().getTime()));
if (value.getTimestamp().after(tsMonth))
month.add(new SensorValueDTO(id, value.getValue(), value.getTimestamp().getTime()));
}
SensorDTO sensorDTO = dtoUtil.convert(sensor);
mav.addObject("sensor", sensorDTO);
mav.addObject("dayValues", day);
mav.addObject("dayStatistics", calculateStatistics(day));
mav.addObject("weekValues", week);
mav.addObject("weekStatistics", calculateStatistics(week));
mav.addObject("monthValues", month);
mav.addObject("monthStatistics", calculateStatistics(month));
return mav;
}
private StatisticsDTO calculateStatistics(List<SensorValueDTO> values) {
if (values != null && values.size() > 0) {
StatisticsDTO s = new StatisticsDTO();
s.setMax(Collections.max(values, new SensorValueComparator()).getValue());
s.setMin(Collections.min(values, new SensorValueComparator()).getValue());
Float total = 0f;
for (SensorValueDTO dto : values) {
total += new Float(dto.getValue());
}
s.setAvg(new Float(total / values.size()).toString());
return s;
}
return null;
}
}
class SensorValueComparator implements Comparator<SensorValueDTO> {
public int compare(SensorValueDTO o1, SensorValueDTO o2) {
return new Float(o1.getValue()).compareTo(new Float(o2.getValue()));
}
}
|
gpl-2.0
|
Nate23k/Candentis
|
src/main/java/com/nate23k/candentis/utility/LogHelper.java
|
958
|
package com.nate23k.candentis.utility;
import com.nate23k.candentis.reference.Reference;
import cpw.mods.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
/**
* Created on 3/25/2015.
*/
public class LogHelper
{
public static void log(Level logLevel, Object object)
{
FMLLog.log(Reference.MOD_NAME, logLevel, String.valueOf(object));
}
public static void all(Object object) { log(Level.ALL, object); }
public static void debug(Object object) { log(Level.DEBUG, object); }
public static void error(Object object) { log(Level.ERROR, object); }
public static void fatal(Object object) { log(Level.FATAL, object); }
public static void info(Object object) { log(Level.INFO, object); }
public static void off(Object object) { log(Level.OFF, object); }
public static void trace(Object object) { log(Level.TRACE, object); }
public static void warn(Object object) { log(Level.WARN, object); }
}
|
gpl-2.0
|
worden-lee/mediawiki-core
|
includes/media/MediaHandler.php
|
17812
|
<?php
/**
* Media-handling base classes and generic functionality.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Media
*/
/**
* Base media handler class
*
* @ingroup Media
*/
abstract class MediaHandler {
const TRANSFORM_LATER = 1;
const METADATA_GOOD = true;
const METADATA_BAD = false;
const METADATA_COMPATIBLE = 2; // for old but backwards compatible.
/**
* Instance cache
*/
static $handlers = array();
/**
* Get a MediaHandler for a given MIME type from the instance cache
*
* @param $type string
*
* @return MediaHandler
*/
static function getHandler( $type ) {
global $wgMediaHandlers;
if ( !isset( $wgMediaHandlers[$type] ) ) {
wfDebug( __METHOD__ . ": no handler found for $type.\n" );
return false;
}
$class = $wgMediaHandlers[$type];
if ( !isset( self::$handlers[$class] ) ) {
self::$handlers[$class] = new $class;
if ( !self::$handlers[$class]->isEnabled() ) {
self::$handlers[$class] = false;
}
}
return self::$handlers[$class];
}
/**
* Get an associative array mapping magic word IDs to parameter names.
* Will be used by the parser to identify parameters.
*/
abstract function getParamMap();
/**
* Validate a thumbnail parameter at parse time.
* Return true to accept the parameter, and false to reject it.
* If you return false, the parser will do something quiet and forgiving.
*
* @param $name
* @param $value
*/
abstract function validateParam( $name, $value );
/**
* Merge a parameter array into a string appropriate for inclusion in filenames
*
* @param $params array
*/
abstract function makeParamString( $params );
/**
* Parse a param string made with makeParamString back into an array
*
* @param $str string
*/
abstract function parseParamString( $str );
/**
* Changes the parameter array as necessary, ready for transformation.
* Should be idempotent.
* Returns false if the parameters are unacceptable and the transform should fail
* @param $image
* @param $params
*/
abstract function normaliseParams( $image, &$params );
/**
* Get an image size array like that returned by getimagesize(), or false if it
* can't be determined.
*
* @param $image File: the image object, or false if there isn't one
* @param string $path the filename
* @return Array Follow the format of PHP getimagesize() internal function. See http://www.php.net/getimagesize
*/
abstract function getImageSize( $image, $path );
/**
* Get handler-specific metadata which will be saved in the img_metadata field.
*
* @param $image File: the image object, or false if there isn't one.
* Warning, FSFile::getPropsFromPath might pass an (object)array() instead (!)
* @param string $path the filename
* @return String
*/
function getMetadata( $image, $path ) {
return '';
}
/**
* Get metadata version.
*
* This is not used for validating metadata, this is used for the api when returning
* metadata, since api content formats should stay the same over time, and so things
* using ForiegnApiRepo can keep backwards compatibility
*
* All core media handlers share a common version number, and extensions can
* use the GetMetadataVersion hook to append to the array (they should append a unique
* string so not to get confusing). If there was a media handler named 'foo' with metadata
* version 3 it might add to the end of the array the element 'foo=3'. if the core metadata
* version is 2, the end version string would look like '2;foo=3'.
*
* @return string version string
*/
static function getMetadataVersion() {
$version = Array( '2' ); // core metadata version
wfRunHooks( 'GetMetadataVersion', Array( &$version ) );
return implode( ';', $version );
}
/**
* Convert metadata version.
*
* By default just returns $metadata, but can be used to allow
* media handlers to convert between metadata versions.
*
* @param $metadata Mixed String or Array metadata array (serialized if string)
* @param $version Integer target version
* @return Array serialized metadata in specified version, or $metadata on fail.
*/
function convertMetadataVersion( $metadata, $version = 1 ) {
if ( !is_array( $metadata ) ) {
//unserialize to keep return parameter consistent.
wfSuppressWarnings();
$ret = unserialize( $metadata );
wfRestoreWarnings();
return $ret;
}
return $metadata;
}
/**
* Get a string describing the type of metadata, for display purposes.
*
* @return string
*/
function getMetadataType( $image ) {
return false;
}
/**
* Check if the metadata string is valid for this handler.
* If it returns MediaHandler::METADATA_BAD (or false), Image
* will reload the metadata from the file and update the database.
* MediaHandler::METADATA_GOOD for if the metadata is a-ok,
* MediaHanlder::METADATA_COMPATIBLE if metadata is old but backwards
* compatible (which may or may not trigger a metadata reload).
* @return bool
*/
function isMetadataValid( $image, $metadata ) {
return self::METADATA_GOOD;
}
/**
* Get a MediaTransformOutput object representing an alternate of the transformed
* output which will call an intermediary thumbnail assist script.
*
* Used when the repository has a thumbnailScriptUrl option configured.
*
* Return false to fall back to the regular getTransform().
* @return bool
*/
function getScriptedTransform( $image, $script, $params ) {
return false;
}
/**
* Get a MediaTransformOutput object representing the transformed output. Does not
* actually do the transform.
*
* @param $image File: the image object
* @param string $dstPath filesystem destination path
* @param string $dstUrl Destination URL to use in output HTML
* @param array $params Arbitrary set of parameters validated by $this->validateParam()
* @return MediaTransformOutput
*/
final function getTransform( $image, $dstPath, $dstUrl, $params ) {
return $this->doTransform( $image, $dstPath, $dstUrl, $params, self::TRANSFORM_LATER );
}
/**
* Get a MediaTransformOutput object representing the transformed output. Does the
* transform unless $flags contains self::TRANSFORM_LATER.
*
* @param $image File: the image object
* @param string $dstPath filesystem destination path
* @param string $dstUrl destination URL to use in output HTML
* @param array $params arbitrary set of parameters validated by $this->validateParam()
* @param $flags Integer: a bitfield, may contain self::TRANSFORM_LATER
*
* @return MediaTransformOutput
*/
abstract function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 );
/**
* Get the thumbnail extension and MIME type for a given source MIME type
* @return array thumbnail extension and MIME type
*/
function getThumbType( $ext, $mime, $params = null ) {
$magic = MimeMagic::singleton();
if ( !$ext || $magic->isMatchingExtension( $ext, $mime ) === false ) {
// The extension is not valid for this mime type and we do
// recognize the mime type
$extensions = $magic->getExtensionsForType( $mime );
if ( $extensions ) {
return array( strtok( $extensions, ' ' ), $mime );
}
}
// The extension is correct (true) or the mime type is unknown to
// MediaWiki (null)
return array( $ext, $mime );
}
/**
* Get useful response headers for GET/HEAD requests for a file with the given metadata
* @param $metadata mixed Result of the getMetadata() function of this handler for a file
* @return Array
*/
public function getStreamHeaders( $metadata ) {
return array();
}
/**
* True if the handled types can be transformed
* @return bool
*/
function canRender( $file ) {
return true;
}
/**
* True if handled types cannot be displayed directly in a browser
* but can be rendered
* @return bool
*/
function mustRender( $file ) {
return false;
}
/**
* True if the type has multi-page capabilities
* @return bool
*/
function isMultiPage( $file ) {
return false;
}
/**
* Page count for a multi-page document, false if unsupported or unknown
* @return bool
*/
function pageCount( $file ) {
return false;
}
/**
* The material is vectorized and thus scaling is lossless
* @return bool
*/
function isVectorized( $file ) {
return false;
}
/**
* The material is an image, and is animated.
* In particular, video material need not return true.
* @note Before 1.20, this was a method of ImageHandler only
* @return bool
*/
function isAnimatedImage( $file ) {
return false;
}
/**
* If the material is animated, we can animate the thumbnail
* @since 1.20
* @return bool If material is not animated, handler may return any value.
*/
function canAnimateThumbnail( $file ) {
return true;
}
/**
* False if the handler is disabled for all files
* @return bool
*/
function isEnabled() {
return true;
}
/**
* Get an associative array of page dimensions
* Currently "width" and "height" are understood, but this might be
* expanded in the future.
* Returns false if unknown or if the document is not multi-page.
*
* @param $image File
* @param $page Unused, left for backcompatibility?
* @return array
*/
function getPageDimensions( $image, $page ) {
$gis = $this->getImageSize( $image, $image->getLocalRefPath() );
return array(
'width' => $gis[0],
'height' => $gis[1]
);
}
/**
* Generic getter for text layer.
* Currently overloaded by PDF and DjVu handlers
* @return bool
*/
function getPageText( $image, $page ) {
return false;
}
/**
* Get an array structure that looks like this:
*
* array(
* 'visible' => array(
* 'Human-readable name' => 'Human readable value',
* ...
* ),
* 'collapsed' => array(
* 'Human-readable name' => 'Human readable value',
* ...
* )
* )
* The UI will format this into a table where the visible fields are always
* visible, and the collapsed fields are optionally visible.
*
* The function should return false if there is no metadata to display.
*/
/**
* @todo FIXME: I don't really like this interface, it's not very flexible
* I think the media handler should generate HTML instead. It can do
* all the formatting according to some standard. That makes it possible
* to do things like visual indication of grouped and chained streams
* in ogg container files.
* @return bool
*/
function formatMetadata( $image ) {
return false;
}
/** sorts the visible/invisible field.
* Split off from ImageHandler::formatMetadata, as used by more than
* one type of handler.
*
* This is used by the media handlers that use the FormatMetadata class
*
* @param array $metadataArray metadata array
* @return array for use displaying metadata.
*/
function formatMetadataHelper( $metadataArray ) {
$result = array(
'visible' => array(),
'collapsed' => array()
);
$formatted = FormatMetadata::getFormattedData( $metadataArray );
// Sort fields into visible and collapsed
$visibleFields = $this->visibleMetadataFields();
foreach ( $formatted as $name => $value ) {
$tag = strtolower( $name );
self::addMeta( $result,
in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
'exif',
$tag,
$value
);
}
return $result;
}
/**
* Get a list of metadata items which should be displayed when
* the metadata table is collapsed.
*
* @return array of strings
* @access protected
*/
function visibleMetadataFields() {
$fields = array();
$lines = explode( "\n", wfMessage( 'metadata-fields' )->inContentLanguage()->text() );
foreach ( $lines as $line ) {
$matches = array();
if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
$fields[] = $matches[1];
}
}
$fields = array_map( 'strtolower', $fields );
return $fields;
}
/**
* This is used to generate an array element for each metadata value
* That array is then used to generate the table of metadata values
* on the image page
*
* @param &$array Array An array containing elements for each type of visibility
* and each of those elements being an array of metadata items. This function adds
* a value to that array.
* @param string $visibility ('visible' or 'collapsed') if this value is hidden
* by default.
* @param string $type type of metadata tag (currently always 'exif')
* @param string $id the name of the metadata tag (like 'artist' for example).
* its name in the table displayed is the message "$type-$id" (Ex exif-artist ).
* @param string $value thingy goes into a wikitext table; it used to be escaped but
* that was incompatible with previous practise of customized display
* with wikitext formatting via messages such as 'exif-model-value'.
* So the escaping is taken back out, but generally this seems a confusing
* interface.
* @param string $param value to pass to the message for the name of the field
* as $1. Currently this parameter doesn't seem to ever be used.
*
* Note, everything here is passed through the parser later on (!)
*/
protected static function addMeta( &$array, $visibility, $type, $id, $value, $param = false ) {
$msg = wfMessage( "$type-$id", $param );
if ( $msg->exists() ) {
$name = $msg->text();
} else {
// This is for future compatibility when using instant commons.
// So as to not display as ugly a name if a new metadata
// property is defined that we don't know about
// (not a major issue since such a property would be collapsed
// by default).
wfDebug( __METHOD__ . ' Unknown metadata name: ' . $id . "\n" );
$name = wfEscapeWikiText( $id );
}
$array[$visibility][] = array(
'id' => "$type-$id",
'name' => $name,
'value' => $value
);
}
/**
* @param $file File
* @return string
*/
function getShortDesc( $file ) {
global $wgLang;
return htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
}
/**
* @param $file File
* @return string
*/
function getLongDesc( $file ) {
global $wgLang;
return wfMessage( 'file-info', htmlspecialchars( $wgLang->formatSize( $file->getSize() ) ),
$file->getMimeType() )->parse();
}
/**
* @param $file File
* @return string
*/
static function getGeneralShortDesc( $file ) {
global $wgLang;
return $wgLang->formatSize( $file->getSize() );
}
/**
* @param $file File
* @return string
*/
static function getGeneralLongDesc( $file ) {
global $wgLang;
return wfMessage( 'file-info', $wgLang->formatSize( $file->getSize() ),
$file->getMimeType() )->parse();
}
/**
* Calculate the largest thumbnail width for a given original file size
* such that the thumbnail's height is at most $maxHeight.
* @param $boxWidth Integer Width of the thumbnail box.
* @param $boxHeight Integer Height of the thumbnail box.
* @param $maxHeight Integer Maximum height expected for the thumbnail.
* @return Integer.
*/
public static function fitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
$idealWidth = $boxWidth * $maxHeight / $boxHeight;
$roundedUp = ceil( $idealWidth );
if ( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight ) {
return floor( $idealWidth );
} else {
return $roundedUp;
}
}
function getDimensionsString( $file ) {
return '';
}
/**
* Modify the parser object post-transform
*/
function parserTransformHook( $parser, $file ) {}
/**
* File validation hook called on upload.
*
* If the file at the given local path is not valid, or its MIME type does not
* match the handler class, a Status object should be returned containing
* relevant errors.
*
* @param string $fileName The local path to the file.
* @return Status object
*/
function verifyUpload( $fileName ) {
return Status::newGood();
}
/**
* Check for zero-sized thumbnails. These can be generated when
* no disk space is available or some other error occurs
*
* @param string $dstPath The location of the suspect file
* @param int $retval Return value of some shell process, file will be deleted if this is non-zero
* @return bool True if removed, false otherwise
*/
function removeBadFile( $dstPath, $retval = 0 ) {
if ( file_exists( $dstPath ) ) {
$thumbstat = stat( $dstPath );
if ( $thumbstat['size'] == 0 || $retval != 0 ) {
$result = unlink( $dstPath );
if ( $result ) {
wfDebugLog( 'thumbnail',
sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() succeeded',
$thumbstat['size'], $dstPath ) );
} else {
wfDebugLog( 'thumbnail',
sprintf( 'Removing bad %d-byte thumbnail "%s". unlink() failed',
$thumbstat['size'], $dstPath ) );
}
return true;
}
}
return false;
}
/**
* Remove files from the purge list
*
* @param array $files
* @param array $options
*/
public function filterThumbnailPurgeList( &$files, $options ) {
// Do nothing
}
/*
* True if the handler can rotate the media
* @since 1.21
* @return bool
*/
public static function canRotate() {
return false;
}
}
|
gpl-2.0
|
RoboMod/network-manager-ipop
|
kde/solidcontrolfuture/solid/networkmanager-0.9/accesspoint.cpp
|
6558
|
/*
Copyright 2008 Will Stephenson <wstephenson@kde.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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "accesspoint.h"
#include <KDebug>
#include "dbus/nm-access-pointinterface.h"
#include "manager.h"
#include "wirelessnetworkinterface.h"
class NMAccessPoint::Private
{
public:
Private( const QString & path ) : iface( NM_DBUS_SERVICE, path, QDBusConnection::systemBus()), capabilities(0), wpaFlags(0), rsnFlags(0), frequency(0), maxBitRate(0), mode((Solid::Control::WirelessNetworkInterfaceNm09::OperationMode)0), signalStrength(0)
{
}
OrgFreedesktopNetworkManagerAccessPointInterface iface;
QString uni;
Solid::Control::AccessPointNm09::Capabilities capabilities;
Solid::Control::AccessPointNm09::WpaFlags wpaFlags;
Solid::Control::AccessPointNm09::WpaFlags rsnFlags;
QString ssid;
QByteArray rawSsid;
uint frequency;
QString hardwareAddress;
uint maxBitRate;
Solid::Control::WirelessNetworkInterfaceNm09::OperationMode mode;
int signalStrength;
};
NMAccessPoint::NMAccessPoint( const QString& path, QObject * parent ) : Solid::Control::Ifaces::AccessPointNm09(parent), d(new Private( path ))
{
d->uni = path;
if (d->iface.isValid()) {
d->capabilities = convertCapabilities( d->iface.flags() );
d->wpaFlags = convertWpaFlags( d->iface.wpaFlags() );
d->rsnFlags = convertWpaFlags( d->iface.rsnFlags() );
d->signalStrength = d->iface.strength();
d->ssid = d->iface.ssid();
d->rawSsid = d->iface.ssid();
d->frequency = d->iface.frequency();
d->hardwareAddress = d->iface.hwAddress();
d->maxBitRate = d->iface.maxBitrate();
d->mode = NMWirelessNetworkInterface::convertOperationMode(d->iface.mode());
connect( &d->iface, SIGNAL(PropertiesChanged(QVariantMap)),
this, SLOT(propertiesChanged(QVariantMap)));
}
}
NMAccessPoint::~NMAccessPoint()
{
delete d;
}
QString NMAccessPoint::uni() const
{
return d->uni;
}
QString NMAccessPoint::hardwareAddress() const
{
return d->hardwareAddress;
}
Solid::Control::AccessPointNm09::Capabilities NMAccessPoint::capabilities() const
{
return d->capabilities;
}
Solid::Control::AccessPointNm09::WpaFlags NMAccessPoint::wpaFlags() const
{
return d->wpaFlags;
}
Solid::Control::AccessPointNm09::WpaFlags NMAccessPoint::rsnFlags() const
{
return d->rsnFlags;
}
QString NMAccessPoint::ssid() const
{
return d->ssid;
}
QByteArray NMAccessPoint::rawSsid() const
{
return d->rawSsid;
}
uint NMAccessPoint::frequency() const
{
return d->frequency;
}
uint NMAccessPoint::maxBitRate() const
{
return d->maxBitRate;
}
Solid::Control::WirelessNetworkInterfaceNm09::OperationMode NMAccessPoint::mode() const
{
return d->mode;
}
int NMAccessPoint::signalStrength() const
{
return d->signalStrength;
}
void NMAccessPoint::propertiesChanged(const QVariantMap &properties)
{
QStringList propKeys = properties.keys();
//kDebug(1441) << propKeys;
QLatin1String flagsKey("Flags"),
wpaFlagsKey("WpaFlags"),
rsnFlagsKey("RsnFlags"),
ssidKey("Ssid"),
freqKey("Frequency"),
hwAddrKey("HwAddress"),
modeKey("Mode"),
maxBitRateKey("MaxBitrate"),
strengthKey("Strength");
QVariantMap::const_iterator it = properties.find(flagsKey);
if (it != properties.end()) {
d->capabilities = convertCapabilities(it->toUInt());
propKeys.removeOne(flagsKey);
}
it = properties.find(wpaFlagsKey);
if (it != properties.end()) {
d->wpaFlags = convertWpaFlags(it->toUInt());
emit wpaFlagsChanged(d->wpaFlags);
propKeys.removeOne(wpaFlagsKey);
}
it = properties.find(rsnFlagsKey);
if (it != properties.end()) {
d->rsnFlags = convertWpaFlags(it->toUInt());
emit rsnFlagsChanged(d->rsnFlags);
propKeys.removeOne(rsnFlagsKey);
}
it = properties.find(ssidKey);
if (it != properties.end()) {
d->ssid = it->toByteArray();
emit ssidChanged(d->ssid);
propKeys.removeOne(ssidKey);
}
it = properties.find(freqKey);
if (it != properties.end()) {
d->frequency = it->toUInt();
emit frequencyChanged(d->frequency);
propKeys.removeOne(freqKey);
}
it = properties.find(hwAddrKey);
if (it != properties.end()) {
d->hardwareAddress = it->toString();
propKeys.removeOne(hwAddrKey);
}
it = properties.find(modeKey);
if (it != properties.end()) {
d->mode = NMWirelessNetworkInterface::convertOperationMode(it->toUInt());
propKeys.removeOne(modeKey);
}
it = properties.find(maxBitRateKey);
if (it != properties.end()) {
d->maxBitRate = it->toUInt();
emit bitRateChanged(d->maxBitRate);
propKeys.removeOne(maxBitRateKey);
}
it = properties.find(strengthKey);
if (it != properties.end()) {
d->signalStrength = it->toInt();
//kDebug(1441) << "UNI: " << d->uni << "MAC: " << d->hardwareAddress << "SignalStrength: " << d->signalStrength;
emit signalStrengthChanged(d->signalStrength);
propKeys.removeOne(strengthKey);
}
if (!propKeys.isEmpty()) {
kDebug(1441) << "Unhandled properties: " << propKeys;
}
}
Solid::Control::AccessPointNm09::Capabilities NMAccessPoint::convertCapabilities(int caps)
{
if ( 1 == caps ) {
return Solid::Control::AccessPointNm09::Privacy;
} else {
return 0;
}
}
Solid::Control::AccessPointNm09::WpaFlags NMAccessPoint::convertWpaFlags(uint theirFlags)
{
return (Solid::Control::AccessPointNm09::WpaFlags)theirFlags;
}
#include "accesspoint.moc"
|
gpl-2.0
|
timewall/RG-Stats
|
database.cpp
|
3127
|
/*
# 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.
*/
//test: test/database_main.cpp
#include "database.h"
std::string database::v_replace(std::string &s, std::string toReplace, std::string replaceWith) {
return(s.replace(s.find(toReplace), toReplace.length(), replaceWith));
}
database::database(std::string pg_db_data){
conn = tntdb::connect(pg_db_data);
}
tntdb::Connection database::get_conn(){
return conn;
}
std::string database::get_rows(std::string ntable){
std::string data;
conn.selectValue("SELECT COUNT(*) FROM " + ntable).get(data);
return data;
}
std::string database::get_table_size(std::string ntable){
std::string data;
conn.selectValue("SELECT pg_size_pretty(pg_relation_size('" + ntable + "'))").get(data);
return data;
}
std::string database::get_db_size(){
std::string data;
conn.selectValue("SELECT pg_size_pretty(pg_database_size('rg-stats'))").get(data);
return data;
}
std::string database::get_db_info(){
std::string db_info = "+---------------------------------------- \n"
"| Table: mp_all \n"
"+---------------------------------------- \n"
"| Number of Entries : =v1 \n"
"| Table Size : =v2 \n"
"+---------------------------------------- \n"
"+---------------------------------------- \n"
"| Table: mp_item_name \n"
"+---------------------------------------- \n"
"| Number of Entries : =v3 \n"
"| Table Size : =v4 \n"
"+---------------------------------------- \n"
"+---------------------------------------- \n"
"| Database Size : =v5 \n"
"+----------------------------------------";
db_info = v_replace(db_info, "=v1", get_rows("mp_all"));
db_info = v_replace(db_info, "=v2", get_table_size("mp_all"));
db_info = v_replace(db_info, "=v3", get_rows("mp_item_name"));
db_info = v_replace(db_info, "=v4", get_table_size("mp_item_name"));
db_info = v_replace(db_info, "=v5", get_db_size());
return db_info;
}
|
gpl-2.0
|
yanyitec/Yanyitec
|
src/Yanyitec/Testing/AssertUnhandledException.cs
|
642
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Yanyitec.Testing
{
public class AssertUnhandledException : AssertException
{
public AssertUnhandledException(Exception exception) {
this.UnhandledException = exception;
}
public Exception UnhandledException { get; private set; }
public override string AssertResult
{
get
{
return "Unexpect exception["+this.UnhandledException.GetType().FullName+"] is thrown : " + this.UnhandledException.Message;
}
}
}
}
|
gpl-2.0
|
palasthotel/grid-wordpress-box-social
|
vendor/google/apiclient-services/src/Google/Service/AdSense/Resource/AccountsAdclientsCustomchannels.php
|
3948
|
<?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.
*/
/**
* The "customchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new Google_Service_Adsense(...);
* $customchannels = $adsenseService->customchannels;
* </code>
*/
class Google_Service_Adsense_Resource_AccountsAdclientsCustomchannels extends Google_Service_Resource
{
/**
* Gets information about the selected custom channel. (customchannels.get)
*
* @param string $name Required. Name of the custom channel. Format:
* accounts/{account}/adclients/{adclient}/customchannels/{customchannel}
* @param array $optParams Optional parameters.
* @return Google_Service_Adsense_CustomChannel
*/
public function get($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Adsense_CustomChannel");
}
/**
* Lists all the custom channels available in an ad client.
* (customchannels.listAccountsAdclientsCustomchannels)
*
* @param string $parent Required. The ad client which owns the collection of
* custom channels. Format: accounts/{account}/adclients/{adclient}
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize The maximum number of custom channels to include in
* the response, used for paging. If unspecified, at most 10000 custom channels
* will be returned. The maximum value is 10000; values above 10000 will be
* coerced to 10000.
* @opt_param string pageToken A page token, received from a previous
* `ListCustomChannels` call. Provide this to retrieve the subsequent page. When
* paginating, all other parameters provided to `ListCustomChannels` must match
* the call that provided the page token.
* @return Google_Service_Adsense_ListCustomChannelsResponse
*/
public function listAccountsAdclientsCustomchannels($parent, $optParams = array())
{
$params = array('parent' => $parent);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Adsense_ListCustomChannelsResponse");
}
/**
* Lists all the ad units available for a custom channel.
* (customchannels.listLinkedAdUnits)
*
* @param string $parent Required. The custom channel which owns the collection
* of ad units. Format:
* accounts/{account}/adclients/{adclient}/customchannels/{customchannel}
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize The maximum number of ad units to include in the
* response, used for paging. If unspecified, at most 10000 ad units will be
* returned. The maximum value is 10000; values above 10000 will be coerced to
* 10000.
* @opt_param string pageToken A page token, received from a previous
* `ListLinkedAdUnits` call. Provide this to retrieve the subsequent page. When
* paginating, all other parameters provided to `ListLinkedAdUnits` must match
* the call that provided the page token.
* @return Google_Service_Adsense_ListLinkedAdUnitsResponse
*/
public function listLinkedAdUnits($parent, $optParams = array())
{
$params = array('parent' => $parent);
$params = array_merge($params, $optParams);
return $this->call('listLinkedAdUnits', array($params), "Google_Service_Adsense_ListLinkedAdUnitsResponse");
}
}
|
gpl-2.0
|
RomainGoussault/Deepov
|
src/Move.cpp
|
1796
|
/*
Deepov, a UCI chess playing engine.
Copyright (c) 20014-2016 Romain Goussault, Navid Hedjazian
Deepov 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.
Deepov 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 Deepov. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Move.hpp"
#include <iostream>
#include <sstream>
std::string Move::toShortString() const
{
// The move format is in long algebraic notation.
std::array<std::string,8> letters = {{"a", "b", "c", "d", "e", "f", "g", "h"}};
unsigned int xOrigin = getOrigin() % 8;
unsigned int yOrigin = (getOrigin() / 8)+1;
unsigned int xDestination = getDestination() % 8;
unsigned int yDestination = (getDestination() / 8)+1;
std::string promotionLetter = "";
if(isPromotion())
{
unsigned int promotedType = getFlags() - Move::PROMOTION_FLAG +1;
if(isCapture())
{
promotedType -= Move::CAPTURE_FLAG;
}
if(promotedType == Piece::KNIGHT)
{
promotionLetter = "n";
}
else if(promotedType == Piece::BISHOP)
{
promotionLetter = "b";
}
else if(promotedType == Piece::ROOK)
{
promotionLetter = "r";
}
else if(promotedType == Piece::QUEEN)
{
promotionLetter = "q";
}
}
std::stringstream ss;
ss << letters[xOrigin] << yOrigin << letters[xDestination] << yDestination << promotionLetter;
return ss.str();
}
|
gpl-2.0
|
vpelletier/neoppod
|
neo/storage/transactions.py
|
14480
|
#
# Copyright (C) 2010-2016 Nexedi SA
#
# 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/>.
from time import time
from neo.lib import logging
from neo.lib.util import dump
from neo.lib.protocol import ProtocolError, uuid_str, ZERO_TID
class ConflictError(Exception):
"""
Raised when a resolvable conflict occurs
Argument: tid of locking transaction or latest revision
"""
def __init__(self, tid):
Exception.__init__(self)
self._tid = tid
def getTID(self):
return self._tid
class DelayedError(Exception):
"""
Raised when an object is locked by a previous transaction
"""
class NotRegisteredError(Exception):
"""
Raised when a ttid is not registered
"""
class Transaction(object):
"""
Container for a pending transaction
"""
_tid = None
has_trans = False
def __init__(self, uuid, ttid):
self._uuid = uuid
self._ttid = ttid
self._object_dict = {}
self._locked = False
self._birth = time()
self._checked_set = set()
def __repr__(self):
return "<%s(ttid=%r, tid=%r, uuid=%r, locked=%r, age=%.2fs) at 0x%x>" \
% (self.__class__.__name__,
dump(self._ttid),
dump(self._tid),
uuid_str(self._uuid),
self.isLocked(),
time() - self._birth,
id(self))
def addCheckedObject(self, oid):
assert oid not in self._object_dict, dump(oid)
self._checked_set.add(oid)
def getTTID(self):
return self._ttid
def setTID(self, tid):
assert self._tid is None, dump(self._tid)
assert tid is not None
self._tid = tid
def getTID(self):
return self._tid
def getUUID(self):
return self._uuid
def lock(self):
assert not self._locked
self._locked = True
def isLocked(self):
return self._locked
def addObject(self, oid, data_id, value_serial):
"""
Add an object to the transaction
"""
assert oid not in self._checked_set, dump(oid)
self._object_dict[oid] = oid, data_id, value_serial
def delObject(self, oid):
try:
return self._object_dict.pop(oid)[1]
except KeyError:
self._checked_set.remove(oid)
def getObject(self, oid):
return self._object_dict[oid]
def getObjectList(self):
return self._object_dict.values()
def getOIDList(self):
return self._object_dict.keys()
def getLockedOIDList(self):
return self._object_dict.keys() + list(self._checked_set)
class TransactionManager(object):
"""
Manage pending transaction and locks
"""
def __init__(self, app):
self._app = app
self._transaction_dict = {}
self._store_lock_dict = {}
self._load_lock_dict = {}
self._uuid_dict = {}
def register(self, uuid, ttid):
"""
Register a transaction, it may be already registered
"""
logging.debug('Register TXN %s for %s', dump(ttid), uuid_str(uuid))
transaction = self._transaction_dict.get(ttid, None)
if transaction is None:
transaction = Transaction(uuid, ttid)
self._uuid_dict.setdefault(uuid, set()).add(transaction)
self._transaction_dict[ttid] = transaction
return transaction
def getObjectFromTransaction(self, ttid, oid):
"""
Return object data for given running transaction.
Return None if not found.
"""
try:
return self._transaction_dict[ttid].getObject(oid)
except KeyError:
return None
def reset(self):
"""
Reset the transaction manager
"""
self._transaction_dict.clear()
self._store_lock_dict.clear()
self._load_lock_dict.clear()
self._uuid_dict.clear()
def vote(self, ttid, txn_info=None):
"""
Store transaction information received from client node
"""
logging.debug('Vote TXN %s', dump(ttid))
transaction = self._transaction_dict[ttid]
object_list = transaction.getObjectList()
if txn_info:
user, desc, ext, oid_list = txn_info
txn_info = oid_list, user, desc, ext, False, ttid
transaction.has_trans = True
# store metadata to temporary table
dm = self._app.dm
dm.storeTransaction(ttid, object_list, txn_info)
dm.commit()
def lock(self, ttid, tid):
"""
Lock a transaction
"""
logging.debug('Lock TXN %s (ttid=%s)', dump(tid), dump(ttid))
try:
transaction = self._transaction_dict[ttid]
except KeyError:
raise ProtocolError("unknown ttid %s" % dump(ttid))
# remember that the transaction has been locked
transaction.lock()
self._load_lock_dict.update(
dict.fromkeys(transaction.getOIDList(), ttid))
# commit transaction and remember its definitive TID
if transaction.has_trans:
self._app.dm.lockTransaction(tid, ttid)
transaction.setTID(tid)
def unlock(self, ttid):
"""
Unlock transaction
"""
tid = self._transaction_dict[ttid].getTID()
logging.debug('Unlock TXN %s (ttid=%s)', dump(tid), dump(ttid))
dm = self._app.dm
dm.unlockTransaction(tid, ttid)
self._app.em.setTimeout(time() + 1, dm.deferCommit())
self.abort(ttid, even_if_locked=True)
def getFinalTID(self, ttid):
try:
return self._transaction_dict[ttid].getTID()
except KeyError:
return self._app.dm.getFinalTID(ttid)
def getLockingTID(self, oid):
return self._store_lock_dict.get(oid)
def lockObject(self, ttid, serial, oid, unlock=False):
"""
Take a write lock on given object, checking that "serial" is
current.
Raises:
DelayedError
ConflictError
"""
# check if the object if locked
locking_tid = self._store_lock_dict.get(oid)
if locking_tid == ttid and unlock:
logging.info('Deadlock resolution on %r:%r', dump(oid), dump(ttid))
# A duplicate store means client is resolving a deadlock, so
# drop the lock it held on this object, and drop object data for
# consistency.
del self._store_lock_dict[oid]
data_id = self._transaction_dict[ttid].delObject(oid)
if data_id:
self._app.dm.pruneData((data_id,))
# Give a chance to pending events to take that lock now.
self._app.executeQueuedEvents()
# Attemp to acquire lock again.
locking_tid = self._store_lock_dict.get(oid)
if locking_tid is None:
previous_serial = None
elif locking_tid == ttid:
# If previous store was an undo, next store must be based on
# undo target.
previous_serial = self._transaction_dict[ttid].getObject(oid)[2]
if previous_serial is None:
# XXX: use some special serial when previous store was not
# an undo ? Maybe it should just not happen.
logging.info('Transaction %s storing %s more than once',
dump(ttid), dump(oid))
elif locking_tid < ttid:
# We have a bigger TTID than locking transaction, so we are younger:
# enter waiting queue so we are handled when lock gets released.
# We also want to delay (instead of conflict) if the client is
# so faster that it is committing another transaction before we
# processed UnlockInformation from the master.
logging.info('Store delayed for %r:%r by %r', dump(oid),
dump(ttid), dump(locking_tid))
raise DelayedError
else:
# We have a smaller TTID than locking transaction, so we are older:
# this is a possible deadlock case, as we might already hold locks
# the younger transaction is waiting upon. Make client release
# locks & reacquire them by notifying it of the possible deadlock.
logging.info('Possible deadlock on %r:%r with %r',
dump(oid), dump(ttid), dump(locking_tid))
raise ConflictError(ZERO_TID)
if previous_serial is None:
previous_serial = self._app.dm.getLastObjectTID(oid)
if previous_serial is not None and previous_serial != serial:
logging.info('Resolvable conflict on %r:%r',
dump(oid), dump(ttid))
raise ConflictError(previous_serial)
logging.debug('Transaction %s storing %s', dump(ttid), dump(oid))
self._store_lock_dict[oid] = ttid
def checkCurrentSerial(self, ttid, serial, oid):
try:
transaction = self._transaction_dict[ttid]
except KeyError:
raise NotRegisteredError
self.lockObject(ttid, serial, oid, unlock=True)
transaction.addCheckedObject(oid)
def storeObject(self, ttid, serial, oid, compression, checksum, data,
value_serial, unlock=False):
"""
Store an object received from client node
"""
try:
transaction = self._transaction_dict[ttid]
except KeyError:
raise NotRegisteredError
self.lockObject(ttid, serial, oid, unlock=unlock)
# store object
if data is None:
data_id = None
else:
data_id = self._app.dm.holdData(checksum, data, compression)
transaction.addObject(oid, data_id, value_serial)
def abort(self, ttid, even_if_locked=False):
"""
Abort a transaction
Releases locks held on all transaction objects, deletes Transaction
instance, and executed queued events.
Note: does not alter persistent content.
"""
if ttid not in self._transaction_dict:
# the tid may be unknown as the transaction is aborted on every node
# of the partition, even if no data was received (eg. conflict on
# another node)
return
logging.debug('Abort TXN %s', dump(ttid))
transaction = self._transaction_dict[ttid]
has_load_lock = transaction.isLocked()
# if the transaction is locked, ensure we can drop it
if has_load_lock:
if not even_if_locked:
return
else:
self._app.dm.abortTransaction(ttid)
# unlock any object
for oid in transaction.getLockedOIDList():
if has_load_lock:
lock_ttid = self._load_lock_dict.pop(oid, None)
assert lock_ttid in (ttid, None), 'Transaction %s tried to ' \
'release the lock on oid %s, but it was held by %s' % (
dump(ttid), dump(oid), dump(lock_ttid))
write_locking_tid = self._store_lock_dict.pop(oid)
assert write_locking_tid == ttid, 'Inconsistent locking state: ' \
'aborting %s:%s but %s has the lock.' % (dump(ttid), dump(oid),
dump(write_locking_tid))
# remove the transaction
uuid = transaction.getUUID()
self._uuid_dict[uuid].discard(transaction)
# clean node index if there is no more current transactions
if not self._uuid_dict[uuid]:
del self._uuid_dict[uuid]
del self._transaction_dict[ttid]
# some locks were released, some pending locks may now succeed
self._app.executeQueuedEvents()
def abortFor(self, uuid):
"""
Abort any non-locked transaction of a node
"""
logging.debug('Abort for %s', uuid_str(uuid))
# BUG: Discarding voted transactions must only be a decision of the
# master, and for this, we'll need to review how transactions are
# aborted. As a workaround, we rely on the fact that lock() will
# disconnect from the master in case of LockInformation.
# abort any non-locked transaction of this node
for ttid in [x.getTTID() for x in self._uuid_dict.get(uuid, [])]:
self.abort(ttid)
# cleanup _uuid_dict if no transaction remains for this node
transaction_set = self._uuid_dict.get(uuid)
if transaction_set is not None and not transaction_set:
del self._uuid_dict[uuid]
def isLockedTid(self, tid):
for t in self._transaction_dict.itervalues():
if t.isLocked() and t.getTID() <= tid:
return True
return False
def loadLocked(self, oid):
return oid in self._load_lock_dict
def log(self):
logging.info("Transactions:")
for txn in self._transaction_dict.values():
logging.info(' %r', txn)
logging.info(' Read locks:')
for oid, ttid in self._load_lock_dict.items():
logging.info(' %r by %r', dump(oid), dump(ttid))
logging.info(' Write locks:')
for oid, ttid in self._store_lock_dict.items():
logging.info(' %r by %r', dump(oid), dump(ttid))
def updateObjectDataForPack(self, oid, orig_serial, new_serial, data_id):
lock_tid = self.getLockingTID(oid)
if lock_tid is not None:
transaction = self._transaction_dict[lock_tid]
if transaction.getObject(oid)[2] == orig_serial:
if new_serial:
data_id = None
else:
self._app.dm.holdData(data_id)
transaction.addObject(oid, data_id, new_serial)
|
gpl-2.0
|
jch1g10/Grid
|
tests/solver/Test_staggered_cg_schur.cc
|
3017
|
/*************************************************************************************
Grid physics library, www.github.com/paboyle/Grid
Source file: ./tests/Test_wilson_cg_schur.cc
Copyright (C) 2015
Author: Peter Boyle <paboyle@ph.ed.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.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
See the full license in the file "LICENSE" in the top level distribution directory
*************************************************************************************/
/* END LEGAL */
#include <Grid/Grid.h>
using namespace std;
using namespace Grid;
using namespace Grid::QCD;
template<class d>
struct scal {
d internal;
};
Gamma::Algebra Gmu [] = {
Gamma::Algebra::GammaX,
Gamma::Algebra::GammaY,
Gamma::Algebra::GammaZ,
Gamma::Algebra::GammaT
};
int main (int argc, char ** argv)
{
typedef typename ImprovedStaggeredFermionR::FermionField FermionField;
typename ImprovedStaggeredFermionR::ImplParams params;
Grid_init(&argc,&argv);
std::vector<int> latt_size = GridDefaultLatt();
std::vector<int> simd_layout = GridDefaultSimd(Nd,vComplex::Nsimd());
std::vector<int> mpi_layout = GridDefaultMpi();
GridCartesian Grid(latt_size,simd_layout,mpi_layout);
GridRedBlackCartesian RBGrid(&Grid);
std::vector<int> seeds({1,2,3,4});
GridParallelRNG pRNG(&Grid); pRNG.SeedFixedIntegers(seeds);
LatticeGaugeField Umu(&Grid); SU3::HotConfiguration(pRNG,Umu);
FermionField src(&Grid); random(pRNG,src);
FermionField result(&Grid); result=zero;
FermionField resid(&Grid);
RealD mass=0.1;
ImprovedStaggeredFermionR Ds(Umu,Umu,Grid,RBGrid,mass);
ConjugateGradient<FermionField> CG(1.0e-8,10000);
SchurRedBlackStaggeredSolve<FermionField> SchurSolver(CG);
double volume=1.0;
for(int mu=0;mu<Nd;mu++){
volume=volume*latt_size[mu];
}
double t1=usecond();
SchurSolver(Ds,src,result);
double t2=usecond();
// Schur solver: uses DeoDoe => volume * 1146
double ncall=CG.IterationsToComplete;
double flops=(16*(3*(6+8+8)) + 15*3*2)*volume*ncall; // == 66*16 + == 1146
std::cout<<GridLogMessage << "usec = "<< (t2-t1)<<std::endl;
std::cout<<GridLogMessage << "flop/s = "<< flops<<std::endl;
std::cout<<GridLogMessage << "mflop/s = "<< flops/(t2-t1)<<std::endl;
Grid_finalize();
}
|
gpl-2.0
|
imincik/pkg-qgis-1.8
|
src/app/composer/qgscompositionwidget.cpp
|
14847
|
/***************************************************************************
qgscompositionwidget.cpp
--------------------------
begin : June 11 2008
copyright : (C) 2008 by Marco Hugentobler
email : marco dot hugentobler at karto dot baug dot ethz dot ch
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <qgis.h>
#include "qgscompositionwidget.h"
#include "qgscomposition.h"
#include <QColorDialog>
#include <QWidget>
#include <QPrinter> //for screen resolution
QgsCompositionWidget::QgsCompositionWidget( QWidget* parent, QgsComposition* c ): QWidget( parent ), mComposition( c )
{
setupUi( this );
blockSignals( true );
createPaperEntries();
//unit
mPaperUnitsComboBox->addItem( tr( "mm" ) );
mPaperUnitsComboBox->addItem( tr( "inch" ) );
//orientation
mPaperOrientationComboBox->insertItem( 0, tr( "Landscape" ) );
mPaperOrientationComboBox->insertItem( 1, tr( "Portrait" ) );
mPaperOrientationComboBox->setCurrentIndex( 0 );
//read with/height from composition and find suitable entries to display
displayCompositionWidthHeight();
if ( mComposition )
{
//read printout resolution from composition
mResolutionSpinBox->setValue( mComposition->printResolution() );
//print as raster
if ( mComposition->printAsRaster() )
{
mPrintAsRasterCheckBox->setCheckState( Qt::Checked );
}
else
{
mPrintAsRasterCheckBox->setCheckState( Qt::Unchecked );
}
//snap grid
if ( mComposition->snapToGridEnabled() )
{
mSnapToGridCheckBox->setCheckState( Qt::Checked );
}
else
{
mSnapToGridCheckBox->setCheckState( Qt::Unchecked );
}
mGridResolutionSpinBox->setValue( mComposition->snapGridResolution() );
mOffsetXSpinBox->setValue( mComposition->snapGridOffsetX() );
mOffsetYSpinBox->setValue( mComposition->snapGridOffsetY() );
//grid pen width
mPenWidthSpinBox->setValue( mComposition->gridPen().widthF() );
//grid pen color
mGridColorButton->setColor( mComposition->gridPen().color() );
mGridStyleComboBox->insertItem( 0, tr( "Solid" ) );
mGridStyleComboBox->insertItem( 1, tr( "Dots" ) );
mGridStyleComboBox->insertItem( 2, tr( "Crosses" ) );
QgsComposition::GridStyle snapGridStyle = mComposition->gridStyle();
if ( snapGridStyle == QgsComposition::Solid )
{
mGridStyleComboBox->setCurrentIndex( 0 );
}
else if ( snapGridStyle == QgsComposition::Dots )
{
mGridStyleComboBox->setCurrentIndex( 1 );
}
else
{
mGridStyleComboBox->setCurrentIndex( 2 );
}
mSelectionToleranceSpinBox->setValue( mComposition->selectionTolerance() );
}
blockSignals( false );
}
QgsCompositionWidget::QgsCompositionWidget(): QWidget( 0 ), mComposition( 0 )
{
setupUi( this );
}
QgsCompositionWidget::~QgsCompositionWidget()
{
}
void QgsCompositionWidget::createPaperEntries()
{
QList<QgsCompositionPaper> formats;
formats
// ISO formats
<< QgsCompositionPaper( tr( "A5 (148x210 mm)" ), 148, 210 )
<< QgsCompositionPaper( tr( "A4 (210x297 mm)" ), 210, 297 )
<< QgsCompositionPaper( tr( "A3 (297x420 mm)" ), 297, 420 )
<< QgsCompositionPaper( tr( "A2 (420x594 mm)" ), 420, 594 )
<< QgsCompositionPaper( tr( "A1 (594x841 mm)" ), 594, 841 )
<< QgsCompositionPaper( tr( "A0 (841x1189 mm)" ), 841, 1189 )
<< QgsCompositionPaper( tr( "B5 (176 x 250 mm)" ), 176, 250 )
<< QgsCompositionPaper( tr( "B4 (250 x 353 mm)" ), 250, 353 )
<< QgsCompositionPaper( tr( "B3 (353 x 500 mm)" ), 353, 500 )
<< QgsCompositionPaper( tr( "B2 (500 x 707 mm)" ), 500, 707 )
<< QgsCompositionPaper( tr( "B1 (707 x 1000 mm)" ), 707, 1000 )
<< QgsCompositionPaper( tr( "B0 (1000 x 1414 mm)" ), 1000, 1414 )
// North american formats
<< QgsCompositionPaper( tr( "Legal (8.5x14 inches)" ), 215.9, 355.6 )
<< QgsCompositionPaper( tr( "ANSI A (Letter; 8.5x11 inches)" ), 215.9, 279.4 )
<< QgsCompositionPaper( tr( "ANSI B (Tabloid; 11x17 inches)" ), 279.4, 431.8 )
<< QgsCompositionPaper( tr( "ANSI C (17x22 inches)" ), 431.8, 558.8 )
<< QgsCompositionPaper( tr( "ANSI D (22x34 inches)" ), 558.8, 863.6 )
<< QgsCompositionPaper( tr( "ANSI E (34x44 inches)" ), 863.6, 1117.6 )
<< QgsCompositionPaper( tr( "Arch A (9x12 inches)" ), 228.6, 304.8 )
<< QgsCompositionPaper( tr( "Arch B (12x18 inches)" ), 304.8, 457.2 )
<< QgsCompositionPaper( tr( "Arch C (18x24 inches)" ), 457.2, 609.6 )
<< QgsCompositionPaper( tr( "Arch D (24x36 inches)" ), 609.6, 914.4 )
<< QgsCompositionPaper( tr( "Arch E (36x48 inches)" ), 914.4, 1219.2 )
<< QgsCompositionPaper( tr( "Arch E1 (30x42 inches)" ), 762, 1066.8 )
;
mPaperSizeComboBox->addItem( tr( "Custom" ) );
for ( QList<QgsCompositionPaper>::const_iterator it = formats.begin(); it != formats.end(); it++ )
{
mPaperSizeComboBox->addItem( it->mName );
mPaperMap.insert( it->mName, *it );
}
mPaperSizeComboBox->setCurrentIndex( 2 ); //A4
}
void QgsCompositionWidget::on_mPaperSizeComboBox_currentIndexChanged( const QString& text )
{
Q_UNUSED( text );
if ( mPaperSizeComboBox->currentText() == tr( "Custom" ) )
{
mPaperWidthDoubleSpinBox->setEnabled( true );
mPaperHeightDoubleSpinBox->setEnabled( true );
mPaperUnitsComboBox->setEnabled( true );
}
else
{
mPaperWidthDoubleSpinBox->setEnabled( false );
mPaperHeightDoubleSpinBox->setEnabled( false );
mPaperUnitsComboBox->setEnabled( false );
}
applyCurrentPaperSettings();
}
void QgsCompositionWidget::on_mPaperOrientationComboBox_currentIndexChanged( const QString& text )
{
Q_UNUSED( text );
if ( mPaperSizeComboBox->currentText() == tr( "Custom" ) )
{
adjustOrientation();
applyWidthHeight();
}
else
{
adjustOrientation();
applyCurrentPaperSettings();
}
}
void QgsCompositionWidget::on_mPaperUnitsComboBox_currentIndexChanged( const QString& text )
{
Q_UNUSED( text );
double width = size( mPaperWidthDoubleSpinBox );
double height = size( mPaperHeightDoubleSpinBox );
if ( mPaperUnitsComboBox->currentIndex() == 0 )
{
// mm, value was inch
width *= 25.4;
height *= 25.4;
}
else
{
// inch, values was mm,
width /= 25.4;
height /= 25.4;
}
setSize( mPaperWidthDoubleSpinBox, width );
setSize( mPaperHeightDoubleSpinBox, height );
if ( mPaperSizeComboBox->currentText() == tr( "Custom" ) )
{
adjustOrientation();
applyWidthHeight();
}
else
{
adjustOrientation();
applyCurrentPaperSettings();
}
}
void QgsCompositionWidget::adjustOrientation()
{
double width = size( mPaperWidthDoubleSpinBox );
double height = size( mPaperHeightDoubleSpinBox );
if ( width < 0 || height < 0 )
{
return;
}
if ( height > width ) //change values such that width > height
{
double tmp = width;
width = height;
height = tmp;
}
bool lineEditsEnabled = mPaperWidthDoubleSpinBox->isEnabled();
mPaperWidthDoubleSpinBox->setEnabled( true );
mPaperHeightDoubleSpinBox->setEnabled( true );
if ( mPaperOrientationComboBox->currentText() == tr( "Landscape" ) )
{
setSize( mPaperWidthDoubleSpinBox, width );
setSize( mPaperHeightDoubleSpinBox, height );
}
else
{
setSize( mPaperWidthDoubleSpinBox, height );
setSize( mPaperHeightDoubleSpinBox, width );
}
mPaperWidthDoubleSpinBox->setEnabled( lineEditsEnabled );
mPaperHeightDoubleSpinBox->setEnabled( lineEditsEnabled );
}
void QgsCompositionWidget::setSize( QDoubleSpinBox *spin, double v )
{
if ( mPaperUnitsComboBox->currentIndex() == 0 )
{
// mm
spin->setValue( v );
}
else
{
// inch (show width in inch)
spin->setValue( v / 25.4 );
}
}
double QgsCompositionWidget::size( QDoubleSpinBox *spin )
{
double size = spin->value();
if ( mPaperUnitsComboBox->currentIndex() == 0 )
{
// mm
return size;
}
else
{
// inch return in mm
return size * 25.4;
}
}
void QgsCompositionWidget::applyCurrentPaperSettings()
{
if ( mComposition )
{
//find entry in mPaper map to set width and height
QMap<QString, QgsCompositionPaper>::iterator it = mPaperMap.find( mPaperSizeComboBox->currentText() );
if ( it == mPaperMap.end() )
{
return;
}
mPaperWidthDoubleSpinBox->setEnabled( true );
mPaperHeightDoubleSpinBox->setEnabled( true );
setSize( mPaperWidthDoubleSpinBox, it->mWidth );
setSize( mPaperHeightDoubleSpinBox, it->mHeight );
mPaperWidthDoubleSpinBox->setEnabled( false );
mPaperHeightDoubleSpinBox->setEnabled( false );
adjustOrientation();
applyWidthHeight();
}
}
void QgsCompositionWidget::applyWidthHeight()
{
double width = size( mPaperWidthDoubleSpinBox );
double height = size( mPaperHeightDoubleSpinBox );
if ( width < 0 || height < 0 )
return;
mComposition->setPaperSize( width, height );
}
void QgsCompositionWidget::on_mPaperWidthDoubleSpinBox_editingFinished()
{
applyWidthHeight();
}
void QgsCompositionWidget::on_mPaperHeightDoubleSpinBox_editingFinished()
{
applyWidthHeight();
}
void QgsCompositionWidget::displayCompositionWidthHeight()
{
if ( !mComposition )
{
return;
}
double paperWidth = mComposition->paperWidth();
setSize( mPaperWidthDoubleSpinBox, paperWidth );
double paperHeight = mComposition->paperHeight();
setSize( mPaperHeightDoubleSpinBox, paperHeight );
//set orientation
if ( paperWidth > paperHeight )
{
mPaperOrientationComboBox->setCurrentIndex( mPaperOrientationComboBox->findText( tr( "Landscape" ) ) );
}
else
{
mPaperOrientationComboBox->setCurrentIndex( mPaperOrientationComboBox->findText( tr( "Portrait" ) ) );
}
//set paper name
bool found = false;
QMap<QString, QgsCompositionPaper>::const_iterator paper_it = mPaperMap.constBegin();
for ( ; paper_it != mPaperMap.constEnd(); ++paper_it )
{
QgsCompositionPaper currentPaper = paper_it.value();
//consider width and height values may be exchanged
if (( doubleNear( currentPaper.mWidth, paperWidth ) && doubleNear( currentPaper.mHeight, paperHeight ) )
|| ( doubleNear( currentPaper.mWidth, paperHeight ) && doubleNear( currentPaper.mHeight, paperWidth ) ) )
{
mPaperSizeComboBox->setCurrentIndex( mPaperSizeComboBox->findText( paper_it.key() ) );
found = true;
break;
}
}
if ( !found )
{
//custom
mPaperSizeComboBox->setCurrentIndex( 0 );
}
}
void QgsCompositionWidget::displaySnapingSettings()
{
if ( !mComposition )
{
return;
}
if ( mComposition->snapToGridEnabled() )
{
mSnapToGridCheckBox->setCheckState( Qt::Checked );
}
else
{
mSnapToGridCheckBox->setCheckState( Qt::Unchecked );
}
mGridResolutionSpinBox->setValue( mComposition->snapGridResolution() );
mOffsetXSpinBox->setValue( mComposition->snapGridOffsetX() );
mOffsetYSpinBox->setValue( mComposition->snapGridOffsetY() );
}
void QgsCompositionWidget::on_mResolutionSpinBox_valueChanged( const int value )
{
mComposition->setPrintResolution( value );
}
void QgsCompositionWidget::on_mPrintAsRasterCheckBox_stateChanged( int state )
{
if ( !mComposition )
{
return;
}
if ( state == Qt::Checked )
{
mComposition->setPrintAsRaster( true );
}
else
{
mComposition->setPrintAsRaster( false );
}
}
void QgsCompositionWidget::on_mSnapToGridCheckBox_stateChanged( int state )
{
if ( mComposition )
{
if ( state == Qt::Checked )
{
mComposition->setSnapToGridEnabled( true );
}
else
{
mComposition->setSnapToGridEnabled( false );
}
}
}
void QgsCompositionWidget::on_mGridResolutionSpinBox_valueChanged( double d )
{
if ( mComposition )
{
mComposition->setSnapGridResolution( d );
}
}
void QgsCompositionWidget::on_mOffsetXSpinBox_valueChanged( double d )
{
if ( mComposition )
{
mComposition->setSnapGridOffsetX( d );
}
}
void QgsCompositionWidget::on_mOffsetYSpinBox_valueChanged( double d )
{
if ( mComposition )
{
mComposition->setSnapGridOffsetY( d );
}
}
void QgsCompositionWidget::on_mGridColorButton_clicked()
{
QColor newColor = QColorDialog::getColor( mGridColorButton->color() );
if ( !newColor.isValid() )
{
return ; //dialog canceled by user
}
mGridColorButton->setColor( newColor );
if ( mComposition )
{
QPen pen = mComposition->gridPen();
pen.setColor( newColor );
mComposition->setGridPen( pen );
}
}
void QgsCompositionWidget::on_mGridStyleComboBox_currentIndexChanged( const QString& text )
{
Q_UNUSED( text );
if ( mComposition )
{
if ( mGridStyleComboBox->currentText() == tr( "Solid" ) )
{
mComposition->setGridStyle( QgsComposition::Solid );
}
else if ( mGridStyleComboBox->currentText() == tr( "Dots" ) )
{
mComposition->setGridStyle( QgsComposition::Dots );
}
else if ( mGridStyleComboBox->currentText() == tr( "Crosses" ) )
{
mComposition->setGridStyle( QgsComposition::Crosses );
}
}
}
void QgsCompositionWidget::on_mPenWidthSpinBox_valueChanged( double d )
{
if ( mComposition )
{
QPen pen = mComposition->gridPen();
pen.setWidthF( d );
mComposition->setGridPen( pen );
}
}
void QgsCompositionWidget::on_mSelectionToleranceSpinBox_valueChanged( double d )
{
if ( mComposition )
{
mComposition->setSelectionTolerance( d );
}
}
void QgsCompositionWidget::blockSignals( bool block )
{
mPaperSizeComboBox->blockSignals( block );
mPaperUnitsComboBox->blockSignals( block );
mPaperWidthDoubleSpinBox->blockSignals( block );
mPaperHeightDoubleSpinBox->blockSignals( block );
mPaperOrientationComboBox->blockSignals( block );
mResolutionSpinBox->blockSignals( block );
mPrintAsRasterCheckBox->blockSignals( block );
mSnapToGridCheckBox->blockSignals( block );
mGridResolutionSpinBox->blockSignals( block );
mOffsetXSpinBox->blockSignals( block );
mOffsetYSpinBox->blockSignals( block );
mPenWidthSpinBox->blockSignals( block );
mGridColorButton->blockSignals( block );
mGridStyleComboBox->blockSignals( block );
mSelectionToleranceSpinBox->blockSignals( block );
}
|
gpl-2.0
|
F1ash/qt-virt-manager
|
src/create_widgets/domain/common_widgets/fs_type_widgets/_fstype.cpp
|
3222
|
#include "_fstype.h"
_FsType::_FsType(
QWidget *parent,
QString _type) :
_QWidget(parent), connType(_type)
{
driverLabel = new QLabel(tr("Driver:"), this);
wrPolicyLabel = new QLabel(tr("WritePolicy (optional):"), this);
formatLabel = new QLabel(tr("Format:"), this);
accessModeLabel = new QLabel(tr("AccessMode:"), this);
sourceLabel = new QPushButton(tr("Source:"), this);
targetLabel = new QLabel(tr("Target:"), this);
driver = new QComboBox(this);
if ( connType.compare("lxc")==0 ) {
driver->addItems(LXC_DRIVER_TYPES);
} else if ( connType.compare("qemu")==0 ) {
driver->addItems(QEMU_DRIVER_TYPES);
};
wrPolicy = new QComboBox(this);
wrPolicy->addItem("default");
wrPolicy->addItem("immediate");
format = new QComboBox(this);
formatLabel->setVisible(false);
format->setVisible(false);
accessMode = new QComboBox(this);
accessMode->addItem("default");
accessMode->addItem("passthrough");
accessMode->addItem("mapped");
accessMode->addItem("squash");
driverAttrLayout = new QGridLayout();
driverAttrLayout->addWidget(wrPolicyLabel, 0, 0);
driverAttrLayout->addWidget(wrPolicy, 0, 1);
driverAttrLayout->addWidget(formatLabel, 1, 0);
driverAttrLayout->addWidget(format, 1, 1);
driverAttrLayout->addWidget(accessModeLabel, 2, 0, Qt::AlignTop);
driverAttrLayout->addWidget(accessMode, 2, 1, Qt::AlignTop);
driverAttrWdg = new QWidget(this);
driverAttrWdg->setLayout(driverAttrLayout);
driverAttrWdg->setVisible(false);
source = new QLineEdit(this);
target = new QLineEdit(this);
readOnly = new QCheckBox(tr("Export filesystem readonly"), this);
commonLayout = new QGridLayout();
commonLayout->addWidget(driverLabel, 0, 0);
commonLayout->addWidget(driver, 0, 1);
commonLayout->addWidget(driverAttrWdg, 1, 0, 2, 2);
commonLayout->addWidget(sourceLabel, 4, 0);
commonLayout->addWidget(source, 4, 1);
commonLayout->addWidget(targetLabel, 5, 0, Qt::AlignCenter);
commonLayout->addWidget(target, 5, 1, Qt::AlignTop);
commonLayout->addWidget(readOnly, 6, 1, Qt::AlignTop);
setLayout(commonLayout);
connect(driver, SIGNAL(currentIndexChanged(QString)),
this, SLOT(driverTypeChanged(QString)));
}
/* virtual */
QDomDocument _FsType::getDataDocument() const
{
return QDomDocument();
}
/* private slots */
void _FsType::driverTypeChanged(QString _type)
{
format->clear();
driverAttrWdg->setVisible( _type.compare("default")!=0 );
/*
* Currently this only works with type='mount' for the QEMU/KVM driver.
*/
accessModeLabel->setVisible( connType.compare("qemu")==0 );
accessMode->setVisible( connType.compare("qemu")==0 );
/*
* LXC supports a type of "loop", with a format of "raw" or "nbd" with any format.
* QEMU supports a type of "path" or "handle", but no formats.
*/
formatLabel->setVisible( connType.compare("lxc")==0 );
format->setVisible( connType.compare("lxc")==0 );
if ( _type.compare("loop")==0 ) {
format->addItem("raw");
} else if ( _type.compare("nbd")==0 ) {
format->addItems(FORMAT_TYPES);
}
}
|
gpl-2.0
|
anthonyryan1/xbmc
|
xbmc/TextureCache.cpp
|
9654
|
/*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "TextureCache.h"
#include "TextureCacheJob.h"
#include "filesystem/File.h"
#include "profiles/ProfileManager.h"
#include "threads/SingleLock.h"
#include "utils/Crc32.h"
#include "settings/AdvancedSettings.h"
#include "settings/SettingsComponent.h"
#include "utils/log.h"
#include "utils/URIUtils.h"
#include "utils/StringUtils.h"
#include "URL.h"
#include "ServiceBroker.h"
using namespace XFILE;
CTextureCache &CTextureCache::GetInstance()
{
static CTextureCache s_cache;
return s_cache;
}
CTextureCache::CTextureCache() : CJobQueue(false, 1, CJob::PRIORITY_LOW_PAUSABLE)
{
}
CTextureCache::~CTextureCache() = default;
void CTextureCache::Initialize()
{
CSingleLock lock(m_databaseSection);
if (!m_database.IsOpen())
m_database.Open();
}
void CTextureCache::Deinitialize()
{
CancelJobs();
CSingleLock lock(m_databaseSection);
m_database.Close();
}
bool CTextureCache::IsCachedImage(const std::string &url) const
{
if (url.empty())
return false;
if (!CURL::IsFullPath(url))
return true;
const std::shared_ptr<CProfileManager> profileManager = CServiceBroker::GetSettingsComponent()->GetProfileManager();
return URIUtils::PathHasParent(url, "special://skin", true) ||
URIUtils::PathHasParent(url, "special://temp", true) ||
URIUtils::PathHasParent(url, "resource://", true) ||
URIUtils::PathHasParent(url, "androidapp://", true) ||
URIUtils::PathHasParent(url, profileManager->GetThumbnailsFolder(), true);
}
bool CTextureCache::HasCachedImage(const std::string &url)
{
CTextureDetails details;
std::string cachedImage(GetCachedImage(url, details));
return (!cachedImage.empty() && cachedImage != url);
}
std::string CTextureCache::GetCachedImage(const std::string &image, CTextureDetails &details, bool trackUsage)
{
std::string url = CTextureUtils::UnwrapImageURL(image);
if (url.empty())
return "";
if (IsCachedImage(url))
return url;
// lookup the item in the database
if (GetCachedTexture(url, details))
{
if (trackUsage)
IncrementUseCount(details);
return GetCachedPath(details.file);
}
return "";
}
bool CTextureCache::CanCacheImageURL(const CURL &url)
{
return url.GetUserName().empty() || url.GetUserName() == "music" ||
StringUtils::StartsWith(url.GetUserName(), "video_");
}
std::string CTextureCache::CheckCachedImage(const std::string &url, bool &needsRecaching)
{
CTextureDetails details;
std::string path(GetCachedImage(url, details, true));
needsRecaching = !details.hash.empty();
if (!path.empty())
return path;
return "";
}
void CTextureCache::BackgroundCacheImage(const std::string &url)
{
if (url.empty())
return;
CTextureDetails details;
std::string path(GetCachedImage(url, details));
if (!path.empty() && details.hash.empty())
return; // image is already cached and doesn't need to be checked further
path = CTextureUtils::UnwrapImageURL(url);
if (path.empty())
return;
// needs (re)caching
AddJob(new CTextureCacheJob(path, details.hash));
}
std::string CTextureCache::CacheImage(const std::string &image, CBaseTexture **texture /* = NULL */, CTextureDetails *details /* = NULL */)
{
std::string url = CTextureUtils::UnwrapImageURL(image);
if (url.empty())
return "";
CSingleLock lock(m_processingSection);
if (m_processinglist.find(url) == m_processinglist.end())
{
m_processinglist.insert(url);
lock.Leave();
// cache the texture directly
CTextureCacheJob job(url);
bool success = job.CacheTexture(texture);
OnCachingComplete(success, &job);
if (success && details)
*details = job.m_details;
return success ? GetCachedPath(job.m_details.file) : "";
}
lock.Leave();
// wait for currently processing job to end.
while (true)
{
m_completeEvent.WaitMSec(1000);
{
CSingleLock lock(m_processingSection);
if (m_processinglist.find(url) == m_processinglist.end())
break;
}
}
CTextureDetails tempDetails;
if (!details)
details = &tempDetails;
return GetCachedImage(url, *details, true);
}
bool CTextureCache::CacheImage(const std::string &image, CTextureDetails &details)
{
std::string path = GetCachedImage(image, details);
if (path.empty()) // not cached
path = CacheImage(image, NULL, &details);
return !path.empty();
}
void CTextureCache::ClearCachedImage(const std::string &url, bool deleteSource /*= false */)
{
//! @todo This can be removed when the texture cache covers everything.
std::string path = deleteSource ? url : "";
std::string cachedFile;
if (ClearCachedTexture(url, cachedFile))
path = GetCachedPath(cachedFile);
if (CFile::Exists(path))
CFile::Delete(path);
path = URIUtils::ReplaceExtension(path, ".dds");
if (CFile::Exists(path))
CFile::Delete(path);
}
bool CTextureCache::ClearCachedImage(int id)
{
std::string cachedFile;
if (ClearCachedTexture(id, cachedFile))
{
cachedFile = GetCachedPath(cachedFile);
if (CFile::Exists(cachedFile))
CFile::Delete(cachedFile);
cachedFile = URIUtils::ReplaceExtension(cachedFile, ".dds");
if (CFile::Exists(cachedFile))
CFile::Delete(cachedFile);
return true;
}
return false;
}
bool CTextureCache::GetCachedTexture(const std::string &url, CTextureDetails &details)
{
CSingleLock lock(m_databaseSection);
return m_database.GetCachedTexture(url, details);
}
bool CTextureCache::AddCachedTexture(const std::string &url, const CTextureDetails &details)
{
CSingleLock lock(m_databaseSection);
return m_database.AddCachedTexture(url, details);
}
void CTextureCache::IncrementUseCount(const CTextureDetails &details)
{
static const size_t count_before_update = 100;
CSingleLock lock(m_useCountSection);
m_useCounts.reserve(count_before_update);
m_useCounts.push_back(details);
if (m_useCounts.size() >= count_before_update)
{
AddJob(new CTextureUseCountJob(m_useCounts));
m_useCounts.clear();
}
}
bool CTextureCache::SetCachedTextureValid(const std::string &url, bool updateable)
{
CSingleLock lock(m_databaseSection);
return m_database.SetCachedTextureValid(url, updateable);
}
bool CTextureCache::ClearCachedTexture(const std::string &url, std::string &cachedURL)
{
CSingleLock lock(m_databaseSection);
return m_database.ClearCachedTexture(url, cachedURL);
}
bool CTextureCache::ClearCachedTexture(int id, std::string &cachedURL)
{
CSingleLock lock(m_databaseSection);
return m_database.ClearCachedTexture(id, cachedURL);
}
std::string CTextureCache::GetCacheFile(const std::string &url)
{
auto crc = Crc32::ComputeFromLowerCase(url);
std::string hex = StringUtils::Format("%08x", crc);
std::string hash = StringUtils::Format("%c/%s", hex[0], hex.c_str());
return hash;
}
std::string CTextureCache::GetCachedPath(const std::string &file)
{
const std::shared_ptr<CProfileManager> profileManager = CServiceBroker::GetSettingsComponent()->GetProfileManager();
return URIUtils::AddFileToFolder(profileManager->GetThumbnailsFolder(), file);
}
void CTextureCache::OnCachingComplete(bool success, CTextureCacheJob *job)
{
if (success)
{
if (job->m_oldHash == job->m_details.hash)
SetCachedTextureValid(job->m_url, job->m_details.updateable);
else
AddCachedTexture(job->m_url, job->m_details);
}
{ // remove from our processing list
CSingleLock lock(m_processingSection);
std::set<std::string>::iterator i = m_processinglist.find(job->m_url);
if (i != m_processinglist.end())
m_processinglist.erase(i);
}
m_completeEvent.Set();
}
void CTextureCache::OnJobComplete(unsigned int jobID, bool success, CJob *job)
{
if (strcmp(job->GetType(), kJobTypeCacheImage) == 0)
OnCachingComplete(success, static_cast<CTextureCacheJob*>(job));
return CJobQueue::OnJobComplete(jobID, success, job);
}
void CTextureCache::OnJobProgress(unsigned int jobID, unsigned int progress, unsigned int total, const CJob *job)
{
if (strcmp(job->GetType(), kJobTypeCacheImage) == 0 && !progress)
{ // check our processing list
{
CSingleLock lock(m_processingSection);
const CTextureCacheJob *cacheJob = static_cast<const CTextureCacheJob*>(job);
std::set<std::string>::iterator i = m_processinglist.find(cacheJob->m_url);
if (i == m_processinglist.end())
{
m_processinglist.insert(cacheJob->m_url);
return;
}
}
CancelJob(job);
}
else
CJobQueue::OnJobProgress(jobID, progress, total, job);
}
bool CTextureCache::Export(const std::string &image, const std::string &destination, bool overwrite)
{
CTextureDetails details;
std::string cachedImage(GetCachedImage(image, details));
if (!cachedImage.empty())
{
std::string dest = destination + URIUtils::GetExtension(cachedImage);
if (overwrite || !CFile::Exists(dest))
{
if (CFile::Copy(cachedImage, dest))
return true;
CLog::Log(LOGERROR, "%s failed exporting '%s' to '%s'", __FUNCTION__, cachedImage.c_str(), dest.c_str());
}
}
return false;
}
bool CTextureCache::Export(const std::string &image, const std::string &destination)
{
CTextureDetails details;
std::string cachedImage(GetCachedImage(image, details));
if (!cachedImage.empty())
{
if (CFile::Copy(cachedImage, destination))
return true;
CLog::Log(LOGERROR, "%s failed exporting '%s' to '%s'", __FUNCTION__, cachedImage.c_str(), destination.c_str());
}
return false;
}
|
gpl-2.0
|
azureskydiver/EasyBridge
|
Source/Wizards/GameOptsFilesPage.cpp
|
2095
|
//----------------------------------------------------------------------------------------
//
// This file and all other Easy Bridge source files are copyright (C) 2002 by Steven Han.
// Use of this file is governed by the GNU General Public License.
// See the files COPYING and COPYRIGHT for details.
//
//----------------------------------------------------------------------------------------
//
// GameOptsFilesPage.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "ObjectWithProperties.h"
#include "GameOptsFilesPage.h"
#include "progopts.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGameOptsFilesPage property page
IMPLEMENT_DYNCREATE(CGameOptsFilesPage, CPropertyPage)
CGameOptsFilesPage::CGameOptsFilesPage(CObjectWithProperties* pApp) :
CPropertyPage(CGameOptsFilesPage::IDD),
m_app(*pApp)
{
//{{AFX_DATA_INIT(CGameOptsFilesPage)
m_bSaveIntermediatePositions = FALSE;
m_bExposePBNGameCards = FALSE;
//}}AFX_DATA_INIT
m_bSaveIntermediatePositions = m_app.GetValue(tbSaveIntermediatePositions);
m_bExposePBNGameCards = m_app.GetValue(tbExposePBNGameCards);
}
CGameOptsFilesPage::~CGameOptsFilesPage()
{
}
void CGameOptsFilesPage::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CGameOptsFilesPage)
DDX_Check(pDX, IDC_SAVE_POSITIONS, m_bSaveIntermediatePositions);
DDX_Check(pDX, IDC_SHOW_PBN_CARDS_FACEUP, m_bExposePBNGameCards);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CGameOptsFilesPage, CPropertyPage)
//{{AFX_MSG_MAP(CGameOptsFilesPage)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CGameOptsFilesPage message handlers
//
void CGameOptsFilesPage::Update()
{
// store results
m_app.SetValue(tbSaveIntermediatePositions, m_bSaveIntermediatePositions);
m_app.SetValue(tbExposePBNGameCards, m_bExposePBNGameCards);
}
|
gpl-2.0
|
acappellamaniac/eva_website
|
sites/all/modules/civicrm/api/v3/Mailing.php
|
24586
|
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* APIv3 functions for registering/processing mailing events.
*
* @package CiviCRM_APIv3
*/
/**
* Handle a create event.
*
* @param array $params
*
* @return array
* API Success Array
* @throws \API_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
function civicrm_api3_mailing_create($params) {
if (CRM_Mailing_Info::workflowEnabled()) {
// Note: 'schedule mailings' and 'approve mailings' can update certain fields, but can't create.
if (empty($params['id'])) {
if (!CRM_Core_Permission::check('access CiviMail') && !CRM_Core_Permission::check('create mailings')) {
throw new \Civi\API\Exception\UnauthorizedException("Cannot create new mailing. Required permission: 'access CiviMail' or 'create mailings'");
}
}
$safeParams = array();
$fieldPerms = CRM_Mailing_BAO_Mailing::getWorkflowFieldPerms();
foreach (array_keys($params) as $field) {
if (CRM_Core_Permission::check($fieldPerms[$field])) {
$safeParams[$field] = $params[$field];
}
}
}
else {
$safeParams = $params;
}
$safeParams['_evil_bao_validator_'] = 'CRM_Mailing_BAO_Mailing::checkSendable';
return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $safeParams);
}
/**
* Get tokens for one or more entity type
*
* Output will be formatted either as a flat list,
* or pass sequential=1 to retrieve as a hierarchy formatted for select2.
*
* @param array $params
* Should contain an array of entities to retrieve tokens for.
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_gettokens($params) {
$tokens = array();
foreach ((array) $params['entity'] as $ent) {
$func = lcfirst($ent) . 'Tokens';
if (!method_exists('CRM_Core_SelectValues', $func)) {
throw new API_Exception('Unknown token entity: ' . $ent);
}
$tokens = array_merge(CRM_Core_SelectValues::$func(), $tokens);
}
if (!empty($params['sequential'])) {
$tokens = CRM_Utils_Token::formatTokensForDisplay($tokens);
}
return civicrm_api3_create_success($tokens, $params, 'Mailing', 'gettokens');
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_gettokens_spec(&$params) {
$params['entity'] = array(
'api.default' => array('contact'),
'api.required' => 1,
'api.multiple' => 1,
'title' => 'Entity',
'options' => array(),
);
// Fetch a list of token functions and format to look like entity names
foreach (get_class_methods('CRM_Core_SelectValues') as $func) {
if (strpos($func, 'Tokens')) {
$ent = ucfirst(str_replace('Tokens', '', $func));
$params['entity']['options'][$ent] = $ent;
}
}
}
/**
* Adjust Metadata for Create action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_create_spec(&$params) {
$params['created_id']['api.required'] = 1;
$params['created_id']['api.default'] = 'user_contact_id';
$params['override_verp']['api.default'] = !CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'track_civimail_replies', NULL, FALSE
);
$params['visibility']['api.default'] = 'Public Pages';
$params['dedupe_email']['api.default'] = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'dedupe_email_default', NULL, FALSE
);
$params['forward_replies']['api.default'] = FALSE;
$params['auto_responder']['api.default'] = FALSE;
$params['open_tracking']['api.default'] = TRUE;
$params['url_tracking']['api.default'] = TRUE;
$params['header_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Header', '');
$params['footer_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Footer', '');
$params['optout_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('OptOut', '');
$params['reply_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Reply', '');
$params['resubscribe_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Resubscribe', '');
$params['unsubscribe_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Unsubscribe', '');
$params['mailing_type']['api.default'] = 'standalone';
$defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
foreach ($defaultAddress as $id => $value) {
if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
$params['from_email']['api.default'] = $match[2];
$params['from_name']['api.default'] = $match[1];
}
}
}
function _civicrm_api3_mailing_clone_spec(&$spec) {
$mailingFields = CRM_Mailing_DAO_Mailing::fields();
$spec['id'] = $mailingFields['id'];
$spec['id']['api.required'] = 1;
}
function civicrm_api3_mailing_clone($params) {
$BLACKLIST = array(
'id',
'is_completed',
'created_id',
'created_date',
'scheduled_id',
'scheduled_date',
'approver_id',
'approval_date',
'approval_status_id',
'approval_note',
'is_archived',
'hash',
);
$get = civicrm_api3('Mailing', 'getsingle', array('id' => $params['id']));
$newParams = array();
$newParams['debug'] = CRM_Utils_Array::value('debug', $params);
$newParams['groups']['include'] = array();
$newParams['groups']['exclude'] = array();
$newParams['mailings']['include'] = array();
$newParams['mailings']['exclude'] = array();
foreach ($get as $field => $value) {
if (!in_array($field, $BLACKLIST)) {
$newParams[$field] = $value;
}
}
$dao = new CRM_Mailing_DAO_MailingGroup();
$dao->mailing_id = $params['id'];
$dao->find();
while ($dao->fetch()) {
// CRM-11431; account for multi-lingual
$entity = (substr($dao->entity_table, 0, 15) == 'civicrm_mailing') ? 'mailings' : 'groups';
$newParams[$entity][strtolower($dao->group_type)][] = $dao->entity_id;
}
return civicrm_api3('Mailing', 'create', $newParams);
}
/**
* Handle a delete event.
*
* @param array $params
*
* @return array
* API Success Array
*/
function civicrm_api3_mailing_delete($params) {
return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Handle a get event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_get($params) {
return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
}
/**
* Adjust metadata for mailing submit api function.
*
* @param array $spec
*/
function _civicrm_api3_mailing_submit_spec(&$spec) {
$mailingFields = CRM_Mailing_DAO_Mailing::fields();
$spec['id'] = $mailingFields['id'];
$spec['scheduled_date'] = $mailingFields['scheduled_date'];
$spec['approval_date'] = $mailingFields['approval_date'];
$spec['approval_status_id'] = $mailingFields['approval_status_id'];
$spec['approval_note'] = $mailingFields['approval_note'];
// _skip_evil_bao_auto_recipients_: bool
}
/**
* Mailing submit.
*
* @param array $params
*
* @return array
* @throws API_Exception
*/
function civicrm_api3_mailing_submit($params) {
civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_Mailing', array('id'));
if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
}
if (!is_numeric(CRM_Core_Session::getLoggedInContactID())) {
throw new API_Exception("Failed to determine current user");
}
$updateParams = array();
$updateParams['id'] = $params['id'];
// Note: we'll pass along scheduling/approval fields, but they may get ignored
// if we don't have permission.
if (isset($params['scheduled_date'])) {
$updateParams['scheduled_date'] = $params['scheduled_date'];
$updateParams['scheduled_id'] = CRM_Core_Session::getLoggedInContactID();
}
if (isset($params['approval_date'])) {
$updateParams['approval_date'] = $params['approval_date'];
$updateParams['approver_id'] = CRM_Core_Session::getLoggedInContactID();
$updateParams['approval_status_id'] = CRM_Utils_Array::value('approval_status_id', $updateParams, CRM_Core_OptionGroup::getDefaultValue('mail_approval_status'));
}
if (isset($params['approval_note'])) {
$updateParams['approval_note'] = $params['approval_note'];
}
if (isset($params['_skip_evil_bao_auto_recipients_'])) {
$updateParams['_skip_evil_bao_auto_recipients_'] = $params['_skip_evil_bao_auto_recipients_'];
}
$updateParams['options']['reload'] = 1;
return civicrm_api3('Mailing', 'create', $updateParams);
}
/**
* Process a bounce event by passing through to the BAOs.
*
* @param array $params
*
* @throws API_Exception
* @return array
*/
function civicrm_api3_mailing_event_bounce($params) {
$body = $params['body'];
unset($params['body']);
$params += CRM_Mailing_BAO_BouncePattern::match($body);
if (CRM_Mailing_Event_BAO_Bounce::create($params)) {
return civicrm_api3_create_success($params);
}
else {
throw new API_Exception(ts('Queue event could not be found'), 'no_queue_event');
}
}
/**
* Adjust Metadata for bounce_spec action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_bounce_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['job_id']['title'] = 'Job ID';
$params['event_queue_id']['api.required'] = 1;
$params['event_queue_id']['title'] = 'Event Queue ID';
$params['hash']['api.required'] = 1;
$params['hash']['title'] = 'Hash';
$params['body']['api.required'] = 1;
$params['body']['title'] = 'Body';
}
/**
* Handle a confirm event.
*
* @deprecated
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_confirm($params) {
return civicrm_api('MailingEventConfirm', 'create', $params);
}
/**
* Declare deprecated functions.
*
* @deprecated api notice
* @return array
* Array of deprecated actions
*/
function _civicrm_api3_mailing_deprecation() {
return array('event_confirm' => 'Mailing api "event_confirm" action is deprecated. Use the mailing_event_confirm api instead.');
}
/**
* Handle a reply event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_reply($params) {
$job = $params['job_id'];
$queue = $params['event_queue_id'];
$hash = $params['hash'];
$replyto = $params['replyTo'];
$bodyTxt = CRM_Utils_Array::value('bodyTxt', $params);
$bodyHTML = CRM_Utils_Array::value('bodyHTML', $params);
$fullEmail = CRM_Utils_Array::value('fullEmail', $params);
$mailing = CRM_Mailing_Event_BAO_Reply::reply($job, $queue, $hash, $replyto);
if (empty($mailing)) {
return civicrm_api3_create_error('Queue event could not be found');
}
CRM_Mailing_Event_BAO_Reply::send($queue, $mailing, $bodyTxt, $replyto, $bodyHTML, $fullEmail);
return civicrm_api3_create_success($params);
}
/**
* Adjust Metadata for event_reply action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_reply_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['job_id']['title'] = 'Job ID';
$params['event_queue_id']['api.required'] = 1;
$params['event_queue_id']['title'] = 'Event Queue ID';
$params['hash']['api.required'] = 1;
$params['hash']['title'] = 'Hash';
$params['replyTo']['api.required'] = 0;
$params['replyTo']['title'] = 'Reply To';//doesn't really explain adequately
}
/**
* Handle a forward event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_forward($params) {
$job = $params['job_id'];
$queue = $params['event_queue_id'];
$hash = $params['hash'];
$email = $params['email'];
$fromEmail = CRM_Utils_Array::value('fromEmail', $params);
$params = CRM_Utils_Array::value('params', $params);
$forward = CRM_Mailing_Event_BAO_Forward::forward($job, $queue, $hash, $email, $fromEmail, $params);
if ($forward) {
return civicrm_api3_create_success($params);
}
return civicrm_api3_create_error('Queue event could not be found');
}
/**
* Adjust Metadata for event_forward action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_event_forward_spec(&$params) {
$params['job_id']['api.required'] = 1;
$params['job_id']['title'] = 'Job ID';
$params['event_queue_id']['api.required'] = 1;
$params['event_queue_id']['title'] = 'Event Queue ID';
$params['hash']['api.required'] = 1;
$params['hash']['title'] = 'Hash';
$params['email']['api.required'] = 1;
$params['email']['title'] = 'Forwarded to Email';
}
/**
* Handle a click event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_click($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_Event_DAO_TrackableURLOpen',
array('event_queue_id', 'url_id'),
FALSE
);
$url_id = $params['url_id'];
$queue = $params['event_queue_id'];
$url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($queue, $url_id);
$values = array();
$values['url'] = $url;
$values['is_error'] = 0;
return civicrm_api3_create_success($values);
}
/**
* Handle an open event.
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_event_open($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_Event_DAO_Opened',
array('event_queue_id'),
FALSE
);
$queue = $params['event_queue_id'];
$success = CRM_Mailing_Event_BAO_Opened::open($queue);
if (!$success) {
return civicrm_api3_create_error('mailing open event failed');
}
return civicrm_api3_create_success($params);
}
/**
* Preview mailing.
*
* @param array $params
* Array per getfields metadata.
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_preview($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_Mailing',
array('id'),
FALSE
);
$fromEmail = NULL;
if (!empty($params['from_email'])) {
$fromEmail = $params['from_email'];
}
$session = CRM_Core_Session::singleton();
$mailing = new CRM_Mailing_BAO_Mailing();
$mailing->id = $params['id'];
$mailing->find(TRUE);
CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
// get and format attachments
$attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
$returnProperties = $mailing->getReturnProperties();
$contactID = CRM_Utils_Array::value('contact_id', $params);
if (!$contactID) {
$contactID = $session->get('userID');
}
$mailingParams = array('contact_id' => $contactID);
$details = CRM_Utils_Token::getTokenDetails($mailingParams, $returnProperties, TRUE, TRUE, NULL, $mailing->getFlattenedTokens());
$mime = &$mailing->compose(NULL, NULL, NULL, $session->get('userID'), $fromEmail, $fromEmail,
TRUE, $details[0][$contactID], $attachments
);
return civicrm_api3_create_success(array(
'id' => $params['id'],
'contact_id' => $contactID,
'subject' => $mime->_headers['Subject'],
'body_html' => $mime->getHTMLBody(),
'body_text' => $mime->getTXTBody(),
));
}
/**
* Adjust metadata for send test function.
*
* @param array $spec
*/
function _civicrm_api3_mailing_send_test_spec(&$spec) {
$spec['test_group']['title'] = 'Test Group ID';
$spec['test_email']['title'] = 'Test Email Address';
}
/**
* Send test mailing.
*
* @param array $params
*
* @return array
* @throws \API_Exception
* @throws \CiviCRM_API3_Exception
*/
function civicrm_api3_mailing_send_test($params) {
if (!array_key_exists('test_group', $params) && !array_key_exists('test_email', $params)) {
throw new API_Exception("Mandatory key(s) missing from params array: test_group and/or test_email field are required");
}
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_MailingJob',
array('mailing_id'),
FALSE
);
$testEmailParams = _civicrm_api3_generic_replace_base_params($params);
$testEmailParams['is_test'] = 1;
$job = civicrm_api3('MailingJob', 'create', $testEmailParams);
$testEmailParams['job_id'] = $job['id'];
$testEmailParams['emails'] = explode(',', $testEmailParams['test_email']);
if (!empty($params['test_email'])) {
$query = CRM_Utils_SQL_Select::from('civicrm_email e')
->select(array('e.id', 'e.contact_id', 'e.email'))
->join('c', 'INNER JOIN civicrm_contact c ON e.contact_id = c.id')
->where('e.email IN (@emails)', array('@emails' => $testEmailParams['emails']))
->where('e.on_hold = 0')
->where('c.is_opt_out = 0')
->where('c.do_not_email = 0')
->where('c.is_deceased = 0')
->where('c.is_deleted = 0')
->groupBy('e.id')
->orderBy(array('e.is_bulkmail DESC', 'e.is_primary DESC'))
->toSQL();
$dao = CRM_Core_DAO::executeQuery($query);
$emailDetail = array();
// fetch contact_id and email id for all existing emails
while ($dao->fetch()) {
$emailDetail[$dao->email] = array(
'contact_id' => $dao->contact_id,
'email_id' => $dao->id,
);
}
$dao->free();
foreach ($testEmailParams['emails'] as $key => $email) {
$email = trim($email);
$contactId = $emailId = NULL;
if (array_key_exists($email, $emailDetail)) {
$emailId = $emailDetail[$email]['email_id'];
$contactId = $emailDetail[$email]['contact_id'];
}
if (!$contactId) {
//create new contact.
$contact = civicrm_api3('Contact', 'create',
array(
'contact_type' => 'Individual',
'email' => $email,
'api.Email.get' => array('return' => 'id'),
)
);
$contactId = $contact['id'];
$emailId = $contact['values'][$contactId]['api.Email.get']['id'];
}
civicrm_api3('MailingEventQueue', 'create',
array(
'job_id' => $job['id'],
'email_id' => $emailId,
'contact_id' => $contactId,
)
);
}
}
$isComplete = FALSE;
$config = CRM_Core_Config::singleton();
$mailerJobSize = (property_exists($config, 'mailerJobSize')) ? $config->mailerJobSize : NULL;
while (!$isComplete) {
// Q: In CRM_Mailing_BAO_Mailing::processQueue(), the three runJobs*()
// functions are all called. Why does Mailing.send_test only call one?
// CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, NULL);
$isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testEmailParams);
// CRM_Mailing_BAO_MailingJob::runJobs_post(NULL);
}
//return delivered mail info
$mailDelivered = CRM_Mailing_Event_BAO_Delivered::getRows($params['mailing_id'], $job['id'], TRUE, NULL, NULL, NULL, TRUE);
return civicrm_api3_create_success($mailDelivered);
}
/**
* Adjust Metadata for send_mail action.
*
* The metadata is used for setting defaults, documentation & validation.
*
* @param array $params
* Array of parameters determined by getfields.
*/
function _civicrm_api3_mailing_stats_spec(&$params) {
$params['date']['api.default'] = 'now';
$params['date']['title'] = 'Date';
}
/**
* Function which needs to be explained.
*
* @param array $params
*
* @return array
* @throws \API_Exception
*/
function civicrm_api3_mailing_stats($params) {
civicrm_api3_verify_mandatory($params,
'CRM_Mailing_DAO_MailingJob',
array('mailing_id'),
FALSE
);
if ($params['date'] == 'now') {
$params['date'] = date('YmdHis');
}
else {
$params['date'] = CRM_Utils_Date::processDate($params['date'] . ' ' . $params['date_time']);
}
$stats[$params['mailing_id']] = array();
if (empty($params['job_id'])) {
$params['job_id'] = NULL;
}
foreach (array('Delivered', 'Bounces', 'Unsubscribers', 'Unique Clicks', 'Opened') as $detail) {
switch ($detail) {
case 'Delivered':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Delivered::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date']),
);
break;
case 'Bounces':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Bounce::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date']),
);
break;
case 'Unsubscribers':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date']),
);
break;
case 'Unique Clicks':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date']),
);
break;
case 'Opened':
$stats[$params['mailing_id']] += array(
$detail => CRM_Mailing_Event_BAO_Opened::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date']),
);
break;
}
}
return civicrm_api3_create_success($stats);
}
/**
* Fix the reset dates on the email record based on when a mail was last delivered.
*
* We only consider mailings that were completed and finished in the last 3 to 7 days
* Both the min and max days can be set via the params
*
* @param array $params
*
* @return array
*/
function civicrm_api3_mailing_update_email_resetdate($params) {
CRM_Mailing_Event_BAO_Delivered::updateEmailResetDate(
CRM_Utils_Array::value('minDays', $params, 3),
CRM_Utils_Array::value('maxDays', $params, 3)
);
return civicrm_api3_create_success();
}
|
gpl-2.0
|
hexmode/wikipathways.org
|
wpi/rdf/ListPathways2Rdf.java
|
13507
|
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.bridgedb.Xref;
import org.bridgedb.bio.BioDataSource;
import org.pathvisio.data.GdbManager;
import org.pathvisio.model.ConverterException;
import org.pathvisio.model.DataNodeType;
import org.pathvisio.model.ObjectType;
import org.pathvisio.model.Pathway;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.wikipathways.webservice.WSPathway;
import org.pathvisio.wikipathways.webservice.WSPathwayInfo;
import org.pathvisio.wikipathways.webservice.WSSearchResult;
import org.pathvisio.wikipathways.WikiPathwaysClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.DC;
import com.hp.hpl.jena.vocabulary.DCTerms;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
public class ListPathways2Rdf {
/**
* @param args
*/
public static void main(String[] args) {
try {
// Create a client to the WikiPathways web service
List<String> blockList=new ArrayList<String>();
WikiPathwaysClient client = new WikiPathwaysClient(
new URL(
"http://www.wikipathways.org/wpi/webservice/webservice.php"));
String wpIdentifier;
/* if (args.length == 0) {
wpIdentifier = "WP716";
} else {
wpIdentifier = args[0];
}
*/
String nsWikipathways = "http://www.wikipathways.org/#";
String nsGenmapp = "http://www.genmapp.org/#";
String nsDwc = "http://rs.tdwg.org/dwc/terms/";
WSPathwayInfo[] pathwayList = client.listPathways();
Model model = ModelFactory.createDefaultModel();
for(WSPathwayInfo pathwaylist : pathwayList) {
try{
wpIdentifier = pathwaylist.getId();
// wpIdentifier = "WP1380";
if (!blockList.contains(wpIdentifier)){
System.out.println(wpIdentifier);
WSPathwayInfo pathwayInfo = client.getPathwayInfo(wpIdentifier);
String pathwayURI = "http://www.wikipathways.org/pathway/"
+ wpIdentifier;
String pathwayName = pathwayInfo.getName();
String pathwaySpecies = pathwayInfo.getSpecies();
WSPathway wsPathway = client.getPathway(wpIdentifier);
Pathway pathway = WikiPathwaysClient.toPathway(wsPathway);
Writer output = null;
File tempFile = new File("rdfoutput/"+UUID.randomUUID()+".gpml");
System.out.println(tempFile.getName());
output = new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8");
output.write(wsPathway.getGpml());
output.close();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (tempFile);
doc.getDocumentElement ().normalize ();
NodeList pathwayLicense = doc.getElementsByTagName("Pathway");
NodeList bpRef = doc.getElementsByTagName("BiopaxRef");
HashMap<String, String> bpRefmap = new HashMap<String, String>();
if(bpRef != null && bpRef.getLength() > 0) {
for(int i = 0 ; i < bpRef.getLength();i++) {
System.out.println(bpRef.item(i).getParentNode().getNodeName());
if (bpRef.item(i).getParentNode().getNodeName().equals("DataNode")){
bpRefmap.put(bpRef.item(i).getTextContent(),nsWikipathways +"/"+wpIdentifier+ "/Datanode/"+ bpRef.item(i).getParentNode().getAttributes().getNamedItem("GraphId").getNodeValue());
}
if (bpRef.item(i).getParentNode().getNodeName().equals("Pathway")){
bpRefmap.put(bpRef.item(i).getTextContent(),nsWikipathways + "/"+ wpIdentifier+"/");
}
if (bpRef.item(i).getParentNode().getNodeName().equals("Line")){
bpRefmap.put(bpRef.item(i).getTextContent(),nsWikipathways +"/"+wpIdentifier+ "/Line/"+ bpRef.item(i).getParentNode().getAttributes().getNamedItem("GraphId").getNodeValue());
}
if (bpRef.item(i).getParentNode().getNodeName().equals("State")){
bpRefmap.put(bpRef.item(i).getTextContent(),nsWikipathways +"/"+wpIdentifier+ "/State/"+ bpRef.item(i).getParentNode().getAttributes().getNamedItem("GraphId").getNodeValue());
}
if (bpRef.item(i).getParentNode().getNodeName().equals("Group")){
bpRefmap.put(bpRef.item(i).getTextContent(),nsWikipathways +"/"+wpIdentifier+ "/Group/"+ bpRef.item(i).getParentNode().getAttributes().getNamedItem("GroupId").getNodeValue());
}
}
}
// namespaces
// predicates
Property hasSpecies = model.createProperty(nsWikipathways,
"species");
Property hasName = model.createProperty(nsWikipathways, "hasName");
Property hasGpmlObjectType = model.createProperty(nsGenmapp,
"hasObject");
Property hasXref = model.createProperty(nsWikipathways, "xref");
Property rdfHasDataNodeType = model.createProperty(nsWikipathways,
"DataNodeType");
Property hasRoleIn = model.createProperty(nsWikipathways,
"HasRoleIn");
Property isGpmlDataNode = model.createProperty(nsGenmapp,
"DataNode");
Property scientificName = model.createProperty(nsDwc,
"scientificName");
for (String groupRef : pathway.getGroupIds()){
Resource groupResource = model.createResource(nsWikipathways+"/"+wpIdentifier+"/Group/"+groupRef);
groupResource.addProperty(RDF.type, model.getResource(nsGenmapp+"/Group/"));
groupResource.addProperty(DC.identifier, groupRef);
}
Resource pathwayResource = model.createResource(pathwayURI);
Resource wikipathwaysResource = model.createResource("http://www.wikipathways.org");
Resource wikiPathwaysPaperResource = model.createResource("http://www.ncbi.nlm.nih.gov/pubmed/18651794");
wikipathwaysResource.addProperty(DCTerms.bibliographicCitation, wikiPathwaysPaperResource);
// Get all genes, proteins and metabolites for a pathway
pathwayResource.addProperty(hasSpecies, pathwaySpecies);
pathwayResource.addProperty(RDF.type, Biopax_level3.Pathway);
pathwayResource.addProperty(RDFS.label, pathwayName);
pathwayResource.addProperty(DCTerms.license, pathwayLicense.item(0).getAttributes().getNamedItem("License").getNodeValue());
// pathwayResource.addProperty(Biopax_level3.BIOPAX3,
// interactionName);
pathwayResource.addProperty(DC.identifier, wpIdentifier);
pathwayResource.addProperty(DC.publisher,
"http://www.wikipathways.org");
pathwayResource.addProperty(scientificName, pathwaySpecies);
pathwayResource.addProperty(DCTerms.isPartOf, "http://www.wikipathways.org");
//pathwayResrouce.addProperty(DCTerms.bibliographicCitation, )
model.setNsPrefix("nsWikipathways", nsWikipathways);
model.setNsPrefix("species", nsWikipathways + "/species/");
model.setNsPrefix("genmapp", nsGenmapp);
model.setNsPrefix("bibo", bibo.NS);
model.setNsPrefix("biopax3", Biopax_level3.BIOPAX3);
model.setNsPrefix("dwc", nsDwc);
model.setNsPrefix("dcterms", DCTerms.getURI());
for (PathwayElement pwElm : pathway.getDataObjects()) {
// Only take elements with type DATANODE (genes, proteins,
// metabolites)
if (pwElm.getObjectType() == ObjectType.DATANODE) {
Resource pathwayEntity = model
.createResource(nsWikipathways+"/"+wpIdentifier + "/Datanode/"
+ pwElm.getGraphId());
pathwayEntity
.addProperty(DCTerms.isPartOf, pathwayResource);
pathwayEntity.addProperty(RDFS.label, pwElm.getTextLabel());
pathwayEntity.addProperty(RDF.type, Biopax_level3.Entity);
pathwayEntity.addProperty(rdfHasDataNodeType,
pwElm.getDataNodeType());
pathwayEntity.addProperty(DC.identifier, pwElm.getGeneID());
if (pwElm.getGroupRef() != null){ //Element is part of a group
pathwayEntity.addProperty(DCTerms.isPartOf, model.getResource(nsWikipathways+"/"+wpIdentifier+"/Group/"+pwElm.getGroupRef()));
}
//pathwayEntity.addProperty(DC.source, pwElm.getDataSource().toString());
if (pwElm.getDataNodeType() == "Metabolite"){
pathwayEntity.addProperty(RDF.type, Biopax_level3.ChemicalStructure);
}
if (pwElm.getDataNodeType().equals("Pathway")){
System.out.println(pwElm.getDataNodeType());
Resource interactingPathwayResource = model.createResource(nsWikipathways+"/"+wpIdentifier+"/PathwayInteraction/"+pwElm.getGraphId());
interactingPathwayResource.addProperty(RDFS.domain, Biopax_level3.Interaction);
interactingPathwayResource.addProperty(RDFS.range, pathwayResource);
interactingPathwayResource.addProperty(RDFS.range, model.createResource("http://www.wikipathways.org/index.php/Pathway:"+pwElm.getXref()));
}
}
if (pwElm.getObjectType().equals(ObjectType.LINE)){
Resource pathwayLine = model.createResource(nsWikipathways +"/"+wpIdentifier+ "/Line/"+ pwElm.getGraphId());
pathwayLine.addProperty(RDFS.domain, Biopax_level3.Interaction);
if (((pathway.getGroupIds().contains(pwElm.getStartGraphRef())||(pathway.getGraphIds().contains(pwElm.getStartGraphRef()))) &&
((pathway.getGroupIds().contains(pwElm.getEndGraphRef()))||(pathway.getGraphIds().contains(pwElm.getEndGraphRef()))))){
String startGroupOrDatanode;
String endGroupOrDatanode;
if (pathway.getGroupIds().contains(pwElm.getStartGraphRef())){
startGroupOrDatanode = "/Group/";
}
else {
startGroupOrDatanode = "/Datanode/";
}
if (pathway.getGroupIds().contains(pwElm.getEndGraphRef())){
endGroupOrDatanode = "/Group/";
}
else {
endGroupOrDatanode = "/Datanode/";
}
pathwayLine.addProperty(RDFS.range, model.getResource(nsWikipathways+"/"+wpIdentifier+startGroupOrDatanode+pwElm.getStartGraphRef()));
pathwayLine.addProperty(RDFS.range, model.getResource(nsWikipathways+"/"+wpIdentifier+endGroupOrDatanode+pwElm.getEndGraphRef()));
}
}
if (pwElm.getObjectType() == ObjectType.LABEL) {
//System.out.println("Label found");
Resource pathwayEntity = model
.createResource(nsWikipathways +"/"+wpIdentifier+ "/Label/"
+ pwElm.getGraphId());
pathwayEntity
.addProperty(DCTerms.isPartOf, pathwayResource);
pathwayEntity.addProperty(RDFS.label, pwElm.getTextLabel());
pathwayEntity.addProperty(RDF.type, RDFS.comment);
//pathwayEntity.addProperty(DC.source, pwElm.getDataSource().toString());
}
if (pwElm.getObjectType() == ObjectType.STATE) {
//System.out.println("Label found");
Resource pathwayEntity = model
.createResource(nsWikipathways +"/"+wpIdentifier+ "/State/"
+ pwElm.getGraphId());
pathwayEntity
.addProperty(DCTerms.isPartOf, pathwayResource);
pathwayEntity.addProperty(RDFS.label, pwElm.getTextLabel());
//pathwayEntity.addProperty(DC.source, pwElm.getDataSource().toString());
}
}
//System.out.println(wsPathway.getGpml());
NodeList nl = doc.getElementsByTagName("bp:PublicationXref");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//System.out.println("xRef: "+nl.item(i).getAttributes().item(0).getNodeValue());
NodeList refId=nl.item(i).getChildNodes();
if (refId.getLength()>3){
if (refId.item(3).getTextContent().equals("PubMed") && (refId.item(1).getTextContent() != null) ){
Resource pubmedEntity = model.createResource("http://www.ncbi.nlm.nih.gov/pubmed/"+refId.item(1).getTextContent());
pubmedEntity.addProperty(DCTerms.identifier, refId.item(1).getTextContent());
System.out.println(bpRefmap.get(nl.item(i).getAttributes().item(0).getNodeValue()).toString());
System.out.println("Lees: "+bpRefmap.get(nl.item(i).getAttributes().item(0).getNodeValue()).toString());
Resource tempItem =model.createResource(bpRefmap.get(nl.item(i).getAttributes().item(0).getNodeValue()).toString());
tempItem.addProperty(DCTerms.bibliographicCitation, pubmedEntity);
}
//System.out.println(refId.item(3).getNodeName() + ": "+refId.item(3).getTextContent());
//System.out.println(refId.item(1).getNodeName()+": "+refId.item(1).getTextContent());
}else
{
System.out.println("PROBLEM with: "+wpIdentifier);
}
}
}
FileOutputStream fout = new FileOutputStream("rdfoutput/"+wpIdentifier+".rdf");
model.write(fout, "N-TRIPLE");
}
} catch (Exception e) {
System.out.println("ERROR IN: "+ pathwaylist.getId());
e.printStackTrace();
}
}
FileOutputStream foutEnd = new FileOutputStream("rdfoutput/wikipathways.rdf");
model.write(foutEnd, "N-TRIPLE");
//model.write(fout);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
gpl-2.0
|
hashfunktion/icingaweb2-module-director
|
library/Director/Data/Db/DbConnection.php
|
836
|
<?php
namespace Icinga\Module\Director\Data\Db;
use Icinga\Data\Db\DbConnection as IcingaDbConnection;
use Zend_Db_Expr;
class DbConnection extends IcingaDbConnection
{
public function isMysql()
{
return $this->getDbType() === 'mysql';
}
public function isPgsql()
{
return $this->getDbType() === 'pgsql';
}
public function quoteBinary($binary)
{
if ($this->isPgsql()) {
return new Zend_Db_Expr("'\\x" . bin2hex($binary) . "'");
}
return $binary;
}
public function hasPgExtension($name)
{
$db = $this->db();
$query = $db->select()->from(
array('e' => 'pg_extension'),
array('cnt' => 'COUNT(*)')
)->where('extname = ?', $name);
return (int) $db->fetchOne($query) === 1;
}
}
|
gpl-2.0
|
thuypx1983/solohaplaza
|
sites/all/modules/slick/js/slick.load.js
|
6071
|
/**
* @file
* Provides Slick loader.
*/
/* global jQuery:false, Drupal:false */
/* jshint -W072 */
/* eslint max-params: 0, consistent-this: [0, "_"] */
(function ($, Drupal) {
"use strict";
Drupal.behaviors.slick = {
attach: function (context, settings) {
var _ = this;
$(".slick", context).once("slick", function () {
var that = this,
b,
t = $("> .slick__slider", that).length ? $("> .slick__slider", that) : $(that),
a = $("> .slick__arrow", that),
o = $.extend({}, settings.slick, t.data("slick"));
// Populate defaults + globals into each breakpoint.
if ($.type(o.responsive) === "array" && o.responsive.length) {
for (b in o.responsive) {
if (o.responsive.hasOwnProperty(b)
&& o.responsive[b].settings !== "unslick") {
o.responsive[b].settings = $.extend(
{},
settings.slick,
_.globals(t, a, o),
o.responsive[b].settings);
}
}
}
// Update the slick settings object.
t.data("slick", o);
o = t.data("slick") || {};
// Build the Slick.
_.beforeSlick(t, a, o);
t.slick(_.globals(t, a, o));
_.afterSlick(t, o);
// Destroy Slick if it is an enforced unslick.
// This allows Slick lazyload to run, but prevents further complication.
// Should use lazyLoaded event, but images are not always there.
if (t.hasClass("unslick")) {
t.slick("unslick");
$(".slide", t).removeClass("slide--loading");
}
});
},
/**
* The event must be bound prior to slick being called.
*/
beforeSlick: function (t, a, o) {
var _ = this,
r = $(".slide--0 .media--ratio", t);
_.randomize(t, o);
// Fixed for broken slick with Blazy, aspect ratio, hidden containers.
if (r.length && r.is(":hidden")) {
r.removeClass("media--ratio").addClass("js-media--ratio");
}
t.on("setPosition.slick", function (e, slick) {
_.setPosition(t, a, o, slick);
});
$(".media--loading", t).closest(".slide").addClass("slide--loading");
t.on("lazyLoaded lazyLoadError", function (e, slick, img, src) {
_.setBackground(img);
});
},
/**
* The event must be bound after slick being called.
*/
afterSlick: function (t, o) {
var _ = this,
slick = t.slick("getSlick"),
$ratio = $(".js-media--ratio", t);
// Arrow down jumper.
t.parent().on("click.slick.load", ".slick-down", function (e) {
e.preventDefault();
var b = $(this);
$("html, body").stop().animate({
scrollTop: $(b.data("target")).offset().top - (b.data("offset") || 0)
}, 800, o.easing);
});
if (o.mousewheel) {
t.on("mousewheel.slick.load", function (e, delta) {
e.preventDefault();
return (delta < 0) ? t.slick("slickNext") : t.slick("slickPrev");
});
}
// Fixed for broken slick with Blazy, aspect ratio, hidden containers.
if ($ratio.length) {
// t[0].slick.refresh();
t.trigger("resize");
$ratio.addClass("media--ratio").removeClass("js-media--ratio");
}
t.trigger("afterSlick", [_, slick, slick.currentSlide]);
},
/**
* Turns images into CSS background if so configured.
*/
setBackground: function (img, unslick) {
var $img = $(img),
$bg = $img.closest(".media--background");
$img.closest(".media").removeClass("media--loading").addClass("media--loaded");
$img.closest(".slide--loading").removeClass("slide--loading");
if ($bg.length) {
$bg.css("background-image", "url(" + $img.attr("src") + ")");
$bg.find("> img").remove();
$bg.removeAttr("data-lazy");
}
},
/**
* Randomize slide orders, for ads/products rotation within cached blocks.
*/
randomize: function (t, o) {
if (o.randomize && !t.hasClass("slick-initiliazed")) {
t.children().sort(function () {
return 0.5 - Math.random();
}).each(function () {
t.append(this);
});
}
},
/**
* Updates arrows visibility based on available options.
*/
setPosition: function (t, a, o, slick) {
// Be sure the most complex slicks are taken care of as well, e.g.:
// asNavFor with the main display containing nested slicks.
// https://github.com/kenwheeler/slick/pull/1846
if (t.attr("id") === slick.$slider.attr("id")) {
// Removes padding rules, if no value is provided to allow non-inline.
if (!o.centerPadding || o.centerPadding === "0") {
slick.$list.css("padding", "");
}
// Do not remove arrows, to allow responsive have different options.
return slick.slideCount <= o.slidesToShow || o.arrows === false
? a.addClass("element-hidden") : a.removeClass("element-hidden");
}
},
/**
* Declare global options explicitly to copy into responsive settings.
*/
globals: function (t, a, o) {
return {
slide: o.slide,
lazyLoad: o.lazyLoad,
dotsClass: o.dotsClass,
rtl: o.rtl,
appendDots: o.appendDots === ".slick__arrow"
? a : (o.appendDots || $(t)),
prevArrow: $(".slick-prev", a),
nextArrow: $(".slick-next", a),
appendArrows: a,
customPaging: function (slick, i) {
var tn = slick.$slides.eq(i).find("[data-thumb]") || null,
alt = Drupal.t(tn.attr("alt")) || "",
img = "<img alt='" + alt + "' src='" + tn.data("thumb") + "'>",
dotsThumb = tn.length && o.dotsClass.indexOf("thumbnail") > 0 ?
"<div class='slick-dots__thumbnail'>" + img + "</div>" : "";
return slick.defaults.customPaging(slick, i).add(dotsThumb);
}
};
}
};
})(jQuery, Drupal);
|
gpl-2.0
|
JacobXie/leanote
|
app/lea/binder/binder.go
|
6068
|
package binder
import (
"github.com/JacobXie/leanote/app/controllers"
"github.com/JacobXie/leanote/app/info"
"github.com/revel/revel"
// "github.com/JacobXie/leanote/app/controllers/api"
"fmt"
"reflect"
"strings"
)
// leanote binder struct
// rewrite revel struct binder
// not need the struct name as prefix,
// eg:
// type Note struct {Name}
// func (c Controller) List(note Note) revel.Result {}
// in revel you must pass the note.Name as key, now you just pass Name
// for test
// map[string][string]
var MSSBinder = revel.Binder{
Bind: func(params *revel.Params, name string, typ reflect.Type) reflect.Value {
var (
result = reflect.MakeMap(typ)
keyType = typ.Key()
valueType = typ.Elem()
)
for paramName, values := range params.Values {
key := paramName // [len(name)+1 : len(paramName)-1]
// ๆฏไธไธชๅผ values[0]
result.SetMapIndex(revel.BindValue(key, keyType), revel.BindValue(values[0], valueType))
}
return result
},
Unbind: func(output map[string]string, name string, val interface{}) {
mapValue := reflect.ValueOf(val)
for _, key := range mapValue.MapKeys() {
revel.Unbind(output, fmt.Sprintf("%v", key.Interface()),
mapValue.MapIndex(key).Interface())
}
},
}
// struct้่ฆ., a.b = "life"
// a: contollerๆฏๅฝขๅๅ
// ไฟฎๆน, ้ป่ฎคๅฐฑๆฏa.b, ไผ b
func nextKey(key string) string {
fieldLen := strings.IndexAny(key, ".[")
if fieldLen == -1 {
return key
}
return key[:fieldLen]
}
var leanoteStructBinder = revel.Binder{
// name == "noteOrContent"
Bind: func(params *revel.Params, name string, typ reflect.Type) reflect.Value {
result := reflect.New(typ).Elem() // ๅๅปบไธไธช่ฏฅ็ฑปๅ็, ็ถๅๅ
ถfieldไปๆๆ็paramๅปๅ
fieldValues := make(map[string]reflect.Value)
// fmt.Println(name)
// fmt.Println(typ) // api.NoteFiles
// name = files[0], files[1], noteContent
// fmt.Println(params.Values)
/*
map[Title:[test1] METHOD:[POST] NotebookId:[54c4f51705fcd14031000002]
files[1][FileId]:[]
controller:[note]
files[1][LocalFileId]:[54c7ae27d98d0329dd000000] files[1][HasBody]:[true] files[0][FileId]:[] files[0][LocalFileId]:[54c7ae855e94ea2dba000000] action:[addNote] Content:[<p>lifedddddd</p><p><img src="app://leanote/data/54bdc65599c37b0da9000002/images/1422368307147_2.png" alt="" data-mce-src="app://leanote/data/54bdc65599c37b0da9000002/images/1422368307147_2.png" style="display: block; margin-left: auto; margin-right: auto;"></p><p><img src="http://127.0.0.1:8008/api/file/getImage?fileId=54c7ae27d98d0329dd000000" alt="" data-mce-src="http://127.0.0.1:8008/api/file/getImg?fileId=54c7ae27d98d0329dd000000"></p><p><br></p><p><img src="http://127.0.0.1:8008/api/file/getImage?fileId=54c7ae855e94ea2dba000000" alt="" data-mce-src="http://127.0.0.1:8008/api/file/getImage?fileId=54c7ae855e94ea2dba000000" style="display: block; margin-left: auto; margin-right: auto;"></p><p><br></p><p><br></p>] IsBlog:[false] token:[user1]
files[0][HasBody]:[true]]
*/
nameIsSlice := strings.Contains(name, "[")
// fmt.Println(params.Values["files[1]"])
// fmt.Println(params.Values["Title"])
for key, _ := range params.Values { // Title, Content, Files
// ่ฟ้, ๅฆๆๆฒกๆ็น, ้ป่ฎคๅฐฑๆฏa.
// life
// fmt.Println("key:" + key); // files[0][LocalFileId]
// fmt.Println("name:" + name); // files[0][LocalFileId]
var suffix string
var noPrefix = false
if nameIsSlice && strings.HasPrefix(key, name) {
suffix = key[len(name)+1 : len(key)-1] // files[0][LocalFileId] ๅปๆ => LocalFileId
} else if !strings.HasPrefix(key, name+".") {
noPrefix = true
suffix = key
// continue
} else {
// Get the name of the struct property.
// Strip off the prefix. e.g. foo.bar.baz => bar.baz
suffix = key[len(name)+1:]
}
// fmt.Println(suffix);
fieldName := nextKey(suffix) // e.g. bar => "bar", bar.baz => "bar", bar[0] => "bar"
// fmt.Println(fieldName);
fieldLen := len(fieldName)
if _, ok := fieldValues[fieldName]; !ok {
// Time to bind this field. Get it and make sure we can set it.
fieldName = strings.Title(fieldName) // ไผ ่ฟๆฅtitle, ไฝstructๆฏTitle
// fmt.Println("xx: " + fieldName)
fieldValue := result.FieldByName(fieldName)
// fmt.Println(fieldValue)
if !fieldValue.IsValid() {
continue
}
if !fieldValue.CanSet() {
continue
}
var boundVal reflect.Value
// ๆฒกๆnameๅ็ผ
if noPrefix {
// life
// fmt.Println("<<")
// fmt.Println(strings.Title(key[:fieldLen]));
boundVal = revel.Bind(params, key[:fieldLen], fieldValue.Type())
} else {
// fmt.Println("final")
// fmt.Println(key[:len(name)+1+fieldLen]) // files[0][HasBody
if nameIsSlice {
fieldLen += 1
}
boundVal = revel.Bind(params, key[:len(name)+1+fieldLen], fieldValue.Type())
}
fieldValue.Set(boundVal)
fieldValues[fieldName] = boundVal
}
}
return result
},
Unbind: func(output map[string]string, name string, iface interface{}) {
val := reflect.ValueOf(iface)
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
structField := typ.Field(i)
fieldValue := val.Field(i)
// PkgPath is specified to be empty exactly for exported fields.
if structField.PkgPath == "" {
revel.Unbind(output, fmt.Sprintf("%s.%s", name, structField.Name), fieldValue.Interface())
}
}
},
}
func init() {
revel.TypeBinders[reflect.TypeOf(info.UserBlogBase{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(info.UserBlogComment{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(info.UserBlogStyle{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(info.Notebook{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(info.UserAccount{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(controllers.NoteOrContent{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(info.ApiNote{})] = leanoteStructBinder
revel.TypeBinders[reflect.TypeOf(info.NoteFile{})] = leanoteStructBinder
}
|
gpl-2.0
|
emundus/v5
|
components/com_fabrik/libs/getid3/getid3/module.misc.cue.php
|
8495
|
<?php
/////////////////////////////////////////////////////////////////
/// getID3() by James Heinrich <info@getid3.org> //
// available at http://getid3.sourceforge.net //
// or http://www.getid3.org //
/////////////////////////////////////////////////////////////////
// See readme.txt for more details //
/////////////////////////////////////////////////////////////////
// //
// module.misc.cue.php //
// module for analyzing CUEsheet files //
// dependencies: NONE //
// //
/////////////////////////////////////////////////////////////////
// //
// Module originally written [2009-Mar-25] by //
// Nigel Barnes <ngbarnes๏ฟฝhotmail*com> //
// Minor reformatting and similar small changes to integrate //
// into getID3 by James Heinrich <info@getid3.org> //
// ///
/////////////////////////////////////////////////////////////////
/*
* CueSheet parser by Nigel Barnes.
*
* This is a PHP conversion of CueSharp 0.5 by Wyatt O'Day (wyday.com/cuesharp)
*/
/**
* A CueSheet class used to open and parse cuesheets.
*
*/
class getid3_cue extends getid3_handler
{
var $cuesheet = array();
function Analyze() {
$info = &$this->getid3->info;
$info['fileformat'] = 'cue';
$this->readCueSheetFilename($info['filenamepath']);
$info['cue'] = $this->cuesheet;
return true;
}
function readCueSheetFilename($filename)
{
$filedata = file_get_contents($filename);
return $this->readCueSheet($filedata);
}
/**
* Parses a cue sheet file.
*
* @param string $filename - The filename for the cue sheet to open.
*/
function readCueSheet(&$filedata)
{
$cue_lines = array();
foreach (explode("\n", str_replace("\r", null, $filedata)) as $line)
{
if ( (strlen($line) > 0) && ($line[0] != '#'))
{
$cue_lines[] = trim($line);
}
}
$this->parseCueSheet($cue_lines);
return $this->cuesheet;
}
/**
* Parses the cue sheet array.
*
* @param array $file - The cuesheet as an array of each line.
*/
function parseCueSheet($file)
{
//-1 means still global, all others are track specific
$track_on = -1;
for ($i=0; $i < count($file); $i++)
{
list($key) = explode(' ', strtolower($file[$i]), 2);
switch ($key)
{
case 'catalog':
case 'cdtextfile':
case 'isrc':
case 'performer':
case 'songwriter':
case 'title':
$this->parseString($file[$i], $track_on);
break;
case 'file':
$currentFile = $this->parseFile($file[$i]);
break;
case 'flags':
$this->parseFlags($file[$i], $track_on);
break;
case 'index':
case 'postgap':
case 'pregap':
$this->parseIndex($file[$i], $track_on);
break;
case 'rem':
$this->parseComment($file[$i], $track_on);
break;
case 'track':
$track_on++;
$this->parseTrack($file[$i], $track_on);
if (isset($currentFile)) // if there's a file
{
$this->cuesheet['tracks'][$track_on]['datafile'] = $currentFile;
}
break;
default:
//save discarded junk and place string[] with track it was found in
$this->parseGarbage($file[$i], $track_on);
break;
}
}
}
/**
* Parses the REM command.
*
* @param string $line - The line in the cue file that contains the TRACK command.
* @param integer $track_on - The track currently processing.
*/
function parseComment($line, $track_on)
{
$explodedline = explode(' ', $line, 3);
$comment_REM = (isset($explodedline[0]) ? $explodedline[0] : '');
$comment_type = (isset($explodedline[1]) ? $explodedline[1] : '');
$comment_data = (isset($explodedline[2]) ? $explodedline[2] : '');
if (($comment_REM == 'REM') && $comment_type) {
$comment_type = strtolower($comment_type);
$commment_data = trim($comment_data, ' "');
if ($track_on != -1) {
$this->cuesheet['tracks'][$track_on]['comments'][$comment_type][] = $comment_data;
} else {
$this->cuesheet['comments'][$comment_type][] = $comment_data;
}
}
}
/**
* Parses the FILE command.
*
* @param string $line - The line in the cue file that contains the FILE command.
* @return array - Array of FILENAME and TYPE of file..
*/
function parseFile($line)
{
$line = substr($line, strpos($line, ' ') + 1);
$type = strtolower(substr($line, strrpos($line, ' ')));
//remove type
$line = substr($line, 0, strrpos($line, ' ') - 1);
//if quotes around it, remove them.
$line = trim($line, '"');
return array('filename'=>$line, 'type'=>$type);
}
/**
* Parses the FLAG command.
*
* @param string $line - The line in the cue file that contains the TRACK command.
* @param integer $track_on - The track currently processing.
*/
function parseFlags($line, $track_on)
{
if ($track_on != -1)
{
foreach (explode(' ', strtolower($line)) as $type)
{
switch ($type)
{
case 'flags':
// first entry in this line
$this->cuesheet['tracks'][$track_on]['flags'] = array(
'4ch' => false,
'data' => false,
'dcp' => false,
'pre' => false,
'scms' => false,
);
break;
case 'data':
case 'dcp':
case '4ch':
case 'pre':
case 'scms':
$this->cuesheet['tracks'][$track_on]['flags'][$type] = true;
break;
default:
break;
}
}
}
}
/**
* Collect any unidentified data.
*
* @param string $line - The line in the cue file that contains the TRACK command.
* @param integer $track_on - The track currently processing.
*/
function parseGarbage($line, $track_on)
{
if ( strlen($line) > 0 )
{
if ($track_on == -1)
{
$this->cuesheet['garbage'][] = $line;
}
else
{
$this->cuesheet['tracks'][$track_on]['garbage'][] = $line;
}
}
}
/**
* Parses the INDEX command of a TRACK.
*
* @param string $line - The line in the cue file that contains the TRACK command.
* @param integer $track_on - The track currently processing.
*/
function parseIndex($line, $track_on)
{
$type = strtolower(substr($line, 0, strpos($line, ' ')));
$line = substr($line, strpos($line, ' ') + 1);
if ($type == 'index')
{
//read the index number
$number = intval(substr($line, 0, strpos($line, ' ')));
$line = substr($line, strpos($line, ' ') + 1);
}
//extract the minutes, seconds, and frames
$explodedline = explode(':', $line);
$minutes = (isset($explodedline[0]) ? $explodedline[0] : '');
$seconds = (isset($explodedline[1]) ? $explodedline[1] : '');
$frames = (isset($explodedline[2]) ? $explodedline[2] : '');
switch ($type) {
case 'index':
$this->cuesheet['tracks'][$track_on][$type][$number] = array('minutes'=>intval($minutes), 'seconds'=>intval($seconds), 'frames'=>intval($frames));
break;
case 'pregap':
case 'postgap':
$this->cuesheet['tracks'][$track_on][$type] = array('minutes'=>intval($minutes), 'seconds'=>intval($seconds), 'frames'=>intval($frames));
break;
}
}
function parseString($line, $track_on)
{
$category = strtolower(substr($line, 0, strpos($line, ' ')));
$line = substr($line, strpos($line, ' ') + 1);
//get rid of the quotes
$line = trim($line, '"');
switch ($category)
{
case 'catalog':
case 'cdtextfile':
case 'isrc':
case 'performer':
case 'songwriter':
case 'title':
if ($track_on == -1)
{
$this->cuesheet[$category] = $line;
}
else
{
$this->cuesheet['tracks'][$track_on][$category] = $line;
}
break;
default:
break;
}
}
/**
* Parses the TRACK command.
*
* @param string $line - The line in the cue file that contains the TRACK command.
* @param integer $track_on - The track currently processing.
*/
function parseTrack($line, $track_on)
{
$line = substr($line, strpos($line, ' ') + 1);
$track = JString::ltrim(substr($line, 0, strpos($line, ' ')), '0');
//find the data type.
$datatype = strtolower(substr($line, strpos($line, ' ') + 1));
$this->cuesheet['tracks'][$track_on] = array('track_number'=>$track, 'datatype'=>$datatype);
}
}
?>
|
gpl-2.0
|
vlabatut/totalboumboum
|
resources/ai/org/totalboumboum/ai/v200809/ais/dayioglugilgeckalan/v2c/ZoneEnum.java
|
387
|
package org.totalboumboum.ai.v200809.ais.dayioglugilgeckalan.v2c;
/**
*
* @author Ali Batuhan Dayioฤlugil
* @author Gรถkhan Geรงkalan
*
*/
public enum ZoneEnum {
/** */
CARACTERE,
/** */
RIVAL,
/** */
BOMBE,
/** */
FEUPOSSIBLE,
/** */
FEU,
/** */
BONUSFEU,
/** */
BONUSBOMBE,
/** */
BLOCDEST,
/** */
BLOCINDEST,
/** */
LIBRE
}
|
gpl-2.0
|
yvesh/weblinks
|
tests/_support/Step/Acceptance/weblink.php
|
2636
|
<?php
namespace Step\Acceptance;
/**
* Class Weblink
*
* Step Object to interact with a weblink
*
* @todo: this class should grow until being able to execute generic operations over a Weblink: change status, add to category...
*
* @package Step\Acceptance
* @link http://codeception.com/docs/06-ReusingTestCode#StepObjects
*/
class weblink extends \AcceptanceTester
{
/**
* Creates a weblink
*
* @param string $title The title for the weblink
* @param string $url The url for the weblink
* @param string $countClicks If not null, we set the "Count Clicks" weblink property to the given value.
*
*/
public function createWeblink($title, $url, $countClicks = null)
{
$I = $this;
$I->comment('I navigate to Weblinks page in /administrator/');
$I->amOnPage('administrator/index.php?option=com_weblinks');
$I->waitForText('Web Links', '30', ['css' => 'h1']);
$I->comment('I see weblinks page');
$I->comment('I try to save a weblink with a filled title and URL');
$I->click('New');
$I->waitForText('Web Link: New', '30', ['css' => 'h1']);
$I->fillField(['id' => 'jform_title'], $title);
$I->fillField(['id' => 'jform_url'], $url);
if ($countClicks !== null) {
$I->click(['link' => 'Options']);
$I->selectOptionInChosen("Count Clicks", $countClicks);
}
$I->clickToolbarButton('Save & Close');
$I->waitForText('Web link successfully saved', '30', ['id' => 'system-message-container']);
}
public function administratorDeleteWeblink($title)
{
$I = $this;
$I->amGoingTo('Navigate to Weblinks page in /administrator/');
$I->amOnPage('administrator/index.php?option=com_weblinks');
$I->waitForText('Web Links','30',['css' => 'h1']);
$I->expectTo('see weblinks page');
$I->amGoingTo('Search for the weblink');
$I->searchForItem($title);
$I->waitForText('Web Links','30',['css' => 'h1']);
$I->amGoingTo('Trash the weblink');
$I->checkAllResults();
$I->clickToolbarButton('Trash');
$I->waitForText('Web Links','30',['css' => 'h1']);
$I->waitForText('1 web link successfully trashed', 30, ['id' => 'system-message-container']);
$I->amGoingTo('Delete the weblink');
$I->selectOptionInChosen('- Select Status -', 'Trashed');
$I->amGoingTo('Search the just saved weblink');
$I->searchForItem($title);
$I->waitForText('Web Links','30',['css' => 'h1']);
$I->checkAllResults();
$I->click(['xpath'=> '//div[@id="toolbar-delete"]/button']);
$I->acceptPopup();
$I->waitForText('Web Links','30',['css' => 'h1']);
$I->waitForText('1 web link successfully deleted.', 30, ['id' => 'system-message-container']);
}
}
|
gpl-2.0
|
app-on-mic/olb-xeon-phi-0.8.0
|
src/complexGrids/multiBlockStructure/parallelDynamics.hh
|
14930
|
/* This file is part of the OpenLB library
*
* Copyright (C) 2007, 2008 Jonas Latt
* E-mail contact: info@openlb.net
* The most recent release of OpenLB can be downloaded at
* <http://www.openlb.net/>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 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.
*/
/** \file
* Parallel dynamics object -- generic template code
*/
#ifndef PARALLEL_DYNAMICS_HH
#define PARALLEL_DYNAMICS_HH
#include "complexGrids/mpiManager/mpiManager.h"
#include "parallelDynamics.h"
namespace olb {
#ifdef PARALLEL_MODE_MPI
////////////////////// Class ParallelDynamics /////////////////////////////
template<typename T, template<typename U> class Lattice>
ParallelDynamics<T,Lattice>::ParallelDynamics(std::vector<Cell<T,Lattice>*>& baseCells_, bool hasBulkCell_)
: baseCells(baseCells_), hasBulkCell(hasBulkCell_)
{ }
template<typename T, template<typename U> class Lattice>
Dynamics<T,Lattice>* ParallelDynamics<T,Lattice>::clone() const {
return new ParallelDynamics(baseCells, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
T ParallelDynamics<T,Lattice>::computeEquilibrium(int iPop, T rho, const T u[Lattice<T>::d], T uSqr) const
{
T eq = T();
if (hasBulkCell) {
eq = baseCells[0] -> computeEquilibrium(iPop, rho, u, uSqr);
}
singleton::mpi().bCastThroughMaster(&eq, 1, hasBulkCell);
return eq;
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::iniEquilibrium(Cell<T,Lattice>& cell, T rho, const T u[Lattice<T>::d]) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> getDynamics() -> iniEquilibrium(*baseCells[iCell], rho, u);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::collide(Cell<T,Lattice>& cell, LatticeStatistics<T>& statistics_) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> collide(statistics_);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::staticCollide (
Cell<T,Lattice>& cell, const T u[Lattice<T>::d],
LatticeStatistics<T>& statistics_ )
{
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> staticCollide(u, statistics_);
}
}
template<typename T, template<typename U> class Lattice>
T ParallelDynamics<T,Lattice>::computeRho(Cell<T,Lattice> const& cell) const {
T rho = T();
if (hasBulkCell) {
rho = baseCells[0] -> computeRho();
}
singleton::mpi().bCastThroughMaster(&rho, 1, hasBulkCell);
return rho;
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computeU(Cell<T,Lattice> const& cell, T u[Lattice<T>::d] ) const
{
if (hasBulkCell) {
baseCells[0] -> computeU(u);
}
singleton::mpi().bCastThroughMaster(u, Lattice<T>::d, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computeJ(Cell<T,Lattice> const& cell, T j[Lattice<T>::d] ) const
{
if (hasBulkCell) {
baseCells[0] -> getDynamics() -> computeJ(*baseCells[0], j);
}
singleton::mpi().bCastThroughMaster(j, Lattice<T>::d, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computeStress (
Cell<T,Lattice> const& cell, T rho, const T u[Lattice<T>::d],
T pi[util::TensorVal<Lattice<T> >::n] ) const
{
if (hasBulkCell) {
baseCells[0] -> getDynamics() -> computeStress(*baseCells[0], rho, u, pi);
}
singleton::mpi().bCastThroughMaster(pi, util::TensorVal<Lattice<T> >::n, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computeRhoU (
Cell<T,Lattice> const& cell, T& rho, T u[Lattice<T>::d] ) const
{
if (hasBulkCell) {
baseCells[0] -> computeRhoU(rho, u);
}
singleton::mpi().bCastThroughMaster(&rho, 1, hasBulkCell);
singleton::mpi().bCastThroughMaster(u, Lattice<T>::d, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computeAllMomenta (
Cell<T,Lattice> const& cell, T& rho, T u[Lattice<T>::d],
T pi[util::TensorVal<Lattice<T> >::n] ) const
{
if (hasBulkCell) {
baseCells[0] -> computeAllMomenta(rho, u, pi);
}
singleton::mpi().bCastThroughMaster(&rho, 1, hasBulkCell);
singleton::mpi().bCastThroughMaster(u, Lattice<T>::d, hasBulkCell);
singleton::mpi().bCastThroughMaster(pi, util::TensorVal<Lattice<T> >::n, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computePopulations(Cell<T,Lattice> const& cell, T* f) const
{
if (hasBulkCell) {
baseCells[0] -> computePopulations(f);
}
singleton::mpi().bCastThroughMaster(f, Lattice<T>::q, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::computeExternalField (
Cell<T,Lattice> const& cell, int pos, int size, T* ext ) const
{
if (hasBulkCell) {
baseCells[0] -> computeExternalField(pos, size, ext);
}
singleton::mpi().bCastThroughMaster(ext, Lattice<T>::ExternalField::numScalars, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::defineRho(Cell<T,Lattice>& cell, T rho) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> defineRho(rho);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::defineU(Cell<T,Lattice>& cell, const T u[Lattice<T>::d]) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> defineU(u);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::defineRhoU(Cell<T,Lattice>& cell, T rho, const T u[Lattice<T>::d]) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> defineRhoU(rho, u);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::defineAllMomenta (
Cell<T,Lattice>& cell, T rho, const T u[Lattice<T>::d],
const T pi[util::TensorVal<Lattice<T> >::n] )
{
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> defineAllMomenta(rho, u, pi);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::definePopulations(Cell<T,Lattice>& cell, const T* f)
{
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> definePopulations(f);
}
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::defineExternalField (
Cell<T,Lattice>& cell, int pos, int size, const T* ext )
{
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> defineExternalField(pos, size, ext);
}
}
template<typename T, template<typename U> class Lattice>
T ParallelDynamics<T,Lattice>::getParameter(int whichParameter) const {
T parameter = T();
if (hasBulkCell) {
parameter = baseCells[0] -> getDynamics() -> getParameter(whichParameter);
}
singleton::mpi().bCastThroughMaster(¶meter, 1, hasBulkCell);
return parameter;
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::setParameter(int whichParameter, T value) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> getDynamics() -> setParameter(whichParameter, value);
}
}
template<typename T, template<typename U> class Lattice>
T ParallelDynamics<T,Lattice>::getOmega() const {
T omega = T();
if (hasBulkCell) {
omega = baseCells[0] -> getDynamics() -> getOmega();
}
singleton::mpi().bCastThroughMaster(&omega, 1, hasBulkCell);
return omega;
}
template<typename T, template<typename U> class Lattice>
void ParallelDynamics<T,Lattice>::setOmega(T omega_) {
for (unsigned iCell=0; iCell<baseCells.size(); ++iCell) {
baseCells[iCell] -> getDynamics() -> setOmega(omega_);
}
}
////////////////// Class ConstParallelDynamics /////////////////////////
template<typename T, template<typename U> class Lattice>
ConstParallelDynamics<T,Lattice>::ConstParallelDynamics(std::vector<Cell<T,Lattice> const*>& baseCells_,
bool hasBulkCell_)
: baseCells(baseCells_), hasBulkCell(hasBulkCell_)
{ }
template<typename T, template<typename U> class Lattice>
Dynamics<T,Lattice>* ConstParallelDynamics<T,Lattice>::clone() const {
return new ConstParallelDynamics(baseCells, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
T ConstParallelDynamics<T,Lattice>::computeEquilibrium(int iPop, T rho, const T u[Lattice<T>::d], T uSqr) const
{
T eq = T();
if (hasBulkCell) {
eq = baseCells[0] -> computeEquilibrium(iPop, rho, u, uSqr);
}
singleton::mpi().bCastThroughMaster(&eq, 1, hasBulkCell);
return eq;
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::iniEquilibrium(Cell<T,Lattice>& cell, T rho, const T u[Lattice<T>::d])
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::collide(Cell<T,Lattice>& cell,
LatticeStatistics<T>& statistics_)
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::staticCollide (
Cell<T,Lattice>& cell, const T u[Lattice<T>::d],
LatticeStatistics<T>& statistics_ )
{ }
template<typename T, template<typename U> class Lattice>
T ConstParallelDynamics<T,Lattice>::computeRho(Cell<T,Lattice> const& cell) const {
T rho = T();
if (hasBulkCell) {
rho = baseCells[0] -> computeRho();
}
singleton::mpi().bCastThroughMaster(&rho, 1, hasBulkCell);
return rho;
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computeU(Cell<T,Lattice> const& cell, T u[Lattice<T>::d] ) const
{
if (hasBulkCell) {
baseCells[0] -> computeU(u);
}
singleton::mpi().bCastThroughMaster(u, Lattice<T>::d, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computeJ(Cell<T,Lattice> const& cell, T j[Lattice<T>::d] ) const
{
if (hasBulkCell) {
baseCells[0] -> getDynamics() -> computeJ(*baseCells[0], j);
}
singleton::mpi().bCastThroughMaster(j, Lattice<T>::d, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computeStress (
Cell<T,Lattice> const& cell, T rho, const T u[Lattice<T>::d],
T pi[util::TensorVal<Lattice<T> >::n] ) const
{
if (hasBulkCell) {
baseCells[0] -> getDynamics() -> computeStress(*baseCells[0], rho, u, pi);
}
singleton::mpi().bCastThroughMaster(pi, util::TensorVal<Lattice<T> >::n, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computeRhoU (
Cell<T,Lattice> const& cell, T& rho, T u[Lattice<T>::d] ) const
{
if (hasBulkCell) {
baseCells[0] -> computeRhoU(rho, u);
}
singleton::mpi().bCastThroughMaster(&rho, 1, hasBulkCell);
singleton::mpi().bCastThroughMaster(u, Lattice<T>::d, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computeAllMomenta (
Cell<T,Lattice> const& cell, T& rho, T u[Lattice<T>::d],
T pi[util::TensorVal<Lattice<T> >::n] ) const
{
if (hasBulkCell) {
baseCells[0] -> computeAllMomenta(rho, u, pi);
}
singleton::mpi().bCastThroughMaster(&rho, 1, hasBulkCell);
singleton::mpi().bCastThroughMaster(u, Lattice<T>::d, hasBulkCell);
singleton::mpi().bCastThroughMaster(pi, util::TensorVal<Lattice<T> >::n, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computePopulations(Cell<T,Lattice> const& cell, T* f) const
{
if (hasBulkCell) {
baseCells[0] -> computePopulations(f);
}
singleton::mpi().bCastThroughMaster(f, Lattice<T>::q, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::computeExternalField (
Cell<T,Lattice> const& cell, int pos, int size, T* ext ) const
{
if (hasBulkCell) {
baseCells[0] -> computeExternalField(pos, size, ext);
}
singleton::mpi().bCastThroughMaster(ext, Lattice<T>::ExternalField::numScalars, hasBulkCell);
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::defineRho(Cell<T,Lattice>& cell, T rho)
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::defineU(Cell<T,Lattice>& cell, const T u[Lattice<T>::d])
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::defineRhoU(Cell<T,Lattice>& cell, T rho, const T u[Lattice<T>::d])
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::defineAllMomenta (
Cell<T,Lattice>& cell, T rho, const T u[Lattice<T>::d],
const T pi[util::TensorVal<Lattice<T> >::n] )
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::definePopulations (
Cell<T,Lattice>& cell, const T* f)
{ }
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::defineExternalField (
Cell<T,Lattice>& cell, int pos, int size, const T* ext )
{ }
template<typename T, template<typename U> class Lattice>
T ConstParallelDynamics<T,Lattice>::getParameter(int whichParameter) const {
T parameter = T();
if (hasBulkCell) {
parameter = baseCells[0] -> getDynamics() -> getParameter(whichParameter);
}
singleton::mpi().bCastThroughMaster(¶meter, 1, hasBulkCell);
return parameter;
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::setParameter(int whichParameter, T value)
{ }
template<typename T, template<typename U> class Lattice>
T ConstParallelDynamics<T,Lattice>::getOmega() const {
T omega = T();
if (hasBulkCell) {
omega = baseCells[0] -> getDynamics() -> getOmega();
}
singleton::mpi().bCastThroughMaster(&omega, 1, hasBulkCell);
return omega;
}
template<typename T, template<typename U> class Lattice>
void ConstParallelDynamics<T,Lattice>::setOmega(T omega_)
{ }
#endif
}
#endif // defined MULTIBLOCK_DYNAMICS_H
|
gpl-2.0
|
ablyx/teammates
|
src/test/java/teammates/test/cases/browsertests/AllJsTests.java
|
1875
|
package teammates.test.cases.browsertests;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import teammates.common.util.Const;
import teammates.test.driver.TestProperties;
import teammates.test.pageobjects.AppPage;
import teammates.test.pageobjects.QUnitPage;
/**
* Loads all JavaScript unit tests (done in QUnit) into a browser window and
* ensures all tests passed. This class is not using the PageObject pattern
* because it is not a regular UI test.
*/
public class AllJsTests extends BaseUiTestCase {
private static final float MIN_COVERAGE_REQUIREMENT = 25;
private QUnitPage page;
@Override
protected void prepareTestData() {
// no test data used in this test
}
@BeforeClass
public void classSetup() {
loginAdmin();
page = AppPage.getNewPageInstance(browser)
.navigateTo(createUrl(Const.ViewURIs.JS_UNIT_TEST))
.changePageType(QUnitPage.class);
page.waitForPageToLoad();
}
@Test
public void executeJsTests() {
int totalCases = page.getTotalCases();
int failedCases = page.getFailedCases();
print("Executed " + totalCases + " JavaScript Unit tests...");
// Some tests such as date-checking behave differently in Firefox and Chrome.
int expectedFailedCases = "firefox".equals(TestProperties.BROWSER) ? 0 : 4;
assertEquals(expectedFailedCases, failedCases);
assertTrue(totalCases != 0);
print("As expected, " + expectedFailedCases + " failed tests out of " + totalCases + " tests.");
float coverage = page.getCoverage();
print(coverage + "% of scripts covered, the minimum requirement is " + MIN_COVERAGE_REQUIREMENT + "%");
assertTrue(coverage >= MIN_COVERAGE_REQUIREMENT);
}
}
|
gpl-2.0
|
SergL/aboutttango
|
wp-content/plugins/siteheart/siteheart.php
|
5049
|
<?php
/*
Plugin Name: SiteHeart
Plugin URI: http://siteheart.com/
Description: SiteHeart - Free online chat for website.
Version: 1.0.0
Author: Pavel Kutsenko, Dmitry Goncharov, Inna Goncharova
Author URI: http://siteheart.com/
*/
define('SH_DEV',false);
define('SH_CONTENT_URL', get_option('siteurl') . '/wp-content');
define('SH_PLUGIN_URL', SH_CONTENT_URL . '/plugins/siteheart');
define('SH_XML_PATH',$_SERVER['DOCUMENT_ROOT'].'/wp-content/uploads');
define('SH_VERSION', '1.0.0');
define('SH_URL', 'http://siteheart.com');
register_deactivation_hook(__FILE__,'sh_delete');
register_activation_hook(__FILE__,'sh_active');
add_action('init', 'sh_request_handler');
add_action('admin_menu', 'sh_add_pages', 10);
add_action('admin_notices', 'sh_messages');
add_action ('wp_head', 'sh_add_widget');
function sh_request_handler() {
if(function_exists('load_plugin_textdomain')) {
load_plugin_textdomain('siteheart', 'wp-content/plugins/siteheart/locales');
}
}
/**
* Action by activating the plugin
*/
function sh_active(){
update_option( 'sh_widget_id', '' );
update_option( 'sh_template', '' );
update_option( 'sh_side', '' );
update_option( 'sh_position', '' );
update_option( 'sh_title', '' );
update_option( 'sh_title_offline', '' );
update_option( 'sh_inviteTimeout', '' );
update_option( 'sh_inviteCancelTimeout', '' );
update_option( 'sh_inviteText', '' );
update_option( 'sh_inviteImage', '' );
update_option( 'sh_devisions', '' );
update_option( 'sh_track', '' );
update_option( 'sh_hide', '' );
update_option( 'sh_hide_offline', '' );
update_option( 'sh_offline_pay', '' );
update_option( 'sh_text_layout', '' );
update_option( 'sh_secret_key', '' );
}
/**
* Action when uninstall plugin
*/
function sh_delete(){
delete_option( 'sh_widget_id' );
delete_option( 'sh_template' );
delete_option( 'sh_side' );
delete_option( 'sh_position' );
delete_option( 'sh_title' );
delete_option( 'sh_title_offline' );
delete_option( 'sh_inviteTimeout' );
delete_option( 'sh_inviteCancelTimeout' );
delete_option( 'sh_inviteText' );
delete_option( 'sh_inviteImage' );
delete_option( 'sh_devisions' );
delete_option( 'sh_track' );
delete_option( 'sh_hide' );
delete_option( 'sh_hide_offline' );
delete_option( 'sh_offline_pay' );
delete_option( 'sh_text_layout' );
delete_option( 'sh_secret_key' );
}
function sh_show_script(){
}
function sh_messages() {
$page = (isset($_GET['page']) ? $_GET['page'] : null);
if ( !get_option('sh_widget_id') && $page != 'siteheart' && $page != 'siteheart_admin') {
echo _e('<div class="updated"><p><b>You must <a href="admin.php?page=siteheart">configure the plugin</a> to enable Siteheart.</b></p></div>', 'siteheart');
}
}
function sh_options_page() {
if( $_SERVER["REQUEST_METHOD"] == "POST" ) {
update_option( 'sh_widget_id', $_POST['widget_id'] );
update_option( 'sh_template', $_POST['template'] );
update_option( 'sh_side', $_POST['side'] );
update_option( 'sh_position', $_POST['position'] );
update_option( 'sh_title', $_POST['title'] );
update_option( 'sh_title_offline', $_POST['title_offline'] );
update_option( 'sh_inviteTimeout', $_POST['inviteTimeout'] );
update_option( 'sh_inviteCancelTimeout', $_POST['inviteCancelTimeout'] );
update_option( 'sh_inviteText', $_POST['inviteText'] );
update_option( 'sh_inviteImage', $_POST['inviteImage'] );
update_option( 'sh_devisions', $_POST['devisions'] );
update_option( 'sh_track', $_POST['track'] );
update_option( 'sh_hide', $_POST['hide'] );
update_option( 'sh_hide_offline', $_POST['hide_offline'] );
update_option( 'sh_offline_pay', $_POST['offline_pay'] );
update_option( 'sh_text_layout', $_POST['text_layout'] );
update_option( 'sh_secret_key', $_POST['secret_key'] );
include_once(dirname(__FILE__) . '/success.php');
}
include_once(dirname(__FILE__) . '/set.php');
}
function sh_add_pages() {
$local_setings = substr(get_locale(), 0, 2) == 'ru' ? 'ะะฐัััะพะนะบะธ' : 'Settings';
$local_admin = substr(get_locale(), 0, 2) == 'ru' ? 'ะะตัะตะนัะธ ะฒ ะฟะฐะฝะตะปั ะฐะดะผะธะฝะธัััะฐัะพัะฐ' : 'Go to administrator panel';
add_menu_page( 'SiteHeart', 'SiteHeart', 'None', 'sh_options_page', '', '/wp-content/plugins/siteheart/img/siteheart_logo.png');
add_submenu_page(
'sh_options_page',
'SiteHeart',
$local_setings,
'moderate_comments',
'siteheart',
'sh_options_page'
);
add_submenu_page(
'sh_options_page',
'SiteHeart',
$local_admin,
'moderate_comments',
'siteheart_admin',
'sh_go'
);
}
function sh_add_widget(){
include_once dirname(__FILE__).'/widget.php';
}
function sh_go(){
echo '<script type="text/javascript">location.href = "http://siteheart.com/go";</script>';
}
?>
|
gpl-2.0
|
Himatekinfo/KP-Sistem-Pengelolaan-SPP-Madrasah-Mu-aliemien
|
protected/models/PeriodeBayar.php
|
2233
|
<?php
/**
* This is the model class for table "tbl_periode_bayar".
*
* The followings are the available columns in table 'tbl_periode_bayar':
* @property string $Id
* @property string $PeriodeBayar
*
* The followings are the available model relations:
* @property JnsTransaksi[] $jnsTransaksis
*/
class PeriodeBayar extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return PeriodeBayar the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_periode_bayar';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('PeriodeBayar', 'length', 'max'=>20),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('Id, PeriodeBayar', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'jnsTransaksis' => array(self::HAS_MANY, 'JnsTransaksi', 'PeriodeBayarId'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'Id' => 'ID',
'PeriodeBayar' => 'Periode Bayar',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('Id',$this->Id,true);
$criteria->compare('PeriodeBayar',$this->PeriodeBayar,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
|
gpl-2.0
|
bangnokia/dota2vn-bet-group
|
js/js.js
|
17850
|
function testscroll(target_id)
{
//document.location = document.location + '#' + target_id;
/*
if($("div").is("#" + target_id))
{
destination = $('#' + target_id).offset().top;
$('body').animate( { scrollTop: destination }, 1100 );
}.
*/
}
function select_all()
{
if($('.admin_checkbox').prop('checked') == true)
$('.admin_checkbox').prop('checked', false);
else
$('.admin_checkbox').prop('checked', true);
}
function reg_payment(input, id)
{
if(input.value == "")
document.getElementById(id).checked=false;
else
document.getElementById(id).checked=true;
}
function changeurl(url)
{
window.history.pushState("", "", url);
}
function popup(act_id)
{
document.getElementById(act_id).click();
}
function chart()
{
if($("div").is("#chart_canvas"))
{
var ctx = document.getElementById('chart_canvas').getContext('2d');
window.myLine = new Chart(ctx).Line(lineChartData,
{
responsive: true
});
}
}
function onloadpage(act)
{
if(act == "agree")
{
popup("agree_welcome");
}
if(act == "popup")
{
popup("popup_welcome");
}
if(act == "error")
{
popup("popup_error_finish");
}
chart();
}
//SLIDER
//var slider_interval = setInterval(function(){ next_slide(); }, 1000);
function stop_slide()
{
//clearInterval(slider_interval);
}
function start_slide()
{
window.slider_interval = setInterval(function(){ next_slide(); }, 5000);
}
function next_slide()
{
document.getElementById("rightControl").click();
}
$(document).ready(function(){
//if(document.getElementById('slidesContainer')) window.onload = start_slide;
var currentPosition = 0;
var slideWidth = 650;
var slides = $('.slide');
var numberOfSlides = slides.length;
$('#slidesContainer').css('overflow', 'hidden');
slides.wrapAll('<div id="slideInner"></div>')
.css({
'float' : 'left',
'width' : slideWidth - 10
});
$('#slideInner').css('width', slideWidth * numberOfSlides);
$('.control')
.bind('click', function(){
currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
//manageControls(currentPosition); // Hide / show controls
if(currentPosition > numberOfSlides-1) currentPosition = 0;
if(currentPosition < 0) currentPosition = numberOfSlides-1;
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
});
});
function manageControls(position){
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
}
});
function validateForm(title, text, form, module)
{
// + CHECK CAPCHA
if(module == "error")
{
if(form.comment.value.length < 2) { alertTip(title, text + " <span class='RedText'>comment text too short</span>. "); return; }
//form.submit();
}
if(module == "comments")
{
if(form.comment_message.value.length < 2) { alertTip(title, text + " <span class='RedText'>comment text too short</span>. "); return; }
//form.submit();
}
if(module == "hash_add")
{
if(form.hash.value.length < 5) { alertTip(title, text + " <span class='RedText'>hash too short</span>. "); return; }
if(form.type.value < 1) { alertTip(title, text + " <span class='RedText'>hash type</span>. "); return; }
if(form.price.value < 5) { alertTip(title, text + " <span class='RedText'>price</span>. "); return; }
//form.submit();
}
if(module == "hash_sell")
{
if(form.pass.value.length < 2) { alertTip(title, text + " <span class='RedText'>password too short</span>. "); return; }
//form.submit();
}
if(module == "search")
{
if(form.search_request.value.length < 2) { alertTip(title, text + " <span class='RedText'>search query too short</span>. "); return; }
//form.submit();
}
if(module == "refuse")
{
if(form.refuse_text.value.length < 2) { alertTip(title, text + " <span class='RedText'>refuse text too short</span>. "); return; }
//form.submit();
}
if(module == "pentest")
{
if(form.url.value.length < 4) { alertTip(title, text + " <span class='RedText'>Url too short</span>. "); return; }
if(form.owner.value > 2) { alertTip(title, text + " <span class='RedText'>Owner type</span>. "); return; }
//form.submit();
}
if(module == "reg")
{
if(form.login.value.length < 3) { alertTip(title, text + " <span class='RedText'>Login too short</span>. "); return; }
if(form.pass.value.length < 6) { alertTip(title, text + " <span class='RedText'>Password too short</span>. "); return; }
if(form.mail.value.length < 6) { alertTip(title, text + " <span class='RedText'>Mail</span>. "); return; }
}
if(module == "auth")
{
if(form.login.value.length < 3) { alertTip(title, text + " <span class='RedText'>Login too short</span>. "); return; }
if(form.pass.value.length < 6) { alertTip(title, text + " <span class='RedText'>Password too short</span>. "); return; }
//form.submit();
}
if(module == "restore")
{
if(form.mail.value.length < 6) { alertTip(title, text + " <span class='RedText'>Mail</span>. "); return; }
//form.submit();
}
if(module == "restore_pass")
{
if(form.new_password.value.length < 6) { alertTip(title, text + " <span class='RedText'>Password is too short</span>. "); return; }
if(form.repeat_password.value.length < 6) { alertTip(title, text + " <span class='RedText'>Repeated password is too short</span>. "); return; }
//form.submit();
}
if(module == "edit")
{
if(form.title.value.length < 3) { alertTip(title, text + " <span class='RedText'>title</span>. "); return; }
if(form.secret_code.value.length < 10) { alertTip(title, text + " <span class='RedText'>exploit code too short</span>. "); return; }
if(form.category.value < 1) { alertTip(title, text + " <span class='RedText'>category</span>. "); return; }
if(form.platform.value < 1) { alertTip(title, text + " <span class='RedText'>platform</span>. "); return; }
if(form.risk.value < 1) { alertTip(title, text + " <span class='RedText'>risk</span>. "); return; }
if(form.programming.value < 1) { alertTip(title, text + " <span class='RedText'>programming language</span>. "); return; }
//form.submit();
}
var check = document.getElementById("capcha_input");
if($check)
{
if(form.capcha.value.length != 5) { alertTip(title, text + " <span class='RedText'>Capcha is incorrect</span>. "); return; }
else
{
$.get("capcha/check/" + form.capcha.value, function( res ) {
if(res == false)
{
alertTip(title, text + " <span class='RedText'>Capcha is incorrect</span>. "); return;
}
else
{
form.submit();
}
}, 'html');
}
}
else
form.submit();
}
function alertTip(title, text)
{
text = text + "<br><br><button class='ok'>Ok</button>";
$('<div />').qtip({
content: {
text: text,
title: title
},
position: {
my: 'center', at: 'center',
target: $(window)
},
show: {
ready: true,
modal: {
on: true,
blur: false
}
},
hide: false,
style: 'dialogue',
events:
{
render: function(event, api) {
$( "body" ).append( "<div id='qtip-overlay' style='opacity: 1; z-index: 14800;'><div></div></div>" );
$('button.ok', api.elements.content).click(function(e) {
api.hide(e);
document.getElementById("qtip-overlay").remove();
});
},
hide: function(event, api) { api.destroy(); }
}
});
}
function confirmTip(title, text, url)
{
text = text + "<br><br><button class='ok'>Ok</button> <button class='cancel'>Cancel</button>";
$('<div />').qtip({
content: {
text: text,
title: title
},
position: {
my: 'center', at: 'center',
target: $(window)
},
show: {
ready: true,
modal: {
on: true,
blur: false
}
},
hide: false,
style: 'dialogue',
events:
{
render: function(event, api) {
//$('#qtip-overlay')
//api.elements.overlay.toggle(true);
$( "body" ).append( "<div id='qtip-overlay' style='opacity: 1; z-index: 14800;'><div></div></div>" );
$('button.ok', api.elements.content).click(function(e) {
api.hide(e);
document.getElementById("qtip-overlay").remove();
document.location = url;
});
$('button.cancel', api.elements.content).click(function(e) {
api.hide(e);
document.getElementById("qtip-overlay").remove();
});
},
hide: function(event, api) { api.destroy(); }
}
});
}
//// CHAT
function createGrowl(text, persistent)
{
var target = $('.qtip.jgrowl:visible:last');
$('<div/>').qtip({
content: {
text: text,
title: {
text: 'New Message',
button: true
}
},
position: {
target: [0,0],
container: $('#qtip-growl-container')
},
show: {
event: false,
ready: true,
effect: function() {
$(this).stop(0, 1).animate({ height: 'toggle' }, 400, 'swing');
},
delay: 0,
persistent: persistent
},
hide: {
event: false,
effect: function(api) {
$(this).stop(0, 1).animate({ height: 'toggle' }, 400, 'swing');
}
},
style: {
width: 250,
classes: 'jgrowl',
tip: false
},
events: {
render: function(event, api) {
if(!api.options.show.persistent) {
$(this).bind('mouseover mouseout', function(e) {
var lifespan = 5000;
clearTimeout(api.timer);
if (e.type !== 'mouseover') {
api.timer = setTimeout(function() { api.hide(e) }, lifespan);
}
})
.triggerHandler('mouseout');
}
}
}
});
}
function check_msg()
{
$.get("/support/check", function( text ) {
if(text != "")
{
document.getElementById("audio_receive_message").play(); // Play sound
createGrowl(text);// Show Notify
}
}, 'html');
$( ".support_contacts_item" ).each(function( index ) {
var div = $(".support_contacts_item").get(index);
var id = div.getAttribute('id');
$("#new_msg_" + id).load("/support/check/contacts/" + id);
});
}
//FIRST LOAD FOR USER
$(document).ready(
function()
{
var id = $("#chat_id").val();
if(id != undefined)
{
$("#chat_content").load("/support/load/" + id, function() {
$("#chat_content").animate({ scrollTop: document.getElementById("chat_content").scrollHeight });
});
}
}
);
//LOAD FOR ADMIN
$(document).ready(
function()
{
$('.support_contacts_item').click(
function()
{
if($(this).attr("id") != $("#chat_id").val())
{
$("#chat_content").html("<img src='/img/loading.gif'>");
window.history.pushState("", "", "/support/" + $(this).attr("id"));
$(".support_contacts").find(".support_contacts_item_selected").attr("class", "support_contacts_item");
$(this).attr("class", "support_contacts_item support_contacts_item_selected");
$("#chat_id").val($(this).attr("id"));
$("#chat_content").load("/support/load/" + $(this).attr("id"), function() {
$("#chat_content").animate({ scrollTop: document.getElementById("chat_content").scrollHeight });
});
}
}
);
}
);
//LOAD HISTORY
function load_history(history)
{
var chat_id = document.getElementById("chat_id").value;
var real_scroll = document.getElementById("chat_content").scrollHeight;
var prev_scroll = $("#scroll_height").attr("class");
var history_id = history.id;
document.getElementById(history.id).remove();
$("#chat_content").prepend(
$("<div>").load( "/support/load/history/" + chat_id + "/" + history_id, function()
{
var scroll = real_scroll - prev_scroll;
$("#scroll_height").attr("class", real_scroll);
document.getElementById("chat_content").scrollTop = scroll;
})
);
}
// SEND FUNC
function send_msg()
{
var text = $("#support_input_text").val();
var id = $("#chat_id").val();
if(id != undefined)
if(text.length > 0)
{
$("#support_input_text").val("");
$("#chat_content").append(
$("<div>").load( "/support/send/" + id + "/" + encodeURIComponent(text), function()
{
$("#chat_content").animate({ scrollTop: document.getElementById("chat_content").scrollHeight });
//document.getElementById("audio_send_message").play();
})
);
}
}
//SEND BY ENTER
$(document).ready(
function()
{
$("#support_input_text").keypress(
function(e)
{
if(e.keyCode==13)
{
e.preventDefault();
send_msg();
}
});
}
);
//SEND
$(document).ready(
function()
{
$('#support_input_button').click(
function(e)
{
send_msg();
}
);
}
);
var interval;
clearInterval(interval);
// RECEIVE
$(document).ready(
function()
{
interval = setInterval(function(){ receive_msg(); }, 3000);
}
);
// RECEIVE FUNC
function receive_msg()
{
var id = $("#chat_id").val();
if(id != undefined)
{
var scroll = false;
var system = document.getElementById("chat_content");
if((system.scrollTop + system.clientHeight) == system.scrollHeight) scroll = true;
$("#chat_content").append(
$("<div>").load( "/support/receive/" + id, function()
{
if(scroll)
{
//move_scroll = true;
//if(document.getElementById("chat_content").scrollHeight)
$("#chat_content").animate({ scrollTop: document.getElementById("chat_content").scrollHeight });
}
})
);
}
}
// DELETE
function delete_msg(message_id)
{
if(message_id != undefined)
{
$("<div>").load( "/support/delete/" + message_id, function(res)
{
if(res == 1)
$("#message_" + message_id).remove();
})
}
}
// DELETE
function delete_msg_all(message_id)
{
if(message_id != undefined)
{
$("<div>").load( "/support/delete/all/" + message_id, function(res)
{
if(res == 1)
$("#" + message_id).remove();
$("#chat_content").html("");
})
}
}
function change_radio(id)
{
document.getElementById(id).checked = true;
}
//// COMMENTS
function comments_change(id)
{
var count = 500;
var entered = $('#' + id).val();
entered = entered.length;
if(entered > count)
{
document.getElementById(id).value = document.getElementById(id).value.substring(0, count);
entered = count;
}
document.getElementById("limit_count_0").value = count - entered;
}
$(document).ready(
function()
{
$('.allow_tip').each(
function()
{
$(this).qtip({
content:
{
text: $(this).children('.TipText')
//, title: 'Sample'
},
position:
{
target: 'mouse',
adjust: { x: 20, y: 15 }
},
style: { classes: 'qtip-green' }
});
}
);
}
);
$( document ).ready(function() {
get_uploaded_imgs();
});
$(document).ready(
function()
{
$('div.allow_tip_big').each(
function()
{
$(this).qtip({
content:
{
text: $(this).children('.TipText')
//, title: 'Sample'
},
position:
{
adjust:
{
x: -870,
y: 15
}
},
style: { classes: 'qtip-green' }
});
}
);
}
);
function comments_rate(act, id)
{
if(act == 1)
{
$("#rate_down_div").css( "text-decoration", "none" );
$("#rate_up_div").css( "text-decoration", "underline" );
$("#rate_down").removeAttr('checked');
$("#rate_up").attr('checked', 'checked');
$("<div>").load("/rate/up/" + id);
}
if(act == 2)
{
$("#rate_up_div").css( "text-decoration", "none" );
$("#rate_down_div").css( "text-decoration", "underline" );
$("#rate_up").removeAttr('checked');
$("#rate_down").attr('checked', 'checked');
$("<div>").load("/rate/down/" + id);
}
}
function del_uploaded_imgs(del_id)
{
var id = $('#temp_id').val()
$("#fm_content").load("/uploaded/" + id + "/" + del_id);
}
function get_uploaded_imgs()
{
var id = $('#temp_id').val()
$("#fm_content").load("/uploaded/" + id );
}
function change_capcha()
{
$("#capcha").attr("src","/capcha/new");
}
function search_types(type)
{
if(type == 1)
{
$("#search_author").animate({height: 'hide'}, 10);
$("#search_content").animate({height: 'show'}, 400);
}
if(type == 2)
{
$("#search_content").animate({height: 'hide'}, 10);
$("#search_author").animate({height: 'show'}, 400);
}
}
function add_price(act, type)
{
if(act == "show")
{
if(type == 1)
{
$("#content_price_2").animate({height: 'hide'}, 200);
$("#content_price_1").animate({height: 'show'}, 400);
}
if(type == 2)
{
$("#content_price_1").animate({height: 'hide'}, 200);
$("#content_price_2").animate({height: 'show'}, 400);
}
}
if(act == "hide")
{
$("#content_price_1").animate({height: 'hide'}, 200);
$("#content_price_2").animate({height: 'hide'}, 200);
}
}
function faq (objName)
{
if( $(objName).css('display') == 'none' )
{
$(objName).animate({height: 'show'}, 400);
}
else
{
$(objName).animate({height: 'hide'}, 200);
}
}
$(function ()
{
$('#fileupload').fileupload({
url: '/uploader/' + $('#temp_id').val(),
done: function (e, data)
{
get_uploaded_imgs();
document.getElementById("progress_bar").style.width = "0%";
},
progressall: function (e, data)
{
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css( 'width', progress + '%');
}
});
});
|
gpl-2.0
|
khonkaen-hospital/ca-service
|
themes/AdminLTE/views/layouts/main1.php
|
6980
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo Yii::app()->name ?></title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<!-- bootstrap 3.0.2 -->
<!-- <link href="<?php //echo Yii::app()->theme->baseUrl; ?>/css/bootstrap.min.css" rel="stylesheet" type="text/css" />-->
<?php
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
//$cs->registerScriptFile($baseUrl . '/js/jquery.tablescroll.js');
$cs->registerCssFile($baseUrl . '/css/jquery.tablescroll.css');
?>
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<!-- Ionicons -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/ionicons.min.css" rel="stylesheet" type="text/css" />
<!-- Theme style -->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/AdminLTE.css" rel="stylesheet" type="text/css" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body class="skin-blue">
<!-- header logo: style can be found in header.less -->
<header class="header">
<a href="#" class="logo">
<!-- Add the class icon to your logo image or logo icon to add the margining -->
<i class="fa fa-plus-square"> </i> <span><?php echo Yii::app()->name; ?></span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="navbar-btn sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="navbar-right">
<ul class="nav navbar-nav">
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle account" data-toggle="dropdown">
<i class="glyphicon glyphicon-user"></i>
<span><?php echo Yii::app()->user->name; ?><i class="caret"></i></span>
</a>
<?php if (!Yii::app()->user->isGuest): ?>
<ul class="dropdown-menu">
<li class="user-header bg-light-blue">
<img src="<?php echo Yii::app()->theme->baseUrl; ?>/img/avatar3.png" class="img-circle" alt="User Image" />
<p>
<?php echo Yii::app()->user->name; ?>
<small>Member since Jul. 2014</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="col-xs-4 text-center">
<a href="#">Followers</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Sales</a>
</div>
<div class="col-xs-4 text-center">
<a href="#">Frends</a>
</div>
</li>
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="<?php echo Yii::app()->createUrl('duser/logout'); ?>" class="btn btn-default btn-flat">Sign Out</a>
</div>
</li>
</ul>
<?php endif; ?>
<?php if (Yii::app()->user->isGuest): ?>
<ul class="dropdown-menu dropdown-user">
<li><a href="<?php echo Yii::app()->createUrl('duser/login'); ?>"><i class="fa fa-lock fa-fw"></i> Login</a>
</li>
</ul>
<?php endif; ?>
</li>
</ul>
</div>
</nav>
</header>
<div class="wrapper row-offcanvas row-offcanvas-left">
<?php echo $content; ?>
</div><!-- ./wrapper -->
<!-- jQuery 2.0.2 -->
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>-->
<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<!-- Bootstrap -->
<!-- <script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/bootstrap.min.js" type="text/javascript"></script>-->
<!-- AdminLTE App -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/AdminLTE/app.js" type="text/javascript"></script>
<!--<script src="<?php //echo Yii::app()->theme->baseUrl; ?>/js/mixitup-master/jquery.mixitup.min.js" type="text/javascript"></script>-->
</body>
</html>
<script>
$(function() {
var loc = window.location.href;
$('.sidebar-menu li').each(function() {
var link = $(this).find('a:first').attr('href');
if (loc.indexOf(link) >= 0)
$(this).addClass('active');
});
});
$(".refresh-btn").on('click', function() {
location.reload();
});
</script>
<style>
/* grid border */
.grid-view table.items th, .grid-view table.items td {
border: 1px solid gray !important;
}
/* disable selection for extrarows */
.grid-view td.extrarow {
background: none repeat scroll 0 0 #F8F8F8;
}
.subtotal {
font-size: 14px;
color: brown;
font-weight: bold;
}
</style>
|
gpl-2.0
|
westerniowawireless/wiaw.net
|
wp-content/themes/shoestrap/lib/slide-down.php
|
2400
|
<?php
/*
* Calculates the class of the widget areas based on a 12-column bootstrap grid.
*/
function shoestrap_navbar_widget_area_class() {
$str = '';
if ( is_active_sidebar( 'navbar-slide-down-1' ) )
$str .= '1';
if ( is_active_sidebar( 'navbar-slide-down-2' ) )
$str .= '2';
if ( is_active_sidebar( 'navbar-slide-down-3' ) )
$str .= '3';
if ( is_active_sidebar( 'navbar-slide-down-4' ) )
$str .= '4';
$strlen = strlen( $str );
if ( $strlen > 0 ) {
$span = 12 / $strlen;
} else {
$span = 12;
}
return $span;
}
/*
* Prints the content of the slide-down widget areas.
*/
function shoestrap_navbar_slidedown_content() {
echo '<div id="megaDrop" class="container-fluid top-megamenu">';
echo '<div class="container">';
$widgetareaclass = 'span' . shoestrap_navbar_widget_area_class();
dynamic_sidebar('navbar-slide-down-top');
echo '<div class="row">';
if ( is_active_sidebar( 'navbar-slide-down-1' ) )
echo '<div class="' . $widgetareaclass . '">';
dynamic_sidebar('navbar-slide-down-1');
echo '</div>';
if ( is_active_sidebar( 'navbar-slide-down-2' ) )
echo '<div class="' . $widgetareaclass . '">';
dynamic_sidebar('navbar-slide-down-2');
echo '</div>';
if ( is_active_sidebar( 'navbar-slide-down-3' ) )
echo '<div class="' . $widgetareaclass . '">';
dynamic_sidebar('navbar-slide-down-3');
echo '</div>';
if ( is_active_sidebar( 'navbar-slide-down-4' ) )
echo '<div class="' . $widgetareaclass . '">';
dynamic_sidebar('navbar-slide-down-4');
echo '</div>';
echo '</div></div></div>';
}
add_action( 'shoestrap_nav_top_bottom', 'shoestrap_navbar_slidedown_content', 1 );
function shoestrap_navbar_slidedown_toggle() {
$navbar_color = get_theme_mod( 'shoestrap_navbar_color' );
if ( is_active_sidebar( 'navbar-slide-down-top' ) || is_active_sidebar( 'navbar-slide-down-1' ) || is_active_sidebar( 'navbar-slide-down-2' ) || is_active_sidebar( 'navbar-slide-down-3' ) || is_active_sidebar( 'navbar-slide-down-4' ) ) {
if ( shoestrap_get_brightness( $navbar_color ) >= 160 ) {
echo '<a style="width: 30px;" class="toggle-nav black" href="#"></a>';
} else {
echo '<a style="width: 30px;" class="toggle-nav" href="#"></a>';
}
}
}
add_action( 'shoestrap_primary_nav_top_left', 'shoestrap_navbar_slidedown_toggle' );
|
gpl-2.0
|
faysalmbt/digigo
|
wp-content/plugins/event-espresso-core-reg/caffeinated/core/libraries/messages/message_type/payment_cancelled/EE_Messages_Email_Payment_Cancelled_Validator.class.php
|
2140
|
<?php
if (!defined('EVENT_ESPRESSO_VERSION') )
exit('NO direct script access allowed');
/**
* EE_Messages_Email_Payment_Cancelled_Validator class
*
* Holds any special validation rules for template fields with Email messenger and Payment Cancelled message type.
*
* @package Event Espresso
* @subpackage messages
* @author Darren Ethier
* @since 4.6.x
*
* ------------------------------------------------------------------------
*/
class EE_Messages_Email_Payment_Cancelled_Validator extends EE_Messages_Validator {
public function __construct( $fields, $context ) {
$this->_m_name = 'email';
$this->_mt_name = 'payment_cancelled';
parent::__construct( $fields, $context );
}
/**
* at this point no custom validation needed for this messenger/message_type combo.
*/
protected function _modify_validator() {
$new_config = $this->_MSGR->get_validator_config();
//modify just event_list
$new_config['event_list'] = array(
'shortcodes' => array('event', 'attendee_list', 'ticket_list', 'datetime_list', 'venue', 'organization','recipient_details', 'recipient_list', 'event_author', 'primary_registration_details', 'primary_registration_list')
);
$new_config['ticket_list'] = array(
'shortcodes' => array('event_list', 'attendee_list', 'ticket', 'datetime_list', 'recipient_details', 'transaction')
);
$new_config['content'] = array(
'shortcodes' => array('event_list','attendee_list', 'ticket_list', 'organization', 'recipient_details', 'recipient_list', 'transaction', 'primary_registration_details', 'primary_registration_list', 'messenger')
);
$this->_MSGR->set_validator_config( $new_config );
if ( $this->_context != 'admin' )
$this->_valid_shortcodes_modifier[$this->_context]['event_list'] = array('event', 'attendee_list', 'ticket_list', 'datetime_list', 'venue', 'organization', 'event_author', 'primary_registration_details', 'primary_registration_list', 'recipient_details', 'recipient_list');
$this->_specific_shortcode_excludes['content'] = array('[DISPLAY_PDF_URL]', '[DISPLAY_PDF_BUTTON]');
}
} //end class EE_Messages_Email_Payment_Cancelled_Validator
|
gpl-2.0
|
Meowse/TechnicolorMillinery
|
Bridget.Lammers/Homework3/HappyBirthdayExtraCredit/HappyBirthdayExtraCredit/Form1.cs
|
3902
|
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HappyBirthdayExtraCredit
{
public partial class month_calendar : Form
{
public month_calendar()
{
InitializeComponent();
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
your_birthday_textbox.Text = monthCalendar1.SelectionRange.Start.ToShortDateString();
}
private void click_for_surprise_button_Click(object sender, EventArgs e)
{
if (name_textbox.Text == "")
{
MessageBox.Show("Please enter a name, required field.");
}
else if (your_birthday_textbox.Text == "")
{
MessageBox.Show("Please enter a date, pick a date from the Date Picker, required field");
} // End IF
if (your_birthday_textbox.Text != null)
{
// Converts the string representation of a date and time to its DateTime equivalent.
DateTime birthday_dt = DateTime.Parse(your_birthday_textbox.Text);
// Get Todays Date
DateTime todays_dt = DateTime.Now;
// Get times of day
DateTime beforeNoon = new DateTime(todays_dt.Year, todays_dt.Month, todays_dt.Day, 11, 59, 59);
DateTime beforeFive = new DateTime(todays_dt.Year, todays_dt.Month, todays_dt.Day, 16, 59, 59);
DateTime afterFive = new DateTime(todays_dt.Year, todays_dt.Month, todays_dt.Day, 17, 0, 0);
// Get todays date
// MessageBox.Show("Birthday " + birthday_dt + "\n" +
// "Today" + todays_dt + "\n" +
// "Before Noon" + beforeNoon + "\n" +
// "Before Five" + beforeFive + "\n" +
// "After Five" + afterFive);
// Is it their birthday
if (birthday_dt.Month == todays_dt.Month &&
birthday_dt.Day == todays_dt.Day)
{
int age = todays_dt.Year - birthday_dt.Year;
string str_age = age.ToString();
//MessageBox.Show("Age string " + str_age);
// Sing Happy Birthday the number times of their age
int i=0;
while(i <= age)
{
MessageBox.Show("Happy Birthday to you! " + str_age + " times\n" +
"Happy Birthday to you!\n" +
"Happy Birthday Dear " + name_textbox.Text + "\n" +
"Happy Birthday to youuuuuuuuuuu!");
i++;
} // End of While
}
// Not birthday, check before noon
else if (todays_dt < beforeNoon)
{
MessageBox.Show("Good morning " + name_textbox.Text);
}
// Cjecl before 5:00
else if (todays_dt < beforeFive)
{
MessageBox.Show("Time for Happy Hour, margarita and nachos! " + name_textbox.Text);
}
// Default after 5:00
else
{
MessageBox.Show("Good night and sleep well! " + name_textbox.Text);
}
} // End IF
} // End enter_button_Click
} // End of Class
} // End of namespace
|
gpl-2.0
|
koutheir/incinerator-hotspot
|
nashorn/src/jdk/nashorn/internal/runtime/ScriptFunction.java
|
40249
|
/*
* Copyright (c) 2010, 2013, 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 jdk.nashorn.internal.runtime;
import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCallNoLookup;
import static jdk.nashorn.internal.lookup.Lookup.MH;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.SwitchPoint;
import java.util.Collections;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.internal.dynalink.support.Guards;
import jdk.nashorn.internal.codegen.ApplySpecialization;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.objects.NativeFunction;
import jdk.nashorn.internal.runtime.ScriptFunctionData;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
/**
* Runtime representation of a JavaScript function.
*/
public abstract class ScriptFunction extends ScriptObject {
/** Method handle for prototype getter for this ScriptFunction */
public static final MethodHandle G$PROTOTYPE = findOwnMH_S("G$prototype", Object.class, Object.class);
/** Method handle for prototype setter for this ScriptFunction */
public static final MethodHandle S$PROTOTYPE = findOwnMH_S("S$prototype", void.class, Object.class, Object.class);
/** Method handle for length getter for this ScriptFunction */
public static final MethodHandle G$LENGTH = findOwnMH_S("G$length", int.class, Object.class);
/** Method handle for name getter for this ScriptFunction */
public static final MethodHandle G$NAME = findOwnMH_S("G$name", Object.class, Object.class);
/** Method handle used for implementing sync() in mozilla_compat */
public static final MethodHandle INVOKE_SYNC = findOwnMH_S("invokeSync", Object.class, ScriptFunction.class, Object.class, Object.class, Object[].class);
/** Method handle for allocate function for this ScriptFunction */
static final MethodHandle ALLOCATE = findOwnMH_V("allocate", Object.class);
private static final MethodHandle WRAPFILTER = findOwnMH_S("wrapFilter", Object.class, Object.class);
private static final MethodHandle SCRIPTFUNCTION_GLOBALFILTER = findOwnMH_S("globalFilter", Object.class, Object.class);
/** method handle to scope getter for this ScriptFunction */
public static final Call GET_SCOPE = virtualCallNoLookup(ScriptFunction.class, "getScope", ScriptObject.class);
private static final MethodHandle IS_FUNCTION_MH = findOwnMH_S("isFunctionMH", boolean.class, Object.class, ScriptFunctionData.class);
private static final MethodHandle IS_APPLY_FUNCTION = findOwnMH_S("isApplyFunction", boolean.class, boolean.class, Object.class, Object.class);
private static final MethodHandle IS_NONSTRICT_FUNCTION = findOwnMH_S("isNonStrictFunction", boolean.class, Object.class, Object.class, ScriptFunctionData.class);
private static final MethodHandle ADD_ZEROTH_ELEMENT = findOwnMH_S("addZerothElement", Object[].class, Object[].class, Object.class);
private static final MethodHandle WRAP_THIS = MH.findStatic(MethodHandles.lookup(), ScriptFunctionData.class, "wrapThis", MH.type(Object.class, Object.class));
/** The parent scope. */
private final ScriptObject scope;
private final ScriptFunctionData data;
/** The property map used for newly allocated object when function is used as constructor. */
protected PropertyMap allocatorMap;
/**
* Constructor
*
* @param name function name
* @param methodHandle method handle to function (if specializations are present, assumed to be most generic)
* @param map property map
* @param scope scope
* @param specs specialized version of this function - other method handles
* @param flags {@link ScriptFunctionData} flags
*/
protected ScriptFunction(
final String name,
final MethodHandle methodHandle,
final PropertyMap map,
final ScriptObject scope,
final MethodHandle[] specs,
final int flags) {
this(new FinalScriptFunctionData(name, methodHandle, specs, flags), map, scope);
}
/**
* Constructor
*
* @param data static function data
* @param map property map
* @param scope scope
*/
protected ScriptFunction(
final ScriptFunctionData data,
final PropertyMap map,
final ScriptObject scope) {
super(map);
if (Context.DEBUG) {
constructorCount++;
}
this.data = data;
this.scope = scope;
this.allocatorMap = data.getAllocatorMap();
}
@Override
public String getClassName() {
return "Function";
}
/**
* ECMA 15.3.5.3 [[HasInstance]] (V)
* Step 3 if "prototype" value is not an Object, throw TypeError
*/
@Override
public boolean isInstance(final ScriptObject instance) {
final Object basePrototype = getTargetFunction().getPrototype();
if (!(basePrototype instanceof ScriptObject)) {
throw typeError("prototype.not.an.object", ScriptRuntime.safeToString(getTargetFunction()), ScriptRuntime.safeToString(basePrototype));
}
for (ScriptObject proto = instance.getProto(); proto != null; proto = proto.getProto()) {
if (proto == basePrototype) {
return true;
}
}
return false;
}
/**
* Returns the target function for this function. If the function was not created using
* {@link #makeBoundFunction(Object, Object[])}, its target function is itself. If it is bound, its target function
* is the target function of the function it was made from (therefore, the target function is always the final,
* unbound recipient of the calls).
* @return the target function for this function.
*/
protected ScriptFunction getTargetFunction() {
return this;
}
boolean isBoundFunction() {
return getTargetFunction() != this;
}
/**
* Set the arity of this ScriptFunction
* @param arity arity
*/
public final void setArity(final int arity) {
data.setArity(arity);
}
/**
* Is this a ECMAScript 'use strict' function?
* @return true if function is in strict mode
*/
public boolean isStrict() {
return data.isStrict();
}
/**
* Returns true if this is a non-strict, non-built-in function that requires non-primitive this argument
* according to ECMA 10.4.3.
* @return true if this argument must be an object
*/
public boolean needsWrappedThis() {
return data.needsWrappedThis();
}
private static boolean needsWrappedThis(final Object fn) {
return fn instanceof ScriptFunction ? ((ScriptFunction)fn).needsWrappedThis() : false;
}
/**
* Execute this script function.
* @param self Target object.
* @param arguments Call arguments.
* @return ScriptFunction result.
* @throws Throwable if there is an exception/error with the invocation or thrown from it
*/
Object invoke(final Object self, final Object... arguments) throws Throwable {
if (Context.DEBUG) {
invokes++;
}
return data.invoke(this, self, arguments);
}
/**
* Execute this script function as a constructor.
* @param arguments Call arguments.
* @return Newly constructed result.
* @throws Throwable if there is an exception/error with the invocation or thrown from it
*/
Object construct(final Object... arguments) throws Throwable {
return data.construct(this, arguments);
}
/**
* Allocate function. Called from generated {@link ScriptObject} code
* for allocation as a factory method
*
* @return a new instance of the {@link ScriptObject} whose allocator this is
*/
@SuppressWarnings("unused")
private Object allocate() {
if (Context.DEBUG) {
allocations++;
}
assert !isBoundFunction(); // allocate never invoked on bound functions
final ScriptObject object = data.allocate(allocatorMap);
if (object != null) {
final Object prototype = getPrototype();
if (prototype instanceof ScriptObject) {
object.setInitialProto((ScriptObject)prototype);
}
if (object.getProto() == null) {
object.setInitialProto(getObjectPrototype());
}
}
return object;
}
/**
* Return Object.prototype - used by "allocate"
* @return Object.prototype
*/
protected abstract ScriptObject getObjectPrototype();
/**
* Creates a version of this function bound to a specific "self" and other arguments, as per
* {@code Function.prototype.bind} functionality in ECMAScript 5.1 section 15.3.4.5.
* @param self the self to bind to this function. Can be null (in which case, null is bound as this).
* @param args additional arguments to bind to this function. Can be null or empty to not bind additional arguments.
* @return a function with the specified self and parameters bound.
*/
protected ScriptFunction makeBoundFunction(final Object self, final Object[] args) {
return makeBoundFunction(data.makeBoundFunctionData(this, self, args));
}
/**
* Create a version of this function as in {@link ScriptFunction#makeBoundFunction(Object, Object[])},
* but using a {@link ScriptFunctionData} for the bound data.
*
* @param boundData ScriptFuntionData for the bound function
* @return a function with the bindings performed according to the given data
*/
protected abstract ScriptFunction makeBoundFunction(ScriptFunctionData boundData);
@Override
public final String safeToString() {
return toSource();
}
@Override
public String toString() {
return data.toString();
}
/**
* Get this function as a String containing its source code. If no source code
* exists in this ScriptFunction, its contents will be displayed as {@code [native code]}
* @return string representation of this function's source
*/
public final String toSource() {
return data.toSource();
}
/**
* Get the prototype object for this function
* @return prototype
*/
public abstract Object getPrototype();
/**
* Set the prototype object for this function
* @param prototype new prototype object
*/
public abstract void setPrototype(Object prototype);
/**
* Create a function that invokes this function synchronized on {@code sync} or the self object
* of the invocation.
* @param sync the Object to synchronize on, or undefined
* @return synchronized function
*/
public abstract ScriptFunction makeSynchronizedFunction(Object sync);
/**
* Return the invoke handle bound to a given ScriptObject self reference.
* If callee parameter is required result is rebound to this.
*
* @param self self reference
* @return bound invoke handle
*/
public final MethodHandle getBoundInvokeHandle(final Object self) {
return MH.bindTo(bindToCalleeIfNeeded(data.getGenericInvoker(scope)), self);
}
/**
* Bind the method handle to this {@code ScriptFunction} instance if it needs a callee parameter. If this function's
* method handles don't have a callee parameter, the handle is returned unchanged.
* @param methodHandle the method handle to potentially bind to this function instance.
* @return the potentially bound method handle
*/
private MethodHandle bindToCalleeIfNeeded(final MethodHandle methodHandle) {
return ScriptFunctionData.needsCallee(methodHandle) ? MH.bindTo(methodHandle, this) : methodHandle;
}
/**
* Get the name for this function
* @return the name
*/
public final String getName() {
return data.getName();
}
/**
* Get the scope for this function
* @return the scope
*/
public final ScriptObject getScope() {
return scope;
}
/**
* Prototype getter for this ScriptFunction - follows the naming convention
* used by Nasgen and the code generator
*
* @param self self reference
* @return self's prototype
*/
public static Object G$prototype(final Object self) {
return self instanceof ScriptFunction ?
((ScriptFunction)self).getPrototype() :
UNDEFINED;
}
/**
* Prototype setter for this ScriptFunction - follows the naming convention
* used by Nasgen and the code generator
*
* @param self self reference
* @param prototype prototype to set
*/
public static void S$prototype(final Object self, final Object prototype) {
if (self instanceof ScriptFunction) {
((ScriptFunction)self).setPrototype(prototype);
}
}
/**
* Length getter - ECMA 15.3.3.2: Function.length
* @param self self reference
* @return length
*/
public static int G$length(final Object self) {
if (self instanceof ScriptFunction) {
return ((ScriptFunction)self).data.getArity();
}
return 0;
}
/**
* Name getter - ECMA Function.name
* @param self self refence
* @return the name, or undefined if none
*/
public static Object G$name(final Object self) {
if (self instanceof ScriptFunction) {
return ((ScriptFunction)self).getName();
}
return UNDEFINED;
}
/**
* Get the prototype for this ScriptFunction
* @param constructor constructor
* @return prototype, or null if given constructor is not a ScriptFunction
*/
public static ScriptObject getPrototype(final ScriptFunction constructor) {
if (constructor != null) {
final Object proto = constructor.getPrototype();
if (proto instanceof ScriptObject) {
return (ScriptObject)proto;
}
}
return null;
}
// These counters are updated only in debug mode.
private static int constructorCount;
private static int invokes;
private static int allocations;
/**
* @return the constructorCount
*/
public static int getConstructorCount() {
return constructorCount;
}
/**
* @return the invokes
*/
public static int getInvokes() {
return invokes;
}
/**
* @return the allocations
*/
public static int getAllocations() {
return allocations;
}
@Override
protected GuardedInvocation findNewMethod(final CallSiteDescriptor desc, final LinkRequest request) {
final MethodType type = desc.getMethodType();
assert desc.getMethodType().returnType() == Object.class && !NashornCallSiteDescriptor.isOptimistic(desc);
final CompiledFunction cf = data.getBestConstructor(type, scope);
final GuardedInvocation bestCtorInv = cf.createConstructorInvocation();
//TODO - ClassCastException
return new GuardedInvocation(pairArguments(bestCtorInv.getInvocation(), type), getFunctionGuard(this, cf.getFlags()), bestCtorInv.getSwitchPoints(), null);
}
@SuppressWarnings("unused")
private static Object wrapFilter(final Object obj) {
if (obj instanceof ScriptObject || !ScriptFunctionData.isPrimitiveThis(obj)) {
return obj;
}
return Context.getGlobal().wrapAsObject(obj);
}
@SuppressWarnings("unused")
private static Object globalFilter(final Object object) {
// replace whatever we get with the current global object
return Context.getGlobal();
}
/**
* dyn:call call site signature: (callee, thiz, [args...])
* generated method signature: (callee, thiz, [args...])
*
* cases:
* (a) method has callee parameter
* (1) for local/scope calls, we just bind thiz and drop the second argument.
* (2) for normal this-calls, we have to swap thiz and callee to get matching signatures.
* (b) method doesn't have callee parameter (builtin functions)
* (3) for local/scope calls, bind thiz and drop both callee and thiz.
* (4) for normal this-calls, drop callee.
*
* @return guarded invocation for call
*/
@Override
protected GuardedInvocation findCallMethod(final CallSiteDescriptor desc, final LinkRequest request) {
final MethodType type = desc.getMethodType();
final String name = getName();
final boolean isUnstable = request.isCallSiteUnstable();
final boolean scopeCall = NashornCallSiteDescriptor.isScope(desc);
final boolean isCall = !scopeCall && data.isBuiltin() && "call".equals(name);
final boolean isApply = !scopeCall && data.isBuiltin() && "apply".equals(name);
final boolean isApplyOrCall = isCall | isApply;
if (isUnstable && !isApplyOrCall) {
//megamorphic - replace call with apply
final MethodHandle handle;
//ensure that the callsite is vararg so apply can consume it
if (type.parameterCount() == 3 && type.parameterType(2) == Object[].class) {
// Vararg call site
handle = ScriptRuntime.APPLY.methodHandle();
} else {
// (callee, this, args...) => (callee, this, args[])
handle = MH.asCollector(ScriptRuntime.APPLY.methodHandle(), Object[].class, type.parameterCount() - 2);
}
// If call site is statically typed to take a ScriptFunction, we don't need a guard, otherwise we need a
// generic "is this a ScriptFunction?" guard.
return new GuardedInvocation(
handle,
null,
(SwitchPoint)null,
ClassCastException.class);
}
MethodHandle boundHandle;
MethodHandle guard = null;
// Special handling of Function.apply and Function.call. Note we must be invoking
if (isApplyOrCall && !isUnstable) {
final Object[] args = request.getArguments();
if (Bootstrap.isCallable(args[1])) {
return createApplyOrCallCall(isApply, desc, request, args);
}
} //else just fall through and link as ordinary function or unstable apply
final int programPoint = NashornCallSiteDescriptor.isOptimistic(desc) ? NashornCallSiteDescriptor.getProgramPoint(desc) : INVALID_PROGRAM_POINT;
final CompiledFunction cf = data.getBestInvoker(type, scope);
final GuardedInvocation bestInvoker = cf.createFunctionInvocation(type.returnType(), programPoint);
final MethodHandle callHandle = bestInvoker.getInvocation();
if (data.needsCallee()) {
if (scopeCall && needsWrappedThis()) {
// (callee, this, args...) => (callee, [this], args...)
boundHandle = MH.filterArguments(callHandle, 1, SCRIPTFUNCTION_GLOBALFILTER);
} else {
// It's already (callee, this, args...), just what we need
boundHandle = callHandle;
}
} else if (data.isBuiltin() && "extend".equals(data.getName())) {
// NOTE: the only built-in named "extend" is NativeJava.extend. As a special-case we're binding the
// current lookup as its "this" so it can do security-sensitive creation of adapter classes.
boundHandle = MH.dropArguments(MH.bindTo(callHandle, desc.getLookup()), 0, type.parameterType(0), type.parameterType(1));
} else if (scopeCall && needsWrappedThis()) {
// Make a handle that drops the passed "this" argument and substitutes either Global or Undefined
// (this, args...) => ([this], args...)
boundHandle = MH.filterArguments(callHandle, 0, SCRIPTFUNCTION_GLOBALFILTER);
// ([this], args...) => ([callee], [this], args...)
boundHandle = MH.dropArguments(boundHandle, 0, type.parameterType(0));
} else {
// (this, args...) => ([callee], this, args...)
boundHandle = MH.dropArguments(callHandle, 0, type.parameterType(0));
}
// For non-strict functions, check whether this-object is primitive type.
// If so add a to-object-wrapper argument filter.
// Else install a guard that will trigger a relink when the argument becomes primitive.
if (!scopeCall && needsWrappedThis()) {
if (ScriptFunctionData.isPrimitiveThis(request.getArguments()[1])) {
boundHandle = MH.filterArguments(boundHandle, 1, WRAPFILTER);
} else {
guard = getNonStrictFunctionGuard(this);
}
}
boundHandle = pairArguments(boundHandle, type);
return new GuardedInvocation(boundHandle, guard == null ? getFunctionGuard(this, cf.getFlags()) : guard, bestInvoker.getSwitchPoints(), null);
}
private GuardedInvocation createApplyOrCallCall(final boolean isApply, final CallSiteDescriptor desc, final LinkRequest request, final Object[] args) {
final MethodType descType = desc.getMethodType();
final int paramCount = descType.parameterCount();
if(descType.parameterType(paramCount - 1).isArray()) {
// This is vararg invocation of apply or call. This can normally only happen when we do a recursive
// invocation of createApplyOrCallCall (because we're doing apply-of-apply). In this case, create delegate
// linkage by unpacking the vararg invocation and use pairArguments to introduce the necessary spreader.
return createVarArgApplyOrCallCall(isApply, desc, request, args);
}
final boolean passesThis = paramCount > 2;
final boolean passesArgs = paramCount > 3;
final int realArgCount = passesArgs ? paramCount - 3 : 0;
final Object appliedFn = args[1];
final boolean appliedFnNeedsWrappedThis = needsWrappedThis(appliedFn);
//box call back to apply
CallSiteDescriptor appliedDesc = desc;
final SwitchPoint applyToCallSwitchPoint = Global.instance().getChangeCallback("apply");
//enough to change the proto switchPoint here
final boolean isApplyToCall = NashornCallSiteDescriptor.isApplyToCall(desc);
final boolean isFailedApplyToCall = isApplyToCall && applyToCallSwitchPoint.hasBeenInvalidated();
// R(apply|call, ...) => R(...)
MethodType appliedType = descType.dropParameterTypes(0, 1);
if (!passesThis) {
// R() => R(this)
appliedType = appliedType.insertParameterTypes(1, Object.class);
} else if (appliedFnNeedsWrappedThis) {
appliedType = appliedType.changeParameterType(1, Object.class);
}
/*
* dropArgs is a synthetic method handle that contains any args that we need to
* get rid of that come after the arguments array in the apply case. We adapt
* the callsite to ask for 3 args only and then dropArguments on the method handle
* to make it fit the extraneous args.
*/
MethodType dropArgs = MH.type(void.class);
if (isApply && !isFailedApplyToCall) {
final int pc = appliedType.parameterCount();
for (int i = 3; i < pc; i++) {
dropArgs = dropArgs.appendParameterTypes(appliedType.parameterType(i));
}
if (pc > 3) {
appliedType = appliedType.dropParameterTypes(3, pc);
}
}
if (isApply || isFailedApplyToCall) {
if (passesArgs) {
// R(this, args) => R(this, Object[])
appliedType = appliedType.changeParameterType(2, Object[].class);
// drop any extraneous arguments for the apply fail case
if (isFailedApplyToCall) {
appliedType = appliedType.dropParameterTypes(3, paramCount - 1);
}
} else {
// R(this) => R(this, Object[])
appliedType = appliedType.insertParameterTypes(2, Object[].class);
}
}
appliedDesc = appliedDesc.changeMethodType(appliedType);
// Create the same arguments for the delegate linking request that would be passed in an actual apply'd invocation
final Object[] appliedArgs = new Object[isApply ? 3 : appliedType.parameterCount()];
appliedArgs[0] = appliedFn;
appliedArgs[1] = passesThis ? appliedFnNeedsWrappedThis ? ScriptFunctionData.wrapThis(args[2]) : args[2] : ScriptRuntime.UNDEFINED;
if (isApply && !isFailedApplyToCall) {
appliedArgs[2] = passesArgs ? NativeFunction.toApplyArgs(args[3]) : ScriptRuntime.EMPTY_ARRAY;
} else {
if (passesArgs) {
if (isFailedApplyToCall) {
final Object[] tmp = new Object[args.length - 3];
System.arraycopy(args, 3, tmp, 0, tmp.length);
appliedArgs[2] = NativeFunction.toApplyArgs(tmp);
} else {
assert !isApply;
System.arraycopy(args, 3, appliedArgs, 2, args.length - 3);
}
} else if (isFailedApplyToCall) {
appliedArgs[2] = ScriptRuntime.EMPTY_ARRAY;
}
}
// Ask the linker machinery for an invocation of the target function
final LinkRequest appliedRequest = request.replaceArguments(appliedDesc, appliedArgs);
GuardedInvocation appliedInvocation;
try {
appliedInvocation = Bootstrap.getLinkerServices().getGuardedInvocation(appliedRequest);
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Exception e) {
throw new RuntimeException(e);
}
assert appliedRequest != null; // Bootstrap.isCallable() returned true for args[1], so it must produce a linkage.
final Class<?> applyFnType = descType.parameterType(0);
MethodHandle inv = appliedInvocation.getInvocation(); //method handle from apply invocation. the applied function invocation
if (isApply && !isFailedApplyToCall) {
if (passesArgs) {
// Make sure that the passed argArray is converted to Object[] the same way NativeFunction.apply() would do it.
inv = MH.filterArguments(inv, 2, NativeFunction.TO_APPLY_ARGS);
} else {
// If the original call site doesn't pass argArray, pass in an empty array
inv = MH.insertArguments(inv, 2, (Object)ScriptRuntime.EMPTY_ARRAY);
}
}
if (isApplyToCall) {
if (isFailedApplyToCall) {
//take the real arguments that were passed to a call and force them into the apply instead
Context.getContextTrusted().getLogger(ApplySpecialization.class).info("Collection arguments to revert call to apply in " + appliedFn);
inv = MH.asCollector(inv, Object[].class, realArgCount);
} else {
appliedInvocation = appliedInvocation.addSwitchPoint(applyToCallSwitchPoint);
}
}
if (!passesThis) {
// If the original call site doesn't pass in a thisArg, pass in Global/undefined as needed
inv = bindImplicitThis(appliedFn, inv);
} else if (appliedFnNeedsWrappedThis) {
// target function needs a wrapped this, so make sure we filter for that
inv = MH.filterArguments(inv, 1, WRAP_THIS);
}
inv = MH.dropArguments(inv, 0, applyFnType);
/*
* Dropargs can only be non-()V in the case of isApply && !isFailedApplyToCall, which
* is when we need to add arguments to the callsite to catch and ignore the synthetic
* extra args that someone has added to the command line.
*/
for (int i = 0; i < dropArgs.parameterCount(); i++) {
inv = MH.dropArguments(inv, 4 + i, dropArgs.parameterType(i));
}
MethodHandle guard = appliedInvocation.getGuard();
// If the guard checks the value of "this" but we aren't passing thisArg, insert the default one
if (!passesThis && guard.type().parameterCount() > 1) {
guard = bindImplicitThis(appliedFn, guard);
}
final MethodType guardType = guard.type();
// We need to account for the dropped (apply|call) function argument.
guard = MH.dropArguments(guard, 0, descType.parameterType(0));
// Take the "isApplyFunction" guard, and bind it to this function.
MethodHandle applyFnGuard = MH.insertArguments(IS_APPLY_FUNCTION, 2, this);
// Adapt the guard to receive all the arguments that the original guard does.
applyFnGuard = MH.dropArguments(applyFnGuard, 2, guardType.parameterArray());
// Fold the original function guard into our apply guard.
guard = MH.foldArguments(applyFnGuard, guard);
return appliedInvocation.replaceMethods(inv, guard);
}
/*
* This method is used for linking nested apply. Specialized apply and call linking will create a variable arity
* call site for an apply call; when createApplyOrCallCall sees a linking request for apply or call with
* Nashorn-style variable arity call site (last argument type is Object[]) it'll delegate to this method.
* This method converts the link request from a vararg to a non-vararg one (unpacks the array), then delegates back
* to createApplyOrCallCall (with which it is thus mutually recursive), and adds appropriate argument spreaders to
* invocation and the guard of whatever createApplyOrCallCall returned to adapt it back into a variable arity
* invocation. It basically reduces the problem of vararg call site linking of apply and call back to the (already
* solved by createApplyOrCallCall) non-vararg call site linking.
*/
private GuardedInvocation createVarArgApplyOrCallCall(final boolean isApply, final CallSiteDescriptor desc,
final LinkRequest request, final Object[] args) {
final MethodType descType = desc.getMethodType();
final int paramCount = descType.parameterCount();
final Object[] varArgs = (Object[])args[paramCount - 1];
// -1 'cause we're not passing the vararg array itself
final int copiedArgCount = args.length - 1;
final int varArgCount = varArgs.length;
// Spread arguments for the delegate createApplyOrCallCall invocation.
final Object[] spreadArgs = new Object[copiedArgCount + varArgCount];
System.arraycopy(args, 0, spreadArgs, 0, copiedArgCount);
System.arraycopy(varArgs, 0, spreadArgs, copiedArgCount, varArgCount);
// Spread call site descriptor for the delegate createApplyOrCallCall invocation. We drop vararg array and
// replace it with a list of Object.class.
final MethodType spreadType = descType.dropParameterTypes(paramCount - 1, paramCount).appendParameterTypes(
Collections.<Class<?>>nCopies(varArgCount, Object.class));
final CallSiteDescriptor spreadDesc = desc.changeMethodType(spreadType);
// Delegate back to createApplyOrCallCall with the spread (that is, reverted to non-vararg) request/
final LinkRequest spreadRequest = request.replaceArguments(spreadDesc, spreadArgs);
final GuardedInvocation spreadInvocation = createApplyOrCallCall(isApply, spreadDesc, spreadRequest, spreadArgs);
// Add spreader combinators to returned invocation and guard.
return spreadInvocation.replaceMethods(
// Use standard ScriptObject.pairArguments on the invocation
pairArguments(spreadInvocation.getInvocation(), descType),
// Use our specialized spreadGuardArguments on the guard (see below).
spreadGuardArguments(spreadInvocation.getGuard(), descType));
}
private static MethodHandle spreadGuardArguments(final MethodHandle guard, final MethodType descType) {
final MethodType guardType = guard.type();
final int guardParamCount = guardType.parameterCount();
final int descParamCount = descType.parameterCount();
final int spreadCount = guardParamCount - descParamCount + 1;
if (spreadCount <= 0) {
// Guard doesn't dip into the varargs
return guard;
}
final MethodHandle arrayConvertingGuard;
// If the last parameter type of the guard is an array, then it is already itself a guard for a vararg apply
// invocation. We must filter the last argument with toApplyArgs otherwise deeper levels of nesting will fail
// with ClassCastException of NativeArray to Object[].
if(guardType.parameterType(guardParamCount - 1).isArray()) {
arrayConvertingGuard = MH.filterArguments(guard, guardParamCount - 1, NativeFunction.TO_APPLY_ARGS);
} else {
arrayConvertingGuard = guard;
}
return ScriptObject.adaptHandleToVarArgCallSite(arrayConvertingGuard, descParamCount);
}
private static MethodHandle bindImplicitThis(final Object fn, final MethodHandle mh) {
final MethodHandle bound;
if(fn instanceof ScriptFunction && ((ScriptFunction)fn).needsWrappedThis()) {
bound = MH.filterArguments(mh, 1, SCRIPTFUNCTION_GLOBALFILTER);
} else {
bound = mh;
}
return MH.insertArguments(bound, 1, ScriptRuntime.UNDEFINED);
}
/**
* Used for noSuchMethod/noSuchProperty and JSAdapter hooks.
*
* These don't want a callee parameter, so bind that. Name binding is optional.
*/
MethodHandle getCallMethodHandle(final MethodType type, final String bindName) {
return pairArguments(bindToNameIfNeeded(bindToCalleeIfNeeded(data.getGenericInvoker(scope)), bindName), type);
}
private static MethodHandle bindToNameIfNeeded(final MethodHandle methodHandle, final String bindName) {
if (bindName == null) {
return methodHandle;
}
// if it is vararg method, we need to extend argument array with
// a new zeroth element that is set to bindName value.
final MethodType methodType = methodHandle.type();
final int parameterCount = methodType.parameterCount();
final boolean isVarArg = parameterCount > 0 && methodType.parameterType(parameterCount - 1).isArray();
if (isVarArg) {
return MH.filterArguments(methodHandle, 1, MH.insertArguments(ADD_ZEROTH_ELEMENT, 1, bindName));
}
return MH.insertArguments(methodHandle, 1, bindName);
}
/**
* Get the guard that checks if a {@link ScriptFunction} is equal to
* a known ScriptFunction, using reference comparison
*
* @param function The ScriptFunction to check against. This will be bound to the guard method handle
*
* @return method handle for guard
*/
private static MethodHandle getFunctionGuard(final ScriptFunction function, final int flags) {
assert function.data != null;
// Built-in functions have a 1-1 correspondence to their ScriptFunctionData, so we can use a cheaper identity
// comparison for them.
if (function.data.isBuiltin()) {
return Guards.getIdentityGuard(function);
}
return MH.insertArguments(IS_FUNCTION_MH, 1, function.data);
}
/**
* Get a guard that checks if a {@link ScriptFunction} is equal to
* a known ScriptFunction using reference comparison, and whether the type of
* the second argument (this-object) is not a JavaScript primitive type.
*
* @param function The ScriptFunction to check against. This will be bound to the guard method handle
*
* @return method handle for guard
*/
private static MethodHandle getNonStrictFunctionGuard(final ScriptFunction function) {
assert function.data != null;
return MH.insertArguments(IS_NONSTRICT_FUNCTION, 2, function.data);
}
@SuppressWarnings("unused")
private static boolean isFunctionMH(final Object self, final ScriptFunctionData data) {
return self instanceof ScriptFunction && ((ScriptFunction)self).data == data;
}
@SuppressWarnings("unused")
private static boolean isNonStrictFunction(final Object self, final Object arg, final ScriptFunctionData data) {
return self instanceof ScriptFunction && ((ScriptFunction)self).data == data && arg instanceof ScriptObject;
}
@SuppressWarnings("unused")
private static boolean isApplyFunction(final boolean appliedFnCondition, final Object self, final Object expectedSelf) {
// NOTE: we're using self == expectedSelf as we're only using this with built-in functions apply() and call()
return appliedFnCondition && self == expectedSelf;
}
@SuppressWarnings("unused")
private static Object[] addZerothElement(final Object[] args, final Object value) {
// extends input array with by adding new zeroth element
final Object[] src = args == null? ScriptRuntime.EMPTY_ARRAY : args;
final Object[] result = new Object[src.length + 1];
System.arraycopy(src, 0, result, 1, src.length);
result[0] = value;
return result;
}
@SuppressWarnings("unused")
private static Object invokeSync(final ScriptFunction func, final Object sync, final Object self, final Object... args)
throws Throwable {
final Object syncObj = sync == UNDEFINED ? self : sync;
synchronized (syncObj) {
return func.invoke(self, args);
}
}
private static MethodHandle findOwnMH_S(final String name, final Class<?> rtype, final Class<?>... types) {
return MH.findStatic(MethodHandles.lookup(), ScriptFunction.class, name, MH.type(rtype, types));
}
private static MethodHandle findOwnMH_V(final String name, final Class<?> rtype, final Class<?>... types) {
return MH.findVirtual(MethodHandles.lookup(), ScriptFunction.class, name, MH.type(rtype, types));
}
}
|
gpl-2.0
|
mwonline/unilago
|
templates/purityfx/index.php
|
8043
|
<?php
/**
* @version $Id: index.php 6263 2013-01-01 22:00:40Z kevin $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
* Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system
*
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted index access' );
// load and inititialize gantry class
require_once(dirname(__FILE__) . '/lib/gantry/gantry.php');
$gantry->init();
// get the current preset
$gpreset = str_replace(' ','',strtolower($gantry->get('name')));
?>
<!doctype html>
<html xml:lang="<?php echo $gantry->language; ?>" lang="<?php echo $gantry->language;?>" >
<head>
<?php if ($gantry->get('layout-mode') == '960fixed') : ?>
<meta name="viewport" content="width=960px">
<?php elseif ($gantry->get('layout-mode') == '1200fixed') : ?>
<meta name="viewport" content="width=1200px">
<?php else : ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php endif; ?>
<?php
$gantry->displayHead();
$gantry->addStyle('grid-responsive.css', 5);
$gantry->addLess('global.less', 'master.css', 8, array('headerstyle'=>$gantry->get('headerstyle','dark')));
if ($gantry->browser->name == 'ie'){
if ($gantry->browser->shortversion == 9){
$gantry->addInlineScript("if (typeof RokMediaQueries !== 'undefined') window.addEvent('domready', function(){ RokMediaQueries._fireEvent(RokMediaQueries.getQuery()); });");
}
if ($gantry->browser->shortversion == 8){
$gantry->addScript('html5shim.js');
}
}
if ($gantry->get('layout-mode', 'responsive') == 'responsive') $gantry->addScript('rokmediaqueries.js');
if ($gantry->get('loadtransition')) {
$gantry->addScript('load-transition.js');
$hidden = ' class="rt-hidden"';}
?>
</head>
<body <?php echo $gantry->displayBodyTag(); ?>>
<?php /** Begin Top Surround **/ if ($gantry->countModules('top') or $gantry->countModules('header')) : ?>
<header id="rt-top-surround">
<?php /** Begin Top **/ if ($gantry->countModules('top')) : ?>
<div id="rt-top" <?php echo $gantry->displayClassesByTag('rt-top'); ?>>
<div class="rt-container">
<?php echo $gantry->displayModules('top','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Top **/ endif; ?>
<?php /** Begin Header **/ if ($gantry->countModules('header')) : ?>
<div id="rt-header">
<div class="rt-container">
<?php echo $gantry->displayModules('header','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Header **/ endif; ?>
</header>
<?php /** End Top Surround **/ endif; ?>
<?php /** Begin Login **/ if ($gantry->countModules('login')) : ?>
<div id="rt-login">
<?php echo $gantry->displayModules('login','standard','standard'); ?>
<div class="clear"></div>
</div>
<?php /** End Login **/ endif; ?>
<?php /** Begin Drawer **/ if ($gantry->countModules('drawer')) : ?>
<div id="rt-drawer">
<div class="rt-container">
<?php echo $gantry->displayModules('drawer','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Drawer **/ endif; ?>
<?php /** Begin FullScreen **/ if ($gantry->countModules('fullscreen')) : ?>
<div id="rt-fullscreen">
<?php echo $gantry->displayModules('fullscreen','standard','standard'); ?>
<div class="clear"></div>
</div>
<?php /** End FullScreen **/ endif; ?>
<?php /** Begin Showcase **/ if ($gantry->countModules('showcase')) : ?>
<div id="rt-showcase">
<div class="rt-showcase-pattern">
<div class="rt-container">
<?php echo $gantry->displayModules('showcase','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
</div>
<?php /** End Showcase **/ endif; ?>
<div id="rt-transition"<?php if ($gantry->get('loadtransition')) echo $hidden; ?>>
<div id="rt-mainbody-surround">
<?php /** Begin Feature **/ if ($gantry->countModules('feature')) : ?>
<div id="rt-feature">
<div class="rt-container">
<?php echo $gantry->displayModules('feature','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Feature **/ endif; ?>
<?php /** Begin Utility **/ if ($gantry->countModules('utility')) : ?>
<div id="rt-utility">
<div class="rt-container">
<?php echo $gantry->displayModules('utility','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Utility **/ endif; ?>
<?php /** Begin Breadcrumbs **/ if ($gantry->countModules('breadcrumb')) : ?>
<div id="rt-breadcrumbs">
<div class="rt-container">
<?php echo $gantry->displayModules('breadcrumb','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Breadcrumbs **/ endif; ?>
<?php /** Begin Main Top **/ if ($gantry->countModules('maintop')) : ?>
<div id="rt-maintop">
<div class="rt-container">
<?php echo $gantry->displayModules('maintop','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Main Top **/ endif; ?>
<?php /** Begin Full Width**/ if ($gantry->countModules('fullwidth')) : ?>
<div id="rt-fullwidth">
<?php echo $gantry->displayModules('fullwidth','basic','basic'); ?>
<div class="clear"></div>
</div>
<?php /** End Full Width **/ endif; ?>
<?php /** Begin Main Body **/ ?>
<div class="rt-container">
<?php echo $gantry->displayMainbody('mainbody','sidebar','standard','standard','standard','standard','standard'); ?>
</div>
<?php /** End Main Body **/ ?>
<?php /** Begin Main Bottom **/ if ($gantry->countModules('mainbottom')) : ?>
<div id="rt-mainbottom">
<div class="rt-container">
<?php echo $gantry->displayModules('mainbottom','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Main Bottom **/ endif; ?>
<?php /** Begin Extension **/ if ($gantry->countModules('extension')) : ?>
<div id="rt-extension">
<div class="rt-container">
<?php echo $gantry->displayModules('extension','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Extension **/ endif; ?>
</div>
</div>
<?php /** Begin Bottom **/ if ($gantry->countModules('bottom')) : ?>
<div id="rt-bottom">
<div class="rt-container">
<?php echo $gantry->displayModules('bottom','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Bottom **/ endif; ?>
<?php /** Begin Footer Section **/ if ($gantry->countModules('footer') or $gantry->countModules('copyright')) : ?>
<footer id="rt-footer-surround">
<?php /** Begin Footer **/ if ($gantry->countModules('footer')) : ?>
<div id="rt-footer">
<div class="rt-container">
<?php echo $gantry->displayModules('footer','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Footer **/ endif; ?>
<?php /** Begin Copyright **/ if ($gantry->countModules('copyright')) : ?>
<div id="rt-copyright">
<div class="rt-container">
<?php echo $gantry->displayModules('copyright','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Copyright **/ endif; ?>
</footer>
<?php /** End Footer Surround **/ endif; ?>
<?php /** Begin Debug **/ if ($gantry->countModules('debug')) : ?>
<div id="rt-debug">
<div class="rt-container">
<?php echo $gantry->displayModules('debug','standard','standard'); ?>
<div class="clear"></div>
</div>
</div>
<?php /** End Debug **/ endif; ?>
<?php /** Begin Analytics **/ if ($gantry->countModules('analytics')) : ?>
<?php echo $gantry->displayModules('analytics','basic','basic'); ?>
<?php /** End Analytics **/ endif; ?>
</body>
</html>
<?php
$gantry->finalize();
?>
|
gpl-2.0
|
Desarrollo-CeSPI/choique
|
plugins/sfGuardPlugin/modules/sfGuardUser/templates/_changepassword_form.php
|
2279
|
<?php
// auto-generated by sfAdvancedAdmin
// date: 2011/08/31 10:41:09
?>
<?php echo form_tag('sfGuardUser/changePassword', array(
'id' => 'sf_admin_edit_form',
'name' => 'sf_admin_edit_form',
'onsubmit' => 'return true;'
)) ?>
<fieldset id="sf_fieldset_none" class="">
<div class="form-row">
<?php echo label_for('sf_guard_user[password]', __($labels['sf_guard_user{password}']), 'class="required" ') ?>
<div class="content<?php if ($sf_request->hasError('sf_guard_user{password}')): ?> form-error<?php endif; ?>">
<?php if ($sf_request->hasError('sf_guard_user{password}')): ?>
<?php echo form_error('sf_guard_user{password}', array('class' => 'form-error-msg')) ?>
<?php endif; ?>
<?php $value = get_partial('password', array('type' => 'create')); echo $value ? $value : ' ' ?>
</div>
<div style="clear:both; height: 1px; font-size: 1px;"> </div>
</div>
<div class="form-row">
<?php echo label_for('sf_guard_user[new_password]', __($labels['sf_guard_user{new_password}']), 'class="required"') ?>
<div class="content<?php if ($sf_request->hasError('sf_guard_user{new_password}')): ?> form-error<?php endif; ?>">
<?php if ($sf_request->hasError('sf_guard_user{new_password}')): ?>
<?php echo form_error('sf_guard_user{new_password}', array('class' => 'form-error-msg')) ?>
<?php endif; ?>
<?php $value = get_partial('new_password', array('type' => 'create')); echo $value ? $value : ' ' ?>
</div>
<div style="clear:both; height: 1px; font-size: 1px;"> </div>
</div>
<div class="form-row">
<?php echo label_for('sf_guard_user[password_bis]', __($labels['sf_guard_user{password_bis}']), 'class="required"') ?>
<div class="content<?php if ($sf_request->hasError('sf_guard_user{password_bis}')): ?> form-error<?php endif; ?>">
<?php if ($sf_request->hasError('sf_guard_user{password_bis}')): ?>
<?php echo form_error('sf_guard_user{password_bis}', array('class' => 'form-error-msg')) ?>
<?php endif; ?>
<?php $value = get_partial('password_bis', array('type' => 'create')); echo $value ? $value : ' ' ?>
</div>
<div style="clear:both; height: 1px; font-size: 1px;"> </div>
</div>
</fieldset>
<?php include_partial('changepassword_actions', array()) ?>
</form>
|
gpl-2.0
|
vargax/ejemplos
|
java/infracomp/InfraComp_Servidor/src/uniandes/infracom/SisTrans/ProtocoloInseguro.java
|
7257
|
package uniandes.infracom.SisTrans;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* @author Martรญn Uribe Gutierrez
* @author Lina Giseth Casas Salas
* Infraestructura Computacional 2012-20
* Universidad de los Andes
*
* Clase que representa la ejecuciรณn del protocolo para las solicitudes de un cliente que desea conocer la posiciรณn
* de un listado de camiones sin usar seguridad en canales.
*/
public class ProtocoloInseguro extends Thread
{
//***************************************************************
//CONSTANTES PARA LA DEFINICION DEL PROTOCOLO
/**
* Constante que representa el inicio de las negociaciones entre las entidades
*/
public static final String HOLA = "HOLA";
/**
* Constante que indica el estado del servidor durante el proceso de negociaciรณn
*/
public static final String STATUS = "STATUS";
/**
* Constante de reconocimiento.
*/
public static final String CERTIFICADO = "CERTIFICADO";
/**
* Constante que indica la etapa de envรญo del listado de camiones
*/
public static final String INIT = "INIT";
/**
* Constante que indica que el cliente tiene una solicitud
*/
public static final String PETICION = "PETICION";
/**
* Constante de respuesta del servidor a la solicitud del cliente
*/
public static final String INFO = "INFO";
/**
* El separador utilizado para segmentar los datos primarios
*/
public static final String SEPARADOR = ":";
/**
* El separador para segmentar los datos secundarios (camiones)
*/
public static final String SEPARADOR2 = ";";
/**
* El separador para segmentar los datos terciarios (posiciรณn)
*/
public static final String SEPARADOR3 = ",";
/**
* Constante que indica el estado correcto de una etapa del protocolo
*/
public static final String OK = "OK";
/**
* Constante que indica que hubo un error en el protocolo, no se contuarรก el protocolo en dado caso
*/
public static final String DENEGADO = "DENEGADO";
/**
* Constante para indicar una excepciรณn, se adicionarรก a la respuesta la signatura de la excepciรณn
*/
public static final String EXCEPCION = "EXCEPCION";
//***************************************************************
//ATRIBUTOS DE LA CLASE
/**
* Un identificador para el ProtocoloSeguro
*/
private int id;
/**
* El momento en milisegundos en que se creรณ la clase
*/
private long inicio;
/**
* Indica si el usuario aun sigue conectado
*/
private boolean conectado;
/**
* Socket de comunicacion con el cliente
*/
private Socket socket;
/**
* Lector del flujo de entrada
*/
private BufferedReader reader;
/**
* Escritor sobre el flujo de salida
*/
private PrintWriter writer;
/**
* Lista de camiones generados
*/
private Camion[] camiones;
//***************************************************************
//CONSTRUCTOR DE LA CLASE
/**
* Abre el canal de comunicaciรณn con el cliente e inicializa los flujos de entrada y salida.
* @param ss El socket de comunicaciรณn con el cliente.
* @param cam Lista de camiones generada previamente.
*/
public ProtocoloInseguro(int id, Socket ss, Camion[] cam)
{
this.id = id;
this.inicio = System.currentTimeMillis();
conectado = true;
socket = ss;
camiones = cam;
try
{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Inicio del hilo de ejecuciรณn
*/
public void run()
{
try
{
while( conectado )
{
procesar(reader.readLine());
}
System.out.println(id+","+(System.currentTimeMillis()-inicio));
}
catch (IOException e) {
e.printStackTrace();
System.out.println("muriรณ el buffer");
}
}
/**
* Procesa el string que le llega como parametro, de acuerdo con el protocolo definido
* @param s Cadena leida en el protocolo de comunicacion.
*/
public void procesar(String s)
{
String[] l = s.split(SEPARADOR);
if( l[0].equals(HOLA) )
{
enviarStatus();
}
else if( l[0].equals(STATUS) )
{
// Caso Cliente
}
else if( l[0].equals(CERTIFICADO) )
{
procesarCertificado(s);
}
else if( l[0].equals(INIT) )
{
// Caso Cliente
}
else if( l[0].equals(PETICION) )
{
procesarPeticion(l[1]);
}
else if( l[0].equals(INFO) )
{
//Caso Cliente
}
else
{
imprimirExcepcion( "Error en Formato");
}
}
/**
* Mรฉtodo que imprime la excepciรณn cuando ha ocurrido un problema en el proceso de comunicaciรณn con el cliente
* @param e Es el mensaje de Excepciรณn
*/
public void imprimirExcepcion(String e)
{
writer.println(EXCEPCION+SEPARADOR +e);
}
/**
* Metodo que responde el status actual del servidor.
* @param s Cadena de entrada
*/
private void enviarStatus()
{
//Responder OK
writer.println(OK);
}
/**
* Metodo que procesa el certificado recibido.
* @param s
*/
private void procesarCertificado(String s)
{
//No hay certificado
//Responder INIT:lista
String resultado = "";
int m = 0;
for (int i = 0; i < camiones.length; i++)
{
if( m > 0 )
resultado += SEPARADOR2;
resultado += camiones[i].getId();
m++;
}
// System.out.println("LISTA " + resultado);
String enviar = INIT+SEPARADOR+resultado;
// System.out.println("A enviar: *" + enviar);
// Envia la lista de camiones como texto plano.
writer.print( enviar );
writer.flush();
}
/**
* Metodo que recibe y procesa la solicitud de informacion de camiones enviada por el cliente.
* @param s El string leido en el protocolo de comunicacion.
*/
private void procesarPeticion(String s)
{
//PETICION:idCamion[;idCamion]
//INFO:idCamion,XXX-XX-XX,XX-XX-XX[;idCamion,XXX-XX-XX,XX-XX-XX]
String[] ids = s.split(SEPARADOR2);
String resultado = "";
int m = 0;
for (int i = 0; i < camiones.length; i++)
{
//System.out.println("entra for");
boolean termino = false;
for (int j = 0; j < ids.length && !termino; j++)
{
//System.out.println("entra for2");
if( ids[j].equals( camiones[i].getId() ) )
{
if( m > 0 )
resultado += SEPARADOR2;
resultado += camiones[i].getId() + SEPARADOR3
+ camiones[i].getLatitud() + SEPARADOR3
+ camiones[i].getLongitud();
termino = true;
m++;
}
}
}
writer.print(INFO+SEPARADOR+resultado);
writer.flush();
conectado = false;
}
}
|
gpl-2.0
|
Ziemin/ktp-text-ui
|
config/appearance-config-tab.cpp
|
14945
|
/***************************************************************************
* Copyright (C) 2013 by Huba Nagy <12huba@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This 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 "appearance-config-tab.h"
#include "ui_appearance-config.h"
#include "chat-window-style-manager.h"
#include "chat-window-style.h"
#include "adium-theme-header-info.h"
#include "adium-theme-content-info.h"
#include "adium-theme-status-info.h"
#include <KMessageBox>
AppearanceConfigTab::AppearanceConfigTab(QWidget *parent, TabMode mode)
: QWidget(parent),
ui(new Ui::ChatWindowConfig)
{
m_groupChat = mode == GroupChat;
ui->setupUi(this);
m_demoChatHeader.setChatName(i18n("A demo chat"));
m_demoChatHeader.setSourceName(i18n("Jabber"));
m_demoChatHeader.setTimeOpened(QDateTime::currentDateTime());
m_demoChatHeader.setDestinationName(i18nc("Example email", "ted@example.com"));
m_demoChatHeader.setDestinationDisplayName(i18nc("Example name", "Ted"));
m_demoChatHeader.setGroupChat(m_groupChat);
m_demoChatHeader.setService(QLatin1String("jabber"));
// check iconPath docs for minus sign in -KIconLoader::SizeMedium
m_demoChatHeader.setServiceIconPath(KIconLoader::global()->iconPath(QLatin1String("im-jabber"), -KIconLoader::SizeMedium));
ChatWindowStyleManager *manager = ChatWindowStyleManager::self();
connect(manager, SIGNAL(loadStylesFinished()), SLOT(onStylesLoaded()));
//loading theme settings.
loadTab();
connect(ui->chatView, SIGNAL(viewReady()), SLOT(sendDemoMessages()));
connect(ui->styleComboBox, SIGNAL(activated(int)), SLOT(onStyleSelected(int)));
connect(ui->variantComboBox, SIGNAL(activated(QString)), SLOT(onVariantSelected(QString)));
connect(ui->showHeader, SIGNAL(clicked(bool)), SLOT(onShowHeaderChanged(bool)));
connect(ui->customFontBox, SIGNAL(clicked(bool)), SLOT(onFontGroupChanged(bool)));
connect(ui->fontFamily, SIGNAL(currentFontChanged(QFont)), SLOT(onFontFamilyChanged(QFont)));
connect(ui->fontSize, SIGNAL(valueChanged(int)), SLOT(onFontSizeChanged(int)));
connect(ui->showPresenceCheckBox, SIGNAL(toggled(bool)), SLOT(onShowPresenceChangesChanged(bool)));
connect(ui->showJoinLeaveCheckBox, SIGNAL(toggled(bool)), SLOT(onShowJoinLeaveChangesChanged(bool)));
}
AppearanceConfigTab::~AppearanceConfigTab()
{
delete ui;
}
void AppearanceConfigTab::changeEvent(QEvent* e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void AppearanceConfigTab::onFontFamilyChanged(const QFont &fontFamily)
{
ui->chatView->setFontFamily(fontFamily.family());
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::onFontGroupChanged(bool useCustomFont)
{
ui->chatView->setUseCustomFont(useCustomFont);
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::onFontSizeChanged(int fontSize)
{
ui->chatView->setFontSize(fontSize);
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::onShowPresenceChangesChanged(bool stateChanged)
{
ui->chatView->setShowPresenceChanges(stateChanged);
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::onShowJoinLeaveChangesChanged(bool joinLeaveChanged)
{
ui->chatView->setShowJoinLeaveChanges(joinLeaveChanged);
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::onShowHeaderChanged(bool showHeader)
{
ui->chatView->setHeaderDisplayed(showHeader);
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::onStyleSelected(int index)
{
//load the style.
QString styleId = ui->styleComboBox->itemData(index).toString();
ChatWindowStyle *style = ChatWindowStyleManager::self()->getValidStyleFromPool(styleId);
if (style) {
ui->chatView->setChatStyle(style);
updateVariantsList();
ui->showHeader->setEnabled(style->hasHeader());
ui->chatView->initialise(m_demoChatHeader);
}
tabChanged();
}
void AppearanceConfigTab::onStylesLoaded()
{
QMap<QString, QString> styles = ChatWindowStyleManager::self()->getAvailableStyles();
ChatWindowStyle *currentStyle = ui->chatView->chatStyle();
ui->styleComboBox->clear();
QMap<QString, QString>::const_iterator i = styles.constBegin();
while (i != styles.constEnd()) {
ui->styleComboBox->addItem(i.value(), i.key());
if (i.key() == currentStyle->id()) {
ui->styleComboBox->setCurrentItem(i.value());
}
++i;
}
//ui->styleComboBox->setCurrentItem(currentStyle->getStyleName());
updateVariantsList();
//FIXME call onStyleSelected
}
void AppearanceConfigTab::onVariantSelected(const QString &variant)
{
ui->chatView->setVariant(variant);
ui->chatView->initialise(m_demoChatHeader);
tabChanged();
}
void AppearanceConfigTab::sendDemoMessages()
{
//add a fake message
AdiumThemeContentInfo message(AdiumThemeMessageInfo::HistoryRemoteToLocal);
message.setMessage(i18nc("Example message in preview conversation","Ok!"));
message.setSenderDisplayName(i18nc("Example email", "larry@example.com"));
message.setSenderScreenName(i18nc("Example name", "Larry Demo"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::HistoryRemoteToLocal);
message.setMessage(i18nc("Example message in preview conversation","Bye Bye"));
message.setSenderDisplayName(i18nc("Example email", "larry@example.com"));
message.setSenderScreenName(i18nc("Example name", "Larry Demo"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::HistoryLocalToRemote);
message.setMessage(i18nc("Example message in preview conversation","Have fun!"));
message.setSenderDisplayName(i18nc("Example email", "ted@example.com"));
message.setSenderScreenName(i18nc("Example name", "Ted Example"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::HistoryLocalToRemote);
message.setMessage(i18nc("Example message in preview conversation","cya"));
message.setSenderDisplayName(i18nc("Example email", "ted@example.com"));
message.setSenderScreenName(i18nc("Example name", "Ted Example"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
AdiumThemeStatusInfo statusMessage(true);
statusMessage.setMessage(i18nc("Example message", "Ted Example waves."));
statusMessage.setSender(i18nc("Example name", "Ted Example"));
statusMessage.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumStatusMessage(statusMessage);
if (ui->chatView->showJoinLeaveChanges()) {
statusMessage = AdiumThemeStatusInfo(true);
statusMessage.setMessage(i18nc("Example message in preview conversation","Ted Example has left the chat.")); //FIXME sync this with chat text logic.
statusMessage.setSender(i18nc("Example name", "Ted Example"));
statusMessage.setTime(QDateTime::currentDateTime());
statusMessage.setStatus(QLatin1String("away"));
ui->chatView->addAdiumStatusMessage(statusMessage);
statusMessage = AdiumThemeStatusInfo(false);
statusMessage.setMessage(i18nc("Example message in preview conversation","Ted Example has joined the chat.")); //FIXME sync this with chat text logic.
statusMessage.setSender(i18nc("Example name", "Ted Example"));
statusMessage.setTime(QDateTime::currentDateTime());
statusMessage.setStatus(QLatin1String("away"));
ui->chatView->addAdiumStatusMessage(statusMessage);
}
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::RemoteToLocal);
message.setMessage(i18nc("Example message in preview conversation","Hello Ted"));
message.setSenderDisplayName(i18nc("Example email", "larry@example.com"));
message.setSenderScreenName(i18nc("Example name", "Larry Demo"));
message.appendMessageClass(QLatin1String("mention"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::RemoteToLocal);
message.setMessage(i18nc("Example message in preview conversation","What's up?"));
message.setSenderDisplayName(i18nc("Example email", "larry@example.com"));
message.setSenderScreenName(i18nc("Example name", "Larry Demo"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::LocalToRemote);
message.setMessage(i18nc("Example message in preview conversation","Check out which cool adium themes work "
"<a href=\"http://community.kde.org/KTp/Components/Chat_Window/Themes\">"
"here</a>!"));
message.setSenderDisplayName(i18nc("Example email", "ted@example.com"));
message.setSenderScreenName(i18nc("Example name", "Ted Example"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
if ( m_groupChat == true) {
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::RemoteToLocal);
message.setMessage(i18nc("Example message in preview conversation","Hello"));
message.setSenderDisplayName(i18nc("Example email", "bob@example.com"));
message.setSenderScreenName(i18nc("Example name", "Bob Example"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
}
message = AdiumThemeContentInfo(AdiumThemeMessageInfo::LocalToRemote);
message.setMessage(i18nc("Example message in preview conversation","A different example message"));
message.setSenderDisplayName(i18nc("Example email", "ted@example.com"));
message.setSenderScreenName(i18nc("Example name", "Ted Example"));
message.setTime(QDateTime::currentDateTime());
ui->chatView->addAdiumContentMessage(message);
if (ui->chatView->showPresenceChanges()) {
statusMessage = AdiumThemeStatusInfo();
statusMessage.setMessage(i18nc("Example message in preview conversation","Ted Example is now Away.")); //FIXME sync this with chat text logic.
statusMessage.setSender(i18nc("Example name", "Ted Example"));
statusMessage.setTime(QDateTime::currentDateTime());
statusMessage.setStatus(QLatin1String("away"));
ui->chatView->addAdiumStatusMessage(statusMessage);
}
}
void AppearanceConfigTab::updateVariantsList()
{
QHash<QString, QString> variants = ui->chatView->chatStyle()->getVariants();
ui->variantComboBox->clear();
ui->variantComboBox->addItems(variants.keys());
ui->variantComboBox->setCurrentItem(ui->chatView->variantName());
}
void AppearanceConfigTab::saveTab(KConfigGroup appearanceConfigGroup)
{
appearanceConfigGroup.writeEntry(QLatin1String("styleName"), ui->styleComboBox->itemData(ui->styleComboBox->currentIndex()).toString());
appearanceConfigGroup.writeEntry(QLatin1String("styleVariant"), ui->variantComboBox->currentText());
appearanceConfigGroup.writeEntry(QLatin1String("displayHeader"), ui->showHeader->isChecked());
appearanceConfigGroup.writeEntry(QLatin1String("useCustomFont"), ui->customFontBox->isChecked());
appearanceConfigGroup.writeEntry(QLatin1String("fontFamily"), ui->fontFamily->currentFont().family());
appearanceConfigGroup.writeEntry(QLatin1String("fontSize"), ui->fontSize->value());
appearanceConfigGroup.writeEntry(QLatin1String("showPresenceChanges"), ui->showPresenceCheckBox->isChecked());
appearanceConfigGroup.writeEntry(QLatin1String("showJoinLeaveChanges"), ui->showJoinLeaveCheckBox->isChecked());
appearanceConfigGroup.sync();
}
void AppearanceConfigTab::loadTab()
{
ChatWindowStyleManager *manager = ChatWindowStyleManager::self();
manager->loadStyles();
AdiumThemeView::ChatType chatType;
if( m_groupChat ) {
chatType = AdiumThemeView::GroupChat;
} else {
chatType = AdiumThemeView::SingleUserChat;
}
ui->chatView->load(chatType);
ui->chatView->initialise(m_demoChatHeader);
ui->showHeader->setChecked(ui->chatView->isHeaderDisplayed());
ui->customFontBox->setChecked(ui->chatView->isCustomFont());
ui->fontFamily->setCurrentFont(QFont(ui->chatView->fontFamily()));
ui->fontSize->setValue(ui->chatView->fontSize());
ui->showPresenceCheckBox->setChecked(ui->chatView->showPresenceChanges());
ui->showJoinLeaveCheckBox->setChecked(ui->chatView->showJoinLeaveChanges());
}
void AppearanceConfigTab::defaultTab()
{
ChatWindowStyleManager *manager = ChatWindowStyleManager::self();
manager->loadStyles();
if (m_groupChat) {
onVariantSelected(QLatin1String("SimKete.AdiumMessageStyle"));
} else {
onVariantSelected(QLatin1String("renkoo.AdiumMessageStyle"));
}
onStyleSelected(0);
ui->showHeader->setChecked(false);
ui->customFontBox->setChecked(false);
ui->chatView->setUseCustomFont(false);
ui->fontFamily->setCurrentFont(KGlobalSettings::generalFont());
ui->fontSize->setValue(QWebSettings::DefaultFontSize);
ui->showPresenceCheckBox->setChecked(!m_groupChat);
ui->showJoinLeaveCheckBox->setChecked(!m_groupChat);
}
|
gpl-2.0
|
CarlAtComputer/tracker
|
playground/other_gef/Model.diagram/src/model/diagram/part/ModelInitDiagramFileAction.java
|
1816
|
package model.diagram.part;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import model.diagram.edit.parts.CarEditPart;
/**
* @generated
*/
public class ModelInitDiagramFileAction implements IWorkbenchWindowActionDelegate {
/**
* @generated
*/
private IWorkbenchWindow window;
/**
* @generated
*/
public void init(IWorkbenchWindow window) {
this.window = window;
}
/**
* @generated
*/
public void dispose() {
window = null;
}
/**
* @generated
*/
public void selectionChanged(IAction action, ISelection selection) {
}
/**
* @generated
*/
private Shell getShell() {
return window.getShell();
}
/**
* @generated
*/
public void run(IAction action) {
TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE.createEditingDomain();
Resource resource = ModelDiagramEditorUtil.openModel(getShell(),
Messages.InitDiagramFile_OpenModelFileDialogTitle, editingDomain);
if (resource == null || resource.getContents().isEmpty()) {
return;
}
EObject diagramRoot = (EObject) resource.getContents().get(0);
Wizard wizard = new ModelNewDiagramFileWizard(resource.getURI(), diagramRoot, editingDomain);
wizard.setWindowTitle(NLS.bind(Messages.InitDiagramFile_WizardTitle, CarEditPart.MODEL_ID));
ModelDiagramEditorUtil.runWizard(getShell(), wizard, "InitDiagramFile"); //$NON-NLS-1$
}
}
|
gpl-2.0
|
UnboundID/ldapsdk
|
tests/unit/src/com/unboundid/ldap/sdk/unboundidds/monitors/GaugeMonitorEntryTestCase.java
|
23975
|
/*
* Copyright 2014-2020 Ping Identity Corporation
* All Rights Reserved.
*/
/*
* Copyright 2014-2020 Ping Identity Corporation
*
* 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.
*/
/*
* Copyright (C) 2014-2020 Ping Identity Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPLv2 only)
* or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
* 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, see <http://www.gnu.org/licenses>.
*/
package com.unboundid.ldap.sdk.unboundidds.monitors;
import java.util.Map;
import org.testng.annotations.Test;
import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.LDAPSDKTestCase;
import com.unboundid.ldap.sdk.unboundidds.AlarmSeverity;
import com.unboundid.util.StaticUtils;
/**
* This class provides test coverage for the GaugeMonitorEntry class.
*/
public class GaugeMonitorEntryTestCase
extends LDAPSDKTestCase
{
/**
* Provides test coverage for the constructor with a valid entry with all
* values present.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testConstructorAllValues()
throws Exception
{
final Entry e = new Entry(
"dn: cn=Test Gauge,cn=monitor",
"objectClass: top",
"objectClass: ds-monitor-entry",
"objectClass: ds-gauge-monitor-entry",
"objectClass: extensibleObject",
"cn: Test Gauge",
"gauge-name: test-gauge-name",
"resource: test-resource",
"resource-type: test-resource-type",
"severity: NORMAL",
"previous-severity: WARNING",
"summary: test-summary",
"error-message: test-error-message-1",
"error-message: test-error-message-2",
"gauge-init-time: 20140102030405.678Z",
"update-time: 20140102030405.679Z",
"samples-this-interval: 1",
"current-severity-start-time: 20140102030405.680Z",
"current-severity-duration: 2 seconds",
"current-severity-duration-millis: 2000",
"last-normal-state-start-time: 20140102030405.681Z",
"last-normal-state-end-time: 20140102030405.682Z",
"last-normal-state-duration: 3 seconds",
"last-normal-state-duration-millis: 3000",
"total-normal-state-duration: 4 seconds",
"total-normal-state-duration-millis: 4000",
"last-warning-state-start-time: 20140102030405.683Z",
"last-warning-state-end-time: 20140102030405.684Z",
"last-warning-state-duration: 5 seconds",
"last-warning-state-duration-millis: 5000",
"total-warning-state-duration: 6 seconds",
"total-warning-state-duration-millis: 6000",
"last-minor-state-start-time: 20140102030405.685Z",
"last-minor-state-end-time: 20140102030405.686Z",
"last-minor-state-duration: 7 seconds",
"last-minor-state-duration-millis: 7000",
"total-minor-state-duration: 8 seconds",
"total-minor-state-duration-millis: 8000",
"last-major-state-start-time: 20140102030405.687Z",
"last-major-state-end-time: 20140102030405.688Z",
"last-major-state-duration: 9 seconds",
"last-major-state-duration-millis: 9000",
"total-major-state-duration: 10 seconds",
"total-major-state-duration-millis: 10000",
"last-critical-state-start-time: 20140102030405.689Z",
"last-critical-state-end-time: 20140102030405.690Z",
"last-critical-state-duration: 11 seconds",
"last-critical-state-duration-millis: 11000",
"total-critical-state-duration: 12 seconds",
"total-critical-state-duration-millis: 12000");
final GaugeMonitorEntry me = new GaugeMonitorEntry(e);
assertNotNull(me.toString());
assertEquals(me.getMonitorClass(), "ds-gauge-monitor-entry");
assertEquals(MonitorEntry.decode(e).getClass().getName(),
GaugeMonitorEntry.class.getName());
assertNotNull(me.getGaugeName());
assertEquals(me.getGaugeName(), "test-gauge-name");
assertNotNull(me.getResource());
assertEquals(me.getResource(), "test-resource");
assertNotNull(me.getResourceType());
assertEquals(me.getResourceType(), "test-resource-type");
assertNotNull(me.getCurrentSeverity());
assertEquals(me.getCurrentSeverity(), AlarmSeverity.NORMAL);
assertNotNull(me.getPreviousSeverity());
assertEquals(me.getPreviousSeverity(), AlarmSeverity.WARNING);
assertNotNull(me.getSummary());
assertEquals(me.getSummary(), "test-summary");
assertNotNull(me.getErrorMessages());
assertFalse(me.getErrorMessages().isEmpty());
assertEquals(me.getErrorMessages().size(), 2);
assertTrue(me.getErrorMessages().contains("test-error-message-1"));
assertTrue(me.getErrorMessages().contains("test-error-message-2"));
assertNotNull(me.getInitTime());
assertEquals(me.getInitTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.678Z"));
assertNotNull(me.getUpdateTime());
assertEquals(me.getUpdateTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.679Z"));
assertNotNull(me.getSamplesThisInterval());
assertEquals(me.getSamplesThisInterval(), Long.valueOf(1L));
assertNotNull(me.getCurrentSeverityStartTime());
assertEquals(me.getCurrentSeverityStartTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.680Z"));
assertNotNull(me.getCurrentSeverityDurationString());
assertEquals(me.getCurrentSeverityDurationString(), "2 seconds");
assertNotNull(me.getCurrentSeverityDurationMillis());
assertEquals(me.getCurrentSeverityDurationMillis(), Long.valueOf(2000L));
assertNotNull(me.getLastNormalStateStartTime());
assertEquals(me.getLastNormalStateStartTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.681Z"));
assertNotNull(me.getLastNormalStateEndTime());
assertEquals(me.getLastNormalStateEndTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.682Z"));
assertNotNull(me.getLastNormalStateDurationString());
assertEquals(me.getLastNormalStateDurationString(), "3 seconds");
assertNotNull(me.getLastNormalStateDurationMillis());
assertEquals(me.getLastNormalStateDurationMillis(), Long.valueOf(3000L));
assertNotNull(me.getTotalNormalStateDurationString());
assertEquals(me.getTotalNormalStateDurationString(), "4 seconds");
assertNotNull(me.getTotalNormalStateDurationMillis());
assertEquals(me.getTotalNormalStateDurationMillis(), Long.valueOf(4000L));
assertNotNull(me.getLastWarningStateStartTime());
assertEquals(me.getLastWarningStateStartTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.683Z"));
assertNotNull(me.getLastWarningStateEndTime());
assertEquals(me.getLastWarningStateEndTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.684Z"));
assertNotNull(me.getLastWarningStateDurationString());
assertEquals(me.getLastWarningStateDurationString(), "5 seconds");
assertNotNull(me.getLastWarningStateDurationMillis());
assertEquals(me.getLastWarningStateDurationMillis(), Long.valueOf(5000L));
assertNotNull(me.getTotalWarningStateDurationString());
assertEquals(me.getTotalWarningStateDurationString(), "6 seconds");
assertNotNull(me.getTotalWarningStateDurationMillis());
assertEquals(me.getTotalWarningStateDurationMillis(), Long.valueOf(6000L));
assertNotNull(me.getLastMinorStateStartTime());
assertEquals(me.getLastMinorStateStartTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.685Z"));
assertNotNull(me.getLastMinorStateEndTime());
assertEquals(me.getLastMinorStateEndTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.686Z"));
assertNotNull(me.getLastMinorStateDurationString());
assertEquals(me.getLastMinorStateDurationString(), "7 seconds");
assertNotNull(me.getLastMinorStateDurationMillis());
assertEquals(me.getLastMinorStateDurationMillis(), Long.valueOf(7000L));
assertNotNull(me.getTotalMinorStateDurationString());
assertEquals(me.getTotalMinorStateDurationString(), "8 seconds");
assertNotNull(me.getTotalMinorStateDurationMillis());
assertEquals(me.getTotalMinorStateDurationMillis(), Long.valueOf(8000L));
assertNotNull(me.getLastMajorStateStartTime());
assertEquals(me.getLastMajorStateStartTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.687Z"));
assertNotNull(me.getLastMajorStateEndTime());
assertEquals(me.getLastMajorStateEndTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.688Z"));
assertNotNull(me.getLastMajorStateDurationString());
assertEquals(me.getLastMajorStateDurationString(), "9 seconds");
assertNotNull(me.getLastMajorStateDurationMillis());
assertEquals(me.getLastMajorStateDurationMillis(), Long.valueOf(9000L));
assertNotNull(me.getTotalMajorStateDurationString());
assertEquals(me.getTotalMajorStateDurationString(), "10 seconds");
assertNotNull(me.getTotalMajorStateDurationMillis());
assertEquals(me.getTotalMajorStateDurationMillis(), Long.valueOf(10000L));
assertNotNull(me.getLastCriticalStateStartTime());
assertEquals(me.getLastCriticalStateStartTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.689Z"));
assertNotNull(me.getLastCriticalStateEndTime());
assertEquals(me.getLastCriticalStateEndTime(),
StaticUtils.decodeGeneralizedTime("20140102030405.690Z"));
assertNotNull(me.getLastCriticalStateDurationString());
assertEquals(me.getLastCriticalStateDurationString(), "11 seconds");
assertNotNull(me.getLastCriticalStateDurationMillis());
assertEquals(me.getLastCriticalStateDurationMillis(), Long.valueOf(11000L));
assertNotNull(me.getTotalCriticalStateDurationString());
assertEquals(me.getTotalCriticalStateDurationString(), "12 seconds");
assertNotNull(me.getTotalCriticalStateDurationMillis());
assertEquals(me.getTotalCriticalStateDurationMillis(),
Long.valueOf(12000L));
assertNotNull(me.getMonitorDisplayName());
assertNotNull(me.getMonitorDescription());
final Map<String,MonitorAttribute> attrs = me.getMonitorAttributes();
assertNotNull(attrs);
assertFalse(attrs.isEmpty());
assertNotNull(attrs.get("gauge-name"));
assertFalse(attrs.get("gauge-name").hasMultipleValues());
assertNotNull(attrs.get("gauge-name").getStringValue());
assertNotNull(attrs.get("resource"));
assertFalse(attrs.get("resource").hasMultipleValues());
assertNotNull(attrs.get("resource").getStringValue());
assertNotNull(attrs.get("resource-type"));
assertFalse(attrs.get("resource-type").hasMultipleValues());
assertNotNull(attrs.get("resource-type").getStringValue());
assertNotNull(attrs.get("severity"));
assertFalse(attrs.get("severity").hasMultipleValues());
assertNotNull(attrs.get("severity").getStringValue());
assertNotNull(attrs.get("previous-severity"));
assertFalse(attrs.get("previous-severity").hasMultipleValues());
assertNotNull(attrs.get("previous-severity").getStringValue());
assertNotNull(attrs.get("summary"));
assertFalse(attrs.get("summary").hasMultipleValues());
assertNotNull(attrs.get("summary").getStringValue());
assertNotNull(attrs.get("error-message"));
assertTrue(attrs.get("error-message").hasMultipleValues());
assertNotNull(attrs.get("error-message").getStringValues());
assertEquals(attrs.get("error-message").getStringValues().size(), 2);
assertNotNull(attrs.get("gauge-init-time"));
assertFalse(attrs.get("gauge-init-time").hasMultipleValues());
assertNotNull(attrs.get("gauge-init-time").getDateValue());
assertNotNull(attrs.get("update-time"));
assertFalse(attrs.get("update-time").hasMultipleValues());
assertNotNull(attrs.get("update-time").getDateValue());
assertNotNull(attrs.get("samples-this-interval"));
assertFalse(attrs.get("samples-this-interval").hasMultipleValues());
assertNotNull(attrs.get("samples-this-interval").getLongValue());
assertNotNull(attrs.get("current-severity-start-time"));
assertFalse(attrs.get("current-severity-start-time").hasMultipleValues());
assertNotNull(attrs.get("current-severity-start-time").getDateValue());
assertNotNull(attrs.get("current-severity-duration"));
assertFalse(attrs.get("current-severity-duration").hasMultipleValues());
assertNotNull(attrs.get("current-severity-duration").getStringValue());
assertNotNull(attrs.get("current-severity-duration-millis"));
assertFalse(attrs.get("current-severity-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("current-severity-duration-millis").getLongValue());
assertNotNull(attrs.get("last-normal-state-start-time"));
assertFalse(attrs.get("last-normal-state-start-time").hasMultipleValues());
assertNotNull(attrs.get("last-normal-state-start-time").getDateValue());
assertNotNull(attrs.get("last-normal-state-end-time"));
assertFalse(attrs.get("last-normal-state-end-time").hasMultipleValues());
assertNotNull(attrs.get("last-normal-state-end-time").getDateValue());
assertNotNull(attrs.get("last-normal-state-duration"));
assertFalse(attrs.get("last-normal-state-duration").hasMultipleValues());
assertNotNull(attrs.get("last-normal-state-duration").getStringValue());
assertNotNull(attrs.get("last-normal-state-duration-millis"));
assertFalse(attrs.get("last-normal-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("last-normal-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("total-normal-state-duration"));
assertFalse(attrs.get("total-normal-state-duration").hasMultipleValues());
assertNotNull(attrs.get("total-normal-state-duration").getStringValue());
assertNotNull(attrs.get("total-normal-state-duration-millis"));
assertFalse(attrs.get("total-normal-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("total-normal-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("last-warning-state-start-time"));
assertFalse(attrs.get("last-warning-state-start-time").hasMultipleValues());
assertNotNull(attrs.get("last-warning-state-start-time").getDateValue());
assertNotNull(attrs.get("last-warning-state-end-time"));
assertFalse(attrs.get("last-warning-state-end-time").hasMultipleValues());
assertNotNull(attrs.get("last-warning-state-end-time").getDateValue());
assertNotNull(attrs.get("last-warning-state-duration"));
assertFalse(attrs.get("last-warning-state-duration").hasMultipleValues());
assertNotNull(attrs.get("last-warning-state-duration").getStringValue());
assertNotNull(attrs.get("last-warning-state-duration-millis"));
assertFalse(attrs.get("last-warning-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("last-warning-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("total-warning-state-duration"));
assertFalse(attrs.get("total-warning-state-duration").hasMultipleValues());
assertNotNull(attrs.get("total-warning-state-duration").getStringValue());
assertNotNull(attrs.get("total-warning-state-duration-millis"));
assertFalse(attrs.get("total-warning-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("total-warning-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("last-minor-state-start-time"));
assertFalse(attrs.get("last-minor-state-start-time").hasMultipleValues());
assertNotNull(attrs.get("last-minor-state-start-time").getDateValue());
assertNotNull(attrs.get("last-minor-state-end-time"));
assertFalse(attrs.get("last-minor-state-end-time").hasMultipleValues());
assertNotNull(attrs.get("last-minor-state-end-time").getDateValue());
assertNotNull(attrs.get("last-minor-state-duration"));
assertFalse(attrs.get("last-minor-state-duration").hasMultipleValues());
assertNotNull(attrs.get("last-minor-state-duration").getStringValue());
assertNotNull(attrs.get("last-minor-state-duration-millis"));
assertFalse(attrs.get("last-minor-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("last-minor-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("total-minor-state-duration"));
assertFalse(attrs.get("total-minor-state-duration").hasMultipleValues());
assertNotNull(attrs.get("total-minor-state-duration").getStringValue());
assertNotNull(attrs.get("total-minor-state-duration-millis"));
assertFalse(attrs.get("total-minor-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("total-minor-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("last-major-state-start-time"));
assertFalse(attrs.get("last-major-state-start-time").hasMultipleValues());
assertNotNull(attrs.get("last-major-state-start-time").getDateValue());
assertNotNull(attrs.get("last-major-state-end-time"));
assertFalse(attrs.get("last-major-state-end-time").hasMultipleValues());
assertNotNull(attrs.get("last-major-state-end-time").getDateValue());
assertNotNull(attrs.get("last-major-state-duration"));
assertFalse(attrs.get("last-major-state-duration").hasMultipleValues());
assertNotNull(attrs.get("last-major-state-duration").getStringValue());
assertNotNull(attrs.get("last-major-state-duration-millis"));
assertFalse(attrs.get("last-major-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("last-major-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("total-major-state-duration"));
assertFalse(attrs.get("total-major-state-duration").hasMultipleValues());
assertNotNull(attrs.get("total-major-state-duration").getStringValue());
assertNotNull(attrs.get("total-major-state-duration-millis"));
assertFalse(attrs.get("total-major-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("total-major-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("last-critical-state-start-time"));
assertFalse(attrs.get("last-critical-state-start-time").
hasMultipleValues());
assertNotNull(attrs.get("last-critical-state-start-time").getDateValue());
assertNotNull(attrs.get("last-critical-state-end-time"));
assertFalse(attrs.get("last-critical-state-end-time").hasMultipleValues());
assertNotNull(attrs.get("last-critical-state-end-time").getDateValue());
assertNotNull(attrs.get("last-critical-state-duration"));
assertFalse(attrs.get("last-critical-state-duration").hasMultipleValues());
assertNotNull(attrs.get("last-critical-state-duration").getStringValue());
assertNotNull(attrs.get("last-critical-state-duration-millis"));
assertFalse(attrs.get("last-critical-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("last-critical-state-duration-millis").
getLongValue());
assertNotNull(attrs.get("total-critical-state-duration"));
assertFalse(attrs.get("total-critical-state-duration").hasMultipleValues());
assertNotNull(attrs.get("total-critical-state-duration").getStringValue());
assertNotNull(attrs.get("total-critical-state-duration-millis"));
assertFalse(attrs.get("total-critical-state-duration-millis").
hasMultipleValues());
assertNotNull(attrs.get("total-critical-state-duration-millis").
getLongValue());
}
/**
* Provides test coverage for the constructor with a valid entry with no
* values present.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test()
public void testConstructorNoValues()
throws Exception
{
final Entry e = new Entry(
"dn: cn=Test Gauge,cn=monitor",
"objectClass: top",
"objectClass: ds-monitor-entry",
"objectClass: ds-gauge-monitor-entry",
"objectClass: extensibleObject",
"cn: Test Gauge");
final GaugeMonitorEntry me = new GaugeMonitorEntry(e);
assertNotNull(me.toString());
assertEquals(me.getMonitorClass(), "ds-gauge-monitor-entry");
assertEquals(MonitorEntry.decode(e).getClass().getName(),
GaugeMonitorEntry.class.getName());
assertNull(me.getGaugeName());
assertNull(me.getResource());
assertNull(me.getResourceType());
assertNull(me.getCurrentSeverity());
assertNull(me.getPreviousSeverity());
assertNull(me.getSummary());
assertNotNull(me.getErrorMessages());
assertTrue(me.getErrorMessages().isEmpty());
assertNull(me.getInitTime());
assertNull(me.getUpdateTime());
assertNull(me.getSamplesThisInterval());
assertNull(me.getCurrentSeverityStartTime());
assertNull(me.getCurrentSeverityDurationString());
assertNull(me.getCurrentSeverityDurationMillis());
assertNull(me.getLastNormalStateStartTime());
assertNull(me.getLastNormalStateEndTime());
assertNull(me.getLastNormalStateDurationString());
assertNull(me.getLastNormalStateDurationMillis());
assertNull(me.getTotalNormalStateDurationString());
assertNull(me.getTotalNormalStateDurationMillis());
assertNull(me.getLastWarningStateStartTime());
assertNull(me.getLastWarningStateEndTime());
assertNull(me.getLastWarningStateDurationString());
assertNull(me.getLastWarningStateDurationMillis());
assertNull(me.getTotalWarningStateDurationString());
assertNull(me.getTotalWarningStateDurationMillis());
assertNull(me.getLastMinorStateStartTime());
assertNull(me.getLastMinorStateEndTime());
assertNull(me.getLastMinorStateDurationString());
assertNull(me.getLastMinorStateDurationMillis());
assertNull(me.getTotalMinorStateDurationString());
assertNull(me.getTotalMinorStateDurationMillis());
assertNull(me.getLastMajorStateStartTime());
assertNull(me.getLastMajorStateEndTime());
assertNull(me.getLastMajorStateDurationString());
assertNull(me.getLastMajorStateDurationMillis());
assertNull(me.getTotalMajorStateDurationString());
assertNull(me.getTotalMajorStateDurationMillis());
assertNull(me.getLastCriticalStateStartTime());
assertNull(me.getLastCriticalStateEndTime());
assertNull(me.getLastCriticalStateDurationString());
assertNull(me.getLastCriticalStateDurationMillis());
assertNull(me.getTotalCriticalStateDurationString());
assertNull(me.getTotalCriticalStateDurationMillis());
assertNotNull(me.getMonitorDisplayName());
assertNotNull(me.getMonitorDescription());
final Map<String,MonitorAttribute> attrs = me.getMonitorAttributes();
assertNotNull(attrs);
assertTrue(attrs.isEmpty());
}
}
|
gpl-2.0
|
atlet/Infinite-Responder
|
templates/bulk_add.admin.php
|
2671
|
<br />
<center>
<table width="750" bgcolor="#660000" cellpadding="0" cellspacing="3" style="border: 1px solid #000000;">
<tr>
<td>
<p align="center" style="font-size: 200%"><font color="#FFFFFF">-- Add a List of Addresses --</font></p>
</td>
</tr>
</table>
<table width="750" bgcolor="#FFFFFF" cellpadding="0" cellspacing="3" style="border: 1px solid #000000;">
<tr>
<td>
<p align="center" style="font-size: 100"><font color="#990000"><strong>Warning: </strong>Manually-added subscribers will not receive a confirmation email!</font></p>
</td>
</tr>
</table>
<FORM action="admin.php" name="List_Adder" enctype="multipart/form-data" method="POST">
<table width="750" bgcolor="#CCCCCC" cellpadding="0" cellspacing="3" style="border: 1px solid #000000;">
<tr>
<td colspan="2">
<center><strong><font size="4" color="#333333">Universal settings (Effects all names)</font></strong></center>
</td>
</tr>
<tr>
<td width="440">
<font size="4" color="#330000">Select Responder:<br></font>
<center>
<?php ResponderPulldown('r_ID'); ?>
</center>
</td>
<td width="250">
<center>
<font size="4" color="#003300">
HTML:
<input type="RADIO" name="h" value="1">Yes
<input type="RADIO" name="h" value="0" checked="checked">No
</font>
</center>
</td>
<tr>
<td colspan="2"><hr style = "border: 0; background-color: #660000; color: #660000; height: 1px; width: 100%;"></td>
</tr>
<tr>
<td colspan="2">
<center>
<strong>Enter list of email addresses, seperated by a comma.</strong><br>
Example: <em>john@doe.org, jane@me-tarzan.com, lois@lane.net</em><br>
<textarea name="comma_list" rows="15" cols="95" class="text_area"></textarea>
</center>
</td>
</tr>
<tr>
<td colspan="2"><hr style = "border: 0; background-color: #660000; color: #660000; height: 1px; width: 100%;"></td>
</tr>
<tr>
<td colspan="2">
<strong>Load a comma-spliced file: </strong><br>
<center><input type="file" name="load_file" size="80" maxlength="200" class="fields"></center>
</td>
</tr>
<tr>
<td colspan="2">
<table align="right"><tr><td>
<input type="hidden" name="action" value="bulk_add_do">
<input type="submit" name="Save" value="Save" class="save_b">
</td></tr></table>
</td>
</tr>
</table>
</FORM>
</center>
|
gpl-2.0
|
SIB-Colombia/biodiversidad_wp
|
wp-content/themes/klaus/vc_extend/vc_templates/az_tog_container.php
|
516
|
<?php
/**
* Shortcode attributes
* @var $atts
* @var $el_class
* @var $content
*/
$output = '';
$atts = vc_map_get_attributes( $this->getShortcode(), $atts );
extract( $atts );
$el_class = $this->getExtraClass($el_class);
$css_class = apply_filters(VC_SHORTCODE_CUSTOM_CSS_FILTER_TAG,'toggle-builder'.$el_class, $this->settings['base']);
$class = setClass(array($css_class));
$output .= '<div'.$class.'>'.wpb_js_remove_wpautop($content).'</div>'.$this->endBlockComment('az_tog_container')."\n";
echo $output;
?>
|
gpl-2.0
|
KungFuLucky7/NetBeansProjects
|
dine-a-mite/logout.php
|
704
|
<?php
/**
* This is for logging out the user
*/
include_once 'Includes/db.php';
session_start();
if (!isset($_SESSION['signed_in']) || $_SESSION['signed_in'] == false) {
include_once 'Includes/header.php';
// Print message if user is not signed in
print '<div class="alert alert-block">
<h4>You have to be signed in to access this page.<br />
If you don\'t have an account, please <a class="btn" href="register.php">Register</a></h4></div>';
include_once 'Includes/footer.php';
} else {
session_destroy();
$_SESSION['signed_in'] = false;
if (!$_SESSION['signed_in']) {
header('Location: http://sfsuswe.com' . $_GET['redirect_url']);
}
}
?>
|
gpl-2.0
|
tinhnd1988/phuongtoan
|
wp-content/themes/phuongtoan/home.php
|
4066
|
<?php
/*
/*
/* Template Name: Trang chแปง
/*
*/
get_header();
echo do_shortcode("[huge_it_slider id='1']"); //Display Homepage Slider
?>
<div id="home-page-content">
<div class="ads-content">
<h2>Phฦฐฦกng Toร n</h2>
<ul>
<li><span></span>Chuyรชn tฦฐ vแบฅn - thiแบฟt kแบฟ - thi cรดng: led, alu, pano, chแปฏ nแปi, bแบฃng hiแปu, hแปp ฤรจn, cแปญa, cแบงu thang, lan can, nhร tiแปn chแบฟ, mรกi xแบฟp lฦฐแปฃn sรณng, mรกi tรดn, nhร vรฒm, mรกi hiรชn di ฤแปng, tแบฅm lแปฃp lแบฅy sรกng poly...</li>
<li><span></span>Thiแบฟt kแบฟ - thi cรดng cafe sรขn vฦฐแปn, quรกn ฤn, nhร hร ng, trฦฐแปng hแปc, hแป bฦกi...</li>
<li><span></span>Nhแบญn thi cรดng tแบฅt cแบฃ cรกc tแปnh & thร nh phแป</li>
</ul>
</div>
<div class="random-cates">
<ul>
<?php
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => 0,
'orderby' => 'name',
'order' => 'ASC',
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'hide_empty' => 0,
'taxonomy' => 'danh-muc',
'pad_counts' => false
);
$categories = get_categories($args);
$nCatesDisplay = 4;
$nCate = 0;
$nItemsFound = 0;
// Check minimum items to display
foreach ($categories as $cate) {
$product = query_posts(array(
'post_type' => 'san-pham',
'tax_query' => array(
array(
'taxonomy' => 'danh-muc',
'terms' => $cate->term_id,
'field' => 'term_id'
),
),
));
$nItemsFound+=count($product);
if ($nItemsFound >= $nCatesDisplay)
break;
}
if ($nItemsFound < $nCatesDisplay){
echo '<center>Cรณ quรก รญt sแบฃn phแบฉm ฤแป hiแปn thแป</center>';
}
else{
$resultProducts = array();
while ($nCate < $nCatesDisplay) :
$randCatesKey = array_rand($categories, $nCatesDisplay);
foreach ($randCatesKey as $key) :
if ($nCate >= $nCatesDisplay)
break;
$product = query_posts(array(
'post_type' => 'san-pham',
'showposts' => 1,
'tax_query' => array(
array(
'taxonomy' => 'danh-muc',
'terms' => $categories[$key]->term_id,
'field' => 'term_id'
),
),
'orderby' => 'rand',
'order' => 'ASC',
'posts_per_page' => -1
));
?>
<?php
if (!empty($product)):
if (in_array($product[0]->ID, $resultProducts))
break;
$nCate++;
array_push($resultProducts,$product[0]->ID);
$meta_value_cate = get_post_meta($product[0]->ID);
$url_cate = wp_get_attachment_url( get_post_thumbnail_id($product[0]->ID) );
$img_featured = get_the_post_thumbnail($product[0]->ID, 'medium');
//$permalink = get_permalink($product[0]->ID);
$permalink = get_permalink( get_page_by_path( 'danh-muc-san-pham' ) ).'#'.$categories[$key]->slug;
?>
<li>
<div class="box">
<a href="<?php echo $permalink; ?>">
<?php if ($img_featured): ?>
<div class="imgsp"><?php echo $img_featured; ?></div>
<?php else: ?>
<img src="<?php bloginfo('template_url');?>/images/noimages.jpeg" width="220" height="190">
<?php endif; ?>
<h2><?php echo $categories[$key]->name; ?></h2>
<p class="cate-desc"><?php echo $categories[$key]->category_description ?></p>
</a>
<div class="button">
<button class="icon_right"><a href="<?php echo $permalink; ?>">Xem thรชm</a></button>
</div>
</div>
</li>
<?php endif;
endforeach;
endwhile;
}
?>
</ul>
</div>
</div>
<?php get_footer(); ?>
|
gpl-2.0
|
mrbullard/Burapa
|
administrator/components/com_joomgallery/script.php
|
12582
|
<?php
// $HeadURL: https://joomgallery.org/svn/joomgallery/JG-2.0/JG/trunk/administrator/components/com_joomgallery/script.php $
// $Id: script.php 3681 2012-03-04 15:59:38Z erftralle $
/****************************************************************************************\
** JoomGallery 2 **
** By: JoomGallery::ProjectTeam **
** Copyright (C) 2008 - 2012 JoomGallery::ProjectTeam **
** Based on: JoomGallery 1.0.0 by JoomGallery::ProjectTeam **
** Released under GNU GPL Public License **
** License: http://www.gnu.org/copyleft/gpl.html or have a look **
** at administrator/components/com_joomgallery/LICENSE.TXT **
\****************************************************************************************/
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
/**
* Install method
* is called by the installer of Joomla!
*
* @access protected
* @return void
* @since 2.0
*/
class Com_JoomGalleryInstallerScript
{
/**
* Version string of the current version
*
* @var string
*/
private $version = '2.0.0';
/**
* Install method
*
* @param
* @param
* @return boolean True on success, false otherwise
* @since 2.0
*/
public function install()
{
jimport('joomla.filesystem.file');
$this->_addStyleDeclarations();
// Create image directories
require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomgallery'.DS.'helpers'.DS.'file.php';
$thumbpath = JPATH_ROOT.DS.'images'.DS.'joomgallery'.DS.'thumbnails';
$imgpath = JPATH_ROOT.DS.'images'.DS.'joomgallery'.DS.'details';
$origpath = JPATH_ROOT.DS.'images'.DS.'joomgallery'.DS.'originals';
$result = array();
$result[] = JFolder::create($thumbpath);
$result[] = JoomFile::copyIndexHtml($thumbpath);
$result[] = JFolder::create($imgpath);
$result[] = JoomFile::copyIndexHtml($imgpath);
$result[] = JFolder::create($origpath);
$result[] = JoomFile::copyIndexHtml($origpath);
$result[] = JoomFile::copyIndexHtml(JPATH_ROOT.DS.'images'.DS.'joomgallery');
if(in_array(false, $result))
{
JError::raiseWarning(500, JText::_('Unable to create image directories!'));
return false;
}
// Create news feed module
$subdomain = '';
$language = & JFactory::getLanguage();
if(strpos($language->getTag(), 'de-') === false)
{
$subdomain = 'en.';
}
$row = JTable::getInstance('module');
$row->title = 'JoomGallery News';
$row->ordering = 1;
$row->position = 'joom_cpanel';
$row->published = 1;
$row->module = 'mod_feed';
$row->access = 1; // TODO: '1' does not have to be a valid access level
$row->showtitle = 1;
$row->params = 'cache=1
cache_time=15
moduleclass_sfx=
rssurl=http://www.'.$subdomain.'joomgallery.net/feed/rss.html
rssrtl=0
rsstitle=1
rssdesc=0
rssimage=1
rssitems=3
rssitemdesc=1
word_count=30';
$row->client_id = 1;
$row->language = '*';
if(!$row->store())
{
JError::raiseWarning(500, JText::_('Unable to insert feed module data!'));
}
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert('#__modules_menu');
$query->set('moduleid = '.$row->id);
$query->set('menuid = 0');
$db->setQuery($query);
if(!$db->query())
{
JError::raiseNotice(500, JText::_('Unable to assign feed module!'));
}
// joom_settings.css
$temp = JPATH_ROOT.DS.'media'.DS.'joomgallery'.DS.'css'.DS.'joom_settings.temp.css';
$dest = JPATH_ROOT.DS.'media'.DS.'joomgallery'.DS.'css'.DS.'joom_settings.css';
if(!JFile::move($temp, $dest))
{
JError::raiseWarning(500, JText::_('Unable to copy joom_settings.css!'));
return false;
}
?>
<div style="margin:0px auto; text-align:center; width:360px;">
<img src="../media/joomgallery/images/joom_logo.png" alt="JoomGallery Logo" />
<h3 class="headline oktext">JoomGallery <?php echo $this->version; ?> was installed successfully.</h3>
<p>You may now start using JoomGallery or download specific language files afore:</p>
<div class="button2-left" style="margin-left:70px;">
<div class="blank">
<a title="Start" onclick="location.href='index.php?option=com_joomgallery';" href="#">Start now!</a>
</div>
</div>
<div class="button2-left jg_floatright" style="margin-right:70px;">
<div class="blank">
<a title="Languages" onclick="location.href='index.php?option=com_joomgallery&controller=help';" href="#">Languages</a>
</div>
</div>
<div style="clear:both;"></div>
</div>
<?php
}
/**
* Update method
*
* @param
* @param
* @return boolean True on success, false otherwise
* @since 2.0
*/
function update()
{
jimport('joomla.filesystem.file');
$this->_addStyleDeclarations(); ?>
<div style="margin:0px auto; text-align:center; width:360px;">
<img src="../media/joomgallery/images/joom_logo.png" alt="JoomGallery Logo" />
</div>
<?php
$error = false;
// Delete temporary joom_settings.temp.css
if(JFile::exists(JPATH_ROOT.DS.'media'.DS.'joomgallery'.DS.'css'.DS.'joom_settings.temp.css'))
{
if(!JFile::delete(JPATH_ROOT.DS.'media'.DS.'joomgallery'.DS.'css'.DS.'joom_settings.temp.css'))
{
JError::raiseWarning(500, JText::_('Unable to delete temporary joom_settings.temp.css!'));
$error = true;
}
}
// - Start Update Info - //
echo '<div class="infobox headline">';
echo ' Update JoomGallery to version: '.$this->version;
echo '</div>';
//******************* Delete folders/files ************************************
echo '<div class="infobox">';
echo '<p class="headline2">File system</p>';
$delete_folders = array();
echo '<p>';
echo 'Looking for orphaned files and folders from the old installation<br />';
// Unzipped folder of latest auto update with cURL
$temp_dir = false;
$query = "SELECT jg_pathtemp FROM #__joomgallery_config";
$database = JFactory::getDBO();
$database->setQuery($query);
$temp_dir = $database->loadResult();
if($temp_dir)
{
//$delete_folders[] = JPATH_SITE.DS.$temp_dir.'update';
for($i = 0; $i <= 100; $i++)
{
$update_folder = JPATH_SITE.DS.$temp_dir.'update'.$i;
if(JFolder::exists($update_folder))
{
$delete_folders[] = $update_folder;
}
}
}
$deleted = false;
$jg_delete_error = false;
foreach($delete_folders as $delete_folder)
{
if(JFolder::exists($delete_folder))
{
echo 'delete folder: '.$delete_folder.' : ';
$result = JFolder::delete($delete_folder);
if($result == true)
{
$deleted = true;
echo '<span class="oktext">ok</span>';
}
else
{
$jg_delete_error = true;
echo '<span class="notoktext">not ok</span>';
}
echo '<br />';
}
}
//Files
$delete_files = array();
// Cache file of the newsfeed for the update checker
$delete_files[] = JPATH_ADMINISTRATOR.DS.'cache'.DS.md5('http://www.joomgallery.net/components/com_newversion/rss/extensions2.rss').'.spc';
$delete_files[] = JPATH_ADMINISTRATOR.DS.'cache'.DS.md5('http://www.en.joomgallery.net/components/com_newversion/rss/extensions2.rss').'.spc';
// Zip file of latest auto update with cURL
$delete_files[] = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomgallery'.DS.'temp'.DS.'update.zip';
foreach($delete_files as $delete_file)
{
if(JFile::exists($delete_file))
{
echo 'delete file: '.$delete_file.' : ';
$result = JFile::delete($delete_file);
if($result == true)
{
$deleted = true;
echo '<span class="oktext">ok</span>';
}
else
{
$jg_delete_error = true;
echo '<span class="notoktext">not ok</span>';
}
echo '<br />';
}
}
//******************* END delete folders/files ************************************
if($deleted)
{
if($jg_delete_error)
{
echo '<span class="notoktext">problems in deletion of files/folders</span>';
$error = true;
}
else
{
echo '<span class="oktext">files/folders sucessfully deleted</span>';
}
}
else
{
echo '<span class="oktext">nothing to delete</span>';
}
echo '</p>';
echo '</div>';
//******************* Write joom_settings.css ************************************
/*echo '<div class="infobox">';
echo '<p class="headline2">CSS</p>';
echo '<p>';
echo 'Update configuration dependent CSS settings: ';
require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomgallery'.DS.'includes'.DS.'defines.php';
JLoader::register('JoomConfig', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomgallery'.DS.'helpers'.DS.'config.php');
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomgallery'.DS.'tables');
$config = JoomConfig::getInstance('admin');
if(!$config->save())
{
$error = true;
echo '<span class="notoktext">not ok</span>';
}
else
{
echo '<span class="oktext">ok</span>';
}
echo '</p>';
echo '</div>';*/
//******************* End write joom_settings.css ************************************
if($error)
{
echo '<h3 class="headline notoktext">Problem with the update to JoomGallery version '.$this->version.'<br />Please read the update infos above</h3>';
JError::raiseWarning(500, JText::_('Problem with the update to JoomGallery version '.$this->version.'. Please read the update infos below'));
}
else
{ ?>
<div style="margin:0px auto; text-align:center; width:360px;">
<img src="../media/joomgallery/images/joom_logo.png" alt="JoomGallery Logo" />
<h3 class="headline oktext">JoomGallery was updated to version <?php echo $this->version; ?> successfully.</h3>
<p>You may now go on using JoomGallery or update your language files for JoomGallery:</p>
<div class="button2-left" style="margin-left:70px;">
<div class="blank">
<a title="Start" onclick="location.href='index.php?option=com_joomgallery';" href="#">Go on!</a>
</div>
</div>
<div class="button2-left jg_floatright" style="margin-right:70px;">
<div class="blank">
<a title="Languages" onclick="location.href='index.php?option=com_joomgallery&controller=help';" href="#">Languages</a>
</div>
</div>
<div style="clear:both;"></div>
</div>
<?php
}
return !$error;
}
/**
* Uninstall method
*
* @param
* @param
* @return boolean True on success, false otherwise
* @since 2.0
*/
function uninstall()
{
$path = JPATH_ROOT.DS.'images'.DS.'joomgallery';
if(JFolder::exists($path))
{
JFolder::delete($path);
}
echo 'JoomGallery was uninstalled successfully!<br />
Please remember to remove your images folders manually
if you didn\'t use JoomGallery\'s default directories.';
return true;
}
/**
* Adds the style declaration for the install or update output to the document
*
* @return void
* @since 2.0
*/
private function _addStyleDeclarations()
{
// CCS Styles
$cssfile = '
<style type="text/css">
p {
margin:0.3em 0;
padding:0.2em 0;
}
.infobox {
margin:0.5em 0;
padding:0.4em 0 0.4em 1em;
background-color:#f0f0f0;
border:2px solid #000;
}
.headline {
font-size:1.5em;
text-align:center;
font-weight:bold;
}
.headline2 {
font-size:1.3em;
text-align:center;
font-weight:bold;
}
.headline3 {
text-align:center;
font-weight:bold;
}
.oktext {
color:#2d2;
font-weight:bold;
}
.notoktext {
color:#d22;
font-weight:bold;
}
.noticetext {
color:#f38201;
font-weight:bold;
}
.button2-left{
margin-top:10px;
margin-bottom:30px;
}
.jg_floatright{
float:right;
}
</style>';
echo $cssfile;
}
}
|
gpl-2.0
|
battle-for-wesnoth/svn
|
src/tools/exploder_cutter.cpp
|
4172
|
/* $Id$ */
/*
Copyright (C) 2004 - 2013 by Philippe Plantier <ayin@anathas.org>
Part of the Battle for Wesnoth Project http://www.wesnoth.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.
See the COPYING file for more details.
*/
#include "exploder_cutter.hpp"
#include "filesystem.hpp"
#include "serialization/parser.hpp"
#include "serialization/preprocessor.hpp"
#include "serialization/string_utils.hpp"
#include "SDL_image.h"
#include <boost/foreach.hpp>
#include <iostream>
cutter::cutter()
: masks_()
, verbose_(false)
{
}
const config cutter::load_config(const std::string &filename)
{
const std::string conf_string = find_configuration(filename);
config res;
try {
scoped_istream stream = preprocess_file(conf_string);
read(res, *stream);
} catch(config::error& err) {
throw exploder_failure("Unable to load the configuration for the file " + filename + ": "+ err.message);
}
return res;
}
void cutter::load_masks(const config& conf)
{
BOOST_FOREACH(const config &m, conf.child_range("mask"))
{
const std::string name = m["name"];
const std::string image = get_mask_dir() + "/" + std::string(m["image"]);
if(verbose_) {
std::cerr << "Adding mask " << name << "\n";
}
if(image.empty())
throw exploder_failure("Missing image for mask " + name);
const exploder_point shift(m["shift"]);
const exploder_rect cut(m["cut"]);
if(masks_.find(name) != masks_.end() && masks_[name].filename != image) {
throw exploder_failure("Mask " + name +
" correspond to two different files: " +
name + " and " +
masks_.find(name)->second.filename);
}
if(masks_.find(name) == masks_.end()) {
mask& cur_mask = masks_[name];
cur_mask.name = name;
cur_mask.shift = shift;
cur_mask.cut = cut;
cur_mask.filename = image;
surface tmp(IMG_Load(image.c_str()));
if(tmp == NULL)
throw exploder_failure("Unable to load mask image " + image);
cur_mask.image = make_neutral_surface(tmp);
}
if(masks_[name].image == NULL)
throw exploder_failure("Unable to load mask image " + image);
}
}
cutter::surface_map cutter::cut_surface(surface surf, const config& conf)
{
surface_map res;
BOOST_FOREACH(const config &part, conf.child_range("part")) {
add_sub_image(surf, res, &part);
}
return res;
}
std::string cutter::find_configuration(const std::string &file)
{
//finds the file prefix.
const std::string fname = file_name(file);
const std::string::size_type dotpos = fname.rfind('.');
std::string basename;
if(dotpos == std::string::npos) {
basename = fname;
} else {
basename = fname.substr(0, dotpos);
}
return get_exploder_dir() + "/" + basename + ".cfg";
}
void cutter::add_sub_image(const surface &surf, surface_map &map, const config* config)
{
const std::string name = (*config)["name"];
if(name.empty())
throw exploder_failure("Un-named sub-image");
if(masks_.find(name) == masks_.end())
throw exploder_failure("Unable to find mask corresponding to " + name);
const cutter::mask& mask = masks_[name];
std::vector<std::string> pos = utils::split((*config)["pos"]);
if(pos.size() != 2)
throw exploder_failure("Invalid position " + (*config)["pos"].str());
int x = atoi(pos[0].c_str());
int y = atoi(pos[1].c_str());
const SDL_Rect cut = create_rect(x - mask.shift.x
, y - mask.shift.y
, mask.image->w
, mask.image->h);
typedef std::pair<std::string, positioned_surface> sme;
positioned_surface ps;
ps.image = ::cut_surface(surf, cut);
if(ps.image == NULL)
throw exploder_failure("Unable to cut surface!");
ps.name = name;
ps.mask = mask;
ps.pos.x = x - mask.shift.x;
ps.pos.y = y - mask.shift.y;
map.insert(sme(name, ps));
if(verbose_) {
std::cerr << "Extracting sub-image " << name << ", position (" << x << ", " << y << ")\n";
}
}
void cutter::set_verbose(bool value)
{
verbose_ = value;
}
|
gpl-2.0
|
mercury233/ygopro-scripts
|
c28400508.lua
|
2935
|
--No.97 ้พๅฝฑ็ฅใใฉใใฐใฉใใชใณ
function c28400508.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,8,2)
c:EnableReviveLimit()
--cannot be target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(aux.tgoval)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(28400508,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,28400508)
e2:SetCost(c28400508.spcost)
e2:SetTarget(c28400508.sptg)
e2:SetOperation(c28400508.spop)
c:RegisterEffect(e2)
end
c28400508.xyz_number=97
function c28400508.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c28400508.cfilter(c)
return c:IsRace(RACE_DRAGON) and c:IsSetCard(0x48) and not c:IsCode(28400508)
end
function c28400508.spfilter(c,e,tp)
return c:IsRace(RACE_DRAGON) and c:IsSetCard(0x48) and not c:IsCode(28400508)
and c:IsType(TYPE_XYZ) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and (c:IsLocation(LOCATION_EXTRA) and Duel.GetLocationCountFromEx(tp)>0
or c:IsLocation(LOCATION_GRAVE) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0)
and Duel.IsExistingMatchingCard(c28400508.cfilter,tp,LOCATION_EXTRA+LOCATION_GRAVE,0,1,c)
end
function c28400508.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c28400508.spfilter,tp,LOCATION_EXTRA+LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA+LOCATION_GRAVE)
end
function c28400508.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c28400508.spfilter),tp,LOCATION_EXTRA+LOCATION_GRAVE,0,1,1,nil,e,tp)
local tc=g:GetFirst()
local fid=0
if tc then
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(28400508,1))
local g2=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c28400508.cfilter),tp,LOCATION_EXTRA+LOCATION_GRAVE,0,1,1,tc)
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
Duel.Overlay(tc,g2)
fid=tc:GetFieldID()
end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
--
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c28400508.ftarget)
e2:SetLabel(fid)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
end
function c28400508.ftarget(e,c)
return e:GetLabel()~=c:GetFieldID()
end
|
gpl-2.0
|
viniciuswiesehofer/ERPLINCE
|
wp-content/plugins/perch-shortcodes/includes/pricing/pricing-post-type.php
|
2115
|
<?php
if ( ! function_exists('landx_pricing_post_type') ) {
// Register Custom Post Type
function landx_pricing_post_type() {
$labels = array(
'name' => _x( 'Pricing tables', 'Post Type General Name', 'landx' ),
'singular_name' => _x( 'Pricing table', 'Post Type Singular Name', 'landx' ),
'menu_name' => __( 'Pricing table', 'landx' ),
'parent_item_colon' => __( 'Parent Item:', 'landx' ),
'all_items' => __( 'All Items', 'landx' ),
'view_item' => __( 'View Item', 'landx' ),
'add_new_item' => __( 'Add New Item', 'landx' ),
'add_new' => __( 'Add New', 'landx' ),
'edit_item' => __( 'Edit Item', 'landx' ),
'update_item' => __( 'Update Item', 'landx' ),
'search_items' => __( 'Search Item', 'landx' ),
'not_found' => __( 'Not found', 'landx' ),
'not_found_in_trash' => __( 'Not found in Trash', 'landx' ),
);
$args = array(
'labels' => $labels,
'supports' => array( 'title', 'editor', 'revisions', 'page-attributes', ),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'pricing', $args );
}
// Hook into the 'init' action
add_action( 'init', 'landx_pricing_post_type', 0 );
}
add_filter('manage_edit-pricing_columns', 'perch_pricings_columns', 10);
add_action('manage_pricing_posts_custom_column', 'perch_pricings_custom_columns', 10, 2);
function perch_pricings_columns($defaults){
$defaults['perch_pricing_thumbs'] = __('Shotcodes', THEMENAME);
return $defaults;
}
function perch_pricings_custom_columns($column_name, $post_id){
switch ( $column_name ) {
case 'perch_pricing_thumbs':
echo '[pricing_table id="'.$post_id.'"]';
break;
}
}
?>
|
gpl-2.0
|
TheCallSign/noskwl
|
src/net/strawberrystudios/noskwl/old/packet/PacketFactory.java
|
1142
|
/*
* Copyright (C) 2015 giddyc
*
* 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.
*/
package net.strawberrystudios.noskwl.old.packet;
/**
*
* @author giddyc
*/
public abstract class PacketFactory {
protected String uuid;
public PacketFactory(){
this.uuid = "";
}
public PacketFactory(String address){
this.uuid = address;
}
public void setUID(String address) {
this.uuid = address;
}
}
|
gpl-2.0
|
joker-b/kbImport
|
classes/ImgInfo.py
|
6937
|
#! /bin/python
"""
Each ImgInfo object contains archive data about a single image
"""
import os
import sys
import re
import shutil
from AppOptions import AppOptions
from DNGConverter import DNGConverter
if sys.version_info > (3,):
long = int
class ImgInfo(object):
"""Data About Images"""
doppelFiles = {}
doppelPaths = {}
createdDirs = []
failedCopies = []
testLog = {}
regexDotAvchd = re.compile('(.*).AVCHD')
regexPic = re.compile(r'([A-Z_][A-Z_][A-Z_][A-Z_]\d\d\d\d)\.(JPG|RAF|RW2|RAW|DNG)')
dng = None
opt = None
@classmethod
def set_options(cls, Options=AppOptions()):
cls.opt = Options
@classmethod
def set_dng_converter(cls, DNG=DNGConverter()):
if cls.opt is None:
cls.set_options()
cls.dng = DNG
def __init__(self, Name, Path):
"basic data about each image to be archived"
self.srcName = Name
self.srcPath = Path
self.destName = ''
self.destPath = ''
self.has_dng = False
if ImgInfo.opt is None:
print("Caution: Class wasn't initialized for image '{},' using defaults".format(self.srcName))
ImgInfo.set_dng_converter()
self.nBytes = long(0)
def has_doppelganger(self):
"figure out if there is a copy of this file in a neighboring archive"
name = ImgInfo.doppelFiles.get(self.srcName)
if name:
return True
(monthPath, dayFolder) = os.path.split(self.destPath)
dayStr = dayFolder[:10]
if self.opt.unify:
print("doppelhunting in {}".format(monthPath))
if not os.path.exists(monthPath):
return False
for d in os.listdir(monthPath):
name = ImgInfo.doppelPaths.get(d)
if name:
# already checked
continue
if d[:10] != dayStr:
# only review days we care about
continue
ImgInfo.doppelPaths[d] = 1
for f in os.listdir(os.path.join(monthPath, d)):
m = ImgInfo.regexPic.search(f)
if m:
theMatch = m.group(0)
ImgInfo.doppelFiles[theMatch] = 1
return ImgInfo.doppelFiles.get(self.srcName) is not None
def dest_mkdir(self, Prefix=' '):
"""
check for existence, create as needed.
Return directory name.
When testing is True, still return name of the (non-existent) directory!
"""
if not os.path.exists(self.destPath):
if ImgInfo.opt.testing:
dp = ImgInfo.testLog.get(self.destPath)
if not dp:
print("Need to dest_mkdir({}) **".format(self.destPath))
ImgInfo.testLog[self.destPath] = 1
else:
os.mkdir(self.destPath)
if not os.path.exists(self.destPath):
print('dest_mkdir("{}") FAIL')
return None
print("** dest_mkdir({})".format(self.destPath))
ImgInfo.createdDirs.append(Prefix+os.path.split(self.destPath)[1])
return self.destPath
elif not os.path.isdir(self.destPath):
print("dest_mkdir() ERROR: {} exists but not a directory!".format(self.destPath))
return None
return self.destPath
def archive(self):
"Archive a Single Image File"
# TODO -- Apply fancier naming to self.destName
FullDestPath = os.path.join(self.destPath, self.destName)
protected = False
opDescription = ''
if os.path.exists(FullDestPath) or self.has_doppelganger():
if ImgInfo.opt.force_copies:
if ImgInfo.opt.verbose:
opDescription += ("Overwriting {}\n".format(FullDestPath))
self.incr(self.srcPath)
else:
protected = True
m = ImgInfo.regexDotAvchd.search(FullDestPath)
if m:
FullDestPath = os.path.join(m.group(1), "...", self.srcName)
else:
reportPath = os.path.join('...', os.path.split(self.destPath)[-1], self.destName)
opDescription += ("{} -> {}".format(self.srcName, reportPath))
self.incr(self.srcPath)
if protected:
return False
self.dest_mkdir()
if len(opDescription) > 0:
print(opDescription)
if ImgInfo.opt.rename:
return self.safe_rename(FullDestPath)
if ImgInfo.opt.use_dng:
return ImgInfo.dng.convert(self.srcPath, self.destPath, self.destName)
# else:
return self.safe_copy(FullDestPath)
def incr(self, FullSrcPath):
try:
s = os.stat(FullSrcPath)
except FileNotFoundError:
print("incr('{}') no file".format(FullSrcPath))
return False
except:
print("incr('{}') cannot stat source".format(FullSrcPath))
print("Err {}".format(sys.exc_info()[0]))
return False
self.nBytes += s.st_size
return True
def safe_copy(self, DestPath):
"Copy file, unless we are testing"
if ImgInfo.opt.testing: # TODO - Volume data
return True # always "work"
try:
shutil.copyfile(self.srcPath, DestPath)
except OSError(e):
print(f"OSErr: {e}")
print("OSErr, bad copy for {}".format(p, self.srcPath, DestPath))
ImgInfo.failedCopies.append(DestPath)
return False
except:
p = sys.exc_info()[0]
print("Failed to copy: '{}'!!\n\t{}\n\t{}".format(p, self.srcPath, DestPath))
print(" Details: errno {} on\n\t'{}'' and\n\t'{}'".format(p.errno, p.filename, p.filename2))
print(" Detail2: {} chars, '{}'".format(p.characters_written, p.strerror))
ImgInfo.failedCopies.append(DestPath)
return False
return True
def safe_rename(self, DestPath):
"Rename file, unless we are testing"
if ImgInfo.opt.verbose:
print("Rename {}\nAs {}".format(self.srcPath, DestPath))
if ImgInfo.opt.testing: # TODO - Volume data
return True # always "work"
try:
os.rename(self.srcPath, DestPath)
except:
p = sys.exc_info()[0]
print("Failed to rename: '{}'!!\n\t{}\n\t{}".format(p, self.srcPath, DestPath))
print(" Details: errno {} on\n\t'{}'' and\n\t'{}'".format(p.errno, p.filename, p.filename2))
print(" Detail2: {} chars, '{}'".format(p.characters_written, p.strerror))
return False
return True
def dng_check(self, UsingDNG):
if UsingDNG:
m = DNGConverter.filetype_search(self.srcName.upper())
if m:
self.has_dng = True
# renaming allowed here
self.destName = "{}.DNG".format(self.opt.add_prefix(m.groups(0)[0]))
@classmethod
def final_cleanup(cls):
if len(cls.failedCopies) < 1:
return
print("FAILED COPIES: {}".format(len(cls.failedCopies)))
foundCruft = False
for file in cls.failedCopies:
if os.path.exists(file):
if not foundCruft:
print("RECOMMENDED ACTION:")
foundCruft = True
print("rm {}".format(file))
if foundCruft:
print("running kbImport again may catch the missing files after cleanup")
if __name__ == '__main__':
print("testing time")
opt = AppOptions()
opt.testing = True
opt.set_jobname('InfoTest')
ImgInfo.set_options(opt)
ai = ImgInfo('test.jpg', '/home/kevinbjorke/pix')
ai.dng_check(ImgInfo.opt.use_dng)
ai.archive()
|
gpl-2.0
|
WBCE/news
|
search.php
|
5355
|
<?php
/**
*
* @category modules
* @package news
* @author WebsiteBaker Project
* @copyright 2009-2011, Website Baker Org. e.V.
* @link http://www.websitebaker2.org/
* @license http://www.gnu.org/licenses/gpl.html
* @platform WebsiteBaker 2.8.x
* @requirements PHP 5.2.2 and higher
* @version $Id: search.php 1538 2011-12-10 15:06:15Z Luisehahne $
* @filesource $HeadURL: svn://isteam.dynxs.de/wb_svn/wb280/tags/2.8.3/wb/modules/news/search.php $
* @lastmodified $Date: 2011-12-10 16:06:15 +0100 (Sa, 10. Dez 2011) $
*
*/
//no direct file access
if(count(get_included_files())==1) die(header("Location: ../index.php",TRUE,301));
function news_search($func_vars) {
extract($func_vars, EXTR_PREFIX_ALL, 'func');
static $search_sql1 = FALSE;
static $search_sql2 = FALSE;
static $search_sql3 = FALSE;
if(function_exists('search_make_sql_part')) {
if($search_sql1===FALSE)
$search_sql1 = search_make_sql_part($func_search_url_array, $func_search_match, array('`title`','`content_short`','`content_long`'));
if($search_sql2===FALSE)
$search_sql2 = search_make_sql_part($func_search_url_array, $func_search_match, array('`title`','`comment`'));
if($search_sql3===FALSE)
$search_sql3 = search_make_sql_part($func_search_url_array, $func_search_match, array('g.`title`'));
} else {
$search_sql1 = $search_sql2 = $search_sql3 = '1=1';
}
// how many lines of excerpt we want to have at most
$max_excerpt_num = $func_default_max_excerpt;
// do we want excerpt from comments?
$excerpt_from_comments = true; // TODO: make this configurable
$divider = ".";
$result = false;
if($func_time_limit>0) {
$stop_time = time() + $func_time_limit;
}
// fetch all active news-posts (from active groups) in this section.
$t = time();
$table_posts = TABLE_PREFIX."mod_news_posts";
$table_groups = TABLE_PREFIX."mod_news_groups";
$query = $func_database->query("
SELECT p.post_id, p.title, p.content_short, p.content_long, p.link, p.posted_when, p.posted_by
FROM $table_posts AS p LEFT OUTER JOIN $table_groups AS g ON p.group_id = g.group_id
WHERE p.section_id='$func_section_id' AND p.active = '1' AND ( g.active IS NULL OR g.active = '1' )
AND (published_when = '0' OR published_when <= $t) AND (published_until = 0 OR published_until >= $t)
ORDER BY p.post_id DESC
");
// now call print_excerpt() for every single post
if($query->numRows() > 0) {
while($res = $query->fetchRow()) {
$text = '';
// break out if stop-time is reached
if(isset($stop_time) && time()>$stop_time) return($result);
// fetch content
$postquery = $func_database->query("
SELECT title, content_short, content_long
FROM $table_posts
WHERE post_id='{$res['post_id']}' AND $search_sql1
");
if($postquery->numRows() > 0) {
if($p_res = $postquery->fetchRow()) {
$text = $p_res['title'].$divider.$p_res['content_short'].$divider.$p_res['content_long'].$divider;
}
}
// fetch comments and add to $text
if($excerpt_from_comments) {
$table = TABLE_PREFIX."mod_news_comments";
$commentquery = $func_database->query("
SELECT title, comment
FROM $table
WHERE post_id='{$res['post_id']}' AND $search_sql2
ORDER BY commented_when ASC
");
if($commentquery->numRows() > 0) {
while($c_res = $commentquery->fetchRow()) {
// break out if stop-time is reached
if(isset($stop_time) && time()>$stop_time) return($result);
$text .= $c_res['title'].$divider.$c_res['comment'].$divider;
}
}
}
if($text) {
$mod_vars = array(
'page_link' => $res['link'], // use direct link to news-item
'page_link_target' => "",
'page_title' => $func_page_title,
'page_description' => $res['title'], // use news-title as description
'page_modified_when' => $res['posted_when'],
'page_modified_by' => $res['posted_by'],
'text' => $text,
'max_excerpt_num' => $max_excerpt_num
);
if(print_excerpt2($mod_vars, $func_vars)) {
$result = true;
}
}
}
}
// now fetch group-titles - ignore those without (active) postings
$table_groups = TABLE_PREFIX."mod_news_groups";
$table_posts = TABLE_PREFIX."mod_news_posts";
$query = $func_database->query("
SELECT DISTINCT g.title, g.group_id
FROM $table_groups AS g INNER JOIN $table_posts AS p ON g.group_id = p.group_id
WHERE g.section_id='$func_section_id' AND g.active = '1' AND p.active = '1' AND $search_sql3
");
// now call print_excerpt() for every single group, too
if($query->numRows() > 0) {
while($res = $query->fetchRow()) {
// break out if stop-time is reached
if(isset($stop_time) && time()>$stop_time) return($result);
$mod_vars = array(
'page_link' => $func_page_link,
'page_link_target' => "&g=".$res['group_id'],
'page_title' => $func_page_title,
'page_description' => $func_page_description,
'page_modified_when' => $func_page_modified_when,
'page_modified_by' => $func_page_modified_by,
'text' => $res['title'].$divider,
'max_excerpt_num' => $max_excerpt_num
);
if(print_excerpt2($mod_vars, $func_vars)) {
$result = true;
}
}
}
return $result;
}
|
gpl-2.0
|
AlanWarren/dotfiles
|
dev/adv-class/oop/inheritance.js
|
747
|
// OO classical inheritance copies parent class props down to instances, and children.
// Inheritance means copying. Ask for bananna, and you get the Gorialla + Jungle.
// [] ----> instance
// Prototypal Inheritance is not really inheritance. It's called "Behavior Delegation"
// Instances link in the opposite direction when they link to parents.
// This is a delegation up the chain, instead of copying down the chain. [] <--- instance
// This example illustrates behavior delegation. a1 doesn't have a speak() function, but
// it looks up the chain until it finds it.
function Foo(who) {
this.me = who;
}
Foo.prototype.speak = function() {
console.log("Hello, I am " + this.me + ".");
};
var a1 = new Foo("a1");
a1.speak();
|
gpl-2.0
|
Voskrese/mipsonqemu
|
user/uc/home/source/do_seccode.php
|
8071
|
<?php
/*
[UCenter Home] (C) 2007-2008 Comsenz Inc.
$Id: do_seccode.php 8531 2008-08-20 07:27:23Z liguode $
*/
if(!defined('IN_UCHOME')) {
exit('Access Denied');
}
//ร
รครร
$seccodedata = array (
'width' => 100,
'height' => 40,
'adulterate' => '0',//รรฆยปรบยฑยณยพยฐรยผรร
'angle' => '0',//รรฆยปรบรรฃรยฑยถร
'shadow' => '1',//รรตรยฐ
);
//รรฉรยครรซ
$seccode = mkseccode();
//รรจยถยจcookie
ssetcookie('seccode', authcode($seccode, 'ENCODE'));
if(function_exists('imagecreate') && function_exists('imagecolorset') && function_exists('imagecopyresized') &&
function_exists('imagecolorallocate') && function_exists('imagechar') && function_exists('imagecolorsforindex') &&
function_exists('imageline') && function_exists('imagecreatefromstring') && (function_exists('imagegif') || function_exists('imagepng') || function_exists('imagejpeg'))) {
include_once(S_ROOT.'./source/securimage.php');
$img = new securimage();
// alternate use: $img->show('/path/to/background.jpg');
$img->show(S_ROOT.'./source/images/secbk1.jpg',$seccode);
//$img->show('',$seccode);
} else {
$numbers = array
(
'B' => array('00','fc','66','66','66','7c','66','66','fc','00'),
'C' => array('00','38','64','c0','c0','c0','c4','64','3c','00'),
'E' => array('00','fe','62','62','68','78','6a','62','fe','00'),
'F' => array('00','f8','60','60','68','78','6a','62','fe','00'),
'G' => array('00','78','cc','cc','de','c0','c4','c4','7c','00'),
'H' => array('00','e7','66','66','66','7e','66','66','e7','00'),
'J' => array('00','f8','cc','cc','cc','0c','0c','0c','7f','00'),
'K' => array('00','f3','66','66','7c','78','6c','66','f7','00'),
'M' => array('00','f7','63','6b','6b','77','77','77','e3','00'),
'P' => array('00','f8','60','60','7c','66','66','66','fc','00'),
'Q' => array('00','78','cc','cc','cc','cc','cc','cc','78','00'),
'R' => array('00','f3','66','6c','7c','66','66','66','fc','00'),
'T' => array('00','78','30','30','30','30','b4','b4','fc','00'),
'V' => array('00','1c','1c','36','36','36','63','63','f7','00'),
'W' => array('00','36','36','36','77','7f','6b','63','f7','00'),
'X' => array('00','f7','66','3c','18','18','3c','66','ef','00'),
'Y' => array('00','7e','18','18','18','3c','24','66','ef','00'),
'2' => array('fc','c0','60','30','18','0c','cc','cc','78','00'),
'3' => array('78','8c','0c','0c','38','0c','0c','8c','78','00'),
'4' => array('00','3e','0c','fe','4c','6c','2c','3c','1c','1c'),
'6' => array('78','cc','cc','cc','ec','d8','c0','60','3c','00'),
'7' => array('30','30','38','18','18','18','1c','8c','fc','00'),
'8' => array('78','cc','cc','cc','78','cc','cc','cc','78','00'),
'9' => array('f0','18','0c','6c','dc','cc','cc','cc','78','00')
);
foreach($numbers as $i => $number) {
for($j = 0; $j < 6; $j++) {
$a1 = substr('012', mt_rand(0, 2), 1).substr('012345', mt_rand(0, 5), 1);
$a2 = substr('012345', mt_rand(0, 5), 1).substr('0123', mt_rand(0, 3), 1);
mt_rand(0, 1) == 1 ? array_push($numbers[$i], $a1) : array_unshift($numbers[$i], $a1);
mt_rand(0, 1) == 0 ? array_push($numbers[$i], $a1) : array_unshift($numbers[$i], $a2);
}
}
$bitmap = array();
for($i = 0; $i < 20; $i++) {
for($j = 0; $j < 4; $j++) {
$n = substr($seccode, $j, 1);
$bytes = $numbers[$n][$i];
$a = mt_rand(0, 14);
array_push($bitmap, $bytes);
}
}
for($i = 0; $i < 8; $i++) {
$a = substr('012345', mt_rand(0, 2), 1) . substr('012345', mt_rand(0, 5), 1);
array_unshift($bitmap, $a);
array_push($bitmap, $a);
}
$image = pack('H*', '424d9e000000000000003e000000280000002000000018000000010001000000'.
'0000600000000000000000000000000000000000000000000000FFFFFF00'.implode('', $bitmap));
header('Content-Type: image/bmp');
echo $image;
}
//รรบยณรรรฆยปรบ
function mkseccode() {
$seccode = random(6, 1);
$s = sprintf('%04s', base_convert($seccode, 10, 24));
$seccode = '';
$seccodeunits = 'BCEFGHJKMPQRTVWXY2346789';
for($i = 0; $i < 4; $i++) {
$unit = ord($s{$i});
$seccode .= ($unit >= 0x30 && $unit <= 0x39) ? $seccodeunits[$unit - 0x30] : $seccodeunits[$unit - 0x57];
}
return $seccode;
}
//ยฑยณยพยฐ
function seccode_background() {
global $seccodedata, $c;
$im = imagecreatetruecolor($seccodedata['width'], $seccodedata['height']);
$backgroundcolor = imagecolorallocate($im, 255, 255, 255);
for($i = 0;$i < 3;$i++) {
$start[$i] = mt_rand(200, 255);
$end[$i] = mt_rand(100, 245);
$step[$i] = ($end[$i] - $start[$i]) / $seccodedata['width'];
$c[$i] = $start[$i];
}
$color = imagecolorallocate($im, 235, 235, 235);
for($i = 0;$i < $seccodedata['width'];$i++) {
//$color = imagecolorallocate($im, $c[0], $c[1], $c[2]);
$color = imagecolorallocate($im, 235, 235, 235);
imageline($im, $i, 0, $i-$angle, $seccodedata['height'], $color);
$c[0] += $step[0];
$c[1] += $step[1];
$c[2] += $step[2];
}
$c[0] -= 20;
$c[1] -= 20;
$c[2] -= 20;
obclean();
if(function_exists('imagepng')) {
imagepng($im);
} else {
imagejpeg($im, '', 100);
}
imagedestroy($im);
$bgcontent = ob_get_contents();
obclean();
return $bgcontent;
}
function seccode_adulterate() {
global $seccodedata, $im, $c;
$linenums = $seccodedata['height'] / 10;
for($i=0; $i <= $linenums; $i++) {
$color = imagecolorallocate($im, $c[0], $c[1], $c[2]);
$x = mt_rand(0, $seccodedata['width']);
$y = mt_rand(0, $seccodedata['height']);
if(mt_rand(0, 1)) {
imagearc($im, $x, $y, mt_rand(0, $seccodedata['width']), mt_rand(0, $seccodedata['height']), mt_rand(0, 360), mt_rand(0, 360), $color);
} else {
imageline($im, $x, $y, $linex + mt_rand(0, 20), $liney + mt_rand(0, mt_rand($seccodedata['height'], $seccodedata['width'])), $color);
}
}
}
function seccode_giffont() {
global $seccode, $seccodedata, $im, $c;
$seccodedir = array();
if(function_exists('imagecreatefromgif')) {
$seccoderoot = 'image/seccode/';
$dirs = opendir($seccoderoot);
while($dir = readdir($dirs)) {
if($dir != '.' && $dir != '..' && file_exists($seccoderoot.$dir.'/9.gif')) {
$seccodedir[] = $dir;
}
}
}
$widthtotal = 0;
for($i = 0; $i <= 3; $i++) {
$imcodefile = $seccodedir ? $seccoderoot.$seccodedir[array_rand($seccodedir)].'/'.strtolower($seccode[$i]).'.gif' : '';
if(!empty($imcodefile) && file_exists($imcodefile)) {
$font[$i]['file'] = $imcodefile;
$font[$i]['data'] = getimagesize($imcodefile);
$font[$i]['width'] = $font[$i]['data'][0] + mt_rand(0, 6) - 4;
$font[$i]['height'] = $font[$i]['data'][1] + mt_rand(0, 6) - 4;
$font[$i]['width'] += mt_rand(0, $seccodedata['width'] / 5 - $font[$i]['width']);
$widthtotal += $font[$i]['width'];
} else {
$font[$i]['file'] = '';
$font[$i]['width'] = 8 + mt_rand(0, $seccodedata['width'] / 5 - 5);
$widthtotal += $font[$i]['width'];
}
}
$x = mt_rand(1, $seccodedata['width'] - $widthtotal);
for($i = 0; $i <= 3; $i++) {
if($font[$i]['file']) {
$imcode = imagecreatefromgif($font[$i]['file']);
$y = mt_rand(0, $seccodedata['height'] - $font[$i]['height']);
if($seccodedata['shadow']) {
$imcodeshadow = $imcode;
imagecolorset($imcodeshadow, 0 , 255 - $c[0], 255 - $c[1], 255 - $c[2]);
imagecopyresized($im, $imcodeshadow, $x + 1, $y + 1, 0, 0, $font[$i]['width'], $font[$i]['height'], $font[$i]['data'][0], $font[$i]['data'][1]);
}
imagecolorset($imcode, 0 , $c[0], $c[1], $c[2]);
imagecopyresized($im, $imcode, $x, $y, 0, 0, $font[$i]['width'], $font[$i]['height'], $font[$i]['data'][0], $font[$i]['data'][1]);
} else {
$y = mt_rand(0, $seccodedata['height'] - 20);
if($seccodedata['shadow']) {
$text_shadowcolor = imagecolorallocate($im, 255 - $c[0], 255 - $c[1], 255 - $c[2]);
imagechar($im, 5, $x + 1, $y + 1, $seccode[$i], $text_shadowcolor);
}
$text_color = imagecolorallocate($im, $c[0], $c[1], $c[2]);
imagechar($im, 5, $x, $y, $seccode[$i], $text_color);
}
$x += $font[$i]['width'];
}
}
?>
|
gpl-2.0
|
jaymaine/connect-local
|
wp-content/plugins/cred-frontend-editor/views/templates/notification-subject-codes.tpl.php
|
1533
|
<?php if (!defined('ABSPATH')) die('Security check'); ?>
<span class="cred-media-button cred-media-button2">
<a href='javascript:;' class='cred-icon-button' title='<?php echo esc_attr(__('Insert Subject Codes','wp-cred')); ?>'></a>
<div class="cred-popup-box">
<div class='cred-popup-heading'>
<h3><?php _e('Subject Codes (click to insert)','wp-cred'); ?></h3>
<a href='javascript:;' title='<?php echo esc_attr(__('Close','wp-cred')); ?>' class='cred-close-button cred-cred-cancel-close'></a>
</div>
<div class="cred-popup-inner cred-notification-subject-codes">
<?php
$notification_codes=apply_filters('cred_admin_notification_subject_codes', array(
'%%POST_ID%%'=> __('Post ID','wp-cred'),
'%%POST_TITLE%%'=> __('Post Title','wp-cred'),
'%%POST_PARENT_TITLE%%'=> __('Parent Title','wp-cred'),
'%%USER_LOGIN_NAME%%'=> __('User Login Name','wp-cred'),
'%%USER_DISPLAY_NAME%%'=> __('User Display Name','wp-cred'),
'%%FORM_NAME%%'=> __('Form Name','wp-cred'),
'%%DATE_TIME%%'=> __('Date/Time','wp-cred')
), $form, $ii, $notification);
foreach ($notification_codes as $_v=>$_l)
{
?><a href="javascript:;" class='button cred_field_add_code' data-area="#<?php echo $area_id; ?>" data-value="<?php echo $_v; ?>"><?php echo $_l; ?></a><?php
}
?>
</div>
</div>
</span>
|
gpl-2.0
|
tomas-pluskal/mzmine3
|
src/main/java/io/github/mzmine/gui/chartbasics/simplechart/providers/impl/series/FeaturesToMobilityMzHeatmapProvider.java
|
5917
|
/*
* Copyright 2006-2020 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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.
*
* MZmine 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 MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.gui.chartbasics.simplechart.providers.impl.series;
import com.google.common.collect.Range;
import io.github.mzmine.datamodel.IMSRawDataFile;
import io.github.mzmine.datamodel.features.ModularFeature;
import io.github.mzmine.datamodel.features.types.numbers.MobilityRangeType;
import io.github.mzmine.datamodel.features.types.numbers.MobilityType;
import io.github.mzmine.gui.chartbasics.simplechart.providers.PlotXYZDataProvider;
import io.github.mzmine.gui.preferences.UnitFormat;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.taskcontrol.TaskStatus;
import io.github.mzmine.util.IonMobilityUtils;
import java.awt.Color;
import java.text.NumberFormat;
import java.util.List;
import java.util.Objects;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jfree.chart.renderer.PaintScale;
public class FeaturesToMobilityMzHeatmapProvider implements
PlotXYZDataProvider {
private final String seriesKey;
private final NumberFormat rtFormat;
private final NumberFormat mzFormat;
private final NumberFormat mobilityFormat;
private final NumberFormat intensityFormat;
private final UnitFormat unitFormat;
private final List<ModularFeature> features;
private double boxWidth;
private double boxHeight;
public FeaturesToMobilityMzHeatmapProvider(@Nonnull final List<ModularFeature> f) {
features = f;
seriesKey = (f.isEmpty()) ? "No features found" : f.get(0).getFeatureList().getName();
rtFormat = MZmineCore.getConfiguration().getRTFormat();
mzFormat = MZmineCore.getConfiguration().getMZFormat();
mobilityFormat = MZmineCore.getConfiguration().getMobilityFormat();
intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();
unitFormat = MZmineCore.getConfiguration().getUnitFormat();
}
@Nonnull
@Override
public Color getAWTColor() {
return Color.BLACK;
}
@Nonnull
@Override
public javafx.scene.paint.Color getFXColor() {
return javafx.scene.paint.Color.BLACK;
}
@Nullable
@Override
public String getLabel(int index) {
return null;
}
@Nullable
@Override
public PaintScale getPaintScale() {
return null;
}
@Nonnull
@Override
public Comparable<?> getSeriesKey() {
return seriesKey;
}
@Nullable
@Override
public String getToolTipText(int itemIndex) {
ModularFeature f = features.get(itemIndex);
StringBuilder sb = new StringBuilder();
sb.append("m/z:");
sb.append(mzFormat.format(f.getRawDataPointsMZRange().lowerEndpoint()));
sb.append(" - ");
sb.append(mzFormat.format(f.getRawDataPointsMZRange().upperEndpoint()));
sb.append("\n");
sb.append(unitFormat.format("Retention time", "min"));
sb.append(": ");
sb.append(rtFormat.format(f.getRawDataPointsRTRange().lowerEndpoint()));
sb.append(" - ");
sb.append(rtFormat.format(f.getRawDataPointsRTRange().upperEndpoint()));
sb.append("\n");
if (f.getRawDataFile() instanceof IMSRawDataFile) {
sb.append(((IMSRawDataFile) f.getRawDataFile()).getMobilityType().getAxisLabel());
sb.append(": ");
Range<Float> mobrange = f.get(MobilityRangeType.class).get();
sb.append(mobilityFormat.format(mobrange.lowerEndpoint()));
sb.append(" - ");
sb.append(mobilityFormat.format(mobrange.upperEndpoint()));
sb.append("\n");
}
sb.append("Height: ");
sb.append(intensityFormat.format(f.getHeight()));
sb.append("MS data file: ");
sb.append(f.getRawDataFile().getName());
return sb.toString();
}
@Override
public void computeValues(SimpleObjectProperty<TaskStatus> status) {
int numSamples = Math.min(features.size(), 100);
double width = 0d;
for (int i = 0; i < features.size(); i += (features.size() / numSamples)) {
Range<Double> mzRange = features.get(i).getRawDataPointsMZRange();
width += mzRange.upperEndpoint() - mzRange.lowerEndpoint();
}
width /= numSamples;
boxWidth = width;
if (!features.isEmpty()) {
boxHeight = IonMobilityUtils.getSmallestMobilityDelta(
((IMSRawDataFile) features.get(0).getRawDataFile()).getFrame(0)) * 3;
}
}
@Override
public double getDomainValue(int index) {
return features.get(index).getMZ();
}
@Override
public double getRangeValue(int index) {
return Objects
.requireNonNullElse(features.get(index).get(MobilityType.class),
new SimpleDoubleProperty(0))
.getValue().doubleValue();
}
@Override
public int getValueCount() {
return features.size();
}
@Override
public double getComputationFinishedPercentage() {
return 1d;
}
@Override
public double getZValue(int index) {
return features.get(index).getHeight();
}
@Nullable
@Override
public Double getBoxHeight() {
return boxHeight;
}
@Nullable
@Override
public Double getBoxWidth() {
return boxWidth;
}
@Nullable
public List<ModularFeature> getSourceFeatures() {
return features;
}
}
|
gpl-2.0
|
itsazzad/zanata-server
|
functional-test/src/main/java/org/zanata/page/projects/ProjectPeoplePage.java
|
2101
|
/*
* Copyright 2014, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This 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 software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.page.projects;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.ArrayList;
import java.util.List;
/**
* @author Damian Jansen <a href="mailto:djansen@redhat.com">djansen@redhat.com</a>
*/
@Slf4j
public class ProjectPeoplePage extends ProjectBasePage {
private By peopleList = By.id("people");
public ProjectPeoplePage(WebDriver driver) {
super(driver);
}
public List<String> getPeople() {
log.info("Query maintainers list");
List<String> names = new ArrayList<String>();
for (WebElement row : readyElement(peopleList)
.findElements(By.tagName("li"))) {
String username = row.findElement(By.tagName("a")).getText().trim();
String roles = "";
for (WebElement role : row.findElements(By.className("txt--understated"))) {
roles = roles.concat(role.getText().trim() + ";");
}
names.add(username + "|" + roles);
}
return names;
}
}
|
gpl-2.0
|
CamDevlopers/aeu
|
application/modules/manage_sub_categories/controllers/manage_sub_categories.php
|
1828
|
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Manage_sub_categories extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->model(array('m_sub_categories'));
$fckeditorConfig = array(
'instanceName' => 'items[]',
'BasePath' => base_url() . 'fckeditor/',
'ToolbarSet' => 'Basic',
'Width' => '100%',
'Height' => '500',
'Value' => ''
);
$this->load->library('fckeditor', $fckeditorConfig);
}
public function index() {
$data['cat'] = $this->m_sub_categories->get_sub_categories();
$this->load->view('manage_sub_categories', $data);
}
public function form_add_sub_categories() {
$data['cat'] = $this->m_sub_categories->get_categories();
$this->load->view('form_add_sub_categories', $data);
}
public function add_sub_categories() {
$this->m_sub_categories->add_sub_categories();
redirect('manage_sub_categories/index');
}
function delete_sub_categories() {
$id = $this->uri->segment(3);
if ($this->m_sub_categories->delete_sub_categories($id)) {
redirect('manage_sub_categories');
} else {
echo "Server not respond your request";
}
}
function form_update_sub_categories() {
$id = $this->uri->segment(3);
$data['cat'] = $this->m_sub_categories->get_categories();
$data['data'] = $this->m_sub_categories->get_sub_categories_byid($id);
$this->load->view('form_update_sub_categories', $data);
}
public function update_sub_categories() {
$this->m_sub_categories->update_sub_categories();
redirect('manage_sub_categories/index');
}
}
|
gpl-2.0
|
gnorasi/gnorasi
|
Gnorasi/modules/itk_generated/processors/itk_ImageIntensity/squareimagefilter.cpp
|
5938
|
/***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2012 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen 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. *
* *
* Voreen 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 in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#include "squareimagefilter.h"
#include "voreen/core/datastructures/volume/volumeram.h"
#include "voreen/core/datastructures/volume/volume.h"
#include "voreen/core/datastructures/volume/volumeatomic.h"
#include "voreen/core/ports/conditions/portconditionvolumetype.h"
#include "modules/itk/utils/itkwrapper.h"
#include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h"
#include "itkImage.h"
#include "itkSquareImageFilter.h"
#include <iostream>
namespace voreen {
const std::string SquareImageFilterITK::loggerCat_("voreen.SquareImageFilterITK");
SquareImageFilterITK::SquareImageFilterITK()
: ITKProcessor(),
inport1_(Port::INPORT, "InputImage"),
outport1_(Port::OUTPORT, "OutputImage"),
enableProcessing_("enabled", "Enable", false)
{
addPort(inport1_);
PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr();
orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble());
inport1_.addCondition(orCondition1);
addPort(outport1_);
addProperty(enableProcessing_);
}
Processor* SquareImageFilterITK::create() const {
return new SquareImageFilterITK();
}
template<class T>
void SquareImageFilterITK::squareImageFilterITK() {
if (!enableProcessing_.get()) {
outport1_.setData(inport1_.getData(), false);
return;
}
typedef itk::Image<T, 3> InputImageType1;
typedef itk::Image<T, 3> OutputImageType1;
typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData());
//Filter define
typedef itk::SquareImageFilter<InputImageType1, OutputImageType1> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput(p1);
observe(filter.GetPointer());
try
{
filter->Update();
}
catch (itk::ExceptionObject &e)
{
LERROR(e);
}
Volume* outputVolume1 = 0;
outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput());
if (outputVolume1) {
transferRWM(inport1_.getData(), outputVolume1);
transferTransformation(inport1_.getData(), outputVolume1);
outport1_.setData(outputVolume1);
} else
outport1_.setData(0);
}
void SquareImageFilterITK::process() {
const VolumeBase* inputHandle1 = inport1_.getData();
const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>();
if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) {
squareImageFilterITK<uint8_t>();
}
else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) {
squareImageFilterITK<int8_t>();
}
else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) {
squareImageFilterITK<uint16_t>();
}
else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) {
squareImageFilterITK<int16_t>();
}
else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) {
squareImageFilterITK<uint32_t>();
}
else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) {
squareImageFilterITK<int32_t>();
}
else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) {
squareImageFilterITK<float>();
}
else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) {
squareImageFilterITK<double>();
}
else {
LERROR("Inputformat of Volume 1 is not supported!");
}
}
} // namespace
|
gpl-2.0
|
louis20150702/mytestgit
|
Settings/src/com/sprd/settings/sim/SimInfoSetActivity.java
|
15355
|
package com.sprd.settings.sim;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.sim.Sim;
import android.sim.SimManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import com.android.settings.R;
import com.android.settings.Settings;
import com.android.settings.WirelessSettings;
import com.android.featureoption.FeatureOption;
import com.android.internal.telephony.TelephonyIntents;
import android.os.SystemProperties;
import android.util.Log;
public class SimInfoSetActivity extends PreferenceActivity implements
Preference.OnPreferenceChangeListener {
private EditTextPreference mName;
// add for SPC0132986 begin
private EditTextPreference mNumber;
// add for SPC0132986 end
private ColorPreference mColor;
private Preference mOperator;
private Context mContext;
private int mPhoneId = -1;
private Dialog colorDialog;
private int mColorIndexSelected = 0;
private int mColorIndexUsed = -1;
private static final String KEY_NAME = "name_setting";
private static final String KEY_NUMBER = "number_setting";// add for SPC0132986 begin
private static final String KEY_COLOR = "color_setting";
private static final String KEY_OPERATOR = "operator_setting";
private static final int INPUT_MAX_LENGTH = 7;
private static final int INPUT_SIM_NUMBER_MAX_LENGTH = 11;// add for SPC0132986
private int[] SIM_IMAGES_BIG = {
R.drawable.sim_color_1_big_sprd, R.drawable.sim_color_2_big_sprd,
R.drawable.sim_color_3_big_sprd, R.drawable.sim_color_4_big_sprd,
R.drawable.sim_color_5_big_sprd, R.drawable.sim_color_6_big_sprd,
R.drawable.sim_color_7_big_sprd, R.drawable.sim_color_8_big_sprd,
};
public void onCreate(Bundle savedInstanceState) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP,ActionBar.DISPLAY_HOME_AS_UP);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
super.onCreate(savedInstanceState);
mContext = this;
mPhoneId = this.getIntent().getIntExtra("phoneId", 0);
SimManager simManager = SimManager.get(mContext);
String simName = simManager.getName(mPhoneId);
Sim[] sims = simManager.getSims();
if (sims == null || sims.length == 0) {
return;
}
mColorIndexSelected = simManager.getColorIndex(mPhoneId);
for (int i = 0; i < sims.length; i++) {
if (sims[i].getPhoneId() != mPhoneId) {
mColorIndexUsed = simManager.getColorIndex(sims[i].getPhoneId());
break;
}
}
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
mName = new EditTextPreference(this);
mName.setPersistent(false);
mName.setDialogTitle(R.string.sim_name_setting_title);
mName.setKey(KEY_NAME + mPhoneId);
mName.setTitle(R.string.sim_name_setting_title);
mName.setText(simName);
mName.getEditText().setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
/* SPRD: modify for the limit of Chinese or English character and cursor position @{ */
mName.getEditText().addTextChangedListener(new TextWatcher() {
private int editStart;
private EditText mEditText = mName.getEditText();
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
editStart = mEditText.getSelectionStart();
mEditText.removeTextChangedListener(this);
while (calculateLength(s.toString()) > INPUT_MAX_LENGTH) {
s.delete(editStart - 1, editStart);
editStart--;
}
mEditText.setText(s);
mEditText.setSelection(editStart);
mEditText.addTextChangedListener(this);
Dialog dialog = mName.getDialog();
if (dialog instanceof AlertDialog) {
Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
btn.setEnabled(s.toString().trim().length() > 0);
}
}
private int calculateLength(CharSequence c) {
double len = 0;
for (int i = 0; i < c.length(); i++) {
int tmp = (int) c.charAt(i);
if (tmp > 0 && tmp < 127) {
len += 0.5;
} else {
len++;
}
}
return (int) Math.round(len);
}
});
/* @} */
mName.setOnPreferenceChangeListener(this);
root.addPreference(mName);
// add for SPC0132986 begin
if(FeatureOption.PRJ_FEATURE_SIM_SETTING_NAME) {
addPrefSimName(root);
}
// add for SPC0132986 end
if (!Settings.CU_SUPPORT || FeatureOption.PRJ_FEATURE_SIM_SETTING_NAME) {
mColor = new ColorPreference(mContext, null);
mColor.setKey(KEY_COLOR + mPhoneId);
mColor.setTitle(R.string.sim_color_setting_title);
mColor.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
pickColorDialog();
return true;
}
});
root.addPreference(mColor);
}
if (Settings.CU_SUPPORT) {
mOperator = new Preference(mContext, null, 0);
mOperator.setKey(KEY_OPERATOR + mPhoneId);
mOperator.setTitle(R.string.device_status);
mOperator.setSummary(R.string.device_status_summary);
mOperator.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent();
intent.setClassName("com.android.settings",
"com.android.settings.deviceinfo.StatusSim");
intent.putExtra(WirelessSettings.SUB_ID, mPhoneId);
SimInfoSetActivity.this.startActivity(intent);
return true;
}
});
root.addPreference(mOperator);
}
setPreferenceScreen(root);
refreshSimInfo();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == android.R.id.home) {
finish();
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
// add for SPC0132986 begin diwei add for set sim name
private void addPrefSimName(PreferenceScreen parent){
if(parent!=null){
SimManager simManager = SimManager.get(mContext);
String simNumber = simManager.getNumber(mPhoneId);
mNumber = new EditTextPreference(this);
mNumber.setPersistent(false);
mNumber.setDialogTitle(R.string.sim_number_setting_title);
mNumber.setKey(KEY_NUMBER + mPhoneId);
mNumber.setTitle(R.string.sim_number_setting_title);
mNumber.setText(simNumber);
mNumber.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
mNumber.getEditText().addTextChangedListener(new TextWatcher() {
private int editStart;
private EditText mEditText = mNumber.getEditText();
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
editStart = mEditText.getSelectionStart();
mEditText.removeTextChangedListener(this);
while (s.length() > INPUT_SIM_NUMBER_MAX_LENGTH) {
s.delete(editStart - 1, editStart);
editStart--;
}
mEditText.setText(s);
mEditText.setSelection(editStart);
mEditText.addTextChangedListener(this);
Dialog dialog = mNumber.getDialog();
if (dialog instanceof AlertDialog) {
Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
btn.setEnabled(s.toString().length() >= 0);
}
}
});
mNumber.setOnPreferenceChangeListener(this);
parent.addPreference(mNumber);
}
}
// add for SPC0132986 end
void refreshSimInfo() {
SimManager simManager = SimManager.get(mContext);
String name = simManager.getName(mPhoneId);
mName.setSummary(name);
// add for SPC0132986 begin
if(FeatureOption.PRJ_FEATURE_SIM_SETTING_NAME){
String number = simManager.getNumber(mPhoneId);
mNumber.setSummary(number);
}
// add for SPC0132986 end
if (!Settings.CU_SUPPORT || FeatureOption.PRJ_FEATURE_SIM_SETTING_NAME) {
mColor.notifyColorUpdated();
}
}
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mName) {
SimManager simManager = SimManager.get(mContext);
simManager.setName(mPhoneId, (String) newValue);
refreshSimInfo();
}
// add for SPC0132986 begin
else if(FeatureOption.PRJ_FEATURE_SIM_SETTING_NAME && preference == mNumber ){
SimManager simManager = SimManager.get(mContext);
simManager.setNumber(mPhoneId, (String) newValue);
refreshSimInfo();
}
// add for SPC0132986 end
return true;
}
void pickColorDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
LayoutInflater inflater = LayoutInflater.from(mContext);
final View colorSelectView = inflater.inflate(R.layout.sim_color_pick, null);
final GridView gridView = (GridView) colorSelectView.findViewById(R.id.color_gridview);
ColorAdapter adapter = new ColorAdapter(mColorIndexSelected);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
SimManager simManager = SimManager.get(mContext);
simManager.setColorIndex(mPhoneId, position);
mColorIndexSelected = position;
refreshSimInfo();
if(FeatureOption.PRJ_FEATURE_SIM_SETTING_NAME){
Intent intent = new Intent();
intent.setAction(TelephonyIntents.ACTION_SIM_COLOR_CHANGED);
intent.putExtra(TelephonyIntents.EXTRA_PHONE_ID, mPhoneId);
sendBroadcast(intent);
}
if (colorDialog.isShowing())
colorDialog.dismiss();
}
});
builder.setTitle(getResources().getString(R.string.sim_color_setting_title));
builder.setView(colorSelectView);
builder.setNegativeButton(getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
colorDialog = builder.create();
colorDialog.show();
}
public class ColorPreference extends Preference {
public ColorPreference(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs);
this.setLayoutResource(R.layout.sim_color_setting);
}
public ColorPreference(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
protected void onBindView(final View view) {
super.onBindView(view);
final ImageView colorImage = (ImageView) view.findViewById(R.id.sim_color);
SimManager simManager = SimManager.get(mContext);
Sim sim = simManager.getSimById(mPhoneId);
colorImage.setImageResource(SimManager.COLORS_IMAGES[sim.getColorIndex()]);
}
public void notifyColorUpdated() {
this.notifyChanged();
}
}
public class ColorAdapter extends BaseAdapter {
private int mSelected;
private int mColorItemWidth;
public ColorAdapter(int selected) {
this.mSelected = selected;
mColorItemWidth = getResources().getDimensionPixelOffset(
R.dimen.uui_sim_color_item_width);
}
public int getCount() {
return SimManager.COLORS.length;
}
public Object getItem(int position) {
return SimManager.COLORS[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
final View colorItem = inflater.inflate(R.layout.sim_color_item, null);
final ImageView imageView = (ImageView) colorItem.findViewById(R.id.color_image);
colorItem.setLayoutParams(new GridView.LayoutParams(mColorItemWidth, mColorItemWidth));
colorItem.setPadding(6, 6, 6, 6);
imageView.setImageResource(SIM_IMAGES_BIG[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
if (position == mSelected) {
colorItem.setBackgroundResource(R.drawable.sim_color_selected_sprd);
}else if (position == mColorIndexUsed) {
colorItem.setBackgroundResource(R.drawable.sim_color_used_sprd);
}
return colorItem;
}
}
}
|
gpl-2.0
|
rattrayalex/splashreader
|
src/lib/dom.js
|
4356
|
/* @flow */
import { splashreaderContainerId } from '../constants'
export function insertWrapper(): HTMLElement {
const wrapper = document.createElement('div')
wrapper.setAttribute('id', splashreaderContainerId)
document.body.appendChild(wrapper)
return wrapper
}
export function isNonSplashEditableFocused(): boolean {
const activeElement = document.activeElement
// return false if it's a child of the splash container
const splashContainer = document.getElementById(splashreaderContainerId)
if (splashContainer.contains(activeElement)) {
return false
}
return isElementEditable(activeElement)
}
function isElementEditable(elem: HTMLElement): boolean {
return (
elem.nodeName === 'INPUT'
|| elem.getAttribute('contenteditable') === 'true'
)
}
/**
* Gets the elem's distance from left edge of screen.
*/
export function getLeftEdge(elem: HTMLElement): number {
return elem.getBoundingClientRect().left + window.scrollX
}
/**
* Finds the point 1/3 of the way down the viewport.
*/
export function getReadingHeight(): number {
return (window.innerHeight * 0.32)
}
/**
* crawls up the DOM tree
* to find the nearest `display: block` element
* (including the passed-in element)
*
* @param {Element} elem
* @return {element}
*/
export function getClosestBlockElement(elem: Element): Element {
if (window.getComputedStyle(elem).display === 'block') {
return elem
}
if (!elem.parentElement) {
// if it's spans all the way up for some reason, just return the top one.
return elem
}
return getClosestBlockElement(elem.parentElement)
}
/**
* tries to detect whether the given element
* is inside a block element
* that is only a single line of text high.
* Doesn't always work.
* TODO: improve accuracy
*
* @param {Element} elem
* @return {Boolean}
*/
export function isSingleLine(elem: Element): boolean {
const elemHeight: number = elem.clientHeight
const lineHeight = parseInt(window.getComputedStyle(elem).lineHeight, 10)
// direct comparison didn't work,
// so just check if it's at least smaller than two lines tall...
return (elemHeight < (lineHeight * 2))
}
/**
* @param {Element} elem
* @return {Boolean}
*/
export function elementContainsASingleWord(elem: Element): boolean {
if (!elem.innerText) return false
return (elem.innerText.split(/\s/).length === 1)
}
/**
* tries to guess at whether an element
* is a heading...
*
* @param {Element} elem
* @return {Boolean}
*/
export function looksLikeAHeading(elemArg: Element): boolean {
const elem = getClosestBlockElement(elemArg)
if (elementContainsASingleWord(elem)) return true
return isSingleLine(elem)
}
export async function scrollToElementOnce(elem: Range | HTMLElement): Promise<void> {
// TODO: scroll w/in scrolly-divs on the page.
const elemTop = elem.getBoundingClientRect().top + window.scrollY
const offset = getReadingHeight()
const target = elemTop - offset
await scrollToOnce(document.body, target, 500)
}
/**
* Scrolls screen to an element with animation.
* @see http://stackoverflow.com/a/16136789/1048433
*/
let isAnimating = false
async function scrollToOnce(element, paddingFromTop, duration) {
if (isAnimating) return Promise.resolve()
const start = element.scrollTop
const change = paddingFromTop - start
const increment = 20
// don't bother if it's close
if (Math.abs(change) < 5) return Promise.resolve()
return await new Promise((resolve) => {
isAnimating = true
const animateScroll = (elapsedTime) => {
/* eslint-disable no-param-reassign */
elapsedTime += increment
const position = easeInOut(elapsedTime, start, change, duration)
element.scrollTop = position
if (elapsedTime < duration) {
setTimeout(animateScroll.bind(null, elapsedTime), increment)
} else {
isAnimating = false
resolve()
}
/* eslint-enable no-param-reassign */
}
animateScroll(0)
})
}
/** see http://stackoverflow.com/a/16136789/1048433 */
function easeInOut(currentTime, start, change, duration) {
/* eslint-disable */
currentTime /= (duration / 2)
if (currentTime < 1) {
return change / 2 * currentTime * currentTime + start
}
currentTime -= 1
return -change / 2 * (currentTime * (currentTime - 2) - 1) + start
/* eslint-enable */
}
|
gpl-2.0
|
52North/epos
|
epos-api/src/main/java/org/n52/epos/filter/EposFilter.java
|
1926
|
/**
* Copyright (C) 2013-2014 52ยฐNorth Initiative for Geospatial Open Source
* Software GmbH
*
* 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.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* icense version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.epos.filter;
/**
* the super-interface of all filters
* used in EPOS.
*
* @author matthes rieke
*
*/
public interface EposFilter {
/**
* @param serializer if not null, the filter shall use the
* {@link FilterSerialization#serializeFilter(EposFilter)} method
* to create the representation. Otherwise it shall return the same
* value as {@link #serialize()}
* @return create a serialized version of this pattern
*/
public CharSequence serialize(FilterSerialization serializer);
/**
* @return create a serialized version of this pattern
*/
public CharSequence serialize();
}
|
gpl-2.0
|
Delta-SH/PecsSystem
|
Site/SystemLogs.aspx.cs
|
7970
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using Ext.Net;
using Delta.PECS.WebCSC.Model;
using Delta.PECS.WebCSC.BLL;
namespace Delta.PECS.WebCSC.Site {
[DirectMethodProxyID(IDMode = DirectMethodProxyIDMode.Alias, Alias = "SystemLogs")]
public partial class SystemLogs : PageBase {
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack && !X.IsAjaxRequest) {
FromDate.Text = WebUtility.GetDateString(DateTime.Today);
ToDate.Text = WebUtility.GetDateString(DateTime.Now);
}
}
/// <summary>
/// LogLevel ComboBox Refresh
/// </summary>
protected void OnLogLevelRefresh(object sender, StoreRefreshDataEventArgs e) {
var data = new List<object>();
foreach (EnmSysLogLevel level in Enum.GetValues(typeof(EnmSysLogLevel))) {
data.Add(new {
Id = (int)level,
Name = WebUtility.GetSysLogLevelName(level)
});
}
LogLevelStore.DataSource = data;
LogLevelStore.DataBind();
}
/// <summary>
/// LogType ComboBox Refresh
/// </summary>
protected void OnLogTypeRefresh(object sender, StoreRefreshDataEventArgs e) {
var data = new List<object>();
foreach (EnmSysLogType type in Enum.GetValues(typeof(EnmSysLogType))) {
data.Add(new {
Id = (int)type,
Name = WebUtility.GetSysLogTypeName(type)
});
}
LogTypeStore.DataSource = data;
LogTypeStore.DataBind();
}
/// <summary>
/// Log Grid Refresh
/// </summary>
protected void OnLogGridRefresh(object sender, StoreRefreshDataEventArgs e) {
try {
var start = Int32.Parse(e.Parameters["start"]);
var limit = Int32.Parse(e.Parameters["limit"]);
var data = new List<object>(limit);
var rowsCnt = 0;
var fromTime = DateTime.Parse(FromDate.Text);
var toTime = DateTime.Parse(ToDate.Text);
string[] eventLevel = null;
string[] eventType = null;
if (LogLevelMultiCombo.SelectedItems.Count > 0) {
eventLevel = new string[LogLevelMultiCombo.SelectedItems.Count];
for (int i = 0; i < eventLevel.Length; i++) {
eventLevel[i] = LogLevelMultiCombo.SelectedItems[i].Value;
}
}
if (LogTypeMultiCombo.SelectedItems.Count > 0) {
eventType = new string[LogTypeMultiCombo.SelectedItems.Count];
for (int i = 0; i < eventType.Length; i++) {
eventType[i] = LogTypeMultiCombo.SelectedItems[i].Value;
}
}
var logEntity = new BLog();
var logs = logEntity.GetSysLogs(fromTime, toTime, eventLevel, eventType, null, start + 1, start + limit, ref rowsCnt);
foreach (var log in logs) {
data.Add(new {
EventID = log.EventID,
EventTime = WebUtility.GetDateString(log.EventTime),
EventLevel = WebUtility.GetSysLogLevelName(log.EventLevel),
EventType = WebUtility.GetSysLogTypeName(log.EventType),
Message = WebUtility.JsonCharFilter(log.Message),
Url = log.Url,
ClientIP = log.ClientIP,
Operator = log.Operator
});
}
e.Total = rowsCnt;
LogGridStore.DataSource = data;
LogGridStore.DataBind();
} catch (Exception err) {
WebUtility.WriteLog(EnmSysLogLevel.Error, EnmSysLogType.Exception, err.ToString(), Page.User.Identity.Name);
WebUtility.ShowMessage(EnmErrType.Error, err.Message);
}
}
/// <summary>
/// Query Button Click
/// </summary>
protected void QueryBtn_Click(object sender, DirectEventArgs e) {
}
/// <summary>
/// Save Logs
/// </summary>
protected void SaveBtn_Click(object sender, DirectEventArgs e) {
try {
var rowsCnt = 0;
var fromTime = DateTime.Parse(FromDate.Text);
var toTime = DateTime.Parse(ToDate.Text);
var _operator = UserData.Uid;
string[] eventLevel = null;
string[] eventType = null;
if (LogLevelMultiCombo.SelectedItems.Count > 0) {
eventLevel = new string[LogLevelMultiCombo.SelectedItems.Count];
for (int i = 0; i < eventLevel.Length; i++) {
eventLevel[i] = LogLevelMultiCombo.SelectedItems[i].Value;
}
}
if (LogTypeMultiCombo.SelectedItems.Count > 0) {
eventType = new string[LogTypeMultiCombo.SelectedItems.Count];
for (int i = 0; i < eventType.Length; i++) {
eventType[i] = LogTypeMultiCombo.SelectedItems[i].Value;
}
}
var logEntity = new BLog();
var logs = logEntity.GetSysLogs(fromTime, toTime, eventLevel, eventType, _operator, 1, Int32.MaxValue, ref rowsCnt);
var logText = new StringBuilder();
logText.AppendLine("ๅจๅ็ฏๅข็ๆงไธญๅฟ็ณป็ปWebๆฅๅฟ");
logText.AppendLine();
foreach (var log in logs) {
logText.AppendLine("=======================================================================================");
logText.AppendLine(String.Format("ไบไปถ็ผๅท: {0}", log.EventID));
logText.AppendLine(String.Format("ไบไปถๆถ้ด: {0}", WebUtility.GetDateString(log.EventTime)));
logText.AppendLine(String.Format("ไบไปถ็บงๅซ: {0}", WebUtility.GetSysLogLevelName(log.EventLevel)));
logText.AppendLine(String.Format("ไบไปถ็ฑปๅ: {0}", WebUtility.GetSysLogTypeName(log.EventType)));
logText.AppendLine(String.Format("่ฏทๆฑ่ทฏๅพ: {0}", log.Url));
logText.AppendLine(String.Format("ๅฎขๆท็ซฏIP: {0}", log.ClientIP));
logText.AppendLine(String.Format("่งฆๅๆบ: {0}", log.Operator));
logText.AppendLine(String.Format("ไบไปถไฟกๆฏ: {0}", WebUtility.JsonCharFilter(log.Message)));
logText.AppendLine();
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-txt";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=SysLog.txt");
var tw = HttpContext.Current.Response.Output;
tw.Write(logText.ToString());
HttpContext.Current.Response.End();
} catch (Exception err) {
WebUtility.WriteLog(EnmSysLogLevel.Error, EnmSysLogType.Exception, err.ToString(), Page.User.Identity.Name);
WebUtility.ShowMessage(EnmErrType.Error, err.Message);
}
}
}
}
|
gpl-2.0
|
JSidrach/visual-react
|
app/src/main/java/sneakycoders/visualreact/level/Level.java
|
3543
|
package sneakycoders.visualreact.level;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import sneakycoders.visualreact.R;
abstract public class Level extends Fragment {
// Basic colors
protected int successColor;
protected int failColor;
protected int successLightColor;
protected int failLightColor;
// Random number generator
private Random random;
// Callback when then player taps its area
abstract public boolean onPlayerTap();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Initialize the random number generator
random = new Random();
// Set colors
successColor = ContextCompat.getColor(getActivity(), R.color.success_primary);
failColor = ContextCompat.getColor(getActivity(), R.color.fail_primary);
successLightColor = ContextCompat.getColor(getActivity(), R.color.success_light);
failLightColor = ContextCompat.getColor(getActivity(), R.color.fail_light);
return super.onCreateView(inflater, container, savedInstanceState);
}
protected Integer getRandomColor() {
return randomColorIn(R.array.palette);
}
protected Integer getRandomDistinctiveColor() {
return randomColorIn(R.array.distinctivePalette);
}
private Integer randomColorIn(int id) {
String[] palette = getResources().getStringArray(id);
return Color.parseColor(palette[random.nextInt(palette.length)]);
}
protected Integer[] getRandomColors(int n) {
return randomColorsIn(R.array.palette, n);
}
protected Integer[] getRandomDistinctiveColors(int n) {
return randomColorsIn(R.array.distinctivePalette, n);
}
private Integer[] randomColorsIn(int id, int n) {
// Initialize lists
List<String> hexPalette = Arrays.asList(getResources().getStringArray(id));
List<Integer> palette = new ArrayList<>();
List<Integer> colors = new ArrayList<>();
// Get colors
for (String hex : hexPalette) {
palette.add(Color.parseColor(hex));
}
// Fill colors
int i = 0;
while (i != n) {
Collections.shuffle(palette);
int addN = Math.min(n - i, palette.size());
colors.addAll(palette.subList(0, addN));
i += addN;
}
return colors.toArray(new Integer[n]);
}
protected int randomInt(int idMin, int idMax) {
int min = getResources().getInteger(idMin);
int max = getResources().getInteger(idMax);
return randomInInterval(min, max);
}
protected float randomFloat(int idMin, int idMax) {
float min = getResources().getFraction(idMin, 1, 1);
float max = getResources().getFraction(idMax, 1, 1);
return randomInInterval(min, max);
}
protected boolean randomBoolean() {
return random.nextBoolean();
}
protected int randomInInterval(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
protected float randomInInterval(float min, float max) {
return (float) (min + (max - min) * random.nextDouble());
}
}
|
gpl-2.0
|
d34db33f/JDA
|
getfile.php
|
234
|
<?php
$path=$_GET["path"];
$fp = fopen($path, "rb");
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Type: application/octet-stream');
header("Content-Length: " . filesize($path));
fpassthru($fp);
|
gpl-2.0
|
cristurm/bad-bode
|
Assets/NGUI/Scripts/Interaction/UIButtonActivate.cs
|
704
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright ยฉ 2011-2012 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Very basic script that will activate or deactivate an object (and all of its children) when clicked.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button Activate")]
public class UIButtonActivate : MonoBehaviour
{
public GameObject target;
public bool state;
void Start(){
state = false;
target = GameObject.FindWithTag("TutoHand");
}
void OnMouseDrag () {
if (target != null && !state) {
NGUITools.SetActive(target, state);
state = true;
}
}
}
|
gpl-2.0
|
holmespi/15QdcZ3
|
wp-content/plugins/spider-event-calendar/front_end/bigcalendarmonth.php
|
62063
|
<?php
function big_calendar_month() {
require_once("frontend_functions.php");
global $wpdb;
$widget = ((isset($_GET['widget']) && (int) $_GET['widget']) ? (int) $_GET['widget'] : 0);
$many_sp_calendar = ((isset($_GET['many_sp_calendar']) && is_numeric(esc_html($_GET['many_sp_calendar']))) ? esc_html($_GET['many_sp_calendar']) : 1);
$calendar_id = (isset($_GET['calendar']) ? (int) $_GET['calendar'] : '');
$theme_id = (isset($_GET['theme_id']) ? (int) $_GET['theme_id'] : 13);
$date = ((isset($_GET['date']) && IsDate_inputed(esc_html($_GET['date']))) ? esc_html($_GET['date']) : '');
$view_select = (isset($_GET['select']) ? esc_html($_GET['select']) : 'month,');
$path_sp_cal = (isset($_GET['cur_page_url']) ? esc_html($_GET['cur_page_url']) : '');
$query = "SELECT * FROM " . $wpdb->prefix . "spidercalendar_calendar where id=".$calendar_id."";
$calendar = $wpdb->query($query);
///////////////////////////////////////////////////////////////////////////////////
if(isset($_GET['cat_id']))
$cat_id = $_GET['cat_id'];
else $cat_id = "";
if(isset($_GET['cat_ids']))
$cat_ids = $_GET['cat_ids'];
else $cat_ids = "";
if($cat_ids=='')
$cat_ids .= $cat_id.',';
else
$cat_ids .= ','.$cat_id.',';
$cat_ids = substr($cat_ids, 0,-1);
function getelementcountinarray($array , $element)
{
$t=0;
for($i=0; $i<count($array); $i++)
{
if($element==$array[$i])
$t++;
}
return $t;
}
function getelementindexinarray($array , $element)
{
$t='';
for($i=0; $i<count($array); $i++)
{
if($element==$array[$i])
$t.=$i.',';
}
return $t;
}
$cat_ids_array = explode(',',$cat_ids);
if($cat_id!='')
{
if(getelementcountinarray($cat_ids_array,$cat_id )%2==0)
{
$index_in_line = getelementindexinarray($cat_ids_array, $cat_id);
$index_array = explode(',' , $index_in_line);
array_pop ($index_array);
for($j=0; $j<count($index_array); $j++)
unset($cat_ids_array[$index_array[$j]]);
$cat_ids = implode(',',$cat_ids_array);
}
}
else
$cat_ids = substr($cat_ids, 0,-1);
///////////////////////////////////////////////////////////////////////////////////////////////////////
$theme = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'spidercalendar_theme WHERE id=%d', $theme_id));
$cal_width = $theme->width;
$bg_top = '#' . $theme->bg_top;
$bg_bottom = '#' . $theme->bg_bottom;
$border_color = '#' . $theme->border_color;
$text_color_year = '#' . $theme->text_color_year;
$text_color_month = '#' . $theme->text_color_month;
$color_week_days = '#' . $theme->text_color_week_days;
$text_color_other_months = '#' . $theme->text_color_other_months;
$text_color_this_month_unevented = '#' . $theme->text_color_this_month_unevented;
$evented_color = '#' . $theme->text_color_this_month_evented;
$evented_color_bg = '#' . $theme->bg_color_this_month_evented;
$color_arrow_year = '#' . $theme->arrow_color_year;
$color_arrow_month = '#' . $theme->arrow_color_month;
$sun_days = '#' . $theme->text_color_sun_days;
$event_title_color = '#' . $theme->event_title_color;
$current_day_border_color = '#' . $theme->current_day_border_color;
$cell_border_color = '#' . $theme->cell_border_color;
$cell_height = $theme->cell_height;
$popup_width = $theme->popup_width;
$popup_height = $theme->popup_height;
$number_of_shown_evetns = $theme->number_of_shown_evetns;
$sundays_font_size = $theme->sundays_font_size;
$other_days_font_size = $theme->other_days_font_size;
$weekdays_font_size = $theme->weekdays_font_size;
$border_width = $theme->border_width;
$top_height = $theme->top_height;
$bg_color_other_months = '#' . $theme->bg_color_other_months;
$sundays_bg_color = '#' . $theme->sundays_bg_color;
$weekdays_bg_color = '#' . $theme->weekdays_bg_color;
$weekstart = $theme->week_start_day;
$weekday_sunday_bg_color = '#' . $theme->weekday_sunday_bg_color;
$border_radius = $theme->border_radius;
$border_radius2 = $border_radius-$border_width;
$week_days_cell_height = $theme->week_days_cell_height;
$year_font_size = $theme->year_font_size;
$month_font_size = $theme->month_font_size;
$arrow_size = $theme->arrow_size;
$arrow_size_hover = $arrow_size + 5;
$next_month_text_color = '#' . $theme->next_month_text_color;
$prev_month_text_color = '#' . $theme->prev_month_text_color;
$next_month_arrow_color = '#' . $theme->next_month_arrow_color;
$prev_month_arrow_color = '#' . $theme->prev_month_arrow_color;
$next_month_font_size = $theme->next_month_font_size;
$prev_month_font_size = $theme->prev_month_font_size;
$month_type = $theme->month_type;
$ev_title_bg_color = '#'.$theme->ev_title_bg_color;
$date_bg_color = '#' . $theme->date_bg_color;
$event_bg_color1 = '#' . $theme->event_bg_color1;
$event_bg_color2 = '#' . $theme->event_bg_color2;
$event_num_bg_color1 = '#' . $theme->event_num_bg_color1;
$event_num_bg_color2 = '#' . $theme->event_num_bg_color2;
$event_num_color = '#' . $theme->event_num_color;
$date_font_size = $theme->date_font_size;
$event_num_font_size = $theme->event_num_font_size;
$event_table_height = $theme->event_table_height;
$date_height = $theme->date_height;
$day_month_font_size = $theme->day_month_font_size;
$week_font_size = $theme->week_font_size;
$day_month_font_color = '#' . $theme->day_month_font_color;
$week_font_color = '#' . $theme->week_font_color;
$views_tabs_bg_color = '#' . $theme->views_tabs_bg_color;
$views_tabs_text_color = '#' . $theme->views_tabs_text_color;
$views_tabs_font_size = $theme->views_tabs_font_size;
$show_numbers_for_events = $theme->day_start;
$ev_color = $theme->event_title_color;
__('January', 'sp_calendar');
__('February', 'sp_calendar');
__('March', 'sp_calendar');
__('April', 'sp_calendar');
__('May', 'sp_calendar');
__('June', 'sp_calendar');
__('July', 'sp_calendar');
__('August', 'sp_calendar');
__('September', 'sp_calendar');
__('October', 'sp_calendar');
__('November', 'sp_calendar');
__('December', 'sp_calendar');
if ($cell_height == '') {
$cell_height = 70;
}
if ($cal_width == '') {
$cal_width = 700;
}
if ($date != '') {
$date_REFERER = $date;
}
else {
$date_REFERER = date("Y-m");
$date = date("Y") . '-' . php_Month_num(date("F")) . '-' . date("d");
}
$year_REFERER = substr($date_REFERER, 0, 4);
$month_REFERER = Month_name(substr($date_REFERER, 5, 2));
$day_REFERER = substr($date_REFERER, 8, 2);
$year = substr($date, 0, 4);
$month = Month_name(substr($date, 5, 2));
$day = substr($date, 8, 2);
$cell_width = $cal_width / 7;
$cell_width = (int) $cell_width - 2;
$this_month = substr($year . '-' . add_0((Month_num($month))), 5, 2);
$prev_month = add_0((int) $this_month - 1);
$next_month = add_0((int) $this_month + 1);
$view = 'bigcalendarmonth';
$views = explode(',', $view_select);
$defaultview = 'month';
array_pop($views);
$display='';
if(count($views)==0)
{
$display="display:none";
echo '<style>
@media only screen and (max-width : 640px) {
#views_tabs_select
{
display:none !important;
}
}
</style>';
}
if(count($views)==1 and $views[0]==$defaultview)
{
$display="display:none";
echo '<style>
@media only screen and (max-width : 640px) {
#views_tabs_select
{
display:none !important;
}
}
</style>';
}
?>
<style type='text/css'>
#bigcalendar<?php echo $many_sp_calendar; ?> table{
border-collapse: inherit !important;
}
#TB_window {
z-index: 10000;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .calyear_table td {
vertical-align: middle !important;
}
#bigcalendar<?php echo $many_sp_calendar; ?> table {
border-collapse: initial;
border:0px;
max-width: none;
}
#bigcalendar<?php echo $many_sp_calendar; ?> table td {
padding: 0px;
vertical-align: none;
border-top:none;
line-height: none;
text-align: none;
}
#bigcalendar<?php echo $many_sp_calendar; ?> p, ol, ul, dl, address {
margin-bottom:0;
}
#bigcalendar<?php echo $many_sp_calendar; ?> td,
#bigcalendar<?php echo $many_sp_calendar; ?> tr,
#spiderCalendarTitlesList td,
#spiderCalendarTitlesList tr {
border:none;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .general_table {
border-radius: <?php echo $border_radius; ?>px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .top_table {
border-top-left-radius: <?php echo $border_radius2; ?>px;
border-top-right-radius: <?php echo $border_radius2; ?>px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .general_table table tr:last-child >td:first-child{
border-bottom-left-radius: <?php echo $border_radius2; ?>px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .general_table table tr:last-child >td:last-child{
border-bottom-right-radius: <?php echo $border_radius2; ?>px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_arrow a:link,
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_arrow a:visited {
text-decoration:none;
background:none;
font-size: <?php echo $arrow_size; ?>px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_arrow a:hover {
text-decoration:none;
background:none;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_day a:link,
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_day a:visited {
text-decoration:none;
background:none;
font-size:12px;
color:red;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_day a:hover {
text-decoration:none;
background:none;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .cala_day {
border:1px solid <?php echo $cell_border_color; ?> !important;
vertical-align:top;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .weekdays {
border: 1px solid <?php echo $cell_border_color; ?> !important;
vertical-align: middle;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .week_days {
font-size:<?php echo $weekdays_font_size; ?>px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .calyear_table {
border-spacing:0;
width:100%;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .calmonth_table {
border-spacing:0;
width:100%;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .calbg,
#bigcalendar<?php echo $many_sp_calendar; ?> .calbg td {
text-align:center;
width:14%;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .caltext_color_other_months {
color:<?php echo $text_color_other_months; ?>;
border:1px solid <?php echo $cell_border_color; ?> !important;
vertical-align:top;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .caltext_color_this_month_unevented {
color:<?php echo $text_color_this_month_unevented; ?>;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .calfont_year {
font-size:24px;
font-weight:bold;
color:<?php echo $text_color_year; ?>;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .calsun_days {
color:<?php echo $sun_days; ?>;
border:1px solid <?php echo $cell_border_color; ?> !important;
vertical-align:top;
text-align:left;
background-color: <?php echo $sundays_bg_color; ?>;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .views {
float: right;
background-color: <?php echo $views_tabs_bg_color; ?>;
min-height: 25px;
min-width: 70px;
margin-right: 2px;
text-align: center;
cursor:pointer;
position: relative;
top: 5px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .views span{
padding: 7px;
}
#bigcalendar<?php echo $many_sp_calendar; ?> .views_select ,
#bigcalendar<?php echo $many_sp_calendar; ?> #views_select
{
background-color: <?php echo $views_tabs_bg_color ?>;
width: 120px;
text-align: center;
cursor: pointer;
padding: 6px;
position: relative;
}
#bigcalendar<?php echo $many_sp_calendar; ?> #views_select
{
min-height: 30px;
}
#drop_down_views
{
list-style-type:none !important;
display:none;
z-index: 4545;
}
#drop_down_views >li:hover .views_select, #drop_down_views >li.active .views_select
{
background:<?php echo $bg_top ?>;
}
#drop_down_views >li
{
border-bottom:1px solid #fff !important;
}
#views_tabs_select
{
display:none;
}
#cal_event p{
color:#<?php echo $ev_color;?>
}
</style>
<div id="afterbig<?php echo $many_sp_calendar; ?>" style="<?php echo $display ?>">
<div style="width:100%;">
<table cellpadding="0" cellspacing="0" style="width:100%;">
<tr>
<td>
<div id="views_tabs" style="<?php echo $display ?>;width: 100.3%;">
<div class="views" style="<?php if (!in_array('day', $views) AND $defaultview != 'day') echo 'display:none;'; if ($view == 'bigcalendarday') echo 'background-color:' . $bg_top . ';top:0;' ?>"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_day',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))) . '-' . date('d'),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
'rand' => $many_sp_calendar,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" ><span style="color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px"><?php echo __('Day', 'sp_calendar'); ?></span>
</div>
<div class="views" style="<?php if (!in_array('week', $views) AND $defaultview != 'week') echo 'display:none;'; if ($view == 'bigcalendarweek') echo 'background-color:' . $bg_top . ';top:0;' ?>"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_week',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'months' => $prev_month . ',' . $this_month . ',' . $next_month,
'date' => $year . '-' . add_0((Month_num($month))) . '-' . date('d'),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
'rand' => $many_sp_calendar,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" ><span style="color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px"><?php echo __('Week', 'sp_calendar'); ?></span>
</div>
<div class="views" style="<?php if (!in_array('list', $views) AND $defaultview != 'list') echo 'display:none;'; if ($view == 'bigcalendarlist') echo 'background-color:' . $bg_top . ';top:0;' ?>"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_list',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
'rand' => $many_sp_calendar,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')"><span style="color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px"><?php echo __('List', 'sp_calendar'); ?></span>
</div>
<div class="views" style="<?php if (!in_array('month', $views) AND $defaultview != 'month') echo 'display:none;'; if ($view == 'bigcalendarmonth') echo 'background-color:' . $bg_top . ';top:0;'; ?>"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_month',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
'rand' => $many_sp_calendar,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" ><span style="color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px"><?php echo __('Month', 'sp_calendar'); ?></span>
</div>
</div>
<div id="views_tabs_select" style="display:none" >
<div id="views_select" style="background-color:<?php echo $bg_top?>;color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px">
<?php if($view=='bigcalendarday') echo 'Day'; ?>
<?php if($view=='bigcalendarmonth') echo 'Month'; ?>
<?php if($view=='bigcalendarweek') echo 'Week'; ?>
<?php if($view=='bigcalendarlist') echo 'List'; ?>
<span>►</span>
</div>
<ul id="drop_down_views" style="float: left;top: inherit;left: -20px;margin-top: 0px;">
<li <?php if($view=='bigcalendarday'):?> class="active" <?php endif; ?> style="<?php if(!in_array('day',$views) AND $defaultview!='day' ) echo 'display:none;' ; ?>">
<div class="views_select"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_day',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year.'-'.add_0((Month_num($month))).'-'.date('d'),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" >
<span style="position:relative;top:25%;color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px">Day</span>
</div>
</li>
<li <?php if($view=='bigcalendarweek'):?> class="active" <?php endif; ?> style="<?php if(!in_array('week',$views) AND $defaultview!='week' ) echo 'display:none;' ; ?>" ><div class="views_select"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_week',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'months' => $prev_month . ',' . $this_month . ',' . $next_month,
'date' => $year . '-' . add_0((Month_num($month))) . '-' . date('d'),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')">
<span style="position:relative;top:25%;color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px">Week</span>
</div>
</li>
<li <?php if($view=='bigcalendarlist'):?> class="active" <?php endif; ?> style="<?php if(!in_array('list',$views) AND $defaultview!='list' ) echo 'display:none;' ;?>"><div class="views_select"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_list',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" >
<span style="position:relative;top:25%;color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px">List</span>
</div>
</li>
<li <?php if($view=='bigcalendarmonth'):?> class="active" <?php endif; ?> style="<?php if(!in_array('month',$views) AND $defaultview!='month' ) echo 'display:none;'; ?>"><div class="views_select"
onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_month',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" >
<span style="position:relative;top:25%;color:<?php echo $views_tabs_text_color ?>;font-size:<?php echo $views_tabs_font_size ?>px">Month</span></div></li>
</ul>
</div>
</td>
</tr>
<tr>
<td>
<table cellpadding="0" cellspacing="0" class="general_table" style="border-spacing:0; width:100%;border:<?php echo $border_color; ?> solid <?php echo $border_width; ?>px; margin:0; padding:0;background-color:<?php echo $bg_bottom; ?>;">
<tr>
<td width="100%" style="padding:0; margin:0">
<table cellpadding="0" cellspacing="0" border="0" style="border-spacing:0; font-size:12px; margin:0; padding:0; width:100%;">
<tr style="height:40px; width:100%;">
<td class="top_table" align="center" colspan="7" style="z-index: 5;position: relative;background-image:url('<?php echo plugins_url('/images/Stver.png', __FILE__); ?>');padding:0; margin:0; background-color:<?php echo $bg_top; ?>;height:20px; background-repeat: no-repeat;background-size: 100% 100%;">
<table cellpadding="0" cellspacing="0" border="0" align="center" class="calyear_table" style="margin:0; padding:0; text-align:center; width:100%; height:<?php echo $top_height; ?>px;">
<tr>
<td width="15%">
<div onclick="javascript:showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>','<?php
echo add_query_arg(array(
'action' => 'spiderbigcalendar_' . $defaultview,
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => ($year - 1) . '-' . add_0(Month_num($month)),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" style="text-align:center; cursor:pointer; width:100%; background-color:#000000; filter:alpha(opacity=30); opacity:0.3;">
<span style="font-size:18px;color:#FFF"><?php echo $year - 1; ?></span>
</div>
</td>
<td class="cala_arrow" width="15%" style="text-align:right;margin:0px;padding:0px">
<a style="text-shadow: 1px 1px 2px black;color:<?php echo $color_arrow_month ?>;" href="javascript:showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>','<?php
if (Month_num($month) == 1) {
$needed_date = ($year - 1) . '-12';
}
else {
$needed_date = $year . '-' . add_0((Month_num($month) - 1));
}
echo add_query_arg(array(
'action' => 'spiderbigcalendar_' . $defaultview,
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $needed_date,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));
?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')">◀
</a>
</td>
<td style="text-align:center; margin:0;" width="40%">
<input type="hidden" name="month" readonly="" value="<?php echo $month; ?>"/>
<span style="line-height: 30px;font-family:arial; color:<?php echo $text_color_month; ?>; font-size:<?php echo $month_font_size; ?>px;text-shadow: 1px 1px black;"><?php echo $year . ', ' . __($month, 'sp_calendar'); ?></span>
</td>
<td style="margin:0; padding:0;text-align:left" width="15%" class="cala_arrow">
<a style="text-shadow: 1px 1px 2px black;color:<?php echo $color_arrow_month; ?>" href="javascript:showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>','<?php
if (Month_num($month) == 12) {
$needed_date = ($year + 1) . '-01';
}
else {
$needed_date = $year . '-' . add_0((Month_num($month) + 1));
}
echo add_query_arg(array(
'action' => 'spiderbigcalendar_' . $defaultview,
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $needed_date,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));
?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')">▶
</a>
</td>
<td width="15%">
<div onclick="javascript:showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>','<?php
echo add_query_arg(array(
'action' => 'spiderbigcalendar_' . $defaultview,
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => ($year + 1) . '-' . add_0(Month_num($month)),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')" style="text-align:center; cursor:pointer; width:100%; background-color:#000000; filter:alpha(opacity=30); opacity:0.3;">
<span style="font-size:18px;color:#FFF"><?php echo $year + 1; ?></span>
</div>
</td>
</tr>
</table>
</td>
</tr>
<tr align="center" height="<?php echo $week_days_cell_height; ?>" style="background-color:<?php echo $weekdays_bg_color; ?>;">
<?php if ($weekstart == "su") { ?>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days;?>; margin:0; padding:0;background-color:<?php echo $weekday_sunday_bg_color; ?>">
<div class="calbottom_border" style="text-align:center; margin:0; padding:0;"><b class="week_days"><?php echo __('Su', 'sp_calendar'); ?> </b></div>
</td>
<?php } ?>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days; ?>; margin:0; padding:0">
<div class="calbottom_border" style="text-align:center; margin:0; padding:0;"><b class="week_days"><?php echo __('Mo', 'sp_calendar'); ?> </b></div>
</td>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days; ?>; margin:0; padding:0">
<div class="calbottom_border" style="text-align:center; margin:0; padding:0;"><b class="week_days"><?php echo __('Tu', 'sp_calendar'); ?> </b></div>
</td>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days; ?>; margin:0; padding:0">
<div class="calbottom_border" style="text-align:center; margin:0; padding:0;"><b class="week_days"><?php echo __('We', 'sp_calendar'); ?> </b></div>
</td>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days; ?>; margin:0; padding:0">
<div class="calbottom_border" style="text-align:center;margin:0; padding:0;"><b class="week_days"><?php echo __('Th', 'sp_calendar'); ?> </b></div>
</td>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days; ?>; margin:0; padding:0">
<div class="calbottom_border" style="text-align:center;margin:0; padding:0;"><b class="week_days"><?php echo __('Fr', 'sp_calendar'); ?> </b></div>
</td>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days; ?>; margin:0; padding:0">
<div class="calbottom_border" style="text-align:center; margin:0; padding:0;"><b class="week_days"><?php echo __('Sa', 'sp_calendar'); ?> </b></div>
</td>
<?php if ($weekstart == "mo") { ?>
<td class="weekdays" style="width:14.2857143%; color:<?php echo $color_week_days;?>; margin:0; padding:0;background-color:<?php echo $weekday_sunday_bg_color; ?>">
<div class="calbottom_border" style="text-align:center; margin:0; padding:0;"><b class="week_days"><?php echo __('Su', 'sp_calendar'); ?> </b></div>
</td>
<?php } ?>
</tr>
<?php
$month_first_weekday = date("N", mktime(0, 0, 0, Month_num($month), 1, $year));
if ($weekstart == "su") {
$month_first_weekday++;
if ($month_first_weekday == 8) {
$month_first_weekday = 1;
}
}
$month_days = date("t", mktime(0, 0, 0, Month_num($month), 1, $year));
$last_month_days = date("t", mktime(0, 0, 0, Month_num($month) - 1, 1, $year));
$weekday_i = $month_first_weekday;
$last_month_days = $last_month_days - $weekday_i + 2;
$percent = 1;
$sum = $month_days - 8 + $month_first_weekday;
if ($sum % 7 <> 0) {
$percent = $percent + 1;
}
$sum = $sum - ($sum % 7);
$percent = $percent + ($sum / 7);
$percent = 107 / $percent;
$all_calendar_files = php_getdays($show_numbers_for_events, $calendar_id, $date, $theme_id, $widget);
$array_days = $all_calendar_files[0]['array_days'];
$array_days1 = $all_calendar_files[0]['array_days1'];
$title = $all_calendar_files[0]['title'];
$ev_ids = $all_calendar_files[0]['ev_ids'];
$categories=$wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "spidercalendar_event_category WHERE published=1");
$calendar = (isset($_GET['calendar']) ? $_GET['calendar'] : '');
echo ' <tr id="days" height="' . $cell_height . '" style="line-height:15px;">';
for ($i = 1; $i < $weekday_i; $i++) {
echo ' <td class="caltext_color_other_months" style="background-color:' . $bg_color_other_months . '">
<span style="font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family: tahoma;padding-left: 5px;">' . $last_month_days . '</span>
</td>';
$last_month_days = $last_month_days + 1;
}
///////////////////////////////////////////////////////////////////////
function category_color($event_id)
{
global $wpdb;
$calendar = (isset($_GET['calendar']) ? $_GET['calendar'] : '');
$query = $wpdb->prepare ("SELECT " . $wpdb->prefix . "spidercalendar_event_category.color AS color FROM " . $wpdb->prefix . "spidercalendar_event JOIN " . $wpdb->prefix . "spidercalendar_event_category ON " . $wpdb->prefix . "spidercalendar_event.category=" . $wpdb->prefix . "spidercalendar_event_category.id WHERE " . $wpdb->prefix . "spidercalendar_event.calendar=%d AND " . $wpdb->prefix . "spidercalendar_event.published='1' AND " . $wpdb->prefix . "spidercalendar_event_category.published='1' AND " . $wpdb->prefix . "spidercalendar_event.id=%d",$calendar,$event_id);
$colors=$wpdb->get_results($query);
if(!empty($colors))
$color=$colors[0]->color;
else $color = "";
$theme_id = (isset($_GET['theme_id']) ? (int) $_GET['theme_id'] : '');
return '#'.$color;
}
function style($title, $color)
{
$new_title = html_entity_decode(strip_tags($title));
$number = $new_title[0];
$first_letter =$new_title[1];
$ev_title = $title;
$color=str_replace('#','',$color);
$bg_color='rgba('.HEXDEC(SUBSTR($color, 0, 2)).','.HEXDEC(SUBSTR($color, 2, 2)).','.HEXDEC(SUBSTR($color, 4, 2)).',0.3'.')';
$event='<div id="cal_event" style="background-color:'.$bg_color.';border-left:2px solid #'.$color.' "><p>'.$ev_title.'</p></div>';
return $event;
}
/////////////////////////////////////////////////////////////////////////////
for ($i = 1; $i <= $month_days; $i++) {
if (isset($title[$i])) {
$ev_title = explode('</p>', $title[$i]);
array_pop($ev_title);
$k = count($ev_title);
$ev_id = explode('<br>', $ev_ids[$i]);
array_pop($ev_id);
$ev_ids_inline = implode(',', $ev_id);
}
else
$k=0;
$dayevent = '';
if (($weekday_i % 7 == 0 and $weekstart == "mo") or ($weekday_i % 7 == 1 and $weekstart == "su")) {
if ($i == $day_REFERER and $month == $month_REFERER and $year == $year_REFERER ) {
echo ' <td class="cala_day" style="padding:0; margin:0;line-height:15px;">
<div class="calborder_day" style=" margin:0; padding:0;">
<p style="font-size:' . $other_days_font_size . 'px;color:' . $evented_color . ';line-height:1.3;font-family: tahoma;padding-left: 5px;text-shadow: 1px 1px white;">' . $i . '</p>';
$r = 0;
echo ' <div style="background-color:' . $ev_title_bg_color . ';">';
for ($j = 0; $j < $k; $j++) {
if(category_color($ev_id[$j])=='#')
$cat_color=$bg_top;
else
$cat_color=category_color($ev_id[$j]);
if ($r < $number_of_shown_evetns) {
echo ' <a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="background:none;color:' . $event_title_color . ';"
href="' . add_query_arg(array(
'action' => 'spidercalendarbig',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'eventID' => $ev_id[$j],
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
'cat_id' => $cat_ids
), admin_url('admin-ajax.php')) . '"><b>' . style($ev_title[$j],$cat_color) . '</b>
</a>';
}
else {
echo '
<a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="font-size:11px; background:none; color:' . $event_title_color . '; text-align:center;"
href="' . add_query_arg(array(
'action' => 'spiderseemore',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . __('See more', 'sp_calendar') . '</b>
</a>';
break;
}
$r++;
}
echo ' </div>
</div>
</td>';
}
else
if ($i ==date( 'j' ) and $month == date('F') and $year == date('Y')) {
if(!isset($border_day)) $border_day = "";
if ($i == date('j') and $month == date('F') and $year == date('Y')) { $border_day = $current_day_border_color;}
if (in_array($i,$array_days)) {
echo ' <td class="cala_day" style="background-color:' . $ev_title_bg_color . ';padding:0; margin:0;line-height:15px; border: 3px solid ' . $current_day_border_color . ' !important">
<p style="background-color:' . $evented_color_bg . ';color:' . $evented_color . ';font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;text-shadow: 1px 1px white;">' . $i . '</p>';
$r = 0;
echo ' <div style="background-color:' . $ev_title_bg_color . '">';
for ($j = 0; $j < $k; $j++) {
if(category_color($ev_id[$j])=='#')
$cat_color=$bg_top;
else
$cat_color=category_color($ev_id[$j]);
if ($r < $number_of_shown_evetns) {
echo ' <a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="background:none;color:' . $event_title_color . ';"
href="' . add_query_arg(array(
'action' => 'spidercalendarbig',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'eventID' => $ev_id[$j],
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . style($ev_title[$j],$cat_color) . '</b>
</a>';
}
else {
echo '
<a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="font-size:11px;background:none;color:' . $event_title_color . ';text-align:center;"
href="' . add_query_arg(array(
'action' => 'spiderseemore',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . __('See more', 'sp_calendar') . '</b>
</a>';
break;
}
$r++;
}
echo ' </div>
</td>';
}
else {
echo ' <td class="calsun_days" style="padding:0; font-size:' . $sundays_font_size . 'px; margin:0;line-height:1.3;font-family:tahoma;padding-left: 5px; border: 3px solid ' . $current_day_border_color . ' !important">
<b>' . $i . '</b>
</td>';
}
}
else
if (in_array($i, $array_days)) {
echo ' <td class="cala_day" style="background-color:' . $ev_title_bg_color . ';padding:0; margin:0;line-height:15px;">
<p style="background-color:' . $evented_color_bg . ';color:' . $evented_color . ';font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;text-shadow: 1px 1px white;">' . $i . '</p>
<div style="background-color:' . $ev_title_bg_color . '">';
$r = 0;
for ($j = 0; $j < $k; $j++) {
if(category_color($ev_id[$j])=='#')
$cat_color=$bg_top;
else
$cat_color=category_color($ev_id[$j]);
if ($r < $number_of_shown_evetns) {
echo ' <a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="background:none; color:' . $event_title_color . ';"
href="' . add_query_arg(array(
'action' => 'spidercalendarbig',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'eventID' => $ev_id[$j],
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . style($ev_title[$j],$cat_color) . '</b>
</a>';
}
else {
echo '
<a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="font-size:11px; background:none; color:' . $event_title_color . ';text-align:center;"
href="' . add_query_arg(array(
'action' => 'spiderseemore',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . __('See more', 'sp_calendar') . '</b>
</a>';
break;
}
$r++;
}
echo ' </div>
</td>';
}
else {
echo ' <td class="calsun_days" style="padding:0; margin:0;line-height:1.3;font-family: tahoma;padding-left: 5px;font-size:' . $sundays_font_size . 'px">
<b>' . $i . '</b>
</td>';
}
}
else
if ($i == $day_REFERER and $month == $month_REFERER and $year == $year_REFERER) {
echo ' <td bgcolor="' . $ev_title_bg_color . '" class="cala_day" style="border: 3px solid ' . $current_day_border_color . ' !important;padding:0; margin:0;line-height:15px;">
<div class="calborder_day" style="margin:0; padding:0;">
<p style="background-color:' . $evented_color_bg . ';color:' . $evented_color . ';font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family: tahoma;padding-left: 5px;text-shadow: 1px 1px white;">' . $i . '</p>
<div style="background-color:' . $ev_title_bg_color . '">';
$r = 0;
for ($j = 0; $j < $k; $j++) {
if(category_color($ev_id[$j])=='#')
$cat_color=$bg_top;
else
$cat_color=category_color($ev_id[$j]);
if ($r < $number_of_shown_evetns) {
echo ' <a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="background:none; color:' . $event_title_color . ';"
href="' . add_query_arg(array(
'action' => 'spidercalendarbig',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'eventID' => $ev_id[$j],
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . style($ev_title[$j],$cat_color) . '</b>
</a>';
}
else {
echo '
<a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="font-size:11px; background:none; color:' . $event_title_color . ';text-align:center;"
href="' . add_query_arg(array(
'action' => 'spiderseemore',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . __('See more', 'sp_calendar') . '</b>
</a>';
break;
}
$r++;
}
echo ' </div>
</div>
</td>';
}
else {
if ($i ==date( 'j' ) and $month == date('F') and $year == date('Y')) {
if (in_array ($i,$array_days)) {
echo ' <td class="cala_day" style="background-color:' . $ev_title_bg_color . ';padding:0; margin:0;line-height:15px; border: 3px solid ' . $current_day_border_color . ' !important;">
<p style="background-color:' . $evented_color_bg . ';color:' . $evented_color . ';font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;text-shadow: 1px 1px white;">' . $i . '</p>
<div style="background-color:' . $ev_title_bg_color . '">';
$r = 0;
for ($j = 0; $j < $k; $j++) {
if(category_color($ev_id[$j])=='#')
$cat_color=$bg_top;
else
$cat_color=category_color($ev_id[$j]);
if ($r < $number_of_shown_evetns) {
echo ' <a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="background:none; color:' . $event_title_color . ';"
href="' . add_query_arg(array(
'action' => 'spidercalendarbig',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'eventID' => $ev_id[$j],
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . style($ev_title[$j],$cat_color) . '</b>
</a>';
}
else {
echo '
<a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="font-size:11px; background:none;color:' . $event_title_color . ';text-align:center;"
href="' . add_query_arg(array(
'action' => 'spiderseemore',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . __('See more', 'sp_calendar') . '</b>
</a>';
break;
}
$r++;
}
echo ' </div>
</td>';
}
else {
echo ' <td style="color:' . $text_color_this_month_unevented . ';padding:0; margin:0; line-height:15px; border: 3px solid ' . $current_day_border_color . ' !important; vertical-align:top;">
<p style="font-size:'.$other_days_font_size.'px;line-height:1.3;font-family: tahoma;padding-left: 5px;">' . $i . '</p>
</td>';
}
}
else
if (in_array($i, $array_days)) {
echo ' <td class="cala_day" style="background-color:' . $ev_title_bg_color . ';padding:0; margin:0;line-height:15px;">
<p style="background-color:' . $evented_color_bg . ';background-color:' . $evented_color_bg . ';color:' . $evented_color . ';font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;text-shadow: 1px 1px white;">' . $i . '</p>';
$r = 0;
echo ' <div>';
for ($j = 0; $j < $k; $j++) {
if(category_color($ev_id[$j])=='#')
$cat_color=$bg_top;
else
$cat_color=category_color($ev_id[$j]);
if ($r < $number_of_shown_evetns) {
echo ' <a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="background:none; color:' . $event_title_color . ';"
href="' . add_query_arg(array(
'action' => 'spidercalendarbig',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'eventID' => $ev_id[$j],
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . style($ev_title[$j],$cat_color) . '</b>
</a>';
}
else {
echo ' <p><a class="thickbox-previewbigcalendar' . $many_sp_calendar . '" style="font-size:11px; background:none; color:' . $event_title_color . ';text-align:center;"
href="' . add_query_arg(array(
'action' => 'spiderseemore',
'theme_id' => $theme_id,
'calendar_id' => $calendar_id,
'ev_ids' => $ev_ids_inline,
'date' => $year . '-' . add_0(Month_num($month)) . '-' . $i,
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'widget' => $widget,
'TB_iframe' => 1,
'tbWidth' => $popup_width,
'tbHeight' => $popup_height,
), admin_url('admin-ajax.php')) . '"><b>' . __('See more', 'sp_calendar') . '</b>
</a></p>';
break;
}
$r++;
}
echo ' </div>
</td>';
}
else {
echo ' <td style=" color:' . $text_color_this_month_unevented . ';padding:0; margin:0; line-height:15px;border: 1px solid ' . $cell_border_color . ' !important;vertical-align:top;">
<p style="font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;">' . $i . '</p>
</td>';
}
}
if ($weekday_i % 7 == 0 && $i <> $month_days) {
echo ' </tr>
<tr height="' . $cell_height . '" style="line-height:15px">';
$weekday_i = 0;
}
$weekday_i += 1;
}
$weekday_i;
$next_i = 1;
if ($weekday_i != 1) {
for ($i = $weekday_i; $i <= 7; $i++) {
if ($i != 7) {
echo ' <td class="caltext_color_other_months" style="font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;background-color:' . $bg_color_other_months . ';">' . $next_i . '</td>';
}
else {
echo ' <td class="caltext_color_other_months" style="font-size:' . $other_days_font_size . 'px;line-height:1.3;font-family:tahoma;padding-left: 5px;background-color:' . $bg_color_other_months . ';">' . $next_i . '</td>';
}
$next_i += 1;
}
}
echo ' </tr>
</table>';
?> <input type="text" value="1" name="day" style="display:none" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<script>
jQuery(document).ready(function (){
jQuery('#views_select').click(function () {
jQuery('#drop_down_views').stop(true, true).delay(200).slideDown(500);
}, function () {
jQuery('#drop_down_views').stop(true, true).slideUp(500);
});
if(jQuery(window).width() > 640 )
{
jQuery('drop_down_views').hide();
}
});
</script>
<style>
@media only screen and (max-width : 640px) {
#views_tabs ,#drop_down_views
{
display:none;
}
#views_tabs_select
{
display:block !important;
}
}
@media only screen and (max-width : 968px) {
#cats >li
{
float:none;
}
}
.categories1 , .categories2
{
display:inline-block;
}
.categories2
{
position:relative;
left: -9px;
cursor:pointer;
}
.categories2:first-letter
{
color:#fff;
}
</style>
<?php
//reindex cat_ids_array
$re_cat_ids_array = array_values($cat_ids_array);
for($i=0; $i<count($re_cat_ids_array); $i++)
{
echo'
<style>
#cats #category'.$re_cat_ids_array[$i].'
{
text-decoration:underline;
cursor:pointer;
}
</style>';
}
if($cat_ids=='')
$cat_ids='';
echo '<ul id="cats" style="list-style-type:none;">';
foreach($categories as $category)
{
?>
<li style="float:left;"><p class="categories1" style="background-color:#<?php echo $category->color;?>"> </p><p class="categories2" id="category<?php echo $category->id ?>" style="color:#<?php echo $category->color?>" onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_month',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => $category->id,
'cat_ids' => $cat_ids,
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')"> <?php echo $category->title ?></p></li>
<?php }
if (!empty($categories)) {
?>
<li style="float:left;"><p class="categories1" style="background-color:<?php echo $bg_top;?>"> </p><p class="categories2" id="category0" style="color:#<?php echo $bg_top; ?>" onclick="showbigcalendar('bigcalendar<?php echo $many_sp_calendar; ?>', '<?php echo add_query_arg(array(
'action' => 'spiderbigcalendar_month',
'theme_id' => $theme_id,
'calendar' => $calendar_id,
'select' => $view_select,
'date' => $year . '-' . add_0((Month_num($month))),
'many_sp_calendar' => $many_sp_calendar,
'cur_page_url' => $path_sp_cal,
'cat_id' => '',
'cat_ids' => '',
'widget' => $widget,
), admin_url('admin-ajax.php'));?>','<?php echo $many_sp_calendar; ?>','<?php echo $widget; ?>')"><?php echo __('All categories', 'sp_calendar'); ?></p></li>
<?php
}
echo '</ul><br><br>';
die();
}
?>
|
gpl-2.0
|
Trd-vandolph/edoo
|
wp-content/themes/edoo/index.php
|
1799
|
<?php get_header(); ?>
<section id="mainvisual">
<div class="wrap">
<?php
$page = get_page_by_path( 'changes' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</div>
<p class="balloon"><img src="<?php bloginfo( 'template_directory' ); ?>/img/balloon.png" /></p>
</section>
<section id="banner">
<div class="wrap">
<?php
$page = get_page_by_path( 'banner' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</div>
</section>
<section id="about">
<?php
$page = get_page_by_path( 'about' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<section id="vision">
<?php
$page = get_page_by_path( 'vision' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<section id="learning">
<?php
$page = get_page_by_path( 'learning' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<section id="service">
<?php
$page = get_page_by_path( 'service' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<section id="responsive">
<?php
$page = get_page_by_path( 'responsiveservice' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<section id="team">
<?php
$page = get_page_by_path( 'team' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<section id="contact">
<?php
$page = get_page_by_path( 'contact' );
if( isset( $page ) ) {
echo apply_filters( 'the_content', $page->post_content );
}
?>
</section>
<?php get_footer(); ?>
|
gpl-2.0
|
stevoland/ez_soextra
|
patch/ezoe-5.2.0/extension/ezoe/ezxmltext/handlers/input/ezoexmlinput.php
|
77032
|
<?php
//
// Created on: <06-Nov-2002 15:10:02 wy>
// Forked on: <20-Des-2007 13:02:06 ar> from eZDHTMLInput class
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Online Editor extension for eZ Publish
// SOFTWARE RELEASE: 5.0
// COPYRIGHT NOTICE: Copyright (C) 1999-2010 eZ Systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2.0 of the GNU General
// Public License 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 version 2.0 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.
//
//
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//
/*! \file ezoexmlinput.php
*/
/*!
\class eZOEXMLInput
\brief The class eZOEXMLInput does
*/
include_once( 'kernel/common/template.php' );
require_once( 'kernel/common/i18n.php' );
class eZOEXMLInput extends eZXMLInputHandler
{
/**
* Constructor
* For more info see {@link eZXMLInputHandler::eZXMLInputHandler()}
*
* @param string $xmlData
* @param string $aliasedType
* @param eZContentObjectAttribute $contentObjectAttribute
*/
function eZOEXMLInput( &$xmlData, $aliasedType, $contentObjectAttribute )
{
$this->eZXMLInputHandler( $xmlData, $aliasedType, $contentObjectAttribute );
$contentIni = eZINI::instance( 'content.ini' );
if ( $contentIni->hasVariable( 'header', 'UseStrictHeaderRule' ) === true )
{
if ( $contentIni->variable( 'header', 'UseStrictHeaderRule' ) === 'true' )
$this->IsStrictHeader = true;
}
$this->eZPublishVersion = eZPublishSDK::majorVersion() + eZPublishSDK::minorVersion() * 0.1;
$ezxmlIni = eZINI::instance( 'ezxml.ini' );
if ( $ezxmlIni->hasVariable( 'InputSettings', 'AllowMultipleSpaces' ) === true )
{
$allowMultipleSpaces = $ezxmlIni->variable( 'InputSettings', 'AllowMultipleSpaces' );
$this->allowMultipleSpaces = $allowMultipleSpaces === 'true' ? true : false;
}
if ( $ezxmlIni->hasVariable( 'InputSettings', 'AllowNumericEntities' ) )
{
$allowNumericEntities = $ezxmlIni->variable( 'InputSettings', 'AllowNumericEntities' );
$this->allowNumericEntities = $allowNumericEntities === 'true' ? true : false;
}
}
/**
* $nativeCustomTags
* List of custom tags that have a native xhtml counterpart.
* {@link eZOEInputParser::tagNameCustomHelper()} hendels
* input parsing.
*
* @static
*/
public static $nativeCustomTags = array(
'sup' => 'sup',
'sub' => 'sub'
);
/**
* List of template callable attributes
*
* @return array
*/
function attributes()
{
return array_merge( array(
'is_editor_enabled',
'can_disable',
'editor_layout_settings',
'browser_supports_dhtml_type',
'is_compatible_version',
'version',
'ezpublish_version',
'xml_tag_alias',
'json_xml_tag_alias' ),
parent::attributes() );
}
/**
* Function used by template system to call ezoe functions
*
* @param string $name
* @return mixed
*/
function attribute( $name )
{
if ( $name === 'is_editor_enabled' )
$attr = self::isEditorEnabled();
else if ( $name === 'can_disable' )
$attr = $this->currentUserHasAccess( 'disable_editor' );
else if ( $name === 'editor_layout_settings' )
$attr = $this->getEditorLayoutSettings();
else if ( $name === 'browser_supports_dhtml_type' )
$attr = self::browserSupportsDHTMLType();
else if ( $name === 'is_compatible_version' )
$attr = $this->isCompatibleVersion();
else if ( $name === 'version' )
$attr = self::version();
else if ( $name === 'ezpublish_version' )
$attr = $this->eZPublishVersion;
else if ( $name === 'xml_tag_alias' )
$attr = self::getXmlTagAliasList();
else if ( $name === 'json_xml_tag_alias' )
$attr = json_encode( self::getXmlTagAliasList() );
else
$attr = parent::attribute( $name );
return $attr;
}
/**
* browserSupportsDHTMLType
* Identify supported browser by layout engine using user agent string.
*
* @static
* @return string|false Name of supported layout engine or false
*/
public static function browserSupportsDHTMLType()
{
if ( self::$browserType === null )
{
self::$browserType = false;
$userAgent = eZSys::serverVariable( 'HTTP_USER_AGENT' );
if ( strpos( $userAgent, 'Presto' ) !== false &&
preg_match('/Presto\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
{
if ( $browserInfo[1] >= 2.1 )
self::$browserType = 'Presto';
}
else if ( strpos( $userAgent, 'Opera' ) !== false &&
preg_match('/Opera\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
{
// Presto is not part of the user agent string on Opera < 9.6
if ( $browserInfo[1] >= 9.5 )
self::$browserType = 'Presto';
}
else if ( strpos( $userAgent, 'Trident' ) !== false &&
preg_match('/Trident\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
{
if ( $browserInfo[1] >= 4.0 )
self::$browserType = 'Trident';
}
else if ( strpos( $userAgent, 'MSIE' ) !== false &&
preg_match('/MSIE[ \/]([0-9\.]+)/i', $userAgent, $browserInfo ) )
{
// IE didn't have Trident in it's user agent string untill IE 8.0
if ( $browserInfo[1] >= 6.0 )
self::$browserType = 'Trident';
}
else if ( strpos( $userAgent, 'Gecko' ) !== false &&
preg_match('/rv:([0-9\.]+)/i', $userAgent, $browserInfo ) )
{
if ( $browserInfo[1] >= 1.8 )
self::$browserType = 'Gecko';
}
else if ( strpos( $userAgent, 'WebKit' ) !== false &&
strpos( $userAgent, 'Mobile' ) === false && // Mobile webkit does not have rich text editing support
strpos( $userAgent, 'Android' ) === false &&
strpos( $userAgent, 'iPad' ) === false &&
strpos( $userAgent, 'iPhone' ) === false &&
strpos( $userAgent, 'iPod' ) === false &&
preg_match('/WebKit\/([0-9\.]+)/i', $userAgent, $browserInfo ) )
{
if ( $browserInfo[1] >= 522.0 )
self::$browserType = 'WebKit';
}
if ( self::$browserType === false )
eZDebug::writeNotice( 'Browser not supported: ' . $userAgent, __METHOD__ );
}
return self::$browserType;
}
/**
* getXmlTagAliasList
* Get and chache XmlTagNameAlias from ezoe.ini
*
* @static
* @return array
*/
public static function getXmlTagAliasList()
{
if ( self::$xmlTagAliasList === null )
{
$ezoeIni = eZINI::instance( 'ezoe.ini' );
self::$xmlTagAliasList = $ezoeIni->variable( 'EditorSettings', 'XmlTagNameAlias' );
}
return self::$xmlTagAliasList;
}
/**
* isCompatibleVersion
*
* @return bool Return true if current eZ Publish verion is supported.
*/
function isCompatibleVersion()
{
return $this->eZPublishVersion >= 4.0;
}
/**
* version
*
* @static
* @return string ezoe verion number
*/
public static function version()
{
$info = ezoeInfo::info();
$version = $info['version'];
return $version;
}
/**
* isValid
* Called by handler loading code to see if this is a valid handler.
*
* @return bool
*/
function isValid()
{
if ( !$this->currentUserHasAccess() )
{
eZDebug::writeNotice('Current user does not have access to ezoe, falling back to normal xml editor!', __METHOD__ );
return false;
}
if ( !self::browserSupportsDHTMLType() )
{
if ( $this->currentUserHasAccess( 'disable_editor' ) )
{
eZDebug::writeNotice('Current browser is not supported by ezoe, falling back to normal xml editor!', __METHOD__ );
return false;
}
eZDebug::writeWarning('Current browser is not supported by ezoe, but user does not have access to disable editor!', __METHOD__ );
}
return true;
}
/**
* customObjectAttributeHTTPAction
* Custom http actions exposed by the editor.
*
* @param eZHTTPTool $http
* @param string $action
* @param eZContentObjectAttribute $contentObjectAttribute
*/
function customObjectAttributeHTTPAction( $http, $action, $contentObjectAttribute )
{
switch ( $action )
{
case 'enable_editor':
{
self::setIsEditorEnabled( true );
} break;
case 'disable_editor':
{
if ( $this->currentUserHasAccess( 'disable_editor' ) )
self::setIsEditorEnabled( false );
else
eZDebug::writeError( 'Current user does not have access to disable editor, but trying anyway!', __METHOD__ );
} break;
default :
{
eZDebug::writeError( 'Unknown custom HTTP action: ' . $action, __METHOD__ );
} break;
}
}
/**
* editTemplateSuffix
*
* @param eZContentObjectAttribute $contentObjectAttribute
* @return string 'ezoe'
*/
function editTemplateSuffix( &$contentObjectAttribute )
{
return 'ezoe';
}
/**
* isEditorEnabled
*
* @static
* @return bool true if editor is enabled
*/
public static function isEditorEnabled()
{
$dhtmlInput = true;
$http = eZHTTPTool::instance();
if ( $http->hasSessionVariable( 'eZOEXMLInputExtension' ) )
$dhtmlInput = $http->sessionVariable( 'eZOEXMLInputExtension' );
return $dhtmlInput;
}
/**
* setIsEditorEnabled
*
* @static
* @param bool $isEnabled sets editor to enabled / disabled
*/
public static function setIsEditorEnabled( $isEnabled )
{
$http = eZHTTPTool::instance();
$http->setSessionVariable( 'eZOEXMLInputExtension', $isEnabled );
}
/**
* currentUserHasAccess
*
* @param string $view name of ezoe view to check for access on
* @return bool
*/
function currentUserHasAccess( $view = 'editor' )
{
if ( !isset( self::$userAccessHash[ $view ] ) )
{
self::$userAccessHash[ $view ] = false;
$user = eZUser::currentUser();
if ( $user instanceOf eZUser )
{
$result = $user->hasAccessTo( 'ezoe', $view );
if ( $result['accessWord'] === 'yes' )
{
self::$userAccessHash[ $view ] = true;
}
else if ( $result['accessWord'] === 'limited' )
{
foreach ( $result['policies'] as $pkey => $limitationArray )
{
foreach ( $limitationArray as $key => $valueList )
{
switch( $key )
{
case 'User_Section':
{
if ( in_array( $this->ContentObjectAttribute->attribute('object')->attribute( 'section_id' ), $valueList ) )
{
self::$userAccessHash[ $view ] = true;
break 3;
}
} break;
case 'User_Subtree':
{
$node = $this->ContentObjectAttribute->attribute('object')->attribute('main_node');
if ( !$node instanceof eZContentObjectTreeNode )
{
// get temp parent node if object don't have node assignmet yet
$tempParentNodeId = $this->ContentObjectAttribute->attribute('object_version')->attribute('main_parent_node_id');
$node = eZContentObjectTreeNode::fetch( $tempParentNodeId );
}
$path = $node->attribute( 'path_string' );
foreach ( $valueList as $subtreeString )
{
if ( strstr( $path, $subtreeString ) )
{
self::$userAccessHash[ $view ] = true;
break 4;
}
}
} break;
}
}
}
}
}
}
return self::$userAccessHash[ $view ];
}
/**
* getEditorGlobalLayoutSettings
* used by {@link eZOEXMLInput::getEditorLayoutSettings()}
*
* @static
* @return array hash with global layout settings for the editor
*/
public static function getEditorGlobalLayoutSettings()
{
if ( self::$editorGlobalLayoutSettings === null )
{
$oeini = eZINI::instance( 'ezoe.ini' );
self::$editorGlobalLayoutSettings = array(
'buttons' => $oeini->variable('EditorLayout', 'Buttons' ),
'toolbar_location' => $oeini->variable('EditorLayout', 'ToolbarLocation' ),
'path_location' => $oeini->variable('EditorLayout', 'PathLocation' ),
);
}
return self::$editorGlobalLayoutSettings;
}
/**
* getEditorLayoutSettings
* generate current layout settings depending on ini settings, current
* class attribute settings and current user access.
*
* @return array hash with layout settings for the editor
*/
function getEditorLayoutSettings()
{
if ( $this->editorLayoutSettings === null )
{
$oeini = eZINI::instance( 'ezoe.ini' );
$xmlini = eZINI::instance( 'ezxml.ini' );
// get global layout settings
$editorLayoutSettings = self::getEditorGlobalLayoutSettings();
// get custom layout features, works only in eZ Publish 4.1 and higher
$contentClassAttribute = $this->ContentObjectAttribute->attribute('contentclass_attribute');
$buttonPreset = $contentClassAttribute->attribute('data_text2');
$buttonPresets = $xmlini->hasVariable( 'TagSettings', 'TagPresets' ) ? $xmlini->variable( 'TagSettings', 'TagPresets' ) : array();
if( $buttonPreset && isset( $buttonPresets[$buttonPreset] ) )
{
if ( $oeini->hasSection( 'EditorLayout_' . $buttonPreset ) )
{
if ( $oeini->hasVariable( 'EditorLayout_' . $buttonPreset , 'Buttons' ) )
$editorLayoutSettings['buttons'] = $oeini->variable( 'EditorLayout_' . $buttonPreset , 'Buttons' );
if ( $oeini->hasVariable( 'EditorLayout_' . $buttonPreset , 'ToolbarLocation' ) )
$editorLayoutSettings['toolbar_location'] = $oeini->variable( 'EditorLayout_' . $buttonPreset , 'ToolbarLocation' );
if ( $oeini->hasVariable( 'EditorLayout_' . $buttonPreset , 'PathLocation' ) )
$editorLayoutSettings['path_location'] = $oeini->variable( 'EditorLayout_' . $buttonPreset , 'PathLocation' );
}
else
{
eZDebug::writeWarning( 'Undefined EditorLayout : EditorLayout_' . $buttonPreset, __METHOD__ );
}
}
$contentini = eZINI::instance( 'content.ini' );
$tags = $contentini->variable('CustomTagSettings', 'AvailableCustomTags' );
$hideButtons = array();
$showButtons = array();
// filter out custom tag icons if the custom tag is not enabled
if ( !in_array('underline', $tags ) )
$hideButtons[] = 'underline';
if ( !in_array('sub', $tags ) )
$hideButtons[] = 'sub';
if ( !in_array('sup', $tags ) )
$hideButtons[] = 'sup';
if ( !in_array('pagebreak', $tags ) )
$hideButtons[] = 'pagebreak';
// filter out relations buttons if user dosn't have access to relations
if ( !$this->currentUserHasAccess( 'relations' ) )
{
$hideButtons[] = 'image';
$hideButtons[] = 'object';
$hideButtons[] = 'file';
$hideButtons[] = 'media';
}
// filter out align buttons on eZ Publish 4.0.x
if ( $this->eZPublishVersion < 4.1 )
{
$hideButtons[] = 'justifyleft';
$hideButtons[] = 'justifycenter';
$hideButtons[] = 'justifyright';
$hideButtons[] = 'justifyfull';
}
foreach( $editorLayoutSettings['buttons'] as $buttonString )
{
if ( strpos( $buttonString, ',' ) !== false )
{
foreach( explode( ',', $buttonString ) as $button )
{
if ( !in_array( $button, $hideButtons ) )
$showButtons[] = trim( $button );
}
}
else if ( !in_array( $buttonString, $hideButtons ) )
$showButtons[] = trim( $buttonString );
}
$editorLayoutSettings['buttons'] = $showButtons;
$this->editorLayoutSettings = $editorLayoutSettings;
}
return $this->editorLayoutSettings;
}
/**
* updateUrlObjectLinks
* Updates URL to object links.
*
* @static
* @param eZContentObjectAttribute $contentObjectAttribute
* @param array $urlIDArray
*/
public static function updateUrlObjectLinks( $contentObjectAttribute, $urlIDArray )
{
$objectAttributeID = $contentObjectAttribute->attribute( 'id' );
$objectAttributeVersion = $contentObjectAttribute->attribute('version');
foreach( $urlIDArray as $urlID )
{
$linkObjectLink = eZURLObjectLink::fetch( $urlID, $objectAttributeID, $objectAttributeVersion );
if ( $linkObjectLink == null )
{
$linkObjectLink = eZURLObjectLink::create( $urlID, $objectAttributeID, $objectAttributeVersion );
$linkObjectLink->store();
}
}
}
/**
* validateInput
* Validates and parses input using {@link eZOEInputParser::process}
* and saves data if valid.
*
* @param eZHTTPTool $http
* @param string $base
* @param eZContentObjectAttribute $contentObjectAttribute
* @return int signals if status is valid or not
*/
function validateInput( $http, $base, $contentObjectAttribute )
{
if ( !$this->isEditorEnabled() )
{
$aliasedHandler = $this->attribute( 'aliased_handler' );
return $aliasedHandler->validateInput( $http, $base, $contentObjectAttribute );
}
if ( $http->hasPostVariable( $base . '_data_text_' . $contentObjectAttribute->attribute( 'id' ) ) )
{
$text = $http->postVariable( $base . '_data_text_' . $contentObjectAttribute->attribute( 'id' ) );
if ( self::browserSupportsDHTMLType() === 'Trident' ) // IE
{
$text = str_replace( "\t", '', $text);
}
eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext-ezoe',
$text,
__METHOD__ . ' html from client' );
$parser = new eZOEInputParser();
$document = $parser->process( $text );
// Remove last empty paragraph (added in the output part)
$parent = $document->documentElement;
$lastChild = $parent->lastChild;
while( $lastChild && $lastChild->nodeName !== 'paragraph' )
{
$parent = $lastChild;
$lastChild = $parent->lastChild;
}
if ( $lastChild && $lastChild->nodeName === 'paragraph' )
{
$textChild = $lastChild->lastChild;
// $textChild->textContent == "ย " : string(2) whitespace in Opera
if ( !$textChild ||
( $lastChild->childNodes->length == 1 &&
$textChild->nodeType == XML_TEXT_NODE &&
( $textChild->textContent == "ย " || $textChild->textContent == ' ' || $textChild->textContent == '' || $textChild->textContent == ' ' ) ) )
{
$parent->removeChild( $lastChild );
}
}
$oeini = eZINI::instance( 'ezoe.ini' );
$validationParameters = $contentObjectAttribute->validationParameters();
if ( !( isset( $validationParameters['skip-isRequired'] ) && $validationParameters['skip-isRequired'] === true )
&& $parser->getDeletedEmbedIDArray( $oeini->variable('EditorSettings', 'ValidateEmbedObjects' ) === 'enabled' ) )
{
self::$showEmbedValidationErrors = true;
$contentObjectAttribute->setValidationError( ezi18n( 'design/standard/ezoe/handler',
'Some objects used in embed(-inline) tags have been deleted and are no longer available.' ) );
return eZInputValidator::STATE_INVALID;
}
if ( $contentObjectAttribute->validateIsRequired() )
{
$root = $document->documentElement;
if ( $root->childNodes->length == 0 )
{
$contentObjectAttribute->setValidationError( ezi18n( 'kernel/classes/datatypes',
'Content required' ) );
return eZInputValidator::STATE_INVALID;
}
}
// Update URL-object links
$urlIDArray = $parser->getUrlIDArray();
if ( count( $urlIDArray ) > 0 )
{
self::updateUrlObjectLinks( $contentObjectAttribute, $urlIDArray );
}
$contentObject = $contentObjectAttribute->attribute( 'object' );
$contentObject->appendInputRelationList( $parser->getEmbeddedObjectIDArray(),
eZContentObject::RELATION_EMBED );
$contentObject->appendInputRelationList( $parser->getLinkedObjectIDArray(),
eZContentObject::RELATION_LINK );
$xmlString = eZXMLTextType::domString( $document );
eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext-ezoe',
$xmlString,
__METHOD__ . ' generated xml' );
$contentObjectAttribute->setAttribute( 'data_text', $xmlString );
$contentObjectAttribute->setValidationLog( $parser->Messages );
return eZInputValidator::STATE_ACCEPTED;
}
else
{
return eZInputValidator::STATE_ACCEPTED;
}
}
/*
Editor inner output implementation
As in code that does all the xml to xhtml transformation (for use inside the editor)
*/
// Get section level and reset curent xml node according to input header.
function §ionLevel( &$sectionLevel, $headerLevel, &$TagStack, &$currentNode, &$domDocument )
{
if ( $sectionLevel < $headerLevel )
{
if ( $this->IsStrictHeader )
{
$sectionLevel += 1;
}
else
{
if ( ( $sectionLevel + 1 ) == $headerLevel )
{
$sectionLevel += 1;
}
else
{
for ( $i = 1; $i <= ( $headerLevel - $sectionLevel - 1 ); $i++ )
{
// Add section tag
unset( $subNode );
$subNode = new DOMElemenetNode( 'section' );
$currentNode->appendChild( $subNode );
$childTag = $this->SectionArray;
$TagStack[] = array( 'TagName' => 'section',
'ParentNodeObject' => &$currentNode,
'ChildTag' => $childTag );
$currentNode = $subNode;
}
$sectionLevel = $headerLevel;
}
}
}
elseif ( $sectionLevel == $headerLevel )
{
$lastNodeArray = array_pop( $TagStack );
$lastNode = $lastNodeArray['ParentNodeObject'];
$currentNode = $lastNode;
$sectionLevel = $headerLevel;
}
else
{
for ( $i = 1; $i <= ( $sectionLevel - $headerLevel + 1 ); $i++ )
{
$lastNodeArray = array_pop( $TagStack );
$lastTag = $lastNodeArray['TagName'];
$lastNode = $lastNodeArray['ParentNodeObject'];
$lastChildTag = $lastNodeArray['ChildTag'];
$currentNode = $lastNode;
}
$sectionLevel = $headerLevel;
}
return $currentNode;
}
/*!
Returns the input XML representation of the datatype.
*/
function inputXML( )
{
$node = null;
$dom = new DOMDocument( '1.0', 'utf-8' );
$success = false;
if ( $this->XMLData )
{
$success = $dom->loadXML( $this->XMLData );
}
eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext',
$this->XMLData,
__METHOD__ . ' xml string stored in database' );
$output = '';
$browserEngineName = self::browserSupportsDHTMLType();
if ( $success )
{
$rootSectionNode = $dom->documentElement;
$output .= $this->inputSectionXML( $rootSectionNode, 0 );
}
if ( $browserEngineName === 'Trident' )
{
$output = str_replace( '<p></p>', '<p> </p>', $output );
}
else /* if ( $browserEngineName !== 'Presto' ) */
{
$output = str_replace( '<p></p>', '<p><br /></p>', $output );
}
$output = str_replace( "\n", '', $output );
if ( $output )
{
if ( $browserEngineName === 'Trident' )
{
$output .= '<p> </p>';
}
else
{
$output .= '<p><br /></p>';
}
}
eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext',
$output,
__METHOD__ . ' xml output to return' );
$output = htmlspecialchars( $output, ENT_COMPAT, 'UTF-8' );
return $output;
}
/*!
\private
\return the user input format for the given section
*/
function &inputSectionXML( &$section, $currentSectionLevel, $tdSectionLevel = null )
{
$output = '';
foreach ( $section->childNodes as $sectionNode )
{
if ( $tdSectionLevel == null )
{
$sectionLevel = $currentSectionLevel;
}
else
{
$sectionLevel = $tdSectionLevel;
}
$tagName = $sectionNode instanceof DOMNode ? $sectionNode->nodeName : '';
switch ( $tagName )
{
case 'header' :
{
$headerClassName = $sectionNode->getAttribute( 'class' );
$headerAlign = $sectionNode->getAttribute( 'align' );
$customAttributePart = self::getCustomAttrPart( $sectionNode, $styleString );
if ( $headerClassName )
{
$customAttributePart .= ' class="' . $headerClassName . '"';
}
if ( $headerAlign )
{
$customAttributePart .= ' align="' . $headerAlign . '"';
}
$tagContent = '';
// render children tags
$tagChildren = $sectionNode->childNodes;
foreach ( $tagChildren as $childTag )
{
$tagContent .= $this->inputTagXML( $childTag, $currentSectionLevel, $tdSectionLevel );
eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext',
$tagContent,
__METHOD__ . ' tag content of <header>' );
}
switch ( $sectionLevel )
{
case '2':
case '3':
case '4':
case '5':
case '6':
{
$level = $sectionLevel;
}break;
default:
{
$level = 1;
}break;
}
$archorName = $sectionNode->getAttribute( 'anchor_name' );
if ( $archorName != null )
{
$output .= "<h$level$customAttributePart$styleString><a name=\"$archorName\"" .
' class="mceItemAnchor"></a>' . $sectionNode->textContent. "</h$level>";
}
else
{
$output .= "<h$level$customAttributePart$styleString>" . $tagContent . "</h$level>";
}
}break;
case 'paragraph' :
{
if ( $tdSectionLevel == null )
{
$output .= $this->inputParagraphXML( $sectionNode, $currentSectionLevel );
}
else
{
$output .= $this->inputParagraphXML( $sectionNode,
$currentSectionLevel,
$tdSectionLevel );
}
}break;
case 'section' :
{
$sectionLevel += 1;
if ( $tdSectionLevel == null )
{
$output .= $this->inputSectionXML( $sectionNode, $sectionLevel );
}
else
{
$output .= $this->inputSectionXML( $sectionNode,
$currentSectionLevel,
$sectionLevel );
}
}break;
case '#text' :
{
//ignore whitespace
}break;
default :
{
eZDebug::writeError( "Unsupported tag at this level: $tagName", __METHOD__ );
}break;
}
}
return $output;
}
/*!
\private
\return the user input format for the given list item
*/
function &inputListXML( &$listNode, $currentSectionLevel, $listSectionLevel = null, $noParagraphs = true )
{
$output = '';
$tagName = $listNode instanceof DOMNode ? $listNode->nodeName : '';
switch ( $tagName )
{
case 'paragraph' :
{
$output .= $this->inputParagraphXML( $listNode,
$currentSectionLevel,
$listSectionLevel,
$noParagraphs );
}break;
case 'section' :
{
$listSectionLevel += 1;
$output .= $this->inputSectionXML( $listNode, $currentSectionLevel, $listSectionLevel );
}break;
case '#text' :
{
//ignore whitespace
}break;
default :
{
eZDebug::writeError( "Unsupported tag at this level: $tagName", __METHOD__ );
}break;
}
return $output;
}
/*!
\private
\return the user input format for the given table cell
*/
function &inputTdXML( &$tdNode, $currentSectionLevel, $tdSectionLevel = null )
{
$output = '';
$tagName = $tdNode instanceof DOMNode ? $tdNode->nodeName : '';
switch ( $tagName )
{
case 'paragraph' :
{
$output .= $this->inputParagraphXML( $tdNode, $currentSectionLevel, $tdSectionLevel );
}break;
case 'section' :
{
$tdSectionLevel += 1;
$output .= $this->inputSectionXML( $tdNode, $currentSectionLevel, $tdSectionLevel );
}break;
default :
{
eZDebug::writeError( "Unsupported tag at this level: $tagName", __METHOD__ );
}break;
}
return $output;
}
/*!
\return the input xml of the given paragraph
*/
function &inputParagraphXML( &$paragraph,
$currentSectionLevel,
$tdSectionLevel = null,
$noRender = false )
{
$output = '';
$children = $paragraph->childNodes;
if ( $noRender )
{
foreach ( $children as $child )
{
$output .= $this->inputTagXML( $child, $currentSectionLevel, $tdSectionLevel );
}
return $output;
}
$paragraphClassName = $paragraph->getAttribute( 'class' );
$paragraphAlign = $paragraph->getAttribute( 'align' );
$customAttributePart = self::getCustomAttrPart( $paragraph, $styleString );
if ( $paragraphAlign )
{
$customAttributePart .= ' align="' . $paragraphAlign . '"';
}
if ( $paragraphClassName )
{
$customAttributePart .= ' class="' . $paragraphClassName . '"';
}
$openPara = "<p$customAttributePart$styleString>";
$closePara = '</p>';
if ( $children->length == 0 )
{
$output = $openPara . $closePara;
return $output;
}
$lastChildInline = null;
$innerContent = '';
foreach ( $children as $child )
{
$childOutput = $this->inputTagXML( $child, $currentSectionLevel, $tdSectionLevel );
// Some tags in xhtml aren't allowed as child of paragraph
$inline = !( $child->nodeName === 'ul'
|| $child->nodeName === 'ol'
|| $child->nodeName === 'literal'
|| ( $child->nodeName === 'custom'
&& !self::customTagIsInline( $child->getAttribute( 'name' ) ) )
|| ( $child->nodeName === 'embed'
&& !self::embedTagIsCompatibilityMode()
&& !self::embedTagIsImageByNode( $child ) )
);
if ( $inline )
{
$innerContent .= $childOutput;
}
if ( ( !$inline && $lastChildInline ) ||
( $inline && !$child->nextSibling ) )
{
$output .= $openPara . $innerContent . $closePara;
$innerContent = '';
}
if ( !$inline )
{
$output .= $childOutput;
}
$lastChildInline = $inline;
}
eZDebugSetting::writeDebug( 'kernel-datatype-ezxmltext', $output, __METHOD__ . ' output' );
return $output;
}
/*!
\return the input xml for the given tag
\as in the xhtml used inside the editor
*/
function &inputTagXML( &$tag, $currentSectionLevel, $tdSectionLevel = null )
{
$output = '';
$tagName = $tag instanceof DOMNode ? $tag->nodeName : '';
$childTagText = '';
// render children tags
if ( $tag->hasChildNodes() )
{
$tagChildren = $tag->childNodes;
foreach ( $tagChildren as $childTag )
{
$childTagText .= $this->inputTagXML( $childTag, $currentSectionLevel, $tdSectionLevel );
}
}
switch ( $tagName )
{
case '#text' :
{
$tagContent = $tag->textContent;
if ( !strlen( $tagContent ) )
{
break;
}
$tagContent = htmlspecialchars( $tagContent );
$tagContent = str_replace ( '&nbsp;', ' ', $tagContent );
if ( $this->allowMultipleSpaces )
{
$tagContent = str_replace( ' ', ' ', $tagContent );
}
else
{
$tagContent = preg_replace( "/ {2,}/", ' ', $tagContent );
}
if ( $tagContent[0] === ' ' && !$tag->previousSibling )//- Fixed "first space in paragraph" issue (ezdhtml rev.12246)
{
$tagContent[0] = ';';
$tagContent = ' ' . $tagContent;
}
if ( $this->allowNumericEntities )
$tagContent = preg_replace( '/&#([0-9]+);/', '&#\1;', $tagContent );
$output .= $tagContent;
}break;
case 'embed' :
case 'embed-inline' :
{
$view = $tag->getAttribute( 'view' );
$size = $tag->getAttribute( 'size' );
$alignment = $tag->getAttribute( 'align' );
$objectID = $tag->getAttribute( 'object_id' );
$nodeID = $tag->getAttribute( 'node_id' );
$showPath = $tag->getAttribute( 'show_path' );
$htmlID = $tag->getAttributeNS( 'http://ez.no/namespaces/ezpublish3/xhtml/', 'id' );
$className = $tag->getAttribute( 'class' );
$idString = '';
$tplSuffix = '';
if ( !$size )
{
$contentIni = eZINI::instance( 'content.ini' );
$size = $contentIni->variable( 'ImageSettings', 'DefaultEmbedAlias' );
}
if ( !$view )
{
$view = $tagName;
}
$objectAttr = '';
$objectAttr .= ' alt="' . $size . '"';
$objectAttr .= ' view="' . $view . '"';
if ( $htmlID != '' )
{
$objectAttr .= ' html_id="' . $htmlID . '"';
}
if ( $showPath === 'true' )
{
$objectAttr .= ' show_path="true"';
}
if ( $tagName === 'embed-inline' )
$objectAttr .= ' inline="true"';
else
$objectAttr .= ' inline="false"';
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$object = false;
if ( is_numeric( $objectID ) )
{
$object = eZContentObject::fetch( $objectID );
$idString = 'eZObject_' . $objectID;
}
elseif ( is_numeric( $nodeID ) )
{
$node = eZContentObjectTreeNode::fetch( $nodeID );
$object = $node instanceof eZContentObjectTreeNode ? $node->object() : false;
$idString = 'eZNode_' . $nodeID;
$tplSuffix = '_node';
}
if ( $object instanceof eZContentObject )
{
$objectName = $object->attribute( 'name' );
$classIdentifier = $object->attribute( 'class_identifier' );
if ( !$object->attribute( 'can_read' ) ||
!$object->attribute( 'can_view_embed' ) )
{
$tplSuffix = '_denied';
}
else if ( $object->attribute( 'status' ) == eZContentObject::STATUS_ARCHIVED )
{
$className .= ' ezoeItemObjectInTrash';
if ( self::$showEmbedValidationErrors )
{
$oeini = eZINI::instance( 'ezoe.ini' );
if ( $oeini->variable('EditorSettings', 'ValidateEmbedObjects' ) === 'enabled' )
$className .= ' ezoeItemValidationError';
}
}
}
else
{
$objectName = 'Unknown';
$classIdentifier = false;
$tplSuffix = '_denied';
$className .= ' ezoeItemObjectDeleted';
if ( self::$showEmbedValidationErrors )
{
$className .= ' ezoeItemValidationError';
}
}
$embedContentType = self::embedTagContentType( $classIdentifier );
if ( $embedContentType === 'images' )
{
$ini = eZINI::instance();
$URL = self::getServerURL();
$objectAttributes = $object->contentObjectAttributes();
$imageDatatypeArray = $ini->variable('ImageDataTypeSettings', 'AvailableImageDataTypes');
$imageWidth = 32;
$imageHeight = 32;
foreach ( $objectAttributes as $objectAttribute )
{
$classAttribute = $objectAttribute->contentClassAttribute();
$dataTypeString = $classAttribute->attribute( 'data_type_string' );
if ( in_array ( $dataTypeString, $imageDatatypeArray ) && $objectAttribute->hasContent() )
{
$content = $objectAttribute->content();
if ( $content == null )
continue;
if ( $content->hasAttribute( $size ) )
{
$imageAlias = $content->imageAlias( $size );
$srcString = $URL . '/' . $imageAlias['url'];
$imageWidth = $imageAlias['width'];
$imageHeight = $imageAlias['height'];
break;
}
else
{
eZDebug::writeError( "Image alias does not exist: $size, missing from image.ini?",
__METHOD__ );
}
}
}
if ( !isset( $srcString ) )
{
$srcString = self::getDesignFile('images/tango/mail-attachment32.png');
}
if ( $alignment === 'center' )
$objectAttr .= ' align="middle"';
else if ( $alignment )
$objectAttr .= ' align="' . $alignment . '"';
if ( $className != '' )
$objectAttr .= ' class="' . $className . '"';
$output .= '<img id="' . $idString . '" title="' . $objectName . '" src="' .
$srcString . '" width="' . $imageWidth . '" height="' . $imageHeight .
'" ' . $objectAttr . $customAttributePart . $styleString . ' />';
}
else if ( self::embedTagIsCompatibilityMode() )
{
$srcString = self::getDesignFile('images/tango/mail-attachment32.png');
if ( $alignment === 'center' )
$objectAttr .= ' align="middle"';
else if ( $alignment )
$objectAttr .= ' align="' . $alignment . '"';
if ( $className != '' )
$objectAttr .= ' class="' . $className . '"';
$output .= '<img id="' . $idString . '" title="' . $objectName . '" src="' .
$srcString . '" width="32" height="32" ' . $objectAttr .
$customAttributePart . $styleString . ' />';
}
else
{
if ( $alignment )
$objectAttr .= ' align="' . $alignment . '"';
if ( $className )
$objectAttr .= ' class="ezoeItemNonEditable ' . $className . ' ezoeItemContentType' .
ucfirst( $embedContentType ) . '"';
else
$objectAttr .= ' class="ezoeItemNonEditable ezoeItemContentType' .
ucfirst( $embedContentType ) . '"';
if ( $tagName === 'embed-inline' )
$htmlTagName = 'span';
else
$htmlTagName = 'div';
$objectParam = array( 'size' => $size, 'align' => $alignment, 'show_path' => $showPath );
if ( $htmlID ) $objectParam['id'] = $htmlID;
$res = eZTemplateDesignResource::instance();
$res->setKeys( array( array('classification', $className) ) );
// stevo
foreach ( $tag->attributes as $attribute )
{
if ( $attribute->namespaceURI == 'http://ez.no/namespaces/ezpublish3/custom/' )
{
$objectParam[$attribute->name] = $attribute->value;
}
}
if ( isset( $node ) )
{
$templateOutput = self::fetchTemplate( 'design:content/datatype/view/ezxmltags/' . $tagName . $tplSuffix . '.tpl', array(
'view' => $view,
'object' => $object,
'link_parameters' => array(),
'classification' => $className,
'object_parameters' => $objectParam,
'node' => $node,
'in_oe' => true,
));
}
else
{
$templateOutput = self::fetchTemplate( 'design:content/datatype/view/ezxmltags/' . $tagName . $tplSuffix . '.tpl', array(
'view' => $view,
'object' => $object,
'link_parameters' => array(),
'classification' => $className,
'object_parameters' => $objectParam,
'in_oe' => true,
));
}
$output .= '<' . $htmlTagName . ' id="' . $idString . '" title="' . $objectName . '"' .
$objectAttr . $customAttributePart . $styleString . '>' . $templateOutput .
'</' . $htmlTagName . '>';
}
}break;
case 'custom' :
{
$name = $tag->getAttribute( 'name' );
$align = $tag->getAttribute( 'align' );
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$inline = self::customTagIsInline( $name );
if ( $align )
{
$customAttributePart .= ' align="' . $align . '"';
}
if ( isset( self::$nativeCustomTags[ $name ] ))
{
if ( !$childTagText ) $childTagText = ' ';
$output .= '<' . self::$nativeCustomTags[ $name ] . $customAttributePart . $styleString .
'>' . $childTagText . '</' . self::$nativeCustomTags[ $name ] . '>';
}
else if ( $inline === true )
{
if ( !$childTagText ) $childTagText = ' ';
$output .= '<span class="ezoeItemCustomTag ' . $name . '" type="custom"' .
$customAttributePart . $styleString . '>' . $childTagText . '</span>';
}
else if ( $inline )
{
$imageUrl = self::getCustomAttrbute( $tag, 'image_url' );
if ( $imageUrl === null || !$imageUrl )
{
$imageUrl = self::getDesignFile( $inline );
$customAttributePart .= ' width="22" height="22"';
}
$output .= '<img src="' . $imageUrl . '" class="ezoeItemCustomTag ' . $name .
'" type="custom"' . $customAttributePart . $styleString . ' />';
}
else
{
$customTagContent = $this->inputSectionXML( $tag, $currentSectionLevel, $tdSectionLevel );
/*foreach ( $tag->childNodes as $tagChild )
{
$customTagContent .= $this->inputTdXML( $tagChild,
$currentSectionLevel,
$tdSectionLevel );
}*/
$output .= '<div class="ezoeItemCustomTag ' . $name . '" type="custom"' .
$customAttributePart . $styleString . '>' . $customTagContent . '</div>';
}
}break;
case 'literal' :
{
$literalText = '';
foreach ( $tagChildren as $childTag )
{
$literalText .= $childTag->textContent;
}
$className = $tag->getAttribute( 'class' );
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$literalText = htmlspecialchars( $literalText );
$literalText = str_replace( "\n", '<br />', $literalText );
if ( $className != '' )
$customAttributePart .= ' class="' . $className . '"';
$output .= '<pre' . $customAttributePart . $styleString . '>' . $literalText . '</pre>';
}break;
case 'ul' :
case 'ol' :
{
$listContent = '';
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
// find all list elements
foreach ( $tag->childNodes as $listItemNode )
{
if ( !$listItemNode instanceof DOMElement )
{
continue;// ignore whitespace
}
$LIcustomAttributePart = self::getCustomAttrPart( $listItemNode, $listItemStyleString );
$noParagraphs = self::childTagCount( $listItemNode ) <= 1;
$listItemContent = '';
foreach ( $listItemNode->childNodes as $itemChildNode )
{
$listSectionLevel = $currentSectionLevel;
if ( $itemChildNode instanceof DOMNode
&& ( $itemChildNode->nodeName === 'section'
|| $itemChildNode->nodeName === 'paragraph' ) )
{
$listItemContent .= $this->inputListXML( $itemChildNode,
$currentSectionLevel,
$listSectionLevel,
$noParagraphs );
}
else
{
$listItemContent .= $this->inputTagXML( $itemChildNode,
$currentSectionLevel,
$tdSectionLevel );
}
}
$LIclassName = $listItemNode->getAttribute( 'class' );
if ( $LIclassName )
$LIcustomAttributePart .= ' class="' . $LIclassName . '"';
$listContent .= '<li' . $LIcustomAttributePart . $listItemStyleString . '>' .
$listItemContent . '</li>';
}
$className = $tag->getAttribute( 'class' );
if ( $className != '' )
$customAttributePart .= ' class="' . $className . '"';
$output .= '<' . $tagName . $customAttributePart . $styleString . '>' . $listContent . '</' .
$tagName . '>';
}break;
case 'table' :
{
$tableRows = '';
$border = $tag->getAttribute( 'border' );
$width = $tag->getAttribute( 'width' );
$align = $tag->getAttribute( 'align' );
$tableClassName = $tag->getAttribute( 'class' );
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
// find all table rows
foreach ( $tag->childNodes as $tableRow )
{
if ( !$tableRow instanceof DOMElement )
{
continue; // ignore whitespace
}
$TRcustomAttributePart = self::getCustomAttrPart( $tableRow, $tableRowStyleString );
$TRclassName = $tableRow->getAttribute( 'class' );
$tableData = '';
foreach ( $tableRow->childNodes as $tableCell )
{
if ( !$tableCell instanceof DOMElement )
{
continue; // ignore whitespace
}
$TDcustomAttributePart = self::getCustomAttrPart( $tableCell, $tableCellStyleString );
$className = $tableCell->getAttribute( 'class' );
$cellAlign = $tableCell->getAttribute( 'align' );
$colspan = $tableCell->getAttributeNS( 'http://ez.no/namespaces/ezpublish3/xhtml/',
'colspan' );
$rowspan = $tableCell->getAttributeNS( 'http://ez.no/namespaces/ezpublish3/xhtml/',
'rowspan' );
$cellWidth = $tableCell->getAttributeNS( 'http://ez.no/namespaces/ezpublish3/xhtml/',
'width' );
if ( $className != '' )
{
$TDcustomAttributePart .= ' class="' . $className . '"';
}
if ( $cellWidth != '' )
{
$TDcustomAttributePart .= ' width="' . $cellWidth . '"';
}
if ( $colspan && $colspan !== '1' )
{
$TDcustomAttributePart .= ' colspan="' . $colspan . '"';
}
if ( $rowspan && $rowspan !== '1' )
{
$TDcustomAttributePart .= ' rowspan="' . $rowspan . '"';
}
if ( $cellAlign )
{
$TDcustomAttributePart .= ' align="' . $cellAlign . '"';
}
$cellContent = '';
$tdSectionLevel = $currentSectionLevel;
foreach ( $tableCell->childNodes as $tableCellChildNode )
{
$cellContent .= $this->inputTdXML( $tableCellChildNode,
$currentSectionLevel,
$tdSectionLevel - $currentSectionLevel );
}
if ( $cellContent === '' )
{
// tinymce has some issues with empty content in some browsers
$cellContent = '<br mce_bogus="1" />';
}
if ( $tableCell->nodeName === 'th' )
{
$tableData .= '<th' . $TDcustomAttributePart . $tableCellStyleString . '>' .
$cellContent . '</th>';
}
else
{
$tableData .= '<td' . $TDcustomAttributePart . $tableCellStyleString . '>' .
$cellContent . '</td>';
}
}
if ( $TRclassName )
$TRcustomAttributePart .= ' class="' . $TRclassName . '"';
$tableRows .= '<tr' . $TRcustomAttributePart . $tableRowStyleString . '>' .
$tableData . '</tr>';
}
//if ( self::browserSupportsDHTMLType() === 'Trident' )
//{
$customAttributePart .= ' width="' . $width . '"';
/*}
else
{
// if this is reenabled merge it with $styleString
$customAttributePart .= ' style="width:' . $width . ';"';
}*/
if ( is_string( $border ) )
{
$customAttributePart .= ' border="' . $border . '"';
}
if ( $align )
{
$customAttributePart .= ' align="' . $align . '"';
}
if ( $tableClassName )
{
$customAttributePart .= ' class="' . $tableClassName . '"';
}
$output .= '<table' . $customAttributePart . $styleString . '><tbody>' . $tableRows .
'</tbody></table>';
}break;
// normal content tags
case 'emphasize' :
{
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$className = $tag->getAttribute( 'class' );
if ( $className )
{
$customAttributePart .= ' class="' . $className . '"';
}
$output .= '<em' . $customAttributePart . $styleString . '>' . $childTagText . '</em>';
}break;
case 'strong' :
{
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$className = $tag->getAttribute( 'class' );
if ( $className )
{
$customAttributePart .= ' class="' . $className . '"';
}
$output .= '<strong' . $customAttributePart . $styleString . '>' . $childTagText . '</strong>';
}break;
case 'line' :
{
$output .= $childTagText . '<br />';
}break;
case 'anchor' :
{
$name = $tag->getAttribute( 'name' );
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$output .= '<a id="' . $name . '" class="mceItemAnchor"' . $customAttributePart .
$styleString . '></a>';
}break;
case 'link' :
{
$customAttributePart = self::getCustomAttrPart( $tag, $styleString );
$linkID = $tag->getAttribute( 'url_id' );
$target = $tag->getAttribute( 'target' );
$className = $tag->getAttribute( 'class' );
$viewName = $tag->getAttribute( 'view' );
$objectID = $tag->getAttribute( 'object_id' );
$nodeID = $tag->getAttribute( 'node_id' );
$anchorName = $tag->getAttribute( 'anchor_name' );
$showPath = $tag->getAttribute( 'show_path' );
$htmlID = $tag->getAttributeNS( 'http://ez.no/namespaces/ezpublish3/xhtml/', 'id' );
$htmlTitle = $tag->getAttributeNS( 'http://ez.no/namespaces/ezpublish3/xhtml/', 'title' );
$attributes = array();
if ( $objectID != null )
{
$href = 'ezobject://' .$objectID;
}
elseif ( $nodeID != null )
{
if ( $showPath === 'true' )
{
$node = eZContentObjectTreeNode::fetch( $nodeID );
$href = $node ?
'eznode://' . $node->attribute('path_identification_string') :
'eznode://' . $nodeID;
}
else
{
$href = 'eznode://' . $nodeID;
}
}
elseif ( $linkID != null )
{
$href = eZURL::url( $linkID );
}
else
{
$href = $tag->getAttribute( 'href' );
}
if ( $anchorName != null )
{
$href .= '#' . $anchorName;
}
if ( $className != '' )
{
$attributes[] = 'class="' . $className . '"';
}
if ( $viewName != '' )
{
$attributes[] = 'view="' . $viewName . '"';
}
$attributes[] = 'href="' . $href . '"';
// Also set mce_href for use by OE to make sure href attribute is not messed up by IE 6 / 7
$attributes[] = 'mce_href="' . $href . '"';
if ( $target != '' )
{
$attributes[] = 'target="' . $target . '"';
}
if ( $htmlTitle != '' )
{
$attributes[] = 'title="' . $htmlTitle . '"';
}
if ( $htmlID != '' )
{
$attributes[] = 'id="' . $htmlID . '"';
}
$attributeText = '';
if ( count( $attributes ) > 0 )
{
$attributeText = ' ' .implode( ' ', $attributes );
}
$output .= '<a' . $attributeText . $customAttributePart . $styleString . '>' .
$childTagText . '</a>';
}break;
case 'tr' :
case 'td' :
case 'th' :
case 'li' :
case 'paragraph' :
{
}break;
default :
{
}break;
}
return $output;
}
/*
* Generates custom attribute value, and also sets tag styles to styleString variable (by ref)
*/
public static function getCustomAttrPart( $tag, &$styleString )
{
$customAttributePart = '';
$styleString = '';
if ( self::$customAttributeStyleMap === null )
{
// Filtered styles because the browser (ie,ff&opera) convert span tag to
// font tag in certain circumstances
$oeini = eZINI::instance( 'ezoe.ini' );
$styles = $oeini->variable('EditorSettings', 'CustomAttributeStyleMap' );
$customAttributeStyleMap = array();
foreach( $styles as $name => $style )
{
// stevo
if ( preg_match("/(margin|border|padding|width|height|color|font-size|line-height)/", $style ) )
{
self::$customAttributeStyleMap[$name] = $style;
}
else
{
eZDebug::writeWarning( "Style not valid: $style, see ezoe.ini[EditorSettings]CustomAttributeStyleMap",
__METHOD__ );
}
}
}
// generate custom attribute value
foreach ( $tag->attributes as $attribute )
{
if ( $attribute->namespaceURI == 'http://ez.no/namespaces/ezpublish3/custom/' )
{
if ( $customAttributePart === '' )
{
$customAttributePart = ' customattributes="';
$customAttributePart .= $attribute->name . '|' . $attribute->value;
}
else
{
$customAttributePart .= 'attribute_separation' . $attribute->name . '|' .
$attribute->value;
}
if ( isset( self::$customAttributeStyleMap[$attribute->name] ) )
{
$styleString .= self::$customAttributeStyleMap[$attribute->name] . ': ' .
$attribute->value . '; ';
}
}
}
if ( $customAttributePart !== '' )
{
$customAttributePart .= '"';
}
if ( $styleString !== '' )
{
$styleString = ' style="' . $styleString . '"';
}
return $customAttributePart;
}
/*
* Get custom attribute value
*/
public static function getCustomAttrbute( $tag, $attributeName )
{
foreach ( $tag->attributes as $attribute )
{
if ( $attribute->name === $attributeName
&& $attribute->namespaceURI === 'http://ez.no/namespaces/ezpublish3/custom/' )
{
return $attribute->value;
}
}
return null;
}
/*
* Get server url in relative or absolute format depending on ezoe settings.
*/
public static function getServerURL()
{
if ( self::$serverURL === null )
{
$oeini = eZINI::instance( 'ezoe.ini' );
if ( $oeini->hasVariable( 'SystemSettings', 'RelativeURL' ) &&
$oeini->variable( 'SystemSettings', 'RelativeURL' ) === 'enabled' )
{
self::$serverURL = eZSys::wwwDir();
if ( self::$serverURL === '/' )
self::$serverURL = '';
}
else
{
$domain = eZSys::hostname();
$protocol = 'http';
// Default to https if SSL is enabled
// Check if SSL port is defined in site.ini
$sslPort = 443;
$ini = eZINI::instance();
if ( $ini->hasVariable( 'SiteSettings', 'SSLPort' ) )
$sslPort = $ini->variable( 'SiteSettings', 'SSLPort' );
if ( eZSys::serverPort() == $sslPort )
$protocol = 'https';
self::$serverURL = $protocol . '://' . $domain . eZSys::wwwDir();
}
}
return self::$serverURL;
}
/*
* Get design file (template) for use in embed tags
*/
public static function getDesignFile( $file, $triedFiles = array() )
{
if ( self::$designBases === null )
{
self::$designBases = eZTemplateDesignResource::allDesignBases();
}
$match = eZTemplateDesignResource::fileMatch( self::$designBases, '', $file, $triedFiles );
if ( $match === false )
{
eZDebug::writeWarning( "Could not find: $file", __METHOD__ );
return $file;
}
return htmlspecialchars( self::getServerURL() . '/' . $match['path'] );
}
/**
* Figgure out if a custom tag is inline or not based on content.ini settings
*
* @param string $name Tag name
* @return bool|string Return 'image' if tag is inline image, otherwise true/false.
*/
public static function customTagIsInline( $name )
{
if ( self::$customInlineTagList === null )
{
$ini = eZINI::instance( 'content.ini' );
self::$customInlineTagList = $ini->variable( 'CustomTagSettings', 'IsInline' );
self::$customInlineIconPath = $ini->hasVariable( 'CustomTagSettings', 'InlineImageIconPath' ) ?
$ini->variable( 'CustomTagSettings', 'InlineImageIconPath' ) :
array();
}
if ( isset( self::$customInlineTagList[ $name ] ) )
{
if ( self::$customInlineTagList[ $name ] === 'true' )
{
return true;
}
else if ( self::$customInlineTagList[ $name ] === 'image' )
{
if ( isset( self::$customInlineIconPath[ $name ] ) )
return self::$customInlineIconPath[ $name ];
else
return 'images/tango/image-x-generic22.png';
}
}
return false;
}
/*
* Find out if embed object is image type or not.
*/
public static function embedTagIsImageByNode( $node )
{
$objectID = $node->getAttribute( 'object_id' );
$nodeID = $node->getAttribute( 'node_id' );
$object = false;
$classIdentifier = false;
if ( is_numeric( $objectID ) )
{
$object = eZContentObject::fetch( $objectID );
}
elseif ( is_numeric( $nodeID ) )
{
$node = eZContentObjectTreeNode::fetch( $nodeID );
if ( is_object($node) ) {
$object = $node->object();
}
}
if ( $object instanceof eZContentObject )
{
$classIdentifier = $object->attribute( 'class_identifier' );
}
return $classIdentifier && self::embedTagContentType( $classIdentifier ) === 'images';
}
/*
* Get content type by class identifier
*/
public static function embedTagContentType( $classIdentifier )
{
$contentIni = eZINI::instance('content.ini');
foreach ( $contentIni->variable( 'RelationGroupSettings', 'Groups' ) as $group )
{
$settingName = ucfirst( $group ) . 'ClassList';
if ( $contentIni->hasVariable( 'RelationGroupSettings', $settingName ) )
{
if ( in_array( $classIdentifier, $contentIni->variable( 'RelationGroupSettings', $settingName ) ) )
return $group;
}
else
eZDebug::writeDebug( "Missing content.ini[RelationGroupSettings]$settingName setting.",
__METHOD__ );
}
return $contentIni->variable( 'RelationGroupSettings', 'DefaultGroup' );
}
/*
* Return if embed tags should be displayed in compatibility mode, as in like the old editor using attachment icons.
*/
public static function embedTagIsCompatibilityMode()
{
if ( self::$embedIsCompatibilityMode === null )
{
$ezoeIni = eZINI::instance('ezoe.ini');
self::$embedIsCompatibilityMode = $ezoeIni->variable('EditorSettings', 'CompatibilityMode' ) === 'enabled';
}
return self::$embedIsCompatibilityMode;
}
/* Count child elements, ignoring whitespace and text
*
* @param DOMElement $parent
* @return int
*/
protected static function childTagCount( DOMElement $parent )
{
$count = 0;
foreach( $parent->childNodes as $child )
{
if ( $child instanceof DOMElement ) $count++;
}
return $count;
}
/* Execute template cleanly, make sure we don't override parameters
* and back them up for setting them back when done.
*
* @param string $template
* @param array $parameters Hash with name and value
* @return string
*/
protected static function fetchTemplate( $template, $parameters = array() )
{
$tpl = templateInit();
$existingPramas = array();
foreach( $parameters as $name => $value )
{
if ( $tpl->hasVariable( $name ) )
$existingPramas[$name] = $tpl->variable( $name );
$tpl->setVariable( $name, $value );
}
$result = $tpl->fetch( $template );
foreach( $parameters as $name => $value )
{
if ( isset( $existingPramas[$name] ) )
$tpl->setVariable( $name, $existingPramas[$name] );
else
$tpl->unsetVariable( $name );
}
return $result;
}
protected static $serverURL = null;
protected static $browserType = null;
protected static $designBases = null;
protected static $userAccessHash = array();
protected static $customInlineTagList = null;
protected static $customInlineIconPath = null;
protected static $customAttributeStyleMap = null;
protected static $embedIsCompatibilityMode = null;
protected static $xmlTagAliasList = null;
protected $editorLayoutSettings = null;
protected static $editorGlobalLayoutSettings = null;
protected static $showEmbedValidationErrors = null;
public $LineTagArray = array( 'emphasize', 'strong', 'link', 'a', 'em', 'i', 'b', 'bold', 'anchor' );
/// Contains the XML data
public $XMLData;
public $IsStrictHeader = false;
public $SectionArray = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'section' );
public $eZPublishVersion;
public $allowMultipleSpaces = true;
protected $allowNumericEntities = false;
}
?>
|
gpl-2.0
|
NatLibFi/NDL-VuFind2
|
module/Finna/src/Finna/Controller/Plugin/Captcha.php
|
5668
|
<?php
/**
* VuFind Captcha controller plugin
*
* PHP version 7
*
* Copyright (C) The National Library of Finland 2017-2018.
*
* 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
*
* @category VuFind
* @package Plugin
* @author Joni Nevalainen <joni.nevalainen@gofore.com>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
namespace Finna\Controller\Plugin;
use Laminas\I18n\Translator\TranslatorInterface;
use Laminas\Session\SessionManager;
/**
* Captcha controller plugin.
*
* @category VuFind
* @package Plugin
* @author Joni Nevalainen <joni.nevalainen@gofore.com>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/
*/
class Captcha extends \VuFind\Controller\Plugin\Captcha
{
/**
* Bypassed authentication methods
*
* @var array
*/
protected $bypassCaptcha = [];
/**
* Authentication manager
*
* @var ServiceManager
*/
protected $authManager;
/**
* Session manager
*
* @var SessionManager
*/
protected $sessionManager;
/**
* Minimum interval between consecutive actions (seconds)
*
* @var int
*/
protected $actionInterval;
/**
* Translator
*
* @var TranslatorInterface
*/
protected $translator;
/**
* Constructor
*
* @param \VuFind\Config $config Config file
* @param array $captchas CAPTCHA objects
* @param \VuFind\Auth\Manager $authManager Authentication Manager
* @param SessionManager $sessionManager Session Manager
* @param TranslatorInterface $translator Translator
*
* @return void
*/
public function __construct(
$config,
array $captchas=[],
\VuFind\Auth\Manager $authManager = null,
SessionManager $sessionManager = null,
TranslatorInterface $translator = null
) {
parent::__construct($config, $captchas);
$this->authManager = $authManager;
$this->sessionManager = $sessionManager;
$this->translator = $translator;
$this->actionInterval = !empty($config->Captcha->actionInterval)
? $config->Captcha->actionInterval : 60;
if (!empty($config->Captcha->bypassCaptcha)) {
$trimLowercase = function ($str) {
return strtolower(trim($str));
};
$bypassCaptcha = $config->Captcha->bypassCaptcha->toArray();
foreach ($bypassCaptcha as $domain => $authMethods) {
$this->bypassCaptcha[$domain] = array_map(
$trimLowercase,
explode(',', $authMethods)
);
}
}
}
/**
* Return whether a specific form is set for Captcha in the config. Takes into
* account authentication methods which should be bypassed.
*
* @param string|bool $domain The specific config term are we checking; ie. "sms"
*
* @return bool
*/
public function active($domain = false): bool
{
if (!$domain || empty($this->bypassCaptcha[$domain])) {
return parent::active($domain);
}
$user = $this->authManager->isLoggedIn();
$bypassCaptcha = $user && in_array(
strtolower($user->auth_method),
$this->bypassCaptcha[$domain]
);
return $bypassCaptcha ? false : parent::active($domain);
}
/**
* Normally, this would pull the captcha field from POST and check them for
* accuracy, but we're not actually using the captcha, so only check that other
* conditions are valid.
*
* @return bool
*/
public function verify(): bool
{
if (!$this->active()) {
return true;
}
// Session checks
$storage = new \Laminas\Session\Container(
'SessionState',
$this->sessionManager
);
if (empty($storage->sessionStartTime)) {
$storage->sessionStartTime = time();
}
$timestamp = $storage->lastProtectedActionTime ?? $storage->sessionStartTime;
$passed = time() - $timestamp >= $this->actionInterval;
if ($passed) {
$storage->lastProtectedActionTime = time();
}
if (!$passed && $this->errorMode != 'none') {
$error = str_replace(
'%%interval%%',
max($this->actionInterval - (time() - $timestamp), 1),
$this->translator->translate('protected_action_interval_not_passed')
);
if ($this->errorMode == 'flash') {
$this->getController()->flashMessenger()->addErrorMessage($error);
} else {
throw new \Exception($error);
}
}
return $passed;
}
}
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.