code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/******************************************************************************* * Piotr's Image&Video Toolbox Version 3.01 * Copyright 2012 Piotr Dollar. [pdollar-at-caltech.edu] * Please email me if you find bugs, or have suggestions or questions! * Licensed under the Simplified BSD License [see external/bsd.txt] *******************************************************************************/ #include <string.h> #include <mex.h> typedef unsigned int uint32; void rtreeFindThr( int H, int N, int F, const float *data, const uint32 *hs, const float *ws, const uint32 *order, uint32 &fid, float &thr, double &gini ) { int i, j, h; double *L, *R, *T; float *data1; uint32 *order1; double gini1, s=0, sl, sr, g=0, gl, gr; L=new double[H]; R=new double[H]; T=new double[H]; for( i=0; i<H; i++ ) T[i] = 0; for( j=0; j<N; j++ ) { s+=ws[j]; T[hs[j]-1]+=ws[j]; } for( i=0; i<H; i++ ) g+=T[i]*T[i]; fid = 1; thr = 0; gini = 1e5; for( i=0; i<F; i++ ) { order1=(uint32*) order+i*N; data1=(float*) data+i*N; for( j=0; j<H; j++ ) { L[j]=0; R[j]=T[j]; } gl=sl=0; gr=g; for( j=0; j<N-1; j++ ) { int j1=order1[j], j2=order1[j+1]; h=hs[j1]-1; sl+=ws[j1]; sr=s-sl; gl-=L[h]*L[h]; L[h]+=ws[j1]; gl+=L[h]*L[h]; gr-=R[h]*R[h]; R[h]-=ws[j1]; gr+=R[h]*R[h]; if( data1[j2]-data1[j1]<1e-6f ) continue; gini1 = (sl-gl/sl)/s + (sr-gr/sr)/s; // + (sl*sl+sr*sr)/(s*s*100); if(gini1<gini) { gini=gini1; fid=i+1; thr=0.5f*(data1[j1]+data1[j2]); } } } delete [] L; delete [] R; delete [] T; } // [fid,thr,gini] = rtreeFindThr(data,hs,ws,order,H); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int H, N, F; float *data, *ws, thr; double gini; uint32 *hs, *order, fid; data = (float*) mxGetData(prhs[0]); hs = (uint32*) mxGetData(prhs[1]); ws = (float*) mxGetData(prhs[2]); order = (uint32*) mxGetData(prhs[3]); H = (int) mxGetScalar(prhs[4]); N = (int) mxGetM(prhs[0]); F = (int) mxGetN(prhs[0]); rtreeFindThr(H,N,F,data,hs,ws,order,fid,thr,gini); plhs[0] = mxCreateDoubleScalar(fid); plhs[1] = mxCreateDoubleScalar(thr); plhs[2] = mxCreateDoubleScalar(gini); }
mmaire/hsa-bench
benchmark/mpi/toolbox/classify/private/forestFindThr.cpp
C++
gpl-2.0
2,177
<h3><?php _e( 'Field Editor', 'woo_ce' ); ?></h3> <p><?php _e( 'Customise the field labels for this export type by filling in the fields, an empty field label will revert to the default Store Exporter field label at export time.', 'woo_ce' ); ?></p> <?php if( $fields ) { ?> <form method="post" id="postform"> <table class="form-table"> <tbody> <?php foreach( $fields as $field ) { ?> <?php if( isset( $field['name'] ) ) { ?> <tr> <th scope="row"><label for="<?php echo $field['name']; ?>"><?php echo $field['name']; ?></label></th> <td> <input type="text" name="fields[<?php echo $field['name']; ?>]" title="<?php echo $field['name']; ?>" placeholder="<?php echo $field['label']; ?>" value="<?php if( isset( $labels[$field['name']] ) ) { echo $labels[$field['name']]; } ?>" class="regular-text all-options" /> </td> </tr> <?php } ?> <?php } ?> </tbody> </table> <!-- .form-table --> <p class="submit"> <input type="submit" value="<?php _e( 'Save Changes', 'woo_ce' ); ?> " class="button-primary" /> </p> <input type="hidden" name="action" value="save-fields" /> <input type="hidden" name="type" value="<?php echo esc_attr( $export_type ); ?>" /> </form> <?php } ?>
C4AProjects/Zuvaa
wp-content/plugins/woocommerce-exporter/templates/admin/tabs-fields.php
PHP
gpl-2.0
1,236
# (c) Copyright 2006-2008 Nick Sieger <nicksieger@gmail.com> # See the file LICENSE.txt included with the distribution for # software license details. require File.dirname(__FILE__) + "/../../spec_helper.rb" require 'stringio' describe "The RSpec reporter" do before(:each) do @error = mock("error") @error.stub!(:expectation_not_met?).and_return(false) @error.stub!(:pending_fixed?).and_return(false) @report_mgr = mock("report manager") @options = mock("options") @args = [@options, StringIO.new("")] @args.shift if Spec::VERSION::MAJOR == 1 && Spec::VERSION::MINOR < 1 @fmt = CI::Reporter::RSpec.new *@args @fmt.report_manager = @report_mgr @formatter = mock("formatter") @fmt.formatter = @formatter end it "should use a progress bar formatter by default" do fmt = CI::Reporter::RSpec.new *@args fmt.formatter.should be_instance_of(Spec::Runner::Formatter::ProgressBarFormatter) end it "should use a specdoc formatter for RSpecDoc" do fmt = CI::Reporter::RSpecDoc.new *@args fmt.formatter.should be_instance_of(Spec::Runner::Formatter::SpecdocFormatter) end it "should create a test suite with one success, one failure, and one pending" do @report_mgr.should_receive(:write_report).and_return do |suite| suite.testcases.length.should == 3 suite.testcases[0].should_not be_failure suite.testcases[0].should_not be_error suite.testcases[1].should be_error suite.testcases[2].name.should =~ /\(PENDING\)/ end example_group = mock "example group" example_group.stub!(:description).and_return "A context" @formatter.should_receive(:start).with(3) @formatter.should_receive(:example_group_started).with(example_group) @formatter.should_receive(:example_started).exactly(3).times @formatter.should_receive(:example_passed).once @formatter.should_receive(:example_failed).once @formatter.should_receive(:example_pending).once @formatter.should_receive(:start_dump).once @formatter.should_receive(:dump_failure).once @formatter.should_receive(:dump_summary).once @formatter.should_receive(:dump_pending).once @formatter.should_receive(:close).once @fmt.start(3) @fmt.example_group_started(example_group) @fmt.example_started("should pass") @fmt.example_passed("should pass") @fmt.example_started("should fail") @fmt.example_failed("should fail", 1, @error) @fmt.example_started("should be pending") @fmt.example_pending("A context", "should be pending", "Not Yet Implemented") @fmt.start_dump @fmt.dump_failure(1, mock("failure")) @fmt.dump_summary(0.1, 3, 1, 1) @fmt.dump_pending @fmt.close end it "should support RSpec 1.0.8 #add_behavior" do @formatter.should_receive(:start) @formatter.should_receive(:add_behaviour).with("A context") @formatter.should_receive(:example_started).once @formatter.should_receive(:example_passed).once @formatter.should_receive(:dump_summary) @report_mgr.should_receive(:write_report) @fmt.start(2) @fmt.add_behaviour("A context") @fmt.example_started("should pass") @fmt.example_passed("should pass") @fmt.dump_summary(0.1, 1, 0, 0) end it "should use the example #description method when available" do group = mock "example group" group.stub!(:description).and_return "group description" example = mock "example" example.stub!(:description).and_return "should do something" @formatter.should_receive(:start) @formatter.should_receive(:example_group_started).with(group) @formatter.should_receive(:example_started).with(example).once @formatter.should_receive(:example_passed).once @formatter.should_receive(:dump_summary) @report_mgr.should_receive(:write_report).and_return do |suite| suite.testcases.last.name.should == "should do something" end @fmt.start(2) @fmt.example_group_started(group) @fmt.example_started(example) @fmt.example_passed(example) @fmt.dump_summary(0.1, 1, 0, 0) end end
Dreyerized/bananascrum
vendor/gems/ci_reporter-1.6.0/spec/ci/reporter/rspec_spec.rb
Ruby
gpl-2.0
4,078
/* LilyPad - Pad plugin for PS2 Emulator * Copyright (C) 2002-2014 PCSX2 Dev Team/ChickenLiver * * PCSX2 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 Found- ation, either version 3 of the License, or (at your option) * any later version. * * PCSX2 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 PCSX2. If not, see <http://www.gnu.org/licenses/>. */ #include "Global.h" #include "InputManager.h" #include "WindowsMessaging.h" #include "VKey.h" #include "DeviceEnumerator.h" #include "WndProcEater.h" #include "WindowsKeyboard.h" #include "WindowsMouse.h" ExtraWndProcResult RawInputWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *output); int GetRawKeyboards(HWND hWnd) { RAWINPUTDEVICE Rid; Rid.hwndTarget = hWnd; Rid.dwFlags = 0; Rid.usUsagePage = 0x01; Rid.usUsage = 0x06; return RegisterRawInputDevices(&Rid, 1, sizeof(Rid)); } void ReleaseRawKeyboards() { RAWINPUTDEVICE Rid; Rid.hwndTarget = 0; Rid.dwFlags = RIDEV_REMOVE; Rid.usUsagePage = 0x01; Rid.usUsage = 0x06; RegisterRawInputDevices(&Rid, 1, sizeof(Rid)); } int GetRawMice(HWND hWnd) { RAWINPUTDEVICE Rid; Rid.hwndTarget = hWnd; Rid.dwFlags = RIDEV_NOLEGACY | RIDEV_CAPTUREMOUSE; Rid.usUsagePage = 0x01; Rid.usUsage = 0x02; return RegisterRawInputDevices(&Rid, 1, sizeof(Rid)); } void ReleaseRawMice() { RAWINPUTDEVICE Rid; Rid.hwndTarget = 0; Rid.dwFlags = RIDEV_REMOVE; Rid.usUsagePage = 0x01; Rid.usUsage = 0x02; RegisterRawInputDevices(&Rid, 1, sizeof(Rid)); } // Count of active raw keyboard devices. // when it gets to 0, release them all. static int rawKeyboardActivatedCount = 0; // Same for mice. static int rawMouseActivatedCount = 0; class RawInputKeyboard : public WindowsKeyboard { public: HANDLE hDevice; RawInputKeyboard(HANDLE hDevice, wchar_t *name, wchar_t *instanceID=0) : WindowsKeyboard(RAW, name, instanceID) { this->hDevice = hDevice; } int Activate(InitInfo *initInfo) { Deactivate(); hWndProc = initInfo->hWndProc; active = 1; if (!rawKeyboardActivatedCount++) { if (!rawMouseActivatedCount) hWndProc->Eat(RawInputWndProc, EATPROC_NO_UPDATE_WHILE_UPDATING_DEVICES); if (!GetRawKeyboards(hWndProc->hWndEaten)) { Deactivate(); return 0; } } InitState(); return 1; } void Deactivate() { FreeState(); if (active) { active = 0; rawKeyboardActivatedCount --; if (!rawKeyboardActivatedCount) { ReleaseRawKeyboards(); if (!rawMouseActivatedCount) hWndProc->ReleaseExtraProc(RawInputWndProc); } } } }; class RawInputMouse : public WindowsMouse { public: HANDLE hDevice; RawInputMouse(HANDLE hDevice, wchar_t *name, wchar_t *instanceID=0, wchar_t *productID=0) : WindowsMouse(RAW, 0, name, instanceID, productID) { this->hDevice = hDevice; } int Activate(InitInfo *initInfo) { Deactivate(); hWndProc = initInfo->hWndProc; active = 1; // Have to be careful with order. At worst, one unmatched call to ReleaseRawMice on // EatWndProc fail. In all other cases, no unmatched initialization/cleanup // lines. if (!rawMouseActivatedCount++) { GetMouseCapture(hWndProc->hWndEaten); if (!rawKeyboardActivatedCount) hWndProc->Eat(RawInputWndProc, EATPROC_NO_UPDATE_WHILE_UPDATING_DEVICES); if (!GetRawMice(hWndProc->hWndEaten)) { Deactivate(); return 0; } } AllocState(); return 1; } void Deactivate() { FreeState(); if (active) { active = 0; rawMouseActivatedCount --; if (!rawMouseActivatedCount) { ReleaseRawMice(); ReleaseMouseCapture(); if (!rawKeyboardActivatedCount) { hWndProc->ReleaseExtraProc(RawInputWndProc); } } } } }; ExtraWndProcResult RawInputWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *output) { if (uMsg == WM_INPUT) { if (GET_RAWINPUT_CODE_WPARAM (wParam) == RIM_INPUT) { RAWINPUT in; unsigned int size = sizeof(RAWINPUT); if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, &in, &size, sizeof(RAWINPUTHEADER)) > 0) { for (int i=0; i<dm->numDevices; i++) { Device *dev = dm->devices[i]; if (dev->api != RAW || !dev->active) continue; if (in.header.dwType == RIM_TYPEKEYBOARD && dev->type == KEYBOARD) { RawInputKeyboard* rik = (RawInputKeyboard*)dev; if (rik->hDevice != in.header.hDevice) continue; u32 uMsg = in.data.keyboard.Message; if (!(in.data.keyboard.VKey>>8)) rik->UpdateKey((u8) in.data.keyboard.VKey, (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN)); } else if (in.header.dwType == RIM_TYPEMOUSE && dev->type == MOUSE) { RawInputMouse* rim = (RawInputMouse*)dev; if (rim->hDevice != in.header.hDevice) continue; if (in.data.mouse.usFlags) { // Never been set for me, and specs on what most of them // actually mean is sorely lacking. Also, specs erroneously // indicate MOUSE_MOVE_RELATIVE is a flag, when it's really // 0... continue; } unsigned short buttons = in.data.mouse.usButtonFlags & 0x3FF; int button = 0; while (buttons) { if (buttons & 3) { // 2 is up, 1 is down. Up takes precedence over down. rim->UpdateButton(button, !(buttons & 2)); } button++; buttons >>= 2; } if (in.data.mouse.usButtonFlags & RI_MOUSE_WHEEL) { rim->UpdateAxis(2, ((short)in.data.mouse.usButtonData)/WHEEL_DELTA); } if (in.data.mouse.lLastX || in.data.mouse.lLastY) { rim->UpdateAxis(0, in.data.mouse.lLastX); rim->UpdateAxis(1, in.data.mouse.lLastY); } } } } } } else if (uMsg == WM_ACTIVATE) { for (int i=0; i<dm->numDevices; i++) { Device *dev = dm->devices[i]; if (dev->api != RAW || dev->physicalControlState == 0) continue; memset(dev->physicalControlState, 0, sizeof(int) * dev->numPhysicalControls); } } else if (uMsg == WM_SIZE && rawMouseActivatedCount) { // Doesn't really matter for raw mice, as I disable legacy stuff, but shouldn't hurt. WindowsMouse::WindowResized(hWnd); } return CONTINUE_BLISSFULLY; } void EnumRawInputDevices() { int count = 0; if (GetRawInputDeviceList(0, (unsigned int*)&count, sizeof(RAWINPUTDEVICELIST)) != (UINT)-1 && count > 0) { wchar_t *instanceID = (wchar_t *) malloc(41000*sizeof(wchar_t)); wchar_t *keyName = instanceID + 11000; wchar_t *displayName = keyName + 10000; wchar_t *productID = displayName + 10000; RAWINPUTDEVICELIST *list = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * count); int keyboardCount = 1; int mouseCount = 1; count = GetRawInputDeviceList(list, (unsigned int*)&count, sizeof(RAWINPUTDEVICELIST)); // Not necessary, but reminder that count is -1 on failure. if (count > 0) { for (int i=0; i<count; i++) { if (list[i].dwType != RIM_TYPEKEYBOARD && list[i].dwType != RIM_TYPEMOUSE) continue; UINT bufferLen = 10000; int nameLen = GetRawInputDeviceInfo(list[i].hDevice, RIDI_DEVICENAME, instanceID, &bufferLen); if (nameLen >= 4) { // nameLen includes terminating null. nameLen--; // Strip out GUID parts of instanceID to make it a generic product id, // and reformat it to point to registry entry containing device description. wcscpy(productID, instanceID); wchar_t *temp = 0; for (int j=0; j<3; j++) { wchar_t *s = wcschr(productID, '#'); if (!s) break; *s = '\\'; if (j==2) { *s = 0; } if (j==1) temp = s; } wsprintfW(keyName, L"SYSTEM\\CurrentControlSet\\Enum%s", productID+3); if (temp) *temp = 0; int haveDescription = 0; HKEY hKey; if (ERROR_SUCCESS == RegOpenKeyExW(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE, &hKey)) { DWORD type; DWORD len = 10000 * sizeof(wchar_t); if (ERROR_SUCCESS == RegQueryValueExW(hKey, L"DeviceDesc", 0, &type, (BYTE*)displayName, &len) && len && type == REG_SZ) { wchar_t *temp2 = wcsrchr(displayName, ';'); if (!temp2) temp2 = displayName; else temp2++; // Could do without this, but more effort than it's worth. wcscpy(keyName, temp2); haveDescription = 1; } RegCloseKey(hKey); } if (list[i].dwType == RIM_TYPEKEYBOARD) { if (!haveDescription) wsprintfW(displayName, L"Raw Keyboard %i", keyboardCount++); else wsprintfW(displayName, L"Raw KB: %s", keyName); dm->AddDevice(new RawInputKeyboard(list[i].hDevice, displayName, instanceID)); } else if (list[i].dwType == RIM_TYPEMOUSE) { if (!haveDescription) wsprintfW(displayName, L"Raw Mouse %i", mouseCount++); else wsprintfW(displayName, L"Raw MS: %s", keyName); dm->AddDevice(new RawInputMouse(list[i].hDevice, displayName, instanceID, productID)); } } } } free(list); free(instanceID); dm->AddDevice(new RawInputKeyboard(0, L"Simulated Keyboard")); dm->AddDevice(new RawInputMouse(0, L"Simulated Mouse")); } }
intervigilium/pcsx2
plugins/LilyPad/RawInput.cpp
C++
gpl-2.0
9,343
/*************************************************************************** testqgsgrassprovider.cpp -------------------------------------- Date : April 2015 Copyright : (C) 2015 by Radim Blazek Email : radim dot blazek at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <cmath> #include <QApplication> #include <QDir> #include <QObject> #include <QString> #include <QStringList> #include <QTemporaryFile> #include <QtTest/QtTest> #include <qgsapplication.h> #include <qgscoordinatereferencesystem.h> #include <qgsgrass.h> #include <qgsgrassimport.h> #include <qgsproviderregistry.h> #include <qgsrasterbandstats.h> #include <qgsrasterlayer.h> #include <qgsvectordataprovider.h> extern "C" { #ifndef _MSC_VER #include <unistd.h> #endif #include <grass/version.h> } #define TINY_VALUE std::numeric_limits<double>::epsilon() * 20 /** \ingroup UnitTests * This is a unit test for the QgsRasterLayer class. */ class TestQgsGrassProvider: public QObject { Q_OBJECT private slots: void initTestCase();// will be called before the first testfunction is executed. void cleanupTestCase();// will be called after the last testfunction was executed. void init() {} // will be called before each testfunction is executed. void cleanup() {} // will be called after every testfunction. void fatalError(); void locations(); void mapsets(); void maps(); void vectorLayers(); void region(); void info(); void rasterImport(); void vectorImport(); private: void reportRow( QString message ); void reportHeader( QString message ); // verify result and report result bool verify( bool ok ); // compare expected and got string and set ok to false if not equal bool compare( QString expected, QString got, bool& ok ); // lists are considered equal if contains the same values regardless order // set ok to false if not equal bool compare( QStringList expected, QStringList got, bool& ok ); // compare with tolerance bool compare( double expected, double got, bool& ok ); bool createTmpLocation( QString& tmpGisdbase, QString& tmpLocation, QString& tmpMapset ); QString mGisdbase; QString mLocation; QString mReport; QString mBuildMapset; }; #define GVERIFY(x) QVERIFY( verify(x) ) void TestQgsGrassProvider::reportRow( QString message ) { mReport += message + "<br>\n"; } void TestQgsGrassProvider::reportHeader( QString message ) { mReport += "<h2>" + message + "</h2>\n"; } //runs before all tests void TestQgsGrassProvider::initTestCase() { // init QGIS's paths - true means that all path will be inited from prefix QgsApplication::init(); // QgsApplication::initQgis() calls QgsProviderRegistry::instance() which registers providers. // Because providers are linked in build directory with rpath, it would also try to load GRASS providers // in version different form which we are testing here and it would also load GRASS libs in different version // and result in segfault when __do_global_dtors_aux() is called. // => we must set QGIS_PROVIDER_FILE before QgsApplication::initQgis() to avoid loading GRASS provider in different version QgsGrass::putEnv( "QGIS_PROVIDER_FILE", "gdal|ogr" ); QgsApplication::initQgis(); QString mySettings = QgsApplication::showSettings(); mySettings = mySettings.replace( "\n", "<br />\n" ); mReport += QString( "<h1>GRASS %1 provider tests</h1>\n" ).arg( GRASS_BUILD_VERSION ); mReport += "<p>" + mySettings + "</p>\n"; #ifndef Q_OS_WIN reportRow( "LD_LIBRARY_PATH: " + QString( getenv( "LD_LIBRARY_PATH" ) ) ); #else reportRow( "PATH: " + QString( getenv( "PATH" ) ) ); #endif QgsGrass::init(); //create some objects that will be used in all tests... //create a raster layer that will be used in all tests... mGisdbase = QString( TEST_DATA_DIR ) + "/grass"; mLocation = "wgs84"; mBuildMapset = QString( "test%1" ).arg( GRASS_BUILD_VERSION ); reportRow( "mGisdbase: " + mGisdbase ); reportRow( "mLocation: " + mLocation ); reportRow( "mBuildMapset: " + mBuildMapset ); qDebug() << "mGisdbase = " << mGisdbase << " mLocation = " << mLocation; } //runs after all tests void TestQgsGrassProvider::cleanupTestCase() { QString myReportFile = QDir::tempPath() + "/qgistest.html"; QFile myFile( myReportFile ); if ( myFile.open( QIODevice::WriteOnly | QIODevice::Append ) ) { QTextStream myQTextStream( &myFile ); myQTextStream << mReport; myFile.close(); } //QgsApplication::exitQgis(); } bool TestQgsGrassProvider::verify( bool ok ) { reportRow( "" ); reportRow( QString( "Test result: " ) + ( ok ? "ok" : "error" ) ); return ok; } bool TestQgsGrassProvider::compare( QString expected, QString got, bool &ok ) { if ( expected != got ) { ok = false; return false; } return true; } bool TestQgsGrassProvider::compare( QStringList expected, QStringList got, bool &ok ) { QStringList e = expected; QStringList g = got; e.sort(); g.sort(); if ( e != g ) { ok = false; return false; } return true; } bool TestQgsGrassProvider::compare( double expected, double got, bool& ok ) { if ( qAbs( got - expected ) > TINY_VALUE ) { ok = false; return false; } return true; } // G_fatal_error() handling void TestQgsGrassProvider::fatalError() { reportHeader( "TestQgsGrassProvider::fatalError" ); bool ok = true; QString errorMessage = "test fatal error"; G_TRY { G_fatal_error( "%s", errorMessage.toAscii().data() ); ok = false; // should not be reached reportRow( "G_fatal_error() did not throw exception" ); } G_CATCH( QgsGrass::Exception &e ) { reportRow( QString( "Exception thrown and caught correctly" ) ); reportRow( "expected error message: " + errorMessage ); reportRow( "got error message: " + QString( e.what() ) ); compare( errorMessage, e.what(), ok ); } compare( errorMessage, QgsGrass::errorMessage(), ok ); GVERIFY( ok ); } void TestQgsGrassProvider::locations() { reportHeader( "TestQgsGrassProvider::locations" ); bool ok = true; QStringList expectedLocations; expectedLocations << "wgs84"; QStringList locations = QgsGrass::locations( mGisdbase ); reportRow( "expectedLocations: " + expectedLocations.join( ", " ) ); reportRow( "locations: " + locations.join( ", " ) ); compare( expectedLocations, locations, ok ); GVERIFY( ok ); } void TestQgsGrassProvider::mapsets() { reportHeader( "TestQgsGrassProvider::mapsets" ); bool ok = true; QStringList expectedMapsets; expectedMapsets << "PERMANENT" << "test" << "test6" << "test7"; QStringList mapsets = QgsGrass::mapsets( mGisdbase, mLocation ); reportRow( "expectedMapsets: " + expectedMapsets.join( ", " ) ); reportRow( "mapsets: " + mapsets.join( ", " ) ); compare( expectedMapsets, mapsets, ok ); QgsGrass::setLocation( mGisdbase, mLocation ); // for G_is_mapset_in_search_path foreach ( QString expectedMapset, expectedMapsets ) { if ( G_is_mapset_in_search_path( expectedMapset.toAscii().data() ) != 1 ) { reportRow( "mapset " + expectedMapset + " not in search path" ); ok = false; } } // open/close mapset try twice to be sure that lock was not left etc. for ( int i = 1; i < 3; i++ ) { reportRow( "" ); reportRow( "Open/close mapset " + mBuildMapset + " for the " + QString::number( i ) + ". time" ); QString error = QgsGrass::openMapset( mGisdbase, mLocation, mBuildMapset ); if ( !error.isEmpty() ) { reportRow( "QgsGrass::openMapset() failed: " + error ); ok = false; } else { reportRow( "mapset successfully opened" ); if ( !QgsGrass::activeMode() ) { reportRow( "QgsGrass::activeMode() returns false after openMapset()" ); ok = false; } error = QgsGrass::closeMapset(); if ( !error.isEmpty() ) { reportRow( "QgsGrass::close() failed: " + error ); ok = false; } else { reportRow( "mapset successfully closed" ); } if ( QgsGrass::activeMode() ) { reportRow( "QgsGrass::activeMode() returns true after closeMapset()" ); ok = false; } } } GVERIFY( ok ); } void TestQgsGrassProvider::maps() { reportHeader( "TestQgsGrassProvider::maps" ); bool ok = true; QStringList expectedVectors; expectedVectors << "test"; QStringList vectors = QgsGrass::vectors( mGisdbase, mLocation, mBuildMapset ); reportRow( "expectedVectors: " + expectedVectors.join( ", " ) ); reportRow( "vectors: " + vectors.join( ", " ) ); compare( expectedVectors, vectors, ok ); reportRow( "" ); QStringList expectedRasters; expectedRasters << "cell" << "dcell" << "fcell"; QStringList rasters = QgsGrass::rasters( mGisdbase, mLocation, "test" ); reportRow( "expectedRasters: " + expectedRasters.join( ", " ) ); reportRow( "rasters: " + rasters.join( ", " ) ); compare( expectedRasters, rasters, ok ); GVERIFY( ok ); } void TestQgsGrassProvider::vectorLayers() { reportHeader( "TestQgsGrassProvider::vectorLayers" ); QString mapset = mBuildMapset; QString mapName = "test"; QStringList expectedLayers; expectedLayers << "1_point" << "2_line" << "3_polygon"; reportRow( "mapset: " + mapset ); reportRow( "mapName: " + mapName ); reportRow( "expectedLayers: " + expectedLayers.join( ", " ) ); bool ok = true; G_TRY { QStringList layers = QgsGrass::vectorLayers( mGisdbase, mLocation, mapset, mapName ); reportRow( "layers: " + layers.join( ", " ) ); compare( expectedLayers, layers, ok ); } G_CATCH( QgsGrass::Exception &e ) { ok = false; reportRow( QString( "ERROR: %1" ).arg( e.what() ) ); } GVERIFY( ok ); } void TestQgsGrassProvider::region() { reportHeader( "TestQgsGrassProvider::region" ); struct Cell_head window; struct Cell_head windowCopy; bool ok = true; try { QgsGrass::region( mGisdbase, mLocation, "PERMANENT", &window ); } catch ( QgsGrass::Exception &e ) { Q_UNUSED( e ); reportRow( "QgsGrass::region() failed" ); ok = false; } if ( ok ) { QString expectedRegion = "proj:3;zone:0;north:90N;south:90S;east:180E;west:180W;cols:1000;rows:500;e-w resol:0:21:36;n-s resol:0:21:36;"; QString region = QgsGrass::regionString( &window ); reportRow( "expectedRegion: " + expectedRegion ); reportRow( "region: " + region ); compare( expectedRegion, region, ok ); windowCopy.proj = window.proj; windowCopy.zone = window.zone; windowCopy.rows = window.rows; windowCopy.cols = window.cols; QgsGrass::copyRegionExtent( &window, &windowCopy ); QgsGrass::copyRegionResolution( &window, &windowCopy ); QString regionCopy = QgsGrass::regionString( &windowCopy ); reportRow( "regionCopy: " + regionCopy ); compare( expectedRegion, regionCopy, ok ); } GVERIFY( ok ); } void TestQgsGrassProvider::info() { // info() -> getInfo() -> runModule() -> startModule() reportHeader( "TestQgsGrassProvider::info" ); bool ok = true; QgsRectangle expectedExtent( -5, -5, 5, 5 ); QMap<QString, QgsRasterBandStats> expectedStats; QgsRasterBandStats es; es.minimumValue = -20; es.maximumValue = 20; expectedStats.insert( "cell", es ); es.minimumValue = -20.25; es.maximumValue = 20.25; expectedStats.insert( "dcell", es ); es.minimumValue = -20.25; es.maximumValue = 20.25; expectedStats.insert( "fcell", es ); foreach ( QString map, expectedStats.keys() ) { es = expectedStats.value( map ); // TODO: QgsGrass::info() may open dialog window on error which blocks tests QHash<QString, QString> info = QgsGrass::info( mGisdbase, mLocation, "test", map, QgsGrassObject::Raster, "stats", expectedExtent, 10, 10, 5000, false ); reportRow( "map: " + map ); QgsRasterBandStats s; s.minimumValue = info["MIN"].toDouble(); s.maximumValue = info["MAX"].toDouble(); reportRow( QString( "expectedStats: min = %1 max = %2" ).arg( es.minimumValue ).arg( es.maximumValue ) ) ; reportRow( QString( "stats: min = %1 max = %2" ).arg( s.minimumValue ).arg( s.maximumValue ) ) ; compare( es.minimumValue, s.minimumValue, ok ); compare( es.maximumValue, s.maximumValue, ok ); QgsRectangle extent = QgsGrass::extent( mGisdbase, mLocation, "test", map, QgsGrassObject::Raster, false ); reportRow( "expectedExtent: " + expectedExtent.toString() ); reportRow( "extent: " + extent.toString() ); if ( extent != expectedExtent ) { ok = false; } } reportRow( "" ); QgsCoordinateReferenceSystem expectedCrs; expectedCrs.createFromOgcWmsCrs( "EPSG:4326" ); QgsCoordinateReferenceSystem crs = QgsGrass::crs( mGisdbase, mLocation ); reportRow( "expectedCrs: " + expectedCrs.toWkt() ); reportRow( "crs: " + crs.toWkt() ); if ( crs != expectedCrs ) { ok = false; } GVERIFY( ok ); } // create temporary output location bool TestQgsGrassProvider::createTmpLocation( QString& tmpGisdbase, QString& tmpLocation, QString& tmpMapset ) { // use QTemporaryFile to generate name (QTemporaryDir since 5.0) QTemporaryFile* tmpFile = new QTemporaryFile( QDir::tempPath() + "/qgis-grass-test" ); tmpFile->open(); tmpGisdbase = tmpFile->fileName(); delete tmpFile; reportRow( "tmpGisdbase: " + tmpGisdbase ); tmpLocation = "test"; tmpMapset = "PERMANENT"; QString tmpMapsetPath = tmpGisdbase + "/" + tmpLocation + "/" + tmpMapset; reportRow( "tmpMapsetPath: " + tmpMapsetPath ); QDir tmpDir = QDir::temp(); if ( !tmpDir.mkpath( tmpMapsetPath ) ) { reportRow( "cannot create " + tmpMapsetPath ); return false; } QStringList cpFiles; cpFiles << "DEFAULT_WIND" << "WIND" << "PROJ_INFO" << "PROJ_UNITS"; QString templateMapsetPath = mGisdbase + "/" + mLocation + "/PERMANENT"; foreach ( QString cpFile, cpFiles ) { if ( !QFile::copy( templateMapsetPath + "/" + cpFile, tmpMapsetPath + "/" + cpFile ) ) { reportRow( "cannot copy " + cpFile ); return false; } } return true; } void TestQgsGrassProvider::rasterImport() { reportHeader( "TestQgsGrassProvider::rasterImport" ); bool ok = true; QString tmpGisdbase; QString tmpLocation; QString tmpMapset; if ( !createTmpLocation( tmpGisdbase, tmpLocation, tmpMapset ) ) { reportRow( "cannot create temporary location" ); GVERIFY( false ); return; } QStringList rasterFiles; rasterFiles << "tenbytenraster.asc" << "landsat.tif" << "raster/band1_byte_ct_epsg4326.tif" << "raster/band1_int16_noct_epsg4326.tif"; rasterFiles << "raster/band1_float32_noct_epsg4326.tif" << "raster/band3_int16_noct_epsg4326.tif"; QgsCoordinateReferenceSystem mapsetCrs = QgsGrass::crsDirect( mGisdbase, mLocation ); foreach ( QString rasterFile, rasterFiles ) { QString uri = QString( TEST_DATA_DIR ) + "/" + rasterFile; QString name = QFileInfo( uri ).baseName(); reportRow( "input raster: " + uri ); QgsRasterDataProvider* provider = qobject_cast<QgsRasterDataProvider*>( QgsProviderRegistry::instance()->provider( "gdal", uri ) ); if ( !provider ) { reportRow( "Cannot create provider " + uri ); ok = false; continue; } if ( !provider->isValid() ) { reportRow( "Provider is not valid " + uri ); ok = false; continue; } QgsRectangle newExtent = provider->extent(); int newXSize = provider->xSize(); int newYSize = provider->ySize(); QgsRasterPipe* pipe = new QgsRasterPipe(); pipe->set( provider ); QgsCoordinateReferenceSystem providerCrs = provider->crs(); if ( providerCrs.isValid() && mapsetCrs.isValid() && providerCrs != mapsetCrs ) { QgsRasterProjector * projector = new QgsRasterProjector; projector->setCRS( providerCrs, mapsetCrs ); projector->destExtentSize( provider->extent(), provider->xSize(), provider->ySize(), newExtent, newXSize, newYSize ); pipe->set( projector ); } QgsGrassObject rasterObject( tmpGisdbase, tmpLocation, tmpMapset, name, QgsGrassObject::Raster ); QgsGrassRasterImport *import = new QgsGrassRasterImport( pipe, rasterObject, newExtent, newXSize, newYSize ); if ( !import->import() ) { reportRow( "import failed: " + import->error() ); ok = false; } delete import; } GVERIFY( ok ); } void TestQgsGrassProvider::vectorImport() { reportHeader( "TestQgsGrassProvider::vectorImport" ); bool ok = true; QString tmpGisdbase; QString tmpLocation; QString tmpMapset; if ( !createTmpLocation( tmpGisdbase, tmpLocation, tmpMapset ) ) { reportRow( "cannot create temporary location" ); GVERIFY( false ); return; } QStringList files; files << "points.shp" << "multipoint.shp" << "lines.shp" << "polys.shp"; files << "polys_overlapping.shp" << "bug5598.shp"; QgsCoordinateReferenceSystem mapsetCrs = QgsGrass::crsDirect( mGisdbase, mLocation ); foreach ( QString file, files ) { QString uri = QString( TEST_DATA_DIR ) + "/" + file; QString name = QFileInfo( uri ).baseName(); reportRow( "input vector: " + uri ); QgsVectorDataProvider* provider = qobject_cast<QgsVectorDataProvider*>( QgsProviderRegistry::instance()->provider( "ogr", uri ) ); if ( !provider ) { reportRow( "Cannot create provider " + uri ); ok = false; continue; } if ( !provider->isValid() ) { reportRow( "Provider is not valid " + uri ); ok = false; continue; } QgsGrassObject vectorObject( tmpGisdbase, tmpLocation, tmpMapset, name, QgsGrassObject::Vector ); QgsGrassVectorImport *import = new QgsGrassVectorImport( provider, vectorObject ); if ( !import->import() ) { reportRow( "import failed: " + import->error() ); ok = false; } delete import; QStringList layers = QgsGrass::vectorLayers( tmpGisdbase, tmpLocation, tmpMapset, name ); reportRow( "created layers: " + layers.join( "," ) ); } GVERIFY( ok ); } QTEST_MAIN( TestQgsGrassProvider ) #include "testqgsgrassprovider.moc"
michaelkirk/QGIS
tests/src/providers/grass/testqgsgrassprovider.cpp
C++
gpl-2.0
18,819
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jme3.bullet.collision.shapes.infos; import com.jme3.bullet.collision.shapes.BoxCollisionShape; import com.jme3.bullet.collision.shapes.CollisionShape; import com.jme3.export.*; import com.jme3.math.Matrix3f; import com.jme3.math.Vector3f; import java.io.IOException; /** * * @author normenhansen */ public class ChildCollisionShape implements Savable { public Vector3f location; public Matrix3f rotation; public CollisionShape shape; public ChildCollisionShape() { } public ChildCollisionShape(Vector3f location, Matrix3f rotation, CollisionShape shape) { this.location = location; this.rotation = rotation; this.shape = shape; } public void write(JmeExporter ex) throws IOException { OutputCapsule capsule = ex.getCapsule(this); capsule.write(location, "location", new Vector3f()); capsule.write(rotation, "rotation", new Matrix3f()); capsule.write(shape, "shape", new BoxCollisionShape(new Vector3f(1, 1, 1))); } public void read(JmeImporter im) throws IOException { InputCapsule capsule = im.getCapsule(this); location = (Vector3f) capsule.readSavable("location", new Vector3f()); rotation = (Matrix3f) capsule.readSavable("rotation", new Matrix3f()); shape = (CollisionShape) capsule.readSavable("shape", new BoxCollisionShape(new Vector3f(1, 1, 1))); } }
rex-xxx/mt6572_x201
external/jmonkeyengine/engine/src/bullet-common/com/jme3/bullet/collision/shapes/infos/ChildCollisionShape.java
Java
gpl-2.0
1,514
<?php /** * @package Joomla.Platform * @subpackage Google * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Joomla Platform class for interacting with the Google APIs. * * @property-read JGoogleData $data Google API object for data. * @property-read JGoogleEmbed $embed Google API object for embed generation. * * @package Joomla.Platform * @subpackage Google * @since 12.3 */ class JGoogle { /** * @var JRegistry Options for the Google object. * @since 12.3 */ protected $options; /** * @var JAuth The authentication client object to use in sending authenticated HTTP requests. * @since 12.3 */ protected $auth; /** * @var JGoogleData Google API object for data request. * @since 12.3 */ protected $data; /** * @var JGoogleEmbed Google API object for embed generation. * @since 12.3 */ protected $embed; /** * Constructor. * * @param JRegistry $options Google options object. * @param JAuth $auth The authentication client object. * * @since 12.3 */ public function __construct(JRegistry $options = null, JGoogleAuth $auth = null) { $this->options = isset($options) ? $options : new JRegistry; $this->auth = isset($auth) ? $auth : new JGoogleAuthOauth2($this->options); } /** * Method to create JGoogleData objects * * @param string $name Name of property to retrieve * @param JRegistry $options Google options object. * @param JAuth $auth The authentication client object. * * @return JGoogleData Google data API object. * * @since 12.3 */ public function data($name, $options = null, $auth = null) { if ($this->options && !$options) { $options = $this->options; } if ($this->auth && !$auth) { $auth = $this->auth; } switch ($name) { case 'plus': case 'Plus': return new JGoogleDataPlus($options, $auth); case 'picasa': case 'Picasa': return new JGoogleDataPicasa($options, $auth); case 'adsense': case 'Adsense': return new JGoogleDataAdsense($options, $auth); case 'calendar': case 'Calendar': return new JGoogleDataCalendar($options, $auth); default: return null; } } /** * Method to create JGoogleEmbed objects * * @param string $name Name of property to retrieve * @param JRegistry $options Google options object. * * @return JGoogleEmbed Google embed API object. * * @since 12.3 */ public function embed($name, $options = null) { if ($this->options && !$options) { $options = $this->options; } switch ($name) { case 'maps': case 'Maps': return new JGoogleEmbedMaps($options); case 'analytics': case 'Analytics': return new JGoogleEmbedAnalytics($options); default: return null; } } /** * Get an option from the JGoogle instance. * * @param string $key The name of the option to get. * * @return mixed The option value. * * @since 12.3 */ public function getOption($key) { return $this->options->get($key); } /** * Set an option for the JGoogle instance. * * @param string $key The name of the option to set. * @param mixed $value The option value to set. * * @return JGoogle This object for method chaining. * * @since 12.3 */ public function setOption($key, $value) { $this->options->set($key, $value); return $this; } }
01J/furcom
libraries/joomla/google/google.php
PHP
gpl-2.0
3,770
<?php class SpotlightsController extends WikiaController { public function index() { } }
SuriyaaKudoIsc/wikia-app-test
skins/oasis/modules/SpotlightsController.class.php
PHP
gpl-2.0
91
<?php /** * Implements hook_html_head_alter(). * This will overwrite the default meta character type tag with HTML5 version. */ function splendio_html_head_alter(&$head_elements) { $head_elements['system_meta_content_type']['#attributes'] = array( 'charset' => 'utf-8' ); } /** * Insert themed breadcrumb page navigation at top of the node content. */ function splendio_breadcrumb($variables) { $breadcrumb = $variables['breadcrumb']; if (!empty($breadcrumb)) { // Use CSS to hide titile .element-invisible. $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>'; // comment below line to hide current page to breadcrumb $breadcrumb[] = drupal_get_title(); $output .= '<nav class="breadcrumb">' . implode(' » ', $breadcrumb) . '</nav>'; return $output; } } /** * Override or insert variables into the page template. */ function splendio_preprocess_page(&$vars) { if (isset($vars['main_menu'])) { $vars['main_menu'] = theme('links__system_main_menu', array( 'links' => $vars['main_menu'], 'attributes' => array( 'class' => array('links', 'main-menu', 'clearfix'), ), 'heading' => array( 'text' => t('Main menu'), 'level' => 'h2', 'class' => array('element-invisible'), ) )); } else { $vars['main_menu'] = FALSE; } if (isset($vars['secondary_menu'])) { $vars['secondary_menu'] = theme('links__system_secondary_menu', array( 'links' => $vars['secondary_menu'], 'attributes' => array( 'class' => array('links', 'secondary-menu', 'clearfix'), ), 'heading' => array( 'text' => t('Secondary menu'), 'level' => 'h2', 'class' => array('element-invisible'), ) )); } else { $vars['secondary_menu'] = FALSE; } } /** * Duplicate of theme_menu_local_tasks() but adds clearfix to tabs. */ function splendio_menu_local_tasks(&$variables) { $output = ''; if (!empty($variables['primary'])) { $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>'; $variables['primary']['#prefix'] .= '<ul class="tabs primary clearfix">'; $variables['primary']['#suffix'] = '</ul>'; $output .= drupal_render($variables['primary']); } if (!empty($variables['secondary'])) { $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>'; $variables['secondary']['#prefix'] .= '<ul class="tabs secondary clearfix">'; $variables['secondary']['#suffix'] = '</ul>'; $output .= drupal_render($variables['secondary']); } return $output; } /** * Override the search box to add our pretty graphic instead of the button. */ function splendio_form_search_block_form_alter(&$form, &$form_state) { $form['actions']['submit']['#value'] = 'GO'; } /** * Add custom PHPTemplate variables into the node template. */ function splendio_preprocess_node(&$vars) { // Grab the node object. $node = $vars['node']; // Make individual variables for the parts of the date. $vars['date'] = format_date($node->created, 'custom', 'M j, Y'); // Add the .post class to all nodes. $vars['classes_array'][] = 'post'; // Change the theme function used for rendering the list of tags. $vars['content']['field_tags']['#theme'] = 'links'; }
VickyDeschrijver/wzs
sites/all/themes/splendio/template.php
PHP
gpl-2.0
3,354
#region Header // ********** // ServUO - World.cs // ********** #endregion #region References using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using CustomsFramework; using Server.Guilds; using Server.Network; #endregion namespace Server { public static class World { private static Dictionary<Serial, Mobile> m_Mobiles; private static Dictionary<Serial, Item> m_Items; private static Dictionary<CustomSerial, SaveData> _Data; private static bool m_Loading; private static bool m_Loaded; private static bool m_Saving; private static readonly ManualResetEvent m_DiskWriteHandle = new ManualResetEvent(true); private static Queue<IEntity> _addQueue, _deleteQueue; private static Queue<ICustomsEntity> _CustomsAddQueue, _CustomsDeleteQueue; public static bool Saving { get { return m_Saving; } } public static bool Loaded { get { return m_Loaded; } } public static bool Loading { get { return m_Loading; } } public static readonly string MobileIndexPath = Path.Combine("Saves/Mobiles/", "Mobiles.idx"); public static readonly string MobileTypesPath = Path.Combine("Saves/Mobiles/", "Mobiles.tdb"); public static readonly string MobileDataPath = Path.Combine("Saves/Mobiles/", "Mobiles.bin"); public static readonly string ItemIndexPath = Path.Combine("Saves/Items/", "Items.idx"); public static readonly string ItemTypesPath = Path.Combine("Saves/Items/", "Items.tdb"); public static readonly string ItemDataPath = Path.Combine("Saves/Items/", "Items.bin"); public static readonly string GuildIndexPath = Path.Combine("Saves/Guilds/", "Guilds.idx"); public static readonly string GuildDataPath = Path.Combine("Saves/Guilds/", "Guilds.bin"); public static readonly string DataIndexPath = Path.Combine("Saves/Customs/", "SaveData.idx"); public static readonly string DataTypesPath = Path.Combine("Saves/Customs/", "SaveData.tdb"); public static readonly string DataBinaryPath = Path.Combine("Saves/Customs/", "SaveData.bin"); public static void NotifyDiskWriteComplete() { if (m_DiskWriteHandle.Set()) { Console.WriteLine("Closing Save Files. "); } } public static void WaitForWriteCompletion() { m_DiskWriteHandle.WaitOne(); } public static Dictionary<Serial, Mobile> Mobiles { get { return m_Mobiles; } } public static Dictionary<Serial, Item> Items { get { return m_Items; } } public static Dictionary<CustomSerial, SaveData> Data { get { return _Data; } } public static bool OnDelete(IEntity entity) { if (m_Saving || m_Loading) { if (m_Saving) { AppendSafetyLog("delete", entity); } _deleteQueue.Enqueue(entity); return false; } return true; } public static bool OnDelete(ICustomsEntity entity) { if (m_Saving || m_Loading) { if (m_Saving) { AppendSafetyLog("delete", entity); } _CustomsDeleteQueue.Enqueue(entity); return false; } return true; } public static void Broadcast(int hue, bool ascii, string text) { Packet p; if (ascii) { p = new AsciiMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "System", text); } else { p = new UnicodeMessage(Serial.MinusOne, -1, MessageType.Regular, hue, 3, "ENU", "System", text); } var list = NetState.Instances; p.Acquire(); for (int i = 0; i < list.Count; ++i) { if (list[i].Mobile != null) { list[i].Send(p); } } p.Release(); NetState.FlushAll(); } public static void Broadcast(int hue, bool ascii, string format, params object[] args) { Broadcast(hue, ascii, String.Format(format, args)); } private interface IEntityEntry { Serial Serial { get; } int TypeID { get; } long Position { get; } int Length { get; } } private sealed class GuildEntry : IEntityEntry { private readonly BaseGuild m_Guild; private readonly long m_Position; private readonly int m_Length; public BaseGuild Guild { get { return m_Guild; } } public Serial Serial { get { return m_Guild == null ? 0 : m_Guild.Id; } } public int TypeID { get { return 0; } } public long Position { get { return m_Position; } } public int Length { get { return m_Length; } } public GuildEntry(BaseGuild g, long pos, int length) { m_Guild = g; m_Position = pos; m_Length = length; } } private sealed class ItemEntry : IEntityEntry { private readonly Item m_Item; private readonly int m_TypeID; private readonly string m_TypeName; private readonly long m_Position; private readonly int m_Length; public Item Item { get { return m_Item; } } public Serial Serial { get { return m_Item == null ? Serial.MinusOne : m_Item.Serial; } } public int TypeID { get { return m_TypeID; } } public string TypeName { get { return m_TypeName; } } public long Position { get { return m_Position; } } public int Length { get { return m_Length; } } public ItemEntry(Item item, int typeID, string typeName, long pos, int length) { m_Item = item; m_TypeID = typeID; m_TypeName = typeName; m_Position = pos; m_Length = length; } } private sealed class MobileEntry : IEntityEntry { private readonly Mobile m_Mobile; private readonly int m_TypeID; private readonly string m_TypeName; private readonly long m_Position; private readonly int m_Length; public Mobile Mobile { get { return m_Mobile; } } public Serial Serial { get { return m_Mobile == null ? Serial.MinusOne : m_Mobile.Serial; } } public int TypeID { get { return m_TypeID; } } public string TypeName { get { return m_TypeName; } } public long Position { get { return m_Position; } } public int Length { get { return m_Length; } } public MobileEntry(Mobile mobile, int typeID, string typeName, long pos, int length) { m_Mobile = mobile; m_TypeID = typeID; m_TypeName = typeName; m_Position = pos; m_Length = length; } } public sealed class DataEntry : ICustomsEntry { private readonly SaveData _Data; private readonly int _TypeID; private readonly string _TypeName; private readonly long _Position; private readonly int _Length; public DataEntry(SaveData data, int typeID, string typeName, long pos, int length) { _Data = data; _TypeID = typeID; _TypeName = typeName; _Position = pos; _Length = length; } public SaveData Data { get { return _Data; } } public CustomSerial Serial { get { return _Data == null ? CustomSerial.MinusOne : _Data.Serial; } } public int TypeID { get { return _TypeID; } } public string TypeName { get { return _TypeName; } } public long Position { get { return _Position; } } public int Length { get { return _Length; } } } private static string m_LoadingType; public static string LoadingType { get { return m_LoadingType; } } private static readonly Type[] m_SerialTypeArray = new Type[1] {typeof(Serial)}; private static readonly Type[] _CustomSerialTypeArray = new Type[1] {typeof(CustomSerial)}; private static List<Tuple<ConstructorInfo, string>> ReadTypes(BinaryReader tdbReader) { int count = tdbReader.ReadInt32(); var types = new List<Tuple<ConstructorInfo, string>>(count); for (int i = 0; i < count; ++i) { string typeName = tdbReader.ReadString(); Type t = ScriptCompiler.FindTypeByFullName(typeName); if (t == null) { Console.WriteLine("failed"); if (!Core.Service) { Console.WriteLine("Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName); if (Console.ReadKey(true).Key == ConsoleKey.Y) { types.Add(null); Console.Write("World: Loading..."); continue; } Console.WriteLine("Types will not be deleted. An exception will be thrown."); } else { Console.WriteLine("Error: Type '{0}' was not found.", typeName); } throw new Exception(String.Format("Bad type '{0}'", typeName)); } ConstructorInfo ctor = t.GetConstructor(m_SerialTypeArray); ConstructorInfo cctor = t.GetConstructor(_CustomSerialTypeArray); if (ctor != null) { types.Add(new Tuple<ConstructorInfo, string>(ctor, typeName)); } else if (cctor != null) { types.Add(new Tuple<ConstructorInfo, string>(cctor, typeName)); } else { throw new Exception(String.Format("Type '{0}' does not have a serialization constructor", t)); } } return types; } public static void Load() { if (m_Loaded) { return; } m_Loaded = true; m_LoadingType = null; Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("World: Loading..."); Utility.PopColor(); Stopwatch watch = Stopwatch.StartNew(); m_Loading = true; _addQueue = new Queue<IEntity>(); _deleteQueue = new Queue<IEntity>(); _CustomsAddQueue = new Queue<ICustomsEntity>(); _CustomsDeleteQueue = new Queue<ICustomsEntity>(); int mobileCount = 0, itemCount = 0, guildCount = 0, dataCount = 0; var ctorArgs = new object[1]; var items = new List<ItemEntry>(); var mobiles = new List<MobileEntry>(); var guilds = new List<GuildEntry>(); var data = new List<DataEntry>(); if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath)) { using (FileStream idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); mobileCount = idxReader.ReadInt32(); m_Mobiles = new Dictionary<Serial, Mobile>(mobileCount); for (int i = 0; i < mobileCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } Mobile m = null; ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { ctorArgs[0] = (Serial)serial; m = (Mobile)(ctor.Invoke(ctorArgs)); } catch { } if (m != null) { mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length)); AddMobile(m); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Mobiles = new Dictionary<Serial, Mobile>(); } if (File.Exists(ItemIndexPath) && File.Exists(ItemTypesPath)) { using (FileStream idx = new FileStream(ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); using (FileStream tdb = new FileStream(ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader tdbReader = new BinaryReader(tdb); var types = ReadTypes(tdbReader); itemCount = idxReader.ReadInt32(); m_Items = new Dictionary<Serial, Item>(itemCount); for (int i = 0; i < itemCount; ++i) { int typeID = idxReader.ReadInt32(); int serial = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); var objs = types[typeID]; if (objs == null) { continue; } Item item = null; ConstructorInfo ctor = objs.Item1; string typeName = objs.Item2; try { ctorArgs[0] = (Serial)serial; item = (Item)(ctor.Invoke(ctorArgs)); } catch { } if (item != null) { items.Add(new ItemEntry(item, typeID, typeName, pos, length)); AddItem(item); } } tdbReader.Close(); } idxReader.Close(); } } else { m_Items = new Dictionary<Serial, Item>(); } if (File.Exists(GuildIndexPath)) { using (FileStream idx = new FileStream(GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader idxReader = new BinaryReader(idx); guildCount = idxReader.ReadInt32(); CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1); for (int i = 0; i < guildCount; ++i) { idxReader.ReadInt32(); //no typeid for guilds int id = idxReader.ReadInt32(); long pos = idxReader.ReadInt64(); int length = idxReader.ReadInt32(); createEventArgs.Id = id; EventSink.InvokeCreateGuild(createEventArgs); BaseGuild guild = createEventArgs.Guild; if (guild != null) { guilds.Add(new GuildEntry(guild, pos, length)); } } idxReader.Close(); } } if (File.Exists(DataIndexPath) && File.Exists(DataTypesPath)) { using (FileStream indexStream = new FileStream(DataIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader indexReader = new BinaryReader(indexStream); using (FileStream typeStream = new FileStream(DataTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader typeReader = new BinaryReader(typeStream); var types = ReadTypes(typeReader); dataCount = indexReader.ReadInt32(); _Data = new Dictionary<CustomSerial, SaveData>(dataCount); for (int i = 0; i < dataCount; ++i) { int typeID = indexReader.ReadInt32(); int serial = indexReader.ReadInt32(); long pos = indexReader.ReadInt64(); int length = indexReader.ReadInt32(); var objects = types[typeID]; if (objects == null) { continue; } SaveData saveData = null; ConstructorInfo ctor = objects.Item1; string typeName = objects.Item2; try { ctorArgs[0] = (CustomSerial)serial; saveData = (SaveData)(ctor.Invoke(ctorArgs)); } catch { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("Error loading {0}, Serial: {1}", typeName, serial); Utility.PopColor(); } if (saveData != null) { data.Add(new DataEntry(saveData, typeID, typeName, pos, length)); AddData(saveData); } } typeReader.Close(); } indexReader.Close(); } } else { _Data = new Dictionary<CustomSerial, SaveData>(); } bool failedMobiles = false, failedItems = false, failedGuilds = false, failedData = false; Type failedType = null; Serial failedSerial = Serial.Zero; CustomSerial failedCustomSerial = CustomSerial.Zero; Exception failed = null; int failedTypeID = 0; if (File.Exists(MobileDataPath)) { using (FileStream bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < mobiles.Count; ++i) { MobileEntry entry = mobiles[i]; Mobile m = entry.Mobile; if (m != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; m.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", m.GetType())); } } catch (Exception e) { mobiles.RemoveAt(i); failed = e; failedMobiles = true; failedType = m.GetType(); failedTypeID = entry.TypeID; failedSerial = m.Serial; break; } } } reader.Close(); } } if (!failedMobiles && File.Exists(ItemDataPath)) { using (FileStream bin = new FileStream(ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < items.Count; ++i) { ItemEntry entry = items[i]; Item item = entry.Item; if (item != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; item.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", item.GetType())); } } catch (Exception e) { items.RemoveAt(i); failed = e; failedItems = true; failedType = item.GetType(); failedTypeID = entry.TypeID; failedSerial = item.Serial; break; } } } reader.Close(); } } m_LoadingType = null; if (!failedMobiles && !failedItems && File.Exists(GuildDataPath)) { using (FileStream bin = new FileStream(GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin)); for (int i = 0; i < guilds.Count; ++i) { GuildEntry entry = guilds[i]; BaseGuild g = entry.Guild; if (g != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { g.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on Guild {0} *****", g.Id)); } } catch (Exception e) { guilds.RemoveAt(i); failed = e; failedGuilds = true; failedType = typeof(BaseGuild); failedTypeID = g.Id; failedSerial = g.Id; break; } } } reader.Close(); } } if (!failedMobiles && !failedItems && !failedGuilds && File.Exists(DataBinaryPath)) { using (FileStream stream = new FileStream(DataBinaryPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(stream)); for (int i = 0; i < data.Count; ++i) { DataEntry entry = data[i]; SaveData saveData = entry.Data; if (saveData != null) { reader.Seek(entry.Position, SeekOrigin.Begin); try { m_LoadingType = entry.TypeName; saveData.Deserialize(reader); if (reader.Position != (entry.Position + entry.Length)) { throw new Exception(String.Format("***** Bad serialize on {0} *****", saveData.GetType())); } } catch (Exception error) { data.RemoveAt(i); failed = error; failedData = true; failedType = saveData.GetType(); failedTypeID = entry.TypeID; failedCustomSerial = saveData.Serial; break; } } } reader.Close(); } } if (failedItems || failedMobiles || failedGuilds || failedData) { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("An error was encountered while loading a saved object"); Utility.PopColor(); Console.WriteLine(" - Type: {0}", failedType); if (failedSerial != Serial.Zero) { Console.WriteLine(" - Serial: {0}", failedSerial); } else { Console.WriteLine(" - Serial: {0}", failedCustomSerial); } if (!Core.Service) { Console.WriteLine("Delete the object? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedType != typeof(BaseGuild)) { Console.WriteLine("Delete all objects of that type? (y/n)"); if (Console.ReadKey(true).Key == ConsoleKey.Y) { if (failedMobiles) { for (int i = 0; i < mobiles.Count;) { if (mobiles[i].TypeID == failedTypeID) { mobiles.RemoveAt(i); } else { ++i; } } } else if (failedItems) { for (int i = 0; i < items.Count;) { if (items[i].TypeID == failedTypeID) { items.RemoveAt(i); } else { ++i; } } } else if (failedData) { for (int i = 0; i < data.Count;) { if (data[i].TypeID == failedTypeID) { data.RemoveAt(i); } else { ++i; } } } } } SaveIndex(mobiles, MobileIndexPath); SaveIndex(items, ItemIndexPath); SaveIndex(guilds, GuildIndexPath); SaveIndex(DataIndexPath, data); } Console.WriteLine("After pressing return an exception will be thrown and the server will terminate."); Console.ReadLine(); } else { Utility.PushColor(ConsoleColor.Red); Console.WriteLine("An exception will be thrown and the server will terminate."); Utility.PopColor(); } throw new Exception( String.Format( "Load failed (items={0}, mobiles={1}, guilds={2}, data={3}, type={4}, serial={5})", failedItems, failedMobiles, failedGuilds, failedData, failedType, (failedSerial != Serial.Zero ? failedSerial.ToString() : failedCustomSerial.ToString())), failed); } EventSink.InvokeWorldLoad(); m_Loading = false; ProcessSafetyQueues(); foreach (Item item in m_Items.Values) { if (item.Parent == null) { item.UpdateTotals(); } item.ClearProperties(); } foreach (Mobile m in m_Mobiles.Values) { m.UpdateRegion(); // Is this really needed? m.UpdateTotals(); m.ClearProperties(); } foreach (SaveData saveData in _Data.Values) { saveData.Prep(); } watch.Stop(); Utility.PushColor(ConsoleColor.Green); Console.WriteLine( "...done ({1} items, {2} mobiles, {3} customs) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, m_Items.Count, m_Mobiles.Count, _Data.Count); Utility.PopColor(); } private static void ProcessSafetyQueues() { while (_addQueue.Count > 0) { IEntity entity = _addQueue.Dequeue(); Item item = entity as Item; if (item != null) { AddItem(item); } else { Mobile mob = entity as Mobile; if (mob != null) { AddMobile(mob); } } } while (_deleteQueue.Count > 0) { IEntity entity = _deleteQueue.Dequeue(); Item item = entity as Item; if (item != null) { item.Delete(); } else { Mobile mob = entity as Mobile; if (mob != null) { mob.Delete(); } } } while (_CustomsAddQueue.Count > 0) { ICustomsEntity entity = _CustomsAddQueue.Dequeue(); SaveData data = entity as SaveData; if (data != null) { AddData(data); } } while (_CustomsDeleteQueue.Count > 0) { ICustomsEntity entity = _CustomsDeleteQueue.Dequeue(); SaveData data = entity as SaveData; if (data != null) { data.Delete(); } } } private static void AppendSafetyLog(string action, ICustomsEntity entity) { string message = String.Format( "Warning: Attempted to {1} {2} during world save." + "{0}This action could cause inconsistent state." + "{0}It is strongly advised that the offending scripts be corrected.", Environment.NewLine, action, entity); AppendSafetyLog(message); } private static void AppendSafetyLog(string action, IEntity entity) { string message = String.Format( "Warning: Attempted to {1} {2} during world save." + "{0}This action could cause inconsistent state." + "{0}It is strongly advised that the offending scripts be corrected.", Environment.NewLine, action, entity); AppendSafetyLog(message); } private static void AppendSafetyLog(string message) { Console.WriteLine(message); try { using (StreamWriter op = new StreamWriter("world-save-errors.log", true)) { op.WriteLine("{0}\t{1}", DateTime.UtcNow, message); op.WriteLine(new StackTrace(2).ToString()); op.WriteLine(); } } catch { } } private static void SaveIndex<T>(List<T> list, string path) where T : IEntityEntry { if (!Directory.Exists("Saves/Mobiles/")) { Directory.CreateDirectory("Saves/Mobiles/"); } if (!Directory.Exists("Saves/Items/")) { Directory.CreateDirectory("Saves/Items/"); } if (!Directory.Exists("Saves/Guilds/")) { Directory.CreateDirectory("Saves/Guilds/"); } using (FileStream idx = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { BinaryWriter idxWriter = new BinaryWriter(idx); idxWriter.Write(list.Count); for (int i = 0; i < list.Count; ++i) { T e = list[i]; idxWriter.Write(e.TypeID); idxWriter.Write(e.Serial); idxWriter.Write(e.Position); idxWriter.Write(e.Length); } idxWriter.Close(); } } private static void SaveIndex<T>(string path, List<T> list) where T : ICustomsEntry { if (!Directory.Exists("Saves/Customs/")) { Directory.CreateDirectory("Saves/Customs/"); } using (FileStream indexStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { BinaryWriter indexWriter = new BinaryWriter(indexStream); indexWriter.Write(list.Count); for (int i = 0; i < list.Count; ++i) { T e = list[i]; indexWriter.Write(e.TypeID); indexWriter.Write(e.Serial); indexWriter.Write(e.Position); indexWriter.Write(e.Length); } indexWriter.Close(); } } internal static int m_Saves; public static void Save() { Save(true, false); } public static void Save(bool message, bool permitBackgroundWrite) { if (m_Saving) { return; } //EventSink.InvokeBeforeWorldSave(new BeforeWorldSaveEventArgs()); ++m_Saves; NetState.FlushAll(); NetState.Pause(); WaitForWriteCompletion(); //Blocks Save until current disk flush is done. m_Saving = true; m_DiskWriteHandle.Reset(); if (message) { Broadcast(0x35, true, "The world is saving, please wait."); } SaveStrategy strategy = SaveStrategy.Acquire(); Console.WriteLine("Core: Using {0} save strategy", strategy.Name.ToLowerInvariant()); Console.WriteLine("World: Saving..."); Stopwatch watch = Stopwatch.StartNew(); if (!Directory.Exists("Saves/Mobiles/")) { Directory.CreateDirectory("Saves/Mobiles/"); } if (!Directory.Exists("Saves/Items/")) { Directory.CreateDirectory("Saves/Items/"); } if (!Directory.Exists("Saves/Guilds/")) { Directory.CreateDirectory("Saves/Guilds/"); } if (!Directory.Exists("Saves/Customs/")) { Directory.CreateDirectory("Saves/Customs/"); } /*using ( SaveMetrics metrics = new SaveMetrics() ) {*/ strategy.Save(null, permitBackgroundWrite); /*}*/ try { EventSink.InvokeWorldSave(new WorldSaveEventArgs(message)); } catch (Exception e) { throw new Exception("World Save event threw an exception. Save failed!", e); } watch.Stop(); m_Saving = false; if (!permitBackgroundWrite) { NotifyDiskWriteComplete(); //Sets the DiskWriteHandle. If we allow background writes, we leave this upto the individual save strategies. } ProcessSafetyQueues(); strategy.ProcessDecay(); Console.WriteLine("Save finished in {0:F2} seconds.", watch.Elapsed.TotalSeconds); if (message) { Broadcast(0x35, true, "World save complete. The entire process took {0:F1} seconds.", watch.Elapsed.TotalSeconds); } NetState.Resume(); EventSink.InvokeAfterWorldSave(new AfterWorldSaveEventArgs()); } internal static List<Type> m_ItemTypes = new List<Type>(); internal static List<Type> m_MobileTypes = new List<Type>(); internal static List<Type> _DataTypes = new List<Type>(); public static IEntity FindEntity(Serial serial) { if (serial.IsItem) { return FindItem(serial); } else if (serial.IsMobile) { return FindMobile(serial); } return null; } public static ICustomsEntity FindCustomEntity(CustomSerial serial) { if (serial.IsValid) { return GetData(serial); } return null; } public static Mobile FindMobile(Serial serial) { Mobile mob; m_Mobiles.TryGetValue(serial, out mob); return mob; } public static void AddMobile(Mobile m) { if (m_Saving) { AppendSafetyLog("add", m); _addQueue.Enqueue(m); } else { m_Mobiles[m.Serial] = m; } } public static Item FindItem(Serial serial) { Item item; m_Items.TryGetValue(serial, out item); return item; } public static void AddItem(Item item) { if (m_Saving) { AppendSafetyLog("add", item); _addQueue.Enqueue(item); } else { m_Items[item.Serial] = item; } } public static void RemoveMobile(Mobile m) { m_Mobiles.Remove(m.Serial); } public static void RemoveItem(Item item) { m_Items.Remove(item.Serial); } public static void AddData(SaveData data) { if (m_Saving) { AppendSafetyLog("add", data); _CustomsAddQueue.Enqueue(data); } else { _Data[data.Serial] = data; } } public static void RemoveData(SaveData data) { _Data.Remove(data.Serial); } public static SaveData GetData(CustomSerial serial) { SaveData data; _Data.TryGetValue(serial, out data); return data; } public static SaveData GetData(string name) { foreach (SaveData data in _Data.Values) { if (data.Name == name) { return data; } } return null; } public static SaveData GetData(Type type) { foreach (SaveData data in _Data.Values) { if (data.GetType() == type) { return data; } } return null; } public static List<SaveData> GetDataList(Type type) { var results = new List<SaveData>(); foreach (SaveData data in _Data.Values) { if (data.GetType() == type) { results.Add(data); } } return results; } public static List<SaveData> SearchData(string find) { var keywords = find.ToLower().Split(' '); var results = new List<SaveData>(); foreach (SaveData data in _Data.Values) { bool match = true; string name = data.Name.ToLower(); for (int i = 0; i < keywords.Length; i++) { if (name.IndexOf(keywords[i]) == -1) { match = false; } } if (match) { results.Add(data); } } return results; } public static SaveData GetCore(Type type) { foreach (SaveData data in _Data.Values) { if (data.GetType() == type) { return data; } } return null; } public static List<SaveData> GetCores(Type type) { var results = new List<SaveData>(); foreach (SaveData data in _Data.Values) { if (data.GetType() == type) { results.Add(data); } } return results; } public static BaseModule GetModule(Mobile mobile) { foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.LinkedMobile == mobile) { return module; } } } return null; } public static List<BaseModule> GetModules(Mobile mobile) { var results = new List<BaseModule>(); foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.LinkedMobile == mobile) { results.Add(module); } } } return results; } public static BaseModule GetModule(Item item) { foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.LinkedItem == item) { return module; } } } return null; } public static List<BaseModule> GetModules(Item item) { var results = new List<BaseModule>(); foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.LinkedItem == item) { results.Add(module); } } } return results; } public static BaseModule GetModule(Mobile mobile, string name) { foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.Name == name && module.LinkedMobile == mobile) { return module; } } } return null; } public static List<BaseModule> GetModules(Mobile mobile, string name) { var results = new List<BaseModule>(); foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.Name == name && module.LinkedMobile == mobile) { results.Add(module); } } } return results; } public static BaseModule GetModule(Mobile mobile, Type type) { foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.GetType() == type && module.LinkedMobile == mobile) { return module; } } } return null; } public static BaseModule GetModule(Item item, string name) { foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.Name == name && module.LinkedItem == item) { return module; } } } return null; } public static List<BaseModule> GetModules(Item item, string name) { var results = new List<BaseModule>(); foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.Name == name && module.LinkedItem == item) { results.Add(module); } } } return results; } public static BaseModule GetModule(Item item, Type type) { foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; if (module.GetType() == type && module.LinkedItem == item) { return module; } } } return null; } public static List<BaseModule> SearchModules(Mobile mobile, string text) { var keywords = text.ToLower().Split(' '); var results = new List<BaseModule>(); foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; bool match = true; string name = module.Name.ToLower(); for (int i = 0; i < keywords.Length; i++) { if (name.IndexOf(keywords[i]) == -1) { match = false; } } if (match && module.LinkedMobile == mobile) { results.Add(module); } } } return results; } public static List<BaseModule> SearchModules(Item item, string text) { var keywords = text.ToLower().Split(' '); var results = new List<BaseModule>(); foreach (SaveData data in _Data.Values) { if (data is BaseModule) { BaseModule module = data as BaseModule; bool match = true; string name = module.Name.ToLower(); for (int i = 0; i < keywords.Length; i++) { if (name.IndexOf(keywords[i]) == -1) { match = false; } } if (match && module.LinkedItem == item) { results.Add(module); } } } return results; } } }
psychoman78/Dragons-Legacy-Alpha-1.0a
Server/World.cs
C#
gpl-2.0
35,869
<?php /** * @package Joomla.Libraries * @subpackage Toolbar * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Renders a modal window button * * @package Joomla.Libraries * @subpackage Toolbar * @since 3.0 */ class JToolbarButtonPopup extends JToolbarButton { /** * Button type * * @var string */ protected $_name = 'Popup'; /** * Fetch the HTML for the button * * @param string $type Unused string, formerly button type. * @param string $name Modal name, used to generate element ID * @param string $text The link text * @param string $url URL for popup * @param integer $width Width of popup * @param integer $height Height of popup * @param integer $top Top attribute. [@deprecated Unused, will be removed in 4.0] * @param integer $left Left attribute. [@deprecated Unused, will be removed in 4.0] * @param string $onClose JavaScript for the onClose event. * @param string $title The title text * * @return string HTML string for the button * * @since 3.0 */ public function fetchButton($type = 'Modal', $name = '', $text = '', $url = '', $width = 640, $height = 480, $top = 0, $left = 0, $onClose = '', $title = '') { // If no $title is set, use the $text element if (strlen($title) == 0) { $title = $text; } // Store all data to the options array for use with JLayout $options = array(); $options['name'] = $name; $options['text'] = JText::_($text); $options['title'] = JText::_($title); $options['class'] = $this->fetchIconClass($name); $options['doTask'] = $this->_getCommand($url); // Instantiate a new JLayoutFile instance and render the layout $layout = new JLayoutFile('joomla.toolbar.popup'); $html = array(); $html[] = $layout->render($options); // Place modal div and scripts in a new div $html[] = '<div class="btn-group" style="width: 0; margin: 0">'; // Build the options array for the modal $params = array(); $params['title'] = $options['title']; $params['url'] = $options['doTask']; $params['height'] = $height; $params['width'] = $width; $html[] = JHtml::_('bootstrap.renderModal', 'modal-' . $name, $params); // If an $onClose event is passed, add it to the modal JS object if (strlen($onClose) >= 1) { $html[] = '<script>' . 'jQuery(\'#modal-' . $name . '\').on(\'hide\', function () {' . $onClose . ';});' . '</script>'; } $html[] = '</div>'; return implode("\n", $html); } /** * Get the button id * * @param string $type Button type * @param string $name Button name * * @return string Button CSS Id * * @since 3.0 */ public function fetchId($type, $name) { return $this->_parent->getName() . '-popup-' . $name; } /** * Get the JavaScript command for the button * * @param string $url URL for popup * * @return string JavaScript command string * * @since 3.0 */ private function _getCommand($url) { if (substr($url, 0, 4) !== 'http') { $url = JUri::base() . $url; } return $url; } }
01J/furcom
libraries/cms/toolbar/button/popup.php
PHP
gpl-2.0
3,416
/* * PluginBrowser.cpp - implementation of the plugin-browser * * Copyright (c) 2005-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - https://lmms.io * * 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 (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #include "PluginBrowser.h" #include <QHeaderView> #include <QLabel> #include <QLineEdit> #include <QMouseEvent> #include <QPainter> #include <QStyleOption> #include <QTreeWidget> #include "embed.h" #include "Engine.h" #include "gui_templates.h" #include "StringPairDrag.h" #include "PluginFactory.h" PluginBrowser::PluginBrowser( QWidget * _parent ) : SideBarWidget( tr( "Instrument Plugins" ), embed::getIconPixmap( "plugins" ).transformed( QTransform().rotate( 90 ) ), _parent ) { setWindowTitle( tr( "Instrument browser" ) ); m_view = new QWidget( contentParent() ); //m_view->setFrameShape( QFrame::NoFrame ); addContentWidget( m_view ); QVBoxLayout * view_layout = new QVBoxLayout( m_view ); view_layout->setMargin( 5 ); view_layout->setSpacing( 5 ); auto hint = new QLabel( tr( "Drag an instrument " "into either the Song-Editor, the " "Beat+Bassline Editor or into an " "existing instrument track." ), m_view ); hint->setWordWrap( true ); QLineEdit * searchBar = new QLineEdit( m_view ); searchBar->setPlaceholderText( "Search" ); searchBar->setMaxLength( 64 ); searchBar->setClearButtonEnabled( true ); m_descTree = new QTreeWidget( m_view ); m_descTree->setColumnCount( 1 ); m_descTree->header()->setVisible( false ); m_descTree->setIndentation( 10 ); m_descTree->setSelectionMode( QAbstractItemView::NoSelection ); connect( searchBar, SIGNAL( textEdited( const QString & ) ), this, SLOT( onFilterChanged( const QString & ) ) ); view_layout->addWidget( hint ); view_layout->addWidget( searchBar ); view_layout->addWidget( m_descTree ); // Add plugins to the tree addPlugins(); // Resize m_descTree->header()->setSectionResizeMode( QHeaderView::ResizeToContents ); // Hide empty roots updateRootVisibilities(); } void PluginBrowser::updateRootVisibility( int rootIndex ) { QTreeWidgetItem * root = m_descTree->topLevelItem( rootIndex ); root->setHidden( !root->childCount() ); } void PluginBrowser::updateRootVisibilities() { int rootCount = m_descTree->topLevelItemCount(); for (int rootIndex = 0; rootIndex < rootCount; ++rootIndex) { updateRootVisibility( rootIndex ); } } void PluginBrowser::onFilterChanged( const QString & filter ) { int rootCount = m_descTree->topLevelItemCount(); for (int rootIndex = 0; rootIndex < rootCount; ++rootIndex) { QTreeWidgetItem * root = m_descTree->topLevelItem( rootIndex ); int itemCount = root->childCount(); for (int itemIndex = 0; itemIndex < itemCount; ++itemIndex) { QTreeWidgetItem * item = root->child( itemIndex ); PluginDescWidget * descWidget = static_cast<PluginDescWidget *> (m_descTree->itemWidget( item, 0)); if (descWidget->name().contains(filter, Qt::CaseInsensitive)) { item->setHidden( false ); } else { item->setHidden( true ); } } } } void PluginBrowser::addPlugins() { // Add a root node to the plugin tree with the specified `label` and return it const auto addRoot = [this](auto label) { const auto root = new QTreeWidgetItem(); root->setText(0, label); m_descTree->addTopLevelItem(root); return root; }; // Add the plugin identified by `key` to the tree under the root node `root` const auto addPlugin = [this](const auto& key, auto root) { const auto item = new QTreeWidgetItem(); root->addChild(item); m_descTree->setItemWidget(item, 0, new PluginDescWidget(key, m_descTree)); }; // Remove any existing plugins from the tree m_descTree->clear(); // Fetch and sort all instrument plugin descriptors auto descs = pluginFactory->descriptors(Plugin::Instrument); std::sort(descs.begin(), descs.end(), [](auto d1, auto d2) { return qstricmp(d1->displayName, d2->displayName) < 0; } ); // Add a root node to the tree for native LMMS plugins const auto lmmsRoot = addRoot("LMMS"); lmmsRoot->setExpanded(true); // Add all of the descriptors to the tree for (const auto desc : descs) { if (desc->subPluginFeatures) { // Fetch and sort all subplugins for this plugin descriptor auto subPluginKeys = Plugin::Descriptor::SubPluginFeatures::KeyList{}; desc->subPluginFeatures->listSubPluginKeys(desc, subPluginKeys); std::sort(subPluginKeys.begin(), subPluginKeys.end(), [](const auto& l, const auto& r) { return QString::compare(l.displayName(), r.displayName(), Qt::CaseInsensitive) < 0; } ); // Create a root node for this plugin and add the subplugins under it const auto root = addRoot(desc->displayName); for (const auto& key : subPluginKeys) { addPlugin(key, root); } } else { addPlugin(Plugin::Descriptor::SubPluginFeatures::Key(desc, desc->name), lmmsRoot); } } } PluginDescWidget::PluginDescWidget(const PluginKey &_pk, QWidget * _parent ) : QWidget( _parent ), m_pluginKey( _pk ), m_logo( _pk.logo()->pixmap() ), m_mouseOver( false ) { setFixedHeight( DEFAULT_HEIGHT ); setMouseTracking( true ); setCursor( Qt::PointingHandCursor ); setToolTip(_pk.desc->subPluginFeatures ? _pk.description() : tr(_pk.desc->description)); } QString PluginDescWidget::name() const { return m_pluginKey.displayName(); } void PluginDescWidget::paintEvent( QPaintEvent * ) { QPainter p( this ); // Paint everything according to the style sheet QStyleOption o; o.initFrom( this ); style()->drawPrimitive( QStyle::PE_Widget, &o, &p, this ); // Draw the rest const int s = 16 + ( 32 * ( qBound( 24, height(), 60 ) - 24 ) ) / ( 60 - 24 ); const QSize logo_size( s, s ); QPixmap logo = m_logo.scaled( logo_size, Qt::KeepAspectRatio, Qt::SmoothTransformation ); p.drawPixmap( 4, 4, logo ); QFont f = p.font(); if ( m_mouseOver ) { f.setBold( true ); } p.setFont( f ); p.drawText( 10 + logo_size.width(), 15, m_pluginKey.displayName()); } void PluginDescWidget::enterEvent( QEvent * _e ) { m_mouseOver = true; QWidget::enterEvent( _e ); } void PluginDescWidget::leaveEvent( QEvent * _e ) { m_mouseOver = false; QWidget::leaveEvent( _e ); } void PluginDescWidget::mousePressEvent( QMouseEvent * _me ) { if ( _me->button() == Qt::LeftButton ) { Engine::setDndPluginKey(&m_pluginKey); new StringPairDrag("instrument", QString::fromUtf8(m_pluginKey.desc->name), m_logo, this); leaveEvent( _me ); } }
tresf/lmms
src/gui/PluginBrowser.cpp
C++
gpl-2.0
7,237
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2021 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "Projection.hpp" #include "Geo/FAISphere.hpp" #include "Math/Angle.hpp" #include <algorithm> Projection::Projection() noexcept { SetScale(1); } GeoPoint Projection::ScreenToGeo(PixelPoint src) const noexcept { assert(IsValid()); const auto p = screen_rotation.Rotate(src - screen_origin); GeoPoint g(PixelsToAngle(p.x), PixelsToAngle(p.y)); g.latitude = geo_location.latitude - g.latitude; /* paranoid sanity check to avoid integer overflow near the poles; our projection isn't doing well at all there; this check avoids assertion failures when the user pans all the way up/down */ const Angle latitude(std::min(Angle::Degrees(80), std::max(Angle::Degrees(-80), g.latitude))); g.longitude = geo_location.longitude + g.longitude * latitude.invfastcosine(); return g; } PixelPoint Projection::GeoToScreen(const GeoPoint &g) const noexcept { assert(IsValid()); const GeoPoint d = geo_location-g; const auto p = screen_rotation.Rotate(PixelPoint(int(g.latitude.fastcosine() * AngleToPixels(d.longitude)), (int)AngleToPixels(d.latitude))); PixelPoint sc; sc.x = screen_origin.x - p.x; sc.y = screen_origin.y + p.y; return sc; } void Projection::SetScale(const double _scale) noexcept { scale = _scale; // Calculate earth radius in pixels draw_scale = FAISphere::REARTH * scale; // Save inverted value for faster calculations inv_draw_scale = 1. / draw_scale; }
Exadios/xcsoar-exp
src/Projection/Projection.cpp
C++
gpl-2.0
2,452
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "Application.h" #include "threads/SystemClock.h" #include "system.h" #include "PluginDirectory.h" #include "addons/AddonManager.h" #include "addons/AddonInstaller.h" #include "addons/IAddon.h" #include "interfaces/generic/ScriptInvocationManager.h" #include "threads/SingleLock.h" #include "guilib/GUIWindowManager.h" #include "dialogs/GUIDialogBusy.h" #include "settings/Settings.h" #include "FileItem.h" #include "video/VideoInfoTag.h" #include "utils/log.h" #include "utils/JobManager.h" #include "utils/StringUtils.h" #include "messaging/ApplicationMessenger.h" #include "URL.h" using namespace XFILE; using namespace ADDON; using namespace KODI::MESSAGING; std::map<int, CPluginDirectory *> CPluginDirectory::globalHandles; int CPluginDirectory::handleCounter = 0; CCriticalSection CPluginDirectory::m_handleLock; CPluginDirectory::CScriptObserver::CScriptObserver(int scriptId, CEvent &event) : CThread("scriptobs"), m_scriptId(scriptId), m_event(event) { Create(); } void CPluginDirectory::CScriptObserver::Process() { while (!m_bStop) { if (!CScriptInvocationManager::GetInstance().IsRunning(m_scriptId)) { m_event.Set(); break; } Sleep(20); } } void CPluginDirectory::CScriptObserver::Abort() { m_bStop = true; } CPluginDirectory::CPluginDirectory() : m_cancelled(false) , m_success(false) , m_totalItems(0) { m_listItems = new CFileItemList; m_fileResult = new CFileItem; } CPluginDirectory::~CPluginDirectory(void) { delete m_listItems; delete m_fileResult; } int CPluginDirectory::getNewHandle(CPluginDirectory *cp) { CSingleLock lock(m_handleLock); int handle = ++handleCounter; globalHandles[handle] = cp; return handle; } void CPluginDirectory::removeHandle(int handle) { CSingleLock lock(m_handleLock); if (!globalHandles.erase(handle)) CLog::Log(LOGWARNING, "Attempt to erase invalid handle %i", handle); } CPluginDirectory *CPluginDirectory::dirFromHandle(int handle) { CSingleLock lock(m_handleLock); std::map<int, CPluginDirectory *>::iterator i = globalHandles.find(handle); if (i != globalHandles.end()) return i->second; CLog::Log(LOGWARNING, "Attempt to use invalid handle %i", handle); return NULL; } bool CPluginDirectory::StartScript(const std::string& strPath, bool retrievingDir) { CURL url(strPath); // try the plugin type first, and if not found, try an unknown type if (!CAddonMgr::GetInstance().GetAddon(url.GetHostName(), m_addon, ADDON_PLUGIN) && !CAddonMgr::GetInstance().GetAddon(url.GetHostName(), m_addon, ADDON_UNKNOWN) && !CAddonInstaller::GetInstance().InstallModal(url.GetHostName(), m_addon)) { CLog::Log(LOGERROR, "Unable to find plugin %s", url.GetHostName().c_str()); return false; } // get options std::string options = url.GetOptions(); url.SetOptions(""); // do this because we can then use the url to generate the basepath // which is passed to the plugin (and represents the share) std::string basePath(url.Get()); // reset our wait event, and grab a new handle m_fetchComplete.Reset(); int handle = getNewHandle(this); // clear out our status variables m_fileResult->Reset(); m_listItems->Clear(); m_listItems->SetPath(strPath); m_listItems->SetLabel(m_addon->Name()); m_cancelled = false; m_success = false; m_totalItems = 0; // setup our parameters to send the script std::string strHandle = StringUtils::Format("%i", handle); std::vector<std::string> argv; argv.push_back(basePath); argv.push_back(strHandle); argv.push_back(options); // run the script CLog::Log(LOGDEBUG, "%s - calling plugin %s('%s','%s','%s')", __FUNCTION__, m_addon->Name().c_str(), argv[0].c_str(), argv[1].c_str(), argv[2].c_str()); bool success = false; std::string file = m_addon->LibPath(); int id = CScriptInvocationManager::GetInstance().ExecuteAsync(file, m_addon, argv); if (id >= 0) { // wait for our script to finish std::string scriptName = m_addon->Name(); success = WaitOnScriptResult(file, id, scriptName, retrievingDir); } else CLog::Log(LOGERROR, "Unable to run plugin %s", m_addon->Name().c_str()); // free our handle removeHandle(handle); return success; } bool CPluginDirectory::GetPluginResult(const std::string& strPath, CFileItem &resultItem) { CURL url(strPath); CPluginDirectory newDir; bool success = newDir.StartScript(strPath, false); if (success) { // update the play path and metadata, saving the old one as needed if (!resultItem.HasProperty("original_listitem_url")) resultItem.SetProperty("original_listitem_url", resultItem.GetPath()); resultItem.SetPath(newDir.m_fileResult->GetPath()); resultItem.SetMimeType(newDir.m_fileResult->GetMimeType()); resultItem.UpdateInfo(*newDir.m_fileResult); if (newDir.m_fileResult->HasVideoInfoTag() && newDir.m_fileResult->GetVideoInfoTag()->m_resumePoint.IsSet()) resultItem.m_lStartOffset = STARTOFFSET_RESUME; // resume point set in the resume item, so force resume } return success; } bool CPluginDirectory::AddItem(int handle, const CFileItem *item, int totalItems) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (!dir) return false; CFileItemPtr pItem(new CFileItem(*item)); dir->m_listItems->Add(pItem); dir->m_totalItems = totalItems; return !dir->m_cancelled; } bool CPluginDirectory::AddItems(int handle, const CFileItemList *items, int totalItems) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (!dir) return false; CFileItemList pItemList; pItemList.Copy(*items); dir->m_listItems->Append(pItemList); dir->m_totalItems = totalItems; return !dir->m_cancelled; } void CPluginDirectory::EndOfDirectory(int handle, bool success, bool replaceListing, bool cacheToDisc) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (!dir) return; // set cache to disc dir->m_listItems->SetCacheToDisc(cacheToDisc ? CFileItemList::CACHE_IF_SLOW : CFileItemList::CACHE_NEVER); dir->m_success = success; dir->m_listItems->SetReplaceListing(replaceListing); if (!dir->m_listItems->HasSortDetails()) dir->m_listItems->AddSortMethod(SortByNone, 552, LABEL_MASKS("%L", "%D")); // set the event to mark that we're done dir->m_fetchComplete.Set(); } void CPluginDirectory::AddSortMethod(int handle, SORT_METHOD sortMethod, const std::string &label2Mask) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (!dir) return; //! @todo Add all sort methods and fix which labels go on the right or left switch(sortMethod) { case SORT_METHOD_LABEL: case SORT_METHOD_LABEL_IGNORE_THE: { dir->m_listItems->AddSortMethod(SortByLabel, 551, LABEL_MASKS("%T", label2Mask), CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone); break; } case SORT_METHOD_TITLE: case SORT_METHOD_TITLE_IGNORE_THE: { dir->m_listItems->AddSortMethod(SortByTitle, 556, LABEL_MASKS("%T", label2Mask), CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone); break; } case SORT_METHOD_ARTIST: case SORT_METHOD_ARTIST_IGNORE_THE: { dir->m_listItems->AddSortMethod(SortByArtist, 557, LABEL_MASKS("%T", "%A"), CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone); break; } case SORT_METHOD_ALBUM: case SORT_METHOD_ALBUM_IGNORE_THE: { dir->m_listItems->AddSortMethod(SortByAlbum, 558, LABEL_MASKS("%T", "%B"), CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone); break; } case SORT_METHOD_DATE: { dir->m_listItems->AddSortMethod(SortByDate, 552, LABEL_MASKS("%T", "%J")); break; } case SORT_METHOD_BITRATE: { dir->m_listItems->AddSortMethod(SortByBitrate, 623, LABEL_MASKS("%T", "%X")); break; } case SORT_METHOD_SIZE: { dir->m_listItems->AddSortMethod(SortBySize, 553, LABEL_MASKS("%T", "%I")); break; } case SORT_METHOD_FILE: { dir->m_listItems->AddSortMethod(SortByFile, 561, LABEL_MASKS("%T", label2Mask)); break; } case SORT_METHOD_TRACKNUM: { dir->m_listItems->AddSortMethod(SortByTrackNumber, 554, LABEL_MASKS("[%N. ]%T", label2Mask)); break; } case SORT_METHOD_DURATION: case SORT_METHOD_VIDEO_RUNTIME: { dir->m_listItems->AddSortMethod(SortByTime, 180, LABEL_MASKS("%T", "%D")); break; } case SORT_METHOD_VIDEO_RATING: case SORT_METHOD_SONG_RATING: { dir->m_listItems->AddSortMethod(SortByRating, 563, LABEL_MASKS("%T", "%R")); break; } case SORT_METHOD_YEAR: { dir->m_listItems->AddSortMethod(SortByYear, 562, LABEL_MASKS("%T", "%Y")); break; } case SORT_METHOD_GENRE: { dir->m_listItems->AddSortMethod(SortByGenre, 515, LABEL_MASKS("%T", "%G")); break; } case SORT_METHOD_COUNTRY: { dir->m_listItems->AddSortMethod(SortByCountry, 574, LABEL_MASKS("%T", "%G")); break; } case SORT_METHOD_VIDEO_TITLE: { dir->m_listItems->AddSortMethod(SortByTitle, 369, LABEL_MASKS("%T", label2Mask)); break; } case SORT_METHOD_VIDEO_SORT_TITLE: case SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE: { dir->m_listItems->AddSortMethod(SortBySortTitle, 556, LABEL_MASKS("%T", label2Mask), CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone); break; } case SORT_METHOD_MPAA_RATING: { dir->m_listItems->AddSortMethod(SortByMPAA, 20074, LABEL_MASKS("%T", "%O")); break; } case SORT_METHOD_STUDIO: case SORT_METHOD_STUDIO_IGNORE_THE: { dir->m_listItems->AddSortMethod(SortByStudio, 572, LABEL_MASKS("%T", "%U"), CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone); break; } case SORT_METHOD_PROGRAM_COUNT: { dir->m_listItems->AddSortMethod(SortByProgramCount, 567, LABEL_MASKS("%T", "%C")); break; } case SORT_METHOD_UNSORTED: { dir->m_listItems->AddSortMethod(SortByNone, 571, LABEL_MASKS("%T", label2Mask)); break; } case SORT_METHOD_NONE: { dir->m_listItems->AddSortMethod(SortByNone, 552, LABEL_MASKS("%T", label2Mask)); break; } case SORT_METHOD_DRIVE_TYPE: { dir->m_listItems->AddSortMethod(SortByDriveType, 564, LABEL_MASKS()); // Preformatted break; } case SORT_METHOD_PLAYLIST_ORDER: { std::string strTrack=CSettings::GetInstance().GetString(CSettings::SETTING_MUSICFILES_TRACKFORMAT); dir->m_listItems->AddSortMethod(SortByPlaylistOrder, 559, LABEL_MASKS(strTrack, "%D")); break; } case SORT_METHOD_EPISODE: { dir->m_listItems->AddSortMethod(SortByEpisodeNumber, 20359, LABEL_MASKS("%E. %T","%R")); break; } case SORT_METHOD_PRODUCTIONCODE: { //dir->m_listItems.AddSortMethod(SORT_METHOD_PRODUCTIONCODE,20368,LABEL_MASKS("%E. %T","%P", "%E. %T","%P")); dir->m_listItems->AddSortMethod(SortByProductionCode, 20368, LABEL_MASKS("%H. %T","%P", "%H. %T","%P")); break; } case SORT_METHOD_LISTENERS: { dir->m_listItems->AddSortMethod(SortByListeners, 20455, LABEL_MASKS("%T","%W")); break; } case SORT_METHOD_DATEADDED: { dir->m_listItems->AddSortMethod(SortByDateAdded, 570, LABEL_MASKS("%T", "%a")); break; } case SORT_METHOD_FULLPATH: { dir->m_listItems->AddSortMethod(SortByPath, 573, LABEL_MASKS("%T", label2Mask)); break; } case SORT_METHOD_LABEL_IGNORE_FOLDERS: { dir->m_listItems->AddSortMethod(SortByLabel, SortAttributeIgnoreFolders, 551, LABEL_MASKS("%T", label2Mask)); break; } case SORT_METHOD_LASTPLAYED: { dir->m_listItems->AddSortMethod(SortByLastPlayed, 568, LABEL_MASKS("%T", "%G")); break; } case SORT_METHOD_PLAYCOUNT: { dir->m_listItems->AddSortMethod(SortByPlaycount, 567, LABEL_MASKS("%T", "%V")); break; } case SORT_METHOD_CHANNEL: { dir->m_listItems->AddSortMethod(SortByChannel, 19029, LABEL_MASKS("%T", label2Mask)); break; } default: break; } } bool CPluginDirectory::GetDirectory(const CURL& url, CFileItemList& items) { const std::string pathToUrl(url.Get()); bool success = StartScript(pathToUrl, true); // append the items to the list items.Assign(*m_listItems, true); // true to keep the current items m_listItems->Clear(); return success; } bool CPluginDirectory::RunScriptWithParams(const std::string& strPath) { CURL url(strPath); if (url.GetHostName().empty()) // called with no script - should never happen return false; AddonPtr addon; if (!CAddonMgr::GetInstance().GetAddon(url.GetHostName(), addon, ADDON_PLUGIN) && !CAddonInstaller::GetInstance().InstallModal(url.GetHostName(), addon)) { CLog::Log(LOGERROR, "Unable to find plugin %s", url.GetHostName().c_str()); return false; } // options std::string options = url.GetOptions(); url.SetOptions(""); // do this because we can then use the url to generate the basepath // which is passed to the plugin (and represents the share) std::string basePath(url.Get()); // setup our parameters to send the script std::string strHandle = StringUtils::Format("%i", -1); std::vector<std::string> argv; argv.push_back(basePath); argv.push_back(strHandle); argv.push_back(options); // run the script CLog::Log(LOGDEBUG, "%s - calling plugin %s('%s','%s','%s')", __FUNCTION__, addon->Name().c_str(), argv[0].c_str(), argv[1].c_str(), argv[2].c_str()); if (CScriptInvocationManager::GetInstance().ExecuteAsync(addon->LibPath(), addon, argv) >= 0) return true; else CLog::Log(LOGERROR, "Unable to run plugin %s", addon->Name().c_str()); return false; } bool CPluginDirectory::WaitOnScriptResult(const std::string &scriptPath, int scriptId, const std::string &scriptName, bool retrievingDir) { bool cancelled = false; // CPluginDirectory::GetDirectory can be called from the main and other threads. // If called form the main thread, we need to bring up the BusyDialog in order to // keep the render loop alive if (g_application.IsCurrentThread()) { if (!m_fetchComplete.WaitMSec(20)) { CScriptObserver scriptObs(scriptId, m_fetchComplete); if (!CGUIDialogBusy::WaitOnEvent(m_fetchComplete, 200)) { cancelled = true; } scriptObs.Abort(); } } else { // kill the script if it does not return within 30 seconds if (!m_fetchComplete.WaitMSec(30000)) { cancelled = true; } } if (cancelled) { // cancel our script if (scriptId != -1 && CScriptInvocationManager::GetInstance().IsRunning(scriptId)) { CLog::Log(LOGDEBUG, "%s- cancelling plugin %s (id=%d)", __FUNCTION__, scriptName.c_str(), scriptId); CScriptInvocationManager::GetInstance().Stop(scriptId); } } return !cancelled && m_success; } void CPluginDirectory::SetResolvedUrl(int handle, bool success, const CFileItem *resultItem) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (!dir) return; dir->m_success = success; *dir->m_fileResult = *resultItem; // set the event to mark that we're done dir->m_fetchComplete.Set(); } std::string CPluginDirectory::GetSetting(int handle, const std::string &strID) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if(dir && dir->m_addon) return dir->m_addon->GetSetting(strID); else return ""; } void CPluginDirectory::SetSetting(int handle, const std::string &strID, const std::string &value) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if(dir && dir->m_addon) dir->m_addon->UpdateSetting(strID, value); } void CPluginDirectory::SetContent(int handle, const std::string &strContent) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (dir) dir->m_listItems->SetContent(strContent); } void CPluginDirectory::SetProperty(int handle, const std::string &strProperty, const std::string &strValue) { CSingleLock lock(m_handleLock); CPluginDirectory *dir = dirFromHandle(handle); if (!dir) return; if (strProperty == "fanart_image") dir->m_listItems->SetArt("fanart", strValue); else dir->m_listItems->SetProperty(strProperty, strValue); } void CPluginDirectory::CancelDirectory() { m_cancelled = true; } float CPluginDirectory::GetProgress() const { if (m_totalItems > 0) return (m_listItems->Size() * 100.0f) / m_totalItems; return 0.0f; }
MarkMuth/xbmc
xbmc/filesystem/PluginDirectory.cpp
C++
gpl-2.0
18,243
namespace Server.Items { public class LocalMap : MapItem { [Constructable] public LocalMap() { SetDisplay(0, 0, 5119, 4095, 400, 400); } public LocalMap(Serial serial) : base(serial) { } public override int LabelNumber => 1015230;// local map public override void CraftInit(Mobile from) { double skillValue = from.Skills[SkillName.Cartography].Value; int dist = 64 + (int)(skillValue * 2); SetDisplay(from.X - dist, from.Y - dist, from.X + dist, from.Y + dist, 200, 200); } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Argalep/ServUO
Scripts/Items/Tools/LocalMap.cs
C#
gpl-2.0
955
<?php class NpdefctbMapBuilder { const CLASS_NAME = 'lib.model.nomina.map.NpdefctbMapBuilder'; private $dbMap; public function isBuilt() { return ($this->dbMap !== null); } public function getDatabaseMap() { return $this->dbMap; } public function doBuild() { $this->dbMap = Propel::getDatabaseMap('propel'); $tMap = $this->dbMap->addTable('npdefctb'); $tMap->setPhpName('Npdefctb'); $tMap->setUseIdGenerator(true); $tMap->setPrimaryKeyMethodInfo('npdefctb_SEQ'); $tMap->addColumn('CODUNI', 'Coduni', 'string', CreoleTypes::VARCHAR, true, 16); $tMap->addColumn('CODCON', 'Codcon', 'string', CreoleTypes::VARCHAR, true, 3); $tMap->addColumn('CODCTA', 'Codcta', 'string', CreoleTypes::VARCHAR, true, 18); $tMap->addColumn('NOMCTA', 'Nomcta', 'string', CreoleTypes::VARCHAR, true, 30); $tMap->addColumn('DEBCRE', 'Debcre', 'string', CreoleTypes::VARCHAR, true, 30); $tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null); } }
cidesa/siga-universitario
lib/model/nomina/map/NpdefctbMapBuilder.php
PHP
gpl-2.0
1,007
/** * Librerías Javascript * * @package Roraima * @author $Author$ <desarrollo@cidesa.com.ve> * @version SVN: $Id$ * * @copyright Copyright 2007, Cide S.A. * @license http://opensource.org/licenses/gpl-2.0.php GPLv2 */ function codigopadre(){ var codigo=$('cideftit_codpre').value; if (codigo.length==2){ codigo=codigo+"-"; } new Ajax.Request(getUrlModuloAjax(),{asynchronous:true, evalScripts:false, onComplete:function(request, json){AjaxJSON(request, json)}, parameters:'ajax=1&codigo='+codigo}); }
cidesa/siga-universitario
web/js/ingresos/ingtitpre.js
JavaScript
gpl-2.0
537
<?php /** * Internationalisation code. * * 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 Language */ /** * @defgroup Language Language */ if ( !defined( 'MEDIAWIKI' ) ) { echo "This file is part of MediaWiki, it is not a valid entry point.\n"; exit( 1 ); } if ( function_exists( 'mb_strtoupper' ) ) { mb_internal_encoding( 'UTF-8' ); } /** * Internationalisation code * @ingroup Language */ class Language { /** * @var LanguageConverter */ public $mConverter; public $mVariants, $mCode, $mLoaded = false; public $mMagicExtensions = array(), $mMagicHookDone = false; private $mHtmlCode = null, $mParentLanguage = false; public $dateFormatStrings = array(); public $mExtendedSpecialPageAliases; protected $namespaceNames, $mNamespaceIds, $namespaceAliases; /** * ReplacementArray object caches */ public $transformData = array(); /** * @var LocalisationCache */ static public $dataCache; static public $mLangObjCache = array(); static public $mWeekdayMsgs = array( 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ); static public $mWeekdayAbbrevMsgs = array( 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ); static public $mMonthMsgs = array( 'january', 'february', 'march', 'april', 'may_long', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ); static public $mMonthGenMsgs = array( 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen', 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen', 'december-gen' ); static public $mMonthAbbrevMsgs = array( 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec' ); static public $mIranianCalendarMonthMsgs = array( 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3', 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6', 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9', 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12' ); static public $mHebrewCalendarMonthMsgs = array( 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3', 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6', 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9', 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12', 'hebrew-calendar-m6a', 'hebrew-calendar-m6b' ); static public $mHebrewCalendarMonthGenMsgs = array( 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen', 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen', 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen', 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen', 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen' ); static public $mHijriCalendarMonthMsgs = array( 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3', 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6', 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9', 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12' ); /** * @since 1.20 * @var array */ static public $durationIntervals = array( 'millennia' => 31556952000, 'centuries' => 3155695200, 'decades' => 315569520, 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 ) 'weeks' => 604800, 'days' => 86400, 'hours' => 3600, 'minutes' => 60, 'seconds' => 1, ); /** * Cache for language fallbacks. * @see Language::getFallbacksIncludingSiteLanguage * @since 1.21 * @var array */ static private $fallbackLanguageCache = array(); /** * Cache for language names * @var MapCacheLRU|null */ static private $languageNameCache; /** * Get a cached or new language object for a given language code * @param string $code * @return Language */ static function factory( $code ) { global $wgDummyLanguageCodes, $wgLangObjCacheSize; if ( isset( $wgDummyLanguageCodes[$code] ) ) { $code = $wgDummyLanguageCodes[$code]; } // get the language object to process $langObj = isset( self::$mLangObjCache[$code] ) ? self::$mLangObjCache[$code] : self::newFromCode( $code ); // merge the language object in to get it up front in the cache self::$mLangObjCache = array_merge( array( $code => $langObj ), self::$mLangObjCache ); // get rid of the oldest ones in case we have an overflow self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true ); return $langObj; } /** * Create a language object for a given language code * @param string $code * @throws MWException * @return Language */ protected static function newFromCode( $code ) { // Protect against path traversal below if ( !Language::isValidCode( $code ) || strcspn( $code, ":/\\\000" ) !== strlen( $code ) ) { throw new MWException( "Invalid language code \"$code\"" ); } if ( !Language::isValidBuiltInCode( $code ) ) { // It's not possible to customise this code with class files, so // just return a Language object. This is to support uselang= hacks. $lang = new Language; $lang->setCode( $code ); return $lang; } // Check if there is a language class for the code $class = self::classFromCode( $code ); self::preloadLanguageClass( $class ); if ( class_exists( $class ) ) { $lang = new $class; return $lang; } // Keep trying the fallback list until we find an existing class $fallbacks = Language::getFallbacksFor( $code ); foreach ( $fallbacks as $fallbackCode ) { if ( !Language::isValidBuiltInCode( $fallbackCode ) ) { throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" ); } $class = self::classFromCode( $fallbackCode ); self::preloadLanguageClass( $class ); if ( class_exists( $class ) ) { $lang = Language::newFromCode( $fallbackCode ); $lang->setCode( $code ); return $lang; } } throw new MWException( "Invalid fallback sequence for language '$code'" ); } /** * Checks whether any localisation is available for that language tag * in MediaWiki (MessagesXx.php exists). * * @param string $code Language tag (in lower case) * @return bool Whether language is supported * @since 1.21 */ public static function isSupportedLanguage( $code ) { return self::isValidBuiltInCode( $code ) && ( is_readable( self::getMessagesFileName( $code ) ) || is_readable( self::getJsonMessagesFileName( $code ) ) ); } /** * Returns true if a language code string is a well-formed language tag * according to RFC 5646. * This function only checks well-formedness; it doesn't check that * language, script or variant codes actually exist in the repositories. * * Based on regexes by Mark Davis of the Unicode Consortium: * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt * * @param string $code * @param bool $lenient Whether to allow '_' as separator. The default is only '-'. * * @return bool * @since 1.21 */ public static function isWellFormedLanguageTag( $code, $lenient = false ) { $alpha = '[a-z]'; $digit = '[0-9]'; $alphanum = '[a-z0-9]'; $x = 'x'; # private use singleton $singleton = '[a-wy-z]'; # other singleton $s = $lenient ? '[-_]' : '-'; $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}"; $script = "$alpha{4}"; # ISO 15924 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})"; $extension = "$singleton(?:$s$alphanum{2,8})+"; $privateUse = "$x(?:$s$alphanum{1,8})+"; # Define certain grandfathered codes, since otherwise the regex is pretty useless. # Since these are limited, this is safe even later changes to the registry -- # the only oddity is that it might change the type of the tag, and thus # the results from the capturing groups. # http://www.iana.org/assignments/language-subtag-registry $grandfathered = "en{$s}GB{$s}oed" . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)" . "|no{$s}(?:bok|nyn)" . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)" . "|zh{$s}min{$s}nan"; $variantList = "$variant(?:$s$variant)*"; $extensionList = "$extension(?:$s$extension)*"; $langtag = "(?:($language)" . "(?:$s$script)?" . "(?:$s$region)?" . "(?:$s$variantList)?" . "(?:$s$extensionList)?" . "(?:$s$privateUse)?)"; # The final breakdown, with capturing groups for each of these components # The variants, extensions, grandfathered, and private-use may have interior '-' $root = "^(?:$langtag|$privateUse|$grandfathered)$"; return (bool)preg_match( "/$root/", strtolower( $code ) ); } /** * Returns true if a language code string is of a valid form, whether or * not it exists. This includes codes which are used solely for * customisation via the MediaWiki namespace. * * @param string $code * * @return bool */ public static function isValidCode( $code ) { static $cache = array(); if ( isset( $cache[$code] ) ) { return $cache[$code]; } // People think language codes are html safe, so enforce it. // Ideally we should only allow a-zA-Z0-9- // but, .+ and other chars are often used for {{int:}} hacks // see bugs 37564, 37587, 36938 $cache[$code] = strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code ) && !preg_match( MediaWikiTitleCodec::getTitleInvalidRegex(), $code ); return $cache[$code]; } /** * Returns true if a language code is of a valid form for the purposes of * internal customisation of MediaWiki, via Messages*.php or *.json. * * @param string $code * * @throws MWException * @since 1.18 * @return bool */ public static function isValidBuiltInCode( $code ) { if ( !is_string( $code ) ) { if ( is_object( $code ) ) { $addmsg = " of class " . get_class( $code ); } else { $addmsg = ''; } $type = gettype( $code ); throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" ); } return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code ); } /** * Returns true if a language code is an IETF tag known to MediaWiki. * * @param string $tag * * @since 1.21 * @return bool */ public static function isKnownLanguageTag( $tag ) { static $coreLanguageNames; // Quick escape for invalid input to avoid exceptions down the line // when code tries to process tags which are not valid at all. if ( !self::isValidBuiltInCode( $tag ) ) { return false; } if ( $coreLanguageNames === null ) { global $IP; include "$IP/languages/Names.php"; } if ( isset( $coreLanguageNames[$tag] ) || self::fetchLanguageName( $tag, $tag ) !== '' ) { return true; } return false; } /** * @param string $code * @return string Name of the language class */ public static function classFromCode( $code ) { if ( $code == 'en' ) { return 'Language'; } else { return 'Language' . str_replace( '-', '_', ucfirst( $code ) ); } } /** * Includes language class files * * @param string $class Name of the language class */ public static function preloadLanguageClass( $class ) { global $IP; if ( $class === 'Language' ) { return; } if ( file_exists( "$IP/languages/classes/$class.php" ) ) { include_once "$IP/languages/classes/$class.php"; } } /** * Get the LocalisationCache instance * * @return LocalisationCache */ public static function getLocalisationCache() { if ( is_null( self::$dataCache ) ) { global $wgLocalisationCacheConf; $class = $wgLocalisationCacheConf['class']; self::$dataCache = new $class( $wgLocalisationCacheConf ); } return self::$dataCache; } function __construct() { $this->mConverter = new FakeConverter( $this ); // Set the code to the name of the descendant if ( get_class( $this ) == 'Language' ) { $this->mCode = 'en'; } else { $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) ); } self::getLocalisationCache(); } /** * Reduce memory usage */ function __destruct() { foreach ( $this as $name => $value ) { unset( $this->$name ); } } /** * Hook which will be called if this is the content language. * Descendants can use this to register hook functions or modify globals */ function initContLang() { } /** * @return array * @since 1.19 */ function getFallbackLanguages() { return self::getFallbacksFor( $this->mCode ); } /** * Exports $wgBookstoreListEn * @return array */ function getBookstoreList() { return self::$dataCache->getItem( $this->mCode, 'bookstoreList' ); } /** * Returns an array of localised namespaces indexed by their numbers. If the namespace is not * available in localised form, it will be included in English. * * @return array */ public function getNamespaces() { if ( is_null( $this->namespaceNames ) ) { global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces; $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' ); $validNamespaces = MWNamespace::getCanonicalNamespaces(); $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces; $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace; if ( $wgMetaNamespaceTalk ) { $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk; } else { $talk = $this->namespaceNames[NS_PROJECT_TALK]; $this->namespaceNames[NS_PROJECT_TALK] = $this->fixVariableInNamespace( $talk ); } # Sometimes a language will be localised but not actually exist on this wiki. foreach ( $this->namespaceNames as $key => $text ) { if ( !isset( $validNamespaces[$key] ) ) { unset( $this->namespaceNames[$key] ); } } # The above mixing may leave namespaces out of canonical order. # Re-order by namespace ID number... ksort( $this->namespaceNames ); Hooks::run( 'LanguageGetNamespaces', array( &$this->namespaceNames ) ); } return $this->namespaceNames; } /** * Arbitrarily set all of the namespace names at once. Mainly used for testing * @param array $namespaces Array of namespaces (id => name) */ public function setNamespaces( array $namespaces ) { $this->namespaceNames = $namespaces; $this->mNamespaceIds = null; } /** * Resets all of the namespace caches. Mainly used for testing */ public function resetNamespaces() { $this->namespaceNames = null; $this->mNamespaceIds = null; $this->namespaceAliases = null; } /** * A convenience function that returns the same thing as * getNamespaces() except with the array values changed to ' ' * where it found '_', useful for producing output to be displayed * e.g. in <select> forms. * * @return array */ function getFormattedNamespaces() { $ns = $this->getNamespaces(); foreach ( $ns as $k => $v ) { $ns[$k] = strtr( $v, '_', ' ' ); } return $ns; } /** * Get a namespace value by key * <code> * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI ); * echo $mw_ns; // prints 'MediaWiki' * </code> * * @param int $index The array key of the namespace to return * @return string|bool String if the namespace value exists, otherwise false */ function getNsText( $index ) { $ns = $this->getNamespaces(); return isset( $ns[$index] ) ? $ns[$index] : false; } /** * A convenience function that returns the same thing as * getNsText() except with '_' changed to ' ', useful for * producing output. * * <code> * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK ); * echo $mw_ns; // prints 'MediaWiki talk' * </code> * * @param int $index The array key of the namespace to return * @return string Namespace name without underscores (empty string if namespace does not exist) */ function getFormattedNsText( $index ) { $ns = $this->getNsText( $index ); return strtr( $ns, '_', ' ' ); } /** * Returns gender-dependent namespace alias if available. * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces * @param int $index Namespace index * @param string $gender Gender key (male, female... ) * @return string * @since 1.18 */ function getGenderNsText( $index, $gender ) { global $wgExtraGenderNamespaces; $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' ); return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index ); } /** * Whether this language uses gender-dependent namespace aliases. * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces * @return bool * @since 1.18 */ function needsGenderDistinction() { global $wgExtraGenderNamespaces, $wgExtraNamespaces; if ( count( $wgExtraGenderNamespaces ) > 0 ) { // $wgExtraGenderNamespaces overrides everything return true; } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) { /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future // $wgExtraNamespaces overrides any gender aliases specified in i18n files return false; } else { // Check what is in i18n files $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' ); return count( $aliases ) > 0; } } /** * Get a namespace key by value, case insensitive. * Only matches namespace names for the current language, not the * canonical ones defined in Namespace.php. * * @param string $text * @return int|bool An integer if $text is a valid value otherwise false */ function getLocalNsIndex( $text ) { $lctext = $this->lc( $text ); $ids = $this->getNamespaceIds(); return isset( $ids[$lctext] ) ? $ids[$lctext] : false; } /** * @return array */ function getNamespaceAliases() { if ( is_null( $this->namespaceAliases ) ) { $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' ); if ( !$aliases ) { $aliases = array(); } else { foreach ( $aliases as $name => $index ) { if ( $index === NS_PROJECT_TALK ) { unset( $aliases[$name] ); $name = $this->fixVariableInNamespace( $name ); $aliases[$name] = $index; } } } global $wgExtraGenderNamespaces; $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' ); foreach ( $genders as $index => $forms ) { foreach ( $forms as $alias ) { $aliases[$alias] = $index; } } # Also add converted namespace names as aliases, to avoid confusion. $convertedNames = array(); foreach ( $this->getVariants() as $variant ) { if ( $variant === $this->mCode ) { continue; } foreach ( $this->getNamespaces() as $ns => $_ ) { $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns; } } $this->namespaceAliases = $aliases + $convertedNames; } return $this->namespaceAliases; } /** * @return array */ function getNamespaceIds() { if ( is_null( $this->mNamespaceIds ) ) { global $wgNamespaceAliases; # Put namespace names and aliases into a hashtable. # If this is too slow, then we should arrange it so that it is done # before caching. The catch is that at pre-cache time, the above # class-specific fixup hasn't been done. $this->mNamespaceIds = array(); foreach ( $this->getNamespaces() as $index => $name ) { $this->mNamespaceIds[$this->lc( $name )] = $index; } foreach ( $this->getNamespaceAliases() as $name => $index ) { $this->mNamespaceIds[$this->lc( $name )] = $index; } if ( $wgNamespaceAliases ) { foreach ( $wgNamespaceAliases as $name => $index ) { $this->mNamespaceIds[$this->lc( $name )] = $index; } } } return $this->mNamespaceIds; } /** * Get a namespace key by value, case insensitive. Canonical namespace * names override custom ones defined for the current language. * * @param string $text * @return int|bool An integer if $text is a valid value otherwise false */ function getNsIndex( $text ) { $lctext = $this->lc( $text ); $ns = MWNamespace::getCanonicalIndex( $lctext ); if ( $ns !== null ) { return $ns; } $ids = $this->getNamespaceIds(); return isset( $ids[$lctext] ) ? $ids[$lctext] : false; } /** * short names for language variants used for language conversion links. * * @param string $code * @param bool $usemsg Use the "variantname-xyz" message if it exists * @return string */ function getVariantname( $code, $usemsg = true ) { $msg = "variantname-$code"; if ( $usemsg && wfMessage( $msg )->exists() ) { return $this->getMessageFromDB( $msg ); } $name = self::fetchLanguageName( $code ); if ( $name ) { return $name; # if it's defined as a language name, show that } else { # otherwise, output the language code return $code; } } /** * @deprecated since 1.24, doesn't handle conflicting aliases. Use * SpecialPageFactory::getLocalNameFor instead. * @param string $name * @return string */ function specialPage( $name ) { $aliases = $this->getSpecialPageAliases(); if ( isset( $aliases[$name][0] ) ) { $name = $aliases[$name][0]; } return $this->getNsText( NS_SPECIAL ) . ':' . $name; } /** * @return array */ function getDatePreferences() { return self::$dataCache->getItem( $this->mCode, 'datePreferences' ); } /** * @return array */ function getDateFormats() { return self::$dataCache->getItem( $this->mCode, 'dateFormats' ); } /** * @return array|string */ function getDefaultDateFormat() { $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' ); if ( $df === 'dmy or mdy' ) { global $wgAmericanDates; return $wgAmericanDates ? 'mdy' : 'dmy'; } else { return $df; } } /** * @return array */ function getDatePreferenceMigrationMap() { return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' ); } /** * @param string $image * @return array|null */ function getImageFile( $image ) { return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image ); } /** * @return array * @since 1.24 */ function getImageFiles() { return self::$dataCache->getItem( $this->mCode, 'imageFiles' ); } /** * @return array */ function getExtraUserToggles() { return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' ); } /** * @param string $tog * @return string */ function getUserToggle( $tog ) { return $this->getMessageFromDB( "tog-$tog" ); } /** * Get native language names, indexed by code. * Only those defined in MediaWiki, no other data like CLDR. * If $customisedOnly is true, only returns codes with a messages file * * @param bool $customisedOnly * * @return array * @deprecated since 1.20, use fetchLanguageNames() */ public static function getLanguageNames( $customisedOnly = false ) { return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' ); } /** * Get translated language names. This is done on best effort and * by default this is exactly the same as Language::getLanguageNames. * The CLDR extension provides translated names. * @param string $code Language code. * @return array Language code => language name * @since 1.18.0 * @deprecated since 1.20, use fetchLanguageNames() */ public static function getTranslatedLanguageNames( $code ) { return self::fetchLanguageNames( $code, 'all' ); } /** * Get an array of language names, indexed by code. * @param null|string $inLanguage Code of language in which to return the names * Use null for autonyms (native names) * @param string $include One of: * 'all' all available languages * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default) * 'mwfile' only if the language is in 'mw' *and* has a message file * @return array Language code => language name * @since 1.20 */ public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) { $cacheKey = $inLanguage === null ? 'null' : $inLanguage; $cacheKey .= ":$include"; if ( self::$languageNameCache === null ) { self::$languageNameCache = new MapCacheLRU( 20 ); } if ( self::$languageNameCache->has( $cacheKey ) ) { $ret = self::$languageNameCache->get( $cacheKey ); } else { $ret = self::fetchLanguageNamesUncached( $inLanguage, $include ); self::$languageNameCache->set( $cacheKey, $ret ); } return $ret; } /** * Uncached helper for fetchLanguageNames * @param null|string $inLanguage Code of language in which to return the names * Use null for autonyms (native names) * @param string $include One of: * 'all' all available languages * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default) * 'mwfile' only if the language is in 'mw' *and* has a message file * @return array Language code => language name */ private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) { global $wgExtraLanguageNames; static $coreLanguageNames; if ( $coreLanguageNames === null ) { global $IP; include "$IP/languages/Names.php"; } // If passed an invalid language code to use, fallback to en if ( $inLanguage !== null && !Language::isValidCode( $inLanguage ) ) { $inLanguage = 'en'; } $names = array(); if ( $inLanguage ) { # TODO: also include when $inLanguage is null, when this code is more efficient Hooks::run( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) ); } $mwNames = $wgExtraLanguageNames + $coreLanguageNames; foreach ( $mwNames as $mwCode => $mwName ) { # - Prefer own MediaWiki native name when not using the hook # - For other names just add if not added through the hook if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) { $names[$mwCode] = $mwName; } } if ( $include === 'all' ) { ksort( $names ); return $names; } $returnMw = array(); $coreCodes = array_keys( $mwNames ); foreach ( $coreCodes as $coreCode ) { $returnMw[$coreCode] = $names[$coreCode]; } if ( $include === 'mwfile' ) { $namesMwFile = array(); # We do this using a foreach over the codes instead of a directory # loop so that messages files in extensions will work correctly. foreach ( $returnMw as $code => $value ) { if ( is_readable( self::getMessagesFileName( $code ) ) || is_readable( self::getJsonMessagesFileName( $code ) ) ) { $namesMwFile[$code] = $names[$code]; } } ksort( $namesMwFile ); return $namesMwFile; } ksort( $returnMw ); # 'mw' option; default if it's not one of the other two options (all/mwfile) return $returnMw; } /** * @param string $code The code of the language for which to get the name * @param null|string $inLanguage Code of language in which to return the name (null for autonyms) * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames() * @return string Language name or empty * @since 1.20 */ public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) { $code = strtolower( $code ); $array = self::fetchLanguageNames( $inLanguage, $include ); return !array_key_exists( $code, $array ) ? '' : $array[$code]; } /** * Get a message from the MediaWiki namespace. * * @param string $msg Message name * @return string */ function getMessageFromDB( $msg ) { return $this->msg( $msg )->text(); } /** * Get message object in this language. Only for use inside this class. * * @param string $msg Message name * @return Message */ protected function msg( $msg ) { return wfMessage( $msg )->inLanguage( $this ); } /** * Get the native language name of $code. * Only if defined in MediaWiki, no other data like CLDR. * @param string $code * @return string * @deprecated since 1.20, use fetchLanguageName() */ function getLanguageName( $code ) { return self::fetchLanguageName( $code ); } /** * @param string $key * @return string */ function getMonthName( $key ) { return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] ); } /** * @return array */ function getMonthNamesArray() { $monthNames = array( '' ); for ( $i = 1; $i < 13; $i++ ) { $monthNames[] = $this->getMonthName( $i ); } return $monthNames; } /** * @param string $key * @return string */ function getMonthNameGen( $key ) { return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] ); } /** * @param string $key * @return string */ function getMonthAbbreviation( $key ) { return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] ); } /** * @return array */ function getMonthAbbreviationsArray() { $monthNames = array( '' ); for ( $i = 1; $i < 13; $i++ ) { $monthNames[] = $this->getMonthAbbreviation( $i ); } return $monthNames; } /** * @param string $key * @return string */ function getWeekdayName( $key ) { return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] ); } /** * @param string $key * @return string */ function getWeekdayAbbreviation( $key ) { return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] ); } /** * @param string $key * @return string */ function getIranianCalendarMonthName( $key ) { return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] ); } /** * @param string $key * @return string */ function getHebrewCalendarMonthName( $key ) { return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] ); } /** * @param string $key * @return string */ function getHebrewCalendarMonthNameGen( $key ) { return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] ); } /** * @param string $key * @return string */ function getHijriCalendarMonthName( $key ) { return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] ); } /** * Pass through result from $dateTimeObj->format() * @param DateTime|bool|null &$dateTimeObj * @param string $ts * @param DateTimeZone|bool|null $zone * @param string $code * @return string */ private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) { if ( !$dateTimeObj ) { $dateTimeObj = DateTime::createFromFormat( 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' ) ); } return $dateTimeObj->format( $code ); } /** * This is a workalike of PHP's date() function, but with better * internationalisation, a reduced set of format characters, and a better * escaping format. * * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See * the PHP manual for definitions. There are a number of extensions, which * start with "x": * * xn Do not translate digits of the next numeric format character * xN Toggle raw digit (xn) flag, stays set until explicitly unset * xr Use roman numerals for the next numeric format character * xh Use hebrew numerals for the next numeric format character * xx Literal x * xg Genitive month name * * xij j (day number) in Iranian calendar * xiF F (month name) in Iranian calendar * xin n (month number) in Iranian calendar * xiy y (two digit year) in Iranian calendar * xiY Y (full year) in Iranian calendar * * xjj j (day number) in Hebrew calendar * xjF F (month name) in Hebrew calendar * xjt t (days in month) in Hebrew calendar * xjx xg (genitive month name) in Hebrew calendar * xjn n (month number) in Hebrew calendar * xjY Y (full year) in Hebrew calendar * * xmj j (day number) in Hijri calendar * xmF F (month name) in Hijri calendar * xmn n (month number) in Hijri calendar * xmY Y (full year) in Hijri calendar * * xkY Y (full year) in Thai solar calendar. Months and days are * identical to the Gregorian calendar * xoY Y (full year) in Minguo calendar or Juche year. * Months and days are identical to the * Gregorian calendar * xtY Y (full year) in Japanese nengo. Months and days are * identical to the Gregorian calendar * * Characters enclosed in double quotes will be considered literal (with * the quotes themselves removed). Unmatched quotes will be considered * literal quotes. Example: * * "The month is" F => The month is January * i's" => 20'11" * * Backslash escaping is also supported. * * Input timestamp is assumed to be pre-normalized to the desired local * time zone, if any. Note that the format characters crUeIOPTZ will assume * $ts is UTC if $zone is not given. * * @param string $format * @param string $ts 14-character timestamp * YYYYMMDDHHMMSS * 01234567890123 * @param DateTimeZone $zone Timezone of $ts * @param[out] int $ttl The amount of time (in seconds) the output may be cached for. * Only makes sense if $ts is the current time. * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai? * * @throws MWException * @return string */ function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = null ) { $s = ''; $raw = false; $roman = false; $hebrewNum = false; $dateTimeObj = false; $rawToggle = false; $iranian = false; $hebrew = false; $hijri = false; $thai = false; $minguo = false; $tenno = false; $usedSecond = false; $usedMinute = false; $usedHour = false; $usedAMPM = false; $usedDay = false; $usedWeek = false; $usedMonth = false; $usedYear = false; $usedISOYear = false; $usedIsLeapYear = false; $usedHebrewMonth = false; $usedIranianMonth = false; $usedHijriMonth = false; $usedHebrewYear = false; $usedIranianYear = false; $usedHijriYear = false; $usedTennoYear = false; if ( strlen( $ts ) !== 14 ) { throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" ); } if ( !ctype_digit( $ts ) ) { throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" ); } $formatLength = strlen( $format ); for ( $p = 0; $p < $formatLength; $p++ ) { $num = false; $code = $format[$p]; if ( $code == 'x' && $p < $formatLength - 1 ) { $code .= $format[++$p]; } if ( ( $code === 'xi' || $code === 'xj' || $code === 'xk' || $code === 'xm' || $code === 'xo' || $code === 'xt' ) && $p < $formatLength - 1 ) { $code .= $format[++$p]; } switch ( $code ) { case 'xx': $s .= 'x'; break; case 'xn': $raw = true; break; case 'xN': $rawToggle = !$rawToggle; break; case 'xr': $roman = true; break; case 'xh': $hebrewNum = true; break; case 'xg': $usedMonth = true; $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) ); break; case 'xjx': $usedHebrewMonth = true; if ( !$hebrew ) { $hebrew = self::tsToHebrew( $ts ); } $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] ); break; case 'd': $usedDay = true; $num = substr( $ts, 6, 2 ); break; case 'D': $usedDay = true; $s .= $this->getWeekdayAbbreviation( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 ); break; case 'j': $usedDay = true; $num = intval( substr( $ts, 6, 2 ) ); break; case 'xij': $usedDay = true; if ( !$iranian ) { $iranian = self::tsToIranian( $ts ); } $num = $iranian[2]; break; case 'xmj': $usedDay = true; if ( !$hijri ) { $hijri = self::tsToHijri( $ts ); } $num = $hijri[2]; break; case 'xjj': $usedDay = true; if ( !$hebrew ) { $hebrew = self::tsToHebrew( $ts ); } $num = $hebrew[2]; break; case 'l': $usedDay = true; $s .= $this->getWeekdayName( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1 ); break; case 'F': $usedMonth = true; $s .= $this->getMonthName( substr( $ts, 4, 2 ) ); break; case 'xiF': $usedIranianMonth = true; if ( !$iranian ) { $iranian = self::tsToIranian( $ts ); } $s .= $this->getIranianCalendarMonthName( $iranian[1] ); break; case 'xmF': $usedHijriMonth = true; if ( !$hijri ) { $hijri = self::tsToHijri( $ts ); } $s .= $this->getHijriCalendarMonthName( $hijri[1] ); break; case 'xjF': $usedHebrewMonth = true; if ( !$hebrew ) { $hebrew = self::tsToHebrew( $ts ); } $s .= $this->getHebrewCalendarMonthName( $hebrew[1] ); break; case 'm': $usedMonth = true; $num = substr( $ts, 4, 2 ); break; case 'M': $usedMonth = true; $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) ); break; case 'n': $usedMonth = true; $num = intval( substr( $ts, 4, 2 ) ); break; case 'xin': $usedIranianMonth = true; if ( !$iranian ) { $iranian = self::tsToIranian( $ts ); } $num = $iranian[1]; break; case 'xmn': $usedHijriMonth = true; if ( !$hijri ) { $hijri = self::tsToHijri ( $ts ); } $num = $hijri[1]; break; case 'xjn': $usedHebrewMonth = true; if ( !$hebrew ) { $hebrew = self::tsToHebrew( $ts ); } $num = $hebrew[1]; break; case 'xjt': $usedHebrewMonth = true; if ( !$hebrew ) { $hebrew = self::tsToHebrew( $ts ); } $num = $hebrew[3]; break; case 'Y': $usedYear = true; $num = substr( $ts, 0, 4 ); break; case 'xiY': $usedIranianYear = true; if ( !$iranian ) { $iranian = self::tsToIranian( $ts ); } $num = $iranian[0]; break; case 'xmY': $usedHijriYear = true; if ( !$hijri ) { $hijri = self::tsToHijri( $ts ); } $num = $hijri[0]; break; case 'xjY': $usedHebrewYear = true; if ( !$hebrew ) { $hebrew = self::tsToHebrew( $ts ); } $num = $hebrew[0]; break; case 'xkY': $usedYear = true; if ( !$thai ) { $thai = self::tsToYear( $ts, 'thai' ); } $num = $thai[0]; break; case 'xoY': $usedYear = true; if ( !$minguo ) { $minguo = self::tsToYear( $ts, 'minguo' ); } $num = $minguo[0]; break; case 'xtY': $usedTennoYear = true; if ( !$tenno ) { $tenno = self::tsToYear( $ts, 'tenno' ); } $num = $tenno[0]; break; case 'y': $usedYear = true; $num = substr( $ts, 2, 2 ); break; case 'xiy': $usedIranianYear = true; if ( !$iranian ) { $iranian = self::tsToIranian( $ts ); } $num = substr( $iranian[0], -2 ); break; case 'a': $usedAMPM = true; $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm'; break; case 'A': $usedAMPM = true; $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM'; break; case 'g': $usedHour = true; $h = substr( $ts, 8, 2 ); $num = $h % 12 ? $h % 12 : 12; break; case 'G': $usedHour = true; $num = intval( substr( $ts, 8, 2 ) ); break; case 'h': $usedHour = true; $h = substr( $ts, 8, 2 ); $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 ); break; case 'H': $usedHour = true; $num = substr( $ts, 8, 2 ); break; case 'i': $usedMinute = true; $num = substr( $ts, 10, 2 ); break; case 's': $usedSecond = true; $num = substr( $ts, 12, 2 ); break; case 'c': case 'r': $usedSecond = true; // fall through case 'e': case 'O': case 'P': case 'T': $s .= Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case 'w': case 'N': case 'z': $usedDay = true; $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case 'W': $usedWeek = true; $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case 't': $usedMonth = true; $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case 'L': $usedIsLeapYear = true; $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case 'o': $usedISOYear = true; $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case 'U': $usedSecond = true; // fall through case 'I': case 'Z': $num = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code ); break; case '\\': # Backslash escaping if ( $p < $formatLength - 1 ) { $s .= $format[++$p]; } else { $s .= '\\'; } break; case '"': # Quoted literal if ( $p < $formatLength - 1 ) { $endQuote = strpos( $format, '"', $p + 1 ); if ( $endQuote === false ) { # No terminating quote, assume literal " $s .= '"'; } else { $s .= substr( $format, $p + 1, $endQuote - $p - 1 ); $p = $endQuote; } } else { # Quote at end of string, assume literal " $s .= '"'; } break; default: $s .= $format[$p]; } if ( $num !== false ) { if ( $rawToggle || $raw ) { $s .= $num; $raw = false; } elseif ( $roman ) { $s .= Language::romanNumeral( $num ); $roman = false; } elseif ( $hebrewNum ) { $s .= self::hebrewNumeral( $num ); $hebrewNum = false; } else { $s .= $this->formatNum( $num, true ); } } } if ( $usedSecond ) { $ttl = 1; } elseif ( $usedMinute ) { $ttl = 60 - substr( $ts, 12, 2 ); } elseif ( $usedHour ) { $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 ); } elseif ( $usedAMPM ) { $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 ); } elseif ( $usedDay || $usedHebrewMonth || $usedIranianMonth || $usedHijriMonth || $usedHebrewYear || $usedIranianYear || $usedHijriYear || $usedTennoYear ) { // @todo Someone who understands the non-Gregorian calendars should write proper logic for them // so that they don't need purged every day. $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 ); } else { $possibleTtls = array(); $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 ); if ( $usedWeek ) { $possibleTtls[] = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay; } elseif ( $usedISOYear ) { // December 28th falls on the last ISO week of the year, every year. // The last ISO week of a year can be 52 or 53. $lastWeekOfISOYear = DateTime::createFromFormat( 'Ymd', substr( $ts, 0, 4 ) . '1228', $zone ?: new DateTimeZone( 'UTC' ) )->format( 'W' ); $currentISOWeek = Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' ); $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek; $timeRemainingInWeek = ( 7 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 + $timeRemainingInDay; $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek; } if ( $usedMonth ) { $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) - substr( $ts, 6, 2 ) ) * 86400 + $timeRemainingInDay; } elseif ( $usedYear ) { $possibleTtls[] = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400 + $timeRemainingInDay; } elseif ( $usedIsLeapYear ) { $year = substr( $ts, 0, 4 ); $timeRemainingInYear = ( Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 - Language::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400 + $timeRemainingInDay; $mod = $year % 4; if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) { // this isn't a leap year. see when the next one starts $nextCandidate = $year - $mod + 4; if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) { $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 + $timeRemainingInYear; } else { $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 + $timeRemainingInYear; } } else { // this is a leap year, so the next year isn't $possibleTtls[] = $timeRemainingInYear; } } if ( $possibleTtls ) { $ttl = min( $possibleTtls ); } } return $s; } private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ); /** * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert * Gregorian dates to Iranian dates. Originally written in C, it * is released under the terms of GNU Lesser General Public * License. Conversion to PHP was performed by Niklas Laxström. * * Link: http://www.farsiweb.info/jalali/jalali.c * * @param string $ts * * @return string */ private static function tsToIranian( $ts ) { $gy = substr( $ts, 0, 4 ) -1600; $gm = substr( $ts, 4, 2 ) -1; $gd = substr( $ts, 6, 2 ) -1; # Days passed from the beginning (including leap years) $gDayNo = 365 * $gy + floor( ( $gy + 3 ) / 4 ) - floor( ( $gy + 99 ) / 100 ) + floor( ( $gy + 399 ) / 400 ); // Add days of the past months of this year for ( $i = 0; $i < $gm; $i++ ) { $gDayNo += self::$GREG_DAYS[$i]; } // Leap years if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) { $gDayNo++; } // Days passed in current month $gDayNo += (int)$gd; $jDayNo = $gDayNo - 79; $jNp = floor( $jDayNo / 12053 ); $jDayNo %= 12053; $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 ); $jDayNo %= 1461; if ( $jDayNo >= 366 ) { $jy += floor( ( $jDayNo - 1 ) / 365 ); $jDayNo = floor( ( $jDayNo - 1 ) % 365 ); } for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) { $jDayNo -= self::$IRANIAN_DAYS[$i]; } $jm = $i + 1; $jd = $jDayNo + 1; return array( $jy, $jm, $jd ); } /** * Converting Gregorian dates to Hijri dates. * * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license * * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0 * * @param string $ts * * @return string */ private static function tsToHijri( $ts ) { $year = substr( $ts, 0, 4 ); $month = substr( $ts, 4, 2 ); $day = substr( $ts, 6, 2 ); $zyr = $year; $zd = $day; $zm = $month; $zy = $zyr; if ( ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) || ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) ) ) { $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) + (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) - (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) + $zd - 32075; } else { $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) + (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777; } $zl = $zjd -1948440 + 10632; $zn = (int)( ( $zl - 1 ) / 10631 ); $zl = $zl - 10631 * $zn + 354; $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) ); $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29; $zm = (int)( ( 24 * $zl ) / 709 ); $zd = $zl - (int)( ( 709 * $zm ) / 24 ); $zy = 30 * $zn + $zj - 30; return array( $zy, $zm, $zd ); } /** * Converting Gregorian dates to Hebrew dates. * * Based on a JavaScript code by Abu Mami and Yisrael Hersch * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted * to translate the relevant functions into PHP and release them under * GNU GPL. * * The months are counted from Tishrei = 1. In a leap year, Adar I is 13 * and Adar II is 14. In a non-leap year, Adar is 6. * * @param string $ts * * @return string */ private static function tsToHebrew( $ts ) { # Parse date $year = substr( $ts, 0, 4 ); $month = substr( $ts, 4, 2 ); $day = substr( $ts, 6, 2 ); # Calculate Hebrew year $hebrewYear = $year + 3760; # Month number when September = 1, August = 12 $month += 4; if ( $month > 12 ) { # Next year $month -= 12; $year++; $hebrewYear++; } # Calculate day of year from 1 September $dayOfYear = $day; for ( $i = 1; $i < $month; $i++ ) { if ( $i == 6 ) { # February $dayOfYear += 28; # Check if the year is leap if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) { $dayOfYear++; } } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) { $dayOfYear += 30; } else { $dayOfYear += 31; } } # Calculate the start of the Hebrew year $start = self::hebrewYearStart( $hebrewYear ); # Calculate next year's start if ( $dayOfYear <= $start ) { # Day is before the start of the year - it is the previous year # Next year's start $nextStart = $start; # Previous year $year--; $hebrewYear--; # Add days since previous year's 1 September $dayOfYear += 365; if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) { # Leap year $dayOfYear++; } # Start of the new (previous) year $start = self::hebrewYearStart( $hebrewYear ); } else { # Next year's start $nextStart = self::hebrewYearStart( $hebrewYear + 1 ); } # Calculate Hebrew day of year $hebrewDayOfYear = $dayOfYear - $start; # Difference between year's days $diff = $nextStart - $start; # Add 12 (or 13 for leap years) days to ignore the difference between # Hebrew and Gregorian year (353 at least vs. 365/6) - now the # difference is only about the year type if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) { $diff += 13; } else { $diff += 12; } # Check the year pattern, and is leap year # 0 means an incomplete year, 1 means a regular year, 2 means a complete year # This is mod 30, to work on both leap years (which add 30 days of Adar I) # and non-leap years $yearPattern = $diff % 30; # Check if leap year $isLeap = $diff >= 30; # Calculate day in the month from number of day in the Hebrew year # Don't check Adar - if the day is not in Adar, we will stop before; # if it is in Adar, we will use it to check if it is Adar I or Adar II $hebrewDay = $hebrewDayOfYear; $hebrewMonth = 1; $days = 0; while ( $hebrewMonth <= 12 ) { # Calculate days in this month if ( $isLeap && $hebrewMonth == 6 ) { # Adar in a leap year if ( $isLeap ) { # Leap year - has Adar I, with 30 days, and Adar II, with 29 days $days = 30; if ( $hebrewDay <= $days ) { # Day in Adar I $hebrewMonth = 13; } else { # Subtract the days of Adar I $hebrewDay -= $days; # Try Adar II $days = 29; if ( $hebrewDay <= $days ) { # Day in Adar II $hebrewMonth = 14; } } } } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) { # Cheshvan in a complete year (otherwise as the rule below) $days = 30; } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) { # Kislev in an incomplete year (otherwise as the rule below) $days = 29; } else { # Odd months have 30 days, even have 29 $days = 30 - ( $hebrewMonth - 1 ) % 2; } if ( $hebrewDay <= $days ) { # In the current month break; } else { # Subtract the days of the current month $hebrewDay -= $days; # Try in the next month $hebrewMonth++; } } return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days ); } /** * This calculates the Hebrew year start, as days since 1 September. * Based on Carl Friedrich Gauss algorithm for finding Easter date. * Used for Hebrew date. * * @param int $year * * @return string */ private static function hebrewYearStart( $year ) { $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 ); $b = intval( ( $year - 1 ) % 4 ); $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 ); if ( $m < 0 ) { $m--; } $Mar = intval( $m ); if ( $m < 0 ) { $m++; } $m -= $Mar; $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 ); if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) { $Mar++; } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) { $Mar += 2; } elseif ( $c == 2 || $c == 4 || $c == 6 ) { $Mar++; } $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24; return $Mar; } /** * Algorithm to convert Gregorian dates to Thai solar dates, * Minguo dates or Minguo dates. * * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar * http://en.wikipedia.org/wiki/Minguo_calendar * http://en.wikipedia.org/wiki/Japanese_era_name * * @param string $ts 14-character timestamp * @param string $cName Calender name * @return array Converted year, month, day */ private static function tsToYear( $ts, $cName ) { $gy = substr( $ts, 0, 4 ); $gm = substr( $ts, 4, 2 ); $gd = substr( $ts, 6, 2 ); if ( !strcmp( $cName, 'thai' ) ) { # Thai solar dates # Add 543 years to the Gregorian calendar # Months and days are identical $gy_offset = $gy + 543; } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) { # Minguo dates # Deduct 1911 years from the Gregorian calendar # Months and days are identical $gy_offset = $gy - 1911; } elseif ( !strcmp( $cName, 'tenno' ) ) { # Nengō dates up to Meiji period # Deduct years from the Gregorian calendar # depending on the nengo periods # Months and days are identical if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) { # Meiji period $gy_gannen = $gy - 1868 + 1; $gy_offset = $gy_gannen; if ( $gy_gannen == 1 ) { $gy_offset = '元'; } $gy_offset = '明治' . $gy_offset; } elseif ( ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) || ( ( $gy == 1912 ) && ( $gm >= 8 ) ) || ( ( $gy > 1912 ) && ( $gy < 1926 ) ) || ( ( $gy == 1926 ) && ( $gm < 12 ) ) || ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) ) ) { # Taishō period $gy_gannen = $gy - 1912 + 1; $gy_offset = $gy_gannen; if ( $gy_gannen == 1 ) { $gy_offset = '元'; } $gy_offset = '大正' . $gy_offset; } elseif ( ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) || ( ( $gy > 1926 ) && ( $gy < 1989 ) ) || ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) ) ) { # Shōwa period $gy_gannen = $gy - 1926 + 1; $gy_offset = $gy_gannen; if ( $gy_gannen == 1 ) { $gy_offset = '元'; } $gy_offset = '昭和' . $gy_offset; } else { # Heisei period $gy_gannen = $gy - 1989 + 1; $gy_offset = $gy_gannen; if ( $gy_gannen == 1 ) { $gy_offset = '元'; } $gy_offset = '平成' . $gy_offset; } } else { $gy_offset = $gy; } return array( $gy_offset, $gm, $gd ); } /** * Roman number formatting up to 10000 * * @param int $num * * @return string */ static function romanNumeral( $num ) { static $table = array( array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ), array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ), array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ), array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ) ); $num = intval( $num ); if ( $num > 10000 || $num <= 0 ) { return $num; } $s = ''; for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) { if ( $num >= $pow10 ) { $s .= $table[$i][(int)floor( $num / $pow10 )]; } $num = $num % $pow10; } return $s; } /** * Hebrew Gematria number formatting up to 9999 * * @param int $num * * @return string */ static function hebrewNumeral( $num ) { static $table = array( array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ), array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ), array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ), array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ) ); $num = intval( $num ); if ( $num > 9999 || $num <= 0 ) { return $num; } $s = ''; for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) { if ( $num >= $pow10 ) { if ( $num == 15 || $num == 16 ) { $s .= $table[0][9] . $table[0][$num - 9]; $num = 0; } else { $s .= $table[$i][intval( ( $num / $pow10 ) )]; if ( $pow10 == 1000 ) { $s .= "'"; } } } $num = $num % $pow10; } if ( strlen( $s ) == 2 ) { $str = $s . "'"; } else { $str = substr( $s, 0, strlen( $s ) - 2 ) . '"'; $str .= substr( $s, strlen( $s ) - 2, 2 ); } $start = substr( $str, 0, strlen( $str ) - 2 ); $end = substr( $str, strlen( $str ) - 2 ); switch ( $end ) { case 'כ': $str = $start . 'ך'; break; case 'מ': $str = $start . 'ם'; break; case 'נ': $str = $start . 'ן'; break; case 'פ': $str = $start . 'ף'; break; case 'צ': $str = $start . 'ץ'; break; } return $str; } /** * Used by date() and time() to adjust the time output. * * @param string $ts The time in date('YmdHis') format * @param mixed $tz Adjust the time by this amount (default false, mean we * get user timecorrection setting) * @return int */ function userAdjust( $ts, $tz = false ) { global $wgUser, $wgLocalTZoffset; if ( $tz === false ) { $tz = $wgUser->getOption( 'timecorrection' ); } $data = explode( '|', $tz, 3 ); if ( $data[0] == 'ZoneInfo' ) { wfSuppressWarnings(); $userTZ = timezone_open( $data[2] ); wfRestoreWarnings(); if ( $userTZ !== false ) { $date = date_create( $ts, timezone_open( 'UTC' ) ); date_timezone_set( $date, $userTZ ); $date = date_format( $date, 'YmdHis' ); return $date; } # Unrecognized timezone, default to 'Offset' with the stored offset. $data[0] = 'Offset'; } if ( $data[0] == 'System' || $tz == '' ) { # Global offset in minutes. $minDiff = $wgLocalTZoffset; } elseif ( $data[0] == 'Offset' ) { $minDiff = intval( $data[1] ); } else { $data = explode( ':', $tz ); if ( count( $data ) == 2 ) { $data[0] = intval( $data[0] ); $data[1] = intval( $data[1] ); $minDiff = abs( $data[0] ) * 60 + $data[1]; if ( $data[0] < 0 ) { $minDiff = -$minDiff; } } else { $minDiff = intval( $data[0] ) * 60; } } # No difference ? Return time unchanged if ( 0 == $minDiff ) { return $ts; } wfSuppressWarnings(); // E_STRICT system time bitching # Generate an adjusted date; take advantage of the fact that mktime # will normalize out-of-range values so we don't have to split $minDiff # into hours and minutes. $t = mktime( ( (int)substr( $ts, 8, 2 ) ), # Hours (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes (int)substr( $ts, 12, 2 ), # Seconds (int)substr( $ts, 4, 2 ), # Month (int)substr( $ts, 6, 2 ), # Day (int)substr( $ts, 0, 4 ) ); # Year $date = date( 'YmdHis', $t ); wfRestoreWarnings(); return $date; } /** * This is meant to be used by time(), date(), and timeanddate() to get * the date preference they're supposed to use, it should be used in * all children. * *<code> * function timeanddate([...], $format = true) { * $datePreference = $this->dateFormat($format); * [...] * } *</code> * * @param int|string|bool $usePrefs If true, the user's preference is used * if false, the site/language default is used * if int/string, assumed to be a format. * @return string */ function dateFormat( $usePrefs = true ) { global $wgUser; if ( is_bool( $usePrefs ) ) { if ( $usePrefs ) { $datePreference = $wgUser->getDatePreference(); } else { $datePreference = (string)User::getDefaultOption( 'date' ); } } else { $datePreference = (string)$usePrefs; } // return int if ( $datePreference == '' ) { return 'default'; } return $datePreference; } /** * Get a format string for a given type and preference * @param string $type May be date, time or both * @param string $pref The format name as it appears in Messages*.php * * @since 1.22 New type 'pretty' that provides a more readable timestamp format * * @return string */ function getDateFormatString( $type, $pref ) { if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) { if ( $pref == 'default' ) { $pref = $this->getDefaultDateFormat(); $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" ); } else { $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" ); if ( $type === 'pretty' && $df === null ) { $df = $this->getDateFormatString( 'date', $pref ); } if ( $df === null ) { $pref = $this->getDefaultDateFormat(); $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" ); } } $this->dateFormatStrings[$type][$pref] = $df; } return $this->dateFormatStrings[$type][$pref]; } /** * @param string $ts The time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param bool $adj Whether to adjust the time output according to the * user configured offset ($timecorrection) * @param mixed $format True to use user's date format preference * @param string|bool $timecorrection The time offset as returned by * validateTimeZone() in Special:Preferences * @return string */ function date( $ts, $adj = false, $format = true, $timecorrection = false ) { $ts = wfTimestamp( TS_MW, $ts ); if ( $adj ) { $ts = $this->userAdjust( $ts, $timecorrection ); } $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) ); return $this->sprintfDate( $df, $ts ); } /** * @param string $ts The time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param bool $adj Whether to adjust the time output according to the * user configured offset ($timecorrection) * @param mixed $format True to use user's date format preference * @param string|bool $timecorrection The time offset as returned by * validateTimeZone() in Special:Preferences * @return string */ function time( $ts, $adj = false, $format = true, $timecorrection = false ) { $ts = wfTimestamp( TS_MW, $ts ); if ( $adj ) { $ts = $this->userAdjust( $ts, $timecorrection ); } $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) ); return $this->sprintfDate( $df, $ts ); } /** * @param string $ts The time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param bool $adj Whether to adjust the time output according to the * user configured offset ($timecorrection) * @param mixed $format What format to return, if it's false output the * default one (default true) * @param string|bool $timecorrection The time offset as returned by * validateTimeZone() in Special:Preferences * @return string */ function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) { $ts = wfTimestamp( TS_MW, $ts ); if ( $adj ) { $ts = $this->userAdjust( $ts, $timecorrection ); } $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) ); return $this->sprintfDate( $df, $ts ); } /** * Takes a number of seconds and turns it into a text using values such as hours and minutes. * * @since 1.20 * * @param int $seconds The amount of seconds. * @param array $chosenIntervals The intervals to enable. * * @return string */ public function formatDuration( $seconds, array $chosenIntervals = array() ) { $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals ); $segments = array(); foreach ( $intervals as $intervalName => $intervalValue ) { // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks, // duration-years, duration-decades, duration-centuries, duration-millennia $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue ); $segments[] = $message->inLanguage( $this )->escaped(); } return $this->listToText( $segments ); } /** * Takes a number of seconds and returns an array with a set of corresponding intervals. * For example 65 will be turned into array( minutes => 1, seconds => 5 ). * * @since 1.20 * * @param int $seconds The amount of seconds. * @param array $chosenIntervals The intervals to enable. * * @return array */ public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) { if ( empty( $chosenIntervals ) ) { $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' ); } $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) ); $sortedNames = array_keys( $intervals ); $smallestInterval = array_pop( $sortedNames ); $segments = array(); foreach ( $intervals as $name => $length ) { $value = floor( $seconds / $length ); if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) { $seconds -= $value * $length; $segments[$name] = $value; } } return $segments; } /** * Internal helper function for userDate(), userTime() and userTimeAndDate() * * @param string $type Can be 'date', 'time' or 'both' * @param string $ts The time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param User $user User object used to get preferences for timezone and format * @param array $options Array, can contain the following keys: * - 'timecorrection': time correction, can have the following values: * - true: use user's preference * - false: don't use time correction * - int: value of time correction in minutes * - 'format': format to use, can have the following values: * - true: use user's preference * - false: use default preference * - string: format to use * @since 1.19 * @return string */ private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) { $ts = wfTimestamp( TS_MW, $ts ); $options += array( 'timecorrection' => true, 'format' => true ); if ( $options['timecorrection'] !== false ) { if ( $options['timecorrection'] === true ) { $offset = $user->getOption( 'timecorrection' ); } else { $offset = $options['timecorrection']; } $ts = $this->userAdjust( $ts, $offset ); } if ( $options['format'] === true ) { $format = $user->getDatePreference(); } else { $format = $options['format']; } $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) ); return $this->sprintfDate( $df, $ts ); } /** * Get the formatted date for the given timestamp and formatted for * the given user. * * @param mixed $ts Mixed: the time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param User $user User object used to get preferences for timezone and format * @param array $options Array, can contain the following keys: * - 'timecorrection': time correction, can have the following values: * - true: use user's preference * - false: don't use time correction * - int: value of time correction in minutes * - 'format': format to use, can have the following values: * - true: use user's preference * - false: use default preference * - string: format to use * @since 1.19 * @return string */ public function userDate( $ts, User $user, array $options = array() ) { return $this->internalUserTimeAndDate( 'date', $ts, $user, $options ); } /** * Get the formatted time for the given timestamp and formatted for * the given user. * * @param mixed $ts The time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param User $user User object used to get preferences for timezone and format * @param array $options Array, can contain the following keys: * - 'timecorrection': time correction, can have the following values: * - true: use user's preference * - false: don't use time correction * - int: value of time correction in minutes * - 'format': format to use, can have the following values: * - true: use user's preference * - false: use default preference * - string: format to use * @since 1.19 * @return string */ public function userTime( $ts, User $user, array $options = array() ) { return $this->internalUserTimeAndDate( 'time', $ts, $user, $options ); } /** * Get the formatted date and time for the given timestamp and formatted for * the given user. * * @param mixed $ts The time format which needs to be turned into a * date('YmdHis') format with wfTimestamp(TS_MW,$ts) * @param User $user User object used to get preferences for timezone and format * @param array $options Array, can contain the following keys: * - 'timecorrection': time correction, can have the following values: * - true: use user's preference * - false: don't use time correction * - int: value of time correction in minutes * - 'format': format to use, can have the following values: * - true: use user's preference * - false: use default preference * - string: format to use * @since 1.19 * @return string */ public function userTimeAndDate( $ts, User $user, array $options = array() ) { return $this->internalUserTimeAndDate( 'both', $ts, $user, $options ); } /** * Convert an MWTimestamp into a pretty human-readable timestamp using * the given user preferences and relative base time. * * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp * on your timestamp object, which will then call this function. Calling * this function directly will cause hooks to be skipped over. * * @see MWTimestamp::getHumanTimestamp * @param MWTimestamp $ts Timestamp to prettify * @param MWTimestamp $relativeTo Base timestamp * @param User $user User preferences to use * @return string Human timestamp * @since 1.22 */ public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) { $diff = $ts->diff( $relativeTo ); $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) - (int)$relativeTo->timestamp->format( 'w' ) ); $days = $diff->days ?: (int)$diffDay; if ( $diff->invert || $days > 5 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' ) ) { // Timestamps are in different years: use full timestamp // Also do full timestamp for future dates /** * @todo FIXME: Add better handling of future timestamps. */ $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' ); $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ); } elseif ( $days > 5 ) { // Timestamps are in same year, but more than 5 days ago: show day and month only. $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' ); $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ); } elseif ( $days > 1 ) { // Timestamp within the past week: show the day of the week and time $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' ); $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )]; // Messages: // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at $ts = wfMessage( "$weekday-at" ) ->inLanguage( $this ) ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) ) ->text(); } elseif ( $days == 1 ) { // Timestamp was yesterday: say 'yesterday' and the time. $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' ); $ts = wfMessage( 'yesterday-at' ) ->inLanguage( $this ) ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) ) ->text(); } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) { // Timestamp was today, but more than 90 minutes ago: say 'today' and the time. $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' ); $ts = wfMessage( 'today-at' ) ->inLanguage( $this ) ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) ) ->text(); // From here on in, the timestamp was soon enough ago so that we can simply say // XX units ago, e.g., "2 hours ago" or "5 minutes ago" } elseif ( $diff->h == 1 ) { // Less than 90 minutes, but more than an hour ago. $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text(); } elseif ( $diff->i >= 1 ) { // A few minutes ago. $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text(); } elseif ( $diff->s >= 30 ) { // Less than a minute, but more than 30 sec ago. $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text(); } else { // Less than 30 seconds ago. $ts = wfMessage( 'just-now' )->text(); } return $ts; } /** * @param string $key * @return array|null */ function getMessage( $key ) { return self::$dataCache->getSubitem( $this->mCode, 'messages', $key ); } /** * @return array */ function getAllMessages() { return self::$dataCache->getItem( $this->mCode, 'messages' ); } /** * @param string $in * @param string $out * @param string $string * @return string */ function iconv( $in, $out, $string ) { # This is a wrapper for iconv in all languages except esperanto, # which does some nasty x-conversions beforehand # Even with //IGNORE iconv can whine about illegal characters in # *input* string. We just ignore those too. # REF: http://bugs.php.net/bug.php?id=37166 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885 wfSuppressWarnings(); $text = iconv( $in, $out . '//IGNORE', $string ); wfRestoreWarnings(); return $text; } // callback functions for uc(), lc(), ucwords(), ucwordbreaks() /** * @param array $matches * @return mixed|string */ function ucwordbreaksCallbackAscii( $matches ) { return $this->ucfirst( $matches[1] ); } /** * @param array $matches * @return string */ function ucwordbreaksCallbackMB( $matches ) { return mb_strtoupper( $matches[0] ); } /** * @param array $matches * @return string */ function ucCallback( $matches ) { list( $wikiUpperChars ) = self::getCaseMaps(); return strtr( $matches[1], $wikiUpperChars ); } /** * @param array $matches * @return string */ function lcCallback( $matches ) { list( , $wikiLowerChars ) = self::getCaseMaps(); return strtr( $matches[1], $wikiLowerChars ); } /** * @param array $matches * @return string */ function ucwordsCallbackMB( $matches ) { return mb_strtoupper( $matches[0] ); } /** * @param array $matches * @return string */ function ucwordsCallbackWiki( $matches ) { list( $wikiUpperChars ) = self::getCaseMaps(); return strtr( $matches[0], $wikiUpperChars ); } /** * Make a string's first character uppercase * * @param string $str * * @return string */ function ucfirst( $str ) { $o = ord( $str ); if ( $o < 96 ) { // if already uppercase... return $str; } elseif ( $o < 128 ) { return ucfirst( $str ); // use PHP's ucfirst() } else { // fall back to more complex logic in case of multibyte strings return $this->uc( $str, true ); } } /** * Convert a string to uppercase * * @param string $str * @param bool $first * * @return string */ function uc( $str, $first = false ) { if ( function_exists( 'mb_strtoupper' ) ) { if ( $first ) { if ( $this->isMultibyte( $str ) ) { return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 ); } else { return ucfirst( $str ); } } else { return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str ); } } else { if ( $this->isMultibyte( $str ) ) { $x = $first ? '^' : ''; return preg_replace_callback( "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/", array( $this, 'ucCallback' ), $str ); } else { return $first ? ucfirst( $str ) : strtoupper( $str ); } } } /** * @param string $str * @return mixed|string */ function lcfirst( $str ) { $o = ord( $str ); if ( !$o ) { return strval( $str ); } elseif ( $o >= 128 ) { return $this->lc( $str, true ); } elseif ( $o > 96 ) { return $str; } else { $str[0] = strtolower( $str[0] ); return $str; } } /** * @param string $str * @param bool $first * @return mixed|string */ function lc( $str, $first = false ) { if ( function_exists( 'mb_strtolower' ) ) { if ( $first ) { if ( $this->isMultibyte( $str ) ) { return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 ); } else { return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ); } } else { return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str ); } } else { if ( $this->isMultibyte( $str ) ) { $x = $first ? '^' : ''; return preg_replace_callback( "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/", array( $this, 'lcCallback' ), $str ); } else { return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str ); } } } /** * @param string $str * @return bool */ function isMultibyte( $str ) { return (bool)preg_match( '/[\x80-\xff]/', $str ); } /** * @param string $str * @return mixed|string */ function ucwords( $str ) { if ( $this->isMultibyte( $str ) ) { $str = $this->lc( $str ); // regexp to find first letter in each word (i.e. after each space) $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/"; // function to use to capitalize a single char if ( function_exists( 'mb_strtoupper' ) ) { return preg_replace_callback( $replaceRegexp, array( $this, 'ucwordsCallbackMB' ), $str ); } else { return preg_replace_callback( $replaceRegexp, array( $this, 'ucwordsCallbackWiki' ), $str ); } } else { return ucwords( strtolower( $str ) ); } } /** * capitalize words at word breaks * * @param string $str * @return mixed */ function ucwordbreaks( $str ) { if ( $this->isMultibyte( $str ) ) { $str = $this->lc( $str ); // since \b doesn't work for UTF-8, we explicitely define word break chars $breaks = "[ \-\(\)\}\{\.,\?!]"; // find first letter after word break $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" . "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/"; if ( function_exists( 'mb_strtoupper' ) ) { return preg_replace_callback( $replaceRegexp, array( $this, 'ucwordbreaksCallbackMB' ), $str ); } else { return preg_replace_callback( $replaceRegexp, array( $this, 'ucwordsCallbackWiki' ), $str ); } } else { return preg_replace_callback( '/\b([\w\x80-\xff]+)\b/', array( $this, 'ucwordbreaksCallbackAscii' ), $str ); } } /** * Return a case-folded representation of $s * * This is a representation such that caseFold($s1)==caseFold($s2) if $s1 * and $s2 are the same except for the case of their characters. It is not * necessary for the value returned to make sense when displayed. * * Do *not* perform any other normalisation in this function. If a caller * uses this function when it should be using a more general normalisation * function, then fix the caller. * * @param string $s * * @return string */ function caseFold( $s ) { return $this->uc( $s ); } /** * @param string $s * @return string */ function checkTitleEncoding( $s ) { if ( is_array( $s ) ) { throw new MWException( 'Given array to checkTitleEncoding.' ); } if ( StringUtils::isUtf8( $s ) ) { return $s; } return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s ); } /** * @return array */ function fallback8bitEncoding() { return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' ); } /** * Most writing systems use whitespace to break up words. * Some languages such as Chinese don't conventionally do this, * which requires special handling when breaking up words for * searching etc. * * @return bool */ function hasWordBreaks() { return true; } /** * Some languages such as Chinese require word segmentation, * Specify such segmentation when overridden in derived class. * * @param string $string * @return string */ function segmentByWord( $string ) { return $string; } /** * Some languages have special punctuation need to be normalized. * Make such changes here. * * @param string $string * @return string */ function normalizeForSearch( $string ) { return self::convertDoubleWidth( $string ); } /** * convert double-width roman characters to single-width. * range: ff00-ff5f ~= 0020-007f * * @param string $string * * @return string */ protected static function convertDoubleWidth( $string ) { static $full = null; static $half = null; if ( $full === null ) { $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $full = str_split( $fullWidth, 3 ); $half = str_split( $halfWidth ); } $string = str_replace( $full, $half, $string ); return $string; } /** * @param string $string * @param string $pattern * @return string */ protected static function insertSpace( $string, $pattern ) { $string = preg_replace( $pattern, " $1 ", $string ); $string = preg_replace( '/ +/', ' ', $string ); return $string; } /** * @param array $termsArray * @return array */ function convertForSearchResult( $termsArray ) { # some languages, e.g. Chinese, need to do a conversion # in order for search results to be displayed correctly return $termsArray; } /** * Get the first character of a string. * * @param string $s * @return string */ function firstChar( $s ) { $matches = array(); preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' . '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches ); if ( isset( $matches[1] ) ) { if ( strlen( $matches[1] ) != 3 ) { return $matches[1]; } // Break down Hangul syllables to grab the first jamo $code = utf8ToCodepoint( $matches[1] ); if ( $code < 0xac00 || 0xd7a4 <= $code ) { return $matches[1]; } elseif ( $code < 0xb098 ) { return "\xe3\x84\xb1"; } elseif ( $code < 0xb2e4 ) { return "\xe3\x84\xb4"; } elseif ( $code < 0xb77c ) { return "\xe3\x84\xb7"; } elseif ( $code < 0xb9c8 ) { return "\xe3\x84\xb9"; } elseif ( $code < 0xbc14 ) { return "\xe3\x85\x81"; } elseif ( $code < 0xc0ac ) { return "\xe3\x85\x82"; } elseif ( $code < 0xc544 ) { return "\xe3\x85\x85"; } elseif ( $code < 0xc790 ) { return "\xe3\x85\x87"; } elseif ( $code < 0xcc28 ) { return "\xe3\x85\x88"; } elseif ( $code < 0xce74 ) { return "\xe3\x85\x8a"; } elseif ( $code < 0xd0c0 ) { return "\xe3\x85\x8b"; } elseif ( $code < 0xd30c ) { return "\xe3\x85\x8c"; } elseif ( $code < 0xd558 ) { return "\xe3\x85\x8d"; } else { return "\xe3\x85\x8e"; } } else { return ''; } } function initEncoding() { # Some languages may have an alternate char encoding option # (Esperanto X-coding, Japanese furigana conversion, etc) # If this language is used as the primary content language, # an override to the defaults can be set here on startup. } /** * @param string $s * @return string */ function recodeForEdit( $s ) { # For some languages we'll want to explicitly specify # which characters make it into the edit box raw # or are converted in some way or another. global $wgEditEncoding; if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) { return $s; } else { return $this->iconv( 'UTF-8', $wgEditEncoding, $s ); } } /** * @param string $s * @return string */ function recodeInput( $s ) { # Take the previous into account. global $wgEditEncoding; if ( $wgEditEncoding != '' ) { $enc = $wgEditEncoding; } else { $enc = 'UTF-8'; } if ( $enc == 'UTF-8' ) { return $s; } else { return $this->iconv( $enc, 'UTF-8', $s ); } } /** * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this * also cleans up certain backwards-compatible sequences, converting them * to the modern Unicode equivalent. * * This is language-specific for performance reasons only. * * @param string $s * * @return string */ function normalize( $s ) { global $wgAllUnicodeFixes; $s = UtfNormal::cleanUp( $s ); if ( $wgAllUnicodeFixes ) { $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s ); $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s ); } return $s; } /** * Transform a string using serialized data stored in the given file (which * must be in the serialized subdirectory of $IP). The file contains pairs * mapping source characters to destination characters. * * The data is cached in process memory. This will go faster if you have the * FastStringSearch extension. * * @param string $file * @param string $string * * @throws MWException * @return string */ function transformUsingPairFile( $file, $string ) { if ( !isset( $this->transformData[$file] ) ) { $data = wfGetPrecompiledData( $file ); if ( $data === false ) { throw new MWException( __METHOD__ . ": The transformation file $file is missing" ); } $this->transformData[$file] = new ReplacementArray( $data ); } return $this->transformData[$file]->replace( $string ); } /** * For right-to-left language support * * @return bool */ function isRTL() { return self::$dataCache->getItem( $this->mCode, 'rtl' ); } /** * Return the correct HTML 'dir' attribute value for this language. * @return string */ function getDir() { return $this->isRTL() ? 'rtl' : 'ltr'; } /** * Return 'left' or 'right' as appropriate alignment for line-start * for this language's text direction. * * Should be equivalent to CSS3 'start' text-align value.... * * @return string */ function alignStart() { return $this->isRTL() ? 'right' : 'left'; } /** * Return 'right' or 'left' as appropriate alignment for line-end * for this language's text direction. * * Should be equivalent to CSS3 'end' text-align value.... * * @return string */ function alignEnd() { return $this->isRTL() ? 'left' : 'right'; } /** * A hidden direction mark (LRM or RLM), depending on the language direction. * Unlike getDirMark(), this function returns the character as an HTML entity. * This function should be used when the output is guaranteed to be HTML, * because it makes the output HTML source code more readable. When * the output is plain text or can be escaped, getDirMark() should be used. * * @param bool $opposite Get the direction mark opposite to your language * @return string * @since 1.20 */ function getDirMarkEntity( $opposite = false ) { if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; } return $this->isRTL() ? '&rlm;' : '&lrm;'; } /** * A hidden direction mark (LRM or RLM), depending on the language direction. * This function produces them as invisible Unicode characters and * the output may be hard to read and debug, so it should only be used * when the output is plain text or can be escaped. When the output is * HTML, use getDirMarkEntity() instead. * * @param bool $opposite Get the direction mark opposite to your language * @return string */ function getDirMark( $opposite = false ) { $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; } return $this->isRTL() ? $rlm : $lrm; } /** * @return array */ function capitalizeAllNouns() { return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' ); } /** * An arrow, depending on the language direction. * * @param string $direction The direction of the arrow: forwards (default), * backwards, left, right, up, down. * @return string */ function getArrow( $direction = 'forwards' ) { switch ( $direction ) { case 'forwards': return $this->isRTL() ? '←' : '→'; case 'backwards': return $this->isRTL() ? '→' : '←'; case 'left': return '←'; case 'right': return '→'; case 'up': return '↑'; case 'down': return '↓'; } } /** * To allow "foo[[bar]]" to extend the link over the whole word "foobar" * * @return bool */ function linkPrefixExtension() { return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' ); } /** * Get all magic words from cache. * @return array */ function getMagicWords() { return self::$dataCache->getItem( $this->mCode, 'magicWords' ); } /** * Run the LanguageGetMagic hook once. */ protected function doMagicHook() { if ( $this->mMagicHookDone ) { return; } $this->mMagicHookDone = true; Hooks::run( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) ); } /** * Fill a MagicWord object with data from here * * @param MagicWord $mw */ function getMagic( $mw ) { // Saves a function call if ( !$this->mMagicHookDone ) { $this->doMagicHook(); } if ( isset( $this->mMagicExtensions[$mw->mId] ) ) { $rawEntry = $this->mMagicExtensions[$mw->mId]; } else { $rawEntry = self::$dataCache->getSubitem( $this->mCode, 'magicWords', $mw->mId ); } if ( !is_array( $rawEntry ) ) { wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" ); } else { $mw->mCaseSensitive = $rawEntry[0]; $mw->mSynonyms = array_slice( $rawEntry, 1 ); } } /** * Add magic words to the extension array * * @param array $newWords */ function addMagicWordsByLang( $newWords ) { $fallbackChain = $this->getFallbackLanguages(); $fallbackChain = array_reverse( $fallbackChain ); foreach ( $fallbackChain as $code ) { if ( isset( $newWords[$code] ) ) { $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions; } } } /** * Get special page names, as an associative array * canonical name => array of valid names, including aliases * @return array */ function getSpecialPageAliases() { // Cache aliases because it may be slow to load them if ( is_null( $this->mExtendedSpecialPageAliases ) ) { // Initialise array $this->mExtendedSpecialPageAliases = self::$dataCache->getItem( $this->mCode, 'specialPageAliases' ); Hooks::run( 'LanguageGetSpecialPageAliases', array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) ); } return $this->mExtendedSpecialPageAliases; } /** * Italic is unsuitable for some languages * * @param string $text The text to be emphasized. * @return string */ function emphasize( $text ) { return "<em>$text</em>"; } /** * Normally we output all numbers in plain en_US style, that is * 293,291.235 for twohundredninetythreethousand-twohundredninetyone * point twohundredthirtyfive. However this is not suitable for all * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as * Icelandic just want to use commas instead of dots, and dots instead * of commas like "293.291,235". * * An example of this function being called: * <code> * wfMessage( 'message' )->numParams( $num )->text() * </code> * * See $separatorTransformTable on MessageIs.php for * the , => . and . => , implementation. * * @todo check if it's viable to use localeconv() for the decimal separator thing. * @param int|float $number The string to be formatted, should be an integer * or a floating point number. * @param bool $nocommafy Set to true for special numbers like dates * @return string */ public function formatNum( $number, $nocommafy = false ) { global $wgTranslateNumerals; if ( !$nocommafy ) { $number = $this->commafy( $number ); $s = $this->separatorTransformTable(); if ( $s ) { $number = strtr( $number, $s ); } } if ( $wgTranslateNumerals ) { $s = $this->digitTransformTable(); if ( $s ) { $number = strtr( $number, $s ); } } return $number; } /** * Front-end for non-commafied formatNum * * @param int|float $number The string to be formatted, should be an integer * or a floating point number. * @since 1.21 * @return string */ public function formatNumNoSeparators( $number ) { return $this->formatNum( $number, true ); } /** * @param string $number * @return string */ public function parseFormattedNumber( $number ) { $s = $this->digitTransformTable(); if ( $s ) { // eliminate empty array values such as ''. (bug 64347) $s = array_filter( $s ); $number = strtr( $number, array_flip( $s ) ); } $s = $this->separatorTransformTable(); if ( $s ) { // eliminate empty array values such as ''. (bug 64347) $s = array_filter( $s ); $number = strtr( $number, array_flip( $s ) ); } $number = strtr( $number, array( ',' => '' ) ); return $number; } /** * Adds commas to a given number * @since 1.19 * @param mixed $number * @return string */ function commafy( $number ) { $digitGroupingPattern = $this->digitGroupingPattern(); if ( $number === null ) { return ''; } if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) { // default grouping is at thousands, use the same for ###,###,### pattern too. return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) ); } else { // Ref: http://cldr.unicode.org/translation/number-patterns $sign = ""; if ( intval( $number ) < 0 ) { // For negative numbers apply the algorithm like positive number and add sign. $sign = "-"; $number = substr( $number, 1 ); } $integerPart = array(); $decimalPart = array(); $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches ); preg_match( "/\d+/", $number, $integerPart ); preg_match( "/\.\d*/", $number, $decimalPart ); $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : ""; if ( $groupedNumber === $number ) { // the string does not have any number part. Eg: .12345 return $sign . $groupedNumber; } $start = $end = ($integerPart) ? strlen( $integerPart[0] ) : 0; while ( $start > 0 ) { $match = $matches[0][$numMatches - 1]; $matchLen = strlen( $match ); $start = $end - $matchLen; if ( $start < 0 ) { $start = 0; } $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber; $end = $start; if ( $numMatches > 1 ) { // use the last pattern for the rest of the number $numMatches--; } if ( $start > 0 ) { $groupedNumber = "," . $groupedNumber; } } return $sign . $groupedNumber; } } /** * @return string */ function digitGroupingPattern() { return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' ); } /** * @return array */ function digitTransformTable() { return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' ); } /** * @return array */ function separatorTransformTable() { return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' ); } /** * Take a list of strings and build a locale-friendly comma-separated * list, using the local comma-separator message. * The last two strings are chained with an "and". * NOTE: This function will only work with standard numeric array keys (0, 1, 2…) * * @param string[] $l * @return string */ function listToText( array $l ) { $m = count( $l ) - 1; if ( $m < 0 ) { return ''; } if ( $m > 0 ) { $and = $this->msg( 'and' )->escaped(); $space = $this->msg( 'word-separator' )->escaped(); if ( $m > 1 ) { $comma = $this->msg( 'comma-separator' )->escaped(); } } $s = $l[$m]; for ( $i = $m - 1; $i >= 0; $i-- ) { if ( $i == $m - 1 ) { $s = $l[$i] . $and . $space . $s; } else { $s = $l[$i] . $comma . $s; } } return $s; } /** * Take a list of strings and build a locale-friendly comma-separated * list, using the local comma-separator message. * @param string[] $list Array of strings to put in a comma list * @return string */ function commaList( array $list ) { return implode( wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(), $list ); } /** * Take a list of strings and build a locale-friendly semicolon-separated * list, using the local semicolon-separator message. * @param string[] $list Array of strings to put in a semicolon list * @return string */ function semicolonList( array $list ) { return implode( wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(), $list ); } /** * Same as commaList, but separate it with the pipe instead. * @param string[] $list Array of strings to put in a pipe list * @return string */ function pipeList( array $list ) { return implode( wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(), $list ); } /** * Truncate a string to a specified length in bytes, appending an optional * string (e.g. for ellipses) * * The database offers limited byte lengths for some columns in the database; * multi-byte character sets mean we need to ensure that only whole characters * are included, otherwise broken characters can be passed to the user * * If $length is negative, the string will be truncated from the beginning * * @param string $string String to truncate * @param int $length Maximum length (including ellipses) * @param string $ellipsis String to append to the truncated text * @param bool $adjustLength Subtract length of ellipsis from $length. * $adjustLength was introduced in 1.18, before that behaved as if false. * @return string */ function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) { # Use the localized ellipsis character if ( $ellipsis == '...' ) { $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped(); } # Check if there is no need to truncate if ( $length == 0 ) { return $ellipsis; // convention } elseif ( strlen( $string ) <= abs( $length ) ) { return $string; // no need to truncate } $stringOriginal = $string; # If ellipsis length is >= $length then we can't apply $adjustLength if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) { $string = $ellipsis; // this can be slightly unexpected # Otherwise, truncate and add ellipsis... } else { $eLength = $adjustLength ? strlen( $ellipsis ) : 0; if ( $length > 0 ) { $length -= $eLength; $string = substr( $string, 0, $length ); // xyz... $string = $this->removeBadCharLast( $string ); $string = rtrim( $string ); $string = $string . $ellipsis; } else { $length += $eLength; $string = substr( $string, $length ); // ...xyz $string = $this->removeBadCharFirst( $string ); $string = ltrim( $string ); $string = $ellipsis . $string; } } # Do not truncate if the ellipsis makes the string longer/equal (bug 22181). # This check is *not* redundant if $adjustLength, due to the single case where # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string. if ( strlen( $string ) < strlen( $stringOriginal ) ) { return $string; } else { return $stringOriginal; } } /** * Remove bytes that represent an incomplete Unicode character * at the end of string (e.g. bytes of the char are missing) * * @param string $string * @return string */ protected function removeBadCharLast( $string ) { if ( $string != '' ) { $char = ord( $string[strlen( $string ) - 1] ); $m = array(); if ( $char >= 0xc0 ) { # We got the first byte only of a multibyte char; remove it. $string = substr( $string, 0, -1 ); } elseif ( $char >= 0x80 && preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' . '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) { # We chopped in the middle of a character; remove it $string = $m[1]; } } return $string; } /** * Remove bytes that represent an incomplete Unicode character * at the start of string (e.g. bytes of the char are missing) * * @param string $string * @return string */ protected function removeBadCharFirst( $string ) { if ( $string != '' ) { $char = ord( $string[0] ); if ( $char >= 0x80 && $char < 0xc0 ) { # We chopped in the middle of a character; remove the whole thing $string = preg_replace( '/^[\x80-\xbf]+/', '', $string ); } } return $string; } /** * Truncate a string of valid HTML to a specified length in bytes, * appending an optional string (e.g. for ellipses), and return valid HTML * * This is only intended for styled/linked text, such as HTML with * tags like <span> and <a>, were the tags are self-contained (valid HTML). * Also, this will not detect things like "display:none" CSS. * * Note: since 1.18 you do not need to leave extra room in $length for ellipses. * * @param string $text HTML string to truncate * @param int $length (zero/positive) Maximum length (including ellipses) * @param string $ellipsis String to append to the truncated text * @return string */ function truncateHtml( $text, $length, $ellipsis = '...' ) { # Use the localized ellipsis character if ( $ellipsis == '...' ) { $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped(); } # Check if there is clearly no need to truncate if ( $length <= 0 ) { return $ellipsis; // no text shown, nothing to format (convention) } elseif ( strlen( $text ) <= $length ) { return $text; // string short enough even *with* HTML (short-circuit) } $dispLen = 0; // innerHTML legth so far $testingEllipsis = false; // checking if ellipses will make string longer/equal? $tagType = 0; // 0-open, 1-close $bracketState = 0; // 1-tag start, 2-tag name, 0-neither $entityState = 0; // 0-not entity, 1-entity $tag = $ret = ''; // accumulated tag name, accumulated result string $openTags = array(); // open tag stack $maybeState = null; // possible truncation state $textLen = strlen( $text ); $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated for ( $pos = 0; true; ++$pos ) { # Consider truncation once the display length has reached the maximim. # We check if $dispLen > 0 to grab tags for the $neLength = 0 case. # Check that we're not in the middle of a bracket/entity... if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) { if ( !$testingEllipsis ) { $testingEllipsis = true; # Save where we are; we will truncate here unless there turn out to # be so few remaining characters that truncation is not necessary. if ( !$maybeState ) { // already saved? ($neLength = 0 case) $maybeState = array( $ret, $openTags ); // save state } } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) { # String in fact does need truncation, the truncation point was OK. list( $ret, $openTags ) = $maybeState; // reload state $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix $ret .= $ellipsis; // add ellipsis break; } } if ( $pos >= $textLen ) { break; // extra iteration just for above checks } # Read the next char... $ch = $text[$pos]; $lastCh = $pos ? $text[$pos - 1] : ''; $ret .= $ch; // add to result string if ( $ch == '<' ) { $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML $entityState = 0; // for bad HTML $bracketState = 1; // tag started (checking for backslash) } elseif ( $ch == '>' ) { $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); $entityState = 0; // for bad HTML $bracketState = 0; // out of brackets } elseif ( $bracketState == 1 ) { if ( $ch == '/' ) { $tagType = 1; // close tag (e.g. "</span>") } else { $tagType = 0; // open tag (e.g. "<span>") $tag .= $ch; } $bracketState = 2; // building tag name } elseif ( $bracketState == 2 ) { if ( $ch != ' ' ) { $tag .= $ch; } else { // Name found (e.g. "<a href=..."), add on tag attributes... $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 ); } } elseif ( $bracketState == 0 ) { if ( $entityState ) { if ( $ch == ';' ) { $entityState = 0; $dispLen++; // entity is one displayed char } } else { if ( $neLength == 0 && !$maybeState ) { // Save state without $ch. We want to *hit* the first // display char (to get tags) but not *use* it if truncating. $maybeState = array( substr( $ret, 0, -1 ), $openTags ); } if ( $ch == '&' ) { $entityState = 1; // entity found, (e.g. "&#160;") } else { $dispLen++; // this char is displayed // Add the next $max display text chars after this in one swoop... $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen; $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max ); $dispLen += $skipped; $pos += $skipped; } } } } // Close the last tag if left unclosed by bad HTML $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); while ( count( $openTags ) > 0 ) { $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags } return $ret; } /** * truncateHtml() helper function * like strcspn() but adds the skipped chars to $ret * * @param string $ret * @param string $text * @param string $search * @param int $start * @param null|int $len * @return int */ private function truncate_skip( &$ret, $text, $search, $start, $len = null ) { if ( $len === null ) { $len = -1; // -1 means "no limit" for strcspn } elseif ( $len < 0 ) { $len = 0; // sanity } $skipCount = 0; if ( $start < strlen( $text ) ) { $skipCount = strcspn( $text, $search, $start, $len ); $ret .= substr( $text, $start, $skipCount ); } return $skipCount; } /** * truncateHtml() helper function * (a) push or pop $tag from $openTags as needed * (b) clear $tag value * @param string &$tag Current HTML tag name we are looking at * @param int $tagType (0-open tag, 1-close tag) * @param string $lastCh Character before the '>' that ended this tag * @param array &$openTags Open tag stack (not accounting for $tag) */ private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) { $tag = ltrim( $tag ); if ( $tag != '' ) { if ( $tagType == 0 && $lastCh != '/' ) { $openTags[] = $tag; // tag opened (didn't close itself) } elseif ( $tagType == 1 ) { if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) { array_pop( $openTags ); // tag closed } } $tag = ''; } } /** * Grammatical transformations, needed for inflected languages * Invoked by putting {{grammar:case|word}} in a message * * @param string $word * @param string $case * @return string */ function convertGrammar( $word, $case ) { global $wgGrammarForms; if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) { return $wgGrammarForms[$this->getCode()][$case][$word]; } return $word; } /** * Get the grammar forms for the content language * @return array Array of grammar forms * @since 1.20 */ function getGrammarForms() { global $wgGrammarForms; if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) { return $wgGrammarForms[$this->getCode()]; } return array(); } /** * Provides an alternative text depending on specified gender. * Usage {{gender:username|masculine|feminine|unknown}}. * username is optional, in which case the gender of current user is used, * but only in (some) interface messages; otherwise default gender is used. * * If no forms are given, an empty string is returned. If only one form is * given, it will be returned unconditionally. These details are implied by * the caller and cannot be overridden in subclasses. * * If three forms are given, the default is to use the third (unknown) form. * If fewer than three forms are given, the default is to use the first (masculine) form. * These details can be overridden in subclasses. * * @param string $gender * @param array $forms * * @return string */ function gender( $gender, $forms ) { if ( !count( $forms ) ) { return ''; } $forms = $this->preConvertPlural( $forms, 2 ); if ( $gender === 'male' ) { return $forms[0]; } if ( $gender === 'female' ) { return $forms[1]; } return isset( $forms[2] ) ? $forms[2] : $forms[0]; } /** * Plural form transformations, needed for some languages. * For example, there are 3 form of plural in Russian and Polish, * depending on "count mod 10". See [[w:Plural]] * For English it is pretty simple. * * Invoked by putting {{plural:count|wordform1|wordform2}} * or {{plural:count|wordform1|wordform2|wordform3}} * * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}} * * @param int $count Non-localized number * @param array $forms Different plural forms * @return string Correct form of plural for $count in this language */ function convertPlural( $count, $forms ) { // Handle explicit n=pluralform cases $forms = $this->handleExplicitPluralForms( $count, $forms ); if ( is_string( $forms ) ) { return $forms; } if ( !count( $forms ) ) { return ''; } $pluralForm = $this->getPluralRuleIndexNumber( $count ); $pluralForm = min( $pluralForm, count( $forms ) - 1 ); return $forms[$pluralForm]; } /** * Handles explicit plural forms for Language::convertPlural() * * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero. * If an explicitly defined plural form matches the $count, then * string value returned, otherwise array returned for further consideration * by CLDR rules or overridden convertPlural(). * * @since 1.23 * * @param int $count Non-localized number * @param array $forms Different plural forms * * @return array|string */ protected function handleExplicitPluralForms( $count, array $forms ) { foreach ( $forms as $index => $form ) { if ( preg_match( '/\d+=/i', $form ) ) { $pos = strpos( $form, '=' ); if ( substr( $form, 0, $pos ) === (string)$count ) { return substr( $form, $pos + 1 ); } unset( $forms[$index] ); } } return array_values( $forms ); } /** * Checks that convertPlural was given an array and pads it to requested * amount of forms by copying the last one. * * @param array $forms Array of forms given to convertPlural * @param int $count How many forms should there be at least * @return array Padded array of forms or an exception if not an array */ protected function preConvertPlural( /* Array */ $forms, $count ) { while ( count( $forms ) < $count ) { $forms[] = $forms[count( $forms ) - 1]; } return $forms; } /** * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used * on old expiry lengths recorded in log entries. You'd need to provide the start date to * match up with it. * * @param string $str The validated block duration in English * @return string Somehow translated block duration * @see LanguageFi.php for example implementation */ function translateBlockExpiry( $str ) { $duration = SpecialBlock::getSuggestedDurations( $this ); foreach ( $duration as $show => $value ) { if ( strcmp( $str, $value ) == 0 ) { return htmlspecialchars( trim( $show ) ); } } // Since usually only infinite or indefinite is only on list, so try // equivalents if still here. $indefs = array( 'infinite', 'infinity', 'indefinite' ); if ( in_array( $str, $indefs ) ) { foreach ( $indefs as $val ) { $show = array_search( $val, $duration, true ); if ( $show !== false ) { return htmlspecialchars( trim( $show ) ); } } } // If all else fails, return a standard duration or timestamp description. $time = strtotime( $str, 0 ); if ( $time === false ) { // Unknown format. Return it as-is in case. return $str; } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp. // $time is relative to 0 so it's a duration length. return $this->formatDuration( $time ); } else { // It's an absolute timestamp. if ( $time === 0 ) { // wfTimestamp() handles 0 as current time instead of epoch. return $this->timeanddate( '19700101000000' ); } else { return $this->timeanddate( $time ); } } } /** * languages like Chinese need to be segmented in order for the diff * to be of any use * * @param string $text * @return string */ public function segmentForDiff( $text ) { return $text; } /** * and unsegment to show the result * * @param string $text * @return string */ public function unsegmentForDiff( $text ) { return $text; } /** * Return the LanguageConverter used in the Language * * @since 1.19 * @return LanguageConverter */ public function getConverter() { return $this->mConverter; } /** * convert text to all supported variants * * @param string $text * @return array */ public function autoConvertToAllVariants( $text ) { return $this->mConverter->autoConvertToAllVariants( $text ); } /** * convert text to different variants of a language. * * @param string $text * @return string */ public function convert( $text ) { return $this->mConverter->convert( $text ); } /** * Convert a Title object to a string in the preferred variant * * @param Title $title * @return string */ public function convertTitle( $title ) { return $this->mConverter->convertTitle( $title ); } /** * Convert a namespace index to a string in the preferred variant * * @param int $ns * @return string */ public function convertNamespace( $ns ) { return $this->mConverter->convertNamespace( $ns ); } /** * Check if this is a language with variants * * @return bool */ public function hasVariants() { return count( $this->getVariants() ) > 1; } /** * Check if the language has the specific variant * * @since 1.19 * @param string $variant * @return bool */ public function hasVariant( $variant ) { return (bool)$this->mConverter->validateVariant( $variant ); } /** * Put custom tags (e.g. -{ }-) around math to prevent conversion * * @param string $text * @return string * @deprecated since 1.22 is no longer used */ public function armourMath( $text ) { return $this->mConverter->armourMath( $text ); } /** * Perform output conversion on a string, and encode for safe HTML output. * @param string $text Text to be converted * @param bool $isTitle Whether this conversion is for the article title * @return string * @todo this should get integrated somewhere sane */ public function convertHtml( $text, $isTitle = false ) { return htmlspecialchars( $this->convert( $text, $isTitle ) ); } /** * @param string $key * @return string */ public function convertCategoryKey( $key ) { return $this->mConverter->convertCategoryKey( $key ); } /** * Get the list of variants supported by this language * see sample implementation in LanguageZh.php * * @return array An array of language codes */ public function getVariants() { return $this->mConverter->getVariants(); } /** * @return string */ public function getPreferredVariant() { return $this->mConverter->getPreferredVariant(); } /** * @return string */ public function getDefaultVariant() { return $this->mConverter->getDefaultVariant(); } /** * @return string */ public function getURLVariant() { return $this->mConverter->getURLVariant(); } /** * If a language supports multiple variants, it is * possible that non-existing link in one variant * actually exists in another variant. this function * tries to find it. See e.g. LanguageZh.php * The input parameters may be modified upon return * * @param string &$link The name of the link * @param Title &$nt The title object of the link * @param bool $ignoreOtherCond To disable other conditions when * we need to transclude a template or update a category's link */ public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) { $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond ); } /** * returns language specific options used by User::getPageRenderHash() * for example, the preferred language variant * * @return string */ function getExtraHashOptions() { return $this->mConverter->getExtraHashOptions(); } /** * For languages that support multiple variants, the title of an * article may be displayed differently in different variants. this * function returns the apporiate title defined in the body of the article. * * @return string */ public function getParsedTitle() { return $this->mConverter->getParsedTitle(); } /** * Prepare external link text for conversion. When the text is * a URL, it shouldn't be converted, and it'll be wrapped in * the "raw" tag (-{R| }-) to prevent conversion. * * This function is called "markNoConversion" for historical * reasons. * * @param string $text Text to be used for external link * @param bool $noParse Wrap it without confirming it's a real URL first * @return string The tagged text */ public function markNoConversion( $text, $noParse = false ) { // Excluding protocal-relative URLs may avoid many false positives. if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) { return $this->mConverter->markNoConversion( $text ); } else { return $text; } } /** * A regular expression to match legal word-trailing characters * which should be merged onto a link of the form [[foo]]bar. * * @return string */ public function linkTrail() { return self::$dataCache->getItem( $this->mCode, 'linkTrail' ); } /** * A regular expression character set to match legal word-prefixing * characters which should be merged onto a link of the form foo[[bar]]. * * @return string */ public function linkPrefixCharset() { return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' ); } /** * @deprecated since 1.24, will be removed in 1.25 * @return Language */ function getLangObj() { wfDeprecated( __METHOD__, '1.24' ); return $this; } /** * Get the "parent" language which has a converter to convert a "compatible" language * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb). * * @return Language|null * @since 1.22 */ public function getParentLanguage() { if ( $this->mParentLanguage !== false ) { return $this->mParentLanguage; } $pieces = explode( '-', $this->getCode() ); $code = $pieces[0]; if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) { $this->mParentLanguage = null; return null; } $lang = Language::factory( $code ); if ( !$lang->hasVariant( $this->getCode() ) ) { $this->mParentLanguage = null; return null; } $this->mParentLanguage = $lang; return $lang; } /** * Get the RFC 3066 code for this language object * * NOTE: The return value of this function is NOT HTML-safe and must be escaped with * htmlspecialchars() or similar * * @return string */ public function getCode() { return $this->mCode; } /** * Get the code in Bcp47 format which we can use * inside of html lang="" tags. * * NOTE: The return value of this function is NOT HTML-safe and must be escaped with * htmlspecialchars() or similar. * * @since 1.19 * @return string */ public function getHtmlCode() { if ( is_null( $this->mHtmlCode ) ) { $this->mHtmlCode = wfBCP47( $this->getCode() ); } return $this->mHtmlCode; } /** * @param string $code */ public function setCode( $code ) { $this->mCode = $code; // Ensure we don't leave incorrect cached data lying around $this->mHtmlCode = null; $this->mParentLanguage = false; } /** * Get the name of a file for a certain language code * @param string $prefix Prepend this to the filename * @param string $code Language code * @param string $suffix Append this to the filename * @throws MWException * @return string $prefix . $mangledCode . $suffix */ public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) { if ( !self::isValidBuiltInCode( $code ) ) { throw new MWException( "Invalid language code \"$code\"" ); } return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix; } /** * Get the language code from a file name. Inverse of getFileName() * @param string $filename $prefix . $languageCode . $suffix * @param string $prefix Prefix before the language code * @param string $suffix Suffix after the language code * @return string Language code, or false if $prefix or $suffix isn't found */ public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) { $m = null; preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' . preg_quote( $suffix, '/' ) . '/', $filename, $m ); if ( !count( $m ) ) { return false; } return str_replace( '_', '-', strtolower( $m[1] ) ); } /** * @param string $code * @return string */ public static function getMessagesFileName( $code ) { global $IP; $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' ); Hooks::run( 'Language::getMessagesFileName', array( $code, &$file ) ); return $file; } /** * @param string $code * @return string * @since 1.23 */ public static function getJsonMessagesFileName( $code ) { global $IP; if ( !self::isValidBuiltInCode( $code ) ) { throw new MWException( "Invalid language code \"$code\"" ); } return "$IP/languages/i18n/$code.json"; } /** * @param string $code * @return string */ public static function getClassFileName( $code ) { global $IP; return self::getFileName( "$IP/languages/classes/Language", $code, '.php' ); } /** * Get the first fallback for a given language. * * @param string $code * * @return bool|string */ public static function getFallbackFor( $code ) { if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) { return false; } else { $fallbacks = self::getFallbacksFor( $code ); $first = array_shift( $fallbacks ); return $first; } } /** * Get the ordered list of fallback languages. * * @since 1.19 * @param string $code Language code * @return array */ public static function getFallbacksFor( $code ) { if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) { return array(); } else { $v = self::getLocalisationCache()->getItem( $code, 'fallback' ); $v = array_map( 'trim', explode( ',', $v ) ); if ( $v[count( $v ) - 1] !== 'en' ) { $v[] = 'en'; } return $v; } } /** * Get the ordered list of fallback languages, ending with the fallback * language chain for the site language. * * @since 1.22 * @param string $code Language code * @return array Array( fallbacks, site fallbacks ) */ public static function getFallbacksIncludingSiteLanguage( $code ) { global $wgLanguageCode; // Usually, we will only store a tiny number of fallback chains, so we // keep them in static memory. $cacheKey = "{$code}-{$wgLanguageCode}"; if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) { $fallbacks = self::getFallbacksFor( $code ); // Append the site's fallback chain, including the site language itself $siteFallbacks = self::getFallbacksFor( $wgLanguageCode ); array_unshift( $siteFallbacks, $wgLanguageCode ); // Eliminate any languages already included in the chain $siteFallbacks = array_diff( $siteFallbacks, $fallbacks ); self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks ); } return self::$fallbackLanguageCache[$cacheKey]; } /** * Get all messages for a given language * WARNING: this may take a long time. If you just need all message *keys* * but need the *contents* of only a few messages, consider using getMessageKeysFor(). * * @param string $code * * @return array */ public static function getMessagesFor( $code ) { return self::getLocalisationCache()->getItem( $code, 'messages' ); } /** * Get a message for a given language * * @param string $key * @param string $code * * @return string */ public static function getMessageFor( $key, $code ) { return self::getLocalisationCache()->getSubitem( $code, 'messages', $key ); } /** * Get all message keys for a given language. This is a faster alternative to * array_keys( Language::getMessagesFor( $code ) ) * * @since 1.19 * @param string $code Language code * @return array Array of message keys (strings) */ public static function getMessageKeysFor( $code ) { return self::getLocalisationCache()->getSubItemList( $code, 'messages' ); } /** * @param string $talk * @return mixed */ function fixVariableInNamespace( $talk ) { if ( strpos( $talk, '$1' ) === false ) { return $talk; } global $wgMetaNamespace; $talk = str_replace( '$1', $wgMetaNamespace, $talk ); # Allow grammar transformations # Allowing full message-style parsing would make simple requests # such as action=raw much more expensive than they need to be. # This will hopefully cover most cases. $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i', array( &$this, 'replaceGrammarInNamespace' ), $talk ); return str_replace( ' ', '_', $talk ); } /** * @param string $m * @return string */ function replaceGrammarInNamespace( $m ) { return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) ); } /** * @throws MWException * @return array */ static function getCaseMaps() { static $wikiUpperChars, $wikiLowerChars; if ( isset( $wikiUpperChars ) ) { return array( $wikiUpperChars, $wikiLowerChars ); } $arr = wfGetPrecompiledData( 'Utf8Case.ser' ); if ( $arr === false ) { throw new MWException( "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" ); } $wikiUpperChars = $arr['wikiUpperChars']; $wikiLowerChars = $arr['wikiLowerChars']; return array( $wikiUpperChars, $wikiLowerChars ); } /** * Decode an expiry (block, protection, etc) which has come from the DB * * @todo FIXME: why are we returnings DBMS-dependent strings??? * * @param string $expiry Database expiry String * @param bool|int $format True to process using language functions, or TS_ constant * to return the expiry in a given timestamp * @return string * @since 1.18 */ public function formatExpiry( $expiry, $format = true ) { static $infinity; if ( $infinity === null ) { $infinity = wfGetDB( DB_SLAVE )->getInfinity(); } if ( $expiry == '' || $expiry == $infinity ) { return $format === true ? $this->getMessageFromDB( 'infiniteblock' ) : $infinity; } else { return $format === true ? $this->timeanddate( $expiry, /* User preference timezone */ true ) : wfTimestamp( $format, $expiry ); } } /** * @todo Document * @param int|float $seconds * @param array $format Optional * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour. * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours. * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev' * and friends. * For backwards compatibility, $format may also be one of the strings 'avoidseconds' * or 'avoidminutes'. * @return string */ function formatTimePeriod( $seconds, $format = array() ) { if ( !is_array( $format ) ) { $format = array( 'avoid' => $format ); // For backwards compatibility } if ( !isset( $format['avoid'] ) ) { $format['avoid'] = false; } if ( !isset( $format['noabbrevs'] ) ) { $format['noabbrevs'] = false; } $secondsMsg = wfMessage( $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this ); $minutesMsg = wfMessage( $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this ); $hoursMsg = wfMessage( $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this ); $daysMsg = wfMessage( $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this ); if ( round( $seconds * 10 ) < 100 ) { $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ); $s = $secondsMsg->params( $s )->text(); } elseif ( round( $seconds ) < 60 ) { $s = $this->formatNum( round( $seconds ) ); $s = $secondsMsg->params( $s )->text(); } elseif ( round( $seconds ) < 3600 ) { $minutes = floor( $seconds / 60 ); $secondsPart = round( fmod( $seconds, 60 ) ); if ( $secondsPart == 60 ) { $secondsPart = 0; $minutes++; } $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text(); $s .= ' '; $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text(); } elseif ( round( $seconds ) <= 2 * 86400 ) { $hours = floor( $seconds / 3600 ); $minutes = floor( ( $seconds - $hours * 3600 ) / 60 ); $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 ); if ( $secondsPart == 60 ) { $secondsPart = 0; $minutes++; } if ( $minutes == 60 ) { $minutes = 0; $hours++; } $s = $hoursMsg->params( $this->formatNum( $hours ) )->text(); $s .= ' '; $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text(); if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) { $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text(); } } else { $days = floor( $seconds / 86400 ); if ( $format['avoid'] === 'avoidminutes' ) { $hours = round( ( $seconds - $days * 86400 ) / 3600 ); if ( $hours == 24 ) { $hours = 0; $days++; } $s = $daysMsg->params( $this->formatNum( $days ) )->text(); $s .= ' '; $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text(); } elseif ( $format['avoid'] === 'avoidseconds' ) { $hours = floor( ( $seconds - $days * 86400 ) / 3600 ); $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 ); if ( $minutes == 60 ) { $minutes = 0; $hours++; } if ( $hours == 24 ) { $hours = 0; $days++; } $s = $daysMsg->params( $this->formatNum( $days ) )->text(); $s .= ' '; $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text(); $s .= ' '; $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text(); } else { $s = $daysMsg->params( $this->formatNum( $days ) )->text(); $s .= ' '; $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format ); } } return $s; } /** * Format a bitrate for output, using an appropriate * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to * the magnitude in question. * * This use base 1000. For base 1024 use formatSize(), for another base * see formatComputingNumbers(). * * @param int $bps * @return string */ function formatBitrate( $bps ) { return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" ); } /** * @param int $size Size of the unit * @param int $boundary Size boundary (1000, or 1024 in most cases) * @param string $messageKey Message key to be uesd * @return string */ function formatComputingNumbers( $size, $boundary, $messageKey ) { if ( $size <= 0 ) { return str_replace( '$1', $this->formatNum( $size ), $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) ) ); } $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' ); $index = 0; $maxIndex = count( $sizes ) - 1; while ( $size >= $boundary && $index < $maxIndex ) { $index++; $size /= $boundary; } // For small sizes no decimal places necessary $round = 0; if ( $index > 1 ) { // For MB and bigger two decimal places are smarter $round = 2; } $msg = str_replace( '$1', $sizes[$index], $messageKey ); $size = round( $size, $round ); $text = $this->getMessageFromDB( $msg ); return str_replace( '$1', $this->formatNum( $size ), $text ); } /** * Format a size in bytes for output, using an appropriate * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question * * This method use base 1024. For base 1000 use formatBitrate(), for * another base see formatComputingNumbers() * * @param int $size Size to format * @return string Plain text (not HTML) */ function formatSize( $size ) { return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" ); } /** * Make a list item, used by various special pages * * @param string $page Page link * @param string $details HTML safe text between brackets * @param bool $oppositedm Add the direction mark opposite to your * language, to display text properly * @return HTML escaped string */ function specialList( $page, $details, $oppositedm = true ) { if ( !$details ) { return $page; } $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark(); return $page . $dirmark . $this->msg( 'word-separator' )->escaped() . $this->msg( 'parentheses' )->rawParams( $details )->escaped(); } /** * Generate (prev x| next x) (20|50|100...) type links for paging * * @param Title $title Title object to link * @param int $offset * @param int $limit * @param array $query Optional URL query parameter string * @param bool $atend Optional param for specified if this is the last page * @return string */ public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) { // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip? # Make 'previous' link $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text(); if ( $offset > 0 ) { $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit, $query, $prev, 'prevn-title', 'mw-prevlink' ); } else { $plink = htmlspecialchars( $prev ); } # Make 'next' link $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text(); if ( $atend ) { $nlink = htmlspecialchars( $next ); } else { $nlink = $this->numLink( $title, $offset + $limit, $limit, $query, $next, 'nextn-title', 'mw-nextlink' ); } # Make links to set number of items per page $numLinks = array(); foreach ( array( 20, 50, 100, 250, 500 ) as $num ) { $numLinks[] = $this->numLink( $title, $offset, $num, $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' ); } return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped(); } /** * Helper function for viewPrevNext() that generates links * * @param Title $title Title object to link * @param int $offset * @param int $limit * @param array $query Extra query parameters * @param string $link Text to use for the link; will be escaped * @param string $tooltipMsg Name of the message to use as tooltip * @param string $class Value of the "class" attribute of the link * @return string HTML fragment */ private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) { $query = array( 'limit' => $limit, 'offset' => $offset ) + $query; $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title ) ->numParams( $limit )->text(); return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ), 'title' => $tooltip, 'class' => $class ), $link ); } /** * Get the conversion rule title, if any. * * @return string */ public function getConvRuleTitle() { return $this->mConverter->getConvRuleTitle(); } /** * Get the compiled plural rules for the language * @since 1.20 * @return array Associative array with plural form, and plural rule as key-value pairs */ public function getCompiledPluralRules() { $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' ); $fallbacks = Language::getFallbacksFor( $this->mCode ); if ( !$pluralRules ) { foreach ( $fallbacks as $fallbackCode ) { $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' ); if ( $pluralRules ) { break; } } } return $pluralRules; } /** * Get the plural rules for the language * @since 1.20 * @return array Associative array with plural form number and plural rule as key-value pairs */ public function getPluralRules() { $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' ); $fallbacks = Language::getFallbacksFor( $this->mCode ); if ( !$pluralRules ) { foreach ( $fallbacks as $fallbackCode ) { $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' ); if ( $pluralRules ) { break; } } } return $pluralRules; } /** * Get the plural rule types for the language * @since 1.22 * @return array Associative array with plural form number and plural rule type as key-value pairs */ public function getPluralRuleTypes() { $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' ); $fallbacks = Language::getFallbacksFor( $this->mCode ); if ( !$pluralRuleTypes ) { foreach ( $fallbacks as $fallbackCode ) { $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' ); if ( $pluralRuleTypes ) { break; } } } return $pluralRuleTypes; } /** * Find the index number of the plural rule appropriate for the given number * @param int $number * @return int The index number of the plural rule */ public function getPluralRuleIndexNumber( $number ) { $pluralRules = $this->getCompiledPluralRules(); $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules ); return $form; } /** * Find the plural rule type appropriate for the given number * For example, if the language is set to Arabic, getPluralType(5) should * return 'few'. * @since 1.22 * @param int $number * @return string The name of the plural rule type, e.g. one, two, few, many */ public function getPluralRuleType( $number ) { $index = $this->getPluralRuleIndexNumber( $number ); $pluralRuleTypes = $this->getPluralRuleTypes(); if ( isset( $pluralRuleTypes[$index] ) ) { return $pluralRuleTypes[$index]; } else { return 'other'; } } }
hipbr/hipbr.github.io
mediawiki-master/languages/Language.php
PHP
gpl-2.0
141,907
# -*- coding: utf-8 -*- # # # TheVirtualBrain-Scientific Package. This package holds all simulators, and # analysers necessary to run brain-simulations. You can use it stand alone or # in conjunction with TheVirtualBrain-Framework Package. See content of the # documentation-folder for more details. See also http://www.thevirtualbrain.org # # (c) 2012-2013, Baycrest Centre for Geriatric Care ("Baycrest") # # 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, you can download it here # http://www.gnu.org/licenses/old-licenses/gpl-2.0 # # # CITATION: # When using The Virtual Brain for scientific publications, please cite it as follows: # # Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide, # Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013) # The Virtual Brain: a simulator of primate brain network dynamics. # Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010) # # """ All the little functions that make life nicer in the Traits package. .. moduleauthor:: Mihai Andrei <mihai.andrei@codemart.ro> .. moduleauthor:: Lia Domide <lia.domide@codemart.ro> .. moduleauthor:: marmaduke <duke@eml.cc> """ import numpy import collections import inspect from tvb.basic.profile import TvbProfile # returns true if key is, by convention, public ispublic = lambda key: key[0] is not '_' def str_class_name(thing, short_form=False): """ A helper function that tries to generate an informative name for its argument: when passed a class, return its name, when passed an object return a string representation of that value. """ # if thing is a class, it has attribute __name__ if hasattr(thing, '__name__'): cls = thing if short_form: return cls.__name__ return cls.__module__ + '.' + cls.__name__ else: # otherwise, it's an object and we return its __str__ return str(thing) def get(obj, key, default=None): """ get() is a general function allowing us to ignore whether we are getting from a dictionary or object. If obj is a dictionary, we return the value corresponding to key, otherwise we return the attribute on obj corresponding to key. In both cases, if key does not exist, default is returned. """ if type(obj) is dict: return obj.get(key, default) else: return getattr(obj, key) if hasattr(obj, key) else default def log_debug_array(log, array, array_name, owner=""): """ Simple access to debugging info on an array. """ if TvbProfile.current.TRAITS_CONFIGURATION.use_storage: return # Hide this logs in web-mode, with storage, because we have multiple storage exceptions if owner != "": name = ".".join((owner, array_name)) else: name = array_name if array is not None and hasattr(array, 'shape'): shape = str(array.shape) dtype = str(array.dtype) has_nan = str(numpy.isnan(array).any()) array_max = str(array.max()) array_min = str(array.min()) log.debug("%s shape: %s" % (name, shape)) log.debug("%s dtype: %s" % (name, dtype)) log.debug("%s has NaN: %s" % (name, has_nan)) log.debug("%s maximum: %s" % (name, array_max)) log.debug("%s minimum: %s" % (name, array_min)) else: log.debug("%s is None or not Array" % name) Args = collections.namedtuple('Args', 'pos kwd') class TypeRegister(list): """ TypeRegister is a smart list that can be queried to obtain selections of the classes inheriting from Traits classes. """ def subclasses(self, obj, avoid_subclasses=False): """ The subclasses method takes a class (or given instance object, will use the class of the instance), and returns a list of all options known to this TypeRegister that are direct subclasses of the class or have the class in their base class list. :param obj: Class or instance :param avoid_subclasses: When specified, subclasses are not retrieved, only current class. """ cls = obj if inspect.isclass(obj) else obj.__class__ if avoid_subclasses: return [cls] if hasattr(cls, '_base_classes'): bases = cls._base_classes else: bases = [] sublcasses = [opt for opt in self if ((issubclass(opt, cls) or cls in opt.__bases__) and not inspect.isabstract(opt) and opt.__name__ not in bases)] return sublcasses def multiline_math_directives_to_matjax(doc): """ Looks for multi-line sphinx math directives in the given rst string It converts them in html text that will be interpreted by mathjax The parsing is simplistic, not a rst parser. Wraps .. math :: body in \[\begin{split}\end{split}\] """ # doc = text | math BEGIN = r'\[\begin{split}' END = r'\end{split}\]' in_math = False # 2 state parser out_lines = [] indent = '' for line in doc.splitlines(): if not in_math: # math = indent directive math_body indent, sep, _ = line.partition('.. math::') if sep: out_lines.append(BEGIN) in_math = True else: out_lines.append(line) else: # math body is at least 1 space more indented than the directive, but we tolerate empty lines if line.startswith(indent + ' ') or line.strip() == '': out_lines.append(line) else: # this line is not properly indented, math block is over out_lines.append(END) out_lines.append(line) in_math = False if in_math: # close math tag out_lines.append(END) return '\n'.join(out_lines)
echohenry2006/tvb-library
tvb/basic/traits/util.py
Python
gpl-2.0
6,354
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2021 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_SOLVER_RESULT_HPP #define XCSOAR_SOLVER_RESULT_HPP /** * Return type for path solver methods. */ enum class SolverResult { /** * Still looking for a solution. */ INCOMPLETE, /** * A valid solution was found. */ VALID, /** * The solver has completed, but failed to find a valid solution, * or the solution was not better than the previous one. More * data may be required. */ FAILED, }; #endif
sandrinr/XCSoar
src/Engine/PathSolvers/SolverResult.hpp
C++
gpl-2.0
1,351
<?php /** * Find double description headers * * @author garth@wikia-inc.com * @ingroup Maintenance */ ini_set('display_errors', 'stderr'); ini_set('error_reporting', E_NOTICE); require_once( dirname( __FILE__ ) . '/../../Maintenance.php' ); class EditCLI extends Maintenance { public function __construct() { parent::__construct(); $this->mDescription = "Find double description headers"; $this->addOption( 'pageid', 'Page ID', false, true, 'p' ); } public function execute() { global $wgTitle; $pageID = $this->getOption( 'pageid' ); if ( !empty($pageID) ) { echo "Scaning page ID $pageID\n"; $this->scanArticle($pageID); exit(0); } $dbs = wfGetDB(DB_SLAVE); if (is_null($dbs)) { exit(1); } # Find all video file pages $query = "select page_id " . "from page join video_info " . " on video_title=page_title " . "where page_namespace = 6"; $res = $dbs->query($query); while ($row = $dbs->fetchObject($res)) { $pageId = $row->page_id; $this->scanArticle($pageId); } $dbs->freeResult($res); } public function scanArticle ( $pageId ) { $wgTitle = Title::newFromID( $pageId ); if ( !$wgTitle ) { $this->error( "Invalid title", true ); } $page = WikiPage::factory( $wgTitle ); # Read the text $text = $page->getText(); if (preg_match('/^== *description *==.+^== *description *==/sim', $text)) { echo "\t($pageId) ".$wgTitle->getFullURL()."\n"; } } } $maintClass = "EditCLI"; require_once( RUN_MAINTENANCE_IF_MAIN );
felixonmars/app
maintenance/wikia/VideoHandlers/findDoubleDescription.php
PHP
gpl-2.0
1,524
<?php namespace Kanboard\Controller; /** * Task Modification controller * * @package controller * @author Frederic Guillot */ class Taskmodification extends Base { /** * Set automatically the start date * * @access public */ public function start() { $task = $this->getTask(); $this->taskModification->update(array('id' => $task['id'], 'date_started' => time())); $this->response->redirect($this->helper->url->to('task', 'show', array('project_id' => $task['project_id'], 'task_id' => $task['id']))); } /** * Update time tracking information * * @access public */ public function time() { $task = $this->getTask(); $values = $this->request->getValues(); list($valid, ) = $this->taskValidator->validateTimeModification($values); if ($valid && $this->taskModification->update($values)) { $this->session->flash(t('Task updated successfully.')); } else { $this->session->flashError(t('Unable to update your task.')); } $this->response->redirect($this->helper->url->to('task', 'show', array('project_id' => $task['project_id'], 'task_id' => $task['id']))); } /** * Edit description form * * @access public */ public function description() { $task = $this->getTask(); $ajax = $this->request->isAjax() || $this->request->getIntegerParam('ajax'); if ($this->request->isPost()) { $values = $this->request->getValues(); list($valid, $errors) = $this->taskValidator->validateDescriptionCreation($values); if ($valid) { if ($this->taskModification->update($values)) { $this->session->flash(t('Task updated successfully.')); } else { $this->session->flashError(t('Unable to update your task.')); } if ($ajax) { $this->response->redirect($this->helper->url->to('board', 'show', array('project_id' => $task['project_id']))); } else { $this->response->redirect($this->helper->url->to('task', 'show', array('project_id' => $task['project_id'], 'task_id' => $task['id']))); } } } else { $values = $task; $errors = array(); } $params = array( 'values' => $values, 'errors' => $errors, 'task' => $task, 'ajax' => $ajax, ); if ($ajax) { $this->response->html($this->template->render('task_modification/edit_description', $params)); } else { $this->response->html($this->taskLayout('task_modification/edit_description', $params)); } } /** * Display a form to edit a task * * @access public */ public function edit(array $values = array(), array $errors = array()) { $task = $this->getTask(); $ajax = $this->request->isAjax(); if (empty($values)) { $values = $task; } $this->dateParser->format($values, array('date_due')); $params = array( 'values' => $values, 'errors' => $errors, 'task' => $task, 'users_list' => $this->projectPermission->getMemberList($task['project_id']), 'colors_list' => $this->color->getList(), 'categories_list' => $this->category->getList($task['project_id']), 'date_format' => $this->config->get('application_date_format'), 'date_formats' => $this->dateParser->getAvailableFormats(), 'ajax' => $ajax, ); if ($ajax) { $html = $this->template->render('task_modification/edit_task', $params); } else { $html = $this->taskLayout('task_modification/edit_task', $params); } $this->response->html($html); } /** * Validate and update a task * * @access public */ public function update() { $task = $this->getTask(); $values = $this->request->getValues(); list($valid, $errors) = $this->taskValidator->validateModification($values); if ($valid && $this->taskModification->update($values)) { $this->session->flash(t('Task updated successfully.')); if ($this->request->isAjax()) { $this->response->redirect($this->helper->url->to('board', 'show', array('project_id' => $task['project_id']))); } else { $this->response->redirect($this->helper->url->to('task', 'show', array('project_id' => $task['project_id'], 'task_id' => $task['id']))); } } else { $this->session->flashError(t('Unable to update your task.')); $this->edit($values, $errors); } } /** * Edit recurrence form * * @access public */ public function recurrence() { $task = $this->getTask(); if ($this->request->isPost()) { $values = $this->request->getValues(); list($valid, $errors) = $this->taskValidator->validateEditRecurrence($values); if ($valid) { if ($this->taskModification->update($values)) { $this->session->flash(t('Task updated successfully.')); } else { $this->session->flashError(t('Unable to update your task.')); } $this->response->redirect($this->helper->url->to('task', 'show', array('project_id' => $task['project_id'], 'task_id' => $task['id']))); } } else { $values = $task; $errors = array(); } $params = array( 'values' => $values, 'errors' => $errors, 'task' => $task, 'recurrence_status_list' => $this->task->getRecurrenceStatusList(), 'recurrence_trigger_list' => $this->task->getRecurrenceTriggerList(), 'recurrence_timeframe_list' => $this->task->getRecurrenceTimeframeList(), 'recurrence_basedate_list' => $this->task->getRecurrenceBasedateList(), ); $this->response->html($this->taskLayout('task_modification/edit_recurrence', $params)); } }
3lywa/gcconnex
kanboard/app/Controller/Taskmodification.php
PHP
gpl-2.0
6,386
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2008 - 2014 by Wilbert Berendsen # # 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 St, Fifth Floor, Boston, MA 02110-1301 USA # See http://www.gnu.org/licenses/ for more information. """ Import and export of snippets. """ import os try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET from PyQt5.QtCore import QSize, Qt from PyQt5.QtGui import QKeySequence from PyQt5.QtWidgets import QMessageBox, QTreeWidget, QTreeWidgetItem import app import appinfo import qutil import userguide import widgets.dialog from . import model from . import snippets from . import builtin def save(names, filename): """Saves the named snippets to a file.""" root = ET.Element('snippets') root.text = '\n\n' root.tail = '\n' d = ET.ElementTree(root) comment = ET.Comment(_comment.format(appinfo=appinfo)) comment.tail = '\n\n' root.append(comment) for name in names: snippet = ET.Element('snippet') snippet.set('id', name) snippet.text = '\n' snippet.tail = '\n\n' title = ET.Element('title') title.text = snippets.title(name, False) title.tail = '\n' shortcuts = ET.Element('shortcuts') ss = model.shortcuts(name) if ss: shortcuts.text = '\n' for s in ss: shortcut = ET.Element('shortcut') shortcut.text = s.toString() shortcut.tail = '\n' shortcuts.append(shortcut) shortcuts.tail = '\n' body = ET.Element('body') body.text = snippets.text(name) body.tail = '\n' snippet.append(title) snippet.append(shortcuts) snippet.append(body) root.append(snippet) d.write(filename, "UTF-8") def load(filename, widget): """Loads snippets from a file, displaying them in a list. The user can then choose: - overwrite builtin snippets or not - overwrite own snippets with same title or not - select and view snippets contents. """ try: d = ET.parse(filename) elements = list(d.findall('snippet')) if not elements: raise ValueError(_("No snippets found.")) except Exception as e: QMessageBox.critical(widget, app.caption(_("Error")), _("Can't read from source:\n\n{url}\n\n{error}").format( url=filename, error=e)) return dlg = widgets.dialog.Dialog(widget) dlg.setWindowModality(Qt.WindowModal) dlg.setWindowTitle(app.caption(_("dialog title", "Import Snippets"))) tree = QTreeWidget(headerHidden=True, rootIsDecorated=False) dlg.setMainWidget(tree) userguide.addButton(dlg.buttonBox(), "snippet_import_export") allnames = frozenset(snippets.names()) builtins = frozenset(builtin.builtin_snippets) titles = dict((snippets.title(n), n) for n in allnames if n not in builtins) new = QTreeWidgetItem(tree, [_("New Snippets")]) updated = QTreeWidgetItem(tree, [_("Updated Snippets")]) unchanged = QTreeWidgetItem(tree, [_("Unchanged Snippets")]) new.setFlags(Qt.ItemIsEnabled) updated.setFlags(Qt.ItemIsEnabled) unchanged.setFlags(Qt.ItemIsEnabled) new.setExpanded(True) updated.setExpanded(True) items = [] for snip in elements: item = QTreeWidgetItem() item.body = snip.find('body').text item.title = snip.find('title').text item.shortcuts = list(e.text for e in snip.findall('shortcuts/shortcut')) title = item.title or snippets.maketitle(snippets.parse(item.body).text) item.setText(0, title) name = snip.get('id') name = name if name in builtins else None # determine if new, updated or unchanged if not name: name = titles.get(title) item.name = name if not name or name not in allnames: new.addChild(item) items.append(item) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) item.setCheckState(0, Qt.Checked) elif name: if (item.body != snippets.text(name) or title != snippets.title(name) or (item.shortcuts and item.shortcuts != [s.toString() for s in model.shortcuts(name) or ()])): updated.addChild(item) items.append(item) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) item.setCheckState(0, Qt.Checked) else: unchanged.addChild(item) item.setFlags(Qt.ItemIsEnabled) # count: for i in new, updated, unchanged: i.setText(0, i.text(0) + " ({0})".format(i.childCount())) for i in new, updated: if i.childCount(): i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) i.setCheckState(0, Qt.Checked) def changed(item): if item in (new, updated): for i in range(item.childCount()): c = item.child(i) c.setCheckState(0, item.checkState(0)) tree.itemChanged.connect(changed) importShortcuts = QTreeWidgetItem([_("Import Keyboard Shortcuts")]) if items: tree.addTopLevelItem(importShortcuts) importShortcuts.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) importShortcuts.setCheckState(0, Qt.Checked) dlg.setMessage(_("Choose which snippets you want to import:")) else: dlg.setMessage(_("There are no new or updated snippets in the file.")) unchanged.setExpanded(True) tree.setWhatsThis(_( "<p>Here the snippets from {filename} are displayed.</p>\n" "<p>If there are new or updated snippets, you can select or deselect " "them one by one, or all at once, using the checkbox of the group. " "Then click OK to import all the selected snippets.</p>\n" "<p>Existing, unchanged snippets can't be imported.</p>\n" ).format(filename=os.path.basename(filename))) qutil.saveDialogSize(dlg, "snippettool/import/size", QSize(400, 300)) if not dlg.exec_() or not items: return ac = model.collection() m = model.model() with qutil.busyCursor(): for i in items: if i.checkState(0) == Qt.Checked: index = m.saveSnippet(i.name, i.body, i.title) if i.shortcuts and importShortcuts.checkState(0): shortcuts = list(map(QKeySequence.fromString, i.shortcuts)) ac.setShortcuts(m.name(index), shortcuts) widget.updateColumnSizes() _comment = """ Created by {appinfo.appname} {appinfo.version}. Every snippet is represented by: title: title text shortcuts: list of shortcut elements, every shortcut is a key sequence body: the snippet text The snippet id attribute can be the name of a builtin snippet or a random name like 'n123456'. In the latter case, the title is used to determine whether a snippet is new or updated. """
wbsoft/frescobaldi
frescobaldi_app/snippet/import_export.py
Python
gpl-2.0
7,763
<?php /******************************************************************************* Copyright 2001, 2004 Wedge Community Co-op Modifications copyright 2010 Whole Foods Co-op This file is part of IT CORE. IT CORE 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. IT CORE 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 *********************************************************************************/ use COREPOS\pos\lib\Database; use COREPOS\pos\lib\FormLib; use COREPOS\pos\lib\MiscLib; use COREPOS\pos\lib\UdpComm; if (!class_exists('AutoLoader')) include_once(dirname(__FILE__).'/../../../lib/AutoLoader.php'); class PaycardEmvGift extends PaycardProcessPage { private $prompt = false; private $runTransaction = false; private $amount = false; private $mode = false; function preprocess() { // check for posts before drawing anything, so we can redirect if (FormLib::get('mode') !== '') { $this->mode = FormLib::get('mode'); if ($this->mode != PaycardLib::PAYCARD_MODE_ACTIVATE && $this->mode != PaycardLib::PAYCARD_MODE_ADDVALUE) { $this->conf->set('boxMsg', 'Invalid Gift Card Mode'); $this->change_page(MiscLib::baseURL() . 'gui-modules/boxMsg2.php'); return false; } } if (is_numeric(FormLib::get('amount'))) { $this->amount = FormLib::get('amount'); } if (FormLib::get('reginput', false) !== false) { $input = strtoupper(trim(FormLib::get('reginput'))); // CL always exits if( $input == "CL") { $this->conf->set("msgrepeat",0); $this->conf->set("toggletax",0); $this->conf->set("togglefoodstamp",0); $this->conf->reset(); $this->conf->set("CachePanEncBlock",""); $this->conf->set("CachePinEncBlock",""); $this->conf->set("CacheCardType",""); $this->conf->set("CacheCardCashBack",0); $this->conf->set('ccTermState','swipe'); UdpComm::udpSend("termReset"); $this->change_page($this->page_url."gui-modules/pos2.php"); return False; } elseif ($this->amount && ($input == "" || $input == 'MANUAL')) { $this->action = "onsubmit=\"return false;\""; $this->addOnloadCommand("emvSubmit();"); if ($input == 'MANUAL') { $this->prompt = true; } $this->runTransaction = true; } elseif ($input != "" && is_numeric($input)) { // any other input is an alternate amount $this->amount = $input / 100.00; } // if we're still here, we haven't accepted a valid amount yet; display prompt again } elseif (FormLib::get('xml-resp') !== '') { $xml = FormLib::get('xml-resp'); $this->emvResponseHandler($xml); return false; } // post? return true; } function head_content() { if (!$this->runTransaction) { return ''; } $e2e = new MercuryDC(); ?> <script type="text/javascript" src="../js/emv.js"></script> <script type="text/javascript"> function emvSubmit() { $('div.baseHeight').html('Processing transaction'); // POST XML request to driver using AJAX var xmlData = '<?php echo json_encode($e2e->prepareDataCapGift($this->mode, $this->amount, $this->prompt)); ?>'; if (xmlData == '"Error"') { // failed to save request info in database location = '<?php echo MiscLib::baseURL(); ?>gui-modules/boxMsg2.php'; return false; } emv.submit(xmlData); } </script> <?php } function body_content() { echo '<div class="baseHeight">'; $title = ($this->mode == PaycardLib::PAYCARD_MODE_ACTIVATE) ? 'Activate Gift Card' : 'Add Value to Gift Card'; $msg = ''; if (!$this->amount) { $msg .= 'Enter amount<br /> [clear] to cancel'; } else { $msg .= 'Value: $' . sprintf('%.2f', $this->amount) . ' [enter] to continue if correct<br>Enter a different amount if incorrect<br> [clear] to cancel'; $this->addOnloadCommand("\$('#formlocal').append(\$('<input type=\"hidden\" name=\"amount\" />').val({$this->amount}));\n"); } // generate message to print echo PaycardLib::paycardMsgBox( $title, '', $msg ); echo '</div>'; $this->addOnloadCommand("\$('#formlocal').append(\$('<input type=\"hidden\" name=\"mode\" />').val({$this->mode}));\n"); } } AutoLoader::dispatch();
FranklinCoop/IS4C
pos/is4c-nf/plugins/Paycards/gui/PaycardEmvGift.php
PHP
gpl-2.0
5,466
$(function() { $('img[data-hover]').hover(function() { $(this).attr('tmp', $(this).attr('src')).attr('src', $(this).attr('data-hover')).attr('data-hover', $(this).attr('tmp')).removeAttr('tmp'); }).each(function() { $('<img>').attr('src', $(this).attr('data-hover')); });; }); jQuery(document).ready(function ($) { var options = { $AutoPlay: true, $SlideDuration: 800, $AutoPlayInterval: 2000 }; var jssor_slider1 = new $JssorSlider$('slider1_container', options); });
alex789/random
wp-content/themes/randomTheme/js/jquery.js
JavaScript
gpl-2.0
528
<?php /** * * @package MediaWiki * @subpackage SpecialPage */ /** * constructor */ function wfSpecialUserlogout() { global $wgUser, $wgOut; if (wfRunHooks('UserLogout', array(&$wgUser))) { $wgUser->logout(); wfRunHooks('UserLogoutComplete', array(&$wgUser)); $wgOut->setRobotpolicy( 'noindex,nofollow' ); $wgOut->addHTML( wfMsgExt( 'logouttext', array( 'parse' ) ) ); $wgOut->returnToMain(); } } ?>
Devanshg/Mediawiki
includes/SpecialUserlogout.php
PHP
gpl-2.0
425
namespace Server.Items { public class EmptyToolKit2 : Item { [Constructable] public EmptyToolKit2() : base(0x1EB7) { Movable = true; Stackable = false; } public EmptyToolKit2(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Argalep/ServUO
Scripts/Items/Decorative/EmptyToolKit2.cs
C#
gpl-2.0
644
<?php namespace Phalcon\Mvc\View\Engine; /** * Phalcon\Mvc\View\Engine\Volt * Designer friendly and fast template engine for PHP written in Zephir/C */ class Volt extends \Phalcon\Mvc\View\Engine implements \Phalcon\Mvc\View\EngineInterface { protected $_options; protected $_compiler; protected $_macros; /** * Set Volt's options * * @param array $options */ public function setOptions($options) {} /** * Return Volt's options * * @return array */ public function getOptions() {} /** * Returns the Volt's compiler * * @return \Phalcon\Mvc\View\Engine\Volt\Compiler */ public function getCompiler() {} /** * Renders a view using the template engine * * @param string $templatePath * @param mixed $params * @param bool $mustClean */ public function render($templatePath, $params, $mustClean = false) {} /** * Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen * * @param mixed $item * @return int */ public function length($item) {} /** * Checks if the needle is included in the haystack * * @param mixed $needle * @param mixed $haystack * @return bool */ public function isIncluded($needle, $haystack) {} /** * Performs a string conversion * * @param string $text * @param string $from * @param string $to * @return string */ public function convertEncoding($text, $from, $to) {} /** * Extracts a slice from a string/array/traversable object value * * @param mixed $value * @param int $start * @param mixed $end */ public function slice($value, $start = 0, $end = null) {} /** * Sorts an array * * @param array $value * @return array */ public function sort($value) {} /** * Checks if a macro is defined and calls it * * @param string $name * @param array $arguments */ public function callMacro($name, $arguments) {} }
mattm479/mafiakingz
vendor/phalcon/src/Phalcon/mvc/view/engine/Volt.php
PHP
gpl-2.0
2,159
<?php /*------------------------------------------------------------------------ # SP Tab - Tab Module for Joomla by JoomShaper.com # ------------------------------------------------------------------------ # author JoomShaper http://www.joomshaper.com # Copyright (C) 2010 - 2012 JoomShaper.com. All Rights Reserved. # @license - Copyrighted Commercial Software # Websites: http://www.joomshaper.com # This file may not be redistributed in whole or significant part -------------------------------------------------------------------------*/ header("Content-Type: text/css"); $uniqid = $_GET['id']; ?> #sptab<?php echo $uniqid ?> ul.tabs_container {list-style:none;margin: 0!important; padding: 0!important} #sptab<?php echo $uniqid ?> .tabs_buttons{background:#fff url(../images/style2/header_bg.gif) repeat-x 0 100%;padding:0 10px;overflow:hidden} #sptab<?php echo $uniqid ?> ul.tabs_container li.tab{background:url(../images/style2/tab-l.png) no-repeat 0 100%;color:#666;float:left;padding:0 0 0 10px;margin:0;border:0!important;} #sptab<?php echo $uniqid ?> ul.tabs_container li.tab span{background:url(../images/style2/tab-r.png) no-repeat 100% 100%;display:inline-block;cursor:pointer;padding:0 10px 0 0;margin:0 5px 0 0;font-weight:700;text-transform:uppercase} #sptab<?php echo $uniqid ?> ul.tabs_container li.tab, #sptab<?php echo $uniqid ?> ul.tabs_container li.tab span{font-size:12px} #sptab<?php echo $uniqid ?> .items_mask {position:relative;overflow:hidden} #sptab<?php echo $uniqid ?> ul.tabs_container li.tab.active{background:url(../images/style2/tab-active-l.png) no-repeat 0 100%} #sptab<?php echo $uniqid ?> ul.tabs_container li.tab.active span{background:url(../images/style2/tab-active-r.png) no-repeat 100% 100%} #sptab<?php echo $uniqid ?>.sptab_red ul.tabs_container li.tab.tab_over, #sptab<?php echo $uniqid ?>.sptab_red ul.tabs_container li.tab.active{color:#ba0202} #sptab<?php echo $uniqid ?>.sptab_green ul.tabs_container li.tab.tab_over, #sptab<?php echo $uniqid ?>.sptab_green ul.tabs_container li.tab.active{color:#91ba02} #sptab<?php echo $uniqid ?>.sptab_blue ul.tabs_container li.tab.tab_over, #sptab<?php echo $uniqid ?>.sptab_blue ul.tabs_container li.tab.active{color:#01b0e2}
apachish/tariin
modules/mod_sptab/assets/css/style2.css.php
PHP
gpl-2.0
2,254
<?php // File Security Check if (!defined('ABSPATH')) die('-1'); /* Register WhoaThemes shortcode. */ class WPBakeryShortCode_WT_gallery_grid extends WPBakeryShortCode { private $wt_sc; public function __construct($settings) { parent::__construct($settings); $this->wt_sc = new WT_VCSC_SHORTCODE; } public function singleParamHtmlHolder( $param, $value ) { $output = ''; // Compatibility fixes $old_names = array( 'yellow_message', 'blue_message', 'green_message', 'button_green', 'button_grey', 'button_yellow', 'button_blue', 'button_red', 'button_orange' ); $new_names = array( 'alert-block', 'alert-info', 'alert-success', 'btn-success', 'btn', 'btn-info', 'btn-primary', 'btn-danger', 'btn-warning' ); $value = str_ireplace( $old_names, $new_names, $value ); //$value = esc_html__($value, "js_composer"); // $param_name = isset( $param['param_name'] ) ? $param['param_name'] : ''; $type = isset( $param['type'] ) ? $param['type'] : ''; $class = isset( $param['class'] ) ? $param['class'] : ''; if ( isset( $param['holder'] ) == true && $param['holder'] !== 'hidden' ) { $output .= '<' . $param['holder'] . ' class="wpb_vc_param_value ' . $param_name . ' ' . $type . ' ' . $class . '" name="' . $param_name . '">' . $value . '</' . $param['holder'] . '>'; } if ( $param_name == 'images' ) { $images_ids = empty( $value ) ? array() : explode( ',', trim( $value ) ); $output .= '<ul class="attachment-thumbnails' . ( empty( $images_ids ) ? ' image-exists' : '' ) . '" data-name="' . $param_name . '">'; foreach ( $images_ids as $image ) { $img = wpb_getImageBySize( array( 'attach_id' => (int)$image, 'thumb_size' => 'thumbnail' ) ); $output .= ( $img ? '<li>' . $img['thumbnail'] . '</li>' : '<li><img width="150" height="150" test="' . $image . '" src="' . vc_asset_url( 'vc/blank.gif' ) . '" class="attachment-thumbnail" alt="" title="" /></li>' ); } $output .= '</ul>'; $output .= '<a href="#" class="column_edit_trigger' . ( ! empty( $images_ids ) ? ' image-exists' : '' ) . '">' . esc_html__( 'Add images', 'js_composer' ) . '</a>'; } return $output; } protected function content($atts, $content = null) { extract( shortcode_atts( array( 'images' => '', 'img_width' => '9999', 'img_height' => '9999', 'columns' => 4, 'grid_style' => '', 'thumbnail_link' => '', 'custom_links' => '', 'custom_links_target' => '_self', 'title' => false, 'black_white' => false, 'el_id' => '', 'el_class' => '', 'css_animation' => '', 'anim_type' => '', 'anim_delay' => '', 'css' => '' ), $atts ) ); $sc_class = 'wt_gallery_grid_sc'; // Img Container Classes $sc_classes = array(); // Adding placeholder images if no image was set if ( $images == '' ) { switch( $columns ) { case 1 : $images = '-1'; break; case 2 : $images = '-1,-2'; break; case 3 : $images = '-1,-2,-3'; break; case 4 : $images = '-1,-2,-3,-4'; break; case 6 : default : $images = '-1,-2,-3,-4,-5,-6'; break; } } // Get Attachments $images = explode( ',', $images ); $i = -1; $id = mt_rand(9999, 99999); if (trim($el_id) != false) { $el_id = esc_attr( trim($el_id) ); } else { $el_id = $sc_class . '-' . $id; } // Custom Links if ( $thumbnail_link == 'custom_link' ) { $custom_links = explode( ',', $custom_links); } // Column Class if ( $columns == '1' ) { $sc_classes[] = 'wt_gallery_1_col'; } else { $sc_classes[] = 'wt_gallery_'.$columns.'_cols'; } // Lightbox Class if ( $thumbnail_link == 'lightbox' ) { $sc_classes[] = 'wt_gallery_lightbox'; } // No Margin Class if ( $grid_style == 'no-margins' ) { $sc_classes[] = 'wt_gallery_no_margins clearfix'; } else { $sc_classes[] = 'row'; } $sc_classes = implode(' ', $sc_classes); if ($sc_classes != '') { $sc_classes = ' ' . $sc_classes; } $sc_class = $sc_class . $sc_classes; $el_class = esc_attr( $this->getExtraClass($el_class) ); $css_class = apply_filters(VC_SHORTCODE_CUSTOM_CSS_FILTER_TAG, $sc_class.$el_class.vc_shortcode_custom_css_class($css, ' '), $this->settings['base']); //$css_class .= $this->wt_sc->getWTCSSAnimationClass($css_animation,$anim_type); //$anim_data = $this->wt_sc->getWTCSSAnimationData($css_animation,$anim_delay); // Load prettyphoto scripts & styles if ( $thumbnail_link == 'lightbox' ) { wp_enqueue_script( 'prettyphoto' ); wp_enqueue_style( 'prettyphoto' ); } // Output posts if( $images ) : // Img Container Classes $classes = array(); switch( $columns ) { case 1 : $classes[] = 'col-xs-12 col-sm-12 col-lg-12 col-md-12'; break; case 2 : $classes[] = 'col-xs-6 col-sm-6 col-md-6 col-lg-6'; break; case 3 : $classes[] = 'col-xs-6 col-sm-6 col-md-4 col-lg-4'; break; case 4 : $classes[] = 'col-xs-6 col-sm-6 col-md-3 col-lg-3'; break; case 6 : default : $classes[] = 'col-xs-6 col-sm-6 col-md-2 col-lg-2'; break; } if ( $black_white == 'yes' ) { $classes[] = 'wt_grayscale'; } $classes = implode(' ', $classes); wp_enqueue_script( 'waypoints' ); // VC file $output = '<div id="'.$el_id.'" class="'.$css_class.'">'; $count = 0; foreach ( $images as $attach_id ) { $image_output = ''; $i ++; $delay = $count * 150; $count ++; // if image alt not set then take it's title $attachment_meta = WT_WpGetAttachment($attach_id); if (!empty($attachment_meta['alt'])) { $img_title = $attachment_meta['alt']; } else { $img_title = $attachment_meta['title']; } $img = $attachment_meta['src']; //$img = wp_get_attachment_url( $attach_id ); if ('9999' != $img_width && '9999' != $img_height) { $width_inline = $img_width; $height_inline = $img_height; } else { $image_meta = wp_get_attachment_image_src($attach_id, 'full', true); $width_inline = $image_meta[1]; // get original image width $height_inline = $image_meta[2]; // get original image height } if ( $grid_style == 'no-margins' ) { $imgThumb = ''; } else { $imgThumb = ' class="img-thumbnail"'; } if ( $attach_id > 0 ) { // Crop featured images if necessary if( function_exists( 'aq_resize' ) ) { $thumb_hard_crop = ( '9999' == $img_height ) ? false : true; $cropped_img = aq_resize( $img, $img_width, $img_height, $thumb_hard_crop ); } $img_output = '<img'. $imgThumb .' src="'. $cropped_img .'" width="'. $width_inline .'" height="'. $height_inline .'" alt="'. $img_title .'" />'; } else { // If no image was set then show placeholders $img_output = '<img'. $imgThumb .' src="' . vc_asset_url( 'vc/no_image.png' ) . '" />'; } // Image output depending of image link if ( $thumbnail_link == 'lightbox' ) { $image_output .= $img_output; $icon = '<i class="entypo-search"></i>'; $image_output .= '<div class="wt_gallery_overlay">'; $image_output .= '<a href="'. $img .'" title="'. $img_title .'" class="wt_image_zoom" data-rel="lightbox[gallery_'.$id.']">'.$icon.'</a>'; if ( $title == 'yes' ) { $image_output .= '<h3>'. $img_title .'</h3>'; } $image_output .= '</div>'; } elseif ( $thumbnail_link == 'custom_link' ) { $custom_link = !empty($custom_links[$i]) ? $custom_links[$i] : '#'; if ( $custom_link == '#' ) { $image_output .= $img_output; } else { $image_output .= '<a href="'. $custom_link .'" title="'. $img_title .'" target="'. $custom_links_target .'">'; $image_output .= $img_output; $image_output .= '</a>'; } } else { $image_output .= $img_output; } $output .= '<article class="wt_gallery_grid_item '.$classes.' wt_col_'.$count.' wt_animate wt_animate_if_visible" data-animation="flipInX" data-animation-delay="'.$delay.'">'; $output .= "\n\t" . '<div class="wt_gallery_item_inner">'; $output .= "\n\t\t" . $image_output; $output .= "\n\t" . '</div>'; $output .= '</article>'; if ( $count == $columns ) $count = 0; // reset column number } $output .= '</div>'; endif; // End has posts check // Reset query wp_reset_postdata(); return $output; } } /* Register WhoaThemes shortcode within Visual Composer interface. */ if (function_exists('wpb_map')) { $add_wt_sc_func = new WT_VCSC_SHORTCODE; $add_wt_extra_id = $add_wt_sc_func->getWTExtraId(); $add_wt_extra_class = $add_wt_sc_func->getWTExtraClass(); $add_wt_css_animation = $add_wt_sc_func->getWTAnimations(); $add_wt_css_animation_type = $add_wt_sc_func->getWTAnimationsType(); $add_wt_css_animation_delay = $add_wt_sc_func->getWTAnimationsDelay(); wpb_map( array( 'name' => esc_html__('WT Gallery Grid', 'wt_vcsc'), 'base' => 'wt_gallery_grid', 'icon' => 'wt_vc_ico_gallery_grid', 'class' => 'wt_vc_sc_gallery_grid', 'category' => esc_html__('by WhoaThemes', 'wt_vcsc'), 'description' => esc_html__('Responsive image gallery grid', 'wt_vcsc'), 'params' => array( array( 'type' => 'attach_images', 'heading' => esc_html__('Images', 'wt_vcsc'), 'param_name' => 'images', 'value' => '', 'description' => esc_html__('Select images from media library.', 'wt_vcsc') ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Image Crop Width', 'wt_vcsc' ), 'param_name' => 'img_width', 'value' => '9999', 'description' => esc_html__( 'Enter the width in pixels.', 'wt_vcsc' ), ), array( 'type' => 'textfield', 'heading' => esc_html__( 'Image Crop Height', 'wt_vcsc' ), 'param_name' => 'img_height', 'value' => '9999', "description" => esc_html__( 'Enter the height in pixels. Set to "9999" to disable vertical cropping and keep image proportions.', 'wt_vcsc' ), ), array( 'type' => 'dropdown', 'heading' => esc_html__('Columns', 'wt_vcsc'), 'param_name' => 'columns', 'value' => array( __( 'Six', 'wt_vcsc' ) => 6, __( 'Four', 'wt_vcsc' ) => 4, __( 'Three', 'wt_vcsc' ) => 3, __( 'Two', 'wt_vcsc' ) => 2, __( 'One', 'wt_vcsc' ) => 1, ), 'std' => 4, 'description' => esc_html__('Select the number of columns for your grid gallery.', 'wt_vcsc') ), array( 'type' => 'dropdown', 'heading' => esc_html__('Grid style', 'wt_vcsc'), 'param_name' => 'grid_style', 'value' => array( __( 'Default', 'wt_vcsc' ) => '', __( 'No Margins', 'wt_vcsc' ) => 'no-margins', ), 'description' => esc_html__('Select the grid style for your gallery.', 'wt_vcsc') ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Image link', 'wt_vcsc' ), 'param_name' => 'thumbnail_link', 'value' => array( __( 'None', 'wt_vcsc' ) => '', __( 'Lightbox', 'wt_vcsc' ) => 'lightbox', __( 'Custom Links', 'wt_vcsc' ) => 'custom_link', ), 'description' => esc_html__( 'Where should the grid images link to?', 'wt_vcsc' ), ), array( 'type' => 'exploded_textarea', 'heading' => esc_html__( 'Custom links', 'wt_vcsc' ), 'param_name' => 'custom_links', 'param_holder_class' => 'border_box wt_dependency', 'dependency' => Array( 'element' => 'thumbnail_link', 'value' => array( 'custom_link' ) ), 'description' => esc_html__( 'Enter links for images here ( Ex: <strong>http://</strong>yoursite.com ). Divide links with linebreaks (Enter). For images withought links just add linebreak (Enter) or add "#" symbol.', 'wt_vcsc' ) ), array( 'type' => 'dropdown', 'heading' => esc_html__( 'Custom links target', 'wt_vcsc' ), 'param_name' => 'custom_links_target', 'value' => array( __( 'Same window', 'wt_vcsc' ) => '_self', __( 'New window', 'wt_vcsc' ) => "_blank" ), 'param_holder_class' => 'border_box wt_dependency', 'dependency' => Array( 'element' => 'thumbnail_link', 'value' => array( 'custom_link' ) ), 'description' => esc_html__( 'Select where to open custom links.', 'wt_vcsc' ) ), array( 'type' => 'checkbox', 'heading' => esc_html__('Display title?', 'wt_vcsc'), 'param_name' => 'title', 'value' => Array( esc_html__('Yes, please', 'wt_vcsc') => 'yes'), 'description' => esc_html__('If selected, the image title will be displayed.', 'wt_vcsc') ), array( 'type' => 'checkbox', 'heading' => esc_html__('Set black & white filter?', 'wt_vcsc'), 'param_name' => 'black_white', 'value' => Array( esc_html__('Yes, please', 'wt_vcsc') => 'yes'), 'description' => esc_html__('If selected, the images will be displayed with black & white filter.', 'wt_vcsc') ), $add_wt_extra_id, $add_wt_extra_class, /* $add_wt_css_animation, $add_wt_css_animation_type, $add_wt_css_animation_delay, */ array( 'type' => 'css_editor', 'heading' => esc_html__('Css', 'wt_vcsc'), 'param_name' => 'css', 'group' => esc_html__('Design options', 'wt_vcsc') ) ) )); }
gtessier/OPTZ
wp-content/themes/simple/framework/shortcodes/elements/wt_vcsc_gallery_grid.php
PHP
gpl-2.0
14,278
/* * Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Thousand Needles SD%Complete: 100 SDComment: Support for Quest: 4770, 4904, 4966, 5151. SDCategory: Thousand Needles EndScriptData */ /* ContentData npc_kanati npc_lakota_windsong npc_swiftmountain npc_enraged_panther go_panther_cage EndContentData */ #include "ScriptMgr.h" #include "GameObject.h" #include "GameObjectAI.h" #include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" /*##### # npc_kanati ######*/ enum Kanati { SAY_KAN_START = 0, QUEST_PROTECT_KANATI = 4966, NPC_GALAK_ASS = 10720 }; Position const GalakLoc = {-4867.387695f, -1357.353760f, -48.226f, 0.0f}; class npc_kanati : public CreatureScript { public: npc_kanati() : CreatureScript("npc_kanati") { } struct npc_kanatiAI : public EscortAI { npc_kanatiAI(Creature* creature) : EscortAI(creature) { } void Reset() override { } void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override { switch (waypointId) { case 0: Talk(SAY_KAN_START); DoSpawnGalak(); break; case 1: if (Player* player = GetPlayerForEscort()) player->GroupEventHappens(QUEST_PROTECT_KANATI, me); break; } } void DoSpawnGalak() { for (int i = 0; i < 3; ++i) me->SummonCreature(NPC_GALAK_ASS, GalakLoc, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000); } void JustSummoned(Creature* summoned) override { summoned->AI()->AttackStart(me); } void QuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_PROTECT_KANATI) Start(false, false, player->GetGUID(), quest, true); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_kanatiAI(creature); } }; /*###### # npc_lakota_windsong ######*/ enum Lakota { SAY_LAKO_START = 0, SAY_LAKO_LOOK_OUT = 1, SAY_LAKO_HERE_COME = 2, SAY_LAKO_MORE = 3, SAY_LAKO_END = 4, QUEST_FREE_AT_LAST = 4904, NPC_GRIM_BANDIT = 10758, ID_AMBUSH_1 = 0, ID_AMBUSH_2 = 2, ID_AMBUSH_3 = 4 }; Position const BanditLoc[6] = { {-4905.479492f, -2062.732666f, 84.352f, 0.0f}, {-4915.201172f, -2073.528320f, 84.733f, 0.0f}, {-4878.883301f, -1986.947876f, 91.966f, 0.0f}, {-4877.503906f, -1966.113403f, 91.859f, 0.0f}, {-4767.985352f, -1873.169189f, 90.192f, 0.0f}, {-4788.861328f, -1888.007813f, 89.888f, 0.0f} }; class npc_lakota_windsong : public CreatureScript { public: npc_lakota_windsong() : CreatureScript("npc_lakota_windsong") { } struct npc_lakota_windsongAI : public EscortAI { npc_lakota_windsongAI(Creature* creature) : EscortAI(creature) { } void Reset() override { } void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override { switch (waypointId) { case 8: Talk(SAY_LAKO_LOOK_OUT); DoSpawnBandits(ID_AMBUSH_1); break; case 14: Talk(SAY_LAKO_HERE_COME); DoSpawnBandits(ID_AMBUSH_2); break; case 21: Talk(SAY_LAKO_MORE); DoSpawnBandits(ID_AMBUSH_3); break; case 45: Talk(SAY_LAKO_END); if (Player* player = GetPlayerForEscort()) player->GroupEventHappens(QUEST_FREE_AT_LAST, me); break; } } void DoSpawnBandits(int AmbushId) { for (int i = 0; i < 2; ++i) me->SummonCreature(NPC_GRIM_BANDIT, BanditLoc[i+AmbushId], TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000); } void QuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_FREE_AT_LAST) { Talk(SAY_LAKO_START, player); me->SetFaction(FACTION_ESCORTEE_H_NEUTRAL_ACTIVE); Start(false, false, player->GetGUID(), quest); } } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_lakota_windsongAI(creature); } }; /*###### # npc_paoka_swiftmountain ######*/ enum Packa { SAY_START = 0, SAY_WYVERN = 1, SAY_COMPLETE = 2, QUEST_HOMEWARD = 4770, NPC_WYVERN = 4107 }; Position const WyvernLoc[3] = { {-4990.606f, -906.057f, -5.343f, 0.0f}, {-4970.241f, -927.378f, -4.951f, 0.0f}, {-4985.364f, -952.528f, -5.199f, 0.0f} }; class npc_paoka_swiftmountain : public CreatureScript { public: npc_paoka_swiftmountain() : CreatureScript("npc_paoka_swiftmountain") { } struct npc_paoka_swiftmountainAI : public EscortAI { npc_paoka_swiftmountainAI(Creature* creature) : EscortAI(creature) { } void Reset() override { } void WaypointReached(uint32 waypointId, uint32 /*pathId*/) override { switch (waypointId) { case 15: Talk(SAY_WYVERN); DoSpawnWyvern(); break; case 26: Talk(SAY_COMPLETE); break; case 27: if (Player* player = GetPlayerForEscort()) player->GroupEventHappens(QUEST_HOMEWARD, me); break; } } void DoSpawnWyvern() { for (int i = 0; i < 3; ++i) me->SummonCreature(NPC_WYVERN, WyvernLoc[i], TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000); } void QuestAccept(Player* player, Quest const* quest) override { if (quest->GetQuestId() == QUEST_HOMEWARD) { Talk(SAY_START, player); me->SetFaction(FACTION_ESCORTEE_H_NEUTRAL_ACTIVE); Start(false, false, player->GetGUID(), quest); } } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_paoka_swiftmountainAI(creature); } }; enum PantherCage { QUEST_HYPERCAPACITOR_GIZMO = 5151, ENRAGED_PANTHER = 10992 }; class go_panther_cage : public GameObjectScript { public: go_panther_cage() : GameObjectScript("go_panther_cage") { } struct go_panther_cageAI : public GameObjectAI { go_panther_cageAI(GameObject* go) : GameObjectAI(go) { } bool GossipHello(Player* player) override { me->UseDoorOrButton(); if (player->GetQuestStatus(QUEST_HYPERCAPACITOR_GIZMO) == QUEST_STATUS_INCOMPLETE) { if (Creature* panther = me->FindNearestCreature(ENRAGED_PANTHER, 5, true)) { panther->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); panther->SetReactState(REACT_AGGRESSIVE); panther->AI()->AttackStart(player); } } return true; } }; GameObjectAI* GetAI(GameObject* go) const override { return new go_panther_cageAI(go); } }; class npc_enraged_panther : public CreatureScript { public: npc_enraged_panther() : CreatureScript("npc_enraged_panther") { } CreatureAI* GetAI(Creature* creature) const override { return new npc_enraged_pantherAI(creature); } struct npc_enraged_pantherAI : public ScriptedAI { npc_enraged_pantherAI(Creature* creature) : ScriptedAI(creature) { } void Reset() override { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); me->SetReactState(REACT_PASSIVE); } void UpdateAI(uint32 /*diff*/) override { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; }; void AddSC_thousand_needles() { new npc_kanati(); new npc_lakota_windsong(); new npc_paoka_swiftmountain(); new npc_enraged_panther(); new go_panther_cage(); }
Effec7/Adamantium
src/server/scripts/Kalimdor/zone_thousand_needles.cpp
C++
gpl-2.0
9,272
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.dao; import java.io.Serializable; import java.util.List; import org.opennms.core.criteria.Criteria; import org.opennms.netmgt.model.OnmsCriteria; /** * <p>OnmsDao interface.</p> */ public interface OnmsDao<T, K extends Serializable> { /** * This is used to lock the table in order to implement upsert type operations */ void lock(); /** * <p>initialize</p> * * @param obj a {@link java.lang.Object} object. * @param <T> a T object. * @param <K> a K object. */ void initialize(Object obj); /** * <p>flush</p> */ void flush(); /** * <p>clear</p> */ void clear(); /** * <p>countAll</p> * * @return a int. */ int countAll(); /** * <p>delete</p> * * @param entity a T object. */ void delete(T entity); /** * <p>delete</p> * * @param key a K object. */ void delete(K key); /** * <p>findAll</p> * * @return a {@link java.util.List} object. */ List<T> findAll(); /** * <p>findMatching</p> * * @param criteria a {@link org.opennms.core.criteria.Criteria} object. * @return a {@link java.util.List} object. */ List<T> findMatching(Criteria criteria); /** * <p>findMatching</p> * * @param criteria a {@link org.opennms.netmgt.model.OnmsCriteria} object. * @return a {@link java.util.List} object. */ List<T> findMatching(OnmsCriteria criteria); /** * <p>countMatching</p> * * @param onmsCrit a {@link org.opennms.core.criteria.Criteria} object. * @return a int. */ int countMatching(final Criteria onmsCrit); /** * <p>countMatching</p> * * @param onmsCrit a {@link org.opennms.netmgt.model.OnmsCriteria} object. * @return a int. */ int countMatching(final OnmsCriteria onmsCrit); /** * <p>get</p> * * @param id a K object. * @return a T object. */ T get(K id); /** * <p>load</p> * * @param id a K object. * @return a T object. */ T load(K id); /** * <p>save</p> * * @param entity a T object. */ void save(T entity); /** * <p>saveOrUpdate</p> * * @param entity a T object. */ void saveOrUpdate(T entity); /** * <p>update</p> * * @param entity a T object. */ void update(T entity); }
qoswork/opennmszh
opennms-dao/src/main/java/org/opennms/netmgt/dao/OnmsDao.java
Java
gpl-2.0
3,710
<?php // $Id: exercise.lib.php 14386 2013-02-08 13:03:23Z kitan1982 $ if ( count( get_included_files() ) == 1 ) die( '---' ); /** * CLAROLINE * * @version $Revision: 14386 $ * @copyright (c) 2001-2011, Universite catholique de Louvain (UCL) * @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE * @author Claro Team <cvs@claroline.net> */ /** * Build a list of available exercises that wil be used by claro_html_form_select to show a filter list * @param $excludeId an exercise id that doesn't have to be shown in filter list * @return array 2d array where keys are the exercise name and value is the exercise id * @author Sebastien Piraux <pir@cerdecam.be> */ function get_filter_list($excludeId = '') { $tbl_cdb_names = get_module_course_tbl( array( 'qwz_exercise' ), claro_get_current_course_id() ); $tbl_quiz_exercise = $tbl_cdb_names['qwz_exercise']; $filterList[get_lang('All exercises')] = 'all'; $filterList[get_lang('Orphan questions')] = 'orphan'; // get exercise list $sql = "SELECT `id`, `title` FROM `".$tbl_quiz_exercise."` ORDER BY `title`"; $exerciseList = claro_sql_query_fetch_all($sql); if( is_array($exerciseList) && !empty($exerciseList) ) { foreach( $exerciseList as $anExercise ) { if( $excludeId != $anExercise['id'] ) { $filterList[$anExercise['title']] = $anExercise['id']; } } } $questionCategoryList = getQuestionCategoryList(); // category foreach ($questionCategoryList as $category) { $filterList[get_lang('Category').' '.$category['title']] = 'categoryId'.$category['id']; } return $filterList; } /** * build a array making the correspondance between question type and its name * * @return array array where key is the type and value is the corresponding translation * @author Sebastien Piraux <pir@cerdecam.be> */ function get_localized_question_type() { $questionType['MCUA'] = get_lang('Multiple choice (Unique answer)'); $questionType['MCMA'] = get_lang('Multiple choice (Multiple answers)'); $questionType['TF'] = get_lang('True/False'); $questionType['FIB'] = get_lang('Fill in blanks'); $questionType['MATCHING'] = get_lang('Matching'); return $questionType; } /** * return the number of exercises using question $quId * * @param $quId requested question id * @return number of exercises using question $quId * @author Sebastien Piraux <pir@cerdecam.be> */ function count_exercise_using_question($quId) { $tbl_cdb_names = get_module_course_tbl( array( 'qwz_rel_exercise_question' ), claro_get_current_course_id() ); $tbl_quiz_rel_exercise_question = $tbl_cdb_names['qwz_rel_exercise_question']; $sql = "SELECT COUNT(`exerciseId`) FROM `".$tbl_quiz_rel_exercise_question."` WHERE `questionId` = '".(int) $quId."'"; $exerciseCount = claro_sql_query_get_single_value($sql); if( ! $exerciseCount ) return 0; else return $exerciseCount; } function set_learning_path_progression($totalResult,$totalGrade,$timeToCompleteExe,$_uid) { $tbl_cdb_names = get_module_course_tbl( array( 'lp_rel_learnPath_module', 'lp_user_module_progress' ), claro_get_current_course_id() ); $tbl_lp_rel_learnPath_module = $tbl_cdb_names['lp_rel_learnPath_module']; $tbl_lp_user_module_progress = $tbl_cdb_names['lp_user_module_progress']; // update raw in DB to keep the best one, so update only if new raw is better AND if user NOT anonymous if( $_uid ) { // exercices can have a negative score, but we don't accept that in LP // so if totalScore is negative use 0 as result $totalResult = max($totalResult, 0); if ( $totalGrade != 0 ) { $newRaw = @round($totalResult/$totalGrade*100); } else { $newRaw = 0; } $scoreMin = 0; $scoreMax = $totalGrade; $scormSessionTime = seconds_to_scorm_time($timeToCompleteExe); // need learningPath_module_id and raw_to_pass value $sql = "SELECT LPM.`raw_to_pass`, LPM.`learnPath_module_id`, UMP.`total_time`, UMP.`raw` FROM `".$tbl_lp_rel_learnPath_module."` AS LPM, `".$tbl_lp_user_module_progress."` AS UMP WHERE LPM.`learnPath_id` = '".(int)$_SESSION['path_id']."' AND LPM.`module_id` = '".(int)$_SESSION['module_id']."' AND LPM.`learnPath_module_id` = UMP.`learnPath_module_id` AND UMP.`user_id` = ".(int) $_uid; $lastProgression = claro_sql_query_get_single_row($sql); if( $lastProgression ) { // build sql query $sql = "UPDATE `".$tbl_lp_user_module_progress."` SET "; // if recorded score is more than the new score => update raw, credit and status if( $lastProgression['raw'] < $totalResult ) { // update raw $sql .= "`raw` = ".$totalResult.","; // update credit and statut if needed ( score is better than raw_to_pass ) if ( $newRaw >= $lastProgression['raw_to_pass']) { $sql .= " `credit` = 'CREDIT', `lesson_status` = 'PASSED',"; } else // minimum raw to pass needed to get credit { $sql .= " `credit` = 'NO-CREDIT', `lesson_status` = 'FAILED',"; } }// else don't change raw, credit and lesson_status // default query statements $sql .= " `scoreMin` = " . (int)$scoreMin . ", `scoreMax` = " . (int)$scoreMax . ", `total_time` = '".addScormTime($lastProgression['total_time'], $scormSessionTime)."', `session_time` = '".$scormSessionTime."' WHERE `learnPath_module_id` = ". (int)$lastProgression['learnPath_module_id']." AND `user_id` = " . (int)$_uid . ""; // Generate an event to notify that the exercise has been completed $learnPathEventArgs = array( 'userId' => (int)$_uid, 'courseCode' => claro_get_current_course_id(), 'scoreRaw' => (int)$totalResult, 'scoreMin' => (int)$scoreMin, 'scoreMax' => (int)$scoreMax, 'sessionTime' => $scormSessionTime, 'learnPathModuleId' => (int)$lastProgression['learnPath_module_id'], 'type' => "update" ); if ( $newRaw >= $lastProgression['raw_to_pass'] ) { $learnPathEventArgs['status'] = "PASSED"; } else { $learnPathEventArgs['status'] = "FAILED"; } $learnPathEvent = new Event( 'lp_user_module_progress_modified', $learnPathEventArgs ); EventManager::notify( $learnPathEvent ); return claro_sql_query($sql); } else { return false; } } } /** * return html required to display the required form elements to ask the user if the question must be modified in * all exercises or only the current one * * @return string html code * @author Sebastien Piraux <pir@cerdecam.be> */ function html_ask_duplicate() { $html = '<strong>' . get_lang('This question is used in several exercises.') . '</strong><br />' . "\n" . '<input type="radio" name="duplicate" id="doNotDuplicate" value="false"'; if( !isset($_REQUEST['duplicate']) || $_REQUEST['duplicate'] != 'true') { $html .= ' checked="checked" '; } $html .= '/>' . '<label for="doNotDuplicate">' . get_lang('Modify it in all exercises') . '</label><br />' . "\n" . '<input type="radio" name="duplicate" id="duplicate" value="true"'; if( isset($_REQUEST['duplicate']) && $_REQUEST['duplicate'] == 'true') { $html .= ' checked="checked" '; } $html .= '/>' . '<label for="duplicate">' . get_lang('Modify it only in this exercise') . '</label>' . "\n"; return $html; } /** * cast $value to a float with max 2 decimals * * @param string string to cast * @return string html code * @author Sebastien Piraux <pir@cerdecam.be> */ function castToFloat($value) { // use dot as decimal separator $value = (float) str_replace(',','.',$value); // round to max 2 decimals $value = round($value*100)/100; return $value; } /** * Record result of user when an exercice was done * @param exercise_id ( id in courseDb exercices table ) * @param result ( score @ exercice ) * @param weighting ( higher score ) * * @return inserted id or false if the query cannot be done * * @author Sebastien Piraux <seb@claroline.net> */ function track_exercice($exercise_id, $score, $weighting, $time, $uid = "") { // get table names $tblList = get_module_course_tbl( array( 'qwz_tracking' ), claro_get_current_course_id() ); $tbl_qwz_tracking = $tblList['qwz_tracking']; if( $uid != "" ) { $user_id = "'".(int) $uid."'"; } else // anonymous { $user_id = "NULL"; } $sql = "INSERT INTO `".$tbl_qwz_tracking."` SET `user_id` = ".$user_id.", `exo_id` = '".(int) $exercise_id."', `result` = '".(float) $score."', `weighting` = '".(float) $weighting."', `date` = FROM_UNIXTIME(".time()."), `time` = '".(int) $time."'"; return claro_sql_query_insert_id($sql); } /** * Record result of user when an exercice was done * @param exerciseTrackId id in qwz_tracking table * @param questionId id of the question * @param values array with user answers * @param questionResult result of this question * * @author Sebastien Piraux <seb@claroline.net> */ function track_exercise_details($exerciseTrackId, $questionId, $values, $questionResult) { // get table names $tblList = get_module_course_tbl( array( 'qwz_tracking_questions', 'qwz_tracking_answers' ), claro_get_current_course_id() ); $tbl_qwz_tracking_questions = $tblList['qwz_tracking_questions']; $tbl_qwz_tracking_answers = $tblList['qwz_tracking_answers']; // add the answer tracking informations $sql = "INSERT INTO `".$tbl_qwz_tracking_questions."` SET `exercise_track_id` = ".(int) $exerciseTrackId.", `question_id` = '".(int) $questionId."', `result` = '".(float) $questionResult."'"; $details_id = claro_sql_query_insert_id($sql); // check if previous query succeed to add answers if( $details_id && is_array($values) ) { // add, if needed, the different answers of the user // one line by answer // each entry of $values should be correctly formatted depending on the question type foreach( $values as $answer ) { $sql = "INSERT INTO `".$tbl_qwz_tracking_answers."` SET `details_id` = ". (int)$details_id.", `answer` = '".claro_sql_escape($answer)."'"; claro_sql_query($sql); } } return 1; } function change_img_url_for_pdf( $str ) { $pattern = '/(.*?)<img (.*?)src=(\'|")(.*?)url=(.*?)=&(.*?)(\'|")(.*?)>(.*?)$/is'; if( ! preg_match( $pattern, urldecode( $str ), $matches) ) { return $str; } if( count($matches) != 10 ) { return $str; } if( is_download_url_encoded( $matches[5] ) ) { $matches[5] = download_url_decode( $matches[5] ); } $matches[5] = get_conf('rootWeb') . 'courses/' . claro_get_current_course_id() . '/document' . $matches[5]; $replace = $matches[1].'<img ' . $matches[2] . ' src="' . $matches[5] .'" ' . $matches[8] . '>' . $matches[9]; return $replace; } function getQuestionCategoryList() { $categoryList = array(); $tbl_cdb_names = get_module_course_tbl( array('qwz_questions_categories' ), claro_get_current_course_id() ); $tblQuestionCategories = $tbl_cdb_names['qwz_questions_categories']; $query = "SELECT `id`, `title` FROM `".$tblQuestionCategories."` ORDER BY `title`"; if( claro_sql_query($query) ) { return claro_sql_query_fetch_all_rows($query); } else { return $categoryList; } } function getCategoryTitle( $categoryId ) { $tbl_cdb_names = get_module_course_tbl( array('qwz_questions_categories' ), claro_get_current_course_id() ); $tblQuestionCategories = $tbl_cdb_names['qwz_questions_categories']; $sql = "SELECT `title` FROM `".$tblQuestionCategories. "` WHERE `id`= '".(int)$categoryId."'"; $data = claro_sql_query_get_single_row($sql); if( !empty($data) ) { // from query return $data['title']; } else { return ''; } }
stevecole804/repda_lms.profilequinte.com
claroline/exercise/lib/exercise.lib.php
PHP
gpl-2.0
13,493
########################################################################## # Author: Jane Curry, jane.curry@skills-1st.co.uk # Date: April 19th, 2011 # Revised: # # interfaces.py for Predictive Threshold ZenPack # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zenoss.com/oss # ################################################################################ __doc__="""interfaces.py Representation of Predictive Threshold components. $Id: info.py,v 1.2 2010/12/14 20:45:46 jc Exp $""" __version__ = "$Revision: 1.4 $"[11:-2] from Products.Zuul.interfaces import IInfo, IFacade from Products.Zuul.interfaces.template import IThresholdInfo from Products.Zuul.form import schema from Products.Zuul.utils import ZuulMessageFactory as _t class IPredThresholdInfo(IThresholdInfo): """ Interfaces for Predictive Threshold """ # pointval = schema.List(title=_t(u"Data Point"), xtype='datapointitemselector', order=6) escalateCount = schema.Int(title=_t(u'Escalate Count'), order=9) alpha = schema.Text(title=_t(u'Alpha'), order=10) beta = schema.Text(title=_t(u'Beta'), order=11) gamma = schema.Text(title=_t(u'Gamma'), order=12) rows = schema.Text(title=_t(u'Rows'), order=13) season = schema.Text(title=_t(u'Season'), order=14) window = schema.Text(title=_t(u'Window'), order=15) threshold = schema.Text(title=_t(u'Threshold'), order=16) delta = schema.Text(title=_t(u'Delta'), order=17) predcolor = schema.Text(title=_t(u'Prediction Color'), order=18) cbcolor = schema.Text(title=_t(u'Confidence Band Color'), order=19) tkcolor = schema.Text(title=_t(u'Tick Color'), order=20) # pointval = schema.List(title=_t(u"Data Point"), xtype='datapointitemselector') # escalateCount = schema.Int(title=_t(u'Escalate Count')) # alpha = schema.Text(title=_t(u'Alpha')) # beta = schema.Text(title=_t(u'Beta')) # gamma = schema.Text(title=_t(u'Gamma')) # rows = schema.Text(title=_t(u'Rows')) # season = schema.Text(title=_t(u'Season')) # window = schema.Text(title=_t(u'Window')) # threshold = schema.Text(title=_t(u'Threshold')) # delta = schema.Text(title=_t(u'Delta')) # predcolor = schema.Text(title=_t(u'Prediction Color')) # cbcolor = schema.Text(title=_t(u'Confidence Band Color')) # tkcolor = schema.Text(title=_t(u'Tick Color'))
jcurry/ZenPacks.community.PredictiveThreshold
ZenPacks/community/PredictiveThreshold/interfaces.py
Python
gpl-2.0
2,440
//asteroid clone (core mechanics only) //arrow keys to move + x to shoot var bullets; var asteroids; var ship; var shipImage, bulletImage, particleImage; var MARGIN = 40; function setup() { createCanvas(800, 600); bulletImage = loadImage('assets/asteroids_bullet.png'); shipImage = loadImage('assets/asteroids_ship0001.png'); particleImage = loadImage('assets/asteroids_particle.png'); ship = createSprite(width/2, height/2); ship.maxSpeed = 6; ship.friction = 0.98; ship.setCollider('circle', 0, 0, 20); ship.addImage('normal', shipImage); ship.addAnimation('thrust', 'assets/asteroids_ship0002.png', 'assets/asteroids_ship0007.png'); asteroids = new Group(); bullets = new Group(); for(var i = 0; i<8; i++) { var ang = random(360); var px = width/2 + 1000 * cos(radians(ang)); var py = height/2+ 1000 * sin(radians(ang)); createAsteroid(3, px, py); } } function draw() { background(0); fill(255); textAlign(CENTER); text('Controls: Arrow Keys + X', width/2, 20); for(var i=0; i<allSprites.length; i++) { var s = allSprites[i]; if(s.position.x<-MARGIN) s.position.x = width+MARGIN; if(s.position.x>width+MARGIN) s.position.x = -MARGIN; if(s.position.y<-MARGIN) s.position.y = height+MARGIN; if(s.position.y>height+MARGIN) s.position.y = -MARGIN; } asteroids.overlap(bullets, asteroidHit); ship.bounce(asteroids); if(keyDown(LEFT_ARROW)) ship.rotation -= 4; if(keyDown(RIGHT_ARROW)) ship.rotation += 4; if(keyDown(UP_ARROW)) { ship.addSpeed(0.2, ship.rotation); ship.changeAnimation('thrust'); } else ship.changeAnimation('normal'); if(keyWentDown('x')) { var bullet = createSprite(ship.position.x, ship.position.y); bullet.addImage(bulletImage); bullet.setSpeed(10+ship.getSpeed(), ship.rotation); bullet.life = 30; bullets.add(bullet); } drawSprites(); } function createAsteroid(type, x, y) { var a = createSprite(x, y); var img = loadImage('assets/asteroid'+floor(random(0, 3))+'.png'); a.addImage(img); a.setSpeed(2.5-(type/2), random(360)); a.rotationSpeed = 0.5; //a.debug = true; a.type = type; if(type == 2) a.scale = 0.6; if(type == 1) a.scale = 0.3; a.mass = 2+a.scale; a.setCollider('circle', 0, 0, 50); asteroids.add(a); return a; } function asteroidHit(asteroid, bullet) { var newType = asteroid.type-1; if(newType>0) { createAsteroid(newType, asteroid.position.x, asteroid.position.y); createAsteroid(newType, asteroid.position.x, asteroid.position.y); } for(var i=0; i<10; i++) { var p = createSprite(bullet.position.x, bullet.position.y); p.addImage(particleImage); p.setSpeed(random(3, 5), random(360)); p.friction = 0.95; p.life = 15; } bullet.remove(); asteroid.remove(); }
sabotai/energyDrinkGame
p5.play/examples/asteroids.js
JavaScript
gpl-2.0
2,832
<?php /** * @package HUBzero CMS * @author Alissa Nedossekina <alisa@purdue.edu> * @copyright Copyright 2005-2009 by Purdue Research Foundation, West Lafayette, IN 47906 * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2 * * Copyright 2005-2009 by Purdue Research Foundation, West Lafayette, IN 47906. * All rights reserved. * * 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. */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die( 'Restricted access' ); // Build url $route = $this->project->provisioned ? 'index.php?option=com_publications' . a . 'task=submit' : 'index.php?option=com_projects' . a . 'alias=' . $this->project->alias; $p_url = JRoute::_($route . a . 'active=files'); // Directory path breadcrumbs $desect_path = explode(DS, $this->subdir); $path_bc = ''; $url = ''; $parent = ''; if(count($desect_path) > 0) { for($p = 0; $p < count($desect_path); $p++) { $parent .= count($desect_path) > 1 && $p != count($desect_path) ? $url : ''; $url .= DS.$desect_path[$p]; $path_bc .= ' &raquo; <span><a href="'.$p_url.'/?subdir='.urlencode($url).'" class="folder">'.$desect_path[$p].'</a></span> '; } } $shown = array(); ?> <form action="<?php echo JRoute::_($route).'?active=publications'; ?>" method="post" enctype="multipart/form-data" id="upload-form" > <ul id="c-browser" <?php if(count($this->files) == 0) { echo 'class="hidden"'; } ?>> <?php if($this->subdir) { ?> <li><a href="<?php echo $p_url.'/?action=browser'.a.'subdir='.$parent; ?>" class="uptoparent gotodir"><?php echo JText::_('COM_PROJECTS_FILES_BACK_TO_PARENT_DIR'); ?></a></li> <?php } if(count($this->files) > 0) { // Do ordering $names = array(); foreach ($this->files as $f) { $names[] = $f['name']; } sort($names); array_multisort($this->files, SORT_ASC, SORT_STRING, $names, SORT_ASC ); $i = 0; foreach($this->files as $file) { if($this->images) { // if(!in_array(strtolower($file['ext']), $this->image_ext)) { if(!in_array(strtolower($file['ext']), $this->image_ext) && !in_array(strtolower($file['ext']), $this->video_ext)) { // Skip non-image/video files continue; } } if(in_array($file['fpath'], $this->exclude)) { // Skip files attached in another role continue; } // Ignore hidden files if(substr(basename($file['fpath']), 0, 1) == '.') { continue; } $shown[] = $file['fpath']; ?> <li class="c-click item|file::<?php echo urlencode($file['fpath']); ?>"><img src="<?php echo ProjectsHtml::getFileIcon($file['ext']); ?>" alt="<?php echo $file['ext']; ?>" /><?php echo $file['fpath']; ?></li> <?php $i++; ?> <?php } } $missing = array(); // Check for missing items // Primary content / Supporting docs if(isset($this->attachments)) { if(count($this->attachments) > 0) { foreach($this->attachments as $attachment) { if(!in_array($attachment->path, $shown)) { // Found missing $miss = array(); $miss['fpath'] = $attachment->path; $miss['ext'] = ProjectsHtml::getFileAttribs( $attachment->path, '', 'ext' ); $missing[] = $miss; } } } } // Screenshots if($this->images) { if(count($this->shots) > 0) { foreach($this->shots as $shot) { if(!in_array($shot->filename, $shown)) { // Found missing $miss = array(); $miss['fpath'] = $shot->filename; $miss['ext'] = ProjectsHtml::getFileAttribs( $shot->filename, '', 'ext' ); $missing[] = $miss; } } } } // Add missing items if(count($missing) > 0) { foreach ($missing as $miss) { ?> <li class="c-click item|file::<?php echo urlencode($miss['fpath']); ?> i-missing"><img src="<?php echo ProjectsHtml::getFileIcon($miss['ext']); ?>" alt="<?php echo $miss['ext']; ?>" /><?php echo $miss['fpath']; ?><span class="c-missing"><?php echo JText::_('PLG_PROJECTS_FILES_MISSING_FILE'); ?></span></li> <?php } } ?> </ul> <label class="addnew"> <input name="upload[]" type="file" size="20" class="option" id="uploader" /> </label> <input type="hidden" name="option" value="<?php echo $this->option; ?>" /> <input type="hidden" name="id" value="<?php echo $this->project->id; ?>" /> <input type="hidden" name="uid" id="uid" value="<?php echo $this->uid; ?>" /> <input type="hidden" name="pid" id="pid" value="<?php echo $this->pid; ?>" /> <input type="hidden" name="images" id="images" value="<?php echo $this->images; ?>" /> <input type="hidden" name="active" value="files" /> <input type="hidden" name="action" value="<?php echo $this->project->provisioned == 1 && !$this->pid ? 'saveprov' : 'save'; ?>" /> <input type="hidden" name="view" value="pub" /> <input type="hidden" name="ajax" value="0" /> <input type="hidden" name="no_html" value="0" /> <input type="hidden" name="return_status" id="return_status" value="0" /> <input type="hidden" name="expand_zip" id="expand_zip" value="0" /> <input type="hidden" name="subdir" value="<?php echo $this->subdir; ?>" /> <input type="hidden" name="provisioned" id="provisioned" value="<?php echo $this->project->provisioned == 1 ? 1 : 0; ?>" /> <?php if($this->project->provisioned == 1 ) { ?> <input type="hidden" name="task" value="submit" /> <?php } ?> <input type="submit" value="<?php echo JText::_('COM_PROJECTS_UPLOAD'); ?>" class="btn yesbtn" id="b-upload" /> </form>
CI-Water-DASYCIM/CIWaterHubZeroPortalDev
plugins/projects/files/views/upload/tmpl/files.php
PHP
gpl-2.0
6,034
def ExOh(str): temp = list(str) xcount = 0 ocount = 0 for c in temp: if c == "x": xcount += 1 if c == "o": ocount += 1 if xcount == ocount: print "true" elif xcount != ocount: print "false" ExOh(raw_input())
ohgodscience/Python
Exercises/ExOh.py
Python
gpl-2.0
230
<?php /** * This file is part of PHPWord - A pure PHP library for reading and writing * word processing documents. * * PHPWord is free software distributed under the terms of the GNU Lesser * General Public License version 3 as published by the Free Software Foundation. * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. For the full list of * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * * @see https://github.com/PHPOffice/PHPWord * @copyright 2010-2017 PHPWord contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ namespace PhpOffice\PhpWord\Style; use PhpOffice\PhpWord\PhpWord; use PhpOffice\PhpWord\SimpleType\LineSpacingRule; use PhpOffice\PhpWord\TestHelperDOCX; /** * Test class for PhpOffice\PhpWord\Style\Paragraph * * @runTestsInSeparateProcesses */ class ParagraphTest extends \PHPUnit\Framework\TestCase { /** * Tear down after each test */ public function tearDown() { TestHelperDOCX::clear(); } /** * Test setting style values with null or empty value */ public function testSetStyleValueWithNullOrEmpty() { $object = new Paragraph(); $attributes = array( 'widowControl' => true, 'keepNext' => false, 'keepLines' => false, 'pageBreakBefore' => false, 'contextualSpacing' => false, ); foreach ($attributes as $key => $default) { $get = $this->findGetter($key, $default, $object); $object->setStyleValue($key, null); $this->assertEquals($default, $object->$get()); $object->setStyleValue($key, ''); $this->assertEquals($default, $object->$get()); } } /** * Test setting style values with normal value */ public function testSetStyleValueNormal() { $object = new Paragraph(); $attributes = array( 'spaceAfter' => 240, 'spaceBefore' => 240, 'indent' => 1, 'hanging' => 1, 'spacing' => 120, 'spacingLineRule' => LineSpacingRule::AT_LEAST, 'basedOn' => 'Normal', 'next' => 'Normal', 'numStyle' => 'numStyle', 'numLevel' => 1, 'widowControl' => false, 'keepNext' => true, 'keepLines' => true, 'pageBreakBefore' => true, 'contextualSpacing' => true, 'textAlignment' => 'auto', 'bidi' => true, ); foreach ($attributes as $key => $value) { $get = $this->findGetter($key, $value, $object); $object->setStyleValue("$key", $value); if ('indent' == $key || 'hanging' == $key) { $value = $value * 720; } elseif ('spacing' == $key) { $value += 240; } $this->assertEquals($value, $object->$get()); } } private function findGetter($key, $value, $object) { if (is_bool($value)) { if (method_exists($object, "is{$key}")) { return "is{$key}"; } elseif (method_exists($object, "has{$key}")) { return "has{$key}"; } } return "get{$key}"; } /** * Test get null style value */ public function testGetNullStyleValue() { $object = new Paragraph(); $attributes = array('spacing', 'indent', 'hanging', 'spaceBefore', 'spaceAfter', 'textAlignment'); foreach ($attributes as $key) { $get = $this->findGetter($key, null, $object); $this->assertNull($object->$get()); } } /** * Test tabs */ public function testTabs() { $object = new Paragraph(); $object->setTabs(array(new Tab('left', 1550), new Tab('right', 5300))); $this->assertCount(2, $object->getTabs()); } /** * Line height */ public function testLineHeight() { $phpWord = new PhpWord(); $section = $phpWord->addSection(); // Test style array $text = $section->addText('This is a test', array(), array('line-height' => 2.0)); $doc = TestHelperDOCX::getDocument($phpWord); $element = $doc->getElement('/w:document/w:body/w:p/w:pPr/w:spacing'); $lineHeight = $element->getAttribute('w:line'); $lineRule = $element->getAttribute('w:lineRule'); $this->assertEquals(480, $lineHeight); $this->assertEquals('auto', $lineRule); // Test setter $text->getParagraphStyle()->setLineHeight(3.0); $doc = TestHelperDOCX::getDocument($phpWord); $element = $doc->getElement('/w:document/w:body/w:p/w:pPr/w:spacing'); $lineHeight = $element->getAttribute('w:line'); $lineRule = $element->getAttribute('w:lineRule'); $this->assertEquals(720, $lineHeight); $this->assertEquals('auto', $lineRule); } /** * Test setLineHeight validation */ public function testLineHeightValidation() { $object = new Paragraph(); $object->setLineHeight('12.5pt'); $this->assertEquals(12.5, $object->getLineHeight()); } /** * Test line height exception by using nonnumeric value * * @expectedException \PhpOffice\PhpWord\Exception\InvalidStyleException */ public function testLineHeightException() { $object = new Paragraph(); $object->setLineHeight('a'); } }
seltmann/Symbiota
vendor/phpoffice/phpword/tests/PhpWord/Style/ParagraphTest.php
PHP
gpl-2.0
5,799
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :identity do end end
livehq/api
spec/factories/identities.rb
Ruby
gpl-2.0
125
<?php namespace Google\AdsApi\AdWords\v201609\o; /** * This file was generated from WSDL. DO NOT EDIT. */ class StringAttribute extends \Google\AdsApi\AdWords\v201609\o\Attribute { /** * @var string $value */ protected $value = null; /** * @param string $AttributeType * @param string $value */ public function __construct($AttributeType = null, $value = null) { parent::__construct($AttributeType); $this->value = $value; } /** * @return string */ public function getValue() { return $this->value; } /** * @param string $value * @return \Google\AdsApi\AdWords\v201609\o\StringAttribute */ public function setValue($value) { $this->value = $value; return $this; } }
renshuki/dfp-manager
vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201609/o/StringAttribute.php
PHP
gpl-2.0
812
#!/usr/bin/env python # -*- coding: utf-8 -*- # StartOS Device Manager(ydm). # Copyright (C) 2011 ivali, Inc. # hechao <hechao@ivali.com>, 2011. __author__="hechao" __date__ ="$2011-12-20 16:36:20$" import gc from xml.parsers import expat from hwclass import * class Device: def __init__(self, dev_xml): self.description = '' self.product = '' self.vendor = '' self.version = '' self.businfo = '' self.logicalname = '' self.date = '' self.serial = '' self.capacity = '' self.width = '' self.clock = '' self.slot = '' self.size = '' self.config = {} self.capability = [] self.attr = {} self.dev_type = {} self.pcid = {} self._parser = expat.ParserCreate() self._parser.buffer_size = 102400 self._parser.StartElementHandler = self.start_handler self._parser.CharacterDataHandler = self.data_handler self._parser.EndElementHandler = self.end_handler self._parser.returns_unicode = False fd = file(dev_xml) self._parser.ParseFile(fd) fd.close() def start_handler(self, tag, attrs): self.flag = tag if tag == "node": self.attr = attrs elif tag == "setting": self.config.setdefault(attrs["id"], attrs["value"]) elif tag == "capability": self.capability.append(attrs["id"]) def data_handler(self, data): if(data == '\n'): return if(data.isspace()): return if self.flag == "description": self.description = data.strip() elif self.flag == "product": self.product = data.strip() elif self.flag == "vendor": self.vendor = data.strip() elif self.flag == "businfo": self.businfo = data.strip() elif self.flag == "logicalname": self.logicalname = data.strip() elif self.flag == "version": self.version = data.strip() elif self.flag == "date": self.date = data.strip() elif self.flag == "serial": self.serial = data.strip() elif self.flag == "capacity": self.capacity = data.strip() elif self.flag == "width": self.width = data.strip() elif self.flag == "clock": self.clock = data.strip() elif self.flag == "slot": self.slot = data.strip() elif self.flag == "size": self.size = data.strip() def end_handler(self, tag): if tag == "node": if self.attr["class"] == "system": system = System(self.description, self.product, self.vendor, self.version, \ self.serial, self.width, self.config, self.capability) self.dev_type.setdefault((0, "system"), []).append(system) elif self.attr["id"].split(":")[0] == "cpu" and self.attr["class"] == "processor": cpu = Cpu(self.description, self.product, self.vendor, self.version, \ self.businfo, self.serial, self.slot, self.size, self.capacity, self.width, self.clock, self.config, self.capability) self.dev_type.setdefault((1, "cpu"), []).append(cpu) elif self.attr["id"].split(":")[0] == "cache" and self.attr["class"] == "memory": cache = Cache(self.description, self.product, self.vendor, self.version, self.slot, self.size) self.dev_type.setdefault((1, "cpu"), []).append(cache) elif (self.attr["id"] == "core" or self.attr["id"] == "board") and self.attr["class"] == "bus": motherboard = Motherboard(self.description, self.product, self.vendor, self.version, self.serial) self.dev_type.setdefault((2, "motherboard"), []).append(motherboard) elif self.attr["id"] == "firmware" and self.attr["class"] == "memory": bios = Bios(self.description, self.product, self.vendor, self.version, \ self.date, self.size, self.capability) self.dev_type.setdefault((2, "motherboard"), []).append(bios) elif self.attr["id"].split(":")[0] == "memory" and self.attr["class"] == "memory": memory = Memory(self.description, self.product, self.vendor, self.version, \ self.slot, self.size) self.dev_type.setdefault((3, "memory"), []).append(memory) elif self.attr["id"].split(":")[0] == "bank" and self.attr["class"] == "memory": bank = Bank(self.description, self.product, self.vendor, self.version, \ self.serial, self.slot, self.size, self.width, self.clock) self.dev_type.setdefault((3, "memory"), []).append(bank) elif self.attr["id"].split(":")[0] == "display" and self.attr["class"] == "display": display = Display(self.description, self.product, self.vendor, self.version, \ self.businfo, self.config, self.capability) self.dev_type.setdefault((4, "display"), []).append(display) self.pcid[display.pcid] = "display" if get_monitor(): monitor = Monitor("", "", "", "") self.dev_type.setdefault((5, "monitor"), [monitor])#.append(monitor) elif self.attr["id"].split(":")[0] == "disk" and self.attr["class"] == "disk": disk = Disk(self.description, self.product, self.vendor, self.version, \ self.businfo, self.logicalname, self.serial, self.size, self.config, self.capability) self.dev_type.setdefault((6, "disk"), []).append(disk) elif self.attr["id"].split(":")[0] == "cdrom" and self.attr["class"] == "disk": cdrom = Cdrom(self.description, self.product, self.vendor, self.version, \ self.businfo, self.logicalname, self.config, self.capability) self.dev_type.setdefault((7, "cdrom"), []).append(cdrom) elif self.attr["class"] == "storage" and self.attr["handle"]: storage = Storage(self.description, self.product, self.vendor, self.version, \ self.businfo, self.logicalname, self.serial, self.config, self.capability) self.dev_type.setdefault((8, "storage"), []).append(storage) elif (self.attr["class"] == "network") or (self.attr["id"].split(":")[0] == "bridge" \ and self.attr["class"] == "bridge"): network = Network(self.description, self.product, self.vendor, self.version, \ self.businfo, self.logicalname, self.serial, self.capacity, self.config, self.capability) self.dev_type.setdefault((9, "network"), []).append(network) self.pcid[network.pcid] = "network" elif self.attr["class"] == "multimedia": media = Multimedia(self.description, self.product, self.vendor, self.version, \ self.businfo, self.config, self.capability) self.dev_type.setdefault((10, "multimedia"), []).append(media) self.pcid[media.pcid] = "multimedia" elif self.attr["class"] == "input": imput = Imput(self.description, self.product, self.vendor, self.version, \ self.businfo, self.config, self.capability) self.dev_type.setdefault((11, "input"), []).append(imput) self.pcid[imput.pcid] = "input" elif self.attr["id"].split(":")[0] != "generic" and self.attr["class"] == "generic": generic = Generic(self.description, self.product, self.vendor, self.version, \ self.businfo, self.serial, self.config, self.capability) self.dev_type.setdefault((12, "generic"), []).append(generic) self.pcid[generic.pcid] = "generic" elif self.attr["id"].split(":")[0] != "communication" and self.attr["class"] == "communication": modem = Modem(self.description, self.product, self.vendor, self.version, \ self.businfo, self.serial, self.config, self.capability) self.dev_type.setdefault((12, "generic"), []).append(modem) elif self.attr["id"].split(":")[0] == "battery" and self.attr["class"] == "power": power = Power(self.description, self.product, self.vendor, self.version, \ self.slot, self.capacity, self.config) self.dev_type.setdefault((12, "generic"), []).append(power) self.clear() def clear(self): self.description = '' self.product = '' self.vendor = '' self.version = '' self.businfo = '' self.logicalname = '' self.date = '' self.serial = '' self.capacity = '' self.width = '' self.clock = '' self.slot = '' self.size = '' self.config = {} self.capability = [] self.attr = {} def close(self): del self._parser gc.collect()
jun-zhang/device-manager
src/lib/ydevicemanager/devices.py
Python
gpl-2.0
8,950
$:.push(File.join(File.dirname(__FILE__), '../../lib')) module Helpers def hand(*cards) Ranking::Hand.new(*cards) end end require 'rspec' include Helpers require_relative '../../lib/ranking/hand' module Ranking class Hand def should_defeat otherHand self.defeats?(otherHand).should == true otherHand.defeats?(self).should == false end def should_tie_with otherHand self.defeats?(otherHand).should == false otherHand.defeats?(self).should == false end end end
ljszalai/poker-croupier
common/spec/ranking/spec_helper.rb
Ruby
gpl-2.0
524
#include <Gosu/WinUtility.hpp> #include <Gosu/Utility.hpp> #include <stdexcept> #include <vector> namespace { typedef std::vector<std::tr1::function<bool (MSG&)> > Hooks; Hooks hooks; bool handledByHook(MSG& message) { for (Hooks::iterator i = hooks.begin(); i != hooks.end(); ++i) if ((*i)(message)) return true; return false; } } HINSTANCE Gosu::Win::instance() { return check(::GetModuleHandle(0), "getting the module handle"); } void Gosu::Win::handleMessage() { MSG message; BOOL ret = ::GetMessage(&message, 0, 0, 0); switch (ret) { case -1: { // GetMessage() failed. throwLastError("trying to get the next message"); } case 0: { // GetMessage() found a WM_QUIT message. // IMPR: Is there a better way to respond to this? break; } default: { // Normal behaviour, if the message does not get handled by // something else. if (!handledByHook(message)) { ::TranslateMessage(&message); ::DispatchMessage(&message); } } } } void Gosu::Win::processMessages() { MSG message; while (::PeekMessage(&message, 0, 0, 0, PM_REMOVE)) if (!handledByHook(message)) { ::TranslateMessage(&message); ::DispatchMessage(&message); } } void Gosu::Win::registerMessageHook(const std::tr1::function<bool (MSG&)>& hook) { hooks.push_back(hook); } void Gosu::Win::throwLastError(const std::string& action) { // Obtain error message from Windows. char* buffer; if (!::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&buffer), 0, 0) || buffer == 0) { // IMPR: Can we do better than this? throw std::runtime_error("Unknown error"); } // Move the message out of the ugly char* buffer. std::string message; try { message = buffer; } catch (...) { ::LocalFree(buffer); throw; } ::LocalFree(buffer); // Optionally prepend the action. if (!action.empty()) message = "While " + action + ", the following error occured: " + message; // Now throw it. throw std::runtime_error(message); } std::wstring Gosu::Win::appFilename() { static std::wstring result; if (!result.empty()) return result; wchar_t buffer[MAX_PATH * 2]; check(::GetModuleFileName(0, buffer, MAX_PATH * 2), "getting the module filename"); result = buffer; return result; } std::wstring Gosu::Win::appDirectory() { static std::wstring result; if (!result.empty()) return result; result = appFilename(); std::wstring::size_type lastDelim = result.find_last_of(L"\\/"); if (lastDelim != std::wstring::npos) result.resize(lastDelim + 1); else result = L""; return result; }
sustmi/oflute
gosu/GosuImpl/WinUtility.cpp
C++
gpl-2.0
3,335
//>>built define("dojox/embed/flashVars",["dojo"],function(_1){ _1.deprecated("dojox.embed.flashVars","Will be removed in 2.0","2.0"); var _2={serialize:function(n,o){ var _3=function(_4){ if(typeof _4=="string"){ _4=_4.replace(/;/g,"_sc_"); _4=_4.replace(/\./g,"_pr_"); _4=_4.replace(/\:/g,"_cl_"); } return _4; }; var df=dojox.embed.flashVars.serialize; var _5=""; if(_1.isArray(o)){ for(var i=0;i<o.length;i++){ _5+=df(n+"."+i,_3(o[i]))+";"; } return _5.replace(/;{2,}/g,";"); }else{ if(_1.isObject(o)){ for(var nm in o){ _5+=df(n+"."+nm,_3(o[nm]))+";"; } return _5.replace(/;{2,}/g,";"); } } return n+":"+o; }}; _1.setObject("dojox.embed.flashVars",_2); return _2; });
hariomkumarmth/champaranexpress
wp-content/plugins/dojo/dojox/embed/flashVars.js
JavaScript
gpl-2.0
705
namespace { enum EnumValue { EnumValue1 = 1 << 1 }; }
nivekkagicom/uncrustify
tests/input/cpp/Issue_2149.cpp
C++
gpl-2.0
134
<?php /** * Internationalisation for LogEntry extension * * @file * @ingroup Extensions */ $messages = array(); /** English * @author Trevor Parscal */ $messages['en'] = array( 'logentry-append' => 'Append', 'logentry-parserhook-desc' => 'This tag extension provides a form for appending/prepending to log pages', 'logentry-specialpage-desc' => 'This tag extension provides processing for appending to log pages', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Invalid page: $1', 'logentry-invalidtoken' => 'Invalid token', ); /** Message documentation (Message documentation) * @author Bennylin * @author Purodha * @author The Evil IP address */ $messages['qqq'] = array( 'logentry-append' => '{{Identical|Append}}', 'logentry-parserhook-desc' => '{{desc}}', ); /** Afrikaans (Afrikaans) * @author Naudefj */ $messages['af'] = array( 'logentry-append' => 'Byvoeg', 'logentry-invalidpage' => 'Ongeldige bladsy', 'logentry-invalidtoken' => 'Ongeldige token', ); /** Arabic (العربية) * @author Meno25 * @author OsamaK */ $messages['ar'] = array( 'logentry-append' => 'ألحق', 'logentry-parserhook-desc' => 'امتداد الوسم هذا يوفر استمارة للإضافة/التخطيط لصفحات السجلات', 'logentry-specialpage-desc' => 'امتداد الوسم هذا يوفر معالجة للإضافة لصفحات السجلات', 'logentry' => 'مدخلة سجل', 'logentry-invalidpage' => 'صفحة غير صحيحة', 'logentry-invalidtoken' => 'نص غير صحيح', ); /** Egyptian Spoken Arabic (مصرى) * @author Meno25 */ $messages['arz'] = array( 'logentry-append' => 'إضافة', 'logentry-parserhook-desc' => 'امتداد الوسم هذا يوفر استمارة للإضافة/التخطيط لصفحات السجلات', 'logentry-specialpage-desc' => 'امتداد الوسم هذا يوفر معالجة للإضافة لصفحات السجلات', 'logentry' => 'مدخلة سجل', 'logentry-invalidpage' => 'صفحة غير صحيحة', 'logentry-invalidtoken' => 'نص غير صحيح', ); /** Asturian (Asturianu) * @author Xuacu */ $messages['ast'] = array( 'logentry-append' => 'Amestar', 'logentry-parserhook-desc' => "Esta estensión d'etiqueta proporciona un formulariu p'amestar/encabezar a les páxines de rexistru", 'logentry-specialpage-desc' => "Esta estensión d'etiqueta proporciona un procesamientu p'amestar a les páxines de rexistru", 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Páxina inválida: $1', 'logentry-invalidtoken' => 'Token non válidu', ); /** Bavarian (Boarisch) * @author Man77 */ $messages['bar'] = array( 'logentry-invalidpage' => 'Ungültige Seitn', ); /** Belarusian (Taraškievica orthography) (‪Беларуская (тарашкевіца)‬) * @author EugeneZelenko * @author Jim-by */ $messages['be-tarask'] = array( 'logentry-append' => 'Дадаць', 'logentry-parserhook-desc' => 'Гэты тэг пашырэньня дадае форму для даданьня інфармацыі ў журналы падзеяў', 'logentry-specialpage-desc' => 'Гэты тэг пашырэньня дазваляе дадаваць інфармацыю ў журналы падзеяў', 'logentry' => 'Дадаць інфармацыю ў журналы падзеяў', 'logentry-invalidpage' => 'Няслушная старонка: $1', 'logentry-invalidtoken' => 'Няслушны сымбаль', ); /** Bulgarian (Български) * @author DCLXVI */ $messages['bg'] = array( 'logentry-invalidpage' => 'Невалидна страница', ); /** Bengali (বাংলা) * @author Wikitanvir */ $messages['bn'] = array( 'logentry' => 'লগএন্ট্রি', 'logentry-invalidpage' => 'ত্রুটিপূর্ণ পাতা', 'logentry-invalidtoken' => 'অবৈধ টোকেন', ); /** Breton (Brezhoneg) * @author Fulup */ $messages['br'] = array( 'logentry-append' => 'Ouzhpennañ', 'logentry-parserhook-desc' => "Ouzhpennañ a ra an astenn-mañ ur valizenn a bourchas ur furmskrid da ouzhpennañ/rakproseziñ testennoù d'ar pajennoù marilh", 'logentry-specialpage-desc' => 'Porvezañ a ra an astenn balizennoù-mañ un argerzh evit ober ouzhpennadennoù da bajennoù ar marilhoù', 'logentry' => 'Marilh ar monedoù', 'logentry-invalidpage' => 'Pajenn direizh : $1', 'logentry-invalidtoken' => 'Fichenn direizh', ); /** Bosnian (Bosanski) * @author CERminator */ $messages['bs'] = array( 'logentry-append' => 'Pridodaj', 'logentry-parserhook-desc' => 'Ova oznaka proširenja omogućuje obrazac za dodavanje/uklanjanje informacija sa stranica zapisnika', 'logentry-specialpage-desc' => 'Ova oznaka proširenja omogućuje obradu neriješenih stranica zapisnika', 'logentry' => 'StavkaZapisa', 'logentry-invalidpage' => 'Nevaljana stranica', 'logentry-invalidtoken' => 'Nevaljan token', ); /** Catalan (Català) * @author Paucabot */ $messages['ca'] = array( 'logentry-invalidpage' => 'Pàgina no vàlida', ); /** Czech (Česky) */ $messages['cs'] = array( 'logentry-append' => 'Přidat', 'logentry-invalidtoken' => 'Neplatný token', ); /** German (Deutsch) * @author Kghbln * @author Melancholie */ $messages['de'] = array( 'logentry-append' => 'Anfügen', 'logentry-parserhook-desc' => 'Diese Tag-Erweiterung bietet ein Formular zur Anhängung/Voranstellung in Logbuchseiten', 'logentry-specialpage-desc' => 'Diese Tag-Erweiterung bietet die Aufbereitung für Anhängungen an Logbuchseiten', 'logentry' => 'Logbucheintrag', 'logentry-invalidpage' => 'Ungültige Seite: $1', 'logentry-invalidtoken' => 'Ungültiges Token', ); /** Lower Sorbian (Dolnoserbski) * @author Michawiki */ $messages['dsb'] = array( 'logentry-append' => 'Pśipowjesyś', 'logentry-parserhook-desc' => 'Toś to rozšyrjenje staja formular za pśipowjesenje a zachopjenje k protokolowym bokam k dispoziciji', 'logentry-specialpage-desc' => 'Toś to rozšyrjenje staja pśeźěłanje za pśipowjesenje k protokolowym bokam k dispoziciji', 'logentry' => 'Protokolowy zapisk', 'logentry-invalidpage' => 'Njepłaśiwy bok: $1', 'logentry-invalidtoken' => 'Njepłaśiwy token', ); /** Greek (Ελληνικά) * @author Omnipaedista * @author ZaDiak */ $messages['el'] = array( 'logentry-append' => 'Προσάρτηση', 'logentry' => 'Αρχείο καταχωρήσεων', 'logentry-invalidpage' => 'Μη έγκυρη σελίδα', 'logentry-invalidtoken' => 'Μή έγκυρο δείγμα', ); /** Esperanto (Esperanto) * @author Melancholie * @author Yekrats */ $messages['eo'] = array( 'logentry-append' => 'Almeti', 'logentry-parserhook-desc' => 'Ĉi tiu etikeda etendilo provizas paĝon por aldoni al la fino aux komenco de protokolaj paĝoj', 'logentry-specialpage-desc' => 'Ĉi tiu etikeda etendilo provizas procesado por aldonado al protokolaj paĝoj', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Malvalida paĝo', 'logentry-invalidtoken' => 'Malvalida ĵetono', ); /** Spanish (Español) * @author Crazymadlover */ $messages['es'] = array( 'logentry-append' => 'Apéndice', 'logentry-parserhook-desc' => 'Esta extensión de etiqueta provee un formulario para añadir/preprocesar a páginas de registro', 'logentry-specialpage-desc' => 'Esta extensión de etiqueta provee un proceso para añadir a páginas de registro', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Página inválida', 'logentry-invalidtoken' => 'Ficha inválida', ); /** Basque (Euskara) * @author Kobazulo */ $messages['eu'] = array( 'logentry-append' => 'Erantsi', 'logentry-invalidpage' => 'Baliogabeko orrialdea', ); /** Finnish (Suomi) * @author Cimon Avaro * @author Crt * @author Str4nd * @author Vililikku */ $messages['fi'] = array( 'logentry-append' => 'Lisää', 'logentry-parserhook-desc' => 'Tämä merkintälaajennus tarjoaa lomakkeen, jonka avulla voidaan lisätä tekstiä lokisivujen alkuun tai loppuun.', 'logentry-invalidpage' => 'Virheellinen sivu: $1', 'logentry-invalidtoken' => 'Virheellinen lipuke', ); /** French (Français) * @author Grondin * @author Hashar * @author IAlex * @author McDutchie */ $messages['fr'] = array( 'logentry-append' => 'Ajouter', 'logentry-parserhook-desc' => 'Cette extension ajoute une balise fournissant un formulaire pour ajouter / préfixer du texte aux pages de journaux', 'logentry-specialpage-desc' => 'Cette extension de balise ajoute un processus pour ajouter aux pages de journaux', 'logentry' => 'Journal des entrées', 'logentry-invalidpage' => 'Page incorrecte : $1', 'logentry-invalidtoken' => 'Prise incorrecte', ); /** Franco-Provençal (Arpetan) * @author ChrisPtDe */ $messages['frp'] = array( 'logentry-append' => 'Apondre', 'logentry' => 'Entrâ du jornal', 'logentry-invalidpage' => 'Pâge fôssa : $1', 'logentry-invalidtoken' => 'Prêsa fôssa', ); /** Galician (Galego) * @author Toliño */ $messages['gl'] = array( 'logentry-append' => 'Anexar', 'logentry-parserhook-desc' => 'Esta extensión proporciona un formulario para anexar/prefixar ás páxinas de rexistros', 'logentry-specialpage-desc' => 'Esta extensión proporciona un proceso para anexar ás páxinas de rexistros', 'logentry' => 'Entrada do rexistro', 'logentry-invalidpage' => 'Páxina inválida: $1', 'logentry-invalidtoken' => 'Pase incorrecto', ); /** Swiss German (Alemannisch) * @author Als-Chlämens * @author Als-Holder */ $messages['gsw'] = array( 'logentry-append' => 'Aafiege', 'logentry-parserhook-desc' => 'Die Tag-Erwyterig bietet e Formular zum Aahänge/Voraastelle in Logbuechsyte', 'logentry-specialpage-desc' => 'Die Tag-Erwyterig bietet d Ufbereitig fir s Aahänge an Logbuechsyte', 'logentry' => 'Logbuechyytrag', 'logentry-invalidpage' => 'Nit giltigi Syte: $1', 'logentry-invalidtoken' => 'Nit giltig Token', ); /** Hebrew (עברית) * @author Amire80 * @author Rotemliss * @author YaronSh */ $messages['he'] = array( 'logentry-append' => 'הוספה', 'logentry-parserhook-desc' => 'הרחבת התג הזאת יוצרת טופס להוספה לדפי יומן', 'logentry-specialpage-desc' => 'הרחבת התג הזאת מאפשרת עיבוד להוספת לדפי יומן', 'logentry' => 'שורה ביומן', 'logentry-invalidpage' => 'דף בלתי תקין: $1', 'logentry-invalidtoken' => 'אסימון בלתי תקין', ); /** Upper Sorbian (Hornjoserbsce) * @author Michawiki */ $messages['hsb'] = array( 'logentry-append' => 'Připójsnyć', 'logentry-parserhook-desc' => 'Tute rozšěrjenje staja formular za připójsnjenje teksta resp. započenje z tekstom k protokolowym stronam', 'logentry-specialpage-desc' => 'Tute rozšěrjenje skića předźěłanje za připójsnjenje k protokolowym stronam', 'logentry' => 'Protokolowy zapisk', 'logentry-invalidpage' => 'Njepłaćiwa strona: $1', 'logentry-invalidtoken' => 'Njepłaćiwy token', ); /** Hungarian (Magyar) * @author Dani * @author Glanthor Reviol */ $messages['hu'] = array( 'logentry-append' => 'Hozzáfűzés', 'logentry-parserhook-desc' => 'Ez a kiegészítő lehetővé teszi bejegyzések hozzáfűzését a naplófájlokhoz', 'logentry-specialpage-desc' => 'Ez a kiegészítő feldolgozza a naplófájlokhoz való hozzáfűzéseket', 'logentry' => 'Naplóbejegyzés', 'logentry-invalidpage' => 'Érvénytelen lap', 'logentry-invalidtoken' => 'Érvénytelen token', ); /** Interlingua (Interlingua) * @author McDutchie */ $messages['ia'] = array( 'logentry-append' => 'Adjunger', 'logentry-parserhook-desc' => 'Iste extension adde un etiquetta que provide un formulario pro adjunger/anteponer texto a paginas de registro', 'logentry-specialpage-desc' => 'Iste extension adde un etiquetta que provide de processamento pro adjunger texto a paginas de registro', 'logentry' => 'Entrata in registro', 'logentry-invalidpage' => 'Pagina invalide: $1', 'logentry-invalidtoken' => 'Indicio invalide', ); /** Indonesian (Bahasa Indonesia) * @author Bennylin */ $messages['id'] = array( 'logentry-append' => 'Tambah', 'logentry-parserhook-desc' => 'Pengaya tag ini menyediakan sebuah formulir untuk menambahkan catatan ke halaman log', 'logentry-specialpage-desc' => 'Pengaya tag ini menyediakan proses untuk menambahkan catatan ke halaman log', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Halaman tidak sah', 'logentry-invalidtoken' => 'Token tidak sah', ); /** Italian (Italiano) * @author Darth Kule */ $messages['it'] = array( 'logentry-append' => 'Aggiungi', 'logentry-parserhook-desc' => "Questa estensione tag fornisce un modulo per aggiungere del testo all'inizio o alla fine della pagine dei registri", 'logentry-specialpage-desc' => 'Questa estensione tag fornisce un processo per aggiungere alle pagine dei registri', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Pagina non valida', 'logentry-invalidtoken' => 'Token non valido', ); /** Japanese (日本語) * @author Fryed-peach * @author Schu */ $messages['ja'] = array( 'logentry-append' => '追加', 'logentry-parserhook-desc' => 'このタグ拡張機能はログページの先頭または末尾に項目を追加するフォームを提供します。', 'logentry-specialpage-desc' => 'このタグ拡張機能はログページに項目を追加する処理を提供します。', 'logentry' => 'ログ項目', 'logentry-invalidpage' => '無効なページ: $1', 'logentry-invalidtoken' => '無効な字句', ); /** Khmer (ភាសាខ្មែរ) * @author Thearith */ $messages['km'] = array( 'logentry-invalidpage' => 'ទំព័រ​មិនត្រឹមត្រូវ', ); /** Colognian (Ripoarisch) * @author Purodha */ $messages['ksh'] = array( 'logentry-append' => 'Draanhange', 'logentry-parserhook-desc' => 'Brengk ene Zosatz en et Wiki för e Fommulaa för för un henger Logboochsigge jet aanzehange.', 'logentry-specialpage-desc' => 'Brengk ene Zosatz en et Wiki för aan Logboochsigge jet aanzehange.', 'logentry' => 'Enndraach em Logbooch', 'logentry-invalidpage' => '„$1“ es en onjöltejje Sigg.', 'logentry-invalidtoken' => 'Onjölisch Markzeiche', ); /** Luxembourgish (Lëtzebuergesch) * @author Robby */ $messages['lb'] = array( 'logentry-append' => 'Derbäisetzen', 'logentry' => 'Androung an e Logbuch', 'logentry-invalidpage' => 'Net valabel Säit: $1', ); /** Macedonian (Македонски) * @author Bjankuloski06 */ $messages['mk'] = array( 'logentry-append' => 'Додај', 'logentry-parserhook-desc' => 'Оваа ознака-додаток дава образец за додавање на записи на почетокот или крајот на дневнички страници', 'logentry-specialpage-desc' => 'Оваа ознака-додаток овозможува обработка за придодавање на дневнички страници', 'logentry' => 'СтавкаВоДневникот', 'logentry-invalidpage' => 'Неважечка страница: $1', 'logentry-invalidtoken' => 'Неправилен жетон', ); /** Malay (Bahasa Melayu) * @author Anakmalaysia */ $messages['ms'] = array( 'logentry-append' => 'Lampiran', 'logentry-parserhook-desc' => 'Sambungan tag ini menyediakan borang lampiran pada laman log', 'logentry-specialpage-desc' => 'Sambungan tag ini menyediakan pemprosesan untuk lampiran pada laman log', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Laman tidak sah: $1', 'logentry-invalidtoken' => 'Token tidak sah', ); /** Nahuatl (Nāhuatl) * @author Fluence * @author Ricardo gs */ $messages['nah'] = array( 'logentry-invalidpage' => 'Ahcualli āmatl: $1', ); /** Norwegian (bokmål)‬ (‪Norsk (bokmål)‬) * @author Nghtwlkr */ $messages['nb'] = array( 'logentry-append' => 'Legg til', 'logentry-parserhook-desc' => 'Denne merkelapputvidelsen gir et skjema for å legge til merkelapper før eller etter på loggsider', 'logentry-specialpage-desc' => 'Denne merkelapputvidelsen tilbyr utførelse av å legge til merkelapper på loggsider', 'logentry' => 'Loggelement', 'logentry-invalidpage' => 'Ugyldig side', 'logentry-invalidtoken' => 'Ugyldig symbol', ); /** Dutch (Nederlands) * @author Siebrand */ $messages['nl'] = array( 'logentry-append' => 'Toevoegen', 'logentry-parserhook-desc' => "Deze tagextensie biedt een formulier voor het toevoegen aan/voorvoegen in logboekpagina's", 'logentry-specialpage-desc' => "Deze tagextensie maakt het mogelijk om logboekpagina's toe te voegen", 'logentry' => 'Logboekregel', 'logentry-invalidpage' => 'Ongeldige pagina: $1', 'logentry-invalidtoken' => 'Ongeldig token', ); /** Norwegian Nynorsk (‪Norsk (nynorsk)‬) * @author Harald Khan */ $messages['nn'] = array( 'logentry-append' => 'Legg til', 'logentry-parserhook-desc' => 'Denne merkeutvidinga gjev eit skjema for å leggja til element etter/føre på loggsider', 'logentry-specialpage-desc' => 'Denne merkeutvidinga gjev handsaming for leggja til element på loggsider', 'logentry' => 'Loggelement', 'logentry-invalidpage' => 'Ugyldig sida', 'logentry-invalidtoken' => 'Ugyldig token', ); /** Occitan (Occitan) * @author Cedric31 */ $messages['oc'] = array( 'logentry-append' => 'Apondre', 'logentry-parserhook-desc' => 'Aquesta extension de balisa apond una balisa que provesís un formulari per apondre / prefixar de tèxte a las paginas de jornals', 'logentry-specialpage-desc' => 'Aquesta extension de balisa apond un processús per apondre a las paginas de jornals', 'logentry' => 'Jornal de las entradas', 'logentry-invalidpage' => 'Pagina incorrècta', 'logentry-invalidtoken' => 'Presa incorrècta', ); /** Deitsch (Deitsch) * @author Xqt */ $messages['pdc'] = array( 'logentry-append' => 'Dezu duh', ); /** Polish (Polski) * @author Sp5uhe */ $messages['pl'] = array( 'logentry-append' => 'Dopisz', 'logentry-parserhook-desc' => 'Rozszerzenie dodaje znacznik wstawiający formularz umożliwiający dopisanie treści na początek lub koniec strony logu', 'logentry-specialpage-desc' => 'Rozszerzenie realizuje dodanie wpisu do strony logu', 'logentry' => 'WpisDoLogu', 'logentry-invalidpage' => 'Nieprawidłowa strona $1', 'logentry-invalidtoken' => 'Nieprawidłowy token', ); /** Piedmontese (Piemontèis) * @author Dragonòt */ $messages['pms'] = array( 'logentry-append' => 'Gionta', 'logentry-parserhook-desc' => 'Sta estension-sì dël tag a da na forma për gionté a fin/inissi dle pàgine dij registr', 'logentry-specialpage-desc' => 'Sta estension-sì dël tag a da un process për gionté a le pàgine dij registr', 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Pàgina pa bon-a: $1', 'logentry-invalidtoken' => 'Token pa bon', ); /** Pashto (پښتو) * @author Ahmed-Najib-Biabani-Ibrahimkhel */ $messages['ps'] = array( 'logentry-invalidpage' => 'ناسم مخ', ); /** Portuguese (Português) * @author Hamilton Abreu * @author Malafaya * @author SandroHc */ $messages['pt'] = array( 'logentry-append' => 'Acrescentar', 'logentry-parserhook-desc' => 'Esta extensão de elementos HTML fornece um formulário para acrescentar dados no topo ou fundo das páginas dos registos', 'logentry-specialpage-desc' => 'Esta extensão de elementos HTML fornece um processo para acrescentar dados no fundo das páginas dos registos', 'logentry' => 'Entrada de Registo', 'logentry-invalidpage' => 'Página inválida: $1', 'logentry-invalidtoken' => 'Token inválido', ); /** Brazilian Portuguese (Português do Brasil) * @author Eduardo.mps */ $messages['pt-br'] = array( 'logentry-append' => 'Acrescentar', 'logentry-parserhook-desc' => 'Esta extensão de marca fornece uma forma de acrescentar dados ao início/fim de páginas de registro', 'logentry-specialpage-desc' => 'Esta extensão de marca fornece processamento para acrescentar dados a páginas de registro', 'logentry' => 'Entrada de Registro', 'logentry-invalidpage' => 'Página inválida', 'logentry-invalidtoken' => 'Token inválido', ); /** Romanian (Română) * @author KlaudiuMihaila * @author Minisarm */ $messages['ro'] = array( 'logentry-invalidpage' => 'Pagină nevalidă: $1', ); /** Tarandíne (Tarandíne) * @author Joetaras */ $messages['roa-tara'] = array( 'logentry-append' => 'Mitte in code', 'logentry-parserhook-desc' => "St'enstenzione d'u tag consente 'nu module pe appennere/mettere nnande a le pàggene de le archivije", 'logentry-specialpage-desc' => "St'enstenzione d'u tag consente 'u processe pe appennere a le pàggene de le archivije", 'logentry' => 'LogEntry', 'logentry-invalidpage' => 'Pàgene invalide: $1', 'logentry-invalidtoken' => 'Token invalide', ); /** Russian (Русский) * @author Eleferen * @author Ferrer * @author Александр Сигачёв */ $messages['ru'] = array( 'logentry-append' => 'Добавить', 'logentry-parserhook-desc' => 'Этот тег-расширение предоставляет форму для добавления записей в начало или конец страницы в виде журнала', 'logentry-specialpage-desc' => 'Этот тег-расширение предоставляет механизм добавления на страницу записей в виде журнала', 'logentry' => 'ЗаписьЖурнала', 'logentry-invalidpage' => 'Недопустимая страница: $1', 'logentry-invalidtoken' => 'Неправильный токен', ); /** Slovak (Slovenčina) * @author Helix84 */ $messages['sk'] = array( 'logentry-append' => 'Pridať', 'logentry-parserhook-desc' => 'Toto rozšírenie poskytuje značku formulára na pridávanie k stránkam záznamov', 'logentry-specialpage-desc' => 'Toto rozšírenie poskytuje logiku pridávania k stránkam záznamov', 'logentry' => 'PoložkaZáznamu', 'logentry-invalidpage' => 'Neplatná stránka', 'logentry-invalidtoken' => 'Neplatný token', ); /** Albanian (Shqip) * @author Puntori */ $messages['sq'] = array( 'logentry-invalidpage' => 'Faqe jovalide', ); /** Serbian (Cyrillic script) (‪Српски (ћирилица)‬) * @author Михајло Анђелковић */ $messages['sr-ec'] = array( 'logentry-append' => 'Додај', ); /** Serbian (Latin script) (‪Srpski (latinica)‬) */ $messages['sr-el'] = array( 'logentry-append' => 'Dodaj', ); /** Swedish (Svenska) * @author Fluff * @author Najami * @author Sertion * @author WikiPhoenix */ $messages['sv'] = array( 'logentry-append' => 'Lägg till efter', 'logentry-parserhook-desc' => 'Detta märkestillägget ger ett formulär för att lägga till element före/efter andra element på loggsidor', 'logentry-specialpage-desc' => 'Det här tillägget gör det möjligt att lägga till saker på loggsidor', 'logentry' => 'Loggelement', 'logentry-invalidpage' => 'Ogiltig sida: $1', 'logentry-invalidtoken' => 'Ogiltig typ', ); /** Telugu (తెలుగు) * @author Veeven */ $messages['te'] = array( 'logentry-invalidpage' => 'చెల్లని పుట', ); /** Tagalog (Tagalog) * @author AnakngAraw */ $messages['tl'] = array( 'logentry-append' => 'Idugtong', 'logentry-parserhook-desc' => 'Ang karugtong na tatak na ito ay nagbibigay ng isang pormularyo para sa pagdurugtong sa huli/harap ng mga pahina ng pagtatala', 'logentry-specialpage-desc' => 'Ang karugtong na tatak na ito ay nagbibigay ng pagpoproseso ng pagdurugtong sa mga pahina ng pagtatala', 'logentry' => 'Pagpapasok sa Tala', 'logentry-invalidpage' => 'Hindi tanggap na pahina', 'logentry-invalidtoken' => 'Hindi tanggap na pananda', ); /** Turkish (Türkçe) * @author Vito Genovese */ $messages['tr'] = array( 'logentry' => 'KayıtGirdisi', ); /** Ukrainian (Українська) * @author Тест */ $messages['uk'] = array( 'logentry-append' => 'Додати', ); /** Veps (Vepsän kel') * @author Игорь Бродский */ $messages['vep'] = array( 'logentry-append' => 'Ližata', 'logentry-parserhook-desc' => 'Nece teg-laskend andab forman kirjutuzlehtpolen augotišhe vai lophu ližates (aiglehtesen formas)', 'logentry-specialpage-desc' => 'Nece teg-laskend andab forman kirjutuzlehtpolele ližates (aiglehtesen formas)', 'logentry' => 'AiglehtesenKirjutez', 'logentry-invalidpage' => "Laskmatoi lehtpol': $1", 'logentry-invalidtoken' => 'Vär token', ); /** Vietnamese (Tiếng Việt) * @author Minh Nguyen * @author Vinhtantran */ $messages['vi'] = array( 'logentry-append' => 'Nối', 'logentry-parserhook-desc' => 'Bộ mở rộng thẻ này cung cấp một mẫu đơn để nối/cắt các trang nhật trình', 'logentry-specialpage-desc' => 'Bộ mở rộng thẻ này cung cấp cách xử lý nối các trang nhật trình', 'logentry' => 'Mục nhật trình', 'logentry-invalidpage' => 'Trang không hợp lệ: $1', 'logentry-invalidtoken' => 'Khóa không hợp lệ', ); /** Volapük (Volapük) * @author Smeira */ $messages['vo'] = array( 'logentry-invalidpage' => 'Pad no lonöföl', ); /** Simplified Chinese (‪中文(简体)‬) * @author Bencmq * @author Hydra */ $messages['zh-hans'] = array( 'logentry-append' => '追加', 'logentry' => '日志条目', 'logentry-invalidpage' => '无效页面:$1', 'logentry-invalidtoken' => '无效的标记', ); /** Traditional Chinese (‪中文(繁體)‬) * @author Mark85296341 */ $messages['zh-hant'] = array( 'logentry-append' => '追加', 'logentry' => '日誌條目', 'logentry-invalidpage' => '無效頁面:$1', 'logentry-invalidtoken' => '無效的標記', );
SuriyaaKudoIsc/wikia-app-test
extensions/LogEntry/LogEntry.i18n.php
PHP
gpl-2.0
25,652
// FileZillaEngine.cpp: Implementierung der Klasse CFileZillaEngine. // ////////////////////////////////////////////////////////////////////// #include <filezilla.h> #include "ControlSocket.h" #include "directorycache.h" #include "engineprivate.h" CFileZillaEngine::CFileZillaEngine(CFileZillaEngineContext& engine_context) : impl_(new CFileZillaEnginePrivate(engine_context, *this)) { } CFileZillaEngine::~CFileZillaEngine() { delete impl_; } int CFileZillaEngine::Init(wxEvtHandler *pEventHandler) { return impl_->Init(pEventHandler); } int CFileZillaEngine::Execute(const CCommand &command) { return impl_->Execute(command); } std::unique_ptr<CNotification> CFileZillaEngine::GetNextNotification() { return impl_->GetNextNotification(); } bool CFileZillaEngine::SetAsyncRequestReply(std::unique_ptr<CAsyncRequestNotification> && pNotification) { return impl_->SetAsyncRequestReply(std::move(pNotification)); } bool CFileZillaEngine::IsPendingAsyncRequestReply(std::unique_ptr<CAsyncRequestNotification> const& pNotification) { return impl_->IsPendingAsyncRequestReply(pNotification); } bool CFileZillaEngine::IsActive(enum CFileZillaEngine::_direction direction) { return CFileZillaEnginePrivate::IsActive(direction); } CTransferStatus CFileZillaEngine::GetTransferStatus(bool &changed) { return impl_->GetTransferStatus(changed); } int CFileZillaEngine::CacheLookup(const CServerPath& path, CDirectoryListing& listing) { return impl_->CacheLookup(path, listing); } int CFileZillaEngine::Cancel() { return impl_->Cancel(); } bool CFileZillaEngine::IsBusy() const { return impl_->IsBusy(); } bool CFileZillaEngine::IsConnected() const { return impl_->IsConnected(); }
oneminot/filezilla3
src/engine/FileZillaEngine.cpp
C++
gpl-2.0
1,697
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.motorola.studio.android.adt; import org.eclipse.ui.IStartup; import com.android.ddmlib.AndroidDebugBridge; import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener; import com.android.ddmlib.IDevice; import com.android.ddmlib.IDevice.DeviceState; /** * DESCRIPTION: * The device change listener to be used by the whole MOTODEV Studio for Android * tool. Other plugins should not register listeners in DDMS. Instead, use * DDMSFacade * * RESPONSIBILITY: * Delegate the deviceConnected and deviceDisconnected events to the registered * runnables * * COLABORATORS: * None. * * USAGE: * This class shall be used by DDMS and DDMSFacade only */ public class StudioDeviceChangeListener implements IDeviceChangeListener, IStartup { /* * (non-Javadoc) * @see org.eclipse.ui.IStartup#earlyStartup() */ public void earlyStartup() { // Adding the listener in the early startup to guarantee that we will receive // events for the devices that were already online before starting the workbench AndroidDebugBridge.addDeviceChangeListener(this); } /* * (non-Javadoc) * @see com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener#deviceChanged(com.android.ddmlib.Device, int) */ public void deviceChanged(IDevice device, int i) { if (i == IDevice.CHANGE_STATE) { // a handset should only be instantiated when its state change from OFFLINE to ONLINE // to avoid the problem of a remote device on the OFFLINE state be presented as an ONLINE handset if ((device.getState() == DeviceState.ONLINE) && (!device.isEmulator())) { DDMSFacade.deviceConnected(device); } DDMSFacade.deviceStatusChanged(device); } } /* * (non-Javadoc) * @see com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener#deviceConnected(com.android.ddmlib.Device) */ public void deviceConnected(IDevice device) { // handsets should not be instantiated right after connection because at that time // they appear on the OFFLINE state if (device.isEmulator()) { DDMSFacade.deviceConnected(device); } } /* * (non-Javadoc) * @see com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener#deviceDisconnected(com.android.ddmlib.Device) */ public void deviceDisconnected(IDevice device) { DDMSFacade.deviceDisconnected(device); } }
rex-xxx/mt6572_x201
tools/motodev/src/plugins/android/src/com/motorola/studio/android/adt/StudioDeviceChangeListener.java
Java
gpl-2.0
3,177
<?php // compatibility // no direct access defined( '_VALID_MOS' ) or die( 'Restricted access' ); require_once( dirname( __FILE__ ) . '/joomla.php' ); ?>
kikine/LC78
includes/mambo.php
PHP
gpl-2.0
155
using Server.Spells.Third; namespace Server.Items { public class FireballWand : BaseWand { [Constructable] public FireballWand() : base(WandEffect.Fireball, 5, 109) { } public FireballWand(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } public override void OnWandUse(Mobile from) { Cast(new FireballSpell(from, this)); } } }
ServUO/ServUO
Scripts/Items/Equipment/Weapons/FireballWand.cs
C#
gpl-2.0
769
/* * Copyright (C) 2010-2013 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2010-2013 Oregon <http://www.oregoncore.com/> * Copyright (C) 2006-2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Lorekeeper_Polkelt SD%Complete: 100 SDComment: SDCategory: Scholomance EndScriptData */ #include "ScriptPCH.h" #include "scholomance.h" #define SPELL_VOLATILEINFECTION 24928 #define SPELL_DARKPLAGUE 18270 #define SPELL_CORROSIVEACID 23313 #define SPELL_NOXIOUSCATALYST 18151 struct boss_lorekeeperpolkeltAI : public ScriptedAI { boss_lorekeeperpolkeltAI(Creature *c) : ScriptedAI(c) {} uint32 VolatileInfection_Timer; uint32 Darkplague_Timer; uint32 CorrosiveAcid_Timer; uint32 NoxiousCatalyst_Timer; void Reset() { VolatileInfection_Timer = 38000; Darkplague_Timer = 8000; CorrosiveAcid_Timer = 45000; NoxiousCatalyst_Timer = 35000; } void JustDied(Unit * /*killer*/) { ScriptedInstance *instance = me->GetInstanceScript(); if (instance) { instance->SetData(DATA_LOREKEEPERPOLKELT_DEATH, 0); if (instance->GetData(TYPE_GANDLING) == IN_PROGRESS) me->SummonCreature(1853, 180.73f, -9.43856f, 75.507f, 1.61399f, TEMPSUMMON_DEAD_DESPAWN, 0); } } void EnterCombat(Unit * /*who*/) { } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //VolatileInfection_Timer if (VolatileInfection_Timer <= diff) { DoCast(me->getVictim(), SPELL_VOLATILEINFECTION); VolatileInfection_Timer = 32000; } else VolatileInfection_Timer -= diff; //Darkplague_Timer if (Darkplague_Timer <= diff) { DoCast(me->getVictim(), SPELL_DARKPLAGUE); Darkplague_Timer = 8000; } else Darkplague_Timer -= diff; //CorrosiveAcid_Timer if (CorrosiveAcid_Timer <= diff) { DoCast(me->getVictim(), SPELL_CORROSIVEACID); CorrosiveAcid_Timer = 25000; } else CorrosiveAcid_Timer -= diff; //NoxiousCatalyst_Timer if (NoxiousCatalyst_Timer <= diff) { DoCast(me->getVictim(), SPELL_NOXIOUSCATALYST); NoxiousCatalyst_Timer = 38000; } else NoxiousCatalyst_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_lorekeeperpolkelt(Creature* creature) { return new boss_lorekeeperpolkeltAI (creature); } void AddSC_boss_lorekeeperpolkelt() { Script *newscript; newscript = new Script; newscript->Name = "boss_lorekeeper_polkelt"; newscript->GetAI = &GetAI_boss_lorekeeperpolkelt; newscript->RegisterSelf(); }
SkyFireArchives/SkyFire_one
src/server/scripts/EasternKingdoms/Scholomance/boss_lorekeeper_polkelt.cpp
C++
gpl-2.0
3,544
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Authors: * - Red Hat Pune libc-alpha@sourceware.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'L' => 'D/M/YY', ], 'months' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रेल', 'मई', 'जुन', 'जुलाई', 'अगस्त', 'सितम्बर', 'अखथबर', 'नवम्बर', 'दिसम्बर'], 'months_short' => ['जनवरी', 'फरवरी', 'मार्च', 'अप्रेल', 'मई', 'जुन', 'जुलाई', 'अगस्त', 'सितम्बर', 'अखथबर', 'नवम्बर', 'दिसम्बर'], 'weekdays' => ['सिंगेमाँहाँ', 'ओतेमाँहाँ', 'बालेमाँहाँ', 'सागुनमाँहाँ', 'सारदीमाँहाँ', 'जारुममाँहाँ', 'ञुहुममाँहाँ'], 'weekdays_short' => ['सिंगे', 'ओते', 'बाले', 'सागुन', 'सारदी', 'जारुम', 'ञुहुम'], 'weekdays_min' => ['सिंगे', 'ओते', 'बाले', 'सागुन', 'सारदी', 'जारुम', 'ञुहुम'], 'day_of_first_week_of_year' => 1, 'month' => ':count ńindạ cando', // less reliable 'm' => ':count ńindạ cando', // less reliable 'a_month' => ':count ńindạ cando', // less reliable 'week' => ':count mãhã', // less reliable 'w' => ':count mãhã', // less reliable 'a_week' => ':count mãhã', // less reliable 'hour' => ':count ᱥᱳᱱᱚ', // less reliable 'h' => ':count ᱥᱳᱱᱚ', // less reliable 'a_hour' => ':count ᱥᱳᱱᱚ', // less reliable 'minute' => ':count ᱯᱤᱞᱪᱩ', // less reliable 'min' => ':count ᱯᱤᱞᱪᱩ', // less reliable 'a_minute' => ':count ᱯᱤᱞᱪᱩ', // less reliable 'second' => ':count ar', // less reliable 's' => ':count ar', // less reliable 'a_second' => ':count ar', // less reliable 'year' => ':count ne̲s', 'y' => ':count ne̲s', 'a_year' => ':count ne̲s', 'day' => ':count ᱫᱤᱱ', 'd' => ':count ᱫᱤᱱ', 'a_day' => ':count ᱫᱤᱱ', ]);
matrix-msu/kora
vendor/nesbot/carbon/src/Carbon/Lang/sat_IN.php
PHP
gpl-2.0
2,504
<?php /** * Admin Notices Class * * @package EDD * @subpackage Admin/Notices * @copyright Copyright (c) 2015, Pippin Williamson * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 2.3 */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) exit; /** * EDD_Notices Class * * @since 2.3 */ class EDD_Notices { /** * Get things started * * @since 2.3 */ public function __construct() { add_action( 'admin_notices', array( $this, 'show_notices' ) ); add_action( 'edd_dismiss_notices', array( $this, 'dismiss_notices' ) ); } /** * Show relevant notices * * @since 2.3 */ public function show_notices() { $notices = array( 'updated' => array(), 'error' => array(), ); // Global (non-action-based) messages if ( ( edd_get_option( 'purchase_page', '' ) == '' || 'trash' == get_post_status( edd_get_option( 'purchase_page', '' ) ) ) && current_user_can( 'edit_pages' ) && ! get_user_meta( get_current_user_id(), '_edd_set_checkout_dismissed' ) ) { ob_start(); ?> <div class="error"> <p><?php printf( __( 'No checkout page has been configured. Visit <a href="%s">Settings</a> to set one.', 'easy-digital-downloads' ), admin_url( 'edit.php?post_type=download&page=edd-settings' ) ); ?></p> <p><a href="<?php echo add_query_arg( array( 'edd_action' => 'dismiss_notices', 'edd_notice' => 'set_checkout' ) ); ?>"><?php _e( 'Dismiss Notice', 'easy-digital-downloads' ); ?></a></p> </div> <?php echo ob_get_clean(); } if ( isset( $_GET['page'] ) && 'edd-payment-history' == $_GET['page'] && current_user_can( 'view_shop_reports' ) && edd_is_test_mode() ) { $notices['updated']['edd-payment-history-test-mode'] = sprintf( __( 'Note: Test Mode is enabled, only test payments are shown below. <a href="%s">Settings</a>.', 'easy-digital-downloads' ), admin_url( 'edit.php?post_type=download&page=edd-settings' ) ); } if( stristr( $_SERVER['SERVER_SOFTWARE'], 'nginx' ) && ! get_user_meta( get_current_user_id(), '_edd_nginx_redirect_dismissed', true ) && current_user_can( 'manage_shop_settings' ) ) { ob_start(); ?> <div class="error"> <p><?php printf( __( 'The download files in %s are not currently protected due to your site running on NGINX.', 'easy-digital-downloads' ), '<strong>' . edd_get_upload_dir() . '</strong>' ); ?></p> <p><?php _e( 'To protect them, you must add a redirect rule as explained in <a href="http://docs.easydigitaldownloads.com/article/682-protected-download-files-on-nginx">this guide</a>.', 'easy-digital-downloads' ); ?></p> <p><?php _e( 'If you have already added the redirect rule, you may safely dismiss this notice', 'easy-digital-downloads' ); ?></p> <p><a href="<?php echo add_query_arg( array( 'edd_action' => 'dismiss_notices', 'edd_notice' => 'nginx_redirect' ) ); ?>"><?php _e( 'Dismiss Notice', 'easy-digital-downloads' ); ?></a></p> </div> <?php echo ob_get_clean(); } if( ! edd_htaccess_exists() && ! get_user_meta( get_current_user_id(), '_edd_htaccess_missing_dismissed', true ) && current_user_can( 'manage_shop_settings' ) ) { if( ! stristr( $_SERVER['SERVER_SOFTWARE'], 'apache' ) ) { return; // Bail if we aren't using Apache... nginx doesn't use htaccess! } ob_start(); ?> <div class="error"> <p><?php printf( __( 'The Easy Digital Downloads .htaccess file is missing from %s!', 'easy-digital-downloads' ), '<strong>' . edd_get_upload_dir() . '</strong>' ); ?></p> <p><?php printf( __( 'First, please resave the Misc settings tab a few times. If this warning continues to appear, create a file called ".htaccess" in the %s directory, and copy the following into it:', 'easy-digital-downloads' ), '<strong>' . edd_get_upload_dir() . '</strong>' ); ?></p> <p><pre><?php echo edd_get_htaccess_rules(); ?></pre></p> <p><a href="<?php echo add_query_arg( array( 'edd_action' => 'dismiss_notices', 'edd_notice' => 'htaccess_missing' ) ); ?>"><?php _e( 'Dismiss Notice', 'easy-digital-downloads' ); ?></a></p> </div> <?php echo ob_get_clean(); } if ( class_exists( 'EDD_Recount_Earnings' ) && current_user_can( 'manage_shop_settings' ) ) { ob_start(); ?> <div class="error"> <p><?php printf( __( 'Easy Digital Downloads 2.5 contains a <a href="%s">built in recount tool</a>. Please <a href="%s">deactivate the Easy Digital Downloads - Recount Earnings plugin</a>', 'easy-digital-downloads' ), admin_url( 'edit.php?post_type=download&page=edd-tools&tab=general' ), admin_url( 'plugins.php' ) ); ?></p> </div> <?php echo ob_get_clean(); } /* Commented out per https://github.com/easydigitaldownloads/Easy-Digital-Downloads/issues/3475 if( ! edd_test_ajax_works() && ! get_user_meta( get_current_user_id(), '_edd_admin_ajax_inaccessible_dismissed', true ) && current_user_can( 'manage_shop_settings' ) ) { echo '<div class="error">'; echo '<p>' . __( 'Your site appears to be blocking the WordPress ajax interface. This may causes issues with your store.', 'easy-digital-downloads' ) . '</p>'; echo '<p>' . sprintf( __( 'Please see <a href="%s" target="_blank">this reference</a> for possible solutions.', 'easy-digital-downloads' ), 'https://easydigitaldownloads.com/docs/admin-ajax-blocked' ) . '</p>'; echo '<p><a href="' . add_query_arg( array( 'edd_action' => 'dismiss_notices', 'edd_notice' => 'admin_ajax_inaccessible' ) ) . '">' . __( 'Dismiss Notice', 'easy-digital-downloads' ) . '</a></p>'; echo '</div>'; } */ if ( isset( $_GET['edd-message'] ) ) { // Shop discounts errors if( current_user_can( 'manage_shop_discounts' ) ) { switch( $_GET['edd-message'] ) { case 'discount_added' : $notices['updated']['edd-discount-added'] = __( 'Discount code added.', 'easy-digital-downloads' ); break; case 'discount_add_failed' : $notices['error']['edd-discount-add-fail'] = __( 'There was a problem adding your discount code, please try again.', 'easy-digital-downloads' ); break; case 'discount_exists' : $notices['error']['edd-discount-exists'] = __( 'A discount with that code already exists, please use a different code.', 'easy-digital-downloads' ); break; case 'discount_updated' : $notices['updated']['edd-discount-updated'] = __( 'Discount code updated.', 'easy-digital-downloads' ); break; case 'discount_update_failed' : $notices['error']['edd-discount-updated-fail'] = __( 'There was a problem updating your discount code, please try again.', 'easy-digital-downloads' ); break; } } // Shop reports errors if( current_user_can( 'view_shop_reports' ) ) { switch( $_GET['edd-message'] ) { case 'payment_deleted' : $notices['updated']['edd-payment-deleted'] = __( 'The payment has been deleted.', 'easy-digital-downloads' ); break; case 'email_sent' : $notices['updated']['edd-payment-sent'] = __( 'The purchase receipt has been resent.', 'easy-digital-downloads' ); break; case 'payment-note-deleted' : $notices['updated']['edd-payment-note-deleted'] = __( 'The payment note has been deleted.', 'easy-digital-downloads' ); break; } } // Shop settings errors if( current_user_can( 'manage_shop_settings' ) ) { switch( $_GET['edd-message'] ) { case 'settings-imported' : $notices['updated']['edd-settings-imported'] = __( 'The settings have been imported.', 'easy-digital-downloads' ); break; case 'api-key-generated' : $notices['updated']['edd-api-key-generated'] = __( 'API keys successfully generated.', 'easy-digital-downloads' ); break; case 'api-key-exists' : $notices['error']['edd-api-key-exists'] = __( 'The specified user already has API keys.', 'easy-digital-downloads' ); break; case 'api-key-regenerated' : $notices['updated']['edd-api-key-regenerated'] = __( 'API keys successfully regenerated.', 'easy-digital-downloads' ); break; case 'api-key-revoked' : $notices['updated']['edd-api-key-revoked'] = __( 'API keys successfully revoked.', 'easy-digital-downloads' ); break; } } // Shop payments errors if( current_user_can( 'edit_shop_payments' ) ) { switch( $_GET['edd-message'] ) { case 'note-added' : $notices['updated']['edd-note-added'] = __( 'The payment note has been added successfully.', 'easy-digital-downloads' ); break; case 'payment-updated' : $notices['updated']['edd-payment-updated'] = __( 'The payment has been successfully updated.', 'easy-digital-downloads' ); break; } } // Customer Notices if ( current_user_can( 'edit_shop_payments' ) ) { switch( $_GET['edd-message'] ) { case 'customer-deleted' : $notices['updated']['edd-customer-deleted'] = __( 'Customer successfully deleted', 'easy-digital-downloads' ); break; case 'user-verified' : $notices['updated']['edd-user-verified'] = __( 'User successfully verified', 'easy-digital-downloads' ); break; } } } if ( count( $notices['updated'] ) > 0 ) { foreach( $notices['updated'] as $notice => $message ) { add_settings_error( 'edd-notices', $notice, $message, 'updated' ); } } if ( count( $notices['error'] ) > 0 ) { foreach( $notices['error'] as $notice => $message ) { add_settings_error( 'edd-notices', $notice, $message, 'error' ); } } settings_errors( 'edd-notices' ); } /** * Dismiss admin notices when Dismiss links are clicked * * @since 2.3 * @return void */ function dismiss_notices() { if( isset( $_GET['edd_notice'] ) ) { update_user_meta( get_current_user_id(), '_edd_' . $_GET['edd_notice'] . '_dismissed', 1 ); wp_redirect( remove_query_arg( array( 'edd_action', 'edd_notice' ) ) ); exit; } } } new EDD_Notices;
jcnh74/Wordpress
wp-content/plugins/easy-digital-downloads/includes/admin/class-edd-notices.php
PHP
gpl-2.0
9,882
<?php $data = elgg_extract("data", $vars); $header = elgg_extract("header", $vars); if (!$header) { $header = elgg_echo('developers:inspect:events'); } if (empty($data)) { return; } $make_id = function ($name) { return "z" . md5($name); }; echo "<table class='elgg-table-alt'>"; echo "<tr>"; echo "<th>$header</th>"; echo "<th>" . elgg_echo('developers:inspect:priority') . "</th>"; echo "<th>" . elgg_echo('developers:inspect:functions') . "</th>"; echo "</tr>"; $last_key = ''; foreach ($data as $key => $arr) { foreach ($arr as $value) { list($priority, $desc) = explode(': ', $value, 2); echo "<tr>"; if ($key !== $last_key) { $id = $make_id($key); echo "<td id='$id' rowspan='" . count($arr) . "'>$key</td>"; $last_key = $key; } echo "<td>$priority</td>"; echo "<td>$desc</td>"; echo "</tr>"; } } echo "</table>";
mrclay/Elgg-leaf
mod/developers/views/default/admin/develop_tools/inspect/events.php
PHP
gpl-2.0
854
=begin = $RCSfile: ssl.rb,v $ -- Ruby-space definitions that completes C-space funcs for SSL = Info 'OpenSSL for Ruby 2' project Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org> All rights reserved. = Licence This program is licenced under the same licence as Ruby. (See the file 'LICENCE'.) = Version $Id: ssl.rb,v 1.5.2.6 2006/05/23 18:14:05 gotoyuzo Exp $ =end require "openssl" require "openssl/buffering" require "fcntl" module OpenSSL module SSL module SocketForwarder def addr to_io.addr end def peeraddr to_io.peeraddr end def setsockopt(level, optname, optval) to_io.setsockopt(level, optname, optval) end def getsockopt(level, optname) to_io.getsockopt(level, optname) end def fcntl(*args) to_io.fcntl(*args) end def closed? to_io.closed? end def do_not_reverse_lookup=(flag) to_io.do_not_reverse_lookup = flag end end module Nonblock def initialize(*args) flag = File::NONBLOCK flag |= @io.fcntl(Fcntl::F_GETFL, nil) if defined?(Fcntl::F_GETFL) @io.fcntl(Fcntl::F_SETFL, flag) super end end class SSLSocket include Buffering include SocketForwarder include Nonblock def post_connection_check(hostname) check_common_name = true cert = peer_cert cert.extensions.each{|ext| next if ext.oid != "subjectAltName" ext.value.split(/,\s+/).each{|general_name| if /\ADNS:(.*)/ =~ general_name check_common_name = false reg = Regexp.escape($1).gsub(/\\\*/, "[^.]+") return true if /\A#{reg}\z/i =~ hostname elsif /\AIP Address:(.*)/ =~ general_name check_common_name = false return true if $1 == hostname end } } if check_common_name cert.subject.to_a.each{|oid, value| if oid == "CN" reg = Regexp.escape(value).gsub(/\\\*/, "[^.]+") return true if /\A#{reg}\z/i =~ hostname end } end raise SSLError, "hostname not match" end end class SSLServer include SocketForwarder attr_accessor :start_immediately def initialize(svr, ctx) @svr = svr @ctx = ctx unless ctx.session_id_context session_id = OpenSSL::Digest::MD5.hexdigest($0) @ctx.session_id_context = session_id end @start_immediately = true end def to_io @svr end def listen(backlog=5) @svr.listen(backlog) end def accept sock = @svr.accept begin ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx) ssl.sync_close = true ssl.accept if @start_immediately ssl rescue SSLError => ex sock.close raise ex end end def close @svr.close end end end end
Dreyerized/bananascrum
vendor/gems/jruby-openssl-0.5.2/lib/openssl/ssl.rb
Ruby
gpl-2.0
3,093
<?php class DumpBinaryCountMetric extends ApiAnalyticsBase { public function getAllowedFilters() { return array( 'selectprojects', 'selectwikis', ); } protected function getQueryInfo() { return array( 'table' => array( 'binaries' ), 'conds' => array(), 'options' => array( 'GROUP BY' => 'date', ), 'join_conds' => array(), ); } protected function getQueryFields() { return array(); } public function getDescription() { return 'All binary files (nearly all of which are multimedia files) available for download/article inclusion on a wiki'; } public function getExamples() { return array( 'api.php?action=analytics&metric=dumpbinarycount', ); } public function getVersion() { return __CLASS__ . ': $Id: DumpBinaryCountMetric.php 91574 2011-07-06 18:09:34Z reedy $'; } }
SuriyaaKudoIsc/wikia-app-test
extensions/MetricsReporting/metrics/DumpBinaryCountMetric.php
PHP
gpl-2.0
827
<?php /** * Joomla! Content Management System * * @copyright (C) 2005 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\Toolbar; \defined('_JEXEC') or die; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\CMS\Layout\FileLayout; use Joomla\CMS\Table\Table; use Joomla\CMS\Uri\Uri; /** * Utility class for the button bar. * * @since 1.5 */ abstract class ToolbarHelper { /** * Title cell. * For the title and toolbar to be rendered correctly, * this title function must be called before the starttable function and the toolbars icons * this is due to the nature of how the css has been used to position the title in respect to the toolbar. * * @param string $title The title. * @param string $icon The space-separated names of the image. * * @return void * * @since 1.5 */ public static function title($title, $icon = 'generic.png') { $layout = new FileLayout('joomla.toolbar.title'); $html = $layout->render(array('title' => $title, 'icon' => $icon)); $app = Factory::getApplication(); $app->JComponentTitle = $html; $title = strip_tags($title) . ' - ' . $app->get('sitename'); if ($app->isClient('administrator')) { $title .= ' - ' . Text::_('JADMINISTRATION'); } Factory::getDocument()->setTitle($title); } /** * Writes a spacer cell. * * @param string $width The width for the cell * * @return void * * @since 1.5 */ public static function spacer($width = '') { $bar = Toolbar::getInstance('toolbar'); // Add a spacer. $bar->appendButton('Separator', 'spacer', $width); } /** * Writes a divider between menu buttons * * @return void * * @since 1.5 */ public static function divider() { $bar = Toolbar::getInstance('toolbar'); // Add a divider. $bar->appendButton('Separator', 'divider'); } /** * Writes a custom option and task button for the button bar. * * @param string $task The task to perform (picked up by the switch($task) blocks). * @param string $icon The image to display. * @param string $iconOver @deprecated 5.0 * @param string $alt The alt text for the icon image. * @param bool $listSelect True if required to check that a standard list item is checked. * @param string $formId The id of action form. * * @return void * * @since 1.5 */ public static function custom($task = '', $icon = '', $iconOver = '', $alt = '', $listSelect = true, $formId = null) { $bar = Toolbar::getInstance('toolbar'); // Strip extension. $icon = preg_replace('#\.[^.]*$#', '', $icon); // Add a standard button. $bar->appendButton('Standard', $icon, $alt, $task, $listSelect, $formId); } /** * Writes a preview button for a given option (opens a popup window). * * @param string $url The name of the popup file (excluding the file extension) * @param bool $updateEditors Unused * @param string $icon The image to display. * @param integer $bodyHeight The body height of the preview popup * @param integer $modalWidth The modal width of the preview popup * * @return void * * @since 1.5 */ public static function preview($url = '', $updateEditors = false, $icon = 'preview', $bodyHeight = null, $modalWidth = null) { $bar = Toolbar::getInstance('toolbar'); // Add a preview button. $bar->appendButton('Popup', $icon, 'Preview', $url . '&task=preview', 640, 480, $bodyHeight, $modalWidth); } /** * Writes a help button for a given option (opens a popup window). * * @param string $ref The name of the popup file (excluding the file extension for an xml file). * @param bool $com Use the help file in the component directory. * @param string $override Use this URL instead of any other * @param string $component Name of component to get Help (null for current component) * * @return void * * @since 1.5 */ public static function help($ref, $com = false, $override = null, $component = null) { $bar = Toolbar::getInstance('toolbar'); // Add a help button. $bar->appendButton('Help', $ref, $com, $override, $component); } /** * Writes a cancel button that will go back to the previous page without doing * any other operation. * * @param string $alt Alternative text. * @param string $href URL of the href attribute. * * @return void * * @since 1.5 */ public static function back($alt = 'JTOOLBAR_BACK', $href = 'javascript:history.back();') { $bar = Toolbar::getInstance('toolbar'); // Add a back button. $arrow = Factory::getLanguage()->isRtl() ? 'arrow-right' : 'arrow-left'; $bar->appendButton('Link', $arrow, $alt, $href); } /** * Creates a button to redirect to a link * * @param string $url The link url * @param string $text Button text * @param string $name Name to be used as apart of the id * * @return void * * @since 3.5 */ public static function link($url, $text, $name = 'link') { $bar = Toolbar::getInstance('toolbar'); $bar->appendButton('Link', $name, $text, $url); } /** * Writes a media_manager button. * * @param string $directory The subdirectory to upload the media to. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function media_manager($directory = '', $alt = 'JTOOLBAR_UPLOAD') { $bar = Toolbar::getInstance('toolbar'); // Add an upload button. $bar->appendButton('Popup', 'upload', $alt, 'index.php?option=com_media&tmpl=component&task=popupUpload&folder=' . $directory, 800, 520); } /** * Writes a common 'default' button for a record. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function makeDefault($task = 'default', $alt = 'JTOOLBAR_DEFAULT') { $bar = Toolbar::getInstance('toolbar'); // Add a default button. $bar->appendButton('Standard', 'default', $alt, $task, true); } /** * Writes a common 'assign' button for a record. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function assign($task = 'assign', $alt = 'JTOOLBAR_ASSIGN') { $bar = Toolbar::getInstance('toolbar'); // Add an assign button. $bar->appendButton('Standard', 'assign', $alt, $task, true); } /** * Writes the common 'new' icon for the button bar. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * @param boolean $check True if required to check that a standard list item is checked. * * @return void * * @since 1.5 */ public static function addNew($task = 'add', $alt = 'JTOOLBAR_NEW', $check = false) { $bar = Toolbar::getInstance('toolbar'); // Add a new button. $bar->appendButton('Standard', 'new', $alt, $task, $check); } /** * Writes a common 'publish' button. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * @param boolean $check True if required to check that a standard list item is checked. * * @return void * * @since 1.5 */ public static function publish($task = 'publish', $alt = 'JTOOLBAR_PUBLISH', $check = false) { $bar = Toolbar::getInstance('toolbar'); // Add a publish button. $bar->appendButton('Standard', 'publish', $alt, $task, $check); } /** * Writes a common 'publish' button for a list of records. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function publishList($task = 'publish', $alt = 'JTOOLBAR_PUBLISH') { $bar = Toolbar::getInstance('toolbar'); // Add a publish button (list). $bar->appendButton('Standard', 'publish', $alt, $task, true); } /** * Writes a common 'unpublish' button. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * @param boolean $check True if required to check that a standard list item is checked. * * @return void * * @since 1.5 */ public static function unpublish($task = 'unpublish', $alt = 'JTOOLBAR_UNPUBLISH', $check = false) { $bar = Toolbar::getInstance('toolbar'); // Add an unpublish button $bar->appendButton('Standard', 'unpublish', $alt, $task, $check); } /** * Writes a common 'unpublish' button for a list of records. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function unpublishList($task = 'unpublish', $alt = 'JTOOLBAR_UNPUBLISH') { $bar = Toolbar::getInstance('toolbar'); // Add an unpublish button (list). $bar->appendButton('Standard', 'unpublish', $alt, $task, true); } /** * Writes a common 'archive' button for a list of records. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function archiveList($task = 'archive', $alt = 'JTOOLBAR_ARCHIVE') { $bar = Toolbar::getInstance('toolbar'); // Add an archive button. $bar->appendButton('Standard', 'archive', $alt, $task, true); } /** * Writes an unarchive button for a list of records. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function unarchiveList($task = 'unarchive', $alt = 'JTOOLBAR_UNARCHIVE') { $bar = Toolbar::getInstance('toolbar'); // Add an unarchive button (list). $bar->appendButton('Standard', 'unarchive', $alt, $task, true); } /** * Writes a common 'edit' button for a list of records. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function editList($task = 'edit', $alt = 'JTOOLBAR_EDIT') { $bar = Toolbar::getInstance('toolbar'); // Add an edit button. $bar->appendButton('Standard', 'edit', $alt, $task, true); } /** * Writes a common 'edit' button for a template html. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function editHtml($task = 'edit_source', $alt = 'JTOOLBAR_EDIT_HTML') { $bar = Toolbar::getInstance('toolbar'); // Add an edit html button. $bar->appendButton('Standard', 'edithtml', $alt, $task, true); } /** * Writes a common 'edit' button for a template css. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function editCss($task = 'edit_css', $alt = 'JTOOLBAR_EDIT_CSS') { $bar = Toolbar::getInstance('toolbar'); // Add an edit css button (hide). $bar->appendButton('Standard', 'editcss', $alt, $task, true); } /** * Writes a common 'delete' button for a list of records. * * @param string $msg Postscript for the 'are you sure' message. * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function deleteList($msg = '', $task = 'remove', $alt = 'JTOOLBAR_DELETE') { $bar = Toolbar::getInstance('toolbar'); // Add a delete button. if ($msg) { $bar->appendButton('Confirm', $msg, 'delete', $alt, $task, true); } else { $bar->appendButton('Standard', 'delete', $alt, $task, true); } } /** * Writes a common 'trash' button for a list of records. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * @param bool $check True to allow lists. * * @return void * * @since 1.5 */ public static function trash($task = 'remove', $alt = 'JTOOLBAR_TRASH', $check = true) { $bar = Toolbar::getInstance('toolbar'); // Add a trash button. $bar->appendButton('Standard', 'trash', $alt, $task, $check, false); } /** * Writes a save button for a given option. * Apply operation leads to a save action only (does not leave edit mode). * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function apply($task = 'apply', $alt = 'JTOOLBAR_APPLY') { $bar = Toolbar::getInstance('toolbar'); // Add an apply button $bar->apply($task, $alt); } /** * Writes a save button for a given option. * Save operation leads to a save and then close action. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function save($task = 'save', $alt = 'JTOOLBAR_SAVE') { $bar = Toolbar::getInstance('toolbar'); // Add a save button. $bar->save($task, $alt); } /** * Writes a save and create new button for a given option. * Save and create operation leads to a save and then add action. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.6 */ public static function save2new($task = 'save2new', $alt = 'JTOOLBAR_SAVE_AND_NEW') { $bar = Toolbar::getInstance('toolbar'); // Add a save and create new button. $bar->save2new($task, $alt); } /** * Writes a save as copy button for a given option. * Save as copy operation leads to a save after clearing the key, * then returns user to edit mode with new key. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.6 */ public static function save2copy($task = 'save2copy', $alt = 'JTOOLBAR_SAVE_AS_COPY') { $bar = Toolbar::getInstance('toolbar'); // Add a save and create new button. $bar->save2copy($task, $alt); } /** * Writes a checkin button for a given option. * * @param string $task An override for the task. * @param string $alt An override for the alt text. * @param boolean $check True if required to check that a standard list item is checked. * * @return void * * @since 1.7 */ public static function checkin($task = 'checkin', $alt = 'JTOOLBAR_CHECKIN', $check = true) { $bar = Toolbar::getInstance('toolbar'); // Add a save and create new button. $bar->appendButton('Standard', 'checkin', $alt, $task, $check); } /** * Writes a cancel button and invokes a cancel operation (eg a checkin). * * @param string $task An override for the task. * @param string $alt An override for the alt text. * * @return void * * @since 1.5 */ public static function cancel($task = 'cancel', $alt = 'JTOOLBAR_CANCEL') { $bar = Toolbar::getInstance('toolbar'); // Add a cancel button. $bar->appendButton('Standard', 'cancel', $alt, $task, false); } /** * Writes a configuration button and invokes a cancel operation (eg a checkin). * * @param string $component The name of the component, eg, com_content. * @param integer $height The height of the popup. [UNUSED] * @param integer $width The width of the popup. [UNUSED] * @param string $alt The name of the button. * @param string $path An alternative path for the configuration xml relative to JPATH_SITE. * * @return void * * @since 1.5 */ public static function preferences($component, $height = 550, $width = 875, $alt = 'JTOOLBAR_OPTIONS', $path = '') { $component = urlencode($component); $path = urlencode($path); $bar = Toolbar::getInstance('toolbar'); $uri = (string) Uri::getInstance(); $return = urlencode(base64_encode($uri)); // Add a button linking to config for component. $bar->appendButton( 'Link', 'options', $alt, 'index.php?option=com_config&amp;view=component&amp;component=' . $component . '&amp;path=' . $path . '&amp;return=' . $return ); } /** * Writes a version history * * @param string $typeAlias The component and type, for example 'com_content.article' * @param integer $itemId The id of the item, for example the article id. * @param integer $height The height of the popup. * @param integer $width The width of the popup. * @param string $alt The name of the button. * * @return void * * @since 3.2 */ public static function versions($typeAlias, $itemId, $height = 800, $width = 500, $alt = 'JTOOLBAR_VERSIONS') { $lang = Factory::getLanguage(); $lang->load('com_contenthistory', JPATH_ADMINISTRATOR, $lang->getTag(), true); /** @var \Joomla\CMS\Table\ContentType $contentTypeTable */ $contentTypeTable = Table::getInstance('Contenttype'); $typeId = $contentTypeTable->getTypeId($typeAlias); // Options array for Layout $options = array(); $options['title'] = Text::_($alt); $options['height'] = $height; $options['width'] = $width; $options['itemId'] = $typeAlias . '.' . $itemId; $bar = Toolbar::getInstance('toolbar'); $layout = new FileLayout('joomla.toolbar.versions'); $bar->appendButton('Custom', $layout->render($options), 'versions'); } /** * Writes a save button for a given option, with an additional dropdown * * @param array $buttons An array of buttons * @param string $class The button class * * @return void * * @since 4.0.0 */ public static function saveGroup($buttons = array(), $class = 'btn-success') { $validOptions = array( 'apply' => 'JTOOLBAR_APPLY', 'save' => 'JTOOLBAR_SAVE', 'save2new' => 'JTOOLBAR_SAVE_AND_NEW', 'save2copy' => 'JTOOLBAR_SAVE_AS_COPY' ); $bar = Toolbar::getInstance('toolbar'); $saveGroup = $bar->dropdownButton('save-group'); $saveGroup->configure( function (Toolbar $childBar) use ($buttons, $validOptions) { foreach ($buttons as $button) { if (!\array_key_exists($button[0], $validOptions)) { continue; } $options['group'] = true; $altText = $button[2] ?? $validOptions[$button[0]]; $childBar->{$button[0]}($button[1]) ->text($altText); } } ); } /** * Displays a modal button * * @param string $targetModalId ID of the target modal box * @param string $icon Icon class to show on modal button * @param string $alt Title for the modal button * @param string $class The button class * * @return void * * @since 3.2 */ public static function modal($targetModalId, $icon, $alt, $class = 'btn-primary') { $title = Text::_($alt); $dhtml = '<joomla-toolbar-button><button data-bs-toggle="modal" data-bs-target="#' . $targetModalId . '" class="btn ' . $class . '"> <span class="' . $icon . ' icon-fw" title="' . $title . '"></span> ' . $title . '</button></joomla-toolbar-button>'; $bar = Toolbar::getInstance('toolbar'); $bar->appendButton('Custom', $dhtml, $alt); } }
Llewellynvdm/joomla-cms
libraries/src/Toolbar/ToolbarHelper.php
PHP
gpl-2.0
19,754
<?php defined('TYPO3_MODE') or die(); if (TYPO3_MODE === 'BE') { \TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule( 'TYPO3.CMS.Cshmanual', 'help', 'cshmanual', 'top', array( 'Help' => 'index,all,detail', ), array( 'access' => 'user', 'icon' => 'EXT:cshmanual/Resources/Public/Icons/module-cshmanual.svg', 'labels' => 'LLL:EXT:lang/locallang_mod_help_cshmanual.xlf', ) ); $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook']['cshmanual'] = \TYPO3\CMS\Cshmanual\Service\JavaScriptService::class . '->addJavaScript'; }
thomaszbz/TYPO3.CMS
typo3/sysext/cshmanual/ext_tables.php
PHP
gpl-2.0
589
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 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 the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.eevolution.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.model.*; import org.compiere.util.KeyNamePair; /** Generated Interface for I_ProductPlanning * @author Adempiere (generated) * @version Release 3.8.0 */ public interface I_I_ProductPlanning { /** TableName=I_ProductPlanning */ public static final String Table_Name = "I_ProductPlanning"; /** AD_Table_ID=53260 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 2 - Client */ BigDecimal accessLevel = BigDecimal.valueOf(2); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_Workflow_ID */ public static final String COLUMNNAME_AD_Workflow_ID = "AD_Workflow_ID"; /** Set Workflow. * Workflow or combination of tasks */ public void setAD_Workflow_ID (int AD_Workflow_ID); /** Get Workflow. * Workflow or combination of tasks */ public int getAD_Workflow_ID(); /** Column name BPartner_Value */ public static final String COLUMNNAME_BPartner_Value = "BPartner_Value"; /** Set Business Partner Key. * The Key of the Business Partner */ public void setBPartner_Value (String BPartner_Value); /** Get Business Partner Key. * The Key of the Business Partner */ public String getBPartner_Value(); /** Column name C_BPartner_ID */ public static final String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID"; /** Set Business Partner . * Identifies a Business Partner */ public void setC_BPartner_ID (int C_BPartner_ID); /** Get Business Partner . * Identifies a Business Partner */ public int getC_BPartner_ID(); public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException; /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name DatePromised */ public static final String COLUMNNAME_DatePromised = "DatePromised"; /** Set Date Promised. * Date Order was promised */ public void setDatePromised (Timestamp DatePromised); /** Get Date Promised. * Date Order was promised */ public Timestamp getDatePromised(); /** Column name DD_NetworkDistribution_ID */ public static final String COLUMNNAME_DD_NetworkDistribution_ID = "DD_NetworkDistribution_ID"; /** Set Network Distribution. * Identifies a distribution network, distribution networks are used to establish the source and target of the materials in the supply chain */ public void setDD_NetworkDistribution_ID (int DD_NetworkDistribution_ID); /** Get Network Distribution. * Identifies a distribution network, distribution networks are used to establish the source and target of the materials in the supply chain */ public int getDD_NetworkDistribution_ID(); /** Column name DeliveryTime_Promised */ public static final String COLUMNNAME_DeliveryTime_Promised = "DeliveryTime_Promised"; /** Set Promised Delivery Time. * Promised days between order and delivery */ public void setDeliveryTime_Promised (BigDecimal DeliveryTime_Promised); /** Get Promised Delivery Time. * Promised days between order and delivery */ public BigDecimal getDeliveryTime_Promised(); /** Column name ForecastValue */ public static final String COLUMNNAME_ForecastValue = "ForecastValue"; /** Set Forecast Key. * Key of the Forecast */ public void setForecastValue (String ForecastValue); /** Get Forecast Key. * Key of the Forecast */ public String getForecastValue(); /** Column name I_ErrorMsg */ public static final String COLUMNNAME_I_ErrorMsg = "I_ErrorMsg"; /** Set Import Error Message. * Messages generated from import process */ public void setI_ErrorMsg (String I_ErrorMsg); /** Get Import Error Message. * Messages generated from import process */ public String getI_ErrorMsg(); /** Column name I_IsImported */ public static final String COLUMNNAME_I_IsImported = "I_IsImported"; /** Set Imported. * Has this import been processed */ public void setI_IsImported (boolean I_IsImported); /** Get Imported. * Has this import been processed */ public boolean isI_IsImported(); /** Column name I_ProductPlanning_ID */ public static final String COLUMNNAME_I_ProductPlanning_ID = "I_ProductPlanning_ID"; /** Set Import Product Planning */ public void setI_ProductPlanning_ID (int I_ProductPlanning_ID); /** Get Import Product Planning */ public int getI_ProductPlanning_ID(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsCreatePlan */ public static final String COLUMNNAME_IsCreatePlan = "IsCreatePlan"; /** Set Create Plan. * Indicates whether planned orders will be generated by MRP */ public void setIsCreatePlan (boolean IsCreatePlan); /** Get Create Plan. * Indicates whether planned orders will be generated by MRP */ public boolean isCreatePlan(); /** Column name IsMPS */ public static final String COLUMNNAME_IsMPS = "IsMPS"; /** Set Is MPS. * Indicates if this product is part of the master production schedule */ public void setIsMPS (boolean IsMPS); /** Get Is MPS. * Indicates if this product is part of the master production schedule */ public boolean isMPS(); /** Column name IsPhantom */ public static final String COLUMNNAME_IsPhantom = "IsPhantom"; /** Set Phantom. * Phantom Component */ public void setIsPhantom (boolean IsPhantom); /** Get Phantom. * Phantom Component */ public boolean isPhantom(); /** Column name M_Forecast_ID */ public static final String COLUMNNAME_M_Forecast_ID = "M_Forecast_ID"; /** Set Forecast. * Material Forecast */ public void setM_Forecast_ID (int M_Forecast_ID); /** Get Forecast. * Material Forecast */ public int getM_Forecast_ID(); public org.compiere.model.I_M_Forecast getM_Forecast() throws RuntimeException; /** Column name M_ForecastLine_ID */ public static final String COLUMNNAME_M_ForecastLine_ID = "M_ForecastLine_ID"; /** Set Forecast Line. * Forecast Line */ public void setM_ForecastLine_ID (int M_ForecastLine_ID); /** Get Forecast Line. * Forecast Line */ public int getM_ForecastLine_ID(); public org.compiere.model.I_M_ForecastLine getM_ForecastLine() throws RuntimeException; /** Column name M_Product_ID */ public static final String COLUMNNAME_M_Product_ID = "M_Product_ID"; /** Set Product. * Product, Service, Item */ public void setM_Product_ID (int M_Product_ID); /** Get Product. * Product, Service, Item */ public int getM_Product_ID(); public org.compiere.model.I_M_Product getM_Product() throws RuntimeException; /** Column name M_Warehouse_ID */ public static final String COLUMNNAME_M_Warehouse_ID = "M_Warehouse_ID"; /** Set Warehouse. * Storage Warehouse and Service Point */ public void setM_Warehouse_ID (int M_Warehouse_ID); /** Get Warehouse. * Storage Warehouse and Service Point */ public int getM_Warehouse_ID(); public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException; /** Column name NetworkDistributionValue */ public static final String COLUMNNAME_NetworkDistributionValue = "NetworkDistributionValue"; /** Set Network Distribution Key. * Key of the Network Distribution */ public void setNetworkDistributionValue (String NetworkDistributionValue); /** Get Network Distribution Key. * Key of the Network Distribution */ public String getNetworkDistributionValue(); /** Column name Order_Max */ public static final String COLUMNNAME_Order_Max = "Order_Max"; /** Set Maximum Order Qty. * Maximum order quantity in UOM */ public void setOrder_Max (BigDecimal Order_Max); /** Get Maximum Order Qty. * Maximum order quantity in UOM */ public BigDecimal getOrder_Max(); /** Column name Order_Min */ public static final String COLUMNNAME_Order_Min = "Order_Min"; /** Set Minimum Order Qty. * Minimum order quantity in UOM */ public void setOrder_Min (BigDecimal Order_Min); /** Get Minimum Order Qty. * Minimum order quantity in UOM */ public BigDecimal getOrder_Min(); /** Column name Order_Pack */ public static final String COLUMNNAME_Order_Pack = "Order_Pack"; /** Set Order Pack Qty. * Package order size in UOM (e.g. order set of 5 units) */ public void setOrder_Pack (BigDecimal Order_Pack); /** Get Order Pack Qty. * Package order size in UOM (e.g. order set of 5 units) */ public BigDecimal getOrder_Pack(); /** Column name Order_Period */ public static final String COLUMNNAME_Order_Period = "Order_Period"; /** Set Order Period. * Order Period */ public void setOrder_Period (BigDecimal Order_Period); /** Get Order Period. * Order Period */ public BigDecimal getOrder_Period(); /** Column name Order_Policy */ public static final String COLUMNNAME_Order_Policy = "Order_Policy"; /** Set Order Policy. * Order Policy */ public void setOrder_Policy (String Order_Policy); /** Get Order Policy. * Order Policy */ public String getOrder_Policy(); /** Column name Order_Qty */ public static final String COLUMNNAME_Order_Qty = "Order_Qty"; /** Set Order Qty. * Order Qty */ public void setOrder_Qty (BigDecimal Order_Qty); /** Get Order Qty. * Order Qty */ public BigDecimal getOrder_Qty(); /** Column name OrgValue */ public static final String COLUMNNAME_OrgValue = "OrgValue"; /** Set Org Key. * Key of the Organization */ public void setOrgValue (String OrgValue); /** Get Org Key. * Key of the Organization */ public String getOrgValue(); /** Column name Planner_ID */ public static final String COLUMNNAME_Planner_ID = "Planner_ID"; /** Set Planner. * Company Agent for Planning */ public void setPlanner_ID (int Planner_ID); /** Get Planner. * Company Agent for Planning */ public int getPlanner_ID(); public org.compiere.model.I_AD_User getPlanner() throws RuntimeException; /** Column name PlannerValue */ public static final String COLUMNNAME_PlannerValue = "PlannerValue"; /** Set Planner Key. * Search Key of the Planning */ public void setPlannerValue (String PlannerValue); /** Get Planner Key. * Search Key of the Planning */ public String getPlannerValue(); /** Column name PP_Product_BOM_ID */ public static final String COLUMNNAME_PP_Product_BOM_ID = "PP_Product_BOM_ID"; /** Set BOM & Formula. * BOM & Formula */ public void setPP_Product_BOM_ID (int PP_Product_BOM_ID); /** Get BOM & Formula. * BOM & Formula */ public int getPP_Product_BOM_ID(); public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException; /** Column name PP_Product_Planning_ID */ public static final String COLUMNNAME_PP_Product_Planning_ID = "PP_Product_Planning_ID"; /** Set Product Planning. * Product Planning */ public void setPP_Product_Planning_ID (int PP_Product_Planning_ID); /** Get Product Planning. * Product Planning */ public int getPP_Product_Planning_ID(); public org.eevolution.model.I_PP_Product_Planning getPP_Product_Planning() throws RuntimeException; /** Column name Processed */ public static final String COLUMNNAME_Processed = "Processed"; /** Set Processed. * The document has been processed */ public void setProcessed (boolean Processed); /** Get Processed. * The document has been processed */ public boolean isProcessed(); /** Column name Processing */ public static final String COLUMNNAME_Processing = "Processing"; /** Set Process Now */ public void setProcessing (boolean Processing); /** Get Process Now */ public boolean isProcessing(); /** Column name Product_BOM_Value */ public static final String COLUMNNAME_Product_BOM_Value = "Product_BOM_Value"; /** Set Product BOM Key. * Key of Product BOM */ public void setProduct_BOM_Value (String Product_BOM_Value); /** Get Product BOM Key. * Key of Product BOM */ public String getProduct_BOM_Value(); /** Column name ProductValue */ public static final String COLUMNNAME_ProductValue = "ProductValue"; /** Set Product Key. * Key of the Product */ public void setProductValue (String ProductValue); /** Get Product Key. * Key of the Product */ public String getProductValue(); /** Column name Qty */ public static final String COLUMNNAME_Qty = "Qty"; /** Set Quantity. * Quantity */ public void setQty (BigDecimal Qty); /** Get Quantity. * Quantity */ public BigDecimal getQty(); /** Column name ResourceValue */ public static final String COLUMNNAME_ResourceValue = "ResourceValue"; /** Set Resource Key. * Key of the Resource */ public void setResourceValue (String ResourceValue); /** Get Resource Key. * Key of the Resource */ public String getResourceValue(); /** Column name SafetyStock */ public static final String COLUMNNAME_SafetyStock = "SafetyStock"; /** Set Safety Stock Qty. * Safety stock is a term used to describe a level of stock that is maintained below the cycle stock to buffer against stock-outs */ public void setSafetyStock (BigDecimal SafetyStock); /** Get Safety Stock Qty. * Safety stock is a term used to describe a level of stock that is maintained below the cycle stock to buffer against stock-outs */ public BigDecimal getSafetyStock(); /** Column name SalesRep_ID */ public static final String COLUMNNAME_SalesRep_ID = "SalesRep_ID"; /** Set Sales Representative. * Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID); /** Get Sales Representative. * Sales Representative or Company Agent */ public int getSalesRep_ID(); /** Column name S_Resource_ID */ public static final String COLUMNNAME_S_Resource_ID = "S_Resource_ID"; /** Set Resource. * Resource */ public void setS_Resource_ID (int S_Resource_ID); /** Get Resource. * Resource */ public int getS_Resource_ID(); public org.compiere.model.I_S_Resource getS_Resource() throws RuntimeException; /** Column name TimeFence */ public static final String COLUMNNAME_TimeFence = "TimeFence"; /** Set Time Fence. * The Time Fence is the number of days since you execute the MRP process inside of which the system must not change the planned orders. */ public void setTimeFence (BigDecimal TimeFence); /** Get Time Fence. * The Time Fence is the number of days since you execute the MRP process inside of which the system must not change the planned orders. */ public BigDecimal getTimeFence(); /** Column name TransferTime */ public static final String COLUMNNAME_TransferTime = "TransferTime"; /** Set Transfer Time. * Transfer Time */ public void setTransferTime (BigDecimal TransferTime); /** Get Transfer Time. * Transfer Time */ public BigDecimal getTransferTime(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name VendorProductNo */ public static final String COLUMNNAME_VendorProductNo = "VendorProductNo"; /** Set Partner Product Key. * Product Key of the Business Partner */ public void setVendorProductNo (String VendorProductNo); /** Get Partner Product Key. * Product Key of the Business Partner */ public String getVendorProductNo(); /** Column name WarehouseValue */ public static final String COLUMNNAME_WarehouseValue = "WarehouseValue"; /** Set Warehouse Key. * Key of the Warehouse */ public void setWarehouseValue (String WarehouseValue); /** Get Warehouse Key. * Key of the Warehouse */ public String getWarehouseValue(); /** Column name WorkingTime */ public static final String COLUMNNAME_WorkingTime = "WorkingTime"; /** Set Working Time. * Workflow Simulation Execution Time */ public void setWorkingTime (BigDecimal WorkingTime); /** Get Working Time. * Workflow Simulation Execution Time */ public BigDecimal getWorkingTime(); /** Column name Yield */ public static final String COLUMNNAME_Yield = "Yield"; /** Set Yield %. * The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ public void setYield (int Yield); /** Get Yield %. * The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ public int getYield(); }
erpcya/adempierePOS
base/src/org/eevolution/model/I_I_ProductPlanning.java
Java
gpl-2.0
19,329
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package ai.instance.aturamSkyFortress; import ai.AggressiveNpcAI2; import com.aionemu.commons.network.util.ThreadPoolManager; import com.aionemu.gameserver.ai2.AI2Actions; import com.aionemu.gameserver.ai2.AIName; import com.aionemu.gameserver.ai2.poll.AIAnswer; import com.aionemu.gameserver.ai2.poll.AIAnswers; import com.aionemu.gameserver.ai2.poll.AIQuestion; import com.aionemu.gameserver.model.gameobjects.Creature; import com.aionemu.gameserver.skillengine.SkillEngine; import com.aionemu.gameserver.utils.MathUtil; import java.util.concurrent.Future; /** * @author xTz */ @AIName("shulack_guided_bomb") public class ShulackGuidedBombAI2 extends AggressiveNpcAI2 { private boolean isDestroyed; private boolean isHome = true; Future<?> task; @Override protected void handleDespawned() { super.handleDespawned(); if (task != null) { task.cancel(true); } } @Override protected void handleSpawned() { super.handleSpawned(); starLifeTask(); } @Override protected void handleCreatureAggro(Creature creature) { super.handleCreatureAggro(creature); if (isHome) { isHome = false; doSchedule(creature); } } private void starLifeTask() { ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isDestroyed) { despawn(); } } }, 10000); } private void doSchedule(final Creature creature) { task = ThreadPoolManager.getInstance().scheduleAtFixedRate(new Runnable() { @Override public void run() { if (!isAlreadyDead() && !isDestroyed) { destroy(creature); } else { if (task != null) { task.cancel(true); } } } }, 1000, 1000); } private void despawn() { if (!isAlreadyDead()) { AI2Actions.deleteOwner(this); } } private void destroy(Creature creature) { if (!isDestroyed && !isAlreadyDead()) { if (creature != null && MathUtil.getDistance(getOwner(), creature) <= 4) { isDestroyed = true; SkillEngine.getInstance().getSkill(getOwner(), 19415, 49, getOwner()).useNoAnimationSkill(); ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { despawn(); } }, 3200); } } } @Override public AIAnswer ask(AIQuestion question) { switch (question) { case CAN_RESIST_ABNORMAL: return AIAnswers.POSITIVE; default: return AIAnswers.NEGATIVE; } } @Override protected AIAnswer pollInstance(AIQuestion question) { switch (question) { case SHOULD_DECAY: return AIAnswers.NEGATIVE; case SHOULD_RESPAWN: return AIAnswers.NEGATIVE; case SHOULD_REWARD: return AIAnswers.NEGATIVE; default: return null; } } }
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/ai/instance/aturamSkyFortress/ShulackGuidedBombAI2.java
Java
gpl-2.0
4,749
#include <Gosu/Text.hpp> #include <Gosu/Bitmap.hpp> #include <Gosu/Utility.hpp> #include <pango/pango.h> #include <pango/pangoft2.h> #include <glib.h> #include <SDL/SDL_ttf.h> #include <string> #include <cstring> #include <stdexcept> std::wstring Gosu::defaultFontName() { return L"sans"; } namespace Gosu { // Used for system fonts // Adapted from original version by Jan Lücker class PangoRenderer { PangoRenderer(const PangoRenderer&); PangoRenderer& operator=(const PangoRenderer&); int width, height; PangoContext* context; PangoLayout* layout; PangoFontDescription *font_description; PangoAttribute* attr; PangoAttrList* attrList; public: PangoRenderer() { font_description = NULL; attr = NULL; attrList = NULL; } ~PangoRenderer() { g_object_unref(context); g_object_unref(layout); if(font_description) pango_font_description_free(font_description); if(attr) pango_attribute_destroy(attr); } unsigned textWidth(const std::wstring& text, const std::wstring& fontFace, unsigned fontHeight, unsigned fontFlags) { g_type_init(); int dpi_x = 100, dpi_y = 100; context = pango_ft2_get_context(dpi_x, dpi_y); pango_context_set_language(context, pango_language_from_string ("en_US")); PangoDirection init_dir = PANGO_DIRECTION_LTR; pango_context_set_base_dir(context, init_dir); font_description = pango_font_description_new(); pango_font_description_set_family(font_description, g_strdup(narrow(fontFace).c_str())); pango_font_description_set_style(font_description, (fontFlags & ffItalic) ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL); pango_font_description_set_variant(font_description, PANGO_VARIANT_NORMAL); pango_font_description_set_weight(font_description, (fontFlags & ffBold) ? PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL); pango_font_description_set_stretch(font_description, PANGO_STRETCH_NORMAL); int init_scale = int(fontHeight/2.0 + 0.5); pango_font_description_set_size(font_description, init_scale * PANGO_SCALE); pango_context_set_font_description(context, font_description); layout = pango_layout_new(context); if(fontFlags & ffUnderline) { // PangoAttribute *attr; attr = pango_attr_underline_new(PANGO_UNDERLINE_SINGLE); attr->start_index = 0; attr->end_index = text.length(); // PangoAttrList* attrList; attrList = pango_attr_list_new(); pango_attr_list_insert(attrList, attr); pango_layout_set_attributes(layout, attrList); pango_attr_list_unref(attrList); } // IMPR: Catch errors? (Last NULL-Pointer) gchar* utf8Str = g_ucs4_to_utf8((gunichar*)text.c_str(), text.length(), NULL, NULL, NULL); pango_layout_set_text(layout, utf8Str, -1); g_free(utf8Str); PangoDirection base_dir = pango_context_get_base_dir(context); pango_layout_set_alignment(layout, base_dir == PANGO_DIRECTION_LTR ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT); pango_layout_set_width(layout, -1); PangoRectangle logical_rect; pango_layout_get_pixel_extents(layout, NULL, &logical_rect); height = logical_rect.height; width = logical_rect.width; return width; } void drawText(Bitmap& bitmap, const std::wstring& text, int x, int y, Color c, const std::wstring& fontFace, unsigned fontHeight, unsigned fontFlags) { textWidth(text, fontFace, fontHeight, fontFlags); FT_Bitmap ft_bitmap; guchar* buf = new guchar[width * height]; std::fill(buf, buf + width * height, 0x00); ft_bitmap.rows = height; ft_bitmap.width = width; ft_bitmap.pitch = ft_bitmap.width; ft_bitmap.buffer = buf; ft_bitmap.num_grays = 256; ft_bitmap.pixel_mode = ft_pixel_mode_grays; int x_start = 0; pango_ft2_render_layout(&ft_bitmap, layout, x_start, 0); int min_height = height; if((unsigned)height > fontHeight) min_height = fontHeight; for(int y2 = 0; y2 < min_height; y2++) { if (y + y2 < 0 || y + y2 >= bitmap.height()) break; for(int x2 = 0; x2 < width; x2++) { if (x + x2 < 0 || x + x2 >= bitmap.width()) break; unsigned val = ft_bitmap.buffer[y2*width+x2]; Color color = multiply(c, Gosu::Color(val, 255, 255, 255)); bitmap.setPixel(x2 + x, y2 + y, color); } } delete[] buf; } }; // Used for custom TTF files // Adapted from customFont class by José Tomás Tocino García (TheOm3ga) class SDLTTFRenderer { SDLTTFRenderer(const SDLTTFRenderer&); SDLTTFRenderer& operator=(const SDLTTFRenderer&); TTF_Font* font; class SDLSurface { SDLSurface(const SDLSurface&); SDLSurface& operator=(const SDLSurface&); SDL_Surface* surface; public: SDLSurface(TTF_Font* font, const std::wstring& text, Gosu::Color c) { SDL_Color color = { c.red(), c.green(), c.blue() }; surface = TTF_RenderUTF8_Blended(font, Gosu::wstringToUTF8(text).c_str(), color); if (!surface) throw std::runtime_error("Could not render text " + Gosu::wstringToUTF8(text)); } ~SDLSurface() { SDL_FreeSurface(surface); } unsigned height() const { return surface->h; } unsigned width() const { return surface->w; } const void* data() const { return surface->pixels; } }; public: SDLTTFRenderer(const std::wstring& fontName, unsigned fontHeight) { static int initResult = TTF_Init(); if (initResult < 0) throw std::runtime_error("Could not initialize SDL_TTF"); // Try to open the font at the given path font = TTF_OpenFont(Gosu::wstringToUTF8(fontName).c_str(), fontHeight); if (!font) throw std::runtime_error("Could not open TTF file " + Gosu::wstringToUTF8(fontName)); // Re-open with scaled height so that ascenders/descenders fit int tooLargeHeight = TTF_FontHeight(font); int realHeight = fontHeight * fontHeight / tooLargeHeight; TTF_CloseFont(font); font = TTF_OpenFont(Gosu::wstringToUTF8(fontName).c_str(), realHeight); if (!font) throw std::runtime_error("Could not open TTF file " + Gosu::wstringToUTF8(fontName)); } ~SDLTTFRenderer() { TTF_CloseFont(font); } unsigned textWidth(const std::wstring& text){ return SDLSurface(font, text, 0xffffff).width(); } void drawText(Bitmap& bmp, const std::wstring& text, int x, int y, Gosu::Color c) { SDLSurface surf(font, text, c); Gosu::Bitmap temp; temp.resize(surf.width(), surf.height()); std::memcpy(temp.data(), surf.data(), temp.width() * temp.height() * 4); bmp.insert(temp, x, y); } }; } unsigned Gosu::textWidth(const std::wstring& text, const std::wstring& fontName, unsigned fontHeight, unsigned fontFlags) { if (text.find_first_of(L"\r\n") != std::wstring::npos) throw std::invalid_argument("the argument to textWidth cannot contain line breaks"); if (fontName.find(L"/") == std::wstring::npos) return PangoRenderer().textWidth(text, fontName, fontHeight, fontFlags); else return SDLTTFRenderer(fontName, fontHeight).textWidth(text); } void Gosu::drawText(Bitmap& bitmap, const std::wstring& text, int x, int y, Color c, const std::wstring& fontName, unsigned fontHeight, unsigned fontFlags) { if (text.find_first_of(L"\r\n") != std::wstring::npos) throw std::invalid_argument("the argument to drawText cannot contain line breaks"); if (fontName.find(L"/") == std::wstring::npos) PangoRenderer().drawText(bitmap, text, x, y, c, fontName, fontHeight, fontFlags); else SDLTTFRenderer(fontName, fontHeight).drawText(bitmap, text, x, y, c); }
sustmi/oflute
gosu/GosuImpl/Graphics/TextUnix.cpp
C++
gpl-2.0
9,293
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class AE_News_Letter extends Burge_CMF_Controller { function __construct() { parent::__construct(); $this->lang->load('ae_news_letter',$this->selected_lang); $this->load->model("news_letter_manager_model"); } public function index() { if($this->input->post("post_type")==="add_template") return $this->add_template(); $this->set_news_letters_info(); $this->data['message']=get_message(); $this->data['raw_page_url']=get_link("admin_news_letter"); $this->data['lang_pages']=get_lang_pages(get_link("admin_news_letter",TRUE)); $this->data['header_title']=$this->lang->line("news_letter"); $this->send_admin_output("news_letter"); return; } private function set_news_letters_info() { $filters=array(); $this->initialize_filters($filters); $total=$this->news_letter_manager_model->get_total_news_letters($filters); if($total) { $per_page=20; $page=1; if($this->input->get("page")) $page=(int)$this->input->get("page"); $start=($page-1)*$per_page; $filters['start']=$start; $filters['count']=$per_page; $this->data['news_letters']=$this->news_letter_manager_model->get_news_letters($filters); $end=$start+sizeof($this->data['news_letters'])-1; unset($filters['start']); unset($filters['count']); unset($filters['group_by']); $this->data['current_page']=$page; $this->data['total_pages']=ceil($total/$per_page); $this->data['total_results']=$total; $this->data['results_start']=$start+1; $this->data['results_end']=$end+1; } else { $this->data['current_page']=0; $this->data['total_pages']=0; $this->data['total_results']=$total; $this->data['results_start']=0; $this->data['results_end']=0; } unset($filters['lang']); $this->data['filter']=$filters; return; } private function initialize_filters(&$filters) { $filters['lang']=$this->language->get(); if($this->input->get("title")) $filters['title']=$this->input->get("title"); persian_normalize($filters); return; } private function add_template() { $nl_id=$this->news_letter_manager_model->add_template(); return redirect(get_admin_news_letter_template_link($nl_id)); } public function template($nl_id) { if($this->input->post("post_type")==="edit_template") return $this->edit_template($nl_id); if($this->input->post("post_type")==="delete_template") return $this->delete_template($nl_id); if($this->input->post("post_type")==="send_news_letter") return $this->send_news_letter($nl_id); $this->data['nl_id']=$nl_id; $this->data['news_letter_id']=$nl_id; $this->data['news_letter_info']=$this->news_letter_manager_model->get_template($nl_id); $this->data['message']=get_message(); $this->data['lang_pages']=get_lang_pages(get_admin_news_letter_template_link($nl_id,TRUE)); $this->data['header_title']=$this->lang->line("news_letter_details")." ".$nl_id; $this->send_admin_output("news_letter_template"); return; } private function delete_template($news_letter_id) { $this->news_letter_manager_model->delete_template($news_letter_id); set_message($this->lang->line('news_letter_deleted_successfully')); return redirect(get_link("admin_news_letter")); } private function edit_template($nl_id) { $props=array( "nlt_subject" => $this->input->post("subject") ,"nlt_content" => $_POST["content"] ); $this->news_letter_manager_model->set_template_props($nl_id, $props); set_message($this->lang->line("changes_saved_successfully")); redirect(get_admin_news_letter_template_link($nl_id)); return; } private function send_news_letter($nl_id) { $this->news_letter_manager_model->send_news_letter($nl_id); set_message($this->lang->line("news_letter_sent_successfully")); redirect(get_admin_news_letter_template_link($nl_id)); return; } }
MohsenKoohi/BurgeATS
CMF/Web/application/controllers/AE_News_Letter.php
PHP
gpl-2.0
3,935
<?php error_reporting(E_ERROR | E_WARNING | E_PARSE); require_once "functions.php"; require_once "sessions.php"; require_once "sanity_check.php"; require_once "version.php"; require_once "config.php"; require_once "db-prefs.php"; $link = db_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); login_sequence($link); $dt_add = get_script_dt_add(); no_cache_incantation(); header('Content-Type: text/html; charset=utf-8'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Tiny Tiny RSS : Preferences</title> <link rel="stylesheet" type="text/css" href="tt-rss.css?<?php echo $dt_add ?>"/> <?php $user_theme = get_user_theme_path($link); if ($user_theme) { ?> <link rel="stylesheet" type="text/css" href="<?php echo $user_theme ?>/theme.css"/> <?php } ?> <?php $user_css_url = get_pref($link, 'USER_STYLESHEET_URL'); ?> <?php if ($user_css_url) { ?> <link type="text/css" href="<?php echo $user_css_url ?>"/> <?php } ?> <link rel="shortcut icon" type="image/png" href="images/favicon.png"/> <script type="text/javascript" src="lib/prototype.js"></script> <script type="text/javascript" src="lib/scriptaculous/scriptaculous.js?load=effects,dragdrop,controls"></script> <script type="text/javascript" charset="utf-8" src="localized_js.php?<?php echo $dt_add ?>"></script> <script type="text/javascript" charset="utf-8" src="functions.js?<?php echo $dt_add ?>"></script> <script type="text/javascript" charset="utf-8" src="prefs.js?<?php echo $dt_add ?>"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script type="text/javascript"> Event.observe(window, 'load', function() { init(); }); </script> </head> <body id="ttrssPrefs"> <div id="overlay"> <div id="overlay_inner"> <?php echo __("Loading, please wait...") ?> <div id="l_progress_o"> <div id="l_progress_i"></div> </div> <noscript> <p><?php print_error(__("Your browser doesn't support Javascript, which is required for this application to function properly. Please check your browser settings.")) ?></p> </noscript> </div> </div> <div id="hotkey_help_overlay" style="display : none" onclick="Element.hide(this)"> <?php rounded_table_start("hho"); ?> <?php include "help/4.php" ?> <?php rounded_table_end(); ?> </div> <img id="piggie" src="images/piggie.png" style="display : none" alt="piggie"/> <ul id="debug_output" style='display : none'><li>&nbsp;</li></ul> <div id="prefHeader"> <div class="topLinks"> <?php if (!SINGLE_USER_MODE) { ?> <?php echo __('Hello,') ?> <b><?php echo $_SESSION["name"] ?></b> | <?php } ?> <a href="#" onclick="gotoMain()"><?php echo __('Exit preferences') ?></a> <?php if (!SINGLE_USER_MODE) { ?> | <a href="logout.php"><?php echo __('Logout') ?></a> <?php } ?> </div> <img src="<?php echo theme_image($link, 'images/ttrss_logo.png') ?>" alt="Tiny Tiny RSS"/> </div> <div id="prefTabs"> <div class='prefKbdHelp'> <img src="<?php echo theme_image($link, 'images/small_question.png') ?>" alt="?"/> <a href='#' onclick="Effect.Appear('hotkey_help_overlay', {duration: 0.3})"><?php echo __("Keyboard shortcuts") ?></a> </div> <div class="firstTab">&nbsp;</div> <div id="genConfigTab" class="prefsTab" onclick="selectTab('genConfig')"><?php echo __('Preferences') ?></div> <div id="feedConfigTab" class="prefsTab" onclick="selectTab('feedConfig')"><?php echo __('Feeds') ?></div> <div id="filterConfigTab" class="prefsTab" onclick="selectTab('filterConfig')"><?php echo __('Filters') ?></div> <div id="labelConfigTab" class="prefsTab" onclick="selectTab('labelConfig')"><?php echo __('Labels') ?></div> <?php if ($_SESSION["access_level"] >= 10) { ?> <div id="userConfigTab" class="prefsTab" onclick="selectTab('userConfig')"><?php echo __('Users') ?></div> <?php } ?> </div> <div id="prefContentOuter"> <div id="prefContent"> <p><?php echo __('Loading, please wait...') ?></p> <noscript> <div class="error"> <?php echo __("Your browser doesn't support Javascript, which is required for this application to function properly. Please check your browser settings.") ?></div> </noscript> </div> </div> <div id="notify" class="notify"><span id="notify_body">&nbsp;</span></div> <div id="infoBoxShadow"><div id="infoBox">BAH</div></div> <div id="cmdline" style="display : none"></div> <div id="errorBoxShadow" style="display : none"> <div id="errorBox"> <div id="xebTitle"><?php echo __('Fatal Exception') ?></div><div id="xebContent">&nbsp;</div> <div id="xebBtn" align='center'> <button onclick="closeErrorBox()"><?php echo __('Close this window') ?></button> </div> </div> </div> <div id="dialog_overlay" style="display : none"> </div> <div id="prefFooter"> <a href="http://tt-rss.org/">Tiny Tiny RSS</a> <?php if (!defined('HIDE_VERSION')) { ?> v<?php echo VERSION ?> <?php } ?> &copy; 2005&ndash;2010 <a href="http://bah.org.ru/">Andrew Dolgov</a> </div> <?php db_close($link); ?> </body> </html>
torne/Tiny-Tiny-RSS
prefs.php
PHP
gpl-2.0
5,102
/** * Created by Stefan on 24.05.14. */ (function() { tinymce.create('tinymce.plugins.Footnotes', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished its initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { ed.addButton('footnotes', { title : 'footnotes', cmd : 'footnotes', image : url + '/../img/fn-wysiwyg.png' }); ed.addCommand('footnotes', function() { jQuery.ajax({ type: 'POST', url: '/wp-admin/admin-ajax.php', data: { action: 'footnotes_getTags' }, success: function(data, textStatus, XMLHttpRequest){ var l_arr_Tags = JSON.parse(data); var return_text = l_arr_Tags['start'] + ed.selection.getContent() + l_arr_Tags['end']; ed.execCommand('insertHTML', true, return_text); }, error: function(MLHttpRequest, textStatus, errorThrown){ console.log("Error: " + errorThrown); } }); }); }, /** * Creates control instances based in the incomming name. This method is normally not * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons * but you sometimes need to create more complex controls like listboxes, split buttons etc then this * method can be used to create those. * * @param {String} n Name of the control to create. * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control. * @return {tinymce.ui.Control} New control instance or null if no control was created. */ createControl : function(n, cm) { return null; }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Inserts the Footnotes short code.', author : 'ManFisher Medien ManuFaktur', authorurl : 'http://http://manfisher.net/', infourl : 'http://wordpress.org/plugins/footnotes/', version : "1.5.0" }; } }); // Register plugin tinymce.PluginManager.add('footnotes', tinymce.plugins.Footnotes); })();
austing/siq
wp-content/plugins/footnotes/js/wysiwyg-editor.js
JavaScript
gpl-2.0
3,155
<?php /** * @package Joomla.Administrator * @subpackage com_tags * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * Tags view class for the Tags package. * * @package Joomla.Administrator * @subpackage com_tags * @since 3.1 */ class TagsViewTags extends JViewLegacy { protected $items; protected $pagination; protected $state; protected $assoc; /** * Display the view */ public function display($tpl = null) { $this->state = $this->get('State'); $this->items = $this->get('Items'); $this->pagination = $this->get('Pagination'); TagsHelper::addSubmenu('tags'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } // Preprocess the list of items to find ordering divisions. foreach ($this->items as &$item) { $this->ordering[$item->parent_id][] = $item->id; } // Levels filter. $options = array(); $options[] = JHtml::_('select.option', '1', JText::_('J1')); $options[] = JHtml::_('select.option', '2', JText::_('J2')); $options[] = JHtml::_('select.option', '3', JText::_('J3')); $options[] = JHtml::_('select.option', '4', JText::_('J4')); $options[] = JHtml::_('select.option', '5', JText::_('J5')); $options[] = JHtml::_('select.option', '6', JText::_('J6')); $options[] = JHtml::_('select.option', '7', JText::_('J7')); $options[] = JHtml::_('select.option', '8', JText::_('J8')); $options[] = JHtml::_('select.option', '9', JText::_('J9')); $options[] = JHtml::_('select.option', '10', JText::_('J10')); $this->f_levels = $options; $this->addToolbar(); $this->sidebar = JHtmlSidebar::render(); parent::display($tpl); } /** * Add the page title and toolbar. * * @since 3.1 */ protected function addToolbar() { $state = $this->get('State'); $canDo = TagsHelper::getActions($state->get('filter.parent_id')); $user = JFactory::getUser(); // Get the toolbar object instance $bar = JToolBar::getInstance('toolbar'); JToolbarHelper::title(JText::_('COM_TAGS_MANAGER_TAGS'), 'modules.png'); if ($canDo->get('core.create')) { JToolbarHelper::addNew('tag.add'); } if ($canDo->get('core.edit')) { JToolbarHelper::editList('tag.edit'); } if ($canDo->get('core.edit.state')) { JToolbarHelper::publish('tags.publish', 'JTOOLBAR_PUBLISH', true); JToolbarHelper::unpublish('tags.unpublish', 'JTOOLBAR_UNPUBLISH', true); JToolbarHelper::archiveList('tags.archive'); } if ($canDo->get('core.admin')) { JToolbarHelper::checkin('tags.checkin'); } if ($state->get('filter.published') == -2 && $canDo->get('core.delete')) { JToolbarHelper::deleteList('', 'tags.delete', 'JTOOLBAR_EMPTY_TRASH'); } elseif ($canDo->get('core.edit.state')) { JToolbarHelper::trash('tags.trash'); } // Add a batch button if ($user->authorise('core.edit')) { JHtml::_('bootstrap.modal', 'collapseModal'); $title = JText::_('JTOOLBAR_BATCH'); $dhtml = "<button data-toggle=\"modal\" data-target=\"#collapseModal\" class=\"btn btn-small\"> <i class=\"icon-checkbox-partial\" title=\"$title\"></i> $title</button>"; $bar->appendButton('Custom', $dhtml, 'batch'); } if ($canDo->get('core.admin')) { JToolbarHelper::preferences('com_tags'); } JToolbarHelper::help('JHELP_COMPONENTS_TAGS'); JHtmlSidebar::setAction('index.php?option=com_tags&view=tags'); JHtmlSidebar::addFilter( JText::_('JOPTION_SELECT_PUBLISHED'), 'filter_published', JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), 'value', 'text', $this->state->get('filter.published'), true) ); JHtmlSidebar::addFilter( JText::_('JOPTION_SELECT_ACCESS'), 'filter_access', JHtml::_('select.options', JHtml::_('access.assetgroups'), 'value', 'text', $this->state->get('filter.access')) ); JHtmlSidebar::addFilter( JText::_('JOPTION_SELECT_LANGUAGE'), 'filter_language', JHtml::_('select.options', JHtml::_('contentlanguage.existing', true, true), 'value', 'text', $this->state->get('filter.language')) ); } /** * Returns an array of fields the table can be sorted by * * @return array Array containing the field name to sort by as the key and display text as value * * @since 3.0 */ protected function getSortFields() { return array( 'a.lft' => JText::_('JGRID_HEADING_ORDERING'), 'a.state' => JText::_('JSTATUS'), 'a.title' => JText::_('JGLOBAL_TITLE'), 'a.access' => JText::_('JGRID_HEADING_ACCESS'), 'language' => JText::_('JGRID_HEADING_LANGUAGE'), 'a.id' => JText::_('JGRID_HEADING_ID') ); } }
malukenho/joomla-cms
administrator/components/com_tags/views/tags/view.html.php
PHP
gpl-2.0
4,791
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2007 ScriptDev2 <https://scriptdev2.svn.sourceforge.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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: instance_uldaman SD%Complete: 99 SDComment: Need some cosmetics updates when archeadas door are closing (Guardians Waypoints). SDCategory: Uldaman EndScriptData */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "uldaman.h" enum Spells { SPELL_ARCHAEDAS_AWAKEN = 10347, SPELL_AWAKEN_VAULT_WALKER = 10258, }; enum Events { EVENT_SUB_BOSS_AGGRO = 2228 }; class instance_uldaman : public InstanceMapScript { public: instance_uldaman() : InstanceMapScript("instance_uldaman", 70) { } struct instance_uldaman_InstanceMapScript : public InstanceScript { instance_uldaman_InstanceMapScript(Map* map) : InstanceScript(map) { } void Initialize() OVERRIDE { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); archaedasGUID = 0; ironayaGUID = 0; whoWokeuiArchaedasGUID = 0; altarOfTheKeeperTempleDoor = 0; archaedasTempleDoor = 0; ancientVaultDoor = 0; ironayaSealDoor = 0; keystoneGUID = 0; ironayaSealDoorTimer = 27000; //animation time keystoneCheck = false; } bool IsEncounterInProgress() const OVERRIDE { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (m_auiEncounter[i] == IN_PROGRESS) return true; return false; } uint64 archaedasGUID; uint64 ironayaGUID; uint64 whoWokeuiArchaedasGUID; uint64 altarOfTheKeeperTempleDoor; uint64 archaedasTempleDoor; uint64 ancientVaultDoor; uint64 ironayaSealDoor; uint64 keystoneGUID; uint32 ironayaSealDoorTimer; bool keystoneCheck; std::vector<uint64> stoneKeepers; std::vector<uint64> altarOfTheKeeperCounts; std::vector<uint64> vaultWalkers; std::vector<uint64> earthenGuardians; std::vector<uint64> archaedasWallMinions; // minions lined up around the wall uint32 m_auiEncounter[MAX_ENCOUNTER]; std::string str_data; void OnGameObjectCreate(GameObject* go) OVERRIDE { switch (go->GetEntry()) { case GO_ALTAR_OF_THE_KEEPER_TEMPLE_DOOR: // lock the door altarOfTheKeeperTempleDoor = go->GetGUID(); if (m_auiEncounter[0] == DONE) HandleGameObject(0, true, go); break; case GO_ARCHAEDAS_TEMPLE_DOOR: archaedasTempleDoor = go->GetGUID(); if (m_auiEncounter[0] == DONE) HandleGameObject(0, true, go); break; case GO_ANCIENT_VAULT_DOOR: go->SetGoState(GO_STATE_READY); go->SetUInt32Value(GAMEOBJECT_FIELD_FLAGS, 33); ancientVaultDoor = go->GetGUID(); if (m_auiEncounter[1] == DONE) HandleGameObject(0, true, go); break; case GO_IRONAYA_SEAL_DOOR: ironayaSealDoor = go->GetGUID(); if (m_auiEncounter[2] == DONE) HandleGameObject(0, true, go); break; case GO_KEYSTONE: keystoneGUID = go->GetGUID(); if (m_auiEncounter[2] == DONE) { HandleGameObject(0, true, go); go->SetUInt32Value(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_INTERACT_COND); } break; } } void SetFrozenState(Creature* creature) { creature->setFaction(35); creature->RemoveAllAuras(); //creature->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_ANIMATION_FROZEN); creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); } void SetDoor(uint64 guid, bool open) { GameObject* go = instance->GetGameObject(guid); if (!go) return; HandleGameObject(guid, open); } void BlockGO(uint64 guid) { GameObject* go = instance->GetGameObject(guid); if (!go) return; go->SetUInt32Value(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_INTERACT_COND); } void ActivateStoneKeepers() { if (GetData(DATA_ALTAR_DOORS) != DONE) { for (std::vector<uint64>::const_iterator i = stoneKeepers.begin(); i != stoneKeepers.end(); ++i) { Creature* target = instance->GetCreature(*i); if (!target || !target->IsAlive()) continue; target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); target->setFaction(14); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); return; // only want the first one we find } // if we get this far than all four are dead so open the door SetData(DATA_ALTAR_DOORS, DONE); SetDoor(archaedasTempleDoor, true); //open next the door too } } void ActivateWallMinions() { Creature* archaedas = instance->GetCreature(archaedasGUID); if (!archaedas) return; for (std::vector<uint64>::const_iterator i = archaedasWallMinions.begin(); i != archaedasWallMinions.end(); ++i) { Creature* target = instance->GetCreature(*i); if (!target || !target->IsAlive() || target->getFaction() == 14) continue; archaedas->CastSpell(target, SPELL_AWAKEN_VAULT_WALKER, true); target->CastSpell(target, SPELL_ARCHAEDAS_AWAKEN, true); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); target->setFaction(14); return; // only want the first one we find } } // used when Archaedas dies. All active minions must be despawned. void DeActivateMinions() { // first despawn any aggroed wall minions for (std::vector<uint64>::const_iterator i = archaedasWallMinions.begin(); i != archaedasWallMinions.end(); ++i) { Creature* target = instance->GetCreature(*i); if (!target || target->isDead() || target->getFaction() != 14) continue; target->setDeathState(JUST_DIED); target->RemoveCorpse(); } // Vault Walkers for (std::vector<uint64>::const_iterator i = vaultWalkers.begin(); i != vaultWalkers.end(); ++i) { Creature* target = instance->GetCreature(*i); if (!target || target->isDead() || target->getFaction() != 14) continue; target->setDeathState(JUST_DIED); target->RemoveCorpse(); } // Earthen Guardians for (std::vector<uint64>::const_iterator i = earthenGuardians.begin(); i != earthenGuardians.end(); ++i) { Creature* target = instance->GetCreature(*i); if (!target || target->isDead() || target->getFaction() != 14) continue; target->setDeathState(JUST_DIED); target->RemoveCorpse(); } } void ActivateArchaedas(uint64 target) { Creature* archaedas = instance->GetCreature(archaedasGUID); if (!archaedas) return; if (Unit::GetUnit(*archaedas, target)) { archaedas->CastSpell(archaedas, SPELL_ARCHAEDAS_AWAKEN, false); whoWokeuiArchaedasGUID = target; } } void ActivateIronaya() { Creature* ironaya = instance->GetCreature(ironayaGUID); if (!ironaya) return; ironaya->setFaction(415); ironaya->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); ironaya->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void RespawnMinions() { // first respawn any aggroed wall minions for (std::vector<uint64>::const_iterator i = archaedasWallMinions.begin(); i != archaedasWallMinions.end(); ++i) { Creature* target = instance->GetCreature(*i); if (target && target->isDead()) { target->Respawn(); target->GetMotionMaster()->MoveTargetedHome(); SetFrozenState(target); } } // Vault Walkers for (std::vector<uint64>::const_iterator i = vaultWalkers.begin(); i != vaultWalkers.end(); ++i) { Creature* target = instance->GetCreature(*i); if (target && target->isDead()) { target->Respawn(); target->GetMotionMaster()->MoveTargetedHome(); SetFrozenState(target); } } // Earthen Guardians for (std::vector<uint64>::const_iterator i = earthenGuardians.begin(); i != earthenGuardians.end(); ++i) { Creature* target = instance->GetCreature(*i); if (target && target->isDead()) { target->Respawn(); target->GetMotionMaster()->MoveTargetedHome(); SetFrozenState(target); } } } void Update(uint32 diff) OVERRIDE { if (!keystoneCheck) return; if (ironayaSealDoorTimer <= diff) { ActivateIronaya(); SetDoor(ironayaSealDoor, true); BlockGO(keystoneGUID); SetData(DATA_IRONAYA_DOOR, DONE); //save state keystoneCheck = false; } else ironayaSealDoorTimer -= diff; } void SetData(uint32 type, uint32 data) OVERRIDE { switch (type) { case DATA_ALTAR_DOORS: m_auiEncounter[0] = data; if (data == DONE) SetDoor(altarOfTheKeeperTempleDoor, true); break; case DATA_ANCIENT_DOOR: m_auiEncounter[1] = data; if (data == DONE) //archeadas defeat { SetDoor(archaedasTempleDoor, true); //re open enter door SetDoor(ancientVaultDoor, true); } break; case DATA_IRONAYA_DOOR: m_auiEncounter[2] = data; break; case DATA_STONE_KEEPERS: ActivateStoneKeepers(); break; case DATA_MINIONS: switch (data) { case NOT_STARTED: if (m_auiEncounter[0] == DONE) //if players opened the doors SetDoor(archaedasTempleDoor, true); RespawnMinions(); break; case IN_PROGRESS: ActivateWallMinions(); break; case SPECIAL: DeActivateMinions(); break; } break; case DATA_IRONAYA_SEAL: keystoneCheck = true; break; } if (data == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << ' ' << m_auiEncounter[1] << ' ' << m_auiEncounter[2]; str_data = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } void SetData64(uint32 type, uint64 data) OVERRIDE { // Archaedas if (type == 0) { ActivateArchaedas (data); SetDoor(archaedasTempleDoor, false); //close when event is started } } std::string GetSaveData() OVERRIDE { return str_data; } void Load(const char* in) OVERRIDE { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); std::istringstream loadStream(in); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2]; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } OUT_LOAD_INST_DATA_COMPLETE; } void OnCreatureCreate(Creature* creature) OVERRIDE { switch (creature->GetEntry()) { case 4857: // Stone Keeper SetFrozenState (creature); stoneKeepers.push_back(creature->GetGUID()); break; case 7309: // Earthen Custodian archaedasWallMinions.push_back(creature->GetGUID()); break; case 7077: // Earthen Hallshaper archaedasWallMinions.push_back(creature->GetGUID()); break; case 7076: // Earthen Guardian earthenGuardians.push_back(creature->GetGUID()); break; case 7228: // Ironaya ironayaGUID = creature->GetGUID(); if (m_auiEncounter[2] != DONE) SetFrozenState (creature); break; case 10120: // Vault Walker vaultWalkers.push_back(creature->GetGUID()); break; case 2748: // Archaedas archaedasGUID = creature->GetGUID(); break; } } uint64 GetData64(uint32 identifier) const OVERRIDE { switch (identifier) { case 0: return whoWokeuiArchaedasGUID; case 1: case 2: case 3: case 4: return vaultWalkers.at(identifier - 1); case 5: case 6: case 7: case 8: case 9: case 10: return earthenGuardians.at(identifier - 5); default: break; } return 0; } // end GetData64 void ProcessEvent(WorldObject* /*gameObject*/, uint32 eventId) OVERRIDE { switch (eventId) { case EVENT_SUB_BOSS_AGGRO: SetData(DATA_STONE_KEEPERS, IN_PROGRESS); // activate the Stone Keepers break; default: break; } } }; InstanceScript* GetInstanceScript(InstanceMap* map) const OVERRIDE { return new instance_uldaman_InstanceMapScript(map); } }; void AddSC_instance_uldaman() { new instance_uldaman(); }
wuhongyi1977/MOP_5_4_1
src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp
C++
gpl-2.0
18,563
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.linear; import java.util.Iterator; import org.apache.commons.math.FunctionEvaluationException; import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.analysis.BinaryFunction; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.ComposableFunction; /** * This class provides default basic implementations for many methods in the * {@link RealVector} interface with. * @version $Revision$ $Date$ * @since 2.1 */ public abstract class AbstractRealVector implements RealVector { /** * Check if instance and specified vectors have the same dimension. * @param v vector to compare instance with * @exception IllegalArgumentException if the vectors do not * have the same dimension */ protected void checkVectorDimensions(RealVector v) { checkVectorDimensions(v.getDimension()); } /** * Check if instance dimension is equal to some expected value. * * @param n expected dimension. * @exception IllegalArgumentException if the dimension is * inconsistent with vector size */ protected void checkVectorDimensions(int n) throws IllegalArgumentException { double d = getDimension(); if (d != n) { throw MathRuntimeException.createIllegalArgumentException( "vector length mismatch: got {0} but expected {1}", d, n); } } /** * Check if an index is valid. * @param index index to check * @exception MatrixIndexException if index is not valid */ protected void checkIndex(final int index) throws MatrixIndexException { if (index < 0 || index >= getDimension()) { throw new MatrixIndexException( "index {0} out of allowed range [{1}, {2}]", index, 0, getDimension() - 1); } } /** {@inheritDoc} */ public void setSubVector(int index, RealVector v) throws MatrixIndexException { checkIndex(index); checkIndex(index + v.getDimension() - 1); setSubVector(index, v.getData()); } /** {@inheritDoc} */ public void setSubVector(int index, double[] v) throws MatrixIndexException { checkIndex(index); checkIndex(index + v.length - 1); for (int i = 0; i < v.length; i++) { setEntry(i + index, v[i]); } } /** {@inheritDoc} */ public RealVector add(double[] v) throws IllegalArgumentException { double[] result = v.clone(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { result[e.getIndex()] += e.getValue(); } return new ArrayRealVector(result, false); } /** {@inheritDoc} */ public RealVector add(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { double[] values = ((ArrayRealVector)v).getDataRef(); return add(values); } RealVector result = v.copy(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final int index = e.getIndex(); result.setEntry(index, e.getValue() + result.getEntry(index)); } return result; } /** {@inheritDoc} */ public RealVector subtract(double[] v) throws IllegalArgumentException { double[] result = v.clone(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final int index = e.getIndex(); result[index] = e.getValue() - result[index]; } return new ArrayRealVector(result, false); } /** {@inheritDoc} */ public RealVector subtract(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { double[] values = ((ArrayRealVector)v).getDataRef(); return add(values); } RealVector result = v.copy(); Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final int index = e.getIndex(); v.setEntry(index, e.getValue() - result.getEntry(index)); } return result; } /** {@inheritDoc} */ public RealVector mapAdd(double d) { return copy().mapAddToSelf(d); } /** {@inheritDoc} */ public RealVector mapAddToSelf(double d) { if (d != 0) { try { return mapToSelf(BinaryFunction.ADD.fix1stArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } return this; } /** {@inheritDoc} */ public abstract AbstractRealVector copy(); /** {@inheritDoc} */ public double dotProduct(double[] v) throws IllegalArgumentException { return dotProduct(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public double dotProduct(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d += e.getValue() * v.getEntry(e.getIndex()); } return d; } /** {@inheritDoc} */ public RealVector ebeDivide(double[] v) throws IllegalArgumentException { return ebeDivide(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public RealVector ebeMultiply(double[] v) throws IllegalArgumentException { return ebeMultiply(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public double getDistance(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final double diff = e.getValue() - v.getEntry(e.getIndex()); d += diff * diff; } return Math.sqrt(d); } /** {@inheritDoc} */ public double getNorm() { double sum = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { final double value = e.getValue(); sum += value * value; } return Math.sqrt(sum); } /** {@inheritDoc} */ public double getL1Norm() { double norm = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { norm += Math.abs(e.getValue()); } return norm; } /** {@inheritDoc} */ public double getLInfNorm() { double norm = 0; Iterator<Entry> it = sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { norm = Math.max(norm, Math.abs(e.getValue())); } return norm; } /** {@inheritDoc} */ public double getDistance(double[] v) throws IllegalArgumentException { return getDistance(new ArrayRealVector(v,false)); } /** {@inheritDoc} */ public double getL1Distance(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d += Math.abs(e.getValue() - v.getEntry(e.getIndex())); } return d; } /** {@inheritDoc} */ public double getL1Distance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d += Math.abs(e.getValue() - v[e.getIndex()]); } return d; } /** {@inheritDoc} */ public double getLInfDistance(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d = Math.max(Math.abs(e.getValue() - v.getEntry(e.getIndex())), d); } return d; } /** {@inheritDoc} */ public double getLInfDistance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double d = 0; Iterator<Entry> it = iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { d = Math.max(Math.abs(e.getValue() - v[e.getIndex()]), d); } return d; } /** {@inheritDoc} */ public RealVector mapAbs() { return copy().mapAbsToSelf(); } /** {@inheritDoc} */ public RealVector mapAbsToSelf() { try { return mapToSelf(ComposableFunction.ABS); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapAcos() { return copy().mapAcosToSelf(); } /** {@inheritDoc} */ public RealVector mapAcosToSelf() { try { return mapToSelf(ComposableFunction.ACOS); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapAsin() { return copy().mapAsinToSelf(); } /** {@inheritDoc} */ public RealVector mapAsinToSelf() { try { return mapToSelf(ComposableFunction.ASIN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapAtan() { return copy().mapAtanToSelf(); } /** {@inheritDoc} */ public RealVector mapAtanToSelf() { try { return mapToSelf(ComposableFunction.ATAN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCbrt() { return copy().mapCbrtToSelf(); } /** {@inheritDoc} */ public RealVector mapCbrtToSelf() { try { return mapToSelf(ComposableFunction.CBRT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCeil() { return copy().mapCeilToSelf(); } /** {@inheritDoc} */ public RealVector mapCeilToSelf() { try { return mapToSelf(ComposableFunction.CEIL); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCos() { return copy().mapCosToSelf(); } /** {@inheritDoc} */ public RealVector mapCosToSelf() { try { return mapToSelf(ComposableFunction.COS); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapCosh() { return copy().mapCoshToSelf(); } /** {@inheritDoc} */ public RealVector mapCoshToSelf() { try { return mapToSelf(ComposableFunction.COSH); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapDivide(double d) { return copy().mapDivideToSelf(d); } /** {@inheritDoc} */ public RealVector mapDivideToSelf(double d){ try { return mapToSelf(BinaryFunction.DIVIDE.fix2ndArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapExp() { return copy().mapExpToSelf(); } /** {@inheritDoc} */ public RealVector mapExpToSelf() { try { return mapToSelf(ComposableFunction.EXP); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapExpm1() { return copy().mapExpm1ToSelf(); } /** {@inheritDoc} */ public RealVector mapExpm1ToSelf() { try { return mapToSelf(ComposableFunction.EXPM1); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapFloor() { return copy().mapFloorToSelf(); } /** {@inheritDoc} */ public RealVector mapFloorToSelf() { try { return mapToSelf(ComposableFunction.FLOOR); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapInv() { return copy().mapInvToSelf(); } /** {@inheritDoc} */ public RealVector mapInvToSelf() { try { return mapToSelf(ComposableFunction.INVERT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapLog() { return copy().mapLogToSelf(); } /** {@inheritDoc} */ public RealVector mapLogToSelf() { try { return mapToSelf(ComposableFunction.LOG); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapLog10() { return copy().mapLog10ToSelf(); } /** {@inheritDoc} */ public RealVector mapLog10ToSelf() { try { return mapToSelf(ComposableFunction.LOG10); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapLog1p() { return copy().mapLog1pToSelf(); } /** {@inheritDoc} */ public RealVector mapLog1pToSelf() { try { return mapToSelf(ComposableFunction.LOG1P); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapMultiply(double d) { return copy().mapMultiplyToSelf(d); } /** {@inheritDoc} */ public RealVector mapMultiplyToSelf(double d){ try { return mapToSelf(BinaryFunction.MULTIPLY.fix1stArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapPow(double d) { return copy().mapPowToSelf(d); } /** {@inheritDoc} */ public RealVector mapPowToSelf(double d){ try { return mapToSelf(BinaryFunction.POW.fix2ndArgument(d)); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapRint() { return copy().mapRintToSelf(); } /** {@inheritDoc} */ public RealVector mapRintToSelf() { try { return mapToSelf(ComposableFunction.RINT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSignum() { return copy().mapSignumToSelf(); } /** {@inheritDoc} */ public RealVector mapSignumToSelf() { try { return mapToSelf(ComposableFunction.SIGNUM); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSin() { return copy().mapSinToSelf(); } /** {@inheritDoc} */ public RealVector mapSinToSelf() { try { return mapToSelf(ComposableFunction.SIN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSinh() { return copy().mapSinhToSelf(); } /** {@inheritDoc} */ public RealVector mapSinhToSelf() { try { return mapToSelf(ComposableFunction.SINH); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSqrt() { return copy().mapSqrtToSelf(); } /** {@inheritDoc} */ public RealVector mapSqrtToSelf() { try { return mapToSelf(ComposableFunction.SQRT); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapSubtract(double d) { return copy().mapSubtractToSelf(d); } /** {@inheritDoc} */ public RealVector mapSubtractToSelf(double d){ return mapAddToSelf(-d); } /** {@inheritDoc} */ public RealVector mapTan() { return copy().mapTanToSelf(); } /** {@inheritDoc} */ public RealVector mapTanToSelf() { try { return mapToSelf(ComposableFunction.TAN); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapTanh() { return copy().mapTanhToSelf(); } /** {@inheritDoc} */ public RealVector mapTanhToSelf() { try { return mapToSelf(ComposableFunction.TANH); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealVector mapUlp() { return copy().mapUlpToSelf(); } /** {@inheritDoc} */ public RealVector mapUlpToSelf() { try { return mapToSelf(ComposableFunction.ULP); } catch (FunctionEvaluationException e) { throw new IllegalArgumentException(e); } } /** {@inheritDoc} */ public RealMatrix outerProduct(RealVector v) throws IllegalArgumentException { RealMatrix product; if (v instanceof SparseRealVector || this instanceof SparseRealVector) { product = new OpenMapRealMatrix(this.getDimension(), v.getDimension()); } else { product = new Array2DRowRealMatrix(this.getDimension(), v.getDimension()); } Iterator<Entry> thisIt = sparseIterator(); Entry thisE = null; while (thisIt.hasNext() && (thisE = thisIt.next()) != null) { Iterator<Entry> otherIt = v.sparseIterator(); Entry otherE = null; while (otherIt.hasNext() && (otherE = otherIt.next()) != null) { product.setEntry(thisE.getIndex(), otherE.getIndex(), thisE.getValue() * otherE.getValue()); } } return product; } /** {@inheritDoc} */ public RealMatrix outerProduct(double[] v) throws IllegalArgumentException { return outerProduct(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public RealVector projection(double[] v) throws IllegalArgumentException { return projection(new ArrayRealVector(v, false)); } /** {@inheritDoc} */ public void set(double value) { Iterator<Entry> it = iterator(); Entry e = null; while (it.hasNext() && (e = it.next()) != null) { e.setValue(value); } } /** {@inheritDoc} */ public double[] toArray() { int dim = getDimension(); double[] values = new double[dim]; for (int i = 0; i < dim; i++) { values[i] = getEntry(i); } return values; } /** {@inheritDoc} */ public double[] getData() { return toArray(); } /** {@inheritDoc} */ public RealVector unitVector() { RealVector copy = copy(); copy.unitize(); return copy; } /** {@inheritDoc} */ public void unitize() { mapDivideToSelf(getNorm()); } /** {@inheritDoc} */ public Iterator<Entry> sparseIterator() { return new SparseEntryIterator(); } /** {@inheritDoc} */ public Iterator<Entry> iterator() { final int dim = getDimension(); return new Iterator<Entry>() { /** Current index. */ private int i = 0; /** Current entry. */ private EntryImpl e = new EntryImpl(); /** {@inheritDoc} */ public boolean hasNext() { return i < dim; } /** {@inheritDoc} */ public Entry next() { e.setIndex(i++); return e; } /** {@inheritDoc} */ public void remove() { throw new UnsupportedOperationException("Not supported"); } }; } /** {@inheritDoc} */ public RealVector map(UnivariateRealFunction function) throws FunctionEvaluationException { return copy().mapToSelf(function); } /** {@inheritDoc} */ public RealVector mapToSelf(UnivariateRealFunction function) throws FunctionEvaluationException { Iterator<Entry> it = (function.value(0) == 0) ? sparseIterator() : iterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { e.setValue(function.value(e.getValue())); } return this; } /** An entry in the vector. */ protected class EntryImpl extends Entry { /** Simple constructor. */ public EntryImpl() { setIndex(0); } /** {@inheritDoc} */ @Override public double getValue() { return getEntry(getIndex()); } /** {@inheritDoc} */ @Override public void setValue(double newValue) { setEntry(getIndex(), newValue); } } /** * This class should rare be used, but is here to provide * a default implementation of sparseIterator(), which is implemented * by walking over the entries, skipping those whose values are the default one. * * Concrete subclasses which are SparseVector implementations should * make their own sparse iterator, not use this one. * * This implementation might be useful for ArrayRealVector, when expensive * operations which preserve the default value are to be done on the entries, * and the fraction of non-default values is small (i.e. someone took a * SparseVector, and passed it into the copy-constructor of ArrayRealVector) */ protected class SparseEntryIterator implements Iterator<Entry> { /** Dimension of the vector. */ private final int dim; /** Temporary entry (reused on each call to {@link #next()}. */ private EntryImpl tmp = new EntryImpl(); /** Current entry. */ private EntryImpl current; /** Next entry. */ private EntryImpl next; /** Simple constructor. */ protected SparseEntryIterator() { dim = getDimension(); current = new EntryImpl(); if (current.getValue() == 0) { advance(current); } if(current.getIndex() >= 0){ // There is at least one non-zero entry next = new EntryImpl(); next.setIndex(current.getIndex()); advance(next); } else { // The vector consists of only zero entries, so deny having a next current = null; } } /** Advance an entry up to the next non null one. * @param e entry to advance */ protected void advance(EntryImpl e) { if (e == null) { return; } do { e.setIndex(e.getIndex() + 1); } while (e.getIndex() < dim && e.getValue() == 0); if (e.getIndex() >= dim) { e.setIndex(-1); } } /** {@inheritDoc} */ public boolean hasNext() { return current != null; } /** {@inheritDoc} */ public Entry next() { tmp.setIndex(current.getIndex()); if (next != null) { current.setIndex(next.getIndex()); advance(next); if (next.getIndex() < 0) { next = null; } } else { current = null; } return tmp; } /** {@inheritDoc} */ public void remove() { throw new UnsupportedOperationException("Not supported"); } } }
SpoonLabs/astor
examples/math_74/src/main/java/org/apache/commons/math/linear/AbstractRealVector.java
Java
gpl-2.0
26,086
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.danaria; import com.aionemu.gameserver.dataholders.DataManager; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.model.TeleportAnimation; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.SystemMessageId; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAY_MOVIE; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; import com.aionemu.gameserver.services.instance.InstanceService; import com.aionemu.gameserver.services.teleport.TeleportService2; import com.aionemu.gameserver.utils.PacketSendUtility; import com.aionemu.gameserver.world.WorldMapInstance; /** * @author pralinka */ public class _20093FIAWOLFalsityIsAWayOfLife extends QuestHandler { private final static int questId = 20093; public _20093FIAWOLFalsityIsAWayOfLife() { super(questId); } @Override public void register() { qe.registerOnLevelUp(questId); qe.registerQuestNpc(800835).addOnTalkEvent(questId); // lucullus qe.registerQuestNpc(800839).addOnTalkEvent(questId); // runa qe.registerQuestNpc(800846).addOnTalkEvent(questId); // lucullus qe.registerQuestNpc(701558).addOnTalkEvent(questId); // Danuar Idgel // Cube qe.registerQuestNpc(800847).addOnTalkEvent(questId); // lucullus qe.registerQuestNpc(800848).addOnTalkEvent(questId); // skuldun qe.registerQuestNpc(800529).addOnTalkEvent(questId); // vard qe.registerQuestNpc(801328).addOnTalkEvent(questId); // marchutan qe.registerQuestNpc(230396).addOnKillEvent(questId); // Hyperion Defense // Officer qe.registerQuestNpc(230397).addOnKillEvent(questId); // Hyperion Rescue // Specialists qe.registerQuestNpc(230402).addOnKillEvent(questId); // Hiding Spirits qe.registerOnLogOut(questId); qe.registerOnDie(questId); } @Override public boolean onLvlUpEvent(QuestEnv env) { return defaultOnLvlUpEvent(env, 20092); } @Override public boolean onDieEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var > 0 && var < 13) { changeQuestStep(env, var, 0, false); return true; } } return false; } @Override public boolean onLogOutEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (var > 0 && var < 13) { changeQuestStep(env, var, 0, false); return true; } } return false; } @Override public boolean onDialogEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null) { return false; } DialogAction dialog = env.getDialog(); int targetId = env.getTargetId(); if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); switch (targetId) { case 800835: { // lucullus switch (dialog) { case QUEST_SELECT: { if (qs.getQuestVarById(0) == 0) { return sendQuestDialog(env, 1011); } } case SETPRO1: { WorldMapInstance newInstance = InstanceService.getNextAvailableInstance(300900000); InstanceService.registerPlayerWithInstance(newInstance, player); TeleportService2.teleportTo(player, 300900000, newInstance.getInstanceId(), 153, 143, 125); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800839, 146f, 144f, 125f, (byte) 119); return defaultCloseDialog(env, 0, 1); } default: break; } break; } case 800839: { // runa switch (dialog) { case QUEST_SELECT: { if (var == 4) { playQuestMovie(env, 856); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800846, 138f, 157f, 121f, (byte) 105); env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 4, 5); } } default: break; } break; } case 800846: { // lucullus switch (dialog) { case QUEST_SELECT: { if (var == 5) { return sendQuestDialog(env, 2034); } } case SETPRO4: { env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 5, 6); } default: break; } break; } case 701558: { // Danuar Idgel Cube switch (dialog) { case USE_OBJECT: { if (var == 6) { return sendQuestDialog(env, 2375); } else if (var == 11) { return sendQuestDialog(env, 3398); } } case SETPRO5: { QuestService.addNewSpawn(300900000, player.getInstanceId(), 230402, 116f, 137f, 113f, (byte) 119); QuestService.addNewSpawn(300900000, player.getInstanceId(), 230402, 117f, 145f, 113f, (byte) 119); QuestService.addNewSpawn(300900000, player.getInstanceId(), 230402, 119f, 139f, 112f, (byte) 49); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800847, 104f, 139f, 112f, (byte) 119); return defaultCloseDialog(env, 6, 7); } case SETPRO8: { playQuestMovie(env, 858); QuestService.addNewSpawn(300900000, player.getInstanceId(), 800848, 105f, 143f, 125f, (byte) 119); TeleportService2.teleportTo(player, 300900000, 109, 141, 125); return defaultCloseDialog(env, 11, 12); } default: break; } break; } case 800847: { // lucullus switch (dialog) { case QUEST_SELECT: { if (var == 10) { return sendQuestDialog(env, 3057); } } case SETPRO7: { env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 10, 11); } default: break; } break; } case 800848: { // skuldun switch (dialog) { case QUEST_SELECT: { if (var == 12) { return sendQuestDialog(env, 3739); } } case SETPRO9: { TeleportService2.teleportTo(player, 600050000, 416f, 424f, 289f, (byte) 0, TeleportAnimation.BEAM_ANIMATION); env.getVisibleObject().getController().delete(); return defaultCloseDialog(env, 12, 13); } default: break; } break; } case 800529: { // vard switch (dialog) { case QUEST_SELECT: { if (var == 13) { return sendQuestDialog(env, 4080); } } case SETPRO10: { return defaultCloseDialog(env, 13, 13, true, false); } default: break; } break; } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 801328) { // marchutan if (env.getDialog() == DialogAction.USE_OBJECT) { return sendQuestDialog(env, 10002); } else { return sendQuestEndDialog(env); } } } return false; } @Override public boolean onKillEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs == null || qs.getStatus() != QuestStatus.START) { return false; } int targetId = env.getTargetId(); int questVar = qs.getQuestVarById(0); if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } Npc npc = (Npc) env.getVisibleObject(); if (targetId == 230396 || targetId == 230397) { if (questVar >= 1 && questVar < 4) { qs.setQuestVarById(0, questVar + 1); updateQuestStatus(env); return true; } else if (questVar == 4) { changeQuestStep(env, 4, 5, false); } } else if (targetId == 230402) { if (questVar >= 7 && questVar < 10) { qs.setQuestVarById(0, questVar + 1); updateQuestStatus(env); return true; } else if (questVar == 10) { changeQuestStep(env, 10, 11, false); } } return false; } }
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/danaria/_20093FIAWOLFalsityIsAWayOfLife.java
Java
gpl-2.0
9,573
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package mysql5; import com.aionemu.commons.database.DB; import com.aionemu.commons.database.IUStH; import com.aionemu.gameserver.dao.MySQL5DAOUtils; import com.aionemu.gameserver.dao.OldNamesDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author synchro2 */ public class MySQL5OldNamesDAO extends OldNamesDAO { private static final Logger log = LoggerFactory.getLogger(MySQL5OldNamesDAO.class); private static final String INSERT_QUERY = "INSERT INTO `old_names` (`player_id`, `old_name`, `new_name`) VALUES (?,?,?)"; @Override public boolean isOldName(final String name) { PreparedStatement s = DB .prepareStatement("SELECT count(player_id) as cnt FROM old_names WHERE ? = old_names.old_name"); try { s.setString(1, name); ResultSet rs = s.executeQuery(); rs.next(); return rs.getInt("cnt") > 0; } catch (SQLException e) { log.error("Can't check if name " + name + ", is used, returning possitive result", e); return true; } finally { DB.close(s); } } @Override public void insertNames(final int id, final String oldname, final String newname) { DB.insertUpdate(INSERT_QUERY, new IUStH() { @Override public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); stmt.setString(2, oldname); stmt.setString(3, newname); stmt.execute(); } }); } /** * {@inheritDoc} */ @Override public boolean supports(String s, int i, int i1) { return MySQL5DAOUtils.supports(s, i, i1); } }
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/database/mysql5/MySQL5OldNamesDAO.java
Java
gpl-2.0
3,146
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ZoomOut = exports.ZoomIn = exports.SlideRight = exports.SlideLeft = undefined; var _slideLeft = require('./slide-left.scss'); var _slideLeft2 = _interopRequireDefault(_slideLeft); var _slideRight = require('./slide-right.scss'); var _slideRight2 = _interopRequireDefault(_slideRight); var _zoomIn = require('./zoom-in.scss'); var _zoomIn2 = _interopRequireDefault(_zoomIn); var _zoomOut = require('./zoom-out.scss'); var _zoomOut2 = _interopRequireDefault(_zoomOut); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.SlideLeft = _slideLeft2.default; exports.SlideRight = _slideRight2.default; exports.ZoomIn = _zoomIn2.default; exports.ZoomOut = _zoomOut2.default;
fonea/velon
themes/frontend/assets/vendor/node_modules/react-toolbox/lib/animations/index.js
JavaScript
gpl-2.0
816
namespace Siegfried { partial class ChoferesCatalogo { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // ChoferesCatalogo // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.ClientSize = new System.Drawing.Size(1008, 606); this.Name = "ChoferesCatalogo"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Catalogo de Choferes"; this.Load += new System.EventHandler(this.ChoferesCatalogo_Load); this.ResumeLayout(false); } #endregion } }
wlnaim/Siegfried
branches/EN/Siegfried/Siegfried/Catalogos/ChoferesCatalogo.Designer.cs
C#
gpl-2.0
1,305
/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "AggressorAI.h" #include "Errors.h" #include "Creature.h" #include "SharedDefines.h" #include "VMapFactory.h" #include "World.h" #include "DBCStores.h" #include "Map.h" #include <list> int AggressorAI::Permissible(const Creature* creature) { // have some hostile factions, it will be selected by IsHostileTo check at MoveInLineOfSight if (!(creature->GetCreatureInfo()->ExtraFlags & CREATURE_EXTRA_FLAG_NO_AGGRO) && !creature->IsNeutralToAll()) return PERMIT_BASE_PROACTIVE; return PERMIT_BASE_NO; } AggressorAI::AggressorAI(Creature* c) : CreatureAI(c), i_state(STATE_NORMAL), i_tracker(TIME_INTERVAL_LOOK) { } void AggressorAI::MoveInLineOfSight(Unit* u) { // Ignore Z for flying creatures if (!m_creature->CanFly() && m_creature->GetDistanceZ(u) > CREATURE_Z_ATTACK_RANGE) return; if (m_creature->CanInitiateAttack() && u->isTargetableForAttack() && m_creature->IsHostileTo(u) && u->isInAccessablePlaceFor(m_creature)) { float attackRadius = m_creature->GetAttackDistance(u); if (m_creature->IsWithinDistInMap(u, attackRadius) && m_creature->IsWithinLOSInMap(u)) { if (!m_creature->getVictim()) { AttackStart(u); u->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); } else if (sMapStore.LookupEntry(m_creature->GetMapId())->IsDungeon()) { m_creature->AddThreat(u); u->SetInCombatWith(m_creature); } } } } void AggressorAI::EnterEvadeMode() { if (!m_creature->isAlive()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, he is dead [guid=%u]", m_creature->GetGUIDLow()); i_victimGuid.Clear(); m_creature->CombatStop(true); m_creature->DeleteThreatList(); return; } Unit* victim = m_creature->GetMap()->GetUnit(i_victimGuid); if (!victim) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, no victim [guid=%u]", m_creature->GetGUIDLow()); } else if (!victim->isAlive()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is dead [guid=%u]", m_creature->GetGUIDLow()); } else if (victim->HasStealthAura()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in stealth [guid=%u]", m_creature->GetGUIDLow()); } else if (victim->IsTaxiFlying()) { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim is in flight [guid=%u]", m_creature->GetGUIDLow()); } else { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "Creature stopped attacking, victim out run him [guid=%u]", m_creature->GetGUIDLow()); // i_state = STATE_LOOK_AT_VICTIM; // i_tracker.Reset(TIME_INTERVAL_LOOK); } if (!m_creature->isCharmed()) { m_creature->RemoveAllAurasOnEvade(); // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) m_creature->GetMotionMaster()->MoveTargetedHome(); } m_creature->DeleteThreatList(); i_victimGuid.Clear(); m_creature->CombatStop(true); m_creature->SetLootRecipient(nullptr); } void AggressorAI::UpdateAI(const uint32 /*diff*/) { // update i_victimGuid if m_creature->getVictim() !=0 and changed if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; i_victimGuid = m_creature->getVictim()->GetObjectGuid(); DoMeleeAttackIfReady(); } bool AggressorAI::IsVisible(Unit* pl) const { return m_creature->IsWithinDist(pl, sWorld.getConfig(CONFIG_FLOAT_SIGHT_MONSTER)) && pl->isVisibleForOrDetect(m_creature, m_creature, true); } void AggressorAI::AttackStart(Unit* u) { if (!u) return; if (m_creature->Attack(u, true)) { i_victimGuid = u->GetObjectGuid(); m_creature->AddThreat(u); m_creature->SetInCombatWith(u); u->SetInCombatWith(m_creature); HandleMovementOnAttackStart(u); } }
51kfa/mangos-classic
src/game/AggressorAI.cpp
C++
gpl-2.0
5,084
<?php namespace Drupal\link\Plugin\Field\FieldType; use Drupal\Component\Utility\Random; use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\Core\Field\FieldItemBase; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\TypedData\DataDefinition; use Drupal\Core\TypedData\MapDataDefinition; use Drupal\Core\Url; use Drupal\link\LinkItemInterface; /** * Plugin implementation of the 'link' field type. * * @FieldType( * id = "link", * label = @Translation("Link"), * description = @Translation("Stores a URL string, optional varchar link text, and optional blob of attributes to assemble a link."), * default_widget = "link_default", * default_formatter = "link", * constraints = {"LinkType" = {}, "LinkAccess" = {}, "LinkExternalProtocols" = {}, "LinkNotExistingInternal" = {}} * ) */ class LinkItem extends FieldItemBase implements LinkItemInterface { /** * {@inheritdoc} */ public static function defaultFieldSettings() { return [ 'title' => DRUPAL_OPTIONAL, 'link_type' => LinkItemInterface::LINK_GENERIC, ] + parent::defaultFieldSettings(); } /** * {@inheritdoc} */ public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) { $properties['uri'] = DataDefinition::create('uri') ->setLabel(t('URI')); $properties['title'] = DataDefinition::create('string') ->setLabel(t('Link text')); $properties['options'] = MapDataDefinition::create() ->setLabel(t('Options')); return $properties; } /** * {@inheritdoc} */ public static function schema(FieldStorageDefinitionInterface $field_definition) { return [ 'columns' => [ 'uri' => [ 'description' => 'The URI of the link.', 'type' => 'varchar', 'length' => 2048, ], 'title' => [ 'description' => 'The link text.', 'type' => 'varchar', 'length' => 255, ], 'options' => [ 'description' => 'Serialized array of options for the link.', 'type' => 'blob', 'size' => 'big', 'serialize' => TRUE, ], ], 'indexes' => [ 'uri' => [['uri', 30]], ], ]; } /** * {@inheritdoc} */ public function fieldSettingsForm(array $form, FormStateInterface $form_state) { $element = []; $element['link_type'] = [ '#type' => 'radios', '#title' => t('Allowed link type'), '#default_value' => $this->getSetting('link_type'), '#options' => [ static::LINK_INTERNAL => t('Internal links only'), static::LINK_EXTERNAL => t('External links only'), static::LINK_GENERIC => t('Both internal and external links'), ], ]; $element['title'] = [ '#type' => 'radios', '#title' => t('Allow link text'), '#default_value' => $this->getSetting('title'), '#options' => [ DRUPAL_DISABLED => t('Disabled'), DRUPAL_OPTIONAL => t('Optional'), DRUPAL_REQUIRED => t('Required'), ], ]; return $element; } /** * {@inheritdoc} */ public static function generateSampleValue(FieldDefinitionInterface $field_definition) { $random = new Random(); if ($field_definition->getItemDefinition()->getSetting('link_type') & LinkItemInterface::LINK_EXTERNAL) { // Set of possible top-level domains. $tlds = ['com', 'net', 'gov', 'org', 'edu', 'biz', 'info']; // Set random length for the domain name. $domain_length = mt_rand(7, 15); switch ($field_definition->getSetting('title')) { case DRUPAL_DISABLED: $values['title'] = ''; break; case DRUPAL_REQUIRED: $values['title'] = $random->sentences(4); break; case DRUPAL_OPTIONAL: // In case of optional title, randomize its generation. $values['title'] = mt_rand(0, 1) ? $random->sentences(4) : ''; break; } $values['uri'] = 'http://www.' . $random->word($domain_length) . '.' . $tlds[mt_rand(0, (count($tlds) - 1))]; } else { $values['uri'] = 'base:' . $random->name(mt_rand(1, 64)); } return $values; } /** * {@inheritdoc} */ public function isEmpty() { $value = $this->get('uri')->getValue(); return $value === NULL || $value === ''; } /** * {@inheritdoc} */ public function isExternal() { return $this->getUrl()->isExternal(); } /** * {@inheritdoc} */ public static function mainPropertyName() { return 'uri'; } /** * {@inheritdoc} */ public function getUrl() { return Url::fromUri($this->uri, (array) $this->options); } /** * {@inheritdoc} */ public function setValue($values, $notify = TRUE) { // Treat the values as property value of the main property, if no array is // given. if (isset($values) && !is_array($values)) { $values = [static::mainPropertyName() => $values]; } if (isset($values)) { $values += [ 'options' => [], ]; } // Unserialize the values. // @todo The storage controller should take care of this, see // SqlContentEntityStorage::loadFieldItems, see // https://www.drupal.org/node/2414835 if (is_string($values['options'])) { if (version_compare(PHP_VERSION, '7.0.0', '>=')) { $values['options'] = unserialize($values['options'], ['allowed_classes' => FALSE]); } else { $values['options'] = unserialize($values['options']); } } parent::setValue($values, $notify); } }
eisbear2020/ZI
core/modules/link/src/Plugin/Field/FieldType/LinkItem.php
PHP
gpl-2.0
5,668
/* * This is the source code of Telegram for Android v. 1.3.2. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013. */ package org.telegram.ui; import android.content.Intent; import android.graphics.Point; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.view.Display; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.FileLog; import org.telegram.objects.PhotoObject; import org.telegram.ui.Views.AbstractGalleryActivity; import org.telegram.ui.Views.GalleryViewPager; import org.telegram.ui.Views.PZSImageView; import org.telegram.TL.TLRPC; import org.telegram.objects.MessageObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.Utilities; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; public class GalleryImageViewer extends AbstractGalleryActivity implements NotificationCenter.NotificationCenterDelegate { private TextView nameTextView; private TextView timeTextView; private View bottomView; private TextView fakeTitleView; private LocalPagerAdapter localPagerAdapter; private GalleryViewPager mViewPager; private boolean withoutBottom = false; private boolean fromAll = false; private boolean isVideo = false; private boolean needSearchMessage = false; private boolean loadingMore = false; private TextView title; private boolean ignoreSet = false; private ProgressBar loadingProgress; private String currentFileName; private int user_id = 0; private Point displaySize = new Point(); private boolean cancelRunning = false; private ArrayList<MessageObject> imagesArrTemp = new ArrayList<MessageObject>(); private HashMap<Integer, MessageObject> imagesByIdsTemp = new HashMap<Integer, MessageObject>(); private long currentDialog = 0; private int totalCount = 0; private int classGuid; private boolean firstLoad = true; private boolean cacheEndReached = false; public static int needShowAllMedia = 2000; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Display display = getWindowManager().getDefaultDisplay(); if(android.os.Build.VERSION.SDK_INT < 13) { displaySize.set(display.getWidth(), display.getHeight()); } else { display.getSize(displaySize); } classGuid = ConnectionsManager.Instance.generateClassGuid(); setContentView(R.layout.gallery_layout); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayUseLogoEnabled(false); actionBar.setTitle(getString(R.string.Gallery)); actionBar.show(); mViewPager = (GalleryViewPager)findViewById(R.id.gallery_view_pager); ImageView shareButton = (ImageView)findViewById(R.id.gallery_view_share_button); ImageView deleteButton = (ImageView) findViewById(R.id.gallery_view_delete_button); nameTextView = (TextView)findViewById(R.id.gallery_view_name_text); timeTextView = (TextView)findViewById(R.id.gallery_view_time_text); bottomView = findViewById(R.id.gallery_view_bottom_view); fakeTitleView = (TextView)findViewById(R.id.fake_title_view); loadingProgress = (ProgressBar)findViewById(R.id.action_progress); title = (TextView)findViewById(R.id.action_bar_title); if (title == null) { final int titleId = getResources().getIdentifier("action_bar_title", "id", "android"); title = (TextView)findViewById(titleId); } NotificationCenter.Instance.addObserver(this, FileLoader.FileDidFailedLoad); NotificationCenter.Instance.addObserver(this, FileLoader.FileDidLoaded); NotificationCenter.Instance.addObserver(this, FileLoader.FileLoadProgressChanged); NotificationCenter.Instance.addObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.Instance.addObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.Instance.addObserver(this, 658); Integer index = null; if (localPagerAdapter == null) { final MessageObject file = (MessageObject)NotificationCenter.Instance.getFromMemCache(51); final TLRPC.FileLocation fileLocation = (TLRPC.FileLocation)NotificationCenter.Instance.getFromMemCache(53); final ArrayList<MessageObject> messagesArr = (ArrayList<MessageObject>)NotificationCenter.Instance.getFromMemCache(54); index = (Integer)NotificationCenter.Instance.getFromMemCache(55); Integer uid = (Integer)NotificationCenter.Instance.getFromMemCache(56); if (uid != null) { user_id = uid; } if (file != null) { ArrayList<MessageObject> imagesArr = new ArrayList<MessageObject>(); HashMap<Integer, MessageObject> imagesByIds = new HashMap<Integer, MessageObject>(); imagesArr.add(file); if (file.messageOwner.action == null || file.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) { needSearchMessage = true; imagesByIds.put(file.messageOwner.id, file); if (file.messageOwner.dialog_id != 0) { currentDialog = file.messageOwner.dialog_id; } else { if (file.messageOwner.to_id.chat_id != 0) { currentDialog = -file.messageOwner.to_id.chat_id; } else { if (file.messageOwner.to_id.user_id == UserConfig.clientUserId) { currentDialog = file.messageOwner.from_id; } else { currentDialog = file.messageOwner.to_id.user_id; } } } } localPagerAdapter = new LocalPagerAdapter(imagesArr, imagesByIds); } else if (fileLocation != null) { ArrayList<TLRPC.FileLocation> arr = new ArrayList<TLRPC.FileLocation>(); arr.add(fileLocation); withoutBottom = true; deleteButton.setVisibility(View.INVISIBLE); nameTextView.setVisibility(View.INVISIBLE); timeTextView.setVisibility(View.INVISIBLE); localPagerAdapter = new LocalPagerAdapter(arr); } else if (messagesArr != null) { ArrayList<MessageObject> imagesArr = new ArrayList<MessageObject>(); HashMap<Integer, MessageObject> imagesByIds = new HashMap<Integer, MessageObject>(); imagesArr.addAll(messagesArr); Collections.reverse(imagesArr); for (MessageObject message : imagesArr) { imagesByIds.put(message.messageOwner.id, message); } index = imagesArr.size() - index - 1; MessageObject object = imagesArr.get(0); if (object.messageOwner.dialog_id != 0) { currentDialog = object.messageOwner.dialog_id; } else { if (object.messageOwner.to_id.chat_id != 0) { currentDialog = -object.messageOwner.to_id.chat_id; } else { if (object.messageOwner.to_id.user_id == UserConfig.clientUserId) { currentDialog = object.messageOwner.from_id; } else { currentDialog = object.messageOwner.to_id.user_id; } } } localPagerAdapter = new LocalPagerAdapter(imagesArr, imagesByIds); } } mViewPager.setPageMargin(Utilities.dp(20)); mViewPager.setOffscreenPageLimit(1); mViewPager.setAdapter(localPagerAdapter); if (index != null) { fromAll = true; mViewPager.setCurrentItem(index); } shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { TLRPC.FileLocation file = getCurrentFile(); File f = new File(Utilities.getCacheDir(), file.volume_id + "_" + file.local_id + ".jpg"); if (f.exists()) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f)); startActivity(intent); } } catch (Exception e) { FileLog.e("tmessages", e); } } }); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mViewPager == null || localPagerAdapter == null || localPagerAdapter.imagesArr == null) { return; } int item = mViewPager.getCurrentItem(); MessageObject obj = localPagerAdapter.imagesArr.get(item); if (obj.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENT) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(obj.messageOwner.id); MessagesController.Instance.deleteMessages(arr); finish(); } } }); if (currentDialog != 0 && totalCount == 0) { MessagesController.Instance.getMediaCount(currentDialog, classGuid, true); } if (user_id != 0) { MessagesController.Instance.loadUserPhotos(user_id, 0, 30, 0, true, classGuid); } checkCurrentFile(); } @Override protected void onDestroy() { super.onDestroy(); NotificationCenter.Instance.removeObserver(this, FileLoader.FileDidFailedLoad); NotificationCenter.Instance.removeObserver(this, FileLoader.FileDidLoaded); NotificationCenter.Instance.removeObserver(this, FileLoader.FileLoadProgressChanged); NotificationCenter.Instance.removeObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.Instance.removeObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.Instance.removeObserver(this, 658); ConnectionsManager.Instance.cancelRpcsForClassGuid(classGuid); } @SuppressWarnings("unchecked") @Override public void didReceivedNotification(int id, final Object... args) { if (id == FileLoader.FileDidFailedLoad) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { if (loadingProgress != null) { loadingProgress.setVisibility(View.GONE); } if (localPagerAdapter != null) { localPagerAdapter.updateViews(); } } } else if (id == FileLoader.FileDidLoaded) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { if (loadingProgress != null) { loadingProgress.setVisibility(View.GONE); } if (localPagerAdapter != null) { localPagerAdapter.updateViews(); } } } else if (id == FileLoader.FileLoadProgressChanged) { String location = (String)args[0]; if (currentFileName != null && currentFileName.equals(location)) { Float progress = (Float)args[1]; if (loadingProgress != null) { loadingProgress.setVisibility(View.VISIBLE); loadingProgress.setProgress((int)(progress * 100)); } if (localPagerAdapter != null) { localPagerAdapter.updateViews(); } } } else if (id == MessagesController.userPhotosLoaded) { int guid = (Integer)args[4]; int uid = (Integer)args[0]; if (user_id == uid && classGuid == guid) { boolean fromCache = (Boolean)args[3]; TLRPC.FileLocation currentLocation = null; int setToImage = -1; if (localPagerAdapter != null && mViewPager != null) { int idx = mViewPager.getCurrentItem(); if (localPagerAdapter.imagesArrLocations.size() > idx) { currentLocation = localPagerAdapter.imagesArrLocations.get(idx); } } ArrayList<TLRPC.Photo> photos = (ArrayList<TLRPC.Photo>)args[5]; if (photos.isEmpty()) { return; } ArrayList<TLRPC.FileLocation> arr = new ArrayList<TLRPC.FileLocation>(); for (TLRPC.Photo photo : photos) { if (photo instanceof TLRPC.TL_photoEmpty) { continue; } TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(photo.sizes, 800, 800); if (sizeFull != null) { if (currentLocation != null && sizeFull.location.local_id == currentLocation.local_id && sizeFull.location.volume_id == currentLocation.volume_id) { setToImage = arr.size(); } arr.add(sizeFull.location); } } mViewPager.setAdapter(null); int count = mViewPager.getChildCount(); for (int a = 0; a < count; a++) { View child = mViewPager.getChildAt(0); mViewPager.removeView(child); } mViewPager.mCurrentView = null; needSearchMessage = false; ignoreSet = true; mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(arr)); mViewPager.invalidate(); ignoreSet = false; if (setToImage != -1) { mViewPager.setCurrentItem(setToImage); } else { mViewPager.setCurrentItem(0); } if (fromCache) { MessagesController.Instance.loadUserPhotos(user_id, 0, 30, 0, false, classGuid); } } } else if (id == MessagesController.mediaCountDidLoaded) { long uid = (Long)args[0]; if (uid == currentDialog) { if ((int)currentDialog != 0) { boolean fromCache = (Boolean)args[2]; if (fromCache) { MessagesController.Instance.getMediaCount(currentDialog, classGuid, false); } } totalCount = (Integer)args[1]; if (needSearchMessage && firstLoad) { firstLoad = false; MessagesController.Instance.loadMedia(currentDialog, 0, 100, 0, true, classGuid); loadingMore = true; } else { if (mViewPager != null && localPagerAdapter != null && localPagerAdapter.imagesArr != null) { final int pos = (totalCount - localPagerAdapter.imagesArr.size()) + mViewPager.getCurrentItem() + 1; Utilities.RunOnUIThread(new Runnable() { @Override public void run() { getSupportActionBar().setTitle(String.format("%d %s %d", pos, getString(R.string.Of), totalCount)); if (title != null) { fakeTitleView.setText(String.format("%d %s %d", pos, getString(R.string.Of), totalCount)); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); } } }); } } } } else if (id == MessagesController.mediaDidLoaded) { long uid = (Long)args[0]; int guid = (Integer)args[4]; if (uid == currentDialog && guid == classGuid) { if (localPagerAdapter == null || localPagerAdapter.imagesArr == null) { return; } loadingMore = false; ArrayList<MessageObject> arr = (ArrayList<MessageObject>)args[2]; boolean fromCache = (Boolean)args[3]; cacheEndReached = !fromCache; if (needSearchMessage) { if (arr.isEmpty()) { needSearchMessage = false; return; } int foundIndex = -1; int index = mViewPager.getCurrentItem(); MessageObject currentMessage = localPagerAdapter.imagesArr.get(index); int added = 0; for (MessageObject message : arr) { if (!imagesByIdsTemp.containsKey(message.messageOwner.id)) { added++; imagesArrTemp.add(0, message); imagesByIdsTemp.put(message.messageOwner.id, message); if (message.messageOwner.id == currentMessage.messageOwner.id) { foundIndex = arr.size() - added; } } } if (added == 0) { totalCount = imagesArrTemp.size(); } if (foundIndex != -1) { mViewPager.setAdapter(null); int count = mViewPager.getChildCount(); for (int a = 0; a < count; a++) { View child = mViewPager.getChildAt(0); mViewPager.removeView(child); } mViewPager.mCurrentView = null; needSearchMessage = false; ignoreSet = true; mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(imagesArrTemp, imagesByIdsTemp)); mViewPager.invalidate(); ignoreSet = false; mViewPager.setCurrentItem(foundIndex); imagesArrTemp = null; imagesByIdsTemp = null; } else { if (!cacheEndReached || !arr.isEmpty()) { MessageObject lastMessage = imagesArrTemp.get(0); loadingMore = true; MessagesController.Instance.loadMedia(currentDialog, 0, 100, lastMessage.messageOwner.id, true, classGuid); } } } else { int added = 0; for (MessageObject message : arr) { if (!localPagerAdapter.imagesByIds.containsKey(message.messageOwner.id)) { added++; localPagerAdapter.imagesArr.add(0, message); localPagerAdapter.imagesByIds.put(message.messageOwner.id, message); } } if (arr.isEmpty() && !fromCache) { totalCount = arr.size(); } if (added != 0) { int current = mViewPager.getCurrentItem(); ignoreSet = true; imagesArrTemp = new ArrayList<MessageObject>(localPagerAdapter.imagesArr); imagesByIdsTemp = new HashMap<Integer, MessageObject>(localPagerAdapter.imagesByIds); mViewPager.setAdapter(localPagerAdapter = new LocalPagerAdapter(imagesArrTemp, imagesByIdsTemp)); mViewPager.invalidate(); ignoreSet = false; imagesArrTemp = null; imagesByIdsTemp = null; mViewPager.setCurrentItem(current + added); } else { totalCount = localPagerAdapter.imagesArr.size(); } } } } else if (id == 658) { try { if (!isFinishing()) { finish(); } } catch (Exception e) { e.printStackTrace(); } } } private TLRPC.FileLocation getCurrentFile() { if (mViewPager == null) { return null; } int item = mViewPager.getCurrentItem(); if (withoutBottom) { return localPagerAdapter.imagesArrLocations.get(item); } else { MessageObject message = localPagerAdapter.imagesArr.get(item); if (message.messageOwner instanceof TLRPC.TL_messageService) { if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { return message.messageOwner.action.newUserPhoto.photo_big; } else { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.action.photo.sizes, 800, 800); if (sizeFull != null) { return sizeFull.location; } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(message.messageOwner.media.photo.sizes, 800, 800); if (sizeFull != null) { return sizeFull.location; } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { return message.messageOwner.media.video.thumb.location; } } return null; } @Override public void topBtn() { if (getSupportActionBar().isShowing()) { getSupportActionBar().hide(); startViewAnimation(bottomView, false); } else { bottomView.setVisibility(View.VISIBLE); getSupportActionBar().show(); startViewAnimation(bottomView, true); } } @Override public void didShowMessageObject(MessageObject obj) { TLRPC.User user = MessagesController.Instance.users.get(obj.messageOwner.from_id); if (user != null) { nameTextView.setText(Utilities.formatName(user.first_name, user.last_name)); timeTextView.setText(Utilities.formatterYearMax.format(((long)obj.messageOwner.date) * 1000)); } else { nameTextView.setText(""); } isVideo = obj.messageOwner.media != null && obj.messageOwner.media instanceof TLRPC.TL_messageMediaVideo; if (obj.messageOwner instanceof TLRPC.TL_messageService) { if (obj.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { TLRPC.FileLocation file = obj.messageOwner.action.newUserPhoto.photo_big; currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; } else { ArrayList<TLRPC.PhotoSize> sizes = obj.messageOwner.action.photo.sizes; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); if (sizeFull != null) { currentFileName = sizeFull.location.volume_id + "_" + sizeFull.location.local_id + ".jpg"; } } } } else if (obj.messageOwner.media != null) { if (obj.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { currentFileName = obj.messageOwner.media.video.dc_id + "_" + obj.messageOwner.media.video.id + ".mp4"; } else if (obj.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { TLRPC.FileLocation file = getCurrentFile(); if (file != null) { currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; } else { currentFileName = null; } } } else { currentFileName = null; } checkCurrentFile(); supportInvalidateOptionsMenu(); } private void checkCurrentFile() { if (currentFileName != null) { File f = new File(Utilities.getCacheDir(), currentFileName); if (f.exists()) { loadingProgress.setVisibility(View.GONE); } else { loadingProgress.setVisibility(View.VISIBLE); Float progress = FileLoader.Instance.fileProgresses.get(currentFileName); if (progress != null) { loadingProgress.setProgress((int)(progress * 100)); } else { loadingProgress.setProgress(0); } } } else { loadingProgress.setVisibility(View.GONE); } if (isVideo) { if (!FileLoader.Instance.isLoadingFile(currentFileName)) { loadingProgress.setVisibility(View.GONE); } else { loadingProgress.setVisibility(View.VISIBLE); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if (withoutBottom) { inflater.inflate(R.menu.gallery_save_only_menu, menu); } else { if (isVideo) { inflater.inflate(R.menu.gallery_video_menu, menu); } else { inflater.inflate(R.menu.gallery_menu, menu); } } return super.onCreateOptionsMenu(menu); } @Override public void openOptionsMenu() { TLRPC.FileLocation file = getCurrentFile(); if (file != null) { File f = new File(Utilities.getCacheDir(), file.volume_id + "_" + file.local_id + ".jpg"); if (f.exists()) { super.openOptionsMenu(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); processSelectedMenu(itemId); return true; } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); fixLayout(); } private void fixLayout() { if (mViewPager != null) { ViewTreeObserver obs = mViewPager.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mViewPager.beginFakeDrag(); if (mViewPager.isFakeDragging()) { mViewPager.fakeDragBy(1); mViewPager.endFakeDrag(); } mViewPager.getViewTreeObserver().removeOnPreDrawListener(this); return false; } }); } } @Override public void onBackPressed() { super.onBackPressed(); cancelRunning = true; mViewPager.setAdapter(null); localPagerAdapter = null; finish(); System.gc(); } private void processSelectedMenu(int itemId) { switch (itemId) { case android.R.id.home: cancelRunning = true; mViewPager.setAdapter(null); localPagerAdapter = null; finish(); System.gc(); break; case R.id.gallery_menu_save: TLRPC.FileLocation file = getCurrentFile(); File f = new File(Utilities.getCacheDir(), file.volume_id + "_" + file.local_id + ".jpg"); File dstFile = Utilities.generatePicturePath(); try { Utilities.copyFile(f, dstFile); Utilities.addMediaToGallery(Uri.fromFile(dstFile)); } catch (Exception e) { FileLog.e("tmessages", e); } break; // case R.id.gallery_menu_send: { // Intent intent = new Intent(this, MessagesActivity.class); // intent.putExtra("onlySelect", true); // startActivityForResult(intent, 10); // break; // } case R.id.gallery_menu_showall: { if (fromAll) { finish(); } else { if (!localPagerAdapter.imagesArr.isEmpty() && currentDialog != 0) { finish(); NotificationCenter.Instance.postNotificationName(needShowAllMedia, currentDialog); } } } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 10) { int chatId = data.getIntExtra("chatId", 0); int userId = data.getIntExtra("userId", 0); int dialog_id = 0; if (chatId != 0) { dialog_id = -chatId; } else if (userId != 0) { dialog_id = userId; } TLRPC.FileLocation location = getCurrentFile(); if (dialog_id != 0 && location != null) { Intent intent = new Intent(GalleryImageViewer.this, ChatActivity.class); if (chatId != 0) { intent.putExtra("chatId", chatId); } else { intent.putExtra("userId", userId); } startActivity(intent); NotificationCenter.Instance.postNotificationName(MessagesController.closeChats); finish(); if (withoutBottom) { MessagesController.Instance.sendMessage(location, dialog_id); } else { int item = mViewPager.getCurrentItem(); MessageObject obj = localPagerAdapter.imagesArr.get(item); MessagesController.Instance.sendMessage(obj, dialog_id); } } } } } private void startViewAnimation(final View panel, boolean up) { Animation animation; if (!up) { animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { panel.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); animation.setDuration(400); } else { animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { panel.setVisibility(View.VISIBLE); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); animation.setDuration(100); } panel.startAnimation(animation); } public class LocalPagerAdapter extends PagerAdapter { public ArrayList<MessageObject> imagesArr; public HashMap<Integer, MessageObject> imagesByIds; private ArrayList<TLRPC.FileLocation> imagesArrLocations; public LocalPagerAdapter(ArrayList<MessageObject> _imagesArr, HashMap<Integer, MessageObject> _imagesByIds) { imagesArr = _imagesArr; imagesByIds = _imagesByIds; } public LocalPagerAdapter(ArrayList<TLRPC.FileLocation> locations) { imagesArrLocations = locations; } @Override public void setPrimaryItem(ViewGroup container, final int position, Object object) { super.setPrimaryItem(container, position, object); if (container == null || object == null || ignoreSet) { return; } ((GalleryViewPager) container).mCurrentView = (PZSImageView)((View) object).findViewById(R.id.page_image); if (imagesArr != null) { didShowMessageObject(imagesArr.get(position)); if (totalCount != 0 && !needSearchMessage) { if (imagesArr.size() < totalCount && !loadingMore && position < 5) { MessageObject lastMessage = imagesArr.get(0); MessagesController.Instance.loadMedia(currentDialog, 0, 100, lastMessage.messageOwner.id, !cacheEndReached, classGuid); loadingMore = true; } Utilities.RunOnUIThread(new Runnable() { @Override public void run() { getSupportActionBar().setTitle(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount)); if (title != null) { fakeTitleView.setText(String.format("%d %s %d", (totalCount - imagesArr.size()) + position + 1, getString(R.string.Of), totalCount)); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); } } }); } } else if (imagesArrLocations != null) { TLRPC.FileLocation file = imagesArrLocations.get(position); currentFileName = file.volume_id + "_" + file.local_id + ".jpg"; checkCurrentFile(); if (imagesArrLocations.size() > 1) { Utilities.RunOnUIThread(new Runnable() { @Override public void run() { getSupportActionBar().setTitle(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size())); if (title != null) { fakeTitleView.setText(String.format("%d %s %d", position + 1, getString(R.string.Of), imagesArrLocations.size())); fakeTitleView.measure(View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.AT_MOST)); title.setWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); title.setMaxWidth(fakeTitleView.getMeasuredWidth() + Utilities.dp(8)); } } }); } else { getSupportActionBar().setTitle(getString(R.string.Gallery)); } } } public void updateViews() { int count = mViewPager.getChildCount(); for (int a = 0; a < count; a++) { View v = mViewPager.getChildAt(a); final TextView playButton = (TextView)v.findViewById(R.id.action_button); MessageObject message = (MessageObject)playButton.getTag(); if (message != null) { processViews(playButton, message); } } } public void processViews(TextView playButton, MessageObject message) { if (message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SENDING && message.messageOwner.send_state != MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { playButton.setVisibility(View.VISIBLE); String fileName = message.messageOwner.media.video.dc_id + "_" + message.messageOwner.media.video.id + ".mp4"; boolean load = false; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); if (f.exists()) { playButton.setText(getString(R.string.ViewVideo)); } else { load = true; } } else { File cacheFile = new File(Utilities.getCacheDir(), fileName); if (cacheFile.exists()) { playButton.setText(getString(R.string.ViewVideo)); } else { load = true; } } if (load) { Float progress = FileLoader.Instance.fileProgresses.get(fileName); if (FileLoader.Instance.isLoadingFile(fileName)) { playButton.setText(R.string.CancelDownload); } else { playButton.setText(String.format("%s %.1f MB", getString(R.string.DOWNLOAD), message.messageOwner.media.video.size / 1024.0f / 1024.0f)); } } } } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public Object instantiateItem(View collection, int position) { View view = View.inflate(collection.getContext(), R.layout.gallery_page_layout, null); ((ViewPager) collection).addView(view, 0); PZSImageView iv = (PZSImageView)view.findViewById(R.id.page_image); final TextView playButton = (TextView)view.findViewById(R.id.action_button); if (imagesArr != null) { final MessageObject message = imagesArr.get(position); view.setTag(message.messageOwner.id); if (message.messageOwner instanceof TLRPC.TL_messageService) { if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { iv.isVideo = false; iv.setImage(message.messageOwner.action.newUserPhoto.photo_big, null, 0, -1); } else { ArrayList<TLRPC.PhotoSize> sizes = message.messageOwner.action.photo.sizes; iv.isVideo = false; if (sizes.size() > 0) { TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, 800, 800); if (message.imagePreview != null) { iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); } else { iv.setImage(sizeFull.location, null, 0, sizeFull.size); } } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { ArrayList<TLRPC.PhotoSize> sizes = message.messageOwner.media.photo.sizes; iv.isVideo = false; if (sizes.size() > 0) { int width = (int)(Math.min(displaySize.x, displaySize.y) * 0.7f); int height = width + Utilities.dp(100); if (width > 800) { width = 800; } if (height > 800) { height = 800; } TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(sizes, width, height); if (message.imagePreview != null) { iv.setImage(sizeFull.location, null, message.imagePreview, sizeFull.size); } else { iv.setImage(sizeFull.location, null, 0, sizeFull.size); } } } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { processViews(playButton, message); playButton.setTag(message); playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean loadFile = false; String fileName = message.messageOwner.media.video.dc_id + "_" + message.messageOwner.media.video.id + ".mp4"; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { File f = new File(message.messageOwner.attachPath); if (f.exists()) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(f), "video/mp4"); startActivity(intent); } else { loadFile = true; } } else { File cacheFile = new File(Utilities.getCacheDir(), fileName); if (cacheFile.exists()) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(cacheFile), "video/mp4"); startActivity(intent); } else { loadFile = true; } } if (loadFile) { if (!FileLoader.Instance.isLoadingFile(fileName)) { FileLoader.Instance.loadFile(message.messageOwner.media.video, null, null, null); } else { FileLoader.Instance.cancelLoadFile(message.messageOwner.media.video, null, null, null); } checkCurrentFile(); processViews(playButton, message); } } }); iv.isVideo = true; if (message.messageOwner.media.video.thumb instanceof TLRPC.TL_photoCachedSize) { iv.setImageBitmap(message.imagePreview); } else { if (message.messageOwner.media.video.thumb != null) { iv.setImage(message.messageOwner.media.video.thumb.location, null, 0, message.messageOwner.media.video.thumb.size); } } } } else { iv.isVideo = false; iv.setImage(imagesArrLocations.get(position), null, 0, -1); } return view; } @Override public void destroyItem(View collection, int position, Object view) { ((ViewPager)collection).removeView((View)view); PZSImageView iv = (PZSImageView)((View)view).findViewById(R.id.page_image); if (cancelRunning) { FileLoader.Instance.cancelLoadingForImageView(iv); } iv.clearImage(); } @Override public int getCount() { if (imagesArr != null) { return imagesArr.size(); } else if (imagesArrLocations != null) { return imagesArrLocations.size(); } else { return 0; } } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } @Override public void finishUpdate(View container) { } @Override public void startUpdate(View container) { } } }
staltz/Telegram
TMessagesProj/src/main/java/org/telegram/ui/GalleryImageViewer.java
Java
gpl-2.0
47,755
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.dao; import java.util.List; import javax.persistence.Query; import org.oscarehr.common.model.IncomingLabRules; import org.oscarehr.common.model.Provider; import org.springframework.stereotype.Repository; @Repository public class IncomingLabRulesDao extends AbstractDao<IncomingLabRules>{ public IncomingLabRulesDao() { super(IncomingLabRules.class); } public List<IncomingLabRules> findCurrentByProviderNoAndFrwdProvider(String providerNo, String frwdProvider) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1 and i.frwdProviderNo=?2 and i.archive=?3"); q.setParameter(1, providerNo); q.setParameter(2, frwdProvider); q.setParameter(3, "0"); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } public List<IncomingLabRules> findByProviderNoAndFrwdProvider(String providerNo, String frwdProvider) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1 and i.frwdProviderNo=?2"); q.setParameter(1, providerNo); q.setParameter(2, frwdProvider); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } public List<IncomingLabRules> findCurrentByProviderNo(String providerNo) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1 and i.archive=?2"); q.setParameter(1, providerNo); q.setParameter(2, "0"); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } public List<IncomingLabRules> findByProviderNo(String providerNo) { Query q = entityManager.createQuery("select i from IncomingLabRules i where i.providerNo=?1"); q.setParameter(1, providerNo); @SuppressWarnings("unchecked") List<IncomingLabRules> results = q.getResultList(); return results; } /** * @param providerNo * @return * Returns a list of pairs {@link IncomingLabRules}, {@link Provider} */ @SuppressWarnings("unchecked") public List<Object[]> findRules(String providerNo) { // assume archive represents boolean with 0 == false and 1 == true Query q = entityManager.createQuery("FROM IncomingLabRules i, " + Provider.class.getSimpleName() + " p " + "WHERE i.archive <> '1' " + // non-archived rules "AND i.providerNo = :providerNo " + "AND p.id = i.frwdProviderNo"); q.setParameter("providerNo", providerNo); return q.getResultList(); } }
hexbinary/landing
src/main/java/org/oscarehr/common/dao/IncomingLabRulesDao.java
Java
gpl-2.0
3,562
<?php /* * @version $Id: softwarelicensetype.tabs.php 14684 2011-06-11 06:32:40Z remi $ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2011 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI 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. GLPI 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 GLPI; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -------------------------------------------------------------------------- */ // ---------------------------------------------------------------------- // Original Author of file: // Purpose of file: // ---------------------------------------------------------------------- define('GLPI_ROOT', '..'); include (GLPI_ROOT . "/inc/includes.php"); $dropdown = new SoftwareLicenseType(); include (GLPI_ROOT . "/ajax/dropdown.common.tabs.php"); ?>
ardowz/Thesis-SideB
ajax/softwarelicensetype.tabs.php
PHP
gpl-2.0
1,549
<?php /** * The default template for displaying content * * Used for both single and index/archive/search. * * @package WordPress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php // Post thumbnail. //twentyfifteen_post_thumbnail(); ?> <header class="entry-header"> <?php if ( is_single() ) : the_title( '<h1 class="entry-title">', '</h1>' ); else : the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); endif; ?> </header><!-- .entry-header --> <div class="entry-content"> <?php /* translators: %s: Name of current post */ the_content( sprintf( __( 'Continue reading %s', 'twentyfifteen' ), the_title( '<span class="screen-reader-text">', '</span>', false ) ) ); wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentyfifteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', 'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>%', 'separator' => '<span class="screen-reader-text">, </span>', ) ); ?> </div><!-- .entry-content --> <?php // Author bio. if ( is_single() && get_the_author_meta( 'description' ) ) : get_template_part( 'author-bio' ); endif; ?> <footer class="entry-footer"> <?php //twentyfifteen_entry_meta(); ?> <?php edit_post_link( __( 'Edit', 'twentyfifteen' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-footer --> </article><!-- #post-## -->
maamunrcdergo/Richard_joseph
wp-content/themes/medical-clinic/content.php
PHP
gpl-2.0
1,706
/* * Ext JS Library 2.1 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.Component * @extends Ext.util.Observable * <p>Base class for all Ext components. All subclasses of Component can automatically participate in the standard * Ext component lifecycle of creation, rendering and destruction. They also have automatic support for basic hide/show * and enable/disable behavior. Component allows any subclass to be lazy-rendered into any {@link Ext.Container} and * to be automatically registered with the {@link Ext.ComponentMgr} so that it can be referenced at any time via * {@link Ext#getCmp}. All visual widgets that require rendering into a layout should subclass Component (or * {@link Ext.BoxComponent} if managed box model handling is required).</p> * <p>Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the * xtype like {@link #getXType} and {@link #isXType}. This is the list of all valid xtypes:</p> * <pre> xtype Class ------------- ------------------ box Ext.BoxComponent button Ext.Button colorpalette Ext.ColorPalette component Ext.Component container Ext.Container cycle Ext.CycleButton dataview Ext.DataView datepicker Ext.DatePicker editor Ext.Editor editorgrid Ext.grid.EditorGridPanel grid Ext.grid.GridPanel paging Ext.PagingToolbar panel Ext.Panel progress Ext.ProgressBar propertygrid Ext.grid.PropertyGrid slider Ext.Slider splitbutton Ext.SplitButton statusbar Ext.StatusBar tabpanel Ext.TabPanel treepanel Ext.tree.TreePanel viewport Ext.Viewport window Ext.Window Toolbar components --------------------------------------- toolbar Ext.Toolbar tbbutton Ext.Toolbar.Button tbfill Ext.Toolbar.Fill tbitem Ext.Toolbar.Item tbseparator Ext.Toolbar.Separator tbspacer Ext.Toolbar.Spacer tbsplit Ext.Toolbar.SplitButton tbtext Ext.Toolbar.TextItem Form components --------------------------------------- form Ext.FormPanel checkbox Ext.form.Checkbox combo Ext.form.ComboBox datefield Ext.form.DateField field Ext.form.Field fieldset Ext.form.FieldSet hidden Ext.form.Hidden htmleditor Ext.form.HtmlEditor label Ext.form.Label numberfield Ext.form.NumberField radio Ext.form.Radio textarea Ext.form.TextArea textfield Ext.form.TextField timefield Ext.form.TimeField trigger Ext.form.TriggerField </pre> * @constructor * @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component. */ Ext.Component = function(config){ config = config || {}; if(config.initialConfig){ if(config.isAction){ // actions this.baseAction = config; } config = config.initialConfig; // component cloning / action set up }else if(config.tagName || config.dom || typeof config == "string"){ // element object config = {applyTo: config, id: config.id || config}; } /** * This Component's initial configuration specification. Read-only. * @type Object * @property initialConfig */ this.initialConfig = config; Ext.apply(this, config); this.addEvents( /** * @event disable * Fires after the component is disabled. * @param {Ext.Component} this */ 'disable', /** * @event enable * Fires after the component is enabled. * @param {Ext.Component} this */ 'enable', /** * @event beforeshow * Fires before the component is shown. Return false to stop the show. * @param {Ext.Component} this */ 'beforeshow', /** * @event show * Fires after the component is shown. * @param {Ext.Component} this */ 'show', /** * @event beforehide * Fires before the component is hidden. Return false to stop the hide. * @param {Ext.Component} this */ 'beforehide', /** * @event hide * Fires after the component is hidden. * @param {Ext.Component} this */ 'hide', /** * @event beforerender * Fires before the component is rendered. Return false to stop the render. * @param {Ext.Component} this */ 'beforerender', /** * @event render * Fires after the component is rendered. * @param {Ext.Component} this */ 'render', /** * @event beforedestroy * Fires before the component is destroyed. Return false to stop the destroy. * @param {Ext.Component} this */ 'beforedestroy', /** * @event destroy * Fires after the component is destroyed. * @param {Ext.Component} this */ 'destroy', /** * @event beforestaterestore * Fires before the state of the component is restored. Return false to stop the restore. * @param {Ext.Component} this * @param {Object} state The hash of state values */ 'beforestaterestore', /** * @event staterestore * Fires after the state of the component is restored. * @param {Ext.Component} this * @param {Object} state The hash of state values */ 'staterestore', /** * @event beforestatesave * Fires before the state of the component is saved to the configured state provider. Return false to stop the save. * @param {Ext.Component} this * @param {Object} state The hash of state values */ 'beforestatesave', /** * @event statesave * Fires after the state of the component is saved to the configured state provider. * @param {Ext.Component} this * @param {Object} state The hash of state values */ 'statesave' ); this.getId(); Ext.ComponentMgr.register(this); Ext.Component.superclass.constructor.call(this); if(this.baseAction){ this.baseAction.addComponent(this); } this.initComponent(); if(this.plugins){ if(Ext.isArray(this.plugins)){ for(var i = 0, len = this.plugins.length; i < len; i++){ this.plugins[i].init(this); } }else{ this.plugins.init(this); } } if(this.stateful !== false){ this.initState(config); } if(this.applyTo){ this.applyToMarkup(this.applyTo); delete this.applyTo; }else if(this.renderTo){ this.render(this.renderTo); delete this.renderTo; } }; // private Ext.Component.AUTO_ID = 1000; Ext.extend(Ext.Component, Ext.util.Observable, { /** * @cfg {String} id * The unique id of this component (defaults to an auto-assigned id). */ /** * @cfg {String/Object} autoEl * A tag name or DomHelper spec to create an element with. This is intended to create shorthand * utility components inline via JSON. It should not be used for higher level components which already create * their own elements. Example usage: * <pre><code> {xtype:'box', autoEl: 'div', cls:'my-class'} {xtype:'box', autoEl: {tag:'blockquote', html:'autoEl is cool!'}} // with DomHelper </code></pre> */ /** * @cfg {String} xtype * The registered xtype to create. This config option is not used when passing * a config object into a constructor. This config option is used only when * lazy instantiation is being used, and a child item of a Container is being * specified not as a fully instantiated Component, but as a <i>Component config * object</i>. The xtype will be looked up at render time up to determine what * type of child Component to create.<br><br> * The predefined xtypes are listed {@link Ext.Component here}. * <br><br> * If you subclass Components to create your own Components, you may register * them using {@link Ext.ComponentMgr#registerType} in order to be able to * take advantage of lazy instantiation and rendering. */ /** * @cfg {String} cls * An optional extra CSS class that will be added to this component's Element (defaults to ''). This can be * useful for adding customized styles to the component or any of its children using standard CSS rules. */ /** * @cfg {String} overCls * An optional extra CSS class that will be added to this component's Element when the mouse moves * over the Element, and removed when the mouse moves out. (defaults to ''). This can be * useful for adding customized "active" or "hover" styles to the component or any of its children using standard CSS rules. */ /** * @cfg {String} style * A custom style specification to be applied to this component's Element. Should be a valid argument to * {@link Ext.Element#applyStyles}. */ /** * @cfg {String} ctCls * An optional extra CSS class that will be added to this component's container (defaults to ''). This can be * useful for adding customized styles to the container or any of its children using standard CSS rules. */ /** * @cfg {Object/Array} plugins * An object or array of objects that will provide custom functionality for this component. The only * requirement for a valid plugin is that it contain an init method that accepts a reference of type Ext.Component. * When a component is created, if any plugins are available, the component will call the init method on each * plugin, passing a reference to itself. Each plugin can then call methods or respond to events on the * component as needed to provide its functionality. */ /** * @cfg {Mixed} applyTo * The id of the node, a DOM node or an existing Element corresponding to a DIV that is already present in * the document that specifies some structural markup for this component. When applyTo is used, constituent parts of * the component can also be specified by id or CSS class name within the main element, and the component being created * may attempt to create its subcomponents from that markup if applicable. Using this config, a call to render() is * not required. If applyTo is specified, any value passed for {@link #renderTo} will be ignored and the target * element's parent node will automatically be used as the component's container. */ /** * @cfg {Mixed} renderTo * The id of the node, a DOM node or an existing Element that will be the container to render this component into. * Using this config, a call to render() is not required. */ /** * @cfg {Boolean} stateful * A flag which causes the Component to attempt to restore the state of internal properties * from a saved state on startup.<p> * For state saving to work, the state manager's provider must have been set to an implementation * of {@link Ext.state.Provider} which overrides the {@link Ext.state.Provider#set set} * and {@link Ext.state.Provider#get get} methods to save and recall name/value pairs. * A built-in implementation, {@link Ext.state.CookieProvider} is available.</p> * <p>To set the state provider for the current page:</p> * <pre><code> Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); </code></pre> * <p>Components attempt to save state when one of the events listed in the {@link #stateEvents} * configuration fires.</p> * <p>You can perform extra processing on state save and restore by attaching handlers to the * {@link #beforestaterestore}, {@link staterestore}, {@link beforestatesave} and {@link statesave} events</p> */ /** * @cfg {String} stateId * The unique id for this component to use for state management purposes (defaults to the component id). * <p>See {@link #stateful} for an explanation of saving and restoring Component state.</p> */ /* //internal - to be set by subclasses * @cfg {Array} stateEvents * An array of events that, when fired, should trigger this component to save its state (defaults to none). * These can be any types of events supported by this component, including browser or custom events (e.g., * ['click', 'customerchange']). * <p>See {@link #stateful} for an explanation of saving and restoring Component state.</p> */ /** * @cfg {String} disabledClass * CSS class added to the component when it is disabled (defaults to "x-item-disabled"). */ disabledClass : "x-item-disabled", /** * @cfg {Boolean} allowDomMove * Whether the component can move the Dom node when rendering (defaults to true). */ allowDomMove : true, /** * @cfg {Boolean} autoShow * True if the component should check for hidden classes (e.g. 'x-hidden' or 'x-hide-display') and remove * them on render (defaults to false). */ autoShow : false, /** * @cfg {String} hideMode * How this component should hidden. Supported values are "visibility" (css visibility), "offsets" (negative * offset position) and "display" (css display) - defaults to "display". */ hideMode: 'display', /** * @cfg {Boolean} hideParent * True to hide and show the component's container when hide/show is called on the component, false to hide * and show the component itself (defaults to false). For example, this can be used as a shortcut for a hide * button on a window by setting hide:true on the button when adding it to its parent container. */ hideParent: false, /** * The component's owner {@link Ext.Container} (defaults to undefined, and is set automatically when * the component is added to a container). Read-only. * @type Ext.Container * @property ownerCt */ /** * True if this component is hidden. Read-only. * @type Boolean * @property */ hidden : false, /** * True if this component is disabled. Read-only. * @type Boolean * @property */ disabled : false, /** * True if this component has been rendered. Read-only. * @type Boolean * @property */ rendered : false, // private ctype : "Ext.Component", // private actionMode : "el", // private getActionEl : function(){ return this[this.actionMode]; }, /* // protected * Function to be implemented by Component subclasses to be part of standard component initialization flow (it is empty by default). * <pre><code> // Traditional constructor: Ext.Foo = function(config){ // call superclass constructor: Ext.Foo.superclass.constructor.call(this, config); this.addEvents({ // add events }); }; Ext.extend(Ext.Foo, Ext.Bar, { // class body } // initComponent replaces the constructor: Ext.Foo = Ext.extend(Ext.Bar, { initComponent : function(){ // call superclass initComponent Ext.Container.superclass.initComponent.call(this); this.addEvents({ // add events }); } } </code></pre> */ initComponent : Ext.emptyFn, /** * If this is a lazy rendering component, render it to its container element. * @param {Mixed} container (optional) The element this component should be rendered into. If it is being * applied to existing markup, this should be left off. * @param {String/Number} position (optional) The element ID or DOM node index within the container <b>before</b> * which this component will be inserted (defaults to appending to the end of the container) */ render : function(container, position){ if(!this.rendered && this.fireEvent("beforerender", this) !== false){ if(!container && this.el){ this.el = Ext.get(this.el); container = this.el.dom.parentNode; this.allowDomMove = false; } this.container = Ext.get(container); if(this.ctCls){ this.container.addClass(this.ctCls); } this.rendered = true; if(position !== undefined){ if(typeof position == 'number'){ position = this.container.dom.childNodes[position]; }else{ position = Ext.getDom(position); } } this.onRender(this.container, position || null); if(this.autoShow){ this.el.removeClass(['x-hidden','x-hide-' + this.hideMode]); } if(this.cls){ this.el.addClass(this.cls); delete this.cls; } if(this.style){ this.el.applyStyles(this.style); delete this.style; } this.fireEvent("render", this); this.afterRender(this.container); if(this.hidden){ this.hide(); } if(this.disabled){ this.disable(); } this.initStateEvents(); } return this; }, // private initState : function(config){ if(Ext.state.Manager){ var state = Ext.state.Manager.get(this.stateId || this.id); if(state){ if(this.fireEvent('beforestaterestore', this, state) !== false){ this.applyState(state); this.fireEvent('staterestore', this, state); } } } }, // private initStateEvents : function(){ if(this.stateEvents){ for(var i = 0, e; e = this.stateEvents[i]; i++){ this.on(e, this.saveState, this, {delay:100}); } } }, // private applyState : function(state, config){ if(state){ Ext.apply(this, state); } }, // private getState : function(){ return null; }, // private saveState : function(){ if(Ext.state.Manager){ var state = this.getState(); if(this.fireEvent('beforestatesave', this, state) !== false){ Ext.state.Manager.set(this.stateId || this.id, state); this.fireEvent('statesave', this, state); } } }, /** * Apply this component to existing markup that is valid. With this function, no call to render() is required. * @param {String/HTMLElement} el */ applyToMarkup : function(el){ this.allowDomMove = false; this.el = Ext.get(el); this.render(this.el.dom.parentNode); }, /** * Adds a CSS class to the component's underlying element. * @param {string} cls The CSS class name to add */ addClass : function(cls){ if(this.el){ this.el.addClass(cls); }else{ this.cls = this.cls ? this.cls + ' ' + cls : cls; } }, /** * Removes a CSS class from the component's underlying element. * @param {string} cls The CSS class name to remove */ removeClass : function(cls){ if(this.el){ this.el.removeClass(cls); }else if(this.cls){ this.cls = this.cls.split(' ').remove(cls).join(' '); } }, // private // default function is not really useful onRender : function(ct, position){ if(this.autoEl){ if(typeof this.autoEl == 'string'){ this.el = document.createElement(this.autoEl); }else{ var div = document.createElement('div'); Ext.DomHelper.overwrite(div, this.autoEl); this.el = div.firstChild; } if (!this.el.id) { this.el.id = this.getId(); } } if(this.el){ this.el = Ext.get(this.el); if(this.allowDomMove !== false){ ct.dom.insertBefore(this.el.dom, position); } if(this.overCls) { this.el.addClassOnOver(this.overCls); } } }, // private getAutoCreate : function(){ var cfg = typeof this.autoCreate == "object" ? this.autoCreate : Ext.apply({}, this.defaultAutoCreate); if(this.id && !cfg.id){ cfg.id = this.id; } return cfg; }, // private afterRender : Ext.emptyFn, /** * Destroys this component by purging any event listeners, removing the component's element from the DOM, * removing the component from its {@link Ext.Container} (if applicable) and unregistering it from * {@link Ext.ComponentMgr}. Destruction is generally handled automatically by the framework and this method * should usually not need to be called directly. */ destroy : function(){ if(this.fireEvent("beforedestroy", this) !== false){ this.beforeDestroy(); if(this.rendered){ this.el.removeAllListeners(); this.el.remove(); if(this.actionMode == "container"){ this.container.remove(); } } this.onDestroy(); Ext.ComponentMgr.unregister(this); this.fireEvent("destroy", this); this.purgeListeners(); } }, // private beforeDestroy : Ext.emptyFn, // private onDestroy : Ext.emptyFn, /** * Returns the underlying {@link Ext.Element}. * @return {Ext.Element} The element */ getEl : function(){ return this.el; }, /** * Returns the id of this component. * @return {String} */ getId : function(){ return this.id || (this.id = "ext-comp-" + (++Ext.Component.AUTO_ID)); }, /** * Returns the item id of this component. * @return {String} */ getItemId : function(){ return this.itemId || this.getId(); }, /** * Try to focus this component. * @param {Boolean} selectText (optional) If applicable, true to also select the text in this component * @param {Boolean/Number} delay (optional) Delay the focus this number of milliseconds (true for 10 milliseconds) * @return {Ext.Component} this */ focus : function(selectText, delay){ if(delay){ this.focus.defer(typeof delay == 'number' ? delay : 10, this, [selectText, false]); return; } if(this.rendered){ this.el.focus(); if(selectText === true){ this.el.dom.select(); } } return this; }, // private blur : function(){ if(this.rendered){ this.el.blur(); } return this; }, /** * Disable this component. * @return {Ext.Component} this */ disable : function(){ if(this.rendered){ this.onDisable(); } this.disabled = true; this.fireEvent("disable", this); return this; }, // private onDisable : function(){ this.getActionEl().addClass(this.disabledClass); this.el.dom.disabled = true; }, /** * Enable this component. * @return {Ext.Component} this */ enable : function(){ if(this.rendered){ this.onEnable(); } this.disabled = false; this.fireEvent("enable", this); return this; }, // private onEnable : function(){ this.getActionEl().removeClass(this.disabledClass); this.el.dom.disabled = false; }, /** * Convenience function for setting disabled/enabled by boolean. * @param {Boolean} disabled */ setDisabled : function(disabled){ this[disabled ? "disable" : "enable"](); }, /** * Show this component. * @return {Ext.Component} this */ show: function(){ if(this.fireEvent("beforeshow", this) !== false){ this.hidden = false; if(this.autoRender){ this.render(typeof this.autoRender == 'boolean' ? Ext.getBody() : this.autoRender); } if(this.rendered){ this.onShow(); } this.fireEvent("show", this); } return this; }, // private onShow : function(){ if(this.hideParent){ this.container.removeClass('x-hide-' + this.hideMode); }else{ this.getActionEl().removeClass('x-hide-' + this.hideMode); } }, /** * Hide this component. * @return {Ext.Component} this */ hide: function(){ if(this.fireEvent("beforehide", this) !== false){ this.hidden = true; if(this.rendered){ this.onHide(); } this.fireEvent("hide", this); } return this; }, // private onHide : function(){ if(this.hideParent){ this.container.addClass('x-hide-' + this.hideMode); }else{ this.getActionEl().addClass('x-hide-' + this.hideMode); } }, /** * Convenience function to hide or show this component by boolean. * @param {Boolean} visible True to show, false to hide * @return {Ext.Component} this */ setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } return this; }, /** * Returns true if this component is visible. */ isVisible : function(){ return this.rendered && this.getActionEl().isVisible(); }, /** * Clone the current component using the original config values passed into this instance by default. * @param {Object} overrides A new config containing any properties to override in the cloned version. * An id property can be passed on this object, otherwise one will be generated to avoid duplicates. * @return {Ext.Component} clone The cloned copy of this component */ cloneConfig : function(overrides){ overrides = overrides || {}; var id = overrides.id || Ext.id(); var cfg = Ext.applyIf(overrides, this.initialConfig); cfg.id = id; // prevent dup id return new this.constructor(cfg); }, /** * Gets the xtype for this component as registered with {@link Ext.ComponentMgr}. For a list of all * available xtypes, see the {@link Ext.Component} header. Example usage: * <pre><code> var t = new Ext.form.TextField(); alert(t.getXType()); // alerts 'textfield' </code></pre> * @return {String} The xtype */ getXType : function(){ return this.constructor.xtype; }, /** * Tests whether or not this component is of a specific xtype. This can test whether this component is descended * from the xtype (default) or whether it is directly of the xtype specified (shallow = true). For a list of all * available xtypes, see the {@link Ext.Component} header. Example usage: * <pre><code> var t = new Ext.form.TextField(); var isText = t.isXType('textfield'); // true var isBoxSubclass = t.isXType('box'); // true, descended from BoxComponent var isBoxInstance = t.isXType('box', true); // false, not a direct BoxComponent instance </code></pre> * @param {String} xtype The xtype to check for this component * @param {Boolean} shallow (optional) False to check whether this component is descended from the xtype (this is * the default), or true to check whether this component is directly of the specified xtype. */ isXType : function(xtype, shallow){ return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype; }, /** * Returns this component's xtype hierarchy as a slash-delimited string. For a list of all * available xtypes, see the {@link Ext.Component} header. Example usage: * <pre><code> var t = new Ext.form.TextField(); alert(t.getXTypes()); // alerts 'component/box/field/textfield' </pre></code> * @return {String} The xtype hierarchy string */ getXTypes : function(){ var tc = this.constructor; if(!tc.xtypes){ var c = [], sc = this; while(sc && sc.constructor.xtype){ c.unshift(sc.constructor.xtype); sc = sc.constructor.superclass; } tc.xtypeChain = c; tc.xtypes = c.join('/'); } return tc.xtypes; }, /** * Find a container above this component at any level by a custom function. If the passed function returns * true, the container will be returned. The passed function is called with the arguments (container, this component). * @param {Function} fcn * @param {Object} scope (optional) * @return {Array} Array of Ext.Components */ findParentBy: function(fn) { for (var p = this.ownerCt; (p != null) && !fn(p, this); p = p.ownerCt); return p || null; }, /** * Find a container above this component at any level by xtype or class * @param {String/Class} xtype The xtype string for a component, or the class of the component directly * @return {Container} The found container */ findParentByType: function(xtype) { return typeof xtype == 'function' ? this.findParentBy(function(p){ return p.constructor === xtype; }) : this.findParentBy(function(p){ return p.constructor.xtype === xtype; }); }, // internal function for auto removal of assigned event handlers on destruction mon : function(item, ename, fn, scope, opt){ if(!this.mons){ this.mons = []; this.on('beforedestroy', function(){ for(var i= 0, len = this.mons.length; i < len; i++){ var m = this.mons[i]; m.item.un(m.ename, m.fn, m.scope); } }, this); } this.mons.push({ item: item, ename: ename, fn: fn, scope: scope }); item.on(ename, fn, scope, opt); } }); Ext.reg('component', Ext.Component);
Kev/maybelater
static/ext-2.1/source/widgets/Component.js
JavaScript
gpl-2.0
31,082
<?php class ET_Global_Settings { private static $_settings = array(); public static function init() { // The class can only be initialized once if ( ! empty( self::$_settings ) ) { return; } self::set_values(); } private static function set_values() { $font_defaults = array( 'size' => '14', 'color' => '#666666', 'letter_spacing' => '0px', 'line_height' => '1.7em', ); $defaults = array( 'et_pb_image-animation' => 'left', 'et_pb_gallery-zoom_icon_color' => et_get_option( 'accent_color', '#2EA3F2' ), 'et_pb_gallery-hover_overlay_color' => 'rgba(255,255,255,0.9)', 'et_pb_gallery-title_font_size' => '16', 'et_pb_gallery-title_color' => '#333333', 'et_pb_gallery-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_gallery-title_line_height' => '1em', 'et_pb_gallery-title_font_style' => '', 'et_pb_gallery-caption_font_size' => '14', 'et_pb_gallery-caption_font_style' => '', 'et_pb_gallery-caption_color' => '#f3f3f3', 'et_pb_gallery-caption_line_height' => '18px', 'et_pb_gallery-caption_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_tabs-tab_font_size' => $font_defaults['size'], 'et_pb_tabs-tab_line_height' => $font_defaults['line_height'], 'et_pb_tabs-tab_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_tabs-body_font_size' => $font_defaults['size'], 'et_pb_tabs-body_line_height' => $font_defaults['line_height'], 'et_pb_tabs-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_tabs-title_font_style' => '', 'et_pb_tabs-padding' => '30', 'et_pb_slider-header_font_size' => '46', 'et_pb_slider-header_line_height' => '1em', 'et_pb_slider-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_slider-header_font_style' => '', 'et_pb_slider-body_font_size' => '16', 'et_pb_slider-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_slider-body_line_height' => $font_defaults['line_height'], 'et_pb_slider-body_font_style' => '', 'et_pb_slider-padding' => '16', 'et_pb_slider-header_color' => '#ffffff', 'et_pb_slider-header_line_height' => '1em', 'et_pb_slider-body_color' => '#ffffff', 'et_pb_testimonial-portrait_border_radius' => '90', 'et_pb_testimonial-portrait_width' => '90', 'et_pb_testimonial-portrait_height' => '90', 'et_pb_testimonial-author_name_font_style' => 'bold', 'et_pb_testimonial-author_details_font_style' => 'bold', 'et_pb_testimonial-border_color' => '#ffffff', 'et_pb_testimonial-border_width' => '1px', 'et_pb_testimonial-body_font_size' => $font_defaults['size'], 'et_pb_testimonial-body_line_height' => '1.5', 'et_pb_testimonial-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_pricing_tables-header_font_size' => '22', 'et_pb_pricing_tables-header_font_style' => '', 'et_pb_pricing_tables-subheader_font_size' => '16', 'et_pb_pricing_tables-subheader_font_style' => '', 'et_pb_pricing_tables-price_font_size' => '80', 'et_pb_pricing_tables-price_font_style' => '', 'et_pb_pricing_tables-header_color' => '#ffffff', 'et_pb_pricing_tables-header_line_height' => '1em', 'et_pb_pricing_tables-subheader_color' => '#ffffff', 'et_pb_pricing_tables-price_color' => '#2EA3F2', 'et_pb_pricing_tables-price_line_height' => '82px', 'et_pb_pricing_tables-body_line_height' => '24px', 'et_pb_fullwidth_post_title-title_font_size' => '26px', 'et_pb_fullwidth_post_title-title_line_height' => '1em', 'et_pb_fullwidth_post_title-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_fullwidth_post_title-meta_font_size' => $font_defaults['size'], 'et_pb_fullwidth_post_title-meta_line_height' => '1em', 'et_pb_fullwidth_post_title-meta_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_fullwidth_post_title-module_bg_color' => 'rgba(255,255,255,0)', 'et_pb_fullwidth_header-scroll_down_icon_size' => '50px', 'et_pb_fullwidth_header-subhead_font_size' => '18px', 'et_pb_fullwidth_header-button_one_font_size' => '20px', 'et_pb_fullwidth_header-button_one_border_radius' => '3px', 'et_pb_fullwidth_header-button_two_font_size' => '20px', 'et_pb_fullwidth_header-button_two_border_radius' => '3px', 'et_pb_post_title-title_font_size' => '26px', 'et_pb_post_title-title_line_height' => '1em', 'et_pb_post_title-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_post_title-meta_font_size' => $font_defaults['size'], 'et_pb_post_title-meta_line_height' => '1em', 'et_pb_post_title-meta_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_post_title-module_bg_color' => 'rgba(255,255,255,0)', 'et_pb_cta-header_font_size' => '26', 'et_pb_cta-header_font_style' => '', 'et_pb_cta-custom_padding' => '40', 'et_pb_cta-header_text_color' => '#333333', 'et_pb_cta-header_line_height' => '1em', 'et_pb_cta-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_cta-body_font_size' => $font_defaults['size'], 'et_pb_cta-body_line_height' => $font_defaults['line_height'], 'et_pb_cta-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_blurb-header_font_size' => '18', 'et_pb_blurb-header_color' => '#333333', 'et_pb_blurb-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_blurb-header_line_height' => '1em', 'et_pb_blurb-body_font_size' => $font_defaults['size'], 'et_pb_blurb-body_color' => '#666666', 'et_pb_blurb-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_blurb-body_line_height' => $font_defaults['line_height'], 'et_pb_text-text_font_size' => $font_defaults['size'], 'et_pb_text-text_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_text-text_line_height' => $font_defaults['line_height'], 'et_pb_text-border_color' => '#ffffff', 'et_pb_text-border_width' => '1px', 'et_pb_slide-header_font_size' => '26px', 'et_pb_slide-header_color' => '#ffffff', 'et_pb_slide-header_line_height' => '1em', 'et_pb_slide-body_font_size' => '16px', 'et_pb_slide-body_color' => '#ffffff', 'et_pb_pricing_table-header_font_size' => '22px', 'et_pb_pricing_table-header_color' => '#ffffff', 'et_pb_pricing_table-header_line_height' => '1em', 'et_pb_pricing_table-subheader_font_size' => '16px', 'et_pb_pricing_table-subheader_color' => '#ffffff', 'et_pb_pricing_table-price_font_size' => '80px', 'et_pb_pricing_table-price_color' => '#2EA3F2', 'et_pb_pricing_table-price_line_height' => '82px', 'et_pb_pricing_table-body_line_height' => '24px', 'et_pb_audio-title_font_size' => '26', 'et_pb_audio-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_audio-title_line_height' => $font_defaults['line_height'], 'et_pb_audio-title_font_style' => '', 'et_pb_audio-caption_font_size' => $font_defaults['size'], 'et_pb_audio-caption_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_audio-caption_line_height' => $font_defaults['line_height'], 'et_pb_audio-caption_font_style' => '', 'et_pb_audio-title_text_color' => '#666666', 'et_pb_signup-header_font_size' => '26', 'et_pb_signup-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_signup-header_line_height' => $font_defaults['line_height'], 'et_pb_signup-body_font_size' => $font_defaults['size'], 'et_pb_signup-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_signup-body_line_height' => $font_defaults['line_height'], 'et_pb_signup-header_font_style' => '', 'et_pb_signup-padding' => '20', 'et_pb_signup-focus_border_color' => '#ffffff', 'et_pb_login-header_font_size' => '26', 'et_pb_login-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_login-header_line_height' => $font_defaults['line_height'], 'et_pb_login-body_font_size' => $font_defaults['size'], 'et_pb_login-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_login-body_line_height' => $font_defaults['line_height'], 'et_pb_login-header_font_style' => '', 'et_pb_login-custom_padding' => '40', 'et_pb_login-focus_border_color' => '#ffffff', 'et_pb_portfolio-zoom_icon_color' => et_get_option( 'accent_color', '#2EA3F2' ), 'et_pb_portfolio-hover_overlay_color' => 'rgba(255,255,255,0.9)', 'et_pb_portfolio-title_font_size' => '18', 'et_pb_portfolio-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_portfolio-title_line_height' => $font_defaults['line_height'], 'et_pb_portfolio-title_font_style' => '', 'et_pb_portfolio-caption_font_size' => '14', 'et_pb_portfolio-caption_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_portfolio-caption_line_height' => $font_defaults['line_height'], 'et_pb_portfolio-caption_font_style' => '', 'et_pb_portfolio-title_color' => '#333333', 'et_pb_filterable_portfolio-zoom_icon_color' => et_get_option( 'accent_color', '#2EA3F2' ), 'et_pb_filterable_portfolio-hover_overlay_color' => 'rgba(255,255,255,0.9)', 'et_pb_filterable_portfolio-title_font_size' => '18', 'et_pb_filterable_portfolio-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_filterable_portfolio-title_line_height' => $font_defaults['line_height'], 'et_pb_filterable_portfolio-title_font_style' => '', 'et_pb_filterable_portfolio-caption_font_size' => '14', 'et_pb_filterable_portfolio-caption_letter_spacing'=> $font_defaults['letter_spacing'], 'et_pb_filterable_portfolio-caption_line_height' => $font_defaults['line_height'], 'et_pb_filterable_portfolio-caption_font_style' => '', 'et_pb_filterable_portfolio-filter_font_size' => '14', 'et_pb_filterable_portfolio-filter_letter_spacing'=> $font_defaults['letter_spacing'], 'et_pb_filterable_portfolio-filter_line_height' => $font_defaults['line_height'], 'et_pb_filterable_portfolio-filter_font_style' => '', 'et_pb_filterable_portfolio-title_color' => '#333333', 'et_pb_counters-title_font_size' => '12', 'et_pb_counters-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_counters-title_line_height' => $font_defaults['line_height'], 'et_pb_counters-title_font_style' => '', 'et_pb_counters-percent_font_size' => '12', 'et_pb_counters-percent_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_counters-percent_line_height' => $font_defaults['line_height'], 'et_pb_counters-percent_font_style' => '', 'et_pb_counters-border_radius' => '0', 'et_pb_counters-padding' => '0', 'et_pb_counters-title_color' => '#999999', 'et_pb_counters-percent_color' => '#ffffff', 'et_pb_circle_counter-title_font_size' => '16', 'et_pb_circle_counter-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_circle_counter-title_line_height' => '1em', 'et_pb_circle_counter-title_font_style' => '', 'et_pb_circle_counter-number_font_size' => '46', 'et_pb_circle_counter-number_font_style' => '', 'et_pb_circle_counter-title_color' => '#333333', 'et_pb_circle_counter-number_line_height' => '225px', 'et_pb_circle_counter-number_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_number_counter-title_font_size' => '16', 'et_pb_number_counter-title_line_height' => '1em', 'et_pb_number_counter-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_number_counter-title_font_style' => '', 'et_pb_number_counter-number_font_size' => '72', 'et_pb_number_counter-number_line_height' => '72px', 'et_pb_number_counter-number_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_number_counter-number_font_style' => '', 'et_pb_number_counter-title_color' => '#333333', 'et_pb_accordion-toggle_font_size' => '16', 'et_pb_accordion-toggle_font_style' => '', 'et_pb_accordion-inactive_toggle_font_style' => '', 'et_pb_accordion-toggle_icon_size' => '16', 'et_pb_accordion-custom_padding' => '20', 'et_pb_accordion-toggle_line_height' => '1em', 'et_pb_accordion-toggle_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_accordion-body_font_size' => $font_defaults['size'], 'et_pb_accordion-body_line_height' => $font_defaults['line_height'], 'et_pb_accordion-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_toggle-title_font_size' => '16', 'et_pb_toggle-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_toggle-title_font_style' => '', 'et_pb_toggle-inactive_title_font_style' => '', 'et_pb_toggle-toggle_icon_size' => '16', 'et_pb_toggle-title_color' => '#333333', 'et_pb_toggle-title_line_height' => '1em', 'et_pb_toggle-custom_padding' => '20', 'et_pb_toggle-body_font_size' => $font_defaults['size'], 'et_pb_toggle-body_line_height' => $font_defaults['line_height'], 'et_pb_toggle-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_contact_form-title_font_size' => '26', 'et_pb_contact_form-title_font_style' => '', 'et_pb_contact_form-form_field_font_size' => '14', 'et_pb_contact_form-form_field_font_style' => '', 'et_pb_contact_form-captcha_font_size' => '14', 'et_pb_contact_form-captcha_font_style' => '', 'et_pb_contact_form-padding' => '16', 'et_pb_contact_form-title_color' => '#333333', 'et_pb_contact_form-title_line_height' => '1em', 'et_pb_contact_form-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_contact_form-form_field_color' => '#999999', 'et_pb_contact_form-form_field_line_height' => $font_defaults['line_height'], 'et_pb_contact_form-form_field_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_sidebar-header_font_size' => '18', 'et_pb_sidebar-header_font_style' => '', 'et_pb_sidebar-header_color' => '#333333', 'et_pb_sidebar-header_line_height' => '1em', 'et_pb_sidebar-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_sidebar-remove_border' => 'off', 'et_pb_sidebar-body_font_size' => $font_defaults['size'], 'et_pb_sidebar-body_line_height' => $font_defaults['line_height'], 'et_pb_sidebar-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_divider-show_divider' => 'off', 'et_pb_divider-divider_style' => 'none', 'et_pb_divider-divider_weight' => '1', 'et_pb_divider-height' => '1', 'et_pb_divider-divider_position' => 'none', 'et_pb_team_member-header_font_size' => '18', 'et_pb_team_member-header_font_style' => '', 'et_pb_team_member-subheader_font_size' => '14', 'et_pb_team_member-subheader_font_style' => '', 'et_pb_team_member-social_network_icon_size' => '16', 'et_pb_team_member-header_color' => '#333333', 'et_pb_team_member-header_line_height' => '1em', 'et_pb_team_member-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_team_member-body_font_size' => $font_defaults['size'], 'et_pb_team_member-body_line_height' => $font_defaults['line_height'], 'et_pb_team_member-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_shop-title_font_size' => '16', 'et_pb_shop-title_font_style' => '', 'et_pb_shop-sale_badge_font_size' => '16', 'et_pb_shop-sale_badge_font_style' => '', 'et_pb_shop-price_font_size' => '14', 'et_pb_shop-price_font_style' => '', 'et_pb_shop-sale_price_font_size' => '14', 'et_pb_shop-sale_price_font_style' => '', 'et_pb_shop-title_color' => '#333333', 'et_pb_shop-title_line_height' => '1em', 'et_pb_shop-title_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_shop-price_line_height' => '26px', 'et_pb_shop-price_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_countdown_timer-header_font_size' => '22', 'et_pb_countdown_timer-header_font_style' => '', 'et_pb_countdown_timer-header_color' => '#333333', 'et_pb_countdown_timer-header_line_height' => '1em', 'et_pb_countdown_timer-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_countdown_timer-numbers_font_size' => '64px', 'et_pb_countdown_timer-numbers_line_height' => '64px', 'et_pb_countdown_timer-numbers_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_countdown_timer-label_line_height' => '25px', 'et_pb_countdown_timer-label_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_countdown_timer-label_font_size' => $font_defaults['size'], 'et_pb_social_media_follow-icon_size' => '14', 'et_pb_social_media_follow-button_font_style' => '', 'et_pb_fullwidth_slider-header_font_size' => '46', 'et_pb_fullwidth_slider-header_font_style' => '', 'et_pb_fullwidth_slider-body_font_size' => '16', 'et_pb_fullwidth_slider-body_font_style' => '', 'et_pb_fullwidth_slider-body_line_height' => $font_defaults['line_height'], 'et_pb_fullwidth_slider-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_fullwidth_slider-padding' => '16', 'et_pb_fullwidth_slider-header_color' => '#ffffff', 'et_pb_fullwidth_slider-header_line_height' => '1em', 'et_pb_fullwidth_slider-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_fullwidth_slider-body_color' => '#ffffff', 'et_pb_blog-header_font_size' => '18', 'et_pb_blog-header_font_style' => '', 'et_pb_blog-meta_font_size' => '14', 'et_pb_blog-meta_font_style' => '', 'et_pb_blog-meta_line_height' => $font_defaults['line_height'], 'et_pb_blog-meta_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_blog-header_color' => '#333333', 'et_pb_blog-header_line_height' => '1em', 'et_pb_blog-header_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_blog-body_font_size' => $font_defaults['size'], 'et_pb_blog-body_line_height' => $font_defaults['line_height'], 'et_pb_blog-body_letter_spacing' => $font_defaults['letter_spacing'], 'et_pb_blog_masonry-header_font_size' => '26', 'et_pb_blog_masonry-header_font_style' => '', 'et_pb_blog_masonry-meta_font_size' => '14', 'et_pb_blog_masonry-meta_font_style' => '', 'all_buttons_font_size' => '20', 'all_buttons_border_width' => '2', 'all_buttons_border_radius' => '3', 'all_buttons_spacing' => '0', 'all_buttons_font_style' => '', 'all_buttons_border_radius_hover' => '3', 'all_buttons_spacing_hover' => '0', ); // reformat defaults array and add actual values to it foreach( $defaults as $setting_name => $default_value ) { $defaults[ $setting_name ] = array( 'default' => $default_value, ); $actual_value = et_get_option( $setting_name, '', '', true ); if ( '' !== $actual_value ) { $defaults[ $setting_name ]['actual'] = $actual_value; } } self::$_settings = apply_filters( 'et_set_default_values', $defaults ); } /** * Get default global setting value * @param string $name Setting name * @param string $get_value Defines the value it should get: actual or default * * @return mixed Global setting value or FALSE */ public static function get_value( $name, $get_value = 'actual' ) { $settings = self::$_settings; if ( ! isset( $settings[ $name ] ) ) { return false; } if ( isset( $settings[ $name ][ $get_value ] ) ) { $result = $settings[ $name ][ $get_value ]; } elseif ( 'actual' === $get_value && isset( $settings[ $name ][ 'default' ] ) ) { $result = $settings[ $name ][ 'default' ]; } else { $result = false; } return $result; } /** * Translate 'on'/'off' into true/false * Pagebuilder use pseudo checkbox with 'on'/'off' value while customizer use true/false * which cause ET_Global_Settings' default value incompatibilities. */ public static function get_checkbox_value( $name, $get_value = 'actual', $source = 'pagebuilder' ) { // Get value $value = self::get_value( $name, $get_value ); // customizer to pagebuilder || pagebuilder to customizer if ( 'customizer' === $source ) { if ( false === $value ) { return 'off'; } else { return 'on'; } } else { if ( 'off' === $value || false === $value ) { return false; } else { return true; } } } } function et_builder_init_global_settings() { ET_Global_Settings::init(); }
studiochakra/foxfirekennel.com
wp-content/themes/Divi/includes/builder/class-et-global-settings.php
PHP
gpl-2.0
24,994
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 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 the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; /** Generated Model for M_InventoryLineMA * @author Adempiere (generated) * @version Release 3.8.0 - $Id$ */ public class X_M_InventoryLineMA extends PO implements I_M_InventoryLineMA, I_Persistent { /** * */ private static final long serialVersionUID = 20150101L; /** Standard Constructor */ public X_M_InventoryLineMA (Properties ctx, int M_InventoryLineMA_ID, String trxName) { super (ctx, M_InventoryLineMA_ID, trxName); /** if (M_InventoryLineMA_ID == 0) { setM_AttributeSetInstance_ID (0); setM_InventoryLine_ID (0); setMovementQty (Env.ZERO); } */ } /** Load Constructor */ public X_M_InventoryLineMA (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 1 - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_InventoryLineMA[") .append(get_ID()).append("]"); return sb.toString(); } public I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException { return (I_M_AttributeSetInstance)MTable.get(getCtx(), I_M_AttributeSetInstance.Table_Name) .getPO(getM_AttributeSetInstance_ID(), get_TrxName()); } /** Set Attribute Set Instance. @param M_AttributeSetInstance_ID Product Attribute Set Instance */ public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Attribute Set Instance. @return Product Attribute Set Instance */ public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InventoryLine getM_InventoryLine() throws RuntimeException { return (org.compiere.model.I_M_InventoryLine)MTable.get(getCtx(), org.compiere.model.I_M_InventoryLine.Table_Name) .getPO(getM_InventoryLine_ID(), get_TrxName()); } /** Set Phys.Inventory Line. @param M_InventoryLine_ID Unique line in an Inventory document */ public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Phys.Inventory Line. @return Unique line in an Inventory document */ public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_InventoryLine_ID())); } /** Set Movement Quantity. @param MovementQty Quantity of a product moved. */ public void setMovementQty (BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Movement Quantity. @return Quantity of a product moved. */ public BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return Env.ZERO; return bd; } }
sumairsh/adempiere
base/src/org/compiere/model/X_M_InventoryLineMA.java
Java
gpl-2.0
5,197
<?php if (isset($_POST['submit-uaf-font'])){ $uaf_api_key = get_option('uaf_api_key'); $font_file_name = $_FILES['font_file']['name']; $font_file_details = pathinfo($_FILES['font_file']['name']); $file_extension = strtolower($font_file_details['extension']); $fontUploadFinalMsg = ''; $fontUploadFinalStatus = 'updated'; $fontNameToStore = sanitize_file_name(date('ymdhis').$font_file_details['filename']); $fontNameToStoreWithUrl = $fontNameToStore; // SEND FONT CONERSION REQUEST set_time_limit(0); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, 'http://dnesscarkey.com/font-convertor/convertor/convert.php'); curl_setopt($ch, CURLOPT_POST, true); $post = array( 'fontfile' => "@".$_FILES['font_file']['tmp_name'], 'fontfileext' => pathinfo($_FILES['font_file']['name'], PATHINFO_EXTENSION), 'api_key' => $uaf_api_key ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $convertResponse = curl_exec($ch); if(curl_errno($ch)) { echo 'Error: ' . curl_error($ch); exit(); } else { $CrulStatinfo = curl_getinfo($ch); if ($CrulStatinfo['http_code'] == '200'): $convertResponseArray = json_decode($convertResponse, true); if ($convertResponseArray['global']['status'] == 'ok'): $neededFontFormats = array('woff','eot'); foreach ($neededFontFormats as $neededFontFormat): if ($convertResponseArray[$neededFontFormat]['status'] == 'ok'): $fontFileContent = ''; $fontFileContent = wp_remote_fopen($convertResponseArray[$neededFontFormat]['filename']); if (!empty($fontFileContent)): $newFileName = $fontNameToStore.'.'.$neededFontFormat; $newFilePath = $uaf_upload_dir.$newFileName; $fh = fopen($newFilePath, 'w') or die("can't open file. Make sure you have write permission to your upload folder"); fwrite($fh, $fontFileContent); fclose($fh); $fontUploadMsg[$neededFontFormat]['status'] = 'ok'; $fontUploadMsg[$neededFontFormat]['text'] = "Done"; else: $fontUploadMsg[$neededFontFormat]['status'] = 'error'; $fontUploadMsg[$neededFontFormat]['text'] = "Couldn't receive $neededFontFormat file"; endif; else: $fontUploadMsg[$neededFontFormat]['status'] = 'error'; $fontUploadMsg[$neededFontFormat]['text'] = "Problem converting to $neededFontFormat format"; endif; endforeach; else: $fontUploadFinalStatus = 'error'; $fontUploadFinalMsg .= $convertResponseArray['global']['msg'].'<br/>'; endif; else: $fontUploadFinalStatus = 'error'; $fontUploadFinalMsg = $convertResponse; endif; } if (!empty($fontUploadMsg)): foreach ($fontUploadMsg as $formatKey => $formatData): if ($formatData['status'] == 'error'): $fontUploadFinalStatus = 'error'; $fontUploadFinalMsg .= $formatData['text'].'<br/>'; endif; endforeach; endif; if ($fontUploadFinalStatus != 'error'): $fontUploadFinalMsg = 'Font Uploaded'; endif; if ($fontUploadFinalStatus != 'error'): $fontsRawData = get_option('uaf_font_data'); $fontsData = json_decode($fontsRawData, true); if (empty($fontsData)): $fontsData = array(); endif; $fontsData[date('ymdhis')] = array('font_name' => $_POST['font_name'], 'font_path' => $fontNameToStoreWithUrl); $updateFontData = json_encode($fontsData); update_option('uaf_font_data',$updateFontData); uaf_write_css(); endif; } if (isset($_GET['delete_font_key'])): $fontsRawData = get_option('uaf_font_data'); $fontsData = json_decode($fontsRawData, true); $key_to_delete = $_GET['delete_font_key']; @unlink(realpath($uaf_upload_dir.$fontsData[$key_to_delete]['font_path'].'.woff')); @unlink(realpath($uaf_upload_dir.$fontsData[$key_to_delete]['font_path'].'.eot')); unset($fontsData[$key_to_delete]); $updateFontData = json_encode($fontsData); update_option('uaf_font_data',$updateFontData); $fontUploadFinalStatus = 'updated'; $fontUploadFinalMsg = 'Font Deleted'; uaf_write_css(); endif; ?> <table class="wp-list-table widefat fixed bookmarks"> <thead> <tr> <th>Upload Fonts</th> </tr> </thead> <tbody> <tr> <td> <?php if (!empty($fontUploadFinalMsg)):?> <div class="<?php echo $fontUploadFinalStatus; ?>" id="message"><p><?php echo $fontUploadFinalMsg ?></p></div> <?php endif; ?> <?php $fontsRawData = get_option('uaf_font_data'); $fontsData = json_decode($fontsRawData, true); ?> <p align="right"><input type="button" name="open_add_font" onClick="open_add_font();" class="button-primary" value="Add Fonts" /><br/></p> <div id="font-upload" style="display:none;"> <form action="options-general.php?page=use-any-font/plugin_interface.php" id="open_add_font_form" method="post" enctype="multipart/form-data"> <table class="uaf_form"> <tr> <td width="175">Font Name</td> <td><input type="text" name="font_name" value="" class="required" style="width:200px;" /></td> </tr> <tr> <td>Font File</td> <td><input type="file" name="font_file" value="" class="required" /><br/> <em>Accepted Font Format : ttf, otf, eot, woff, svg, dfont, suit | Font Size: Less than 2MB</em> </td> </tr> <tr> <td>&nbsp; </td> <td><input type="submit" name="submit-uaf-font" class="button-primary" value="Upload" /> <p>By clicking on Upload, you confirm that you have rights to use this font.</p> </td> </tr> </table> </form> <br/><br/> </div> <table cellspacing="0" class="wp-list-table widefat fixed bookmarks"> <thead> <tr> <th width="20">Sn</th> <th>Font</th> <th width="100">Delete</th> </tr> </thead> <tbody> <?php if (!empty($fontsData)): ?> <?php $sn = 0; foreach ($fontsData as $key=>$fontData): $sn++ ?> <tr> <td><?php echo $sn; ?></td> <td><?php echo $fontData['font_name'] ?></td> <td><a onclick="if (!confirm('Are you sure ?')){return false;}" href="options-general.php?page=use-any-font/plugin_interface.php&delete_font_key=<?php echo $key; ?>">Delete</a></td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td colspan="3">No font found. Please click on Add Fonts to add font</td> </tr> <?php endif; ?> </tbody> </table> <script> function open_add_font(){ jQuery('#font-upload').toggle('fast'); jQuery("#open_add_font_form").validate({ rules: { font_name : {required:true, maxlength:40}, font_file : {required:true, accept:'ttf|otf|eot|woff|svg|dfont|suit'} }, messages:{ font_file : {accept:'ttf,otf,eot,woff,svg,dfont,suit font format accepted now.'} } }); } </script> <br/> </td> </tr> </tbody> </table><br/>
joga3001/ctperu
wp-content/plugins/use-any-font/includes/uaf_font_upload.php
PHP
gpl-2.0
7,106
<?php /** * EXHIBIT A. Common Public Attribution License Version 1.0 * The contents of this file are subject to the Common Public Attribution 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://www.oxwall.org/license. The License is based on the Mozilla Public License Version 1.1 * but Sections 14 and 15 have been added to cover use of software over a computer network and provide for * limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent * with Exhibit B. Software distributed under the License is distributed on an “AS IS” basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language * governing rights and limitations under the License. The Original Code is Oxwall software. * The Initial Developer of the Original Code is Oxwall Foundation (http://www.oxwall.org/foundation). * All portions of the code written by Oxwall Foundation are Copyright (c) 2011. All Rights Reserved. * EXHIBIT B. Attribution Information * Attribution Copyright Notice: Copyright 2011 Oxwall Foundation. All rights reserved. * Attribution Phrase (not exceeding 10 words): Powered by Oxwall community software * Attribution URL: http://www.oxwall.org/ * Graphic Image as provided in the Covered Code. * Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work * which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. */ class BIRTHDAYS_Cron extends OW_Cron { public function __construct() { parent::__construct(); } public function run() { BIRTHDAYS_BOL_Service::getInstance()->checkBirthdays(); } }
seret/oxtebafu
ow_plugins/birthdays/cron.php
PHP
gpl-2.0
1,841
/* * Copyright 2001 Telef�nica I+D. All rights reserved */ package icaro.gestores.gestorOrganizacion.comportamiento; //import icaro.infraestructura.corba.ORBDaemonExec; import icaro.infraestructura.entidadesBasicas.NombresPredefinidos; import icaro.infraestructura.entidadesBasicas.comunicacion.EventoRecAgte; import icaro.infraestructura.entidadesBasicas.comunicacion.InfoContEvtMsgAgteReactivo; import icaro.infraestructura.entidadesBasicas.comunicacion.MensajeSimple; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.DescInstanciaAgente; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.DescInstanciaGestor; import icaro.infraestructura.entidadesBasicas.factorias.FactoriaComponenteIcaro; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazGestion; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazUsoAgente; import icaro.infraestructura.patronAgenteReactivo.control.acciones.AccionesSemanticasAgenteReactivo; import icaro.infraestructura.patronAgenteReactivo.factoriaEInterfaces.ItfGestionAgenteReactivo; import icaro.infraestructura.patronAgenteReactivo.factoriaEInterfaces.ItfUsoAgenteReactivo; import icaro.infraestructura.patronAgenteReactivo.factoriaEInterfaces.imp.HebraMonitorizacion; import icaro.infraestructura.recursosOrganizacion.configuracion.ItfUsoConfiguracion; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza; /** * Clase que contiene las acciones necesarias para el gestor de la * organizaci�n * * * @created 3 de Diciembre de 2007 */ public class AccionesSemanticasGestorOrganizacion extends AccionesSemanticasAgenteReactivo { // Tiempo que fijaremos para las monitorizaciones ciclicas /** * @uml.property name="tiempoParaNuevaMonitorizacion" */ protected long tiempoParaNuevaMonitorizacion; /** * Hebra para que inyecte eventos de monitorizacion cada cierto tiempo * * @uml.property name="hebra" * @uml.associationEnd */ private HebraMonitorizacion hebra; private InterfazGestion itfGestionRecTrazas; private ItfUsoConfiguracion config; private ItfUsoAgenteReactivo itfUsoPropiadeEsteAgente; // private ItfUsoRecursoTrazas ItfUsoRecTrazas; public AccionesSemanticasGestorOrganizacion() { super(); // try { // // itfGestionRecTrazas = (InterfazGestion) // this.itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + // NombresPredefinidos.RECURSO_TRAZAS); // // } catch (Exception ex) { // logger.fatal("No sepuede obtener la interfaz de gestion del recurso de trazas."); // trazas.aceptaNuevaTraza(new InfoTraza("GestorOrganizacion", // "No sepuede obtener la interfaz de gestion del recurso de trazas.", // InfoTraza.NivelTraza.error)); // ex.printStackTrace(); // // System.exit(1); // } // trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, // "Construyendo agente reactivo " + nombreAgente + ".", // InfoTraza.NivelTraza.debug)); } /** * Establece la configuracion para el gestor de Organizacion */ public void configurarGestor() { try { /* * En esta accion semantica se configura todo aquello que sea * necesario a partir del archivo xml */ trazas.setIdentAgenteAReportar(nombreAgente); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Configuracion del agente : " + nombreAgente + ".", InfoTraza.NivelTraza.debug)); config = (ItfUsoConfiguracion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + NombresPredefinidos.CONFIGURACION); tiempoParaNuevaMonitorizacion = Integer .parseInt(config .getValorPropiedadGlobal(NombresPredefinidos.INTERVALO_MONITORIZACION_ATR_PROPERTY)); itfUsoPropiadeEsteAgente = (ItfUsoAgenteReactivo) itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + nombreAgente); itfGestionRecTrazas = (InterfazGestion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.RECURSO_TRAZAS); this.informaraMiAutomata("gestor_configurado"); } catch (Exception e) { e.printStackTrace(); logger.error("GestorRecursos: Hubo problemas al configurar el gestor de Organizacion."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Hubo problemas al configurar el gestor de Organizacion.", InfoTraza.NivelTraza.error)); } } /** * Crea el gestor de agentes y el gestor de recursos */ public void crearGestores() { try { // creo los gestores // logger.debug("GestorOrganizacion: Creando gestor de agentes..."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Creando gestor de agentes ...", InfoTraza.NivelTraza.debug)); // Gestor de Agentes: local o remoto? DescInstanciaGestor descGestor = config .getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); String esteNodo = descGestor.getNodo().getNombreUso(); DescInstanciaGestor gestorRecursos = config .getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_RECURSOS); String nodoDestino = gestorRecursos.getNodo().getNombreUso(); if (nodoDestino.equals(esteNodo)) { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(gestorAgentes); FactoriaComponenteIcaro.instanceAgteReactInpObj() .crearAgenteReactivo(gestorRecursos); } // else { // while (!ok) { // ++intentos; // try { // ((FactoriaAgenteReactivo) ClaseGeneradoraRepositorioInterfaces // .instance() // .obtenerInterfaz( // NombresPredefinidos.FACTORIA_AGENTE_REACTIVO // + nodoDestino)) // .crearAgenteReactivo(gestorAgentes); // ok = true; // } catch (Exception e) { // trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, // "Error al crear el agente " // + NombresPredefinidos.NOMBRE_GESTOR_AGENTES // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino, // InfoTraza.NivelTraza.error)); // logger // .error("Error al crear el agente " // + NombresPredefinidos.NOMBRE_GESTOR_AGENTES // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino); // // Thread.sleep(1000 * intentos); // // ok = false; // } // } // } logger.debug("GestorOrganizacion: Gestor de recursos creado."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestor de recursos creado.", InfoTraza.NivelTraza.debug)); // Set<Object> conjuntoEventos = new HashSet<Object>(); // conjuntoEventos.add(EventoRecAgte.class); // indico a quien debe reportar ((ItfGestionAgenteReactivo) itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)) .setGestorAReportar(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); logger.debug("GestorOrganizacion: Creando gestor de agentes ..."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Creando gestor de agentes ...", InfoTraza.NivelTraza.debug)); // Gestor de recursos: local o remoto? DescInstanciaAgente gestorAgentes = config .getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_AGENTES); nodoDestino = gestorAgentes.getNodo().getNombreUso(); if (nodoDestino.equals(esteNodo)) { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(gestorRecursos); FactoriaComponenteIcaro.instanceAgteReactInpObj() .crearAgenteReactivo(gestorAgentes); } // else { // intentos = 0; // ok = false; // while (!ok) { // ++intentos; // try { // ((FactoriaAgenteReactivo) ClaseGeneradoraRepositorioInterfaces // .instance() // .obtenerInterfaz( // NombresPredefinidos.FACTORIA_AGENTE_REACTIVO // + nodoDestino)) // .crearAgenteReactivo(gestorRecursos); // ok = true; // } catch (Exception e) { // trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, // "Error al crear agente " // + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino, // InfoTraza.NivelTraza.error)); // logger // .error("Error al crear agente " // + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS // + " en un nodo remoto. Se volver� a intentar en " // + intentos // + " segundos...\n nodo origen: " // + esteNodo + "\t nodo destino: " // + nodoDestino); // // Thread.sleep(1000 * intentos); // ok = false; // } // } // } logger.debug("GestorOrganizacion: Gestor de agentes creado."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestor de agentes creado.", InfoTraza.NivelTraza.debug)); // indico a quien debe reportar ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_AGENTES)) .setGestorAReportar(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); logger.debug("GestorOrganizacion: Gestores registrados correctamente."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestores registrados correctamente.", InfoTraza.NivelTraza.debug)); this.informaraMiAutomata("gestores_creados"); } catch (Exception e) { logger.error( "GestorOrganizacion: Fue imposible crear los gestores de agentes y recursos en el gestor de la organizacion", e); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Fue imposible crear los gestores de agentes y recursos en el gestor de la organizacion", InfoTraza.NivelTraza.error)); e.printStackTrace(); try { this.informaraMiAutomata("error_en_creacion_gestores"); } catch (Exception e1) { e1.printStackTrace(); } } } public void arrancarGestorAgentes() { logger.debug("GestorOrganizacion: Arrancando Gestor de Agentes."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Arrancando Gestor de Agentes.", InfoTraza.NivelTraza.debug)); try { ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_AGENTES)) .arranca(); this.informaraMiAutomata("gestor_agentes_arrancado_ok"); // this.itfUsoAgente.aceptaEvento(new // EventoRecAgte("gestor_agentes_arrancado_ok")); } catch (Exception e) { logger.error("GestorOrganizacion: Fue imposible arrancar el Gestor de Agentes."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Fue imposible arrancar el Gestor de Agentes.", InfoTraza.NivelTraza.error)); e.printStackTrace(); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestor_agentes", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("error_en_arranque_gestor_agentes"); } catch (Exception e1) { e1.printStackTrace(); } } } public void arrancarGestorRecursos() { logger.debug("GestorOrganizacion: Arrancando Gestor de Recursos."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Arrancando Gestor de Recursos.", InfoTraza.NivelTraza.debug)); try { ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)) .arranca(); this.informaraMiAutomata("gestor_recursos_arrancado_ok"); // this.itfUsoAgente.aceptaEvento(new // EventoRecAgte("gestor_recursos_arrancado_ok")); } catch (Exception e) { logger.error("GestorOrganizacion: Fue imposible arrancar el Gestor de Recursos."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Fue imposible arrancar el Gestor de Recursos.", InfoTraza.NivelTraza.error)); e.printStackTrace(); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestor_recursos", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("error_en_arranque_gestor_recursos"); } catch (Exception e1) { e1.printStackTrace(); } } } public void gestoresArrancadosConExito() { // creo hebra de monitorizacion hebra = new HebraMonitorizacion(tiempoParaNuevaMonitorizacion, this.itfUsoPropiadeEsteAgente, "monitorizar"); this.hebra.start(); this.generarTimeOut(tiempoParaNuevaMonitorizacion, "monitorizar", nombreAgente, nombreAgente); logger.debug("GestorOrganizacion: Gestor de la organizacion esperando peticiones."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Gestor de la organizacion esperando peticiones.", InfoTraza.NivelTraza.debug)); } /** * Decide que hacer en caso de fallos en el gestor de agentes y/o en el * gestor de recursos */ public void decidirTratamientoErrorIrrecuperable() { // el tratamiento ser� siempre cerrar todo el chiringuito logger.debug("GestorOrganizacion: Se decide cerrar el sistema ante un error critico irrecuperable."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Se decide cerrar el sistema ante un error critico irrecuperable.", InfoTraza.NivelTraza.debug)); trazas.mostrarMensajeError("Error irrecuperable. Esperando por su solicitud de terminación"); /* * try { this.itfUsoAgente.aceptaEvento(new EventoRecAgte( * "tratamiento_terminar_gestores_y_gestor_organizacion", * NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, * NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception * e) { e.printStackTrace(); } */ } /** * intenta arrancar el gestor de agentes y/o el gestor de recursos si alguno * ha dado problemas en el arranque. */ public void recuperarErrorArranqueGestores() { // por defecto no se implementan politicas de recuperacion logger.debug("GestorOrganizacion: Fue imposible recuperar el error en el arranque de los gestores."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Fue imposible recuperar el error en el arranque de los gestores.", InfoTraza.NivelTraza.debug)); try { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "imposible_recuperar_arranque", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception e) { e.printStackTrace(); } } /** * Elabora un informe del estado en el que se encuentran el gestor de * agentes y el gestor de recursos y lo env�a al sistema de trazas. */ public void generarInformeErrorIrrecuperable() { // Producimos traza de un error logger.debug("GestorOrganizaci�n: Finalizando gestor de la organizacion debido a un error irrecuperable."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Finalizando gestor de la organizaci�n debido a un error irrecuperable.", InfoTraza.NivelTraza.debug)); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // EventoRecAgte("informe_generado", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("informe_generado"); } catch (Exception e) { e.printStackTrace(); } } /** * Monitoriza al gestor de recursos y al gestor de agentes. */ public void monitorizarGestores() { // monitorizamos los dos gestores en serie // if(DEBUG) System.out.println("GestorOrganizaci�n: Iniciando ciclo // de // monitorizaci�n"); boolean errorAlMonitorizar = false; int monitAgentes = 0; int monitRecursos = 0; try { monitAgentes = ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_AGENTES)) .obtenerEstado(); monitRecursos = ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)) .obtenerEstado(); // � hay problemas con el gestor de agentes ? errorAlMonitorizar = ((monitAgentes == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE) || (monitAgentes == InterfazGestion.ESTADO_ERRONEO_RECUPERABLE) || (monitAgentes == InterfazGestion.ESTADO_TERMINADO) || (monitAgentes == InterfazGestion.ESTADO_TERMINANDO)); if (errorAlMonitorizar) { logger.debug("GestorOrganizacion: Error al monitorizar gestores"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Error al monitorizar gestores", InfoTraza.NivelTraza.debug)); if ((monitAgentes == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE) || (monitAgentes == InterfazGestion.ESTADO_ERRONEO_RECUPERABLE)) { logger.error("GestorOrganizacion: El GESTOR DE AGENTES ha fallado. Su estado es " + monitAgentes); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "El GESTOR DE AGENTES ha fallado. Su estado es " + monitAgentes, InfoTraza.NivelTraza.error)); } else { logger.error("GestorOrganizacion: El GESTOR DE RECURSOS ha fallado. Su estado es " + monitRecursos); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "El GESTOR DE RECURSOS ha fallado. Su estado es " + monitRecursos, InfoTraza.NivelTraza.error)); this.itfUsoPropiadeEsteAgente .aceptaEvento(new EventoRecAgte( "error_al_monitorizar", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } } else { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "gestores_ok", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); // if(DEBUG) System.out.println("GestorOrganizaci�n: // Monitorizaci�n de los gestores ok"); } } catch (Exception ex) { ex.printStackTrace(); try { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "error_al_monitorizar", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception e) { e.printStackTrace(); } } } /** * Da orden de terminacion al gestor de agentes si est� activos. */ public void terminarGestorAgentes() { // mandamos la orden de terminar a los gestores logger.debug("GestorOrganizaci�n: Terminando gestor de agentes"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Terminando gestor de agentes", InfoTraza.NivelTraza.debug)); // InterfazGestion gestorAgentes; InterfazUsoAgente itfGestorAgentes; try { // gestorAgentes = (ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_AGENTES); // gestorAgentes.termina(); itfGestorAgentes = (InterfazUsoAgente) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + NombresPredefinidos.NOMBRE_GESTOR_AGENTES); // itfGestorAgentes.aceptaEvento(new // EventoRecAgte("ordenTerminacion", nombreAgente, // itfGestorAgentes.getIdentAgente())); itfGestorAgentes.aceptaMensaje(new MensajeSimple( new InfoContEvtMsgAgteReactivo("ordenTerminacion"), this.nombreAgente, NombresPredefinidos.NOMBRE_GESTOR_AGENTES)); // timeout de 5 segundosnew this.generarTimeOut(2000, "timeout_gestor_agentes", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); } catch (Exception ex) { logger.debug("GestorOrganizacion: No se pudo acceder al gestor de agentes."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "No se pudo acceder al gestor de agentes.", InfoTraza.NivelTraza.debug)); ex.printStackTrace(); } } /** * Da orden de terminacion al gestor de recursos si esta activo. */ public void terminarGestorRecursos() { // mandamos la orden de terminar a los gestores logger.debug("GestorOrganizacion: Terminando gestor de recursos"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Terminando gestor de recursos", InfoTraza.NivelTraza.debug)); InterfazUsoAgente gestorRecursos; try { // gestorRecursos = (ItfGestionAgenteReactivo) // this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS); // gestorRecursos.termina(); gestorRecursos = (InterfazUsoAgente) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_USO + NombresPredefinidos.NOMBRE_GESTOR_RECURSOS); // gestorRecursos.aceptaEvento(new EventoRecAgte("ordenTerminacion", // nombreAgente, gestorRecursos.getIdentAgente())); gestorRecursos.aceptaMensaje(new MensajeSimple( new InfoContEvtMsgAgteReactivo("ordenTerminacion"), this.nombreAgente, NombresPredefinidos.NOMBRE_GESTOR_RECURSOS)); // timeout de 5 segundosnew // timeout de 5 segundos this.generarTimeOut(2000, "timeout_gestor_recursos", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); } catch (Exception ex) { logger.debug("GestorOrganizacion: No se pudo acceder al gestor de recursos."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "No se pudo acceder al gestor de recursos.", InfoTraza.NivelTraza.debug)); ex.printStackTrace(); } } public void procesarPeticionTerminacion() { logger.debug("GestorOrganizacion: Procesando la peticion de terminacion"); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Procesando la peticion de terminacion", InfoTraza.NivelTraza.debug)); trazas.setIdentAgenteAReportar(nombreAgente); trazas.pedirConfirmacionTerminacionAlUsuario(); /* * try { // this.itfUsoAgente.aceptaEvento(new // * EventoRecAgte("termina",null,null)); * * * ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) * this.itfUsoRepositorio * .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + * NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); gestion.termina(); } * catch (Exception e) { e.printStackTrace(); } */ } public void comenzarTerminacionConfirmada() { logger.debug("GestorOrganizacion: Comenzando terminacion de la organizacion..."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Comenzando la terminacion de la organizacion...", InfoTraza.NivelTraza.info)); try { // String estadoInternoAgente = // this.ctrlGlobalAgenteReactivo.getItfControl().getEstadoControlAgenteReactivo(); // ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) // this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // gestion.termina(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // EventoRecAgte ("termina",this.nombreAgente,this.nombreAgente)); // this.ctrlGlobalAgenteReactivo.getItfControl().getEstadoControlAgenteReactivo(); this.informaraMiAutomata("termina"); } catch (Exception e) { e.printStackTrace(); } } public void recuperarErrorAlMonitorizarGestores() { // por defecto no se implementan pol�ticas de recuperaci�n logger.debug("GestorOrganizaci�n: No se pudo recuperar el error de monitorizaci�n."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "No se pudo recuperar el error de monitorizacion.", InfoTraza.NivelTraza.debug)); try { this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( "imposible_recuperar_error_monitorizacion", NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); } catch (Exception e) { e.printStackTrace(); } } /** * destruye los recursos que se crearon a lo largo del ciclo de vida del * gestor de la organizacion- */ public void terminarGestorOrganizacion() { // termina el gestor. // puede esperarse a que terminen los dos gestores para mayor seguridad logger.debug("GestorOrganizacion: Terminando gestor de la organizacion y los recursos de la infraestructura."); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Terminando gestor de la organizacion y los recursos de la infraestructura.", InfoTraza.NivelTraza.debug)); try { // se acaba con los recursos de la organizacion que necesiten ser // terminados itfGestionRecTrazas.termina(); // y a continuacion se termina el gestor de organizacion ((ItfGestionAgenteReactivo) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)) .termina(); } catch (Exception ex) { ex.printStackTrace(); } logger.debug("GestorOrganizacion: Cerrando sistema."); trazas.aceptaNuevaTraza(new InfoTraza(nombreAgente, "Cerrando sistema.", InfoTraza.NivelTraza.debug)); if (this.hebra != null) { this.hebra.finalizar(); } System.exit(0); /* * if (ORBDaemonExec.finalInstance() != null) { * ORBDaemonExec.finalInstance().finalize(); } */ } @Override public void clasificaError() { } public void tratarTerminacionNoConfirmada() { logger.debug("Se ha recibido un evento de timeout debido a que un gestor no ha confirmado la terminacion. Se procede a continuar la terminaci�n del sistema"); trazas.aceptaNuevaTraza(new InfoTraza( nombreAgente, "Se ha recibido un evento de timeout debido a que un gestor no ha confirmado la terminacion. Se procede a continuar la terminaci�n del sistema", InfoTraza.NivelTraza.debug)); try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "continuaTerminacion", // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); this.informaraMiAutomata("continuaTerminacion"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
SONIAGroup/S.O.N.I.A.
src/icaro/gestores/gestorOrganizacion/comportamiento/AccionesSemanticasGestorOrganizacion.java
Java
gpl-2.0
26,070
// InputFactory.hpp // KlayGE ÊäÈëÒýÇæ³éÏ󹤳§ Í·Îļþ // Ver 3.1.0 // °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2003-2005 // Homepage: http://www.klayge.org // // 3.1.0 // Ôö¼ÓÁËNullObject (2005.10.29) // // 2.0.0 // ³õ´Î½¨Á¢ (2003.8.30) // // Ð޸ļǼ ///////////////////////////////////////////////////////////////////////////////// #ifndef _INPUTFACTORY_HPP #define _INPUTFACTORY_HPP #pragma once #include <KlayGE/PreDeclare.hpp> #include <string> #include <boost/noncopyable.hpp> namespace KlayGE { class KLAYGE_CORE_API InputFactory { public: virtual ~InputFactory() { } static InputFactoryPtr NullObject(); virtual std::wstring const & Name() const = 0; InputEngine& InputEngineInstance(); void Suspend(); void Resume(); private: virtual InputEnginePtr DoMakeInputEngine() = 0; virtual void DoSuspend() = 0; virtual void DoResume() = 0; protected: InputEnginePtr ie_; }; template <typename InputEngineType> class ConcreteInputFactory : boost::noncopyable, public InputFactory { public: ConcreteInputFactory(std::wstring const & name) : name_(name) { } std::wstring const & Name() const { return name_; } private: InputEnginePtr DoMakeInputEngine() { return MakeSharedPtr<InputEngineType>(); } virtual void DoSuspend() KLAYGE_OVERRIDE { } virtual void DoResume() KLAYGE_OVERRIDE { } private: std::wstring const name_; }; } #endif // _INPUTFACTORY_HPP
qiankanglai/KlayGE
KlayGE/Core/Include/KlayGE/InputFactory.hpp
C++
gpl-2.0
1,431
/*************************************************************************** * 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. * * * * copyright (C) 2003 Brian Thomas <thomas@mail630.gsfc.nasa.gov> * * copyright (C) 2004-2014 * * Umbrello UML Modeller Authors <umbrello-devel@kde.org> * ***************************************************************************/ // own header #include "textblock.h" // local includes #include "codedocument.h" #include "codegenerationpolicy.h" #include "debug_utils.h" #include "uml.h" // qt includes #include <QRegExp> #include <QTextStream> /** * Constructor. */ TextBlock::TextBlock(CodeDocument * parent, const QString & text) : m_text(QString()), m_tag(QString()), m_canDelete(true), m_writeOutText(true), m_indentationLevel(0), m_parentDocument(parent) { setText(text); } /** * Destructor. */ TextBlock::~TextBlock() { } /** * Set the attribute m_canDelete. * @param canDelete the new value to set */ void TextBlock::setCanDelete(bool canDelete) { m_canDelete = canDelete; } /** * Determine if its OK to delete this textblock from the document. * Used by the text editor to know if deletion could cause a crash of * the program. * @return the value of m_canDelete */ bool TextBlock::canDelete() const { return m_canDelete; } /** * Get the value of m_parentDoc * @return the value of m_parentDoc */ CodeDocument * TextBlock::getParentDocument() const { return m_parentDocument; } /** * Set the value of m_text * The actual text of this code block. * @param text the new value of m_text */ void TextBlock::setText(const QString & text) { m_text = text; } /** * Add text to this object. * @param text the text to add */ void TextBlock::appendText(const QString & text) { m_text = m_text + text; } /** * Get the value of m_text * The actual text of this code block. * @return the value of m_text */ QString TextBlock::getText() const { return m_text; } /** * Get the tag of this text block. This tag * may be used to find this text block in the code document * to which it belongs. * @return the tag */ QString TextBlock::getTag() const { return m_tag; } /** * Set the tag of this text block. This tag * may be used to find this text block in the code document * to which it belongs. * @param value the new value for the tag */ void TextBlock::setTag(const QString & value) { m_tag = value; } /** * Set the value of m_writeOutText * Whether or not to include the text of this TextBlock into a file. * @param write the new value of m_writeOutText */ void TextBlock::setWriteOutText(bool write) { m_writeOutText = write; } /** * Get the value of m_writeOutText * Whether or not to include the text of this TextBlock into a file. * @return the value of m_writeOutText */ bool TextBlock::getWriteOutText() const { return m_writeOutText; } /** * Set how many times to indent this text block. * The amount of each indenatation is determined from the parent * codedocument codegeneration policy. * @param level the new value for the indentation level */ void TextBlock::setIndentationLevel(int level) { m_indentationLevel = level; } /** * Get how many times to indent this text block. * The amount of each indenatation is determined from the parent * codedocument codegeneration policy. * @return the indentation level */ int TextBlock::getIndentationLevel() const { return m_indentationLevel; } /** * Get the new line chars which ends the line. * @return the ending chars for new line */ QString TextBlock::getNewLineEndingChars() { CodeGenerationPolicy* policy = UMLApp::app()->commonPolicy(); return policy->getNewLineEndingChars(); } /** * Get how much a single "level" of indentation will actually indent. * @return the unit of indentation (for one level) */ QString TextBlock::getIndentation() { CodeGenerationPolicy* policy = UMLApp::app()->commonPolicy(); return policy->getIndentation(); } /** * Get the actual amount of indentation for a given level of indentation. * @param level the level of interest * @return the indentation string */ QString TextBlock::getIndentationString(int level) const { if (!level) { level = m_indentationLevel; } QString indentAmount = getIndentation(); QString indentation; for (int i=0; i<level; ++i) { indentation.append(indentAmount); } return indentation; } /** * TODO: Ush. These are terrifically bad and must one day go away. * Both methods indicate the range of lines in this textblock * which may be edited by the codeeditor (assuming that any are * actually editable). The default case is no lines are editable. * The line numbering starts with '0' and a '-1' means no line * qualifies. * @return line number */ int TextBlock::firstEditableLine() { return 0; } /** * @see firstEditableLine */ int TextBlock::lastEditableLine() { return 0; } /** * Used by the CodeEditor. It provides it with an appropriate * starting string for a new line of text within the given textblock * (for example a string with the proper indentation). * If the indentation amount is '0' the current indentation string will * be used. * <p> * TODO: Can be refactored away and replaced with * <a href="#getIndentationString">getIndentationString</a>. * @param amount the number of indent steps to use * @return the new line */ QString TextBlock::getNewEditorLine(int amount) { return getIndentationString(amount); } /** * UnFormat a long text string. Typically, this means removing * the indentaion (linePrefix) and/or newline chars from each line. * If an indentation is not specified, then the current indentation is used. * @param text the original text for unformatting * @param indent the indentation * @return the unformatted text */ QString TextBlock::unformatText(const QString & text, const QString & indent) { QString output = text; QString myIndent = indent; if (myIndent.isEmpty()) { myIndent = getIndentationString(); } if (!output.isEmpty()) { // remove indenation from this text block. output.remove(QRegExp(QLatin1Char('^') + myIndent)); } return output; } /** * Causes the text block to release all of its connections * and any other text blocks that it 'owns'. * Needed to be called prior to deletion of the textblock. * TODO: Does nothing. */ void TextBlock::release() { } /** * Format a long text string to be more readable. * @param work the original text for formatting * @param linePrefix a line prefix * @param breakStr a break string * @param addBreak control to add always a break string * @param lastLineHasBreak control to add a break string to the last line * @return the new formatted text */ QString TextBlock::formatMultiLineText(const QString & work, const QString & linePrefix, const QString & breakStr, bool addBreak, bool lastLineHasBreak) { QString output; QString text = work; QString endLine = getNewLineEndingChars(); int matches = text.indexOf(QRegExp(breakStr)); if (matches >= 0) { // check that last part of string matches, if not, then // we have to tack on extra match if (!text.contains(QRegExp(breakStr + QLatin1String("\\$")))) matches++; for (int i=0; i < matches; ++i) { QString line = text.section(QRegExp(breakStr), i, i); output += linePrefix + line; if ((i != matches-1) || lastLineHasBreak) output += endLine; // add break to line } } else { output = linePrefix + text; if (addBreak) output += breakStr; } return output; } /** * Set attributes of the node that represents this class * in the XMI document. * @param doc the xmi document * @param blockElement the xmi element holding the attributes */ void TextBlock::setAttributesOnNode(QDomDocument & doc, QDomElement & blockElement) { Q_UNUSED(doc); QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); blockElement.setAttribute(QLatin1String("tag"), getTag()); // only write these if different from defaults const QString trueStr = QLatin1String("true"); const QString falseStr = QLatin1String("false"); if (getIndentationLevel()) blockElement.setAttribute(QLatin1String("indentLevel"), QString::number(getIndentationLevel())); if (!m_text.isEmpty()) blockElement.setAttribute(QLatin1String("text"), encodeText(m_text, endLine)); if (!getWriteOutText()) blockElement.setAttribute(QLatin1String("writeOutText"), getWriteOutText() ? trueStr : falseStr); if (!canDelete()) blockElement.setAttribute(QLatin1String("canDelete"), canDelete() ? trueStr : falseStr); } /** * Set the class attributes from a passed object. * @param obj text block from which the attributes are taken */ void TextBlock::setAttributesFromObject(TextBlock * obj) { // DON'T set tag here. setIndentationLevel(obj->getIndentationLevel()); setText(obj->getText()); setWriteOutText(obj->getWriteOutText()); m_canDelete = obj->canDelete(); } /** * Set the class attributes of this object from * the passed element node. * @param root the xmi element from which to load */ void TextBlock::setAttributesFromNode(QDomElement & root) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); setIndentationLevel(root.attribute(QLatin1String("indentLevel"), QLatin1String("0")).toInt()); setTag(root.attribute(QLatin1String("tag"))); setText(decodeText(root.attribute(QLatin1String("text")), endLine)); const QString trueStr = QLatin1String("true"); setWriteOutText(root.attribute(QLatin1String("writeOutText"), trueStr) == trueStr); m_canDelete = root.attribute(QLatin1String("canDelete"), trueStr) == trueStr; } /** * Encode text for XML storage. * We simply convert all types of newLines to the "\n" or &#010; * entity. * @param text the not yet encoded text * @param endLine the chars at the end of each line * @return the encoded text */ QString TextBlock::encodeText(const QString & text, const QString & endLine) { QString encoded = text; encoded.replace(QRegExp(endLine), QLatin1String("&#010;")); return encoded; } /** * Decode text from XML storage. * We simply convert all newLine entity &#010; to chosen line ending. * @param text the not yet decoded text * @param endLine the chars at the end of each line * @return the decoded text */ QString TextBlock::decodeText(const QString & text, const QString & endLine) { QString decoded = text; decoded.replace(QRegExp(QLatin1String("&#010;")), endLine); return decoded; } /** * Return the text in the right format. Returned string is empty * if m_writeOutText is false. * @return QString */ QString TextBlock::toString() const { // simple output method if (m_writeOutText && !m_text.isEmpty()) { QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); return formatMultiLineText(m_text, getIndentationString(), endLine); } else { return QString(); } } /** * Operator '<<' for TextBlock. */ QDebug operator<<(QDebug os, const TextBlock& obj) { os.nospace() << "TextBlock: tag=" << obj.getTag() << ", writeOutText=" << (obj.getWriteOutText() ? "true" : "false") << ", canDelete=" << (obj.canDelete() ? "true" : "false") << ", indentationLevel=" << obj.getIndentationLevel() << ", parentDocument id=" << (obj.getParentDocument() ? obj.getParentDocument()->ID() : QLatin1String("null")) << ", text=" << obj.getText(); return os.space(); }
behlingc/umbrello-behlingc
umbrello/codegenerators/textblock.cpp
C++
gpl-2.0
12,390
<?php /** * @version 2.9.x * @package K2 * @author JoomlaWorks https://www.joomlaworks.net * @copyright Copyright (c) 2006 - 2018 JoomlaWorks Ltd. All rights reserved. * @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html */ // no direct access defined('_JEXEC') or die; if (K2_JVERSION != '15') { $language = JFactory::getLanguage(); $language->load('com_k2.dates', JPATH_ADMINISTRATOR, null, true); } require_once(dirname(__FILE__).'/helper.php'); // Params $moduleclass_sfx = $params->get('moduleclass_sfx', ''); $getTemplate = $params->get('getTemplate', 'Default'); $itemAuthorAvatarWidthSelect = $params->get('itemAuthorAvatarWidthSelect', 'custom'); $itemAuthorAvatarWidth = $params->get('itemAuthorAvatarWidth', 50); $itemCustomLinkTitle = $params->get('itemCustomLinkTitle', ''); $itemCustomLinkURL = trim($params->get('itemCustomLinkURL')); $itemCustomLinkMenuItem = $params->get('itemCustomLinkMenuItem'); if ($itemCustomLinkURL && ($itemCustomLinkURL!='http://' || $itemCustomLinkURL!='https://')) { if ($itemCustomLinkTitle=='') { if (strpos($itemCustomLinkURL, '://')!==false) { $linkParts = explode('://', $itemCustomLinkURL); $itemCustomLinkURL = $linkParts[1]; } $itemCustomLinkTitle = $itemCustomLinkURL; } } elseif ($itemCustomLinkMenuItem) { $menu = JMenu::getInstance('site'); $menuLink = $menu->getItem($itemCustomLinkMenuItem); if (!$itemCustomLinkTitle) { $itemCustomLinkTitle = (K2_JVERSION != '15') ? $menuLink->title : $menuLink->name; } $itemCustomLinkURL = JRoute::_('index.php?&Itemid='.$menuLink->id); } // Make params backwards compatible $params->set('itemCustomLinkTitle', $itemCustomLinkTitle); $params->set('itemCustomLinkURL', $itemCustomLinkURL); // Get component params $componentParams = JComponentHelper::getParams('com_k2'); // User avatar if ($itemAuthorAvatarWidthSelect == 'inherit') { $avatarWidth = $componentParams->get('userImageWidth'); } else { $avatarWidth = $itemAuthorAvatarWidth; } $items = modK2ContentHelper::getItems($params); if (count($items)) { require(JModuleHelper::getLayoutPath('mod_k2_content', $getTemplate.'/default')); }
renebentes/joomla-3.x
modules/mod_k2_content/mod_k2_content.php
PHP
gpl-2.0
2,235
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MediaBrowser.Controller.Providers; namespace MediaBrowser.Providers.Manager { public class SeriesOrderManager : ISeriesOrderManager { private Dictionary<string, ISeriesOrderProvider[]> _providers; public void AddParts(IEnumerable<ISeriesOrderProvider> orderProviders) { _providers = orderProviders .GroupBy(p => p.OrderType) .ToDictionary(g => g.Key, g => g.ToArray()); } public async Task<int?> FindSeriesIndex(string orderType, string seriesName) { ISeriesOrderProvider[] providers; if (!_providers.TryGetValue(orderType, out providers)) return null; foreach (ISeriesOrderProvider provider in providers) { int? index = await provider.FindSeriesIndex(seriesName); if (index != null) return index; } return null; } } }
ChubbyArse/Emby
MediaBrowser.Providers/Manager/SeriesOrderManager.cs
C#
gpl-2.0
1,067
"use strict"; describe("Services: bigQueryLogging", function() { beforeEach(module("risevision.common.components.logging")); var bigQueryLogging, httpResp, forceHttpError, externalLogEventSpy; beforeEach(module(function($provide) { $provide.service("$q", function() {return Q;}); $provide.factory("externalLogging", [function () { return { logEvent: function(eventName, eventDetails, eventValue, userId, companyId) { console.log(eventName, eventDetails, eventValue,userId, companyId); var deferred = Q.defer(); if (forceHttpError) { deferred.reject("Http Error"); } else { deferred.resolve(httpResp); } deferred.resolve(httpResp); return deferred.promise; } }; }]); $provide.factory("userState", [function () { return { getUsername: function() {return "user1";}, getSelectedCompanyId: function() {return "company1";} }; }]); })); beforeEach(function() { inject(function($injector){ forceHttpError = false; bigQueryLogging = $injector.get("bigQueryLogging"); var externalLogging = $injector.get("externalLogging"); externalLogEventSpy = sinon.spy(externalLogging,"logEvent"); }); }); it("should exist",function() { expect(bigQueryLogging.logEvent).to.be.a("function"); }); describe("logEvent:", function(){ it("should POST with userId and companyId if not provided",function(done){ bigQueryLogging.logEvent("eventName","details",1).then(function(){ externalLogEventSpy.should.have.been.calledWith("eventName","details",1,"user1","company1"); done(); }).then(null,done); }); it("should POST with custom userId and companyId",function(done){ bigQueryLogging.logEvent("eventName","details",1, "myUser", "myCompany").then(function(){ externalLogEventSpy.should.have.been.calledWith("eventName","details",1,"myUser","myCompany"); done(); }).then(null,done); }); it("should handle http error",function(done){ forceHttpError = true; bigQueryLogging.logEvent("eventName","details",1).then(function(){ done(new Error("Should have rejected")); },function(){ done(); }).then(null,done); }); }); });
Rise-Vision/common-header
test/unit/components/userstate/services/svc-big-query-logging.tests.js
JavaScript
gpl-3.0
2,365
//>>built define("dijit/_KeyNavMixin",["dojo/_base/array","dojo/_base/declare","dojo/dom-attr","dojo/keys","dojo/_base/lang","dojo/on","dijit/registry","dijit/_FocusMixin"],function(_1,_2,_3,_4,_5,on,_6,_7){ return _2("dijit._KeyNavMixin",_7,{tabIndex:"0",childSelector:null,postCreate:function(){ this.inherited(arguments); _3.set(this.domNode,"tabIndex",this.tabIndex); if(!this._keyNavCodes){ var _8=this._keyNavCodes={}; _8[_4.HOME]=_5.hitch(this,"focusFirstChild"); _8[_4.END]=_5.hitch(this,"focusLastChild"); _8[this.isLeftToRight()?_4.LEFT_ARROW:_4.RIGHT_ARROW]=_5.hitch(this,"_onLeftArrow"); _8[this.isLeftToRight()?_4.RIGHT_ARROW:_4.LEFT_ARROW]=_5.hitch(this,"_onRightArrow"); _8[_4.UP_ARROW]=_5.hitch(this,"_onUpArrow"); _8[_4.DOWN_ARROW]=_5.hitch(this,"_onDownArrow"); } var _9=this,_a=typeof this.childSelector=="string"?this.childSelector:_5.hitch(this,"childSelector"); this.own(on(this.domNode,"keypress",_5.hitch(this,"_onContainerKeypress")),on(this.domNode,"keydown",_5.hitch(this,"_onContainerKeydown")),on(this.domNode,"focus",_5.hitch(this,"_onContainerFocus")),on(this.containerNode,on.selector(_a,"focusin"),function(_b){ _9._onChildFocus(_6.getEnclosingWidget(this),_b); })); },_onLeftArrow:function(){ },_onRightArrow:function(){ },_onUpArrow:function(){ },_onDownArrow:function(){ },focus:function(){ this.focusFirstChild(); },_getFirstFocusableChild:function(){ return this._getNextFocusableChild(null,1); },_getLastFocusableChild:function(){ return this._getNextFocusableChild(null,-1); },focusFirstChild:function(){ this.focusChild(this._getFirstFocusableChild()); },focusLastChild:function(){ this.focusChild(this._getLastFocusableChild()); },focusChild:function(_c,_d){ if(!_c){ return; } if(this.focusedChild&&_c!==this.focusedChild){ this._onChildBlur(this.focusedChild); } _c.set("tabIndex",this.tabIndex); _c.focus(_d?"end":"start"); },_onContainerFocus:function(_e){ if(_e.target!==this.domNode||this.focusedChild){ return; } this.focus(); },_onFocus:function(){ _3.set(this.domNode,"tabIndex","-1"); this.inherited(arguments); },_onBlur:function(_f){ _3.set(this.domNode,"tabIndex",this.tabIndex); if(this.focusedChild){ this.focusedChild.set("tabIndex","-1"); this.lastFocusedChild=this.focusedChild; this._set("focusedChild",null); } this.inherited(arguments); },_onChildFocus:function(_10){ if(_10&&_10!=this.focusedChild){ if(this.focusedChild&&!this.focusedChild._destroyed){ this.focusedChild.set("tabIndex","-1"); } _10.set("tabIndex",this.tabIndex); this.lastFocused=_10; this._set("focusedChild",_10); } },_searchString:"",multiCharSearchDuration:1000,onKeyboardSearch:function(_11,evt,_12,_13){ if(_11){ this.focusChild(_11); } },_keyboardSearchCompare:function(_14,_15){ var _16=_14.domNode,_17=_14.label||(_16.focusNode?_16.focusNode.label:"")||_16.innerText||_16.textContent||"",_18=_17.replace(/^\s+/,"").substr(0,_15.length).toLowerCase(); return (!!_15.length&&_18==_15)?-1:0; },_onContainerKeydown:function(evt){ var _19=this._keyNavCodes[evt.keyCode]; if(_19){ _19(evt,this.focusedChild); evt.stopPropagation(); evt.preventDefault(); this._searchString=""; }else{ if(evt.keyCode==_4.SPACE&&this._searchTimer&&!(evt.ctrlKey||evt.altKey||evt.metaKey)){ evt.stopImmediatePropagation(); evt.preventDefault(); this._keyboardSearch(evt," "); } } },_onContainerKeypress:function(evt){ if(evt.charCode<_4.SPACE||evt.ctrlKey||evt.altKey||evt.metaKey||(evt.charCode==_4.SPACE&&this._searchTimer)){ return; } evt.preventDefault(); evt.stopPropagation(); this._keyboardSearch(evt,String.fromCharCode(evt.charCode).toLowerCase()); },_keyboardSearch:function(evt,_1a){ var _1b=null,_1c,_1d=0,_1e=_5.hitch(this,function(){ if(this._searchTimer){ this._searchTimer.remove(); } this._searchString+=_1a; var _1f=/^(.)\1*$/.test(this._searchString); var _20=_1f?1:this._searchString.length; _1c=this._searchString.substr(0,_20); this._searchTimer=this.defer(function(){ this._searchTimer=null; this._searchString=""; },this.multiCharSearchDuration); var _21=this.focusedChild||null; if(_20==1||!_21){ _21=this._getNextFocusableChild(_21,1); if(!_21){ return; } } var _22=_21; do{ var rc=this._keyboardSearchCompare(_21,_1c); if(!!rc&&_1d++==0){ _1b=_21; } if(rc==-1){ _1d=-1; break; } _21=this._getNextFocusableChild(_21,1); }while(_21!=_22); }); _1e(); this.onKeyboardSearch(_1b,evt,_1c,_1d); },_onChildBlur:function(){ },_getNextFocusableChild:function(_23,dir){ var _24=_23; do{ if(!_23){ _23=this[dir>0?"_getFirst":"_getLast"](); if(!_23){ break; } }else{ _23=this._getNext(_23,dir); } if(_23!=null&&_23!=_24&&_23.isFocusable()){ return _23; } }while(_23!=_24); return null; },_getFirst:function(){ return null; },_getLast:function(){ return null; },_getNext:function(_25,dir){ if(_25){ _25=_25.domNode; while(_25){ _25=_25[dir<0?"previousSibling":"nextSibling"]; if(_25&&"getAttribute" in _25){ var w=_6.byNode(_25); if(w){ return w; } } } } return null; }}); });
cryo3d/cryo3d
static/ThirdParty/dojo-release-1.9.3/dijit/_KeyNavMixin.js
JavaScript
gpl-3.0
5,071
namespace NzbDrone.Core.Download.Clients.Transmission { public class TransmissionTorrent { public int Id { get; set; } public string HashString { get; set; } public string Name { get; set; } public string DownloadDir { get; set; } public long TotalSize { get; set; } public long LeftUntilDone { get; set; } public bool IsFinished { get; set; } public int Eta { get; set; } public TransmissionTorrentStatus Status { get; set; } public int SecondsDownloading { get; set; } public int SecondsSeeding { get; set; } public string ErrorString { get; set; } public long DownloadedEver { get; set; } public long UploadedEver { get; set; } public double SeedRatioLimit { get; set; } public int SeedRatioMode { get; set; } public long SeedIdleLimit { get; set; } public int SeedIdleMode { get; set; } public int FileCount { get; set; } } }
Radarr/Radarr
src/NzbDrone.Core/Download/Clients/Transmission/TransmissionTorrent.cs
C#
gpl-3.0
997
package com.nisovin.magicspells.spells.targeted; import org.bukkit.Location; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import com.nisovin.magicspells.spelleffects.EffectPosition; import com.nisovin.magicspells.spells.TargetedEntitySpell; import com.nisovin.magicspells.spells.TargetedSpell; import com.nisovin.magicspells.util.MagicConfig; import com.nisovin.magicspells.util.TargetInfo; import com.nisovin.magicspells.util.Util; public class RotateSpell extends TargetedSpell implements TargetedEntitySpell { boolean random; int rotation; public RotateSpell(MagicConfig config, String spellName) { super(config, spellName); random = getConfigBoolean("random", false); rotation = getConfigInt("rotation", 10); } @Override public PostCastAction castSpell(Player player, SpellCastState state, float power, String[] args) { if (state == SpellCastState.NORMAL) { TargetInfo<LivingEntity> target = getTargetedEntity(player, power); if (target == null) { return noTarget(player); } spin(target.getTarget()); playSpellEffects(player, target.getTarget()); } return PostCastAction.HANDLE_NORMALLY; } void spin(LivingEntity target) { if (random) { Location loc = target.getLocation(); loc.setYaw(Util.getRandomInt(360)); target.teleport(loc); } else { Location loc = target.getLocation(); loc.setYaw(loc.getYaw() + rotation); target.teleport(loc); } } @Override public boolean castAtEntity(Player caster, LivingEntity target, float power) { spin(target); playSpellEffects(caster, target); return true; } @Override public boolean castAtEntity(LivingEntity target, float power) { spin(target); playSpellEffects(EffectPosition.TARGET, target); return true; } }
usevalue/MagicSpells
src/com/nisovin/magicspells/spells/targeted/RotateSpell.java
Java
gpl-3.0
1,772
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('monitoring', '0002_monitoring_update'), ] operations = [ migrations.RemoveField( model_name='requestevent', name='resources', ), migrations.AddField( model_name='requestevent', name='resources', field=models.ManyToManyField(help_text='List of resources affected', to='monitoring.MonitoredResource', null=True, blank=True), ), ]
tomkralidis/geonode
geonode/monitoring/migrations/0003_monitoring_resources.py
Python
gpl-3.0
572
#region License // ==================================================== // Project Porcupine Copyright(C) 2016 Team Porcupine // This program comes with ABSOLUTELY NO WARRANTY; This is free software, // and you are welcome to redistribute it under certain conditions; See // file LICENSE, which is part of this source code package, for details. // ==================================================== #endregion using UnityEngine; public class ShipSpriteController : BaseSpriteController<Ship> { public ShipSpriteController(World world) : base(world, "Ships", 10) { world.ShipManager.ShipCreated += OnCreated; world.ShipManager.ShipRemoved += OnRemoved; } protected override void OnCreated(Ship ship) { UnityDebugger.Debugger.Log("Ships", "Ship created: " + ship.Type); GameObject ship_go = new GameObject(); // Add our tile/GO pair to the dictionary. objectGameObjectMap.Add(ship, ship_go); ship_go.name = "Ship"; ship_go.transform.SetParent(objectParent.transform, true); SpriteRenderer sr = ship_go.AddComponent<SpriteRenderer>(); sr.sortingLayerName = "Characters"; sr.sprite = SpriteManager.GetSprite("Ship", ship.Type); ship.ShipChanged += OnChanged; } protected override void OnChanged(Ship ship) { GameObject ship_go = objectGameObjectMap[ship]; ship_go.transform.position = new Vector3(ship.Position.x, ship.Position.y, 0); if (ship.State == ShipState.UNWRAPPED) { ship_go.GetComponent<SpriteRenderer>().enabled = false; } else { ship_go.GetComponent<SpriteRenderer>().enabled = true; } } protected override void OnRemoved(Ship ship) { GameObject ship_go = objectGameObjectMap[ship]; GameObject.Destroy(ship_go); objectGameObjectMap.Remove(ship); } }
NogginBops/ProjectPorcupine
Assets/Scripts/Controllers/ShipSpriteController.cs
C#
gpl-3.0
1,932
/* * Copyright 2010 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid 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. * * KeePassDroid 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 KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ package com.keepassdroid.stream; import java.io.IOException; import java.io.OutputStream; /** Little Endian version of the DataOutputStream * @author bpellin * */ public class LEDataOutputStream extends OutputStream { private OutputStream baseStream; public LEDataOutputStream(OutputStream out) { baseStream = out; } public void writeUInt(long uint) throws IOException { baseStream.write(LEDataOutputStream.writeIntBuf((int) uint)); } @Override public void close() throws IOException { baseStream.close(); } @Override public void flush() throws IOException { baseStream.flush(); } @Override public void write(byte[] buffer, int offset, int count) throws IOException { baseStream.write(buffer, offset, count); } @Override public void write(byte[] buffer) throws IOException { baseStream.write(buffer); } @Override public void write(int oneByte) throws IOException { baseStream.write(oneByte); } public void writeLong(long val) throws IOException { byte[] buf = new byte[8]; writeLong(val, buf, 0); baseStream.write(buf); } public void writeInt(int val) throws IOException { byte[] buf = new byte[4]; writeInt(val, buf, 0); baseStream.write(buf); } public void writeUShort(int val) throws IOException { byte[] buf = new byte[2]; writeUShort(val, buf, 0); baseStream.write(buf); } public static byte[] writeIntBuf(int val) { byte[] buf = new byte[4]; writeInt(val, buf, 0); return buf; } public static byte[] writeUShortBuf(int val) { byte[] buf = new byte[2]; writeUShort(val, buf, 0); return buf; } /** Write an unsigned 16-bit value * * @param val * @param buf * @param offset */ public static void writeUShort(int val, byte[] buf, int offset) { buf[offset + 0] = (byte)(val & 0x00FF); buf[offset + 1] = (byte)((val & 0xFF00) >> 8); } /** * Write a 32-bit value. * * @param val * @param buf * @param offset */ public static void writeInt( int val, byte[] buf, int offset ) { buf[offset + 0] = (byte)(val & 0xFF); buf[offset + 1] = (byte)((val >>> 8) & 0xFF); buf[offset + 2] = (byte)((val >>> 16) & 0xFF); buf[offset + 3] = (byte)((val >>> 24) & 0xFF); } public static byte[] writeLongBuf(long val) { byte[] buf = new byte[8]; writeLong(val, buf, 0); return buf; } public static void writeLong( long val, byte[] buf, int offset ) { buf[offset + 0] = (byte)(val & 0xFF); buf[offset + 1] = (byte)((val >>> 8) & 0xFF); buf[offset + 2] = (byte)((val >>> 16) & 0xFF); buf[offset + 3] = (byte)((val >>> 24) & 0xFF); buf[offset + 4] = (byte)((val >>> 32) & 0xFF); buf[offset + 5] = (byte)((val >>> 40) & 0xFF); buf[offset + 6] = (byte)((val >>> 48) & 0xFF); buf[offset + 7] = (byte)((val >>> 56) & 0xFF); } }
red13dotnet/keepass2android
src/java/KP2AKdbLibrary/src/com/keepassdroid/stream/LEDataOutputStream.java
Java
gpl-3.0
3,614
/* * Font.cpp * * Copyright (C) 2012 Simon Lehmann * * This file is part of Actracktive. * * Actracktive 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. * * Actracktive 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ #include "gluit/Font.h" #include "gluit/Graphics.h" #include "gluit/Utils.h" #include <algorithm> #include <boost/make_shared.hpp> #include <boost/algorithm/string.hpp> namespace gluit { static const FT_Error SUCCESS = 0; static const std::size_t NUMBER_OF_CHARACTERS = UCHAR_MAX + 1; static const std::string EX_CHARS = "xuvw"; FontFaceId::FontFaceId(const std::string& family, const std::string& style) : family(boost::algorithm::to_lower_copy(family)), style(boost::algorithm::to_lower_copy(style)) { } bool FontFaceId::operator<(const FontFaceId& other) const { return family < other.family || (family == other.family && style < other.style); } bool FontFaceId::operator<=(const FontFaceId& other) const { return *this < other || *this == other; } bool FontFaceId::operator>(const FontFaceId& other) const { return family > other.family || (family == other.family && style > other.style); } bool FontFaceId::operator>=(const FontFaceId& other) const { return *this > other || *this == other; } bool FontFaceId::operator==(const FontFaceId& other) const { return family == other.family && style == other.style; } bool FontFaceId::operator!=(const FontFaceId& other) const { return !(*this == other); } FontId::FontId(const std::string& family, const std::string& style, const unsigned int& size) : face(family, style), size(size) { } FontId::FontId(const FontFaceId& face, const unsigned int& size) : face(face), size(size) { } bool FontId::operator<(const FontId& other) const { return face < other.face || (face == other.face && size < other.size); } bool FontId::operator<=(const FontId& other) const { return *this < other || *this == other; } bool FontId::operator>(const FontId& other) const { return face > other.face || (face == other.face && size > other.size); } bool FontId::operator>=(const FontId& other) const { return *this > other || *this == other; } bool FontId::operator==(const FontId& other) const { return face == other.face && size == other.size; } bool FontId::operator!=(const FontId& other) const { return !(*this == other); } Font::CharProps::CharProps() : valid(false), advance(0), bitmapBearing(0, 0), bitmap() { } Font::Font() : id(FontFaceId("", ""), 0), lineHeight(0), exHeight(0), ascenderHeight(0), descenderHeight(0), characters() { } Font::Font(FT_Face face, const FontId& id) : id(id), lineHeight(0), exHeight(0), ascenderHeight(0), descenderHeight(0), characters() { lineHeight = gluit::round(id.size * 1.4f); int maxDescent = 0; int maxAscent = 0; characters.resize(NUMBER_OF_CHARACTERS); unsigned char charCode = 0; for (std::vector<CharProps>::iterator character = characters.begin(); character != characters.end(); ++character) { if (FT_Load_Glyph(face, FT_Get_Char_Index(face, FT_ULong(charCode)), FT_LOAD_RENDER | FT_LOAD_NO_AUTOHINT) == SUCCESS) { const FT_Bitmap& bitmap = face->glyph->bitmap; character->valid = true; character->advance = face->glyph->advance.x >> 6; character->bitmapBearing = Point(face->glyph->bitmap_left, -face->glyph->bitmap_top); maxAscent = std::max(maxAscent, face->glyph->bitmap_top); maxDescent = std::max(maxDescent, bitmap.rows - face->glyph->bitmap_top); character->bitmap = boost::make_shared<RasterImage>(Size::fromInt(bitmap.width, bitmap.rows), RasterImage::GRAY_ALPHA); RasterAccess raster(character->bitmap); for (unsigned int y = 0; y < raster.size.height; ++y) { for (unsigned int x = 0; x < raster.size.width; ++x) { raster.data[2 * (y * raster.size.width + x)] = 255; // luminance raster.data[2 * (y * raster.size.width + x) + 1] = bitmap.buffer[y * bitmap.pitch + x]; // alpha } } } else { character->valid = false; } charCode += 1; } float exHeightSum = 0; unsigned int validChars = 0; for (std::string::const_iterator exChar = EX_CHARS.begin(); exChar != EX_CHARS.end(); ++exChar) { const CharProps& character = characters[*exChar]; if (character.valid) { validChars += 1; exHeightSum += -(character.bitmapBearing.y); } } ascenderHeight = maxAscent; descenderHeight = maxDescent; if (validChars > 0) { exHeight = gluit::round(exHeightSum / float(validChars)); } else { exHeight = 0; } } bool Font::isEmpty() const { return characters.empty(); } const FontId& Font::getId() const { return id; } unsigned int Font::getSize() const { return id.size; } unsigned int Font::getLineHeight() const { return lineHeight; } unsigned int Font::getExHeight() const { return exHeight; } unsigned int Font::getAscenderHeight() const { return ascenderHeight; } unsigned int Font::getDescenderHeight() const { return descenderHeight; } Rectangle Font::getBoundingBox(const std::string& text) const { if (isEmpty() || text.empty()) { return Rectangle::ZERO; } Rectangle bounds = Rectangle::ZERO; int xoffset = 0; int yoffset = 0; for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) { unsigned char c = *it; const CharProps& character = characters[c]; if (c == '\n') { yoffset += lineHeight; xoffset = 0; } else if (character.valid) { Size size = character.bitmap->getSize(); Point p1 = character.bitmapBearing.move(xoffset, yoffset); Point p2 = p1.move(size.width, size.height); bounds = bounds.combineVisible(Rectangle::fromCoordinates(p1, p2)); xoffset += character.advance; } } return bounds; } void Font::draw(const Graphics& g2, const std::string& text) const { if (isEmpty()) { return; } Graphics g(g2); GLfloat xoffset = 0; for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) { unsigned char c = *it; const CharProps& character = characters[c]; if (c == '\n') { g.translate(-xoffset, lineHeight); xoffset = 0; } else if (character.valid) { g.drawRasterImage(character.bitmap, character.bitmapBearing, true); g.translate(character.advance, 0); xoffset += character.advance; } } } }
simonlmn/actracktive
src/gluit/Font.cpp
C++
gpl-3.0
6,877
import PropTypes from 'prop-types'; import React from 'react'; import Icon from 'Components/Icon'; import Link from 'Components/Link/Link'; import { icons } from 'Helpers/Props'; import styles from './ModalContent.css'; function ModalContent(props) { const { className, children, showCloseButton, onModalClose, ...otherProps } = props; return ( <div className={className} {...otherProps} > { showCloseButton && <Link className={styles.closeButton} onPress={onModalClose} > <Icon name={icons.CLOSE} size={18} /> </Link> } {children} </div> ); } ModalContent.propTypes = { className: PropTypes.string, children: PropTypes.node, showCloseButton: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; ModalContent.defaultProps = { className: styles.modalContent, showCloseButton: true }; export default ModalContent;
Radarr/Radarr
frontend/src/Components/Modal/ModalContent.js
JavaScript
gpl-3.0
1,031
#region Copyright & License Information /* * Copyright 2007-2020 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using System; using System.ComponentModel; using System.Net; namespace OpenRA { public class Download { readonly object syncObject = new object(); WebClient wc; public static string FormatErrorMessage(Exception e) { var ex = e as WebException; if (ex == null) return e.Message; switch (ex.Status) { case WebExceptionStatus.RequestCanceled: return "Cancelled"; case WebExceptionStatus.NameResolutionFailure: return "DNS lookup failed"; case WebExceptionStatus.Timeout: return "Connection timeout"; case WebExceptionStatus.ConnectFailure: return "Cannot connect to remote server"; case WebExceptionStatus.ProtocolError: return "File not found on remote server"; default: return ex.Message; } } void EnableTLS12OnWindows() { // Enable TLS 1.2 on Windows: .NET 4.7 on Windows 10 only supports obsolete protocols by default // SecurityProtocolType.Tls12 is not defined in the .NET 4.5 reference dlls used by mono, // so we must use the enum's constant value directly if (Platform.CurrentPlatform == PlatformType.Windows) ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; } public Download(string url, string path, Action<DownloadProgressChangedEventArgs> onProgress, Action<AsyncCompletedEventArgs> onComplete) { EnableTLS12OnWindows(); lock (syncObject) { wc = new WebClient { Proxy = null }; wc.DownloadProgressChanged += (_, a) => onProgress(a); wc.DownloadFileCompleted += (_, a) => { DisposeWebClient(); onComplete(a); }; wc.DownloadFileAsync(new Uri(url), path); } } public Download(string url, Action<DownloadProgressChangedEventArgs> onProgress, Action<DownloadDataCompletedEventArgs> onComplete) { EnableTLS12OnWindows(); lock (syncObject) { wc = new WebClient { Proxy = null }; wc.DownloadProgressChanged += (_, a) => onProgress(a); wc.DownloadDataCompleted += (_, a) => { DisposeWebClient(); onComplete(a); }; wc.DownloadDataAsync(new Uri(url)); } } void DisposeWebClient() { lock (syncObject) { wc.Dispose(); wc = null; } } public void CancelAsync() { lock (syncObject) wc?.CancelAsync(); } } }
atlimit8/OpenRA
OpenRA.Game/Download.cs
C#
gpl-3.0
2,659
# encoding: utf-8 from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Application.content_type' db.add_column('applications_application', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False) # Adding field 'Application.object_id' db.add_column('applications_application', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Deleting field 'UserApplication.object_id' db.delete_column('applications_userapplication', 'object_id') # Deleting field 'UserApplication.content_type' db.delete_column('applications_userapplication', 'content_type_id') def backwards(self, orm): # Deleting field 'Application.content_type' db.delete_column('applications_application', 'content_type_id') # Deleting field 'Application.object_id' db.delete_column('applications_application', 'object_id') # Adding field 'UserApplication.object_id' db.add_column('applications_userapplication', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding field 'UserApplication.content_type' db.add_column('applications_userapplication', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False) models = { 'applications.applicant': { 'Meta': {'object_name': 'Applicant'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']", 'null': 'True', 'blank': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '16', 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'applications.application': { 'Meta': {'object_name': 'Application'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'content_type_temp': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'app_temp_obj'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Person']", 'null': 'True', 'blank': 'True'}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateTimeField', [], {}), 'header_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'object_id_temp': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'secret_token': ('django.db.models.fields.CharField', [], {'default': "'f0369b28f1adc73f2c0c351ed377febb0fa872d4'", 'unique': 'True', 'max_length': '64'}), 'state': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}), 'submitted_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'applications.projectapplication': { 'Meta': {'object_name': 'ProjectApplication', '_ormbases': ['applications.Application']}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['applications.Application']", 'unique': 'True', 'primary_key': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['machines.MachineCategory']", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'user_applications': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['applications.UserApplication']", 'null': 'True', 'blank': 'True'}) }, 'applications.userapplication': { 'Meta': {'object_name': 'UserApplication', '_ormbases': ['applications.Application']}, 'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['applications.Application']", 'unique': 'True', 'primary_key': 'True'}), 'make_leader': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'needs_account': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'null': 'True', 'blank': 'True'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'machines.machinecategory': { 'Meta': {'object_name': 'MachineCategory', 'db_table': "'machine_category'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.institute': { 'Meta': {'object_name': 'Institute', 'db_table': "'institute'"}, 'active_delegate': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'active_delegate'", 'null': 'True', 'to': "orm['people.Person']"}), 'delegate': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'delegate'", 'null': 'True', 'to': "orm['people.Person']"}), 'gid': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'sub_delegates': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'sub_delegates'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['people.Person']"}) }, 'people.person': { 'Meta': {'object_name': 'Person', 'db_table': "'person'"}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_approver'", 'null': 'True', 'to': "orm['people.Person']"}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_deletor'", 'null': 'True', 'to': "orm['people.Person']"}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'projects.project': { 'Meta': {'object_name': 'Project', 'db_table': "'project'"}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_approver'", 'null': 'True', 'to': "orm['people.Person']"}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_deletor'", 'null': 'True', 'to': "orm['people.Person']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_expertise': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'leaders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'leaders'", 'symmetrical': 'False', 'to': "orm['people.Person']"}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'projects'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['machines.MachineCategory']"}), 'machine_category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.MachineCategory']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['people.Person']", 'null': 'True', 'blank': 'True'}) } } complete_apps = ['applications']
Karaage-Cluster/karaage-debian
karaage/legacy/applications/south_migrations/0004_auto__add_field_application_content_type__add_field_application_object.py
Python
gpl-3.0
17,096
<?php /** * Copyright © OXID eSales AG. All rights reserved. * See LICENSE file for license details. */ declare(strict_types=1); namespace OxidEsales\EshopCommunity\Internal\Domain\Admin\Exception; use function sprintf; class InvalidEmailException extends \Exception { public function __construct(string $email) { parent::__construct(sprintf('Provided email string %s is not a valid email.', $email)); } }
michaelkeiluweit/oxideshop_ce
source/Internal/Domain/Admin/Exception/InvalidEmailException.php
PHP
gpl-3.0
435
// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009-2012, Jonathan Turner (jonathan@emptycrate.com) // Copyright 2009-2015, Jason Turner (jason@emptycrate.com) // http://www.chaiscript.com #ifndef CHAISCRIPT_BOXED_CAST_HPP_ #define CHAISCRIPT_BOXED_CAST_HPP_ #include "../chaiscript_defines.hpp" #include "bad_boxed_cast.hpp" #include "boxed_cast_helper.hpp" #include "boxed_value.hpp" #include "type_conversions.hpp" #include "type_info.hpp" namespace chaiscript { class Type_Conversions; namespace detail { namespace exception { class bad_any_cast; } // namespace exception } // namespace detail } // namespace chaiscript namespace chaiscript { /// \brief Function for extracting a value stored in a Boxed_Value object /// \tparam Type The type to extract from the Boxed_Value /// \param[in] bv The Boxed_Value to extract a typed value from /// \returns Type equivalent to the requested type /// \throws exception::bad_boxed_cast If the requested conversion is not possible /// /// boxed_cast will attempt to make conversions between value, &, *, std::shared_ptr, std::reference_wrapper, /// and std::function (const and non-const) where possible. boxed_cast is used internally during function /// dispatch. This means that all of these conversions will be attempted automatically for you during /// ChaiScript function calls. /// /// \li non-const values can be extracted as const or non-const /// \li const values can be extracted only as const /// \li Boxed_Value constructed from pointer or std::reference_wrapper can be extracted as reference, /// pointer or value types /// \li Boxed_Value constructed from std::shared_ptr or value types can be extracted as reference, /// pointer, value, or std::shared_ptr types /// /// Conversions to std::function objects are attempted as well /// /// Example: /// \code /// // All of the following should succeed /// chaiscript::Boxed_Value bv(1); /// std::shared_ptr<int> spi = chaiscript::boxed_cast<std::shared_ptr<int> >(bv); /// int i = chaiscript::boxed_cast<int>(bv); /// int *ip = chaiscript::boxed_cast<int *>(bv); /// int &ir = chaiscript::boxed_cast<int &>(bv); /// std::shared_ptr<const int> cspi = chaiscript::boxed_cast<std::shared_ptr<const int> >(bv); /// const int ci = chaiscript::boxed_cast<const int>(bv); /// const int *cip = chaiscript::boxed_cast<const int *>(bv); /// const int &cir = chaiscript::boxed_cast<const int &>(bv); /// \endcode /// /// std::function conversion example /// \code /// chaiscript::ChaiScript chai; /// Boxed_Value bv = chai.eval("`+`"); // Get the functor for the + operator which is built in /// std::function<int (int, int)> f = chaiscript::boxed_cast<std::function<int (int, int)> >(bv); /// int i = f(2,3); /// assert(i == 5); /// \endcode template<typename Type> typename detail::Cast_Helper<Type>::Result_Type boxed_cast(const Boxed_Value &bv, const Type_Conversions *t_conversions = nullptr) { if (!t_conversions || bv.get_type_info().bare_equal(user_type<Type>()) || (t_conversions && !t_conversions->convertable_type<Type>())) { try { return detail::Cast_Helper<Type>::cast(bv, t_conversions); } catch (const chaiscript::detail::exception::bad_any_cast &) { } } if (t_conversions && t_conversions->convertable_type<Type>()) { try { // std::cout << "trying an up conversion " << typeid(Type).name() << '\n'; // We will not catch any bad_boxed_dynamic_cast that is thrown, let the user get it // either way, we are not responsible if it doesn't work return detail::Cast_Helper<Type>::cast(t_conversions->boxed_type_conversion<Type>(bv), t_conversions); } catch (...) { try { // std::cout << "trying a down conversion " << typeid(Type).name() << '\n'; // try going the other way - down the inheritance graph return detail::Cast_Helper<Type>::cast(t_conversions->boxed_type_down_conversion<Type>(bv), t_conversions); } catch (const chaiscript::detail::exception::bad_any_cast &) { throw exception::bad_boxed_cast(bv.get_type_info(), typeid(Type)); } } } else { // If it's not polymorphic, just throw the error, don't waste the time on the // attempted dynamic_cast throw exception::bad_boxed_cast(bv.get_type_info(), typeid(Type)); } } } #endif
drummyfish/text-rpg
src/chaiscript/dispatchkit/boxed_cast.hpp
C++
gpl-3.0
4,499